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));
            }
        }
Esempio n. 2
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);
        }
Esempio n. 3
0
        public void ProcessRequest(HttpContext context)
        {
            SiteConfig          siteConfig     = SiteConfig.GetSiteConfig();
            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
            IBlogDataService    dataService    = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), loggingService);


            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;
                }
            }
            else
            {
                loggingService.AddReferral(
                    new LogDataItem(
                        context.Request.RawUrl,
                        referrer,
                        context.Request.UserAgent,
                        context.Request.UserHostName));
            }
            context.Response.ContentType = "application/x-cdf";

            //Create the XmlWriter around the Response
            XmlTextWriter xw = new XmlTextWriter(context.Response.Output);

            xw.Formatting = Formatting.Indented;

            EntryCollection entriesAll = dataService.GetEntriesForDay(
                DateTime.Now.ToUniversalTime(), new Util.UTCTimeZone(),
                null, siteConfig.RssDayCount, siteConfig.RssMainEntryCount, null);
            EntryCollection entries = new EntryCollection();

            foreach (Entry e in entriesAll)
            {
                if (e.IsPublic == true)
                {
                    entries.Add(e);
                }
            }
            entries.Sort(new EntrySorter());

            //Write out the boilerplate CDF
            xw.WriteStartDocument();

            xw.WriteStartElement("CHANNEL");
            xw.WriteAttributeString("HREF", SiteUtilities.GetBaseUrl(siteConfig));

            foreach (Entry current in entries)
            {
                xw.WriteAttributeString("LASTMOD",
                                        FormatLastMod(current.ModifiedLocalTime));
            }

            /*IEnumerator enumerator = entries.GetEnumerator();
             * if(enumerator.MoveNext())
             * {
             *      xw.WriteAttributeString("LASTMOD",
             *              FormatLastMod(((Entry)enumerator.Current).ModifiedLocalTime));
             * }*/
            xw.WriteAttributeString("LEVEL", "1");
            xw.WriteAttributeString("PRECACHE", "YES");

            xw.WriteElementString("TITLE", siteConfig.Title);
            xw.WriteElementString("ABSTRACT", siteConfig.Subtitle);

            foreach (Entry entry in entries)
            {
                xw.WriteStartElement("ITEM");
                xw.WriteAttributeString("HREF", SiteUtilities.GetPermaLinkUrl(siteConfig, (ITitledEntry)entry));
                xw.WriteAttributeString("LASTMOD", FormatLastMod(entry.ModifiedLocalTime));
                xw.WriteAttributeString("LEVEL", "1");
                xw.WriteAttributeString("PRECACHE", "YES");

                xw.WriteElementString("TITLE", entry.Title);

                if (entry.Description != null && entry.Description.Length > 0)
                {
                    xw.WriteElementString("ABSTRACT", entry.Description);
                }

                xw.WriteEndElement();
            }

            xw.WriteEndElement(); //channel
            xw.WriteEndDocument();
        }
Esempio n. 4
0
        private IARoot GetInstantArticleCount(int maxDays, int maxEntries)
        {
            EntryCollection entries = null;

            //We only build the entries if blogcore doesn't exist and we'll need them later...
            if (dataService.GetLastEntryUpdate() == DateTime.MinValue)
            {
                entries = BuildEntries(null, maxDays, maxEntries);
            }

            //Try to get out as soon as possible with as little CPU as possible
            if (inASMX)
            {
                DateTime lastModified = SiteUtilities.GetLatestModifedEntryDateTime(dataService, entries);
                if (SiteUtilities.GetStatusNotModified(lastModified))
                {
                    return(null);
                }
            }

            if (inASMX)
            {
                string referrer = Context.Request.UrlReferrer != null ? Context.Request.UrlReferrer.AbsoluteUri : "";
                if (ReferralBlackList.IsBlockedReferrer(referrer))
                {
                    if (siteConfig.EnableReferralUrlBlackList404s)
                    {
                        return(null);
                    }
                }
                else
                {
                    loggingService.AddReferral(
                        new LogDataItem(
                            Context.Request.RawUrl,
                            referrer,
                            Context.Request.UserAgent,
                            Context.Request.UserHostName));
                }
            }

            //not-modified didn't work, do we have this in cache?
            string CacheKey     = string.Format("InstantArticle:{0}:{1}", maxDays, maxEntries);
            IARoot documentRoot = cache[CacheKey] as IARoot;

            if (documentRoot == null) //we'll have to build it...
            {
                //However, if we made it this far, the not-modified check didn't work, and we may not have entries...
                if (entries == null)
                {
                    entries = BuildEntries(null, maxDays, maxEntries);
                }

                documentRoot = new IARoot();
                documentRoot.Namespaces.Add("content", "http://purl.org/rss/1.0/modules/content/");

                IAChannel ch = new IAChannel();

                ch.Title = siteConfig.Title;
                ch.Link  = SiteUtilities.GetBaseUrl(siteConfig);

                if (siteConfig.Description == null || siteConfig.Description.Trim().Length == 0)
                {
                    ch.Description = siteConfig.Subtitle;
                }
                else
                {
                    ch.Description = siteConfig.Description;
                }

                ch.PubDate       = DateTime.UtcNow.ToString();
                ch.LastBuildDate = DateTime.UtcNow.ToString();

                if (siteConfig.RssLanguage != null && siteConfig.RssLanguage.Length > 0)
                {
                    ch.Language = siteConfig.RssLanguage;
                }

                //generator
                ch.Docs = string.Empty;

                documentRoot.Channels.Add(ch);

                foreach (Entry entry in entries)
                {
                    if (entry.IsPublic == false || entry.Syndicated == false)
                    {
                        continue;
                    }

                    IAItem            item        = new IAItem();
                    List <XmlElement> anyElements = new List <XmlElement>();
                    XmlDocument       xmlDoc      = new XmlDocument();

                    item.Title   = entry.Title;
                    item.PubDate = entry.CreatedUtc.ToString("R");

                    if (ch.LastBuildDate == null || ch.LastBuildDate.Length == 0)
                    {
                        ch.LastBuildDate = item.PubDate;
                    }

                    item.Link = SiteUtilities.GetPermaLinkUrl(siteConfig, (ITitledEntry)entry);
                    item.Guid = entry.EntryId;

                    if (!siteConfig.AlwaysIncludeContentInRSS &&
                        entry.Description != null &&
                        entry.Description.Trim().Length > 0)
                    {
                        item.Description = PreprocessItemContent(entry.EntryId, entry.Description);
                    }
                    else
                    {
                        item.Description = ContentFormatter.FormatContentAsHTML(PreprocessItemContent(entry.EntryId, entry.Content));
                    }

                    XmlElement contentEncoded = xmlDoc.CreateElement("content", "encoded", "http://purl.org/rss/1.0/modules/content/");
                    string     encData        = string.Format("<!doctype html>" +
                                                              "<html lang=\"en\" prefix=\"op: http://media.facebook.com/op#\">" +
                                                              "<head>" +
                                                              "<meta charset=\"utf-8\">" +
                                                              "<link rel=\"canonical\" href=\"{3}\">" +
                                                              "<meta property=\"op:markup_version\" content=\"v1.0\">" +
                                                              "</head>" +
                                                              "<body><article>" +
                                                              "<header>{0}</header>" +
                                                              "{1}" +
                                                              "<footer>{2}</footer>" +
                                                              "</article></body></html>",
                                                              entry.Title,
                                                              ContentFormatter.FormatContentAsHTML(PreprocessItemContent(entry.EntryId, entry.Content)),
                                                              string.Empty, item.Link);
                    XmlCDataSection cdata = xmlDoc.CreateCDataSection(encData);
                    contentEncoded.AppendChild(cdata);

                    anyElements.Add(contentEncoded);

                    item.anyElements = anyElements.ToArray();

                    ch.Items.Add(item);
                }
                cache.Insert(CacheKey, documentRoot, DateTime.Now.AddMinutes(5));
            }
            return(documentRoot);
        }
Esempio n. 5
0
        private AtomRoot GetAtomCore(string category, int maxDayCount, int maxEntryCount)
        {
            if (RedirectToFeedBurnerIfNeeded(category) == true)
            {
                return(null);
            }

            EntryCollection entries = null;

            //We only build the entries if blogcore doesn't exist and we'll need them later...
            if (dataService.GetLastEntryUpdate() == DateTime.MinValue)
            {
                entries = BuildEntries(category, maxDayCount, maxEntryCount);
            }

            //Try to get out as soon as possible with as little CPU as possible
            if (inASMX)
            {
                if (SiteUtilities.GetStatusNotModified(SiteUtilities.GetLatestModifedEntryDateTime(dataService, entries)))
                {
                    return(null);
                }
            }

            if (inASMX)
            {
                string referrer = Context.Request.UrlReferrer != null?Context.Request.UrlReferrer.AbsoluteUri:"";
                if (ReferralBlackList.IsBlockedReferrer(referrer))
                {
                    if (siteConfig.EnableReferralUrlBlackList404s)
                    {
                        return(null);
                    }
                }
                else
                {
                    loggingService.AddReferral(
                        new LogDataItem(
                            Context.Request.RawUrl,
                            referrer,
                            Context.Request.UserAgent,
                            Context.Request.UserHostName));
                }
            }


            //not-modified didn't work, do we have this in cache?
            string   CacheKey = "Atom:" + category + ":" + maxDayCount.ToString() + ":" + maxEntryCount.ToString();
            AtomRoot atomFeed = cache[CacheKey] as AtomRoot;

            if (atomFeed == null)             //we'll have to build it...
            {
                atomFeed = new AtomRoot();

                //However, if we made it this far, the not-modified check didn't work, and we may not have entries...
                if (entries == null)
                {
                    entries = BuildEntries(category, maxDayCount, maxEntryCount);
                }

                if (siteConfig.RssLanguage != null && siteConfig.RssLanguage.Length > 0)
                {
                    atomFeed.Lang = siteConfig.RssLanguage;
                }
                else                 //original default behavior of dasBlog
                {
                    atomFeed.Lang = "en-us";
                }

                if (category == null)
                {
                    atomFeed.Title = siteConfig.Title;
                }
                else
                {
                    atomFeed.Title = siteConfig.Title + " - " + category;
                }


                atomFeed.Tagline = siteConfig.Subtitle;
                atomFeed.Links.Add(new AtomLink(SiteUtilities.GetBaseUrl(siteConfig)));
                atomFeed.Links.Add(new AtomLink(SiteUtilities.GetAtomUrl(siteConfig), "self", null));
                atomFeed.Author = new AtomParticipant();
                // shouldn't we use the display name of an owner??
                atomFeed.Author.Name       = siteConfig.Copyright;
                atomFeed.Generator         = new AtomGenerator();
                atomFeed.Generator.Version = GetType().Assembly.GetName().Version.ToString();
                atomFeed.Icon = "favicon.ico";

                atomFeed.Id = SiteUtilities.GetBaseUrl(siteConfig);

                atomFeed.Logo = null;
                if (siteConfig.ChannelImageUrl != null && siteConfig.ChannelImageUrl.Trim().Length > 0)
                {
                    if (siteConfig.ChannelImageUrl.StartsWith("http"))
                    {
                        atomFeed.Logo = siteConfig.ChannelImageUrl;
                    }
                    else
                    {
                        atomFeed.Logo = SiteUtilities.RelativeToRoot(siteConfig, siteConfig.ChannelImageUrl);
                    }
                }


                DateTime feedModified = DateTime.MinValue;

                foreach (Entry entry in entries)
                {
                    if (entry.IsPublic == false || entry.Syndicated == false)
                    {
                        continue;
                    }

                    string entryLink = SiteUtilities.GetPermaLinkUrl(siteConfig, (ITitledEntry)entry);
                    string entryGuid = SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId);

                    AtomEntry atomEntry = new AtomEntry(entry.Title, new AtomLink(entryLink), entryGuid, entry.CreatedUtc, entry.ModifiedUtc);
                    //atomEntry.Created = entry.CreatedUtc; //not needed in 1.0
                    atomEntry.Summary = PreprocessItemContent(entry.EntryId, entry.Description);

                    // for multiuser blogs we want to be able to
                    // show the author per entry
                    User user = SiteSecurity.GetUser(entry.Author);
                    if (user != null)
                    {
                        // only the displayname
                        atomEntry.Author = new AtomParticipant()
                        {
                            Name = user.DisplayName
                        };
                    }

                    if (entry.Categories != null && entry.Categories.Length > 0)
                    {
                        if (atomEntry.Categories == null)
                        {
                            atomEntry.Categories = new AtomCategoryCollection();
                        }

                        string[] cats = entry.Categories.Split(';');
                        foreach (string c in cats)
                        {
                            AtomCategory cat = new AtomCategory();

                            //paulb: scheme should be a valid IRI, acsording to the spec
                            // (http://www.atomenabled.org/developers/syndication/atom-format-spec.php#element.category)
                            // so I changed this to the Category view for specified category. Now the feed validator likes us again ;-)
                            cat.Scheme = SiteUtilities.GetCategoryViewUrl(siteConfig, c);                               // "hierarchical";
                            // sub categories should be delimited using the path delimiter
                            string cleanCat = c.Replace('|', '/');
                            //Grab the first category, atom doesn't let us do otherwise!
                            cat.Term  = HttpUtility.HtmlEncode(cleanCat);
                            cat.Label = HttpUtility.HtmlEncode(cleanCat);
                            atomEntry.Categories.Add(cat);
                        }
                    }


                    // only if we don't have a summary we emit the content
                    if (siteConfig.AlwaysIncludeContentInRSS || entry.Description == null || entry.Description.Length == 0)
                    {
                        atomEntry.Summary = null;                         // remove empty summary tag

                        try
                        {
                            AtomContent atomContent = new AtomContent();
                            atomContent.Type = "xhtml";

                            XmlDocument xmlDoc2 = new XmlDocument();
                            xmlDoc2.LoadXml(ContentFormatter.FormatContentAsXHTML(PreprocessItemContent(entry.EntryId, entry.Content), "div"));
                            atomContent.anyElements = new XmlElement[] { xmlDoc2.DocumentElement };

                            // set the langauge for the content item
                            atomContent.Lang = entry.Language;

                            atomEntry.Content = atomContent;
                        }
                        catch (Exception)                        //XHTML isn't happening today
                        {
                            //Try again as HTML
                            AtomContent atomContent = new AtomContent();
                            atomContent.Type        = "html";
                            atomContent.TextContent = ContentFormatter.FormatContentAsHTML(PreprocessItemContent(entry.EntryId, entry.Content));
                            // set the langauge for the content item
                            atomContent.Lang = entry.Language;

                            atomEntry.Content = atomContent;
                        }
                    }

                    if (atomEntry.ModifiedUtc > feedModified)
                    {
                        feedModified = atomEntry.ModifiedUtc;
                    }

                    atomFeed.Entries.Add(atomEntry);
                }

                // set feed modified date to the most recent entry date
                atomFeed.ModifiedUtc = feedModified;
                cache.Insert(CacheKey, atomFeed, DateTime.Now.AddMinutes(5));
            }
            return(atomFeed);
        }
Esempio n. 6
0
        private RssRoot GetCommentsRssCore(CommentCollection _com, string guid)
        {
            //Try to get out as soon as possible with as little CPU as possible
            if (inASMX)
            {
                DateTime lastModified = SiteUtilities.GetLatestModifedCommentDateTime(dataService, _com);
                if (SiteUtilities.GetStatusNotModified(lastModified))
                {
                    return(null);
                }
            }

            if (inASMX)
            {
                string referrer = Context.Request.UrlReferrer != null?Context.Request.UrlReferrer.AbsoluteUri:"";
                if (ReferralBlackList.IsBlockedReferrer(referrer) == false)
                {
                    loggingService.AddReferral(
                        new LogDataItem(
                            Context.Request.RawUrl,
                            referrer,
                            Context.Request.UserAgent,
                            Context.Request.UserHostName));
                }
            }

            // TODO: Figure out why this code is copied and pasted from above rather than using a function (shame!)
            RssRoot    documentRoot = new RssRoot();
            RssChannel ch           = new RssChannel();

            if (guid != null && guid != String.Empty)
            {
                //Set the title for this RSS Comments feed
                ch.Title = siteConfig.Title + " - Comments on " + dataService.GetEntry(guid).Title;
            }
            else
            {
                ch.Title = siteConfig.Title + " - Comments";
            }
            ch.Link           = SiteUtilities.GetBaseUrl(siteConfig);
            ch.Copyright      = siteConfig.Copyright;
            ch.ManagingEditor = siteConfig.Contact;
            ch.WebMaster      = siteConfig.Contact;
            documentRoot.Channels.Add(ch);


            int i = 0;

            foreach (Comment c in _com)
            {
                List <XmlElement> anyElements = new List <XmlElement>();
                if (i == siteConfig.RssEntryCount)
                {
                    break;
                }
                i++;
                string  tempTitle = "";
                RssItem item      = new RssItem();

                if (c.TargetTitle != null && c.TargetTitle.Length > 0)
                {
                    tempTitle = " on \"" + c.TargetTitle + "\"";
                }

                if (c.Author == null || c.Author == "")
                {
                    item.Title = "Comment" + tempTitle;
                }
                else
                {
                    item.Title = "Comment by " + c.Author + tempTitle;
                }

                //Per the RSS Comments Spec it makes more sense for guid and link to be the same.
                // http://blogs.law.harvard.edu/tech/rss#comments
                // 11/11/05 - SDH - Now, I'm thinking not so much...
                item.Guid             = new Rss20.Guid();
                item.Guid.Text        = c.EntryId;
                item.Guid.IsPermaLink = false;
                item.Link             = SiteUtilities.GetCommentViewUrl(siteConfig, c.TargetEntryId, c.EntryId);

                item.PubDate = c.CreatedUtc.ToString("R");

                item.Description = c.Content.Replace(Environment.NewLine, "<br />");
                if (c.AuthorHomepage == null || c.AuthorHomepage == "")
                {
                    if (c.AuthorEmail == null || c.AuthorEmail == "")
                    {
                        if (!(c.Author == null || c.Author == ""))
                        {
                            item.Description = c.Content.Replace(Environment.NewLine, "<br />") + "<br /><br />" + "Posted by: " + c.Author;
                        }
                    }
                    else
                    {
                        string content = c.Content.Replace(Environment.NewLine, "<br />");
                        if (!siteConfig.SupressEmailAddressDisplay)
                        {
                            item.Description = content + "<br /><br />" + "Posted by: " + "<a href=\"mailto:" + SiteUtilities.SpamBlocker(c.AuthorEmail) + "\">" + c.Author + "</a>";
                        }
                        else
                        {
                            item.Description = content + "<br /><br />" + "Posted by: " + c.Author;
                        }
                    }
                }
                else
                {
                    if (c.AuthorHomepage.IndexOf("http://") < 0)
                    {
                        c.AuthorHomepage = "http://" + c.AuthorHomepage;
                    }
                    item.Description += "<br /><br />" + "Posted by: " + "<a href=\"" + c.AuthorHomepage +
                                        "\">" + c.Author + "</a>";
                }

                if (c.Author != null && c.Author.Length > 0)
                {
                    // the rss spec requires an email address in the author tag
                    // and it can not be obfuscated
                    // according to the feedvalidator
                    string email;

                    if (!siteConfig.SupressEmailAddressDisplay)
                    {
                        email = (c.AuthorEmail != null && c.AuthorEmail.Length > 0 ? c.AuthorEmail : "*****@*****.**");
                    }
                    else
                    {
                        email = "*****@*****.**";
                    }

                    item.Author = String.Format("{0} ({1})", email, c.Author);
                }

                item.Comments = SiteUtilities.GetCommentViewUrl(siteConfig, c.TargetEntryId, c.EntryId);

                if (ch.LastBuildDate == null || ch.LastBuildDate.Length == 0)
                {
                    ch.LastBuildDate = item.PubDate;
                }

                XmlDocument doc2 = new XmlDocument();
                try
                {
                    doc2.LoadXml(c.Content);
                    anyElements.Add((XmlElement)doc2.SelectSingleNode("//*[local-name() = 'body'][namespace-uri()='http://www.w3.org/1999/xhtml']"));
                }
                catch
                {
                    // absorb
                }
                item.anyElements = anyElements.ToArray();
                ch.Items.Add(item);
            }

            return(documentRoot);
        }
Esempio n. 7
0
        private RssRoot GetRssCore(string category, int maxDayCount, int maxEntryCount)
        {
            if (RedirectToFeedBurnerIfNeeded(category) == true)
            {
                return(null);
            }
            EntryCollection entries = null;

            //We only build the entries if blogcore doesn't exist and we'll need them later...
            if (dataService.GetLastEntryUpdate() == DateTime.MinValue)
            {
                entries = BuildEntries(category, maxDayCount, maxEntryCount);
            }

            //Try to get out as soon as possible with as little CPU as possible
            if (inASMX)
            {
                DateTime lastModified = SiteUtilities.GetLatestModifedEntryDateTime(dataService, entries);
                if (SiteUtilities.GetStatusNotModified(lastModified))
                {
                    return(null);
                }
            }

            if (inASMX)
            {
                string referrer = Context.Request.UrlReferrer != null?Context.Request.UrlReferrer.AbsoluteUri:"";
                if (ReferralBlackList.IsBlockedReferrer(referrer))
                {
                    if (siteConfig.EnableReferralUrlBlackList404s)
                    {
                        return(null);
                    }
                }
                else
                {
                    loggingService.AddReferral(
                        new LogDataItem(
                            Context.Request.RawUrl,
                            referrer,
                            Context.Request.UserAgent,
                            Context.Request.UserHostName));
                }
            }

            //not-modified didn't work, do we have this in cache?
            string  CacheKey     = "Rss:" + category + ":" + maxDayCount.ToString() + ":" + maxEntryCount.ToString();
            RssRoot documentRoot = cache[CacheKey] as RssRoot;

            if (documentRoot == null)             //we'll have to build it...
            {
                //However, if we made it this far, the not-modified check didn't work, and we may not have entries...
                if (entries == null)
                {
                    entries = BuildEntries(category, maxDayCount, maxEntryCount);
                }

                documentRoot = new RssRoot();
                documentRoot.Namespaces.Add("dc", "http://purl.org/dc/elements/1.1/");
                documentRoot.Namespaces.Add("trackback", "http://madskills.com/public/xml/rss/module/trackback/");
                documentRoot.Namespaces.Add("pingback", "http://madskills.com/public/xml/rss/module/pingback/");
                if (siteConfig.EnableComments)
                {
                    documentRoot.Namespaces.Add("wfw", "http://wellformedweb.org/CommentAPI/");
                    documentRoot.Namespaces.Add("slash", "http://purl.org/rss/1.0/modules/slash/");
                }
                if (siteConfig.EnableGeoRss)
                {
                    documentRoot.Namespaces.Add("georss", "http://www.georss.org/georss");
                }

                RssChannel ch = new RssChannel();

                if (category == null)
                {
                    ch.Title = siteConfig.Title;
                }
                else
                {
                    ch.Title = siteConfig.Title + " - " + category;
                }

                if (siteConfig.Description == null || siteConfig.Description.Trim().Length == 0)
                {
                    ch.Description = siteConfig.Subtitle;
                }
                else
                {
                    ch.Description = siteConfig.Description;
                }

                ch.Link      = SiteUtilities.GetBaseUrl(siteConfig);
                ch.Copyright = siteConfig.Copyright;
                if (siteConfig.RssLanguage != null && siteConfig.RssLanguage.Length > 0)
                {
                    ch.Language = siteConfig.RssLanguage;
                }
                ch.ManagingEditor = siteConfig.Contact;
                ch.WebMaster      = siteConfig.Contact;
                ch.Image          = null;
                if (siteConfig.ChannelImageUrl != null && siteConfig.ChannelImageUrl.Trim().Length > 0)
                {
                    ChannelImage channelImage = new ChannelImage();
                    channelImage.Title = ch.Title;
                    channelImage.Link  = ch.Link;
                    if (siteConfig.ChannelImageUrl.StartsWith("http"))
                    {
                        channelImage.Url = siteConfig.ChannelImageUrl;
                    }
                    else
                    {
                        channelImage.Url = SiteUtilities.RelativeToRoot(siteConfig, siteConfig.ChannelImageUrl);
                    }
                    ch.Image = channelImage;
                }

                documentRoot.Channels.Add(ch);

                foreach (Entry entry in entries)
                {
                    if (entry.IsPublic == false || entry.Syndicated == false)
                    {
                        continue;
                    }
                    XmlDocument       doc2        = new XmlDocument();
                    List <XmlElement> anyElements = new List <XmlElement>();
                    RssItem           item        = new RssItem();
                    item.Title            = entry.Title;
                    item.Guid             = new Rss20.Guid();
                    item.Guid.IsPermaLink = false;
                    item.Guid.Text        = SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId);
                    item.Link             = SiteUtilities.GetPermaLinkUrl(siteConfig, (ITitledEntry)entry);
                    User user = SiteSecurity.GetUser(entry.Author);
                    //Scott Hanselman: According to the RSS 2.0 spec and FeedValidator.org,
                    // we can have EITHER an Author tag OR the preferred dc:creator tag, but NOT BOTH.
                    //					if (user != null && user.EmailAddress != null && user.EmailAddress.Length > 0)
                    //					{
                    //						if (user.DisplayName != null && user.DisplayName.Length > 0)
                    //						{
                    //							item.Author = String.Format("{0} ({1})", user.EmailAddress, user.DisplayName);
                    //						}
                    //						else
                    //						{
                    //							item.Author = user.EmailAddress;
                    //						}
                    //					}
                    XmlElement trackbackPing = doc2.CreateElement("trackback", "ping", "http://madskills.com/public/xml/rss/module/trackback/");
                    trackbackPing.InnerText = SiteUtilities.GetTrackbackUrl(siteConfig, entry.EntryId);
                    anyElements.Add(trackbackPing);

                    XmlElement pingbackServer = doc2.CreateElement("pingback", "server", "http://madskills.com/public/xml/rss/module/pingback/");
                    pingbackServer.InnerText = new Uri(new Uri(SiteUtilities.GetBaseUrl(siteConfig)), "pingback.aspx").ToString();
                    anyElements.Add(pingbackServer);

                    XmlElement pingbackTarget = doc2.CreateElement("pingback", "target", "http://madskills.com/public/xml/rss/module/pingback/");
                    pingbackTarget.InnerText = SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId);
                    anyElements.Add(pingbackTarget);

                    XmlElement dcCreator = doc2.CreateElement("dc", "creator", "http://purl.org/dc/elements/1.1/");
                    if (user != null)
                    {
                        // HACK AG No author e-mail address in feed items.
                        //						if (user.DisplayName != null && user.DisplayName.Length > 0)
                        //						{
                        //							if(user.EmailAddress != null && user.EmailAddress.Length > 0)
                        //							{
                        //								dcCreator.InnerText = String.Format("{0} ({1})", user.EmailAddress, user.DisplayName);
                        //							}
                        //							else
                        //							{
                        dcCreator.InnerText = user.DisplayName;
                        //							}
                        //						}
                        //						else
                        //						{
                        //							dcCreator.InnerText = user.EmailAddress;
                        //						}
                    }
                    anyElements.Add(dcCreator);

                    // Add GeoRSS if it exists.
                    if (siteConfig.EnableGeoRss)
                    {
                        Nullable <double> latitude  = new Nullable <double>();
                        Nullable <double> longitude = new Nullable <double>();

                        if (entry.Latitude.HasValue)
                        {
                            latitude = entry.Latitude;
                        }
                        else
                        {
                            if (siteConfig.EnableDefaultLatLongForNonGeoCodedPosts)
                            {
                                latitude = siteConfig.DefaultLatitude;
                            }
                        }

                        if (entry.Longitude.HasValue)
                        {
                            longitude = entry.Longitude;
                        }
                        else
                        {
                            if (siteConfig.EnableDefaultLatLongForNonGeoCodedPosts)
                            {
                                longitude = siteConfig.DefaultLongitude;
                            }
                        }

                        if (latitude.HasValue && longitude.HasValue)
                        {
                            XmlElement geoLoc = doc2.CreateElement("georss", "point", "http://www.georss.org/georss");
                            geoLoc.InnerText = String.Format(CultureInfo.InvariantCulture, "{0:R} {1:R}", latitude, longitude);
                            anyElements.Add(geoLoc);
                        }
                    }

                    if (siteConfig.EnableComments)
                    {
                        if (entry.AllowComments)
                        {
                            XmlElement commentApi = doc2.CreateElement("wfw", "comment", "http://wellformedweb.org/CommentAPI/");
                            commentApi.InnerText = SiteUtilities.GetCommentViewUrl(siteConfig, entry.EntryId);
                            anyElements.Add(commentApi);
                        }

                        XmlElement commentRss = doc2.CreateElement("wfw", "commentRss", "http://wellformedweb.org/CommentAPI/");
                        commentRss.InnerText = SiteUtilities.GetEntryCommentsRssUrl(siteConfig, entry.EntryId);
                        anyElements.Add(commentRss);

                        //for RSS conformance per FeedValidator.org
                        int commentsCount = dataService.GetPublicCommentsFor(entry.EntryId).Count;
                        if (commentsCount > 0)
                        {
                            XmlElement slashComments = doc2.CreateElement("slash", "comments", "http://purl.org/rss/1.0/modules/slash/");
                            slashComments.InnerText = commentsCount.ToString();
                            anyElements.Add(slashComments);
                        }
                        item.Comments = SiteUtilities.GetCommentViewUrl(siteConfig, entry.EntryId);
                    }
                    item.Language = entry.Language;

                    if (entry.Categories != null && entry.Categories.Length > 0)
                    {
                        if (item.Categories == null)
                        {
                            item.Categories = new RssCategoryCollection();
                        }

                        string[] cats = entry.Categories.Split(';');
                        foreach (string c in cats)
                        {
                            RssCategory cat      = new RssCategory();
                            string      cleanCat = c.Replace('|', '/');
                            cat.Text = cleanCat;
                            item.Categories.Add(cat);
                        }
                    }
                    if (entry.Attachments.Count > 0)
                    {
                        // RSS currently supports only a single enclsoure so we return the first one
                        item.Enclosure        = new Enclosure();
                        item.Enclosure.Url    = SiteUtilities.GetEnclosureLinkUrl(entry.EntryId, entry.Attachments[0]);
                        item.Enclosure.Type   = entry.Attachments[0].Type;
                        item.Enclosure.Length = entry.Attachments[0].Length.ToString();
                    }
                    item.PubDate = entry.CreatedUtc.ToString("R");
                    if (ch.LastBuildDate == null || ch.LastBuildDate.Length == 0)
                    {
                        ch.LastBuildDate = item.PubDate;
                    }


                    if (!siteConfig.AlwaysIncludeContentInRSS &&
                        entry.Description != null &&
                        entry.Description.Trim().Length > 0)
                    {
                        item.Description = PreprocessItemContent(entry.EntryId, entry.Description);
                    }
                    else
                    {
                        if (siteConfig.HtmlTidyContent == false)
                        {
                            item.Description = "<div>" + PreprocessItemContent(entry.EntryId, entry.Content) + "</div>";
                        }
                        else
                        {
                            item.Description = ContentFormatter.FormatContentAsHTML(PreprocessItemContent(entry.EntryId, entry.Content));


                            try
                            {
                                string xhtml = ContentFormatter.FormatContentAsXHTML(PreprocessItemContent(entry.EntryId, entry.Content));
                                doc2.LoadXml(xhtml);
                                anyElements.Add((XmlElement)doc2.SelectSingleNode("//*[local-name() = 'body'][namespace-uri()='http://www.w3.org/1999/xhtml']"));
                            }
                            catch //(Exception ex)
                            {
                                //Debug.Write(ex.ToString());
                                // absorb
                            }
                        }
                    }

                    item.anyElements = anyElements.ToArray();
                    ch.Items.Add(item);
                }
                cache.Insert(CacheKey, documentRoot, DateTime.Now.AddMinutes(5));
            }
            return(documentRoot);
        }