Beispiel #1
0
        protected void buttonSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SharedBasePage requestPage = Page as SharedBasePage;
                SiteConfig     siteConfig  = requestPage.SiteConfig;

                string userName = requestPage.User.Identity.Name;

                User user = SiteSecurity.GetUser(userName);

                // failed to retrieve the user
                if (user != null)
                {
                    if (textPassword.Text.Length > 0 && textPassword.Text != passwordPlaceHolder)
                    {
                        user.Password = textPassword.Text;
                    }

                    user.EmailAddress       = textEMail.Text;
                    user.NotifyOnNewPost    = checkboxNewPost.Checked;
                    user.NotifyOnAllComment = checkboxAllComment.Checked;
                    user.NotifyOnOwnComment = checkboxOwnComment.Checked;
                    user.DisplayName        = textDisplayName.Text;
                    user.OpenIDUrl          = textOpenIdIdentifier.Text;

                    SiteSecurity.UpdateUser(user);
                }

                SetProfileContent(editControl.Text);
                requestPage.Redirect(Page.Request.Url.AbsoluteUri);
            }
        }
Beispiel #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SharedBasePage requestPage = this.Page as SharedBasePage;

            if (!SiteSecurity.IsValidContributor())
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            this.ID = "EditUserBox";

            editControl.Text   = GetProfileContent();
            editControl.Width  = Unit.Percentage(99d);
            editControl.Height = Unit.Pixel(400);
            editControl.SetLanguage(CultureInfo.CurrentUICulture.Name);
            editControl.SetTextDirection(requestPage.ReadingDirection);

            if (!IsPostBack)
            {
                SiteConfig siteConfig  = requestPage.SiteConfig;
                User       currentUser = SiteSecurity.GetUser(requestPage.User.Identity.Name);

                textEMail.Text             = currentUser.EmailAddress;
                textDisplayName.Text       = currentUser.DisplayName;
                checkboxNewPost.Checked    = currentUser.NotifyOnNewPost;
                checkboxAllComment.Checked = currentUser.NotifyOnAllComment;
                checkboxOwnComment.Checked = currentUser.NotifyOnOwnComment;
                textPassword.Text          = passwordPlaceHolder;
                textConfirmPassword.Text   = passwordPlaceHolder;
                textOpenIdIdentifier.Text  = currentUser.OpenIDUrl;

                DataBind();
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (SiteSecurity.IsInRole("admin") == false)
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }



            if (!IsPostBack ||
                Session["newtelligence.DasBlog.Web.EditBlogRollBox.OpmlTree"] == null)
            {
                SharedBasePage requestPage = Page as SharedBasePage;
                foreach (string file in Directory.GetFiles(SiteConfig.GetConfigPathFromCurrentContext(), "*.opml"))
                {
                    listFiles.Items.Add(Path.GetFileName(file));
                }
                if (listFiles.Items.Count == 0)
                {
                    listFiles.Items.Add("blogroll.opml");
                }
                Session["newtelligence.DasBlog.Web.EditBlogRollBox.baseFileName"] = baseFileName = listFiles.Items[0].Text;
                string fileName = Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(), baseFileName);
                LoadOutline(fileName);
            }
            else
            {
                baseFileName = Session["newtelligence.DasBlog.Web.EditBlogRollBox.baseFileName"] as string;
                opmlTree     = Session["newtelligence.DasBlog.Web.EditBlogRollBox.OpmlTree"] as Opml;
            }
            BindGrid();
        }
Beispiel #4
0
 protected void Application_AuthenticateRequest(Object sender, EventArgs e)
 {
     if (Request.IsAuthenticated == true)
     {
         HttpCookie authenCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
         if (authenCookie == null)
         {
             FormsAuthentication.SignOut();
             HttpContext.Current.User = null;
             return;
         }
         FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authenCookie.Value);
         FormsIdentity             id     = new FormsIdentity(ticket);
         UserToken token = SiteSecurity.GetToken(ticket.Name);
         if (token != null)
         {
             GenericPrincipal principal = new GenericPrincipal(id, new string[] { token.Role });
             HttpContext.Current.User = principal;
         }
         else
         {
             FormsAuthentication.SignOut();
             HttpContext.Current.User = null;
         }
     }
 }
Beispiel #5
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            requestPage = Page as SharedBasePage;

            // if you are commenting on your own blog, no need for Captha
            if (SiteSecurity.IsValidContributor())
            {
                CaptchaControl1.Enabled = CaptchaControl1.Visible = false;
            }
            else
            {
                CaptchaControl1.Enabled = CaptchaControl1.Visible = requestPage.SiteConfig.EnableCaptcha;
            }

            resmgr = ApplicationResourceTable.Get();

            if (!IsPostBack)
            {
                if (Request.Cookies["name"] != null)
                {
                    string nameStr = HttpUtility.UrlDecode(Request.Cookies["name"].Value, Encoding.UTF8);
                    //truncate at 32 chars to avoid abuse...
                    name.Text = nameStr.Substring(0, Math.Min(32, nameStr.Length));
                }

                if (Request.Cookies["email"] != null)
                {
                    email.Text = HttpUtility.UrlDecode(Request.Cookies["email"].Value, Encoding.UTF8);
                }
            }

            DataBind();
        }
 // handles the button click
 protected void doSignIn_Click(object sender, System.EventArgs e)
 {
     if (SiteConfig.EncryptLoginPassword)
     {
         string viewStateChallenge = ViewState["challenge"] as string;
         if (viewStateChallenge == null)
         {
             throw new ArgumentException("Password Challenge was null in ViewState!");
         }
         UserToken token = SiteSecurity.Login(username.Text, challenge.Value, viewStateChallenge.ToString());
         if (token != null)
         {
             SetAuthCookie(token.Name, username.Text);
             Response.Redirect(SiteUtilities.GetAdminPageUrl(), true);
         }
         else
         {
             challenge.Value        = Session.SessionID.ToString();
             ViewState["challenge"] = challenge.Value;
         }
     }
     else
     {
         UserToken token = SiteSecurity.Login(username.Text, password.Text);
         if (token != null)
         {
             SetAuthCookie(token.Name, username.Text);
             Response.Redirect(SiteUtilities.GetAdminPageUrl(), true);
         }
     }
 }
 protected void Eventlog_Load(object sender, System.EventArgs e)
 {
     this.CategoryName = "admin";
     if (SiteSecurity.IsInRole("admin") == false)
     {
         Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
     }
 }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (SiteSecurity.IsInRole("admin") == false)
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            //set the current page <li> tag to here
            string filePath = this.Request.FilePath;

            if (filePath.EndsWith("CrosspostReferrers.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                crosspost.Attributes["class"]           = "here";
                hyperlinkCrosspostReferrers.NavigateUrl = "";
            }
            else if (filePath.EndsWith("UserClickThroughs.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                userclickthrough.Attributes["class"]   = "here";
                hyperlinkUserClickThroughs.NavigateUrl = "";
            }
            else if (filePath.EndsWith("ClickThroughs.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                clickthrough.Attributes["class"]   = "here";
                hyperlinkClickThroughs.NavigateUrl = "";
            }
            else if (filePath.EndsWith("AggBugs.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                aggbugs.Attributes["class"]  = "here";
                hyperlinkAggBugs.NavigateUrl = "";
            }
            else if (filePath.EndsWith("Referrers.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                referrers.Attributes["class"]  = "here";
                hyperLinkReferrers.NavigateUrl = "";
            }
            else if (filePath.EndsWith("Eventlog.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                eventlog.Attributes["class"]  = "firstHere";
                hyperLinkEventlog.NavigateUrl = "";
            }

            if (this.Request.QueryString["date"] != null)
            {
                AddDateQueryString(hyperLinkEventlog);
                AddDateQueryString(hyperLinkReferrers);
                AddDateQueryString(hyperlinkAggBugs);
                AddDateQueryString(hyperlinkClickThroughs);
                AddDateQueryString(hyperlinkUserClickThroughs);
                AddDateQueryString(hyperlinkCrosspostReferrers);
            }
        }
Beispiel #9
0
        protected override EntryCollection LoadEntries()
        {
            string userName = Request.QueryString["user"];

            User user = SiteSecurity.GetUser(userName);

            if (user != null && !String.IsNullOrEmpty(user.DisplayName))
            {
                userName = user.DisplayName;
            }

            base.TitleOverride = string.Format("{0}'s profile", userName);
            return(new EntryCollection());
        }
 /// <summary>
 /// Fired upon login.
 /// Note, that straight after login, forms auth will redirect the user to their original page. So this page may never be rendererd.
 /// </summary>
 protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e)
 {
     // only allow the openid validation when it's enabled in the siteconfig
     if (SiteConfig.AllowOpenIdAdmin)
     {
         e.Cancel = true; //Need to cancel or the control will log us in for free. Eek!
         UserToken token = SiteSecurity.Login(e.Response);
         if (token != null)
         {
             SetAuthCookie(token.Name, token.Name);
             Response.Redirect(SiteUtilities.GetAdminPageUrl(), true);
         }
     }
 }
Beispiel #11
0
 private static void Login(UserToken token, String userName)
 {
     if (token == null)
     {
         SiteSecurity.LogFailure(userName);
     }
     else
     {
         SiteSecurity.LogSuccess(token.Name);
         GenericIdentity  identity  = new GenericIdentity(token.Name, "Custom");
         GenericPrincipal principal = new GenericPrincipal(identity, new string[] { token.Role });
         HttpContext.Current.User = principal;
         System.Threading.Thread.CurrentPrincipal = principal;
     }
 }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (SiteSecurity.IsInRole("admin") == false)
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            resmgr = ((System.Resources.ResourceManager)ApplicationResourceTable.Get());

            if (!IsPostBack || crosspostSites == null)
            {
                LoadSites( );
            }

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

            if (SiteSecurity.IsInRole("admin") == false)
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            resmgr = ((ResourceManager)ApplicationResourceTable.Get());

            if (!IsPostBack || contentFilters == null)
            {
                LoadFilters();
                UpdateTestBox();
            }

            BindGrid();
        }
Beispiel #14
0
        /// <summary>
        /// This function takes a password, the  challenge and the userName to
        /// make an super challenge like on the client side.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="clientHash"></param>
        /// <param name="challenge"></param>
        /// <returns>user as UserToken.</returns>
        public static UserToken Login(string userName, string clientHash, string challenge)
        {
            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());

            UserToken token = null;

            /*
             *          SiteSecurityConfig ssc = GetSecurity();
             *          foreach (User user in ssc.Users)
             *          {
             *  if (user.Active && user.Name.Equals(userName, StringComparison.InvariantCultureIgnoreCase))
             *                  {
             *                          if (DoSuperChallenge(challenge, user.Password, userName, clientHash))
             *                          {
             *                                  token = user.ToToken();
             *                                  break;
             *                          }
             *                  }
             *          }
             */
            User user = GetUser(userName);

            if (user != null && user.Active && DoSuperChallenge(challenge, user.Password, userName, clientHash))
            {
                token = user.ToToken();
            }

            if (token == null)
            {
                SiteSecurity.LogFailure(userName);
            }
            else
            {
                SiteSecurity.LogSuccess(token.Name);
                GenericIdentity  identity  = new GenericIdentity(token.Name, "Custom");
                GenericPrincipal principal = new GenericPrincipal(identity, new string[] { token.Role });
                HttpContext.Current.User = principal;
                System.Threading.Thread.CurrentPrincipal = principal;
            }

            return(token);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            SharedBasePage page = this.Page as SharedBasePage;

            if (!page.SiteConfig.EnableStartPageCaching)
            {
                UserCollection users = SiteSecurity.GetSecurity().Users;

                if (users != null && users.Count > 0)
                {
                    listProfiles.Items.Add(new ListItem("(select)", string.Empty));

                    users.Sort(new UserSorter());

                    foreach (User user in users)
                    {
                        string profileName = string.Empty;

                        if (user.DisplayName != null && user.DisplayName.Length > 0)
                        {
                            profileName = user.DisplayName;
                        }
                        else
                        {
                            profileName = user.Name;
                        }

                        listProfiles.Items.Add(new ListItem(profileName, user.Name));
                    }
                }
                else
                {
                    this.Visible = false;
                }
            }
            else
            {
                this.Visible = false;
            }

            listProfiles.SelectedValue = string.Empty;
        }
        private object[] ComposeMailForUsers(Entry entry, Comment c)
        {
            List <object> actions = new List <object>();

            foreach (User user in SiteSecurity.GetSecurity().Users)
            {
                if (user.EmailAddress == null || user.EmailAddress.Length == 0)
                {
                    continue;
                }

                if (user.NotifyOnAllComment || (user.NotifyOnOwnComment && entry.Author.ToUpper() == user.Name.ToUpper()))
                {
                    SendMailInfo sendMailInfo = ComposeMail(c);
                    sendMailInfo.Message.To.Add(user.EmailAddress);
                    actions.Add(sendMailInfo);
                }
            }

            return(actions.ToArray());
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (SiteSecurity.IsInRole("admin") == false)
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            resmgr = ((System.Resources.ResourceManager)ApplicationResourceTable.Get());

            if (!IsPostBack ||
                Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] == null)
            {
                SharedBasePage requestPage = Page as SharedBasePage;
                string         fileName    = Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(), baseFileName);
                LoadList(fileName);
            }
            else
            {
                navigationRoot = Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] as NavigationRoot;
            }
            BindGrid();
        }
Beispiel #18
0
 /// <summary>
 /// Shortcut for determining a valid contributor to the blog...currently only users in the "admin" role
 /// or the "contributor" role are supported.
 /// </summary>
 public static bool IsValidContributor()
 {
     return(SiteSecurity.IsInRole("admin") || SiteSecurity.IsInRole("contributor"));
 }
        protected void save_Click(object sender, EventArgs e)
        {
            SharedBasePage requestPage = this.Page as SharedBasePage;

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

                CrosspostInfoCollection crosspostList = new CrosspostInfoCollection();
                Entry entry;

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

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

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

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

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

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

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

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

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

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

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

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

                // handle categories
                string categories = "";

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

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

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

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

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

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

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

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

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

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

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


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

                if (Session["newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer"] != null)
                {
                    Uri originalReferrer = Session["newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer"] as Uri;
                    Session.Remove("newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer");
                    Redirect(originalReferrer.AbsoluteUri);
                }
                else
                {
                    Redirect(SiteUtilities.GetAdminPageUrl(requestPage.SiteConfig));
                }
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            SharedBasePage requestPage = Page as SharedBasePage;

            // only allow users to login using openid when we actually allow it
            if (requestPage.SiteConfig.AllowOpenIdComments == true)
            {
                OpenIdRelyingParty      openid   = new OpenIdRelyingParty();
                IAuthenticationResponse response = openid.GetResponse();
                if (response != null)
                {
                    // Stage 3: OpenID Provider sending assertion response
                    switch (response.Status)
                    {
                    case AuthenticationStatus.Authenticated:
                        ClaimsResponse sregResponse = response.GetExtension <ClaimsResponse>();
                        FetchResponse  axResponse   = response.GetExtension <FetchResponse>();
                        string         nick         = response.FriendlyIdentifierForDisplay;
                        string         homepage     = response.ClaimedIdentifier;
                        string         email        = "*****@*****.**";
                        if (sregResponse != null)
                        {
                            nick  = string.IsNullOrEmpty(sregResponse.Nickname) ? sregResponse.FullName : sregResponse.Nickname;
                            email = sregResponse.Email;
                        }

                        if (String.IsNullOrEmpty(nick) && axResponse != null && axResponse.Attributes.Contains(WellKnownAttributes.Name.First) && axResponse.Attributes.Contains(WellKnownAttributes.Name.Last))
                        {
                            nick = axResponse.GetAttributeValue(WellKnownAttributes.Name.First) + " " +
                                   axResponse.GetAttributeValue(WellKnownAttributes.Name.Last);
                        }

                        string comment = Session["pendingComment"] as string;
                        string entryId = Session["pendingEntryId"] as string;
                        if (String.IsNullOrEmpty(comment) == false && String.IsNullOrEmpty(entryId) == false)
                        {
                            AddNewComment(nick, email, homepage, comment, entryId, /* openid */ true);
                        }

                        break;
                    }
                }
            }

            // if you are commenting on your own blog, no need for Captha
            if (SiteSecurity.IsValidContributor())
            {
                CaptchaControl1.Enabled = CaptchaControl1.Visible = false;
            }
            else
            {
                CaptchaControl1.Enabled = CaptchaControl1.Visible = requestPage.SiteConfig.EnableCaptcha;
            }

            resmgr = ApplicationResourceTable.Get();

            if (!IsPostBack)
            {
                if (requestPage.WeblogEntryId.Length == 0)
                {
                    requestPage.Redirect(SiteUtilities.GetStartPageUrl(requestPage.SiteConfig));
                }
                ViewState["entryId"] = requestPage.WeblogEntryId;

                if (Request.Cookies["name"] != null)
                {
                    string nameStr = HttpUtility.UrlDecode(Request.Cookies["name"].Value, Encoding.UTF8);
                    //truncate at 32 chars to avoid abuse...
                    name.Text = nameStr.Substring(0, Math.Min(32, nameStr.Length));
                }

                if (Request.Cookies["email"] != null)
                {
                    email.Text = HttpUtility.UrlDecode(Request.Cookies["email"].Value, Encoding.UTF8);
                }

                if (Request.Cookies["homepage"] != null)
                {
                    homepage.Text = HttpUtility.UrlDecode(Request.Cookies["homepage"].Value, Encoding.UTF8);
                }

                if (Request.Cookies["openid"] != null)
                {
                    openid_identifier.Text = HttpUtility.UrlDecode(Request.Cookies["openid"].Value, Encoding.UTF8);
                }
            }

            DataBind();
        }
        public void AddNewComment(string name, string email, string homepage, string comment, string entryId, bool openid)
        {
            SharedBasePage requestPage = Page as SharedBasePage;

            // if we allow tags, use the allowed tags, otherwise use an empty array
            ValidTagCollection allowedTags = (requestPage.SiteConfig.CommentsAllowHtml ? requestPage.SiteConfig.AllowedTags : new ValidTagCollection(null));

            Entry entry = requestPage.DataService.GetEntry(entryId);

            if ((entry != null) && SiteUtilities.AreCommentsAllowed(entry, requestPage.SiteConfig))
            {
                Comment c = new Comment();
                c.Initialize();
                c.OpenId          = openid;
                c.Author          = HttpUtility.HtmlEncode(name);
                c.AuthorEmail     = HttpUtility.HtmlEncode(email);
                c.AuthorHomepage  = FixUrl(homepage);
                c.AuthorIPAddress = Request.UserHostAddress;
                c.AuthorUserAgent = Request.UserAgent;
                c.Referer         = Request.UrlReferrer != null?Request.UrlReferrer.ToString() : String.Empty;

                // clean the code from html tags


                c.TargetEntryId = entryId;
                c.TargetTitle   = entry.Title;

                if (requestPage.SiteConfig.CommentsRequireApproval == true &&
                    (requestPage.SiteConfig.SmtpServer == null || requestPage.SiteConfig.SmtpServer.Length == 0))
                {
                    requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.Error, "ERROR: Comment Moderation is turned on, but you haven't configured an SMTP Server for sending mail!", ""));
                }

                // if comments require moderation, they are not public.
                // except when the commenter is a contributor
                if (SiteSecurity.IsValidContributor())
                {
                    c.IsPublic = true;
                }
                else
                {
                    // bypass spam when the comment is authenticated by openid en openid doesn't require approval
                    if (requestPage.SiteConfig.EnableSpamBlockingService && (requestPage.SiteConfig.BypassSpamOpenIdComment && openid) == false)
                    {
                        // make sure to send the unfiltered comment for analysis by external service
                        c.Content = comment;
                        bool externalServiceSucceeded = false;
                        try
                        {
                            if (requestPage.SiteConfig.SpamBlockingService.IsSpam(c))
                            {
                                potentialSpamSubmitted = true;
                                if (!requestPage.SiteConfig.EnableSpamModeration)
                                {
                                    // abort saving the comment
                                    requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.CommentBlocked, String.Format("Blocking suspected spam from {0} {1} [{2}].", c.Author, c.AuthorEmail, c.AuthorIPAddress), SiteUtilities.GetPermaLinkUrl(entryId)));
                                    clearCommentInput();
                                    return;
                                }
                                c.SpamState = SpamState.Spam;
                                c.IsPublic  = false;
                            }
                            else
                            {
                                c.SpamState = SpamState.NotSpam;
                                c.IsPublic  = true;
                            }
                            externalServiceSucceeded = true;
                        }
                        catch (Exception ex)
                        {
                            requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for comment {0}. Original exception: {1}", c.EntryId, ex), SiteUtilities.GetPermaLinkUrl(entryId)));
                        }
                        if (!externalServiceSucceeded)
                        {
                            // If the external service fails, we will hide the comment, but not delete it,
                            // even if moderation is disabled.
                            c.SpamState = SpamState.NotChecked;
                            if (doesFeedbackHaveSpamPotential(c))
                            {
                                potentialSpamSubmitted = true;
                                c.IsPublic             = false;
                            }
                            else
                            {
                                c.IsPublic = true;
                            }
                        }
                    }
                    else
                    {
                        c.IsPublic = true;
                    }
                    // If comment moderation enabled, hide all comments regardless of the what the external spam service says
                    if (requestPage.SiteConfig.CommentsRequireApproval)
                    {
                        c.IsPublic = false;
                    }
                }

                // FilterHtml html encodes anything we don't like
                string filteredText = SiteUtilities.FilterHtml(comment, allowedTags);
                c.Content = filteredText;


                if (requestPage.SiteConfig.SendCommentsByEmail &&
                    requestPage.SiteConfig.SmtpServer != null &&
                    requestPage.SiteConfig.SmtpServer.Length > 0)
                {
                    SendMailInfo defaultMailInfo = ComposeMail(c);
                    requestPage.DataService.AddComment(c, defaultMailInfo);
                    requestPage.DataService.RunActions(ComposeMailForUsers(entry, c));

                    string commentShort = c.Content.Replace("\n", "");
                    if (commentShort.Length > 50)
                    {
                        commentShort = commentShort.Substring(0, 50) + "...";
                    }
                    requestPage.LoggingService.AddEvent(
                        new EventDataItem(
                            EventCodes.CommentAdded, commentShort, SiteUtilities.GetCommentViewUrl(entryId)));
                }
                else
                {
                    requestPage.DataService.AddComment(c);
                }

                clearCommentInput();

                // break the caching
                requestPage.DataCache.Remove("BlogCoreData");
                Session.Remove("pendingComment");
                Session.Remove("pendingEntryId");

                //Send the user to the comment they JUST posted.
                if (!potentialSpamSubmitted)
                {
                    Response.Redirect(SiteUtilities.GetCommentViewUrl(c.TargetEntryId) + "#" + c.EntryId);
                }
            }
        }
        protected void CommentView_PreRender(object sender, System.EventArgs e)
        {
            SharedBasePage requestPage    = Page as SharedBasePage;
            string         entryId        = (string)ViewState["entryId"];
            bool           obfuscateEmail = requestPage.SiteConfig.ObfuscateEmail;

            Entry entry = requestPage.DataService.GetEntry(entryId);

            if (entry != null)
            {
                //Modified 10-3-03 HPierson
                //Render the day template with just the single entry, rather than the item template
                //Modified 12-8-03 HPierson
                //Using entry.CreatedLocalTime causes a bug when dasBlog is not configured to be in
                //the same time zone as the server. Instead, we use the configured WindowsTimeZone
                //to calculate the dasBlog configured local time for the entry
                requestPage.WeblogEntries.Add(entry);
                if (requestPage.SiteConfig.AdjustDisplayTimeZone)
                {
                    newtelligence.DasBlog.Util.WindowsTimeZone wtz = requestPage.SiteConfig.GetConfiguredTimeZone();
                    requestPage.ProcessDayTemplate(wtz.ToLocalTime(entry.CreatedUtc), commentViewContent);
                }
                else
                {
                    requestPage.ProcessDayTemplate(entry.CreatedUtc, commentViewContent);
                }

                HtmlAnchor commentStart = new HtmlAnchor();
                commentStart.Name = "commentstart";
                commentViewContent.Controls.Add(commentStart);

                // Show all public comments, or all contents if you can approve them
                // This way all non-public comments remain hidden, when you no longer require approval.
                bool allComments = SiteSecurity.IsValidContributor();

                foreach (Comment c in requestPage.DataService.GetCommentsFor(entryId, allComments))
                {
                    SingleCommentView view = (SingleCommentView)LoadControl("SingleCommentView.ascx");
                    view.Comment        = c;
                    view.ObfuscateEmail = obfuscateEmail;
                    commentViewContent.Controls.Add(view);
                }

                commentsClosed.Visible   = false;
                commentViewTable.Visible = true;
                // only show the openid option when allowed in the config
                openIdTable.Visible = requestPage.SiteConfig.AllowOpenIdComments;

                commentsGravatarEnabled.Visible = requestPage.SiteConfig.CommentsAllowGravatar;

                // show the comments require approval warning when moderating, or suspected spam,
                // maybe users won't post multiple comments when their comment won't show immediately
                commentsModerated.Visible = (requestPage.SiteConfig.CommentsRequireApproval || potentialSpamSubmitted);
                if (potentialSpamSubmitted)
                {
                    labelCommentsModerated.Text = resmgr.GetString("text_comment_potential_spam");
                }
                // display no/some html
                labelCommentHtml.Visible = requestPage.SiteConfig.CommentsAllowHtml && (requestPage.SiteConfig.AllowedTags.AllowedTagsCount > 0);
                labelComment.Visible     = !labelCommentHtml.Visible;
                labelCommentHtml.Text    = String.Format(resmgr.GetString("text_comment_content_html"), requestPage.SiteConfig.AllowedTags.ToString());

                if (SiteUtilities.AreCommentsAllowed(entry, requestPage.SiteConfig) == false)
                {
                    commentsClosed.Visible   = true;
                    commentViewTable.Visible = false;
                    openIdTable.Visible      = false;
                    // if comments are not allow, there is no need to show the approval warning
                    commentsModerated.Visible = false;
                }

                if (Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "coCommentScript") == false && requestPage.SiteConfig.EnableCoComment == true)
                {
                    string coCommentScript = String.Format(@"

					<script type=""text/javascript"">
// this ensures coComment gets the correct values
coco =
{{
     tool          : ""dasBlog"",
     siteurl       : ""{0}"",
     sitetitle     : ""{1}"",
     pageurl       : ""{2}"",
     pagetitle     : ""{3}"",
     author        : ""{4}"",
     formID        : ""{5}"",
     textareaID    : ""{6}"",
     buttonID      : ""{7}""
}}
</script>
<script id=""cocomment-fetchlet"" src=""http://www.cocomment.com/js/enabler.js"" type=""text/javascript"">
// this activates coComment
</script>
  ",
                                                           requestPage.SiteConfig.Root,
                                                           Server.HtmlEncode(requestPage.SiteConfig.Title),
                                                           Request.Url.ToString(),
                                                           Server.HtmlEncode(entry.Title),
                                                           Server.HtmlEncode(entry.Author),
                                                           this.Page.Form.ClientID,
                                                           this.comment.ClientID,
                                                           this.add.ClientID
                                                           );
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "coComment", coCommentScript);
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// This function takes a password and the userName to
        /// compare the password with the password asigned to the userName.
        /// Both passwords, only one or none will exist as md5 hashed.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>user as UserToken.</returns>
        public static UserToken Login(string userName, string password)
        {
            UserToken          token = null;
            SiteSecurityConfig ssc   = GetSecurity();

            /*
             * foreach (User user in ssc.Users)
             * {
             *  if (user.Name.ToUpper() == userName.ToUpper() && user.Active)
             *  {
             *      if ((IsCleanStringEncrypted(user.Password) && IsCleanStringEncrypted(password)) ||
             *          (!IsCleanStringEncrypted(user.Password) && !IsCleanStringEncrypted(password)))
             *      {
             *          if (user.Password == password)
             *          {
             *              token = user.ToToken();
             *              break;
             *          }
             *          else if (user.Password == SiteSecurity.Encrypt(password))
             *          {
             *              token = user.ToToken();
             *              break;
             *          }
             *      }
             *      else if ((IsCleanStringEncrypted(user.Password) && !IsCleanStringEncrypted(password)))
             *      {
             *          if (user.Password == Encrypt(password))
             *          {
             *              token = user.ToToken();
             *              break;
             *          }
             *      }
             *      else
             *      {
             *          if (Encrypt(user.Password) == password)
             *          {
             *              token = user.ToToken();
             *              break;
             *          }
             *      }
             *  }
             * }
             * */
            User user = GetUser(userName);

            if (user != null && user.Active)
            {
                //Make sure password is encrypted
                if (!IsCleanStringEncrypted(password))
                {
                    password = SiteSecurity.Encrypt(password);
                }
                //if the stored password is encrypted, test equality, or test equality with the encrypted version of it
                if ((IsCleanStringEncrypted(user.Password) && user.Password == password) || (SiteSecurity.Encrypt(user.Password) == password))
                {
                    token = user.ToToken();
                }
            }

            Login(token, userName);

            return(token);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            SharedBasePage requestPage = this.Page as SharedBasePage;

            siteConfig = SiteConfig.GetSiteConfig();

            resmgr = ApplicationResourceTable.Get();

            imageUpload.Accept = "image/jpeg,image/gif,image/png";
            editControl.Width  = Unit.Percentage(99d);
            editControl.Height = Unit.Pixel(400);
            editControl.Text   = "<p></p>";

            // TODO: OmarS need to get rid of this
            isDHTMLEdit = true;

            editControl.SetLanguage(CultureInfo.CurrentUICulture.Name);
            editControl.SetTextDirection(requestPage.ReadingDirection);

            if (!requestPage.SiteConfig.EnableCrossposts)
            {
                gridCrossposts.Visible = false;
                labelCrosspost.Visible = false;
            }

            if (!SiteSecurity.IsValidContributor())
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            CrosspostInfoCollection crosspostSiteInfo = new CrosspostInfoCollection();

            if (!IsPostBack)
            {
                foreach (CrosspostSite site in requestPage.SiteConfig.CrosspostSites)
                {
                    CrosspostInfo ci = new CrosspostInfo(site);
                    ci.TrackingUrlBase = SiteUtilities.GetCrosspostTrackingUrlBase(requestPage.SiteConfig);
                    crosspostSiteInfo.Add(ci);
                }

                // set up categories
                foreach (CategoryCacheEntry category in requestPage.DataService.GetCategories())
                {
                    this.categoryList.Items.Add(category.Name);
                }


                // get the cultures
                CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

                // setup temp store for listitem items, for sorting
                List <ListItem> cultureList = new List <ListItem>(cultures.Length);

                foreach (CultureInfo ci in cultures)
                {
                    string langName = (ci.NativeName != ci.EnglishName) ? ci.NativeName + " / " + ci.EnglishName : ci.NativeName;

                    if (langName.Length > 55)
                    {
                        langName = langName.Substring(0, 55) + "...";
                    }

                    cultureList.Add(new ListItem(langName, ci.Name));
                }

                // setup the sort culture
                string rssCulture = requestPage.SiteConfig.RssLanguage;

                CultureInfo sortCulture;

                try
                {
                    sortCulture = (rssCulture != null && rssCulture.Length > 0 ? new CultureInfo(rssCulture) : CultureInfo.CurrentCulture);
                }
                catch (ArgumentException)
                {
                    // default to the culture of the server
                    sortCulture = CultureInfo.CurrentCulture;
                }

                // sort the list
                cultureList.Sort(delegate(ListItem x, ListItem y)
                {
                    // actual comparison
                    return(String.Compare(x.Text, y.Text, true, sortCulture));
                });

                // add to the languages listbox
                ListItem[] cultureListItems = cultureList.ToArray();

                listLanguages.Items.AddRange(cultureListItems);

                listLanguages.SelectedValue = "";

                if (requestPage != null && requestPage.WeblogEntryId != "")
                {
                    Session["newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer"] = Request.UrlReferrer;
                    Entry entry = requestPage.DataService.GetEntryForEdit(requestPage.WeblogEntryId);

                    if (entry != null)
                    {
                        CurrentEntry       = entry;
                        entryTitle.Text    = entry.Title;
                        entryAbstract.Text = entry.Description;

                        textDate.SelectedDate = entry.CreatedLocalTime;

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

                        foreach (string s in entry.GetSplitCategories())
                        {
                            categoryList.Items.FindByText(s).Selected = true;
                        }

                        this.checkBoxAllowComments.Checked = entry.AllowComments;
                        this.checkBoxPublish.Checked       = entry.IsPublic;
                        this.checkBoxSyndicated.Checked    = entry.Syndicated;

                        // GeoRSS.
                        this.txtLat.Text  = String.Format(CultureInfo.InvariantCulture, "{0}", entry.Latitude);
                        this.txtLong.Text = String.Format(CultureInfo.InvariantCulture, "{0}", entry.Longitude);

                        if (entry.Attachments.Count > 0)
                        {
                            foreach (Attachment enclosure in entry.Attachments)
                            {
                                enclosure.Url = SiteUtilities.GetEnclosureLinkUrl(requestPage.SiteConfig, entry.EntryId, enclosure);
                            }

                            this.enclosureUpload.Visible    = false;
                            this.buttonRemove.Visible       = true;
                            this.labelEnclosureName.Visible = true;
                            this.labelEnclosureName.Text    = entry.Attachments[0].Name;
                        }

                        listLanguages.SelectedValue = entry.Language == null ? "" : entry.Language;

                        // merge the crosspost config with the crosspost data
                        foreach (CrosspostInfo cpi in crosspostSiteInfo)
                        {
                            foreach (Crosspost cp in entry.Crossposts)
                            {
                                if (cp.ProfileName == cpi.Site.ProfileName)
                                {
                                    cpi.IsAlreadyPosted = true;
                                    cpi.TargetEntryId   = cp.TargetEntryId;
                                    cpi.Categories      = cp.Categories;
                                    break;
                                }
                            }
                        }
                        // if the entry is not public yet but opened for editing, then we can setup autosave.
                        // (If the entry was already published publically and then autosave was used, the
                        // entry's status would change to non-public and then no longer be accessible!)
                        if (requestPage.SiteConfig.EnableAutoSave && !entry.IsPublic)
                        {
                            SetupAutoSave();
                        }

                        if (requestPage.SiteConfig.EnableGoogleMaps)
                        {
                            AddGoogleMapsApi();
                        }
                    }
                }
                else // This is a brand new entry, so setup the AutoSave script if it's enabled.
                {
                    if (requestPage.SiteConfig.EnableAutoSave)
                    {
                        SetupAutoSave();
                    }

                    if (requestPage.SiteConfig.EnableGoogleMaps)
                    {
                        AddGoogleMapsApi();
                    }

                    txtLat.Text  = String.Format(CultureInfo.InvariantCulture, "{0}", siteConfig.DefaultLatitude);
                    txtLong.Text = String.Format(CultureInfo.InvariantCulture, "{0}", siteConfig.DefaultLongitude);
                }

                gridCrossposts.DataSource = crosspostSiteInfo;
                DataBind();
            }
        }
        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);
                }
            }
        }
        protected void buttonSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                // There were validation errors, save client states.
                CleanGravatar();
                CleanAutoExpire();
                CleanHtmlComments();
                CleanGeoRss();
                return;
            }

            SharedBasePage requestPage = Page as SharedBasePage;
            SiteConfig     siteConfig  = requestPage.SiteConfig;

            siteConfig.Contact             = textContact.Text;
            siteConfig.Copyright           = textCopyright.Text;
            siteConfig.FrontPageCategory   = textFrontPageCategory.Text;
            siteConfig.FrontPageDayCount   = int.Parse(textFrontPageDayCount.Text);
            siteConfig.FrontPageEntryCount = int.Parse(textFrontPageEntryCount.Text);
            siteConfig.EntriesPerPage      = int.Parse(textEntriesPerPage.Text);
            try
            {
                siteConfig.ContentLookaheadDays = int.Parse(textContentLookaheadDays.Text);
            }
            catch (FormatException)
            {
                siteConfig.ContentLookaheadDays = 0;
            }
            siteConfig.RssDayCount               = int.Parse(textMainMaxDaysInRss.Text);
            siteConfig.RssMainEntryCount         = int.Parse(textMainMaxEntriesInRss.Text);
            siteConfig.RssEntryCount             = int.Parse(textOtherMaxEntriesInRss.Text);
            siteConfig.AlwaysIncludeContentInRSS = checkAlwaysIncludeContentInRSS.Checked;
            siteConfig.EnableRssItemFooters      = checkEnableRSSItemFooter.Checked;
            siteConfig.RssItemFooter             = textRSSItemFooter.Text;
            siteConfig.RSSEndPointRewrite        = txtRSSEndPointRewrite.Text;
            siteConfig.EnablePop3        = checkPop3Enabled.Checked;
            siteConfig.Pop3Interval      = int.Parse(textPop3Interval.Text);
            siteConfig.Pop3Server        = textPop3Server.Text;
            siteConfig.Pop3SubjectPrefix = textPop3SubjectPrefix.Text;
            siteConfig.Pop3Username      = textPop3Username.Text;
            if (textPop3Password.Text.Length > 0 &&
                textPop3Password.Text != passwordPlaceHolder)
            {
                siteConfig.Pop3Password = textPop3Password.Text;
            }
            siteConfig.Pop3DeleteAllMessages = mailDeletionAll.Checked;
            siteConfig.Pop3LogIgnoredEmails  = logIgnoredEmails.Checked;
            siteConfig.EnableXSSUpstream     = checkXssEnabled.Checked;
            siteConfig.XSSUpstreamEndpoint   = textXssEndpoint.Text;
            siteConfig.XSSUpstreamInterval   = int.Parse(textXssInterval.Text);
            if (textXssPassword.Text.Length > 0 &&
                textXssPassword.Text != passwordPlaceHolder)
            {
                siteConfig.XSSUpstreamPassword = textXssPassword.Text;
            }
            siteConfig.XSSUpstreamUsername = textXssUsername.Text;
            siteConfig.XSSRSSFilename      = textXssRssFilename.Text;

            siteConfig.Root                                   = textRoot.Text;
            siteConfig.SmtpServer                             = textSmtpServer.Text;
            siteConfig.SmtpPort                               = int.Parse(textSmtpPort.Text);
            siteConfig.UseSSLForSMTP                          = checkUseSSLForSMTP.Checked;
            siteConfig.NotificationEMailAddress               = textNotificationEmailAddress.Text;
            siteConfig.SendCommentsByEmail                    = checkComments.Checked;
            siteConfig.EnableCoComment                        = checkEnableCoComment.Checked;
            siteConfig.SendPingbacksByEmail                   = checkPingbacks.Checked;
            siteConfig.SendReferralsByEmail                   = checkReferrals.Checked;
            siteConfig.SendTrackbacksByEmail                  = checkTrackbacks.Checked;
            siteConfig.SendPostsByEmail                       = checkPosts.Checked;
            siteConfig.EnableAutoPingback                     = checkEnableAutoPingback.Checked;
            siteConfig.EnableBloggerApi                       = checkEnableBloggerApi.Checked;
            siteConfig.EnableComments                         = checkEnableComments.Checked;
            siteConfig.EnableCommentApi                       = checkEnableCommentApi.Checked;
            siteConfig.ShowCommentsWhenViewingEntry           = checkShowCommentsWhenViewingEntry.Checked;
            siteConfig.EnableConfigEditService                = checkEnableConfigEditService.Checked;
            siteConfig.EnableEditService                      = checkEnableEditService.Checked;
            siteConfig.EnableAutoSave                         = checkEnableAutoSave.Checked;
            siteConfig.EnableTrackbackService                 = checkEnableTrackbackService.Checked;
            siteConfig.EnablePingbackService                  = checkEnablePingbackService.Checked;
            siteConfig.EnableClickThrough                     = checkEnableClickThrough.Checked;
            siteConfig.EnableAggregatorBugging                = checkEnableAggregatorBugging.Checked;
            siteConfig.Subtitle                               = textSubtitle.Text;
            siteConfig.Title                                  = textTitle.Text;
            siteConfig.ShowCommentCount                       = checkShowCommentCounters.Checked;
            siteConfig.Pop3InlineAttachedPictures             = checkPop3InlineAttachedPictures.Checked;
            siteConfig.Pop3InlinedAttachedPicturesThumbHeight = int.Parse(textPop3AttachedPicturesPictureThumbnailHeight.Text);
            siteConfig.ShowItemDescriptionInAggregatedViews   = checkShowItemDescriptionInAggregatedViews.Checked;
            siteConfig.EnableStartPageCaching                 = checkEnableStartPageCaching.Checked;
            siteConfig.EnableBlogrollDescription              = checkEnableBlogrollDescription.Checked;
            siteConfig.EnableUrlRewriting                     = checkEnableUrlRewriting.Checked;
            siteConfig.DisplayTimeZoneIndex                   = Convert.ToInt32(listTimeZones.SelectedValue);
            siteConfig.AdjustDisplayTimeZone                  = !checkUseUTC.Checked;
            siteConfig.EntryTitleAsLink                       = checkEntryTitleAsLink.Checked;
            siteConfig.EnableCrossposts                       = checkEnableCrosspost.Checked;
            if (textPassword.Text.Length > 0 &&
                textPassword.Text != passwordPlaceHolder)
            {
                SiteSecurity.SetPassword(requestPage.User.Identity.Name, textPassword.Text);
            }
            siteConfig.CategoryAllEntries = checkCategoryAllEntries.Checked;
            requestPage.UserTheme         = siteConfig.Theme = listThemes.SelectedValue;

            siteConfig.ReferralUrlBlackList       = textReferralBlacklist.Text.TrimEnd(';');
            siteConfig.EnableReferralUrlBlackList = checkReferralUrlBlacklist.Checked;
            siteConfig.EnableCaptcha = checkCaptchaEnabled.Checked;
            siteConfig.EnableReferralUrlBlackList404s = checkReferralBlacklist404s.Checked;
            siteConfig.ChannelImageUrl            = textRSSChannelImage.Text;
            siteConfig.EnableTitlePermaLink       = checkEnableTitlePermaLink.Checked;
            siteConfig.EnableTitlePermaLinkUnique = checkEnableTitlePermaLinkUnique.Checked;
            siteConfig.EnableTitlePermaLinkSpaces = checkEnableTitlePermaLinkSpaces.Checked;
            siteConfig.EncryptLoginPassword       = checkEnableEncryptLoginPassword.Checked;
            siteConfig.EnableSmtpAuthentication   = checkEnableSmtpAuthentication.Checked;
            siteConfig.SmtpUserName = textSmtpUsername.Text;
            if (textSmtpPassword.Text.Length > 0 &&
                textSmtpPassword.Text != passwordPlaceHolder)
            {
                siteConfig.SmtpPassword = textSmtpPassword.Text;
            }
            siteConfig.RssLanguage           = textRssLanguage.Text;
            siteConfig.EnableSearchHighlight = checkEnableSearchHighlight.Checked;
            siteConfig.EnableEntryReferrals  = checkEnableEntryReferral.Checked;

            siteConfig.FeedBurnerName = textFeedBurnerName.Text.Trim();
            siteConfig.UseFeedSchemeForSyndication = checkUseFeedScheme.Checked;
            siteConfig.LogBlockedReferrals         = checkLogBlockedReferrals.Checked;
            siteConfig.EnableSpamBlockingService   = checkSpamBlockingEnabled.Checked;
            siteConfig.SpamBlockingServiceApiKey   = textSpamBlockingApiKey.Text;
            siteConfig.EnableSpamModeration        = (optionSpamHandling.SelectedValue != SPAM_OPTION_DELETE);
            siteConfig.EnableCommentDays           = checkEnableCommentDays.Checked;
            siteConfig.HtmlTidyContent             = checkAttemptToHtmlTidyContent.Checked;
            siteConfig.ResolveCommenterIP          = checkResolveCommenterIP.Checked;

            siteConfig.TitlePermalinkSpaceReplacement = dropDownTitlePermalinkReplacementCharacter.SelectedValue;

            if (checkEnableCommentDays.Checked)
            {
                try
                {
                    int days = Convert.ToInt32(textDaysCommentsAllowed.Text);
                    if (days > 0)
                    {
                        siteConfig.DaysCommentsAllowed = days;
                    }
                }
                catch (FormatException)
                {
                    siteConfig.DaysCommentsAllowed = 60;
                }
            }
            else
            {
                siteConfig.DaysCommentsAllowed = 60;
            }

            // comments approval
            siteConfig.CommentsRequireApproval = checkCommentsRequireApproval.Checked;

            // removed the ability to edit the html tags, which are allowed for now
            foreach (ListItem li in checkBoxListAllowedTags.Items)
            {
                ValidTag tag = siteConfig.AllowedTags[li.Value];
                if (tag != null)
                {
                    tag.IsAllowed = li.Selected;
                }
            }

            // comments allow html
            siteConfig.CommentsAllowHtml = checkAllowHtml.Checked;

            // comments allow Gravatar and alt path
            GravatarPopulateConfig();

            // supress email address display
            siteConfig.SupressEmailAddressDisplay = checkDisableEmailDisplay.Checked;

            // enable daily report email
            siteConfig.EnableDailyReportEmail = checkDailyReport.Checked;

            PingServiceCollection savePingServices = new PingServiceCollection();

            foreach (PingService pingService in PingServiceCollection)
            {
                if (checkBoxListPingServices.Items.FindByValue(pingService.Endpoint).Selected)
                {
                    savePingServices.Add(pingService);
                }
            }

            siteConfig.PingServices     = savePingServices;
            siteConfig.EntryEditControl = drpEntryEditControl.SelectedValue;

            // GeoRSS stuff.
            siteConfig.EnableGeoRss = checkEnableGeoRss.Checked;
            if (checkEnableGeoRss.Checked)
            {
                siteConfig.EnableDefaultLatLongForNonGeoCodedPosts = checkEnableDefaultLatLongForNonGeoCodedPosts.Checked;
                if (checkEnableDefaultLatLongForNonGeoCodedPosts.Checked)
                {
                    double latitude;
                    if (double.TryParse(textDefaultLatitude.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out latitude))
                    {
                        siteConfig.DefaultLatitude = latitude;
                    }

                    double longitude;
                    if (double.TryParse(textDefaultLongitude.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out longitude))
                    {
                        siteConfig.DefaultLongitude = longitude;
                    }
                }

                siteConfig.EnableGoogleMaps = checkEnableGoogleMaps.Checked;
                if (checkEnableGoogleMaps.Checked)
                {
                    siteConfig.GoogleMapsApiKey = textGoogleMapsApi.Text;
                }
            }

            // open id stuff
            siteConfig.AllowOpenIdAdmin        = chkAllowOpenIdAdmin.Checked;
            siteConfig.AllowOpenIdComments     = chkAllowOpenIdCommenter.Checked;
            siteConfig.BypassSpamOpenIdComment = chkBypassSpamOpenIdCommenter.Checked;

            siteConfig.AMPPagesEnabled = checkAmpEnabled.Checked;

            SiteConfig.Save(siteConfig);

            SeoMetaTags smt = new SeoMetaTags().GetMetaTags();

            smt.MetaDescription = txtMetaDescription.Text;
            smt.MetaKeywords    = txtMetaKeywords.Text;
            smt.TwitterCard     = txtTwitterCard.Text;
            smt.TwitterSite     = txtTwitterSite.Text;
            smt.TwitterCreator  = txtTwitterCreator.Text;
            smt.TwitterImage    = txtTwitterImage.Text;
            smt.FaceBookAdmins  = txtFaceBookAdmins.Text;
            smt.FaceBookAppID   = txtFaceBookAppID.Text;

            SeoMetaTags.Save(smt);

            if (siteConfig.EnableReferralUrlBlackList && siteConfig.ReferralUrlBlackList.Length != 0)
            {
                ReferralBlackListFactory.AddBlacklist(new ReferralUrlBlacklist(), siteConfig.ReferralUrlBlackList);
            }
            else
            {
                ReferralBlackListFactory.RemoveBlacklist(typeof(ReferralUrlBlacklist));
            }

            requestPage.Redirect(Page.Request.Url.AbsoluteUri);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (SiteSecurity.IsInRole("admin") == false)
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            ID = "EditConfigBox";

            SharedBasePage requestPage = Page as SharedBasePage;
            SiteConfig     siteConfig  = requestPage.SiteConfig;

            if (!IsPostBack)
            {
                textContact.Text                       = siteConfig.Contact;
                textCopyright.Text                     = siteConfig.Copyright;
                textPassword.Text                      = passwordPlaceHolder;
                textConfirmPassword.Text               = passwordPlaceHolder;
                textFrontPageCategory.Text             = siteConfig.FrontPageCategory;
                textFrontPageDayCount.Text             = siteConfig.FrontPageDayCount.ToString();
                textFrontPageEntryCount.Text           = siteConfig.FrontPageEntryCount.ToString();
                textEntriesPerPage.Text                = siteConfig.EntriesPerPage.ToString();
                textContentLookaheadDays.Text          = siteConfig.ContentLookaheadDays.ToString();
                textMainMaxDaysInRss.Text              = siteConfig.RssDayCount.ToString();
                textMainMaxEntriesInRss.Text           = siteConfig.RssMainEntryCount.ToString();
                textOtherMaxEntriesInRss.Text          = siteConfig.RssEntryCount.ToString();
                checkAlwaysIncludeContentInRSS.Checked = siteConfig.AlwaysIncludeContentInRSS;
                checkEnableRSSItemFooter.Checked       = siteConfig.EnableRssItemFooters;
                textRSSItemFooter.Text                 = siteConfig.RssItemFooter;
                txtRSSEndPointRewrite.Text             = siteConfig.RSSEndPointRewrite;
                checkPop3Enabled.Checked               = siteConfig.EnablePop3;
                textPop3Interval.Text                  = siteConfig.Pop3Interval.ToString();
                textPop3Server.Text                    = siteConfig.Pop3Server;
                textPop3SubjectPrefix.Text             = siteConfig.Pop3SubjectPrefix;
                textPop3Username.Text                  = siteConfig.Pop3Username;
                textPop3Password.Text                  = passwordPlaceHolder;
                textPop3PasswordRepeat.Text            = passwordPlaceHolder;
                textRoot.Text                                       = siteConfig.Root;
                textSmtpServer.Text                                 = siteConfig.SmtpServer;
                textSmtpPort.Text                                   = siteConfig.SmtpPort.ToString();
                checkUseSSLForSMTP.Checked                          = siteConfig.UseSSLForSMTP;
                textNotificationEmailAddress.Text                   = siteConfig.NotificationEMailAddress;
                textSubtitle.Text                                   = siteConfig.Subtitle;
                textSmtpServer.Text                                 = siteConfig.SmtpServer;
                checkEnableCoComment.Checked                        = siteConfig.EnableCoComment;
                checkComments.Checked                               = siteConfig.SendCommentsByEmail;
                checkPingbacks.Checked                              = siteConfig.SendPingbacksByEmail;
                checkReferrals.Checked                              = siteConfig.SendReferralsByEmail;
                checkPosts.Checked                                  = siteConfig.SendPostsByEmail;
                checkTrackbacks.Checked                             = siteConfig.SendTrackbacksByEmail;
                checkShowCommentCounters.Checked                    = siteConfig.ShowCommentCount;
                checkEnableAutoPingback.Checked                     = siteConfig.EnableAutoPingback;
                checkEnableBloggerApi.Checked                       = siteConfig.EnableBloggerApi;
                checkEnableComments.Checked                         = siteConfig.EnableComments;
                checkEnableCommentApi.Checked                       = siteConfig.EnableCommentApi;
                checkShowCommentsWhenViewingEntry.Checked           = siteConfig.ShowCommentsWhenViewingEntry;
                checkEnableConfigEditService.Checked                = siteConfig.EnableConfigEditService;
                checkEnableEditService.Checked                      = siteConfig.EnableEditService;
                checkEnableAutoSave.Checked                         = siteConfig.EnableAutoSave;
                checkEnablePingbackService.Checked                  = siteConfig.EnablePingbackService;
                checkEnableTrackbackService.Checked                 = siteConfig.EnableTrackbackService;
                checkEnableClickThrough.Checked                     = siteConfig.EnableClickThrough;
                checkEnableAggregatorBugging.Checked                = siteConfig.EnableAggregatorBugging;
                checkXssEnabled.Checked                             = siteConfig.EnableXSSUpstream;
                textXssEndpoint.Text                                = siteConfig.XSSUpstreamEndpoint;
                textXssInterval.Text                                = siteConfig.XSSUpstreamInterval.ToString();
                textXssPassword.Text                                = passwordPlaceHolder;
                textXssPasswordRepeat.Text                          = passwordPlaceHolder;
                textXssUsername.Text                                = siteConfig.XSSUpstreamUsername;
                textXssRssFilename.Text                             = siteConfig.XSSRSSFilename;
                checkPop3InlineAttachedPictures.Checked             = siteConfig.Pop3InlineAttachedPictures;
                textPop3AttachedPicturesPictureThumbnailHeight.Text = siteConfig.Pop3InlinedAttachedPicturesThumbHeight.ToString();
                mailDeletionAll.Checked                             = siteConfig.Pop3DeleteAllMessages;
                mailDeletionProcessed.Checked                       = !siteConfig.Pop3DeleteAllMessages;
                logIgnoredEmails.Checked                            = siteConfig.Pop3LogIgnoredEmails;
                checkShowItemDescriptionInAggregatedViews.Checked   = siteConfig.ShowItemDescriptionInAggregatedViews;
                checkEnableStartPageCaching.Checked                 = siteConfig.EnableStartPageCaching;
                checkEnableBlogrollDescription.Checked              = siteConfig.EnableBlogrollDescription;
                checkEntryTitleAsLink.Checked                       = siteConfig.EntryTitleAsLink;
                checkEnableUrlRewriting.Checked                     = siteConfig.EnableUrlRewriting;
                checkEnableCrosspost.Checked                        = siteConfig.EnableCrossposts;
                checkCategoryAllEntries.Checked                     = siteConfig.CategoryAllEntries;
                checkReferralUrlBlacklist.Checked                   = siteConfig.EnableReferralUrlBlackList;
                textReferralBlacklist.Text                          = siteConfig.ReferralUrlBlackList;
                checkCaptchaEnabled.Checked                         = siteConfig.EnableCaptcha;
                checkReferralBlacklist404s.Checked                  = siteConfig.EnableReferralUrlBlackList404s;
                textRSSChannelImage.Text                            = siteConfig.ChannelImageUrl;
                checkEnableTitlePermaLink.Checked                   = siteConfig.EnableTitlePermaLink;
                checkEnableTitlePermaLinkUnique.Checked             = siteConfig.EnableTitlePermaLinkUnique;
                checkEnableTitlePermaLinkSpaces.Checked             = siteConfig.EnableTitlePermaLinkSpaces;
                checkEnableEncryptLoginPassword.Checked             = siteConfig.EncryptLoginPassword;
                checkEnableSmtpAuthentication.Checked               = siteConfig.EnableSmtpAuthentication;
                textSmtpUsername.Text                               = siteConfig.SmtpUserName;
                textSmtpPassword.Text                               = passwordPlaceHolder;
                textRssLanguage.Text                                = siteConfig.RssLanguage;
                checkEnableSearchHighlight.Checked                  = siteConfig.EnableSearchHighlight;
                checkEnableEntryReferral.Checked                    = siteConfig.EnableEntryReferrals;
                textFeedBurnerName.Text                             = siteConfig.FeedBurnerName;
                checkUseFeedScheme.Checked                          = siteConfig.UseFeedSchemeForSyndication;
                checkLogBlockedReferrals.Checked                    = siteConfig.LogBlockedReferrals;

                //populate the title space replacement options
                dropDownTitlePermalinkReplacementCharacter.Items.Clear();//in casee someone adds them in the ascx
                foreach (string s in TitleMapperModule.TitlePermalinkSpaceReplacementOptions)
                {
                    dropDownTitlePermalinkReplacementCharacter.Items.Add(s);
                }
                dropDownTitlePermalinkReplacementCharacter.SelectedValue = siteConfig.TitlePermalinkSpaceReplacement;

                checkSpamBlockingEnabled.Checked = siteConfig.EnableSpamBlockingService;
                textSpamBlockingApiKey.Text      = siteConfig.SpamBlockingServiceApiKey;
                optionSpamHandling.SelectedValue = siteConfig.EnableSpamModeration ? SPAM_OPTION_SAVE : SPAM_OPTION_DELETE;

                // setup the checkbox list to select which tags to allow
                checkBoxListAllowedTags.DataSource     = siteConfig.AllowedTags;
                checkBoxListAllowedTags.DataTextField  = "Name";
                checkBoxListAllowedTags.DataValueField = "Name";

                // enable comment moderation
                checkCommentsRequireApproval.Checked = siteConfig.CommentsRequireApproval;

                // allow html and comments
                checkAllowHtml.Checked = siteConfig.CommentsAllowHtml;

                // populate from config - Gravatar
                GravatarPopulateForm();

                // supress email address display
                checkDisableEmailDisplay.Checked = siteConfig.SupressEmailAddressDisplay;

                checkEnableCommentDays.Checked = siteConfig.EnableCommentDays;

                checkAttemptToHtmlTidyContent.Checked = siteConfig.HtmlTidyContent;
                checkResolveCommenterIP.Checked       = siteConfig.ResolveCommenterIP;

                //if ( siteConfig.EnableCommentDays )
                //{
                if (siteConfig.DaysCommentsAllowed > 0)
                {
                    textDaysCommentsAllowed.Text = siteConfig.DaysCommentsAllowed.ToString();
                }
                //}
                //else
                //{
                //	textDaysCommentsAllowed.Text = null;
                //}

                // supress email address display
                checkDisableEmailDisplay.Checked = siteConfig.SupressEmailAddressDisplay;

                checkEnableCommentDays.Checked = siteConfig.EnableCommentDays;

                //if ( siteConfig.EnableCommentDays )
                //{
                if (siteConfig.DaysCommentsAllowed > 0)
                {
                    textDaysCommentsAllowed.Text = siteConfig.DaysCommentsAllowed.ToString();
                }
                //}
                //else
                //{
                //	textDaysCommentsAllowed.Text = null;
                //}

                // email daily report
                checkDailyReport.Text    = resmgr.GetString("text_daily_activity_report");
                checkDailyReport.Checked = siteConfig.EnableDailyReportEmail;

                WindowsTimeZoneCollection timeZones = WindowsTimeZone.TimeZones;
                foreach (WindowsTimeZone tz in timeZones)
                {
                    listTimeZones.Items.Add(new ListItem(tz.DisplayName, tz.ZoneIndex.ToString()));
                }
                listTimeZones.SelectedValue = siteConfig.DisplayTimeZoneIndex.ToString();
                checkUseUTC.Checked         = !siteConfig.AdjustDisplayTimeZone;

                //FIX: hardcoded path
                ThemeDictionary themes = BlogTheme.Load(SiteUtilities.MapPath("themes"));
                foreach (BlogTheme theme in themes.Values)
                {
                    // setting the selected item like this instead of
                    // using    listThemes.SelectedValue = siteConfig.Theme;
                    // prevents the page from breaking.

                    ListItem item = new ListItem(theme.Title, theme.Name);
                    if (item.Value == siteConfig.Theme)
                    {
                        item.Selected = true;
                    }
                    listThemes.Items.Add(item);
                }

                textTitle.Text = siteConfig.Title;

                checkBoxListPingServices.DataSource     = PingServiceCollection;
                checkBoxListPingServices.DataTextField  = "Hyperlink";
                checkBoxListPingServices.DataValueField = "Endpoint";

                drpEntryEditControl.Items.Clear();
                foreach (string potentialAssembly in Directory.GetFiles(HttpRuntime.BinDirectory, "*.dll"))
                {
                    try
                    {
                        Assembly a = Assembly.LoadFrom(potentialAssembly);
                        foreach (Type potentialType in a.GetTypes())
                        {
                            if (potentialType.BaseType == typeof(EditControlAdapter))
                            {
                                drpEntryEditControl.Items.Add(new ListItem(potentialType.Name, potentialType.AssemblyQualifiedName));
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //swallow
                    }
                }

                //Reasonable default
                if (string.IsNullOrEmpty(siteConfig.EntryEditControl))
                {
                    siteConfig.EntryEditControl = typeof(TinyMCEAdapter).AssemblyQualifiedName;
                }
                DataBind();

                ListItem li = drpEntryEditControl.Items.FindByText(siteConfig.EntryEditControl);
                if (li != null)
                {
                    li.Selected = true;
                }
                else
                {
                    drpEntryEditControl.SelectedIndex = 0;
                }

                foreach (PingService ps in siteConfig.PingServices)
                {
                    checkBoxListPingServices.Items.FindByValue(ps.Endpoint).Selected = true;
                }

                foreach (ValidTag tag in siteConfig.AllowedTags)
                {
                    checkBoxListAllowedTags.Items.FindByValue(tag.Name).Selected = tag.IsAllowed;
                }

                //check for Smtp permission
                if (SecurityManager.IsGranted(new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort)))
                {
                    phSmtpTrustWarning.Visible = false;
                }
                else
                {
                    phSmtpTrustWarning.Visible = true;
                }

                //check for Socket permission
                SocketPermission sp;
                if (String.IsNullOrEmpty(textPop3Server.Text))
                {
                    sp = new SocketPermission(PermissionState.Unrestricted);
                }
                else
                {
                    sp = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, textPop3Server.Text, 110);
                }

                if (SecurityManager.IsGranted(sp))
                {
                    phPop3TrustWarning.Visible = false;
                }
                else
                {
                    phPop3TrustWarning.Visible = true;
                }

                // georss stuff
                checkEnableGeoRss.Checked     = siteConfig.EnableGeoRss;
                textGoogleMapsApi.Text        = siteConfig.GoogleMapsApiKey;
                textDefaultLatitude.Text      = siteConfig.DefaultLatitude.ToString(CultureInfo.InvariantCulture);
                textDefaultLongitude.Text     = siteConfig.DefaultLongitude.ToString(CultureInfo.InvariantCulture);
                checkEnableGoogleMaps.Checked = siteConfig.EnableGoogleMaps;
                checkEnableDefaultLatLongForNonGeoCodedPosts.Checked = siteConfig.EnableDefaultLatLongForNonGeoCodedPosts;

                // OpenId
                chkAllowOpenIdAdmin.Checked          = siteConfig.AllowOpenIdAdmin;
                chkAllowOpenIdCommenter.Checked      = siteConfig.AllowOpenIdComments;
                chkBypassSpamOpenIdCommenter.Checked = siteConfig.BypassSpamOpenIdComment;


                SeoMetaTags smt = new SeoMetaTags().GetMetaTags();

                txtMetaDescription.Text = smt.MetaDescription;
                txtMetaKeywords.Text    = smt.MetaKeywords;
                txtTwitterCard.Text     = smt.TwitterCard;
                txtTwitterSite.Text     = smt.TwitterSite;
                txtTwitterCreator.Text  = smt.TwitterCreator;
                txtTwitterImage.Text    = smt.TwitterImage;
                txtFaceBookAdmins.Text  = smt.FaceBookAdmins;
                txtFaceBookAppID.Text   = smt.FaceBookAppID;

                checkAmpEnabled.Checked = siteConfig.AMPPagesEnabled;
            } // end if !postback

            //enable list controls that may have been enabled client-side
            //in 2.0 if they are not enable we won't get there postback data
            checkBoxListAllowedTags.Enabled = true;
            dropGravatarRating.Enabled      = true;
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            siteConfig = SiteConfig.GetSiteConfig();

            resmgr = ((System.Resources.ResourceManager)ApplicationResourceTable.Get());

            //set the current page <li> tag to here
            string filePath = this.Request.FilePath;

            if (filePath.EndsWith("EditCrossPostSites.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                editCrossPostSites.Attributes["class"]  = "here";
                hyperLinkEditCrossPostSites.NavigateUrl = "";
            }
            else if (filePath.EndsWith("EditNavigatorLinks.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                editNavigatorLinks.Attributes["class"]  = "here";
                hyperLinkEditNavigatorLinks.NavigateUrl = "";
            }
            else if (filePath.EndsWith("EditBlogRoll.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                editBlogRoll.Attributes["class"]  = "here";
                hyperLinkEditBlogRoll.NavigateUrl = "";
            }
            else if (filePath.EndsWith("EditContentFilters.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                editContentFilters.Attributes["class"]  = "here";
                hyperLinkEditContentFilters.NavigateUrl = "";
            }
            else if (filePath.EndsWith("EditConfig.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                editConfig.Attributes["class"]  = "here";
                hyperLinkEditConfig.NavigateUrl = "";
            }
            else if (filePath.EndsWith("Referrers.aspx", StringComparison.InvariantCultureIgnoreCase) ||
                     filePath.EndsWith("Eventlog.aspx", StringComparison.InvariantCultureIgnoreCase) ||
                     filePath.EndsWith("AggBugs.aspx", StringComparison.InvariantCultureIgnoreCase) ||
                     filePath.EndsWith("ClickThroughs.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                activity.Attributes["class"]  = "here";
                hyperLinkActivity.NavigateUrl = "";
            }
            else if (filePath.EndsWith("EditEntry.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                editEntry.Attributes["class"]  = "firstHere";
                hyperLinkEditEntry.NavigateUrl = "";
            }
            else if (filePath.EndsWith("EditUser.aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                editUser.Attributes["class"]  = "here";
                hyperLinkEditUser.NavigateUrl = "";
            }

            // The only tab that should be visible for a contributor is the
            // "Add Entry" and "User Settings" tab
            if (SiteSecurity.IsInRole("contributor"))
            {
                this.editConfig.Visible         = false;
                this.editCrossPostSites.Visible = false;
                this.editContentFilters.Visible = false;
                this.editBlogRoll.Visible       = false;
                this.editNavigatorLinks.Visible = false;
                this.activity.Visible           = false;
            }
            DataBind();
        }