Beispiel #1
0
        string GetProfileContent()
        {
            string profileContent = string.Empty;

            try
            {
                FileInfo profileInfo = new FileInfo(GetProfilePath());
                if (!profileInfo.Exists)
                {
                    DirectoryInfo profileDirectory = new DirectoryInfo(profileInfo.DirectoryName);
                    if (!profileDirectory.Exists)
                    {
                        profileDirectory.Create();
                    }

                    using (profileInfo.Create())
                    {
                        // using statement will enforce the dispose of the FileStream
                    };
                }
                else
                {
                    using (StreamReader reader = new StreamReader(profileInfo.FullName))
                    {
                        profileContent = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception exc)
            {
                ErrorTrace.Trace(TraceLevel.Error, exc);
            }

            return(profileContent);
        }
        /// <summary>
        /// Report-Mailer runs in background thread and this is the thread function.
        /// </summary>
        public void Run()
        {
            IBlogDataService    dataService       = null;
            ILoggingDataService loggingService    = null;
            DateTime            lastReportDateUTC = DateTime.Now.ToUniversalTime();


            SiteConfig siteConfig = SiteConfig.GetSiteConfig(configPath);

            loggingService = LoggingDataServiceFactory.GetService(logPath);
            dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);

            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "ReportMailer thread spinning up");
            loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerServiceStart, "", ""));

            do
            {
                try
                {
                    // reload on every cycle to get the current settings
                    siteConfig     = SiteConfig.GetSiteConfig(configPath);
                    loggingService = LoggingDataServiceFactory.GetService(logPath);
                    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);

                    if (siteConfig.EnableDailyReportEmail)
                    {
                        if (siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0 &&
                            lastReportDateUTC.Day != DateTime.Now.ToUniversalTime().Day)
                        {
                            // It's a new day so send the report
                            SendEmailReport(lastReportDateUTC, siteConfig, dataService, loggingService);
                            // and update the cached date to today
                            lastReportDateUTC = DateTime.Now.ToUniversalTime();
                        }
                    }

                    // tick again in an hour
                    Thread.Sleep(TimeSpan.FromSeconds(3600));
                }

                catch (ThreadAbortException abortException)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException);
                    loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerServiceShutdown, "", ""));
                    break;
                }
                catch (Exception e)
                {
                    // if the siteConfig can't be read, stay running regardless
                    // default wait time is 60 minutes in that case
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                    loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerServiceError, e.ToString().Replace("\n", "<br />"), null, null));
                    Thread.Sleep(TimeSpan.FromSeconds(3600));
                }
            }while (true);

            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "ReportMailer thread terminating");
            loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerServiceShutdown, "", ""));
        }
Beispiel #3
0
        public static void FixDays(string path)
        {
            ContentPath = path;

            IBlogDataService dataService = BlogDataServiceFactory.GetService(ContentPath, null);

            EntryCollection entries = dataService.GetEntriesForDay(
                DateTime.MaxValue.AddDays(-2),
                TimeZone.CurrentTimeZone,
                String.Empty,
                int.MaxValue,
                int.MaxValue,
                String.Empty);

            Hashtable DayEntries = new Hashtable();

            foreach (Entry entry in entries)
            {
                DayEntry dayEntry = new DayEntry();
                dayEntry.DateUtc = entry.CreatedUtc;

                if (DayEntries.ContainsKey(entry.CreatedUtc.Date))
                {
                    dayEntry = DayEntries[entry.CreatedUtc.Date] as DayEntry;
                }
                dayEntry.Entries.Add(entry);
                DayEntries[entry.CreatedUtc.Date] = dayEntry;
            }

            DirectoryInfo directoryInfo = new DirectoryInfo(path);

            foreach (FileInfo fileInfo in directoryInfo.GetFiles("*.dayentry.xml"))
            {
                // backup the old file
                try
                {
                    DirectoryInfo backup = new DirectoryInfo(Path.Combine(directoryInfo.FullName, "backup"));

                    if (!backup.Exists)
                    {
                        backup.Create();
                    }

                    fileInfo.MoveTo(Path.Combine(backup.FullName, fileInfo.Name));
                }
                catch (Exception e)
                {
                    ErrorTrace.Trace(TraceLevel.Error, e);
                }
            }

            foreach (DayEntry dayEntry in DayEntries.Values)
            {
                Save(dayEntry, path);
            }
        }
Beispiel #4
0
        public static void Upgrade(string path)
        {
            // more aggresive way to upgrade files
            foreach (FileInfo fi in new DirectoryInfo(path).GetFiles("*.dayextra.xml"))
            {
                DayExtraOld dayExtra   = new DayExtraOld(fi.FullName);
                string      filename   = dayExtra.DateLocalTime.ToUniversalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".dayfeedback.xml";
                FileStream  fileStream = FileUtils.OpenForWrite(Path.Combine(path, filename));
                if (fileStream != null)
                {
                    try
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(DayExtraOld), "urn:newtelligence-com:dasblog:runtime:data");
                        using (StreamWriter writer = new StreamWriter(fileStream))
                        {
                            ser.Serialize(writer, dayExtra);
                        }

                        try
                        {
                            WriteLine(String.Format("Saved {0}", fi.Name));

                            DirectoryInfo backup = new DirectoryInfo(Path.Combine(path, "backup"));

                            if (!backup.Exists)
                            {
                                backup.Create();
                            }

                            fi.MoveTo(Path.Combine(backup.FullName, fi.Name));
                        }
                        catch (Exception ex)
                        {
                            WriteLine(String.Format("ERROR: Cannot delete file: {0}", fi.FullName));
                            WriteLine(ex.ToString());
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, e);
                        // truncate the file if this fails
                        fileStream.SetLength(0);
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }
            }
        }
Beispiel #5
0
 void SetProfileContent(string content)
 {
     try
     {
         using (StreamWriter writer = new StreamWriter(GetProfilePath()))
         {
             writer.Write(content);
         }
     }
     catch (Exception exc)
     {
         ErrorTrace.Trace(TraceLevel.Error, exc);
     }
 }
        public void ProcessRequest(HttpContext context)
        {
            SiteConfig siteConfig = SiteConfig.GetSiteConfig();

            string sourceId;
            string referrerUrl;

            /*
             * This service is a bit diffent from the other handlers, because
             * the "bugs" are out in the wild regardless of whether the service is
             * enabled. So the service must yield a valid result, regardless of
             * whetr
             */
            if (siteConfig.EnableCrossposts)
            {
                sourceId    = context.Request.QueryString["id"];
                referrerUrl = context.Request.UrlReferrer != null?context.Request.UrlReferrer.ToString() : "";

                try
                {
                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

                    Entry entry = dataService.GetEntry(sourceId);
                    if (entry != null)
                    {
                        // we'll check whether the entry exists just to avoid trash in the DB
                        logService.AddCrosspostReferrer(
                            new LogDataItem(
                                SiteUtilities.GetPermaLinkUrl(siteConfig, sourceId), referrerUrl, context.Request.UserAgent, context.Request.UserHostName));
                    }
                    else
                    {
                        StackTrace st = new StackTrace();
                        logService.AddEvent(new EventDataItem(EventCodes.Error, "Entry was not found: " + sourceId + " " + st.ToString(), ""));
                    }
                }
                catch (Exception exc)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                }
            }

            context.Response.OutputStream.Write(aggBugBitmap, 0, aggBugBitmap.Length);
            context.Response.ContentType = "image/gif";
            context.Response.StatusCode  = 200;
            context.Response.End();
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //Cache the sitemap for 8 hours...
                DataCache cache    = CacheFactory.GetCache();
                string    CacheKey = "TimelineXml";
                timeline  root     = cache[CacheKey] as timeline;
                if (root == null)                 //we'll have to build it...
                {
                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
                    SiteConfig          siteConfig  = SiteConfig.GetSiteConfig();

                    root = new timeline();

                    root.events = new eventCollection();

                    int i = 0;

                    //All Pages (stop after 750...it gets too big and the browser can't handle it...we'd need
                    // to include dynamic paging
                    EntryCollection entryCache = dataService.GetEntries(false);
                    //Fortunately this comes in ordered by post date, descending
                    foreach (Entry e in entryCache)
                    {
                        if (e.IsPublic && (++i < 750))
                        {
                            //then add permalinks
                            string url = SiteUtilities.GetPermaLinkUrl(siteConfig, (ITitledEntry)e);
                            @event foo = new @event(e.CreatedLocalTime, false, TruncateDotDotDot(StripAllTags(e.Title), 50), url);
                            foo.text += String.Format("<div align=\"right\"><a href=\"{0}\">More...</a></div>", url);
                            root.events.Add(foo);
                        }
                    }

                    cache.Insert(CacheKey, root, DateTime.Now.AddHours(8));
                }

                XmlSerializer x = new XmlSerializer(typeof(timeline));
                x.Serialize(HttpContext.Current.Response.OutputStream, root);
                HttpContext.Current.Response.ContentType = "text/xml";
            }
            catch (Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
            }
        }
Beispiel #8
0
        public void ProcessRequest(HttpContext context)
        {
            SiteConfig siteConfig = SiteConfig.GetSiteConfig();

            string targetUrl;
            string sourceId;

            if (!siteConfig.EnableClickThrough)
            {
                context.Response.StatusCode = 503;
                context.Response.Status     = "503 Service Unavailable";
                context.Response.End();
                return;
            }

            sourceId  = context.Request.QueryString["id"];
            targetUrl = context.Request.QueryString["url"];

            if (targetUrl == null || targetUrl.Length == 0)
            {
                context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
                return;
            }
            else
            {
                try
                {
                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

                    Entry entry = dataService.GetEntry(sourceId);
                    if (entry != null)
                    {
                        // we'll check whether the entry exists just to avoid trash in the DB
                        logService.AddClickThrough(
                            new LogDataItem(targetUrl, SiteUtilities.GetPermaLinkUrl(siteConfig, sourceId), context.Request.UserAgent, context.Request.UserHostName));
                    }
                }
                catch (Exception exc)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                }
            }
            context.Response.Redirect(targetUrl);
        }
Beispiel #9
0
        public static ThemeDictionary Load(string path)
        {
            ThemeDictionary configData = new ThemeDictionary();

            DirectoryInfo directoryInfo = new DirectoryInfo(path);

            foreach (DirectoryInfo info in directoryInfo.GetDirectories())
            {
                FileInfo[] files = info.GetFiles("theme.manifest");
                if (files.Length != 0)
                {
                    try
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(files[0].FullName);

                        XmlNodeList ndNodeList = doc.GetElementsByTagName("theme");
                        foreach (XmlElement elTheme in ndNodeList)
                        {
                            BlogTheme blogTheme = new BlogTheme();
                            blogTheme.Name              = elTheme.GetAttribute("name");
                            blogTheme.Title             = elTheme.GetAttribute("title");
                            blogTheme.TemplateDirectory = elTheme.GetAttribute("templateDirectory");
                            blogTheme.ImageDirectory    = elTheme.GetAttribute("imageDirectory");
                            foreach (XmlElement elImage in elTheme.GetElementsByTagName("image"))
                            {
                                string name     = elImage.GetAttribute("name");
                                string fileName = elImage.GetAttribute("fileName");
                                if (name != null && fileName != null)
                                {
                                    blogTheme.ImageList.Add(name, fileName);
                                }
                            }
                            configData.Add(blogTheme.Name, blogTheme);
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, e);
                    }
                }
            }

            return(configData);
        }
        protected void buttonUpload_Click(object sender, System.EventArgs e)
        {
            try
            {
                long           numBytes;
                string         uploadType;
                SharedBasePage requestPage = this.Page as SharedBasePage;

                string baseFileName;
                string absUrl   = HandleUpload(imageUpload, out uploadType, out numBytes, out baseFileName);
                string linkText = String.Format("<img border=\"0\" src=\"{0}\">",
                                                absUrl);

                editControl.Text += linkText;
            }
            catch (Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
            }
        }
Beispiel #11
0
        static internal void Save(DayEntry dayEntry, string fullPath)
        {
            fullPath = Path.Combine(fullPath, dayEntry.FileName);

            // We use the internal list to circumvent ignoring
            // items where IsPublic is set to false.
            if (dayEntry.Entries.Count == 0)
            {
                if (File.Exists(fullPath))
                {
                    File.Delete(fullPath);
                }
            }
            else
            {
                FileStream fileStream = FileUtils.OpenForWrite(fullPath);

                if (fileStream != null)
                {
                    try
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(DayEntry), "urn:newtelligence-com:dasblog:runtime:data");
                        using (StreamWriter writer = new StreamWriter(fileStream))
                        {
                            ser.Serialize(writer, dayEntry);
                        }

                        WriteLine(String.Format("Saved {0}", dayEntry.FileName));
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }
            }
        }
        static PingServiceCollection GetPingServiceInfo()
        {
            PingServiceCollection pingServiceCollection = new PingServiceCollection();
            string fullPath = SiteConfig.GetConfigPathFromCurrentContext() + "PingServices.xml";

            if (File.Exists(fullPath))
            {
                FileStream fileStream = FileUtils.OpenForRead(fullPath);

                if (fileStream != null)
                {
                    try
                    {
                        XmlSerializer ser    = new XmlSerializer(typeof(PingServiceCollection));
                        StreamReader  reader = new StreamReader(fileStream);
                        pingServiceCollection = (PingServiceCollection)ser.Deserialize(reader);

                        // add to cache
                        DataCache cache = CacheFactory.GetCache();
                        cache.Insert("PingServices", pingServiceCollection, new CacheDependency(fullPath));
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, e);
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }
            }

            // add some defaults
            if (pingServiceCollection.Count == 0)
            {
                pingServiceCollection = PingService.GetDefaultPingServices();
            }

            return(pingServiceCollection);
        }
Beispiel #13
0
        protected override void Render(HtmlTextWriter writer)
        {
            HtmlGenericControl section = new HtmlGenericControl("div");

            section.Attributes["class"] = "archiveLinksContainerStyle";
            this.Controls.Add(section);

            Table list = new Table();

            list.CssClass = "archiveLinksTableStyle";
            section.Controls.Add(list);

            try
            {
                foreach (DateTime date in _monthList)
                {
                    TableRow  row  = new TableRow();
                    TableCell cell = new TableCell();
                    //cell.CssClass ="archiveLinksCellStyle";
                    list.Rows.Add(row);
                    row.Cells.Add(cell);

                    HyperLink monthLink = new HyperLink();
                    //monthLink.CssClass = "archiveLinksLinkStyle";
                    string monthKey = date.ToString("MMMM, yyyy");
                    monthLink.Text        = string.Format("{0} ({1})", monthKey, _monthTable[monthKey]);
                    monthLink.NavigateUrl = SiteUtilities.GetMonthViewUrl(_requestPage.SiteConfig, date);
                    cell.Controls.Add(monthLink);
                }
            }
            catch (Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                section.Controls.Add(new LiteralControl("There was an error generating archive list<br />"));
            }

            section.RenderControl(writer);
        }
        protected void buttonUploadAttachment_Click(object sender, System.EventArgs e)
        {
            try
            {
                long           numBytes;
                string         uploadType;
                SharedBasePage requestPage = this.Page as SharedBasePage;
                string         baseFileName;
                string         absUrl   = HandleUpload(attachmentUpload, out uploadType, out numBytes, out baseFileName);
                string         linkText = String.Format("<a href=\"{0}\">{1} ({2:#.##} {3})</a>",
                                                        absUrl,
                                                        baseFileName,
                                                        (numBytes > 1024 * 1024) ? (((double)numBytes) / (1024.0 * 1024.0)) : (((double)numBytes) / 1024.0),
                                                        (numBytes > 1024 * 1024) ? "MB" : "KB");


                editControl.Text += linkText;
            }
            catch (Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
            }
        }
        public bool CanEdit(string username, string password)
        {
            if (!SiteConfig.GetSiteConfig().EnableEditService)
            {
                throw new ServiceDisabledException();
            }

            try
            {
                if (Context.Request.IsAuthenticated)
                {
                    return(SiteSecurity.IsValidContributor());
                }

                Authenticate(username, password);
                return(true); // no exception we're good
            }
            catch (Exception e)
            {
                ErrorTrace.Trace(TraceLevel.Error, e);
                return(false);
            }
        }
        //FIX: this should be in the IBlogDataService somewhere, not in this class
        private void DeleteEnclosures()
        {
            try
            {
                SharedBasePage requestPage = this.Page as SharedBasePage;

                if (CurrentEntry != null)
                {
                    // TODO: when we add support for more than just enclosures, we can't delete the entire folder
                    DirectoryInfo enclosuresPath = new DirectoryInfo(SiteUtilities.MapPath(Path.Combine(requestPage.SiteConfig.BinariesDir, CurrentEntry.EntryId)));
                    if (enclosuresPath.Exists)
                    {
                        enclosuresPath.Delete(true);
                    }

                    CurrentEntry.Attachments.Remove(CurrentEntry.Enclosure);
                }
            }
            catch (Exception ex)
            {
                ErrorTrace.Trace(TraceLevel.Error, ex);
            }
        }
        private void LoadCrossPostServerInfo()
        {
            string fullPath = SiteConfig.GetConfigPathFromCurrentContext() + "CrossPostServerInfo.xml";

            if (File.Exists(fullPath))
            {
                FileStream fileStream = newtelligence.DasBlog.Util.FileUtils.OpenForRead(fullPath);

                if (fileStream != null)
                {
                    try
                    {
                        XmlSerializer ser    = new XmlSerializer(typeof(CrossPostServerInfo[]));
                        StreamReader  reader = new StreamReader(fileStream);
                        crossPostServerInfo = (CrossPostServerInfo[])ser.Deserialize(reader);
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }
            }
            else
            {
                CrossPostServerInfo[] crossPostServerInfo = new CrossPostServerInfo[1];
                CrossPostServerInfo   c1 = new CrossPostServerInfo();
                c1.Name                = "DasBlog";
                c1.Endpoint            = "blogger.aspx";
                c1.Port                = 80;
                c1.Service             = 1;
                crossPostServerInfo[0] = c1;
            }
        }
Beispiel #18
0
        /// <summary>
        /// Render this control to the output parameter specified.
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            HtmlGenericControl section = new HtmlGenericControl("div");

            section.Attributes["class"] = "blogRollContainerStyle";
            this.Controls.Add(section);

            Table list = new Table();

            list.CssClass = "blogRollTableStyle";


            section.Controls.Add(list);


            //TODO: restructure: code-reuse != copy+paste

            try
            {
                bool foundOpml = false;

                Opml   nav = null;
                string fullPath;

                if (unresolvedFileName.StartsWith("http:"))
                {
                    try
                    {
                        Uri externalUri = new Uri(unresolvedFileName);
                        if (externalUri.Scheme != "file")
                        {
                            foundOpml = true;
                            WebRequest wq = WebRequest.Create(unresolvedFileName);
                            using (WebResponse wr = wq.GetResponse())
                            {
                                XmlSerializer ser;
                                using (Stream s = wr.GetResponseStream())
                                {
                                    ser = new XmlSerializer(typeof(Opml));
                                    nav = (Opml)ser.Deserialize(s);
                                }
                            }
                        }
                        else
                        {
                            unresolvedFileName = externalUri.LocalPath;
                        }
                    }
                    catch (Exception exc)
                    {
                        ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                        foundOpml = false;
                    }
                }

                if (foundOpml == false)
                {
                    if (File.Exists(unresolvedFileName))
                    {
                        fullPath = unresolvedFileName;
                    }
                    else
                    {
                        fullPath = SiteUtilities.MapPath(unresolvedFileName);
                    }

                    if ((File.Exists(fullPath)) && (foundOpml == false))
                    {
                        foundOpml = true;
                        fileName  = fullPath;
                        XmlSerializer ser;
                        using (Stream s = File.OpenRead(fileName))
                        {
                            ser = new XmlSerializer(typeof(Opml));
                            nav = (Opml)ser.Deserialize(s);
                        }
                    }
                }

                if (foundOpml == false)
                {
                    fullPath = SiteUtilities.MapPath("~/SiteConfig/blogroll.opml");
                    if ((File.Exists(fullPath)))
                    {
                        foundOpml = true;
                        fileName  = fullPath;

                        XmlSerializer ser;
                        using (Stream s = File.OpenRead(fullPath))
                        {
                            ser = new XmlSerializer(typeof(Opml));
                            nav = (Opml)ser.Deserialize(s);
                        }
                    }
                }

                if (foundOpml == false)
                {
                    string urlPath = SiteUtilities.MapPath("~/SiteConfig/opml.txt");
                    if ((File.Exists(urlPath)))
                    {
                        foundOpml = true;
                        string url;
                        fileName = urlPath;

                        using (StreamReader t = File.OpenText(urlPath))
                        {
                            url = t.ReadLine();
                        }

                        WebRequest wq = WebRequest.Create(url);
                        using (WebResponse wr = wq.GetResponse())
                        {
                            XmlSerializer ser;
                            using (Stream s = wr.GetResponseStream())
                            {
                                ser = new XmlSerializer(typeof(Opml));
                                nav = (Opml)ser.Deserialize(s);
                            }
                        }
                    }
                }



                if (foundOpml == true)
                {
                    RenderOutlinesIntoTable(list, nav.body.outline, 0, renderDescription);
                }
                else
                {
                    section.Controls.Add(new LiteralControl("Add 'blogroll.opml' to your SiteConfig directory<br />"));
                }
            }
            catch (Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                section.Controls.Add(new LiteralControl("There was an error processing '" + fileName + "'<br />"));
            }
            section.RenderControl(output);
        }
Beispiel #19
0
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.ContentType == "text/xml" &&
                context.Request.RequestType == "POST" &&
                context.Request.QueryString["guid"] != null)
            {
                try
                {
                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
                    DataCache           cache       = CacheFactory.GetCache();

                    Entry entry = dataService.GetEntry(context.Request.QueryString["guid"]);

                    if (entry != null && DasBlog.Web.Core.SiteUtilities.AreCommentsAllowed(entry, SiteConfig.GetSiteConfig()))
                    {
                        XmlSerializer ser  = new XmlSerializer(typeof(RssItem));
                        RssItem       item = (RssItem)ser.Deserialize(context.Request.InputStream);
                        if (item != null)
                        {
                            Comment c = new Comment();
                            c.Initialize();
                            foreach (XmlElement el in item.anyElements)
                            {
                                if (el.NamespaceURI == "http://purl.org/dc/elements/1.1/" &&
                                    el.LocalName == "creator")
                                {
                                    c.Author = el.InnerText;
                                    break;
                                }
                            }
                            c.AuthorEmail     = item.Author;
                            c.AuthorHomepage  = item.Link;
                            c.AuthorIPAddress = context.Request.UserHostAddress;
                            c.Content         = context.Server.HtmlEncode(item.Description);
                            c.TargetEntryId   = entry.EntryId;
                            c.TargetTitle     = "";
                            dataService.AddComment(c);

                            // TODO: no comment mail?

                            // break the caching
                            cache.Remove("BlogCoreData");
                            context.Response.StatusCode      = 200;
                            context.Response.SuppressContent = true;
                            context.Response.End();
                        }
                    }
                    else if (entry != null && !entry.AllowComments)
                    {
                        context.Response.StatusCode      = 403;                    // Forbidden
                        context.Response.SuppressContent = true;
                        context.Response.End();
                    }
                    else if (entry == null)
                    {
                        context.Response.StatusCode      = 404;                    // Not Found
                        context.Response.SuppressContent = true;
                        context.Response.End();
                    }
                }
                catch (Exception exc)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //Cache the sitemap for 12 hours...
                string    CacheKey = "GoogleSiteMap";
                DataCache cache    = CacheFactory.GetCache();

                urlset root = cache[CacheKey] as urlset;
                if (root == null) //we'll have to build it...
                {
                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
                    SiteConfig          siteConfig  = SiteConfig.GetSiteConfig();

                    root = new urlset();

                    root.url = new urlCollection();

                    //Default first...
                    url basePage = new url(SiteUtilities.GetBaseUrl(siteConfig), DateTime.Now, changefreq.daily, 1.0M);
                    root.url.Add(basePage);

                    url defaultPage = new url(SiteUtilities.GetStartPageUrl(siteConfig), DateTime.Now, changefreq.daily, 1.0M);
                    root.url.Add(defaultPage);

                    //Archives next...
                    url archivePage = new url(SiteUtilities.RelativeToRoot(siteConfig, "archives.aspx"), DateTime.Now, changefreq.daily, 1.0M);
                    root.url.Add(archivePage);

                    //All Pages
                    EntryCollection entryCache = dataService.GetEntries(false);
                    foreach (Entry e in entryCache)
                    {
                        if (e.IsPublic)
                        {
                            //Start with a RARE change freq...newer posts are more likely to change more often.
                            // The older a post, the less likely it is to change...
                            changefreq freq = changefreq.daily;

                            //new stuff?
                            if (e.CreatedLocalTime < DateTime.Now.AddMonths(-9))
                            {
                                freq = changefreq.yearly;
                            }
                            else if (e.CreatedLocalTime < DateTime.Now.AddDays(-30))
                            {
                                freq = changefreq.monthly;
                            }
                            else if (e.CreatedLocalTime < DateTime.Now.AddDays(-7))
                            {
                                freq = changefreq.weekly;
                            }
                            if (e.CreatedLocalTime > DateTime.Now.AddDays(-2))
                            {
                                freq = changefreq.hourly;
                            }

                            //Add comments pages, since comments have indexable content...
                            // Only add comments if we aren't showing comments on permalink pages already
                            if (siteConfig.ShowCommentsWhenViewingEntry == false)
                            {
                                url commentPage = new url(SiteUtilities.GetCommentViewUrl(siteConfig, e.EntryId), e.CreatedLocalTime, freq, 0.7M);
                                root.url.Add(commentPage);
                            }

                            //then add permalinks
                            url permaPage = new url(SiteUtilities.GetPermaLinkUrl(siteConfig, (ITitledEntry)e), e.CreatedLocalTime, freq, 0.9M);
                            root.url.Add(permaPage);
                        }
                    }

                    //All Categories
                    CategoryCacheEntryCollection catCache = dataService.GetCategories();
                    foreach (CategoryCacheEntry cce in catCache)
                    {
                        if (cce.IsPublic)
                        {
                            url catPage = new url(SiteUtilities.GetCategoryViewUrl(siteConfig, cce.Name), DateTime.Now, changefreq.weekly, 0.6M);
                            root.url.Add(catPage);
                        }
                    }
                    cache.Insert(CacheKey, root, DateTime.Now.AddHours(12));
                }

                XmlSerializer x = new XmlSerializer(typeof(urlset));
                x.Serialize(context.Response.OutputStream, root);
                context.Response.ContentType = "text/xml";
            }
            catch (Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
            }
        }
        private void EventlogBox_PreRender(object sender, EventArgs e)
        {
            SiteConfig          siteConfig = SiteConfig.GetSiteConfig();
            Control             root       = contentPlaceHolder;
            ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());

            Table table = new Table();

            table.CssClass = "statsTableStyle";

            TableRow row = new TableRow();

            row.CssClass = "statsTableHeaderRowStyle";
            row.Cells.Add(new TableCell());
            row.Cells.Add(new TableCell());
            row.Cells.Add(new TableCell());
            row.Cells[0].CssClass = "statsTableDateColumnStyle";
            row.Cells[1].CssClass = "statsTableNumColumnStyle";
            row.Cells[2].CssClass = "statsTableColumnStyle";
            row.Cells[0].Text     = "<b>" + resmgr.GetString("text_time") + "</b>";
            row.Cells[1].Text     = "<b>" + resmgr.GetString("text_message_code") + "</b>";
            row.Cells[2].Text     = "<b>" + resmgr.GetString("text_message_text") + "</b>";
            table.Rows.Add(row);

            // get the user's local time
            DateTime utcTime   = DateTime.UtcNow;
            DateTime localTime = siteConfig.GetConfiguredTimeZone().ToLocalTime(utcTime);

            if (Request.QueryString["date"] != null)
            {
                try
                {
                    DateTime popUpTime = DateTime.ParseExact(Request.QueryString["date"], "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    utcTime   = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, utcTime.Hour, utcTime.Minute, utcTime.Second);
                    localTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, localTime.Hour, localTime.Minute, localTime.Second);
                }
                catch (FormatException ex)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
                }
            }

            EventDataItemCollection logItems = new EventDataItemCollection();

            logItems.AddRange(logService.GetEventsForDay(localTime));

            if (siteConfig.AdjustDisplayTimeZone)
            {
                newtelligence.DasBlog.Util.WindowsTimeZone tz = siteConfig.GetConfiguredTimeZone();
                TimeSpan ts     = tz.GetUtcOffset(DateTime.UtcNow);
                int      offset = ts.Hours;

                if (offset < 0)
                {
                    logItems.AddRange(logService.GetEventsForDay(localTime.AddDays(1)));
                }
                else
                {
                    logItems.AddRange(logService.GetEventsForDay(localTime.AddDays(-1)));
                }
            }

            EventDataItem[] sortedLogItems = logItems.ToSortedArray();

            foreach (EventDataItem eventItem in sortedLogItems)
            {
                if (siteConfig.AdjustDisplayTimeZone)
                {
                    if (siteConfig.GetConfiguredTimeZone().ToLocalTime(eventItem.EventTimeUtc).Date != localTime.Date)
                    {
                        continue;
                    }
                }

                row          = new TableRow();
                row.CssClass = "statsTableRowStyle";

                switch (eventItem.EventCode)
                {
                case ((int)EventCodes.Error):
                case ((int)EventCodes.PingbackServerError):
                case ((int)EventCodes.PingWeblogsError):
                case ((int)EventCodes.Pop3ServerError):
                case ((int)EventCodes.SmtpError):
                    row.CssClass = "statsTableRowStyleError";
                    break;

                case ((int)EventCodes.SecurityFailure):
                    row.CssClass = "statsTableRowStyleSecurityFailure";
                    break;

                case ((int)EventCodes.TrackbackBlocked):
                case ((int)EventCodes.ReferralBlocked):
                case ((int)EventCodes.ItemReferralBlocked):
                case ((int)EventCodes.CommentBlocked):
                case ((int)EventCodes.PingbackBlocked):
                    row.CssClass = "statsTableRowStyleBlocked";
                    break;

                default:
                    break;
                }

                row.Cells.Add(new TableCell());
                row.Cells.Add(new TableCell());
                row.Cells.Add(new TableCell());
                row.Cells[0].CssClass = "statsTableDateColumnStyle";
                row.Cells[1].CssClass = "statsTableNumColumnStyle";
                row.Cells[2].CssClass = "statsTableColumnStyle";

                if (siteConfig.AdjustDisplayTimeZone)
                {
                    row.Cells[0].Text = siteConfig.GetConfiguredTimeZone().ToLocalTime(eventItem.EventTimeUtc).ToString("yyyy-MM-dd HH:mm:ss tt");
                }
                else
                {
                    row.Cells[0].Text = eventItem.EventTimeUtc.ToString("yyyy-MM-dd HH:mm:ss tt") + " UTC";
                }

                row.Cells[1].Text = eventItem.EventCode.ToString();
                row.Cells[2].Text = eventItem.HtmlMessage;

                table.Rows.Add(row);
            }

            root.Controls.Add(table);

            DataBind();
        }
Beispiel #22
0
        protected override void Render(HtmlTextWriter writer)
        {
            HtmlGenericControl section = new HtmlGenericControl("div");

            section.Attributes["class"] = "navigatorLinksContainerStyle";
            this.Controls.Add(section);

            string controlType   = "table";
            string controlClass  = "navigatorLinksTableStyle";
            string listItemClass = "navigatorLinksCellStyle";

            if (renderAsList)
            {
                controlType   = "ul";
                controlClass  = "navigatorLinksListStyle";
                listItemClass = "navigatorLinksListItemStyle";
            }

            HtmlGenericControl list = new HtmlGenericControl(controlType);

            list.Attributes.Add("class", controlClass);
            section.Controls.Add(list);

            //FIX: Why do we support 2 different schema's for the SideBarList content???

            try
            {
                string fullPath = Path.Combine(SiteConfig.GetContentPathFromCurrentContext(), fileName);
                if (File.Exists(fullPath))
                {
                    NavigatorXml nav;
                    using (Stream s = File.OpenRead(fullPath))
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(NavigatorXml));
                        nav = (NavigatorXml)ser.Deserialize(s);
                    }
                    foreach (NavigatorItem navitem in nav.Items)
                    {
                        HyperLink catLink = new HyperLink();
                        catLink.CssClass    = "navigatorLinksLinkStyle";
                        catLink.Text        = navitem.Name;
                        catLink.NavigateUrl = navitem.Url;

                        if (renderAsList)
                        {
                            HtmlGenericControl cell = new HtmlGenericControl("li");
                            cell.Attributes.Add("class", listItemClass);
                            list.Controls.Add(cell);
                            cell.Controls.Add(catLink);
                        }
                        else
                        {
                            TableRow  row  = new TableRow();
                            TableCell cell = new TableCell();
                            cell.CssClass = listItemClass;
                            list.Controls.Add(row);
                            row.Cells.Add(cell);
                            cell.Controls.Add(catLink);
                        }
                    }
                }
                else
                {
                    NavigationRoot nav;

                    fullPath = Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(), fileName);
                    if (File.Exists(fullPath))
                    {
                        using (Stream s = File.OpenRead(fullPath))
                        {
                            XmlSerializer ser = new XmlSerializer(typeof(NavigationRoot));
                            nav = (NavigationRoot)ser.Deserialize(s);
                        }
                        foreach (NavigationLink navitem in nav.Items)
                        {
                            HyperLink catLink = new HyperLink();
                            catLink.CssClass    = "navigatorLinksLinkStyle";
                            catLink.Text        = navitem.Name;
                            catLink.NavigateUrl = navitem.Url;

                            if (renderAsList)
                            {
                                HtmlGenericControl cell = new HtmlGenericControl("li");
                                cell.Attributes.Add("class", listItemClass);
                                list.Controls.Add(cell);
                                cell.Controls.Add(catLink);
                            }
                            else
                            {
                                TableRow  row  = new TableRow();
                                TableCell cell = new TableCell();
                                cell.CssClass = listItemClass;
                                list.Controls.Add(row);
                                row.Cells.Add(cell);
                                cell.Controls.Add(catLink);
                            }
                        }
                    }
                    else
                    {
                        section.Controls.Add(new LiteralControl("Add '" + fileName + "' to your SiteConfig directory<br />"));
                    }
                }
            }
            catch (Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                section.Controls.Add(new LiteralControl("There was an error processing '" + fileName + "'<br />"));
            }

            section.RenderControl(writer);
        }
Beispiel #23
0
        public void Run()
        {
            SiteConfig          siteConfig     = SiteConfig.GetSiteConfig(configPath);
            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(logPath);
            IBlogDataService    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


            loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceStart, "", ""));

            do
            {
                try
                {
                    // reload on every cycle to get the current settings
                    siteConfig     = SiteConfig.GetSiteConfig(configPath);
                    loggingService = LoggingDataServiceFactory.GetService(logPath);
                    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);

                    SyndicationServiceImplementation syndicator = new SyndicationServiceImplementation(siteConfig, dataService, loggingService);

                    if (siteConfig.EnableXSSUpstream &&
                        siteConfig.XSSUpstreamPassword != null &&
                        siteConfig.XSSUpstreamUsername != null)
                    {
                        try
                        {
                            MemoryStream  memoryStream = new MemoryStream();
                            StreamWriter  streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
                            XmlSerializer ser          = new XmlSerializer(typeof(RssRoot));
                            RssRoot       root         = syndicator.GetRss();
                            ser.Serialize(streamWriter, root);



                            XmlStorageSystemClientProxy xssProxy = new XmlStorageSystemClientProxy();
                            if (siteConfig.XSSUpstreamEndpoint != null && siteConfig.XSSUpstreamEndpoint.Length > 0)
                            {
                                xssProxy.Url = siteConfig.XSSUpstreamEndpoint;
                            }

                            string rssFileName = "rss-dasblog.xml";
                            if (siteConfig.XSSRSSFilename != null && siteConfig.XSSRSSFilename.Length > 0)
                            {
                                rssFileName = siteConfig.XSSRSSFilename;
                            }

                            // the buffer is longer than the output and must be shortened
                            // by copying into a new buffer
                            byte[] rssBuffer          = new byte[memoryStream.Position];
                            byte[] memoryStreamBuffer = memoryStream.GetBuffer();
                            for (int l = 0; l < rssBuffer.Length; l++)
                            {
                                rssBuffer[l] = memoryStreamBuffer[l];
                            }


                            XSSSaveMultipleFilesReply reply =
                                xssProxy.SaveMultipleFiles(
                                    siteConfig.XSSUpstreamUsername,
                                    XmlStorageSystemClientProxy.EncodePassword(siteConfig.XSSUpstreamPassword),
                                    new string[] { rssFileName },
                                    new byte[][] { rssBuffer });

                            if (reply.flError)
                            {
                                loggingService.AddEvent(
                                    new EventDataItem(
                                        EventCodes.XSSUpstreamError, reply.message, null, null));
                            }
                            else
                            {
                                loggingService.AddEvent(
                                    new EventDataItem(
                                        EventCodes.XSSUpstreamSuccess, reply.message, rssFileName, xssProxy.Url));
                            }
                        }
                        catch (Exception e)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(
                                    EventCodes.XSSUpstreamError, e.Message, e.StackTrace, null));
                        }
                    }

                    upstreamTrigger.WaitOne(TimeSpan.FromSeconds(siteConfig.XSSUpstreamInterval), false);

                    // introduce a little time offset to limit competition for the files.
                    Thread.Sleep(500);
                }
                catch (ThreadAbortException abortException)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException);
                    loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceShutdown, "", ""));
                    break;
                }
                catch (Exception e)
                {
                    // if the siteConfig can't be read, stay running regardless
                    // default wait time is 4 minutes in that case
                    Thread.Sleep(TimeSpan.FromSeconds(240));
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                }
            }while (true);
            loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceShutdown, "", ""));
        }
        public void ProcessRequest(HttpContext context)
        {
            if (!SiteSecurity.IsValidContributor())
            {
                context.Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            SiteConfig siteConfig = SiteConfig.GetSiteConfig();

            string entryId;
            string commentId;
            string referralPermalink;
            string type;
            string redirectUrl = SiteUtilities.GetStartPageUrl();
            bool   reportAsSpam;

            entryId           = context.Request.QueryString["entryId"];
            commentId         = context.Request.QueryString["commentId"];
            referralPermalink = context.Request.QueryString["referralPermalink"];
            type         = context.Request.QueryString["type"];
            reportAsSpam = context.Request.QueryString["report"] != null;

            // make sure the entry param is there
            if (entryId == null || entryId.Length == 0)
            {
                context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
                return;
            }
            else
            {
                try
                {
                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

                    Entry entry = dataService.GetEntry(entryId);
                    if (entry != null)
                    {
                        if (commentId != null && commentId.Length > 0)
                        {
                            if (reportAsSpam)
                            {
                                ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService;
                                if (spamBlockingService != null)
                                {
                                    Comment comment = dataService.GetCommentById(entryId, commentId);
                                    if ((comment != null) && (comment.SpamState != SpamState.Spam))
                                    {
                                        try
                                        {
                                            spamBlockingService.ReportSpam(comment);
                                        }
                                        catch (Exception ex)
                                        {
                                            logService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("Unable to report comment {0} as spam. Original exception: {1}", comment.EntryId, ex), SiteUtilities.GetPermaLinkUrl(entryId)));
                                        }
                                    }
                                }
                            }
                            dataService.DeleteComment(entryId, commentId);

                            logService.AddEvent(
                                new EventDataItem(
                                    EventCodes.CommentDeleted, commentId,
                                    SiteUtilities.GetPermaLinkUrl(entryId)));

                            redirectUrl = SiteUtilities.GetCommentViewUrl(entryId);
                        }
                        else if (referralPermalink != null && referralPermalink.Length > 0)
                        {
                            TrackingType trackingType = TrackingType.Referral;

                            if (type != null && type.Length != 0)
                            {
                                trackingType = (TrackingType)Enum.Parse(typeof(TrackingType), type);
                            }

                            dataService.DeleteTracking(entryId, referralPermalink, trackingType);

                            logService.AddEvent(
                                new EventDataItem(
                                    EventCodes.ItemReferralDeleted, referralPermalink,
                                    SiteUtilities.GetPermaLinkUrl(entryId)));

                            redirectUrl = SiteUtilities.GetPermaLinkUrl(entryId);
                        }
                        else                         // it must be an entry we are deleting
                        {
                            SiteUtilities.DeleteEntry(entryId, siteConfig, logService, dataService);
                            redirectUrl = SiteUtilities.GetStartPageUrl();
                        }
                    }
                }
                catch (Exception exc)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                }
            }

            context.Response.Redirect(redirectUrl);
        }
Beispiel #25
0
        private void ClickThroughsBox_PreRender(object sender, EventArgs e)
        {
            Control root = contentPlaceHolder;

            SiteConfig          siteConfig  = SiteConfig.GetSiteConfig();
            ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
            IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

            Dictionary <string, int> clickThroughUrls = new Dictionary <string, int>();
            Dictionary <string, int> userAgents       = new Dictionary <string, int>();
            Dictionary <string, int> userDomains      = new Dictionary <string, int>();

            // get the user's local time
            DateTime utcTime   = DateTime.UtcNow;
            DateTime localTime = siteConfig.GetConfiguredTimeZone().ToLocalTime(utcTime);

            if (Request.QueryString["date"] != null)
            {
                try
                {
                    DateTime popUpTime = DateTime.ParseExact(Request.QueryString["date"], "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    utcTime   = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, utcTime.Hour, utcTime.Minute, utcTime.Second);
                    localTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, localTime.Hour, localTime.Minute, localTime.Second);
                }
                catch (FormatException ex)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
                }
            }

            LogDataItemCollection logItems = new LogDataItemCollection();

            logItems.AddRange(logService.GetClickThroughsForDay(localTime));

            if (siteConfig.AdjustDisplayTimeZone)
            {
                newtelligence.DasBlog.Util.WindowsTimeZone tz = siteConfig.GetConfiguredTimeZone();
                TimeSpan ts     = tz.GetUtcOffset(DateTime.UtcNow);
                int      offset = ts.Hours;

                if (offset < 0)
                {
                    logItems.AddRange(logService.GetClickThroughsForDay(localTime.AddDays(1)));
                }
                else
                {
                    logItems.AddRange(logService.GetClickThroughsForDay(localTime.AddDays(-1)));
                }
            }

            foreach (LogDataItem log in logItems)
            {
                bool exclude = false;

                if (siteConfig.AdjustDisplayTimeZone)
                {
                    if (siteConfig.GetConfiguredTimeZone().ToLocalTime(log.RequestedUtc).Date != localTime.Date)
                    {
                        exclude = true;
                    }
                }

                if (!exclude)
                {
                    string key = log.UrlRequested + "°" + log.UrlReferrer;
                    if (!clickThroughUrls.ContainsKey(key))
                    {
                        clickThroughUrls[key] = 0;
                    }
                    clickThroughUrls[key] = clickThroughUrls[key] + 1;

                    if (!userAgents.ContainsKey(log.UserAgent))
                    {
                        userAgents[log.UserAgent] = 0;
                    }
                    userAgents[log.UserAgent] = userAgents[log.UserAgent] + 1;

                    if (!userDomains.ContainsKey(log.UserDomain))
                    {
                        userDomains[log.UserDomain] = 0;
                    }
                    userDomains[log.UserDomain] = userDomains[log.UserDomain] + 1;
                }
            }

            root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(clickThroughUrls), resmgr.GetString("text_activity_click_throughs"), resmgr.GetString("text_activity_clicks"), new StatisticsBuilderCallback(this.BuildClickThroughsRow), dataService));
            root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userDomains), resmgr.GetString("text_activity_user_domains"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildUserDomainRow), dataService));
            root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userAgents), resmgr.GetString("text_activity_user_agent"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildAgentsRow), dataService));

            DataBind();
        }
        private void ReferrersBox_PreRender(object sender, EventArgs e)
        {
            Control root = contentPlaceHolder;

            SiteConfig          siteConfig = SiteConfig.GetSiteConfig();
            ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
            string siteRoot = siteConfig.Root.ToUpper();

            Dictionary <string, int> referrerUrls = new Dictionary <string, int>();
            Dictionary <string, int> userAgents   = new Dictionary <string, int>();
            Dictionary <string, int> searchUrls   = new Dictionary <string, int>();
            Dictionary <string, int> userDomains  = new Dictionary <string, int>();

            // get the user's local time
            DateTime utcTime   = DateTime.UtcNow;
            DateTime localTime = siteConfig.GetConfiguredTimeZone().ToLocalTime(utcTime);

            if (Request.QueryString["date"] != null)
            {
                try
                {
                    DateTime popUpTime = DateTime.ParseExact(Request.QueryString["date"], "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    utcTime   = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, utcTime.Hour, utcTime.Minute, utcTime.Second);
                    localTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, localTime.Hour, localTime.Minute, localTime.Second);
                }
                catch (FormatException ex)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
                }
            }

            LogDataItemCollection logItems = new LogDataItemCollection();

            logItems.AddRange(logService.GetReferralsForDay(localTime));

            if (siteConfig.AdjustDisplayTimeZone)
            {
                newtelligence.DasBlog.Util.WindowsTimeZone tz = siteConfig.GetConfiguredTimeZone();
                TimeSpan ts     = tz.GetUtcOffset(DateTime.UtcNow);
                int      offset = ts.Hours;

                if (offset < 0)
                {
                    logItems.AddRange(logService.GetReferralsForDay(localTime.AddDays(1)));
                }
                else
                {
                    logItems.AddRange(logService.GetReferralsForDay(localTime.AddDays(-1)));
                }
            }

            foreach (LogDataItem log in logItems)
            {
                bool exclude = false;
                if (log.UrlReferrer != null)
                {
                    exclude = log.UrlReferrer.ToUpper().StartsWith(siteRoot);

                    // Let Utils.ParseSearchString decide whether it's a search engine referrer.
                    if (SiteUtilities.ParseSearchString(log.UrlReferrer) != null)
                    {
                        exclude = true;

                        bool addToSearches = true;
                        if (siteConfig.AdjustDisplayTimeZone)
                        {
                            if (siteConfig.GetConfiguredTimeZone().ToLocalTime(log.RequestedUtc).Date != localTime.Date)
                            {
                                addToSearches = false;
                            }
                        }

                        if (addToSearches)
                        {
                            if (!searchUrls.ContainsKey(log.UrlReferrer))
                            {
                                searchUrls[log.UrlReferrer] = 0;
                            }

                            searchUrls[log.UrlReferrer] = searchUrls[log.UrlReferrer] + 1;
                        }
                    }
                }

                if (siteConfig.AdjustDisplayTimeZone)
                {
                    if (siteConfig.GetConfiguredTimeZone().ToLocalTime(log.RequestedUtc).Date != localTime.Date)
                    {
                        exclude = true;
                    }
                }

                if (!exclude)
                {
                    if (!referrerUrls.ContainsKey(log.UrlReferrer))
                    {
                        referrerUrls[log.UrlReferrer] = 0;
                    }

                    referrerUrls[log.UrlReferrer] = referrerUrls[log.UrlReferrer] + 1;

                    log.UserAgent = Server.HtmlEncode(log.UserAgent);
                    if (!userAgents.ContainsKey(log.UserAgent))
                    {
                        userAgents[log.UserAgent] = 0;
                    }

                    userAgents[log.UserAgent] = userAgents[log.UserAgent] + 1;

                    if (!userDomains.ContainsKey(log.UserDomain))
                    {
                        userDomains[log.UserDomain] = 0;
                    }

                    userDomains[log.UserDomain] = userDomains[log.UserDomain] + 1;
                }
            }

            Table rollupTable = new Table();

            rollupTable.CssClass = "statsTableStyle";
            TableRow row = new TableRow();

            row.CssClass = "statsTableHeaderRowStyle";
            row.Cells.Add(new TableCell());
            row.Cells.Add(new TableCell());
            row.Cells[0].CssClass = "statsTableHeaderColumnStyle";
            row.Cells[1].CssClass = "statsTableHeaderNumColumnStyle";
            row.Cells[0].Text     = resmgr.GetString("text_activity_summary");
            row.Cells[1].Text     = resmgr.GetString("text_activity_hits");
            rollupTable.Rows.Add(row);

            //SDH: I know this is gross, but I didn't want to totally rewrite this whole thing, I just wanted to get the rollup to work
            string total = String.Empty;
            Table  internetSearchesTable = BuildStatisticsTable(GenerateSortedSearchStringItemList(searchUrls), resmgr.GetString("text_activity_internet_searches"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildSearchesRow), out total, null);

            BuildRow(total, rollupTable, resmgr.GetString("text_activity_internet_searches"));
            Table userDomainsTable  = BuildStatisticsTable(GenerateSortedItemList(userDomains), resmgr.GetString("text_activity_user_domains"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildUserDomainRow), out total, null);
            Table userAgentsTable   = BuildStatisticsTable(GenerateSortedItemList(userAgents), resmgr.GetString("text_activity_user_agent"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildAgentsRow), out total, null);
            Table referrerUrlsTable = BuildStatisticsTable(GenerateSortedItemList(referrerUrls), resmgr.GetString("text_activity_referrer_urls"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildReferrerRow), out total, null);

            BuildRow(total, rollupTable, resmgr.GetString("text_activity_referrer_urls"));

            root.Controls.Add(rollupTable);

            root.Controls.Add(internetSearchesTable);
            root.Controls.Add(referrerUrlsTable);
            root.Controls.Add(userDomainsTable);
            root.Controls.Add(userAgentsTable);

            //root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userAgents), CONSTUSERAGENTSLIST, CONSTHITS, new StatisticsBuilderCallback(this.BuildAgentsRow), out total, null));

            DataBind();
        }
        public void ProcessRequest(HttpContext context)
        {
            SiteConfig siteConfig = SiteConfig.GetSiteConfig();
            string     entryId;
            string     title;
            string     excerpt;
            string     url;
            string     blog_name;

            if (!siteConfig.EnableTrackbackService)
            {
                context.Response.StatusCode = 503;
                context.Response.Status     = "503 Service Unavailable";
                context.Response.End();
                return;
            }

            // Try blocking them once, on the off chance they sent us a referrer
            string referrer = context.Request.UrlReferrer != null?context.Request.UrlReferrer.AbsoluteUri:"";

            if (ReferralBlackList.IsBlockedReferrer(referrer))
            {
                if (siteConfig.EnableReferralUrlBlackList404s)
                {
                    context.Response.StatusCode = 404;
                    context.Response.End();
                    return;
                }
            }

            entryId = context.Request.QueryString["guid"];

            if (context.Request.HttpMethod == "POST")
            {
                title     = context.Request.Form["title"];
                excerpt   = context.Request.Form["excerpt"];
                url       = context.Request.Form["url"];
                blog_name = context.Request.Form["blog_name"];
            }

            /* GET is no longer in the Trackback spec. Keeping
             * this arround for testing. Just uncomment.
             * else if ( context.Request.HttpMethod == "GET" )
             * {
             * title = context.Request.QueryString["title"];
             * excerpt= context.Request.QueryString["excerpt"];
             * url = context.Request.QueryString["url"];
             * blog_name = context.Request.QueryString["blog_name"];
             * }
             */
            else
            {
                context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
                return;
            }

            if (url != null && url.Length > 0)
            {
                try
                {
                    // First line of defense, try blocking again with the URL they are tracking us back with
                    if (ReferralBlackList.IsBlockedReferrer(url))
                    {
                        if (siteConfig.EnableReferralUrlBlackList404s)
                        {
                            context.Response.StatusCode = 404;
                            context.Response.End();
                            return;
                        }
                    }

                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

                    Entry entry = dataService.GetEntry(entryId);

                    if (entry != null)
                    {
                        try
                        {
                            string requestBody = null;
                            // see if this is a spammer
                            HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
                            webRequest.Method    = "GET";
                            webRequest.UserAgent = SiteUtilities.GetUserAgent();

                            HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse;

                            // now we want to get the page contents of the target body
                            using (StreamReader requestReader = new StreamReader(response.GetResponseStream()))
                            {
                                requestBody = requestReader.ReadToEnd();
                            }

                            response.Close();

                            // the source URL in the page could be URL encoded like the ClickThroughHandler does
                            string urlEncodedBaseUrl = HttpUtility.UrlEncode(SiteUtilities.GetBaseUrl());

                            // check to see if the source's page contains a link to us
                            if (Regex.Match(requestBody, SiteUtilities.GetBaseUrl()).Success == false &&
                                Regex.Match(requestBody, urlEncodedBaseUrl).Success == false)
                            {
                                logService.AddEvent(new EventDataItem(
                                                        EventCodes.TrackbackBlocked,
                                                        context.Request.UserHostAddress + " because it did not contain a link",
                                                        SiteUtilities.GetPermaLinkUrl(entryId),
                                                        url,
                                                        entry.Title
                                                        ));

                                context.Response.StatusCode = 404;
                                context.Response.End();
                                return;
                            }
                        }
                        catch
                        {
                            // trackback url is not even alive
                            logService.AddEvent(new EventDataItem(
                                                    EventCodes.TrackbackBlocked,
                                                    context.Request.UserHostAddress + " because the server did not return a valid response",
                                                    SiteUtilities.GetPermaLinkUrl(entryId),
                                                    url,
                                                    entry.Title
                                                    ));

                            context.Response.StatusCode = 404;
                            context.Response.End();
                            return;
                        }

                        // if we've gotten this far, the trackback is real and valid
                        Tracking t = new Tracking();
                        t.PermaLink = url;
                        t.Referer   = context.Request.UrlReferrer != null?context.Request.UrlReferrer.ToString() : String.Empty;

                        t.RefererBlogName  = blog_name;
                        t.RefererExcerpt   = excerpt;
                        t.RefererTitle     = title;
                        t.RefererIPAddress = context.Request.UserHostAddress;
                        t.TargetEntryId    = entryId;
                        t.TargetTitle      = entry.Title;
                        t.TrackingType     = TrackingType.Trackback;

                        ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService;
                        if (spamBlockingService != null)
                        {
                            bool isSpam = false;
                            try
                            {
                                isSpam = spamBlockingService.IsSpam(t);
                            }
                            catch (Exception ex)
                            {
                                logService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for trackback from {0}. Original exception: {1}", t.PermaLink, ex), SiteUtilities.GetPermaLinkUrl(entryId)));
                            }
                            if (isSpam)
                            {
                                //TODO: maybe we can add a configuration option to moderate trackbacks.
                                // For now, we'll just avoid saving suspected spam
                                logService.AddEvent(new EventDataItem(
                                                        EventCodes.TrackbackBlocked,
                                                        context.Request.UserHostAddress + " because it was considered spam by the external blocking service.",
                                                        SiteUtilities.GetPermaLinkUrl(entryId),
                                                        url,
                                                        entry.Title
                                                        ));
                                context.Response.StatusCode = 404;
                                context.Response.End();
                                return;
                            }
                        }

                        if (siteConfig.SendTrackbacksByEmail &&
                            siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0)
                        {
                            MailMessage emailMessage = new MailMessage();
                            if (siteConfig.NotificationEMailAddress != null &&
                                siteConfig.NotificationEMailAddress.Length > 0)
                            {
                                emailMessage.To.Add(siteConfig.NotificationEMailAddress);
                            }
                            else
                            {
                                emailMessage.To.Add(siteConfig.Contact);
                            }
                            emailMessage.Subject = String.Format("Weblog trackback by '{0}' on '{1}'", t.PermaLink, t.TargetTitle);
                            emailMessage.Body    = String.Format("You were tracked back from\n{0}\r\non your weblog entry '{1}'\n({2}\r\n\r\nDelete Trackback: {3})",
                                                                 t.PermaLink,
                                                                 t.TargetTitle,
                                                                 SiteUtilities.GetPermaLinkUrl(entryId),
                                                                 SiteUtilities.GetTrackbackDeleteUrl(entryId, t.PermaLink, t.TrackingType));


                            emailMessage.IsBodyHtml   = false;
                            emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                            emailMessage.From         = new MailAddress(siteConfig.Contact);
                            SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer,
                                                                         siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort);
                            dataService.AddTracking(t, sendMailInfo);
                        }
                        else
                        {
                            dataService.AddTracking(t);
                        }

                        logService.AddEvent(
                            new EventDataItem(
                                EventCodes.TrackbackReceived,
                                entry.Title,
                                SiteUtilities.GetPermaLinkUrl(entryId),
                                url));

                        // return the correct Trackback response
                        // http://www.movabletype.org/docs/mttrackback.html
                        context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>0</error></response>");
                        return;
                    }
                }
                catch (System.Threading.ThreadAbortException ex)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
                    return;
                }
                catch (Exception exc)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);

                    // return the correct Trackback response
                    // http://www.movabletype.org/docs/mttrackback.html
                    context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>1</error><message>" + exc.ToString() + "</message></response>");
                    return;
                }
            }

            if (entryId != null && entryId.Length > 0)
            {
                context.Response.Redirect(SiteUtilities.GetPermaLinkUrl(siteConfig, entryId));
            }
            else
            {
                context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
            }
        }
Beispiel #28
0
        private void ClickThroughsBox_PreRender(object sender, EventArgs e)
        {
            if (_robotDefinition == null)
            {
                return;
            }

            Control root = contentPlaceHolder;

            SiteConfig          siteConfig  = SiteConfig.GetSiteConfig();
            ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
            IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

            Dictionary <string, int> clickThroughUrls = new Dictionary <string, int>();
            Dictionary <string, int> userAgents       = new Dictionary <string, int>();
            Dictionary <string, int> userDomains      = new Dictionary <string, int>();

            DateTime serverTimeUtc = DateTime.Now.ToUniversalTime();
            DateTime localTime     = siteConfig.GetConfiguredTimeZone().ToLocalTime(serverTimeUtc);

            if (Request.QueryString["date"] != null)
            {
                try
                {
                    DateTime popUpTime = DateTime.ParseExact(Request.QueryString["date"], "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    localTime     = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day);
                    serverTimeUtc = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, 23, 59, 59).ToUniversalTime();
                }
                catch (FormatException ex)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
                }
            }

            LogDataItemCollection logItems = new LogDataItemCollection();

            logItems.AddRange(logService.GetClickThroughsForDay(serverTimeUtc));

            // depending on the offset (positive or negative) we want to grab events in the
            // next or previos day to account for timezone difference.
            if (siteConfig.AdjustDisplayTimeZone)
            {
                newtelligence.DasBlog.Util.WindowsTimeZone tz = siteConfig.GetConfiguredTimeZone();
                TimeSpan ts     = tz.GetUtcOffset(DateTime.Now);
                int      offset = ts.Hours;
                if (serverTimeUtc.Date != serverTimeUtc.AddHours(offset).Date)
                {
                    logItems.AddRange(logService.GetClickThroughsForDay(serverTimeUtc.AddHours(offset)));
                }
            }

            foreach (LogDataItem log in logItems)
            {
                bool exclude = false;

                if (siteConfig.AdjustDisplayTimeZone)
                {
                    if (siteConfig.GetConfiguredTimeZone().ToLocalTime(log.RequestedUtc).Date != localTime.Date)
                    {
                        exclude = true;
                    }
                }

                if (_robotDefinition.IsRobot(log))
                {
                    exclude = true;
                }

                if (!exclude)
                {
                    string key = log.UrlRequested + "°" + log.UrlReferrer;
                    if (!clickThroughUrls.ContainsKey(key))
                    {
                        clickThroughUrls[key] = 0;
                    }
                    clickThroughUrls[key] = clickThroughUrls[key] + 1;

                    if (!userAgents.ContainsKey(log.UserAgent))
                    {
                        userAgents[log.UserAgent] = 0;
                    }
                    userAgents[log.UserAgent] = userAgents[log.UserAgent] + 1;

                    // AG User domain added.
                    if (!userDomains.ContainsKey(log.UserDomain))
                    {
                        userDomains[log.UserDomain] = 0;
                    }

                    userDomains[log.UserDomain] = userDomains[log.UserDomain] + 1;
                }
            }

            root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(clickThroughUrls), resmgr.GetString("text_activity_click_throughs"), resmgr.GetString("text_activity_clicks"), new StatisticsBuilderCallback(this.BuildClickThroughsRow), dataService));
            root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userDomains), resmgr.GetString("text_activity_user_domains"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildUserDomainRow), dataService));
            root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userAgents), resmgr.GetString("text_activity_user_agent"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildAgentsRow), dataService));

            DataBind();
        }
        protected void save_Click(object sender, EventArgs e)
        {
            SharedBasePage requestPage = this.Page as SharedBasePage;

            if (SiteSecurity.IsValidContributor())
            {
                //Catch empty posts!
                if (!editControl.HasText())
                {
                    return;
                }

                CrosspostInfoCollection crosspostList = new CrosspostInfoCollection();
                Entry entry;

                if (CurrentEntry == null)
                {
                    entry = new Entry();
                    entry.Initialize();
                }
                else
                {
                    entry = CurrentEntry;
                }

                //Try a culture specific parse...
                // TODO: Come up with a shiny javascript datetime picker

                if (textDate.SelectedDateFormatted.Length > 0)
                {
                    try
                    {
                        DateTime createdLocalTime = new DateTime(textDate.SelectedDate.Year,
                                                                 textDate.SelectedDate.Month,
                                                                 textDate.SelectedDate.Day,
                                                                 entry.CreatedLocalTime.Hour,
                                                                 entry.CreatedLocalTime.Minute,
                                                                 entry.CreatedLocalTime.Second,
                                                                 entry.CreatedLocalTime.Millisecond);

                        entry.CreatedLocalTime = createdLocalTime;
                    }
                    catch (FormatException fex)
                    {
                        Trace.Write("Bad DateTime string creating new Entry: " + fex.ToString());
                    }
                }

                // see if we need to delete any old Enclosures
                if (entry.Enclosure != null)
                {
                    if (this.enclosureUpload.Visible == true && this.buttonRemove.Visible == false)
                    {
                        DeleteEnclosures();
                    }
                }

                // upload the attachment
                if (enclosureUpload.Value != null && enclosureUpload.Value != String.Empty)
                {
                    try
                    {
                        long   numBytes;
                        string type;

                        string baseFileName;
                        string fileUrl = HandleUpload(enclosureUpload, entry.EntryId, out type, out numBytes, out baseFileName);

                        entry.Attachments.Add(new Attachment(baseFileName, type, numBytes, AttachmentType.Enclosure));
                    }
                    catch (Exception exc)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, exc);
                    }
                }

                entry.Language      = listLanguages.SelectedValue == "" ? null : listLanguages.SelectedValue;
                entry.Title         = entryTitle.Text;
                entry.Description   = entryAbstract.Text;
                entry.Author        = requestPage.User.Identity.Name;
                entry.AllowComments = checkBoxAllowComments.Checked;
                entry.IsPublic      = checkBoxPublish.Checked;
                entry.Syndicated    = checkBoxSyndicated.Checked;

                // GeoRSS.
                if (siteConfig.EnableGeoRss)
                {
                    double latitude, longitude;
                    if (double.TryParse(txtLat.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out latitude))
                    {
                        entry.Latitude = latitude;
                    }
                    else
                    {
                        entry.Latitude = null;
                    }

                    if (double.TryParse(txtLong.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out longitude))
                    {
                        entry.Longitude = longitude;
                    }
                    else
                    {
                        entry.Longitude = null;
                    }
                }

                if (isDHTMLEdit)
                {
                    entry.Content = editControl.Text;
                }

                // handle categories
                string categories = "";

                StringBuilder sb       = new StringBuilder();
                bool          needSemi = false;

                foreach (ListItem listItem in categoryList.Items)
                {
                    if (listItem.Selected)
                    {
                        if (needSemi)
                        {
                            sb.Append(";");
                        }
                        sb.Append(listItem.Text);
                        needSemi = true;
                    }
                }

                categories       = sb.ToString();
                entry.Categories = categories;

                // handle crosspostSiteInfo
                CrosspostInfoCollection crosspostSiteInfo = new CrosspostInfoCollection();

                // we need to reload the crosspostinfo as it contains sensitive data like password
                foreach (CrosspostSite site in requestPage.SiteConfig.CrosspostSites)
                {
                    CrosspostInfo ci = new CrosspostInfo(site);
                    ci.TrackingUrlBase = SiteUtilities.GetCrosspostTrackingUrlBase(requestPage.SiteConfig);
                    crosspostSiteInfo.Add(ci);
                }

                // merge the crosspost config with the crosspost data
                foreach (CrosspostInfo cpi in crosspostSiteInfo)
                {
                    foreach (Crosspost cp in entry.Crossposts)
                    {
                        if (cp.ProfileName == cpi.Site.ProfileName)
                        {
                            cpi.IsAlreadyPosted = true;
                            cpi.TargetEntryId   = cp.TargetEntryId;
                            cpi.Categories      = cp.Categories;
                            break;
                        }
                    }
                }

                foreach (DataGridItem item in gridCrossposts.Items)
                {
                    CheckBox checkSite = item.FindControl("checkSite") as CheckBox;
                    if (checkSite.Checked)
                    {
                        TextBox textSiteCategory = item.FindControl("textSiteCategory") as TextBox;
                        foreach (CrosspostInfo cpi in crosspostSiteInfo)
                        {
                            if (cpi.Site.ProfileName == checkSite.Text)
                            {
                                cpi.Categories = textSiteCategory.Text;
                                crosspostList.Add(cpi);
                                break;
                            }
                        }
                    }
                }

                try
                {
                    // prevent SaveEntry from happenning twice
                    if (crosspostList.Count == 0)
                    {
                        crosspostList = null;
                    }

                    if (CurrentEntry == null) // new entry
                    {
                        SiteUtilities.SaveEntry(entry, this.textTrackback.Text, crosspostList, requestPage.SiteConfig, requestPage.LoggingService, requestPage.DataService);
                    }
                    else // existing entry
                    {
                        SiteUtilities.UpdateEntry(entry, this.textTrackback.Text, crosspostList, requestPage.SiteConfig, requestPage.LoggingService, requestPage.DataService);
                    }
                }
                catch (Exception ex)
                {
                    //SDH: Changed to ex.ToString as the InnerException is often null, which causes another error in this catch!
                    StackTrace st = new StackTrace();
                    requestPage.LoggingService.AddEvent(
                        new EventDataItem(EventCodes.Error, ex.ToString() + Environment.NewLine + st.ToString(), SiteUtilities.GetPermaLinkUrl(entry)));

                    // if we created a new entry, and there was an error, delete the enclosure folder
                    DeleteEnclosures();

                    requestPage.Redirect("FormatPage.aspx?path=SiteConfig/pageerror.format.html");
                }


                entryTitle.Text    = "";
                entryAbstract.Text = "";
                categoryList.Items.Clear();

                if (Session["newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer"] != null)
                {
                    Uri originalReferrer = Session["newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer"] as Uri;
                    Session.Remove("newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer");
                    Redirect(originalReferrer.AbsoluteUri);
                }
                else
                {
                    Redirect(SiteUtilities.GetAdminPageUrl(requestPage.SiteConfig));
                }
            }
        }
Beispiel #30
0
        public string ping(
            string sourceUri,
            string targetUri)
        {
            if (!siteConfig.EnablePingbackService)
            {
                throw new ServiceDisabledException();
            }

            string returnValue = "0";


            if (ReferralBlackList.IsBlockedReferrer(sourceUri))
            {
                if (siteConfig.EnableReferralUrlBlackList404s)
                {
                    this.Context.Response.StatusCode = 404;
                    this.Context.Response.End();
                    throw new XmlRpcFaultException(404, "not found");
                }
            }


            try
            {
                string entryId = null;

                // OmarS: need to rewrite the URL so w can find the entryId
                Uri    uriTargetUri = new Uri(SiteUtilities.MapUrl(targetUri));
                string query        = uriTargetUri.Query;
                if (query.Length > 0 && query[0] == '?')
                {
                    query = query.Substring(1);
                }
                else
                {
                    return(returnValue);
                }

                string[] queryItems = query.Split('&');
                if (queryItems == null)
                {
                    return(returnValue);
                }

                foreach (string queryItem in queryItems)
                {
                    string[] keyvalue = queryItem.Split('=');
                    if (keyvalue.Length == 2)
                    {
                        string key    = keyvalue[0];
                        string @value = keyvalue[1];

                        if (key == "guid")
                        {
                            entryId = @value;
                            break;
                        }
                    }
                }

                if (entryId != null)
                {
                    Entry entry = dataService.GetEntry(entryId);
                    if (entry != null)
                    {
                        Tracking t = new Tracking();
                        t.PermaLink = sourceUri;
                        t.Referer   = this.Context.Request.UrlReferrer != null?this.Context.Request.UrlReferrer.ToString() : String.Empty;

                        t.RefererBlogName  = sourceUri;
                        t.RefererExcerpt   = String.Empty;
                        t.RefererTitle     = sourceUri;
                        t.TargetEntryId    = entryId;
                        t.TargetTitle      = entry.Title;
                        t.TrackingType     = TrackingType.Pingback;
                        t.RefererIPAddress = this.Context.Request.UserHostAddress;

                        ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService;
                        if (spamBlockingService != null)
                        {
                            bool isSpam = false;
                            try
                            {
                                isSpam = spamBlockingService.IsSpam(t);
                            }
                            catch (Exception ex)
                            {
                                logDataService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for pingback from {0}. Original exception: {1}", sourceUri, ex), targetUri));
                            }
                            if (isSpam)
                            {
                                //TODO: May provide moderation in the future. For now we just ignore the pingback
                                logDataService.AddEvent(new EventDataItem(
                                                            EventCodes.PingbackBlocked,
                                                            "Pingback blocked from " + sourceUri + " because it was considered spam by the external blocking service.",
                                                            targetUri, sourceUri));
                                System.Web.HttpContext.Current.Response.StatusCode = 404;
                                System.Web.HttpContext.Current.Response.End();
                                throw new XmlRpcFaultException(404, "not found");
                            }
                        }

                        if (siteConfig.SendPingbacksByEmail &&
                            siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0)
                        {
                            MailMessage emailMessage = new MailMessage();
                            if (siteConfig.NotificationEMailAddress != null &&
                                siteConfig.NotificationEMailAddress.Length > 0)
                            {
                                emailMessage.To.Add(siteConfig.NotificationEMailAddress);
                            }
                            else
                            {
                                emailMessage.To.Add(siteConfig.Contact);
                            }
                            emailMessage.Subject = String.Format("Weblog pingback by '{0}' on '{1}'", sourceUri, t.TargetTitle);
                            emailMessage.Body    = String.Format("You were pinged back by\n{0}\r\non your weblog entry '{1}'\n({2}\r\n\r\nDelete Trackback: {3})",
                                                                 sourceUri,
                                                                 t.TargetTitle,
                                                                 SiteUtilities.GetPermaLinkUrl(entry),
                                                                 SiteUtilities.GetTrackbackDeleteUrl(entryId, t.PermaLink, t.TrackingType));

                            emailMessage.IsBodyHtml   = false;
                            emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                            emailMessage.From         = new MailAddress(siteConfig.Contact);
                            SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer,
                                                                         siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort);
                            dataService.AddTracking(t, sendMailInfo);
                        }
                        else
                        {
                            dataService.AddTracking(t);
                        }

                        logDataService.AddEvent(
                            new EventDataItem(EventCodes.PingbackReceived, entry.Title, targetUri, sourceUri));
                        returnValue = sourceUri;
                    }
                }
            }
            catch (Exception e)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                return("0");
            }
            return(returnValue);
        }