protected override EntryCollection LoadEntries()
        {
            SharedBasePage requestPage = Page as SharedBasePage;

            EntryCollection entryCollection = DataService.GetEntriesForCategory(categoryName, Request.Headers["Accept-Language"]);

            if (!requestPage.SiteConfig.CategoryAllEntries)
            {
                // Do some paging if we are NOT showing all entries in category view.
                string pageString = Request.QueryString.Get("page");
                int    page;
                if (!int.TryParse(pageString, out page))
                {
                    page = 1;
                }

                if (page != 0)
                {
                    int count = entryCollection.Count;
                    if (count == 0)
                    {
                        Response.Redirect(SiteUtilities.GetBaseUrl());
                    }

                    int entriesPerPage = SiteConfig.EntriesPerPage;
                    int maxPage        = (int)Math.Ceiling((double)count / (double)entriesPerPage);
                    if (page > maxPage)
                    {
                        page = maxPage;
                    }
                    int lastEntryToInclude = page * entriesPerPage;

                    // page = 1, remove everything after.
                    // page = maxPage, remove everything before.
                    // 1 < page < maxPage, remove left and right.
                    if (page == maxPage)
                    {
                        entryCollection.RemoveRange(0, lastEntryToInclude - entriesPerPage);
                    }
                    else
                    {
                        // Remove to the right.
                        entryCollection.RemoveRange(lastEntryToInclude, count - lastEntryToInclude);
                        // Remove to the left.
                        entryCollection.RemoveRange(0, lastEntryToInclude - entriesPerPage);
                    }

                    HttpContext.Current.Items["page"]    = page;
                    HttpContext.Current.Items["maxpage"] = maxPage;
                }
            }

            return(entryCollection);
        }
Esempio n. 2
0
        public static string CreateSeoMetaInformation(EntryCollection weblogEntries, IBlogDataService dataService)
        {
            string metaTags   = "\r\n";
            string currentUrl = HttpContext.Current.Request.Url.AbsoluteUri;

            if (currentUrl.IndexOf("categoryview.aspx", StringComparison.OrdinalIgnoreCase) > -1 || currentUrl.IndexOf("default.aspx?month=", StringComparison.OrdinalIgnoreCase) > -1)
            {
                metaTags += MetaNoindexFollowPattern;
            }
            else if (currentUrl.IndexOf("permalink.aspx", StringComparison.OrdinalIgnoreCase) > -1)
            {
                if (weblogEntries.Count >= 1)
                {
                    Entry entry = weblogEntries[0];
                    metaTags = GetMetaTags(metaTags, entry);
                }
            }
            else if (currentUrl.IndexOf("commentview.aspx", StringComparison.OrdinalIgnoreCase) > -1 && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["guid"]))
            {
                Entry entry = dataService.GetEntry(HttpContext.Current.Request.QueryString["guid"]);
                if (entry != null)
                {
                    metaTags = GetMetaTags(metaTags, entry);
                }
            }
            else if (currentUrl.IndexOf("commentview.aspx", StringComparison.OrdinalIgnoreCase) > -1 && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["title"]))
            {
                Entry entry = dataService.GetEntry(HttpContext.Current.Request.QueryString["title"]);
                if (entry != null)
                {
                    metaTags = GetMetaTags(metaTags, entry);
                }
            }
            else if (currentUrl.IndexOf("default.aspx", StringComparison.OrdinalIgnoreCase) > -1)
            {
                var smt = new SeoMetaTags();
                smt = smt.GetMetaTags();
                if (smt != null)
                {
                    if (!string.IsNullOrEmpty(smt.MetaDescription))
                    {
                        metaTags += string.Format(MetaDescriptionTagPattern, smt.MetaDescription);
                    }

                    if (!string.IsNullOrEmpty(smt.MetaKeywords))
                    {
                        metaTags += string.Format(MetaKeywordTagPattern, smt.MetaKeywords);
                    }
                }
                metaTags += string.Format(CanonicalLinkPattern, SiteUtilities.GetBaseUrl());
            }
            return(metaTags);
        }
        public RsdRoot GetRsd()
        {
            // TODO: NLS - Make the default API configurable through SiteConfig
            SiteConfig       siteConfig    = SiteConfig.GetSiteConfig();
            RsdApiCollection apiCollection = new RsdApiCollection();

            RsdRoot    rsd            = new RsdRoot();
            RsdService dasBlogService = new RsdService();

            dasBlogService.HomePageLink = SiteUtilities.GetBaseUrl(siteConfig);

            RsdApi metaWeblog = new RsdApi();

            metaWeblog.Name      = "MetaWeblog";
            metaWeblog.Preferred = (siteConfig.PreferredBloggingAPI == metaWeblog.Name);
            metaWeblog.ApiLink   = SiteUtilities.GetBloggerUrl(siteConfig);
            metaWeblog.BlogID    = dasBlogService.HomePageLink;
            apiCollection.Add(metaWeblog);

            RsdApi blogger = new RsdApi();

            blogger.Name      = "Blogger";
            blogger.Preferred = (siteConfig.PreferredBloggingAPI == blogger.Name);
            blogger.ApiLink   = SiteUtilities.GetBloggerUrl(siteConfig);
            blogger.BlogID    = dasBlogService.HomePageLink;
            apiCollection.Add(blogger);

            RsdApi moveableType = new RsdApi();

            moveableType.Name      = "Moveable Type";
            moveableType.Preferred = (siteConfig.PreferredBloggingAPI == moveableType.Name);
            moveableType.ApiLink   = SiteUtilities.GetBloggerUrl(siteConfig);
            moveableType.BlogID    = dasBlogService.HomePageLink;
            apiCollection.Add(moveableType);

            dasBlogService.RsdApiCollection = apiCollection;
            rsd.Services.Add(dasBlogService);

            return(rsd);
        }
        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. 5
0
 public static string GetBaseUrl(SiteConfig siteConfig)
 {
     return(SiteUtilities.GetBaseUrl(siteConfig));
 }
Esempio n. 6
0
 public static string GetBaseUrl()
 {
     return(SiteUtilities.GetBaseUrl());
 }
        protected void Page_PreRender(object sender, System.EventArgs e)
        {
            SharedBasePage requestPage = Page as SharedBasePage;

            Control            root  = this;
            HtmlGenericControl entry = new HtmlGenericControl("div");

            if (SiteSecurity.GetUserByEmail(comment.AuthorEmail) == null)
            {
                entry.Attributes["class"] = "commentBoxStyle";
            }
            else
            {
                entry.Attributes["class"] = "commentBoxStyle commentBoxAuthorStyle";
            }
            root.Controls.Add(entry);

            HtmlGenericControl entryTitle = new HtmlGenericControl("div");

            entryTitle.Attributes["class"] = "commentDateStyle";

            //Add the unique anchor for each comment
            HtmlAnchor anchor = new HtmlAnchor();

            anchor.Name = comment.EntryId;
            entryTitle.Controls.Add(anchor);

            if (requestPage.SiteConfig.AdjustDisplayTimeZone)
            {
                entryTitle.Controls.Add(new LiteralControl(requestPage.SiteConfig.GetConfiguredTimeZone().FormatAdjustedUniversalTime(comment.CreatedUtc)));
            }
            else
            {
                entryTitle.Controls.Add(new LiteralControl(comment.CreatedUtc.ToString("U") + " UTC"));
            }
            entry.Controls.Add(entryTitle);


            HtmlGenericControl entryBody = new HtmlGenericControl("div");

            if (SiteSecurity.GetUserByEmail(comment.AuthorEmail) == null)
            {
                entryBody.Attributes["class"] = "commentBodyStyle";
            }
            else
            {
                entryBody.Attributes["class"] = "commentBodyStyle commentBodyAuthorStyle";
            }

            if (comment.Content != null)
            {
                entryBody.Controls.Add(new LiteralControl(Regex.Replace(comment.Content, "\n", "<br />")));
            }
            if (!requestPage.HideAdminTools && SiteSecurity.IsInRole("admin"))
            {
                HtmlGenericControl spamStatus = new HtmlGenericControl("div");
                spamStatus.Attributes["class"] = "commentSpamStateStyle";
                spamStatus.InnerText           = ApplicationResourceTable.GetSpamStateDescription(comment.SpamState);
                entryBody.Controls.Add(spamStatus);
            }


            entry.Controls.Add(entryBody);

            HtmlGenericControl footer = new HtmlGenericControl("div");

            footer.Attributes["class"] = "commentBoxFooterStyle";
            entry.Controls.Add(footer);


            if (requestPage.SiteConfig.CommentsAllowGravatar && String.IsNullOrEmpty(comment.AuthorEmail) == false)
            {
                string hash = "";
                byte[] data, enc;

                data = Encoding.Default.GetBytes(comment.AuthorEmail.ToLowerInvariant());

                using (MD5 md5 = new MD5CryptoServiceProvider())
                {
                    enc = md5.TransformFinalBlock(data, 0, data.Length);
                    foreach (byte b in md5.Hash)
                    {
                        hash += Convert.ToString(b, 16).ToLower().PadLeft(2, '0');
                    }
                    md5.Clear();
                }

                string nogravpath = "";
                if (requestPage.SiteConfig.CommentsGravatarNoImgPath != null)
                {
                    if (requestPage.SiteConfig.CommentsGravatarNoImgPath != "")
                    {
                        if (requestPage.SiteConfig.CommentsGravatarNoImgPath.Substring(0, 4) == "http")
                        {
                            nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.CommentsGravatarNoImgPath);
                        }
                        else
                        {
                            nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.Root + requestPage.SiteConfig.CommentsGravatarNoImgPath);
                        }
                    }
                }

                if (String.IsNullOrEmpty(requestPage.SiteConfig.CommentsGravatarNoImgPath) == false)
                {
                    if (requestPage.SiteConfig.CommentsGravatarNoImgPath == "identicon" ||
                        requestPage.SiteConfig.CommentsGravatarNoImgPath == "wavatar" ||
                        requestPage.SiteConfig.CommentsGravatarNoImgPath == "monsterid" ||
                        requestPage.SiteConfig.CommentsGravatarNoImgPath.Substring(0, 4) == "http")
                    {
                        nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.CommentsGravatarNoImgPath);
                    }
                    else
                    {
                        nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.Root + requestPage.SiteConfig.CommentsGravatarNoImgPath);
                    }
                }

                string gravborder = "";
                if (requestPage.SiteConfig.CommentsGravatarBorder != null)
                {
                    if (requestPage.SiteConfig.CommentsGravatarBorder != "")
                    {
                        gravborder = "&border=" + requestPage.SiteConfig.CommentsGravatarBorder;
                    }
                }

                string gravsize = "";
                if (requestPage.SiteConfig.CommentsGravatarSize != null)
                {
                    if (requestPage.SiteConfig.CommentsGravatarSize != "")
                    {
                        gravsize = "&size=" + requestPage.SiteConfig.CommentsGravatarSize;
                    }
                }

                string gravrating = "";
                if (requestPage.SiteConfig.CommentsGravatarRating != null)
                {
                    if (requestPage.SiteConfig.CommentsGravatarRating != "")
                    {
                        gravrating = "&rating=" + requestPage.SiteConfig.CommentsGravatarRating;
                    }
                }



                HtmlGenericControl entryGRAVATAR = new HtmlGenericControl("span");
                entryGRAVATAR.Attributes["class"] = "commentGravatarBlock";
                entryGRAVATAR.InnerHtml           = "<img class=\"commentGravatar\" src=\"http://www.gravatar.com/avatar.php?gravatar_id=" + hash + gravrating + gravsize + nogravpath + gravborder + "\"/>";
                footer.Controls.Add(entryGRAVATAR);
            }

            string authorLink = null;

            if (comment.AuthorHomepage != null && comment.AuthorHomepage.Length > 0)
            {
                authorLink = FixUrl(comment.AuthorHomepage);
            }
            else if (comment.AuthorEmail != null && comment.AuthorEmail.Length > 0)
            {
                if (!requestPage.SiteConfig.SupressEmailAddressDisplay)
                {
                    authorLink = "mailto:" + SiteUtilities.SpamBlocker(comment.AuthorEmail);
                }
            }

            if (authorLink != null)
            {
                HyperLink link = new HyperLink();
                link.Attributes["class"] = "commentPermalinkStyle";
                link.NavigateUrl         = authorLink;
                link.Text = comment.Author;
                link.Attributes.Add("rel", "nofollow");
                footer.Controls.Add(link);

                if (comment.OpenId)
                {
                    System.Web.UI.WebControls.Image i = new System.Web.UI.WebControls.Image();
                    i.ImageUrl = "~/images/openid-icon-small.gif";
                    i.CssClass = "commentOpenId";
                    link.Controls.Add(i);
                    Literal l = new Literal();
                    l.Text = comment.Author;
                    link.Controls.Add(l);
                }
            }
            else
            {
                Label l = new Label();
                l.Attributes["class"] = "commentPermalinkStyle";
                l.Text = comment.Author;
                footer.Controls.Add(l);
            }


            if (!requestPage.SiteConfig.SupressEmailAddressDisplay)
            {
                if (comment.AuthorEmail != null && comment.AuthorEmail.Length > 0)
                {
                    footer.Controls.Add(new LiteralControl(" | "));

                    HtmlGenericControl mailto = new HtmlGenericControl("span");
                    footer.Controls.Add(mailto);

                    HyperLink link = new HyperLink();
                    link.CssClass    = "commentMailToStyle";
                    link.NavigateUrl = "mailto:" + SiteUtilities.SpamBlocker(comment.AuthorEmail);
                    link.Text        = SiteUtilities.SpamBlocker(comment.AuthorEmail);
                    mailto.Controls.Add(link);
                }
            }

            if (!requestPage.HideAdminTools && SiteSecurity.IsInRole("admin"))
            {
                if (!string.IsNullOrEmpty(comment.AuthorIPAddress))
                {
                    try
                    {
                        if (requestPage.SiteConfig.ResolveCommenterIP == true)
                        {
                            System.Net.IPHostEntry hostInfo = System.Net.Dns.GetHostEntry(comment.AuthorIPAddress);
                            footer.Controls.Add(
                                new LiteralControl(" (" + comment.AuthorIPAddress + " " + hostInfo.HostName + ") "));
                        }
                        else
                        {
                            footer.Controls.Add(new LiteralControl(" (" + comment.AuthorIPAddress + ") "));
                        }
                    }
                    catch
                    {
                        footer.Controls.Add(new LiteralControl(" (" + comment.AuthorIPAddress + ") "));
                    }
                }

                footer.Controls.Add(new LiteralControl(" "));

                // create delete hyperlink
                HyperLink deleteHl = new HyperLink();
                deleteHl.CssClass = "deleteLinkStyle";
                System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
                img.CssClass    = "deleteLinkImageStyle";
                img.ImageUrl    = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("deletebutton")).ToString();
                img.BorderWidth = 0;
                deleteHl.Controls.Add(img);
                deleteHl.NavigateUrl = String.Format("javascript:deleteComment(\"{0}\", \"{1}\", \"{2}\")", Comment.TargetEntryId, Comment.EntryId, Comment.Author == null ? String.Empty : Comment.Author.Replace("\"", "\\\""));

                ResourceManager resmgr = resmgr = ApplicationResourceTable.Get();

                if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "deleteCommentScript"))
                {
                    // add the javascript to allow deletion of the comment
                    string scriptString = "<script type=\"text/javascript\" language=\"JavaScript\">\n";
                    scriptString += "function deleteComment(entryId, commentId, commentFrom)\n";
                    scriptString += "{\n";
                    scriptString += String.Format("	if(confirm(\"{0} \\n\\n\" + commentFrom))\n", resmgr.GetString("text_delete_confirm"));
                    scriptString += "	{\n";
                    scriptString += "		location.href=\"deleteItem.ashx?entryid=\" +  entryId + \"&commentId=\" + commentId\n";
                    scriptString += "	}\n";
                    scriptString += "}\n";
                    scriptString += "</script>";

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "deleteCommentScript", scriptString);
                }


                footer.Controls.Add(deleteHl);

                // create approve hyperlink, when a comment is not public or if its marked as spam
                if ((!Comment.IsPublic) || (Comment.SpamState == SpamState.Spam))
                {
                    HyperLink approveHl = new HyperLink();
                    approveHl.CssClass = "approveLinkStyle";
                    System.Web.UI.WebControls.Image okImg = new System.Web.UI.WebControls.Image();
                    okImg.CssClass    = "approveImageStyle";
                    okImg.ImageUrl    = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("okbutton-list")).ToString();
                    okImg.BorderWidth = 0;
                    approveHl.Controls.Add(okImg);
                    approveHl.NavigateUrl = String.Format("javascript:approveComment(\"{0}\", \"{1}\")", Comment.TargetEntryId, Comment.EntryId);

                    if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "approveCommentScript"))
                    {
                        string approveScript = "<script type=\"text/javascript\" language=\"JavaScript\">\n";
                        approveScript += "function approveComment(entryId, commentId)\n";
                        approveScript += "{\n";
                        approveScript += "	location.href=\"approveItem.ashx?entryid=\" +  entryId + \"&commentId=\" + commentId\n";
                        approveScript += "}\n";
                        approveScript += "</script>";

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "approveCommentScript", approveScript);
                    }

                    footer.Controls.Add(approveHl);
                }
                ISpamBlockingService spamBlockingService = requestPage.SiteConfig.SpamBlockingService;
                if ((spamBlockingService != null) && (comment.SpamState != SpamState.Spam))
                {
                    HyperLink reportSpamLink = new HyperLink();
                    reportSpamLink.CssClass = "approveLinkStyle";
                    System.Web.UI.WebControls.Image spamImg = new System.Web.UI.WebControls.Image();
                    spamImg.CssClass    = "approveImageStyle";
                    spamImg.ImageUrl    = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("reportspambutton")).ToString();
                    spamImg.BorderWidth = 0;
                    reportSpamLink.Controls.Add(spamImg);
                    reportSpamLink.NavigateUrl = String.Format("javascript:reportComment(\"{0}\", \"{1}\", \"{2}\")", Comment.TargetEntryId, Comment.EntryId, Comment.Author == null ? String.Empty : Comment.Author.Replace("\"", "\\\""));

                    string reportScript = "<script type=\"text/javascript\" language=\"JavaScript\">\n";
                    reportScript += "function reportComment(entryId, commentId, commentFrom)\n";
                    reportScript += "{\n";
                    reportScript += String.Format("	if(confirm(\"{0} \\n\\n\" + commentFrom))\n", resmgr.GetString("text_reportspam_confirm"));
                    reportScript += "	{\n";
                    reportScript += "		location.href=\"deleteItem.ashx?report=true&entryid=\" +  entryId + \"&commentId=\" + commentId\n";
                    reportScript += "	}\n";
                    reportScript += "}\n";
                    reportScript += "</script>";

                    if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "reportCommentScript"))
                    {
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "reportCommentScript", reportScript);
                    }

                    footer.Controls.Add(reportSpamLink);
                }
            }
        }
        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);
            }
        }
Esempio n. 9
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. 10
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. 11
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. 12
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. 13
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);
        }