using System; using System.Collections.Generic; using System.Web; using System.Collections; using System.Data; using CMS.Blogs; using CMS.CMSHelper; using CMS.GlobalHelper; using CMS.PortalEngine; using CMS.SettingsProvider; using CMS.SiteProvider; using CMS.DocumentEngine; using CMS.UIControls; using CMS.WebAnalytics; using CMS.WorkflowEngine; public partial class CMSModules_Blogs_Controls_BlogCommentEdit : CMSUserControl { #region "Variables" private int mPostDocumentId = 0; private int mCommentId = 0; private string mOkButtonText = null; private string mCommentSavedText = null; private bool mClearFormAfterSave = false; private bool mUseCaptcha = false; private bool mAdvancedMode = false; private bool mEnableSubscriptions = false; private bool mRequireEmails = false; protected string mValidationGroup = null; public event OnBeforeCommentSavedEventHandler OnBeforeCommentSaved; public event OnAfterCommentSavedEventHandler OnAfterCommentSaved; #endregion #region "Public properties" /// /// Post document ID. Set when creating new comment to the post. /// public int PostDocumentId { get { return mPostDocumentId; } set { mPostDocumentId = value; } } /// /// Gets or sets document node ID. /// public int PostNodeId { get; set; } /// /// Gets or sets document culture. /// public string PostCulture { get; set; } /// /// Comment ID. Set when editing existing comment. /// public int CommentId { get { return mCommentId; } set { mCommentId = value; } } /// /// Ok button text. /// public string OkButtonText { get { return mOkButtonText; } set { mOkButtonText = value; } } /// /// Comment saved text. /// public string CommentSavedText { get { return mCommentSavedText; } set { mCommentSavedText = value; } } /// /// Indicates whether form fields should be cleared after data are saved. /// public bool ClearFormAfterSave { get { return mClearFormAfterSave; } set { mClearFormAfterSave = value; } } /// /// Indicates whether security code control should be displayed. /// public bool UseCaptcha { get { return mUseCaptcha; } set { mUseCaptcha = value; } } /// /// Indicates whether advanced mode controls should be displayed. /// public bool AdvancedMode { get { return mAdvancedMode; } set { mAdvancedMode = value; } } /// /// Indicates whether subscription is allowed. /// public bool EnableSubscriptions { get { return mEnableSubscriptions; } set { mEnableSubscriptions = value; } } /// /// Indicates whether e-mail is required. /// public bool RequireEmails { get { return mRequireEmails; } set { mRequireEmails = value; } } /// /// Indicates if buttons should be displayed. /// public bool DisplayButtons { get { return plcButtons.Visible; } set { plcButtons.Visible = value; } } /// /// Validation group of controls. /// public string ValidationGroup { get { if (mValidationGroup == null) { mValidationGroup = "CommentEdit_" + Guid.NewGuid().ToString("N"); } return mValidationGroup; } set { mValidationGroup = value; } } #endregion #region "Private properties" /// /// Indicates whether the control is displayed within the insert mode. /// private bool IsInsertMode { get { // Insert mode if (mPostDocumentId > 0) { return true; } // Edit mode else { return false; } } } /// /// CSS used for the live site mode. /// protected string LiveSiteCss { get { if (CMSContext.ViewMode != ViewModeEnum.LiveSite) { return "BlogBreakLine"; } return null; } } #endregion protected void Page_Load(object sender, EventArgs e) { mOkButtonText = GetString("general.add"); mCommentSavedText = GetString("Blog.CommentEdit.CommentSaved"); // Basic control initialization lblName.Text = GetString("Blog.CommentEdit.lblName"); lblUrl.Text = GetString("Blog.CommentEdit.lblUrl"); lblComments.Text = GetString("Blog.CommentEdit.lblComments"); btnOk.Text = mOkButtonText; // Validators initialization rfvComments.ErrorMessage = GetString("Blog.CommentEdit.CommentEmpty"); rfvName.ErrorMessage = GetString("Blog.CommentEdit.NameEmpty"); revEmailValid.ErrorMessage = GetString("general.correctemailformat"); rfvEmail.ErrorMessage = GetString("blog.commentedit.rfvemail"); rfvEmail.Enabled = RequireEmails; // Show or hide security code control plcCaptcha.Visible = mUseCaptcha; lblApproved.Text = GetString("Blog.CommentEdit.Approved"); lblSpam.Text = GetString("Blog.CommentEdit.Spam"); lblInserted.Text = GetString("Blog.CommentEdit.Inserted"); revEmailValid.ValidationExpression = ValidationHelper.EmailRegExp.ToString(); plcChkSubscribe.Visible = EnableSubscriptions; revEmailValid.ValidationGroup = ValidationGroup; rfvComments.ValidationGroup = ValidationGroup; rfvEmail.ValidationGroup = ValidationGroup; rfvName.ValidationGroup = ValidationGroup; btnOk.ValidationGroup = ValidationGroup; if (!RequestHelper.IsPostBack()) { CurrentUserInfo currentUser = CMSContext.CurrentUser; // New comment if (IsInsertMode) { // Prefill current user fullname if ((currentUser != null) && (!currentUser.IsPublic())) { txtName.Text = currentUser.UserNickName != "" ? currentUser.UserNickName : currentUser.FullName; txtEmail.Text = currentUser.Email; } } // Existing comment else { LoadCommentData(); } // Advaced mode in CMSDesk if (AdvancedMode) { plcAdvancedMode.Visible = true; } } // Ensure information is displayed to the user bool savedRequiresApprove = QueryHelper.GetBoolean("saveda", false); bool saved = QueryHelper.GetBoolean("saved", false); if (saved || savedRequiresApprove) { if (savedRequiresApprove) { CommentSavedText = GetString("blog.comments.requiresmoderationafteraction"); } lblInfo.Text = CommentSavedText; lblInfo.Visible = true; } } /// /// Fill form with the comment data. /// protected void LoadCommentData() { // Get comment info from database BlogCommentInfo bci = BlogCommentInfoProvider.GetBlogCommentInfo(mCommentId); if (bci != null) { txtName.Text = bci.CommentUserName; txtUrl.Text = bci.CommentUrl; txtComments.Text = bci.CommentText; txtEmail.Text = bci.CommentEmail; chkApproved.Checked = bci.CommentApproved; chkSpam.Checked = bci.CommentIsSpam; if ((CMSContext.ViewMode == ViewModeEnum.LiveSite) && (CMSContext.CurrentUser != null)) { lblInsertedDate.Text = CMSContext.ConvertDateTime(bci.CommentDate, this).ToString(); } else { lblInsertedDate.Text = bci.CommentDate.ToString(); } } } protected void btnOk_Click(object sender, EventArgs e) { PerformAction(); } public void PerformAction() { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } if (OnBeforeCommentSaved != null) { OnBeforeCommentSaved(); } BlogCommentInfo bci = null; // Validate form string errorMessage = ValidateForm(); if (errorMessage == "") { // Check flooding when message being inserted through the LiveSite if (IsLiveSite && FloodProtectionHelper.CheckFlooding(CMSContext.CurrentSiteName, CMSContext.CurrentUser)) { lblError.Visible = true; lblError.Text = GetString("General.FloodProtection"); return; } CurrentUserInfo currentUser = CMSContext.CurrentUser; // Create new comment if (IsInsertMode) { bci = new BlogCommentInfo(); bci.CommentDate = DateTime.Now; bci.CommentPostDocumentID = mPostDocumentId; // User IP address bci.CommentInfo.IPAddress = HTTPHelper.UserHostAddress; // User agent bci.CommentInfo.Agent = Request.UserAgent; if (!currentUser.IsPublic()) { bci.CommentUserID = currentUser.UserID; } bci.CommentIsTrackback = false; } // Get existing comment else { bci = BlogCommentInfoProvider.GetBlogCommentInfo(mCommentId); } // Update basic comment properties if (bci != null) { // Add http:// if needed string url = txtUrl.Text.Trim(); if (url != "") { if ((!url.ToLowerCSafe().StartsWithCSafe("http://")) && (!url.ToLowerCSafe().StartsWithCSafe("https://"))) { url = "http://" + url; } } bci.CommentIsSpam = chkSpam.Checked; bci.CommentApproved = chkApproved.Checked; bci.CommentUserName = txtName.Text.Trim(); bci.CommentUrl = url; bci.CommentText = txtComments.Text.Trim(); bci.CommentUrl = bci.CommentUrl.ToLowerCSafe().Replace("javascript", "_javascript"); bci.CommentEmail = txtEmail.Text.Trim(); } if (IsInsertMode) { // Auto approve owner comments if (bci != null) { TreeNode blogNode = BlogHelper.GetParentBlog(bci.CommentPostDocumentID, false); if ((currentUser != null) && (blogNode != null)) { bool isAuthorized = BlogHelper.IsUserAuthorizedToManageComments(blogNode); if (isAuthorized) { bci.CommentApprovedByUserID = blogNode.NodeOwner; bci.CommentApproved = true; } else { // Is blog moderated ? bool moderated = ValidationHelper.GetBoolean(blogNode.GetValue("BlogModerateComments"), false); bci.CommentApprovedByUserID = 0; bci.CommentApproved = !moderated; } } } } // Perform bad words check if (!BadWordInfoProvider.CanUseBadWords(CMSContext.CurrentUser, CMSContext.CurrentSiteName)) { if (bci != null) { // Prepare columns to check Dictionary columns = new Dictionary(); columns.Add("CommentText", 0); columns.Add("CommentUserName", 200); // Perform bad words to check errorMessage = BadWordsHelper.CheckBadWords(bci, columns, "CommentApproved", "CommentApprovedByUserID", bci.CommentText, CMSContext.CurrentUser.UserID, () => { return ValidateComment(bci); }); } } if (errorMessage == string.Empty) { if (bci != null) { if (!ValidateComment(bci)) { // Show error message lblError.Visible = true; lblError.Text = GetString("Blog.CommentEdit.EmptyBadWord"); } else { // Subscribe new subscriber if (chkSubscribe.Checked) { BlogPostSubscriptionInfo bpsi = BlogPostSubscriptionInfoProvider.GetBlogPostSubscriptionInfo(txtEmail.Text, mPostDocumentId); // Check for duplicit subscriptions if ((bpsi == null) || !bpsi.SubscriptionApproved) { bpsi = new BlogPostSubscriptionInfo(); bpsi.SubscriptionEmail = txtEmail.Text; bpsi.SubscriptionPostDocumentID = mPostDocumentId; bpsi.SubscriptionUserID = bci.CommentUserID; BlogPostSubscriptionInfoProvider.Subscribe(bpsi, DateTime.Now, true, true); if (bpsi.SubscriptionApproved) { LogRegistrationActivity(bpsi); } } else { errorMessage = GetString("blog.subscription.emailexists"); } } if (errorMessage == "") { // Save changes to database BlogCommentInfoProvider.SetBlogCommentInfo(bci); if (!bci.CommentApproved) { CommentSavedText = GetString("blog.comments.requiresmoderationafteraction"); } // Inform user lblInfo.Visible = true; lblInfo.Text = CommentSavedText; // Clear form when required if (mClearFormAfterSave) { txtComments.Text = ""; txtUrl.Text = ""; ctrlCaptcha.Value = ""; } LogCommentActivity(bci, PostNodeId, PostCulture); if (OnAfterCommentSaved != null) { OnAfterCommentSaved(bci); } } } } } } if (errorMessage != "") { // Show error message lblError.Visible = true; lblError.Text = errorMessage; } } private static bool ValidateComment(BlogCommentInfo commentInfo) { if ((commentInfo.CommentText != null) && (commentInfo.CommentUserName != null)) { return (commentInfo.CommentText.Trim() != "") && (commentInfo.CommentUserName.Trim() != ""); } return false; } /// /// Logs activity. /// /// Blog comment info /// Document node ID /// Document culture private void LogCommentActivity(BlogCommentInfo bci, int nodeId, string culture) { TreeNode blogPost = DocumentHelper.GetDocument(bci.CommentPostDocumentID, new TreeProvider()); TreeNode blogNode = BlogHelper.GetParentBlog(bci.CommentPostDocumentID, false); string blogName = (blogNode != null) ? blogNode.GetDocumentName() : null; var blogComment = new ActivityBlogComment(bci, blogPost, CMSContext.ActivityEnvironmentVariables); if (blogComment.Data != null) { blogComment.Data.TitleData = blogName; blogComment.Data.ItemDetailID = (blogNode != null ? blogNode.NodeID : 0); blogComment.Data.NodeID = nodeId; blogComment.Data.Culture = culture; blogComment.Log(); } } /// /// Logs registration activity. /// /// Blog subscription info private void LogRegistrationActivity(BlogPostSubscriptionInfo bpsi) { if ((bpsi != null) && (bpsi.SubscriptionPostDocumentID > 0)) { TreeNode blogPost = DocumentHelper.GetDocument(bpsi.SubscriptionPostDocumentID, new TreeProvider()); TreeNode blogNode = BlogHelper.GetParentBlog(bpsi.SubscriptionPostDocumentID, false); string blogName = blogNode != null ? blogNode.GetDocumentName() : null; Activity activity = new ActivitySubscriptionBlogPost(blogName, blogNode, blogPost, bpsi, CMSContext.ActivityEnvironmentVariables); activity.Log(); } } /// /// Validates form. /// protected string ValidateForm() { string errorMessage = new Validator().NotEmpty(txtComments.Text.Trim(), rfvComments.ErrorMessage).NotEmpty(txtName.Text.Trim(), rfvName.ErrorMessage).Result; if ((mUseCaptcha) && (errorMessage == "")) { // Check whether security code is correct if (!ctrlCaptcha.IsValid()) { errorMessage = ctrlCaptcha.ValidationError; } } // Check if e-mail address is required if ((errorMessage == "") && (RequireEmails || chkSubscribe.Checked)) { errorMessage = new Validator().NotEmpty(txtEmail.Text, GetString("blog.subscription.noemail")).Result; } // Check e-mail address format if some e-mail adrress is specified if ((errorMessage == "") && !String.IsNullOrEmpty(txtEmail.Text)) { errorMessage = new Validator().IsEmail(txtEmail.Text, GetString("general.correctemailformat")).Result; } return errorMessage; } }