protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Initialize resource strings rqfWordExpression.ErrorMessage = GetString("general.requiresvalue"); if (badWordId > 0) { badWordObj = BadWordInfoProvider.GetBadWordInfo(badWordId); // Set edited object EditedObject = badWordObj; if (badWordObj != null) { // Fill editing form if (!RequestHelper.IsPostBack()) { LoadData(badWordObj); // Show that the badWord was created or updated successfully if (QueryHelper.GetString("saved", string.Empty) == "1") { ShowChangesSaved(); } } else { // Set selected action SetSelectedAction(badWordObj); } } } else { PageTitle.TitleText = GetString("BadWords_Edit.NewItemCaption"); // Initialize breadcrumbs List <BreadcrumbItem> breadCrumbItems = new List <BreadcrumbItem>(); breadCrumbItems.Add(new BreadcrumbItem { Text = GetString("badwords_edit.itemlistlink"), RedirectUrl = "~/CMSModules/BadWords/BadWords_List.aspx", Target = "_self", }); breadCrumbItems.Add(new BreadcrumbItem { Text = GetString("badwords_list.newitemcaption"), }); PageBreadcrumbs.Items = breadCrumbItems; SetSelectedAction(null); } // Enable / disable actions (depending on inheritance) SelectBadWordActionControl.Enabled = !chkInheritAction.Checked; txtWordReplacement.Enabled = !chkInheritReplacement.Checked; // Show / hide replacement textbox depending on action plcReplacement.Visible = ((BadWordActionEnum)Enum.Parse(typeof(BadWordActionEnum), SelectBadWordActionControl.Value.ToString())) == BadWordActionEnum.Replace; }
/// <summary> /// Gets and updates the first single bad word matching the condition. Called when the "Get and update bad word" button is pressed. /// Expects the CreateBadWord method to be run first. /// </summary> private bool GetAndUpdateBadWord() { // Prepare the parameters string where = "[WordExpression] = 'testbadword'"; // Get the data DataSet words = BadWordInfoProvider.GetBadWords(where, null); if (!DataHelper.DataSourceIsEmpty(words)) { // Get the bad word's data row DataRow wordDr = words.Tables[0].Rows[0]; // Create object from DataRow BadWordInfo modifyWord = new BadWordInfo(wordDr); // Update the properties modifyWord.WordAction = BadWordActionEnum.Replace; modifyWord.WordReplacement = "testpoliteword"; // Save the changes BadWordInfoProvider.SetBadWordInfo(modifyWord); return(true); } return(false); }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { string errorMessage = new Validator().NotEmpty(txtWordExpression.Text, GetString("general.requiresvalue")).Result; if (errorMessage == string.Empty) { if (badWordObj == null) { badWordObj = new BadWordInfo(); } // Set edited object EditedObject = badWordObj; // If bad word doesn't already exist, create new one if (!(((badWordId <= 0) || WordExpressionHasChanged()) && BadWordInfoProvider.BadWordExists(txtWordExpression.Text.Trim()))) { badWordObj.WordExpression = txtWordExpression.Text.Trim(); BadWordActionEnum action = (BadWordActionEnum)Convert.ToInt32(SelectBadWordActionControl.Value.ToString().Trim()); badWordObj.WordAction = !chkInheritAction.Checked ? action : 0; badWordObj.WordReplacement = (!chkInheritReplacement.Checked && (action == BadWordActionEnum.Replace)) ? txtWordReplacement.Text : null; badWordObj.WordLastModified = DateTime.Now; badWordObj.WordIsRegularExpression = chkIsRegular.Checked; badWordObj.WordMatchWholeWord = chkMatchWholeWord.Checked; if (badWordId <= 0) { badWordObj.WordIsGlobal = true; } BadWordInfoProvider.SetBadWordInfo(badWordObj); if (badWordId <= 0) { string redirectTo = badWordId <= 0 ? UIContextHelper.GetElementUrl("CMS.Badwords", "Administration.BadWords.Edit") : UIContextHelper.GetElementUrl("CMS.Badwords", "Administration.BadWords.Edit.General"); redirectTo = URLHelper.AddParameterToUrl(redirectTo, "objectid", badWordObj.WordID.ToString()); redirectTo = URLHelper.AddParameterToUrl(redirectTo, "saved", "1"); URLHelper.Redirect(redirectTo); } else { ScriptHelper.RefreshTabHeader(Page, txtWordExpression.Text.Trim()); ShowChangesSaved(); } } else { ShowError(GetString("badwords_edit.badwordexists")); } } else { ShowError(errorMessage); } }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void uniGrid_OnAction(string actionName, object actionArgument) { switch (actionName.ToLowerCSafe()) { case "edit": URLHelper.Redirect("BadWords_Edit.aspx?badwordid=" + Convert.ToString(actionArgument)); break; case "delete": BadWordInfoProvider.DeleteBadWordInfo(Convert.ToInt32(actionArgument)); break; } }
protected void isGlobal_CheckedChanged(object sender, EventArgs e) { if (badWordObj != null) { // Set whether the word is global badWordObj.WordIsGlobal = radAll.Checked; // Save badword BadWordInfoProvider.SetBadWordInfo(badWordObj); // Display message ShowChangesSaved(); // Show / hide selector SetSelectorVisibility(); } }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { string errorMessage = new Validator().NotEmpty(txtWordExpression.Text, GetString("general.requiresvalue")).Result; if (errorMessage == string.Empty) { if (badWordObj == null) { badWordObj = new BadWordInfo(); } // Set edited object EditedObject = badWordObj; // If bad word doesn't already exist, create new one if (!BadWordInfoProvider.BadWordExists(txtWordExpression.Text.Trim()) || (badWordId != 0)) { badWordObj.WordExpression = txtWordExpression.Text.Trim(); BadWordActionEnum action = (BadWordActionEnum)Convert.ToInt32(SelectBadWordActionControl.Value.ToString().Trim()); badWordObj.WordAction = !chkInheritAction.Checked ? action : 0; badWordObj.WordReplacement = (!chkInheritReplacement.Checked && (action == BadWordActionEnum.Replace)) ? txtWordReplacement.Text : null; badWordObj.WordLastModified = DateTime.Now; badWordObj.WordIsRegularExpression = chkIsRegular.Checked; badWordObj.WordMatchWholeWord = chkMatchWholeWord.Checked; if (badWordId == 0) { badWordObj.WordIsGlobal = true; } BadWordInfoProvider.SetBadWordInfo(badWordObj); string redirectTo = badWordId == 0 ? "BadWords_Edit.aspx" : "BadWords_Edit_General.aspx"; URLHelper.Redirect(redirectTo + "?badwordid=" + Convert.ToString(badWordObj.WordID) + "&saved=1"); } else { lblError.Visible = true; lblError.Text = GetString("badwords_edit.badwordexists"); } } else { lblError.Visible = true; lblError.Text = errorMessage; } }
private void OnAction(string actionName, object actionArgument) { switch (actionName.ToLowerCSafe()) { case "delete": BadWordInfoProvider.DeleteBadWordInfo(ValidationHelper.GetInteger(actionArgument, 0)); break; case "edit": string editUrl = UIContextHelper.GetElementUrl("CMS.BadWords", "Administration.BadWords.Edit"); editUrl = URLHelper.AddParameterToUrl(editUrl, "objectid", actionArgument.ToString()); editUrl = URLHelper.AddParameterToUrl(editUrl, "displaytitle", "false"); URLHelper.Redirect(editUrl); break; } }
/// <summary> /// Creates a "testbadword" bad word. Called when the "Create word" button is pressed. /// </summary> private bool CreateBadWord() { // Create new bad word object BadWordInfo newWord = new BadWordInfo(); // Set the properties newWord.WordExpression = "testbadword"; newWord.WordAction = BadWordActionEnum.ReportAbuse; newWord.WordIsGlobal = true; newWord.WordIsRegularExpression = false; // Save the bad word BadWordInfoProvider.SetBadWordInfo(newWord); return(true); }
/// <summary> /// Checks the declared custom string for presence of any defined bad word. /// </summary> private bool CheckAllBadWords() { // String to be checked for presence of bad words string text = "This is a string containing the sample testbadword, which can be created by the first code example on this page. It also contains the word asshole, which is one of the default bad words defined in the system."; // Hashtable that will contain found bad words Hashtable foundWords = new Hashtable(); // Modify the string according to found bad words and return which action should be performed BadWordActionEnum action = BadWordInfoProvider.CheckAllBadWords(null, null, ref text, foundWords); if (foundWords.Count != 0) { switch (action) { case BadWordActionEnum.Deny: // Some additional actions performed here ... break; case BadWordActionEnum.RequestModeration: // Some additional actions performed here ... break; case BadWordActionEnum.Remove: // Some additional actions performed here ... break; case BadWordActionEnum.Replace: // Some additional actions performed here ... break; case BadWordActionEnum.ReportAbuse: // Some additional actions performed here ... break; case BadWordActionEnum.None: // Some additional actions performed here ... break; } return(true); } return(false); }
protected void Page_Load(object sender, EventArgs e) { int badWordId = QueryHelper.GetInteger("badWordId", 0); bool badWordIsSelected = (badWordId != 0); // Initialize PageTitle breadcrumbs string[,] pageTitleTabs = new string[2, 3]; pageTitleTabs[0, 0] = GetString("badwords_edit.itemlistlink"); pageTitleTabs[0, 1] = "~/CMSModules/BadWords/BadWords_List.aspx"; pageTitleTabs[0, 2] = "_parent"; string badWord = string.Empty; // Get bad word name if (!badWordIsSelected) { badWord = GetString("badwords_list.newitemcaption"); } else { BadWordInfo badWordInfo = BadWordInfoProvider.GetBadWordInfo(badWordId); if (badWordInfo != null) { badWord = badWordInfo.WordExpression; } } pageTitleTabs[1, 0] = badWord; pageTitleTabs[1, 1] = string.Empty; pageTitleTabs[1, 2] = string.Empty; // Initialize masterpage properties CurrentMaster.Title.Breadcrumbs = pageTitleTabs; CurrentMaster.Title.TitleText = !badWordIsSelected?GetString("BadWords_List.HeaderCaption") : GetString("BadWords_Edit.badwordproperties"); CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Badwords_Word/object.png"); CurrentMaster.Title.HelpTopicName = "general_badwords"; CurrentMaster.Title.HelpName = "helpTopic"; if (!RequestHelper.IsPostBack()) { InitalizeMenu(); } }
protected void Page_Load(object sender, EventArgs e) { // Get ID of bad word badWordId = QueryHelper.GetInteger("badwordid", 0); if (badWordId > 0) { radAll.CheckedChanged += isGlobal_CheckedChanged; radSelected.CheckedChanged += isGlobal_CheckedChanged; badWordObj = BadWordInfoProvider.GetBadWordInfo(badWordId); // Set edited object EditedObject = badWordObj; if (badWordObj != null) { if (!RequestHelper.IsPostBack()) { // Initialize radiobuttons radAll.Checked = badWordObj.WordIsGlobal; radSelected.Checked = !badWordObj.WordIsGlobal; } } // Show / hide selector SetSelectorVisibility(); // Get the word cultures if (!RequestHelper.IsPostBack() || (radSelected == ControlsHelper.GetPostBackControl(Page))) { usWordCultures.Value = GetCurrentValues(); } } // Initialize selector properties usWordCultures.OnSelectionChanged += usWordCultures_OnSelectionChanged; usWordCultures.ButtonRemoveSelected.CssClass = "XLongButton"; usWordCultures.ButtonAddItems.CssClass = "XLongButton"; }
/// <summary> /// Deletes all "testbadword" bad words. Called when the "Delete bad word(s)" button is pressed. /// Expects the CreateBadWord method to be run first. /// </summary> private bool DeleteBadWord() { // Prepare the parameters string where = "[WordExpression] = 'testbadword' "; // Get the data DataSet words = BadWordInfoProvider.GetBadWords(where, null); if (!DataHelper.DataSourceIsEmpty(words)) { foreach (DataRow wordDr in words.Tables[0].Rows) { // Create object from DataRow BadWordInfo deleteWord = new BadWordInfo(wordDr); // Delete the bad word BadWordInfoProvider.DeleteBadWordInfo(deleteWord); } return(true); } return(false); }
/// <summary> /// OK click hadler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { #region "Security" // Check whether forum exists if (ForumContext.CurrentForum == null) { return; } // Check security bool securityCheck = true; switch (ForumContext.CurrentState) { case ForumStateEnum.NewThread: securityCheck = IsAvailable(ForumContext.CurrentForum, ForumActionType.NewThread); break; case ForumStateEnum.ReplyToPost: securityCheck = IsAvailable(ForumContext.CurrentForum, ForumActionType.Reply); break; case ForumStateEnum.EditPost: securityCheck = ForumContext.CurrentPost != null && IsAvailable(ForumContext.CurrentPost, ForumActionType.Edit); break; } if (!securityCheck) { ShowError(GetString("ForumNewPost.PermissionDenied")); return; } #region "Captcha" // Check security code if is required if ((ForumContext.CurrentForum.ForumUseCAPTCHA) && (!SecurityCode1.IsValid()) && (ForumContext.CurrentState != ForumStateEnum.EditPost)) { ShowError(GetString("ForumNewPost.InvalidCaptcha")); return; } #endregion #region "Email field" // Create instance of validator Validator validator = new Validator(); // Check whether email is valid string result = validator.IsEmail(txtEmail.Text, rfvEmail.ErrorMessage).Result; // Check whether email is present with correct format if email is required // or when subscribtion to current post is checked if ((ForumContext.CurrentForum.ForumRequireEmail || chkSubscribe.Checked) && (!String.IsNullOrEmpty(result))) { ShowError(result); return; } // Check if email is added if is in correct format if ((txtEmail.Text.Trim() != "") && (!String.IsNullOrEmpty(result))) { ShowError(rfvEmail.ErrorMessage); return; } #endregion #region "Subject" // Check whether subject is filled if (txtSubject.Text.Trim() == "") { ShowError(rfvSubject.ErrorMessage); return; } #endregion #region "Text" validator = new Validator(); // Check post text in HTML editor or text area if (!ForumContext.CurrentForum.ForumHTMLEditor) { // Check whether post text is added in text area if ((result = validator.NotEmpty(DiscussionMacroHelper.RemoveTags(ucBBEditor.Text), rfvText.ErrorMessage).Result) != "") { ShowError(result); return; } } else { // Check whether post text is added in HTML editor if ((result = validator.NotEmpty(htmlTemplateBody.ResolvedValue, rfvText.ErrorMessage).Result) != "") { ShowError(result); return; } } #endregion #region "User name" // Check whether user name is filled if user name field is visible if (ForumContext.CurrentForum.ForumAllowChangeName || MembershipContext.AuthenticatedUser.IsPublic() || ((ForumContext.CurrentForum != null) && (ForumContext.UserIsModerator(ForumContext.CurrentForum.ForumID, ForumContext.CommunityGroupID)))) { validator = new Validator(); if (!String.IsNullOrEmpty(result = validator.NotEmpty(txtUserName.Text, rfvUserName.ErrorMessage).Result)) { ShowError(result); return; } } #endregion #endregion #region "Forum post properties" bool newPost = false; // Current forum info object ForumInfo fi = ForumContext.CurrentForum; // Forum post info object ForumPostInfo fp = null; // Get forum post info with dependence on current state if (ForumContext.CurrentState == ForumStateEnum.EditPost) { // Get existing object fp = ForumContext.CurrentPost; fp.PostLastEdit = DateTime.Now; } else { // Create new forum post info object fp = new ForumPostInfo(); newPost = true; } #region "Ad-hoc forum" if (IsAdHocForum && (ForumContext.CurrentForum.ForumID == 0)) { if (DocumentContext.CurrentDocument == null) { ShowError(GetString("forums.documentdoesnotexist")); return; } fi.ForumGroupID = ForumGroupInfoProvider.GetAdHocGroupInfo(SiteID).GroupID; fi.ForumName = "AdHoc-" + Guid.NewGuid(); fi.ForumDisplayName = TextHelper.LimitLength(DocumentContext.CurrentDocument.GetDocumentName(), POST_USERNAME_LENGTH, String.Empty); fi.ForumOpen = true; fi.ForumModerated = false; fi.ForumAccess = 040000; fi.ForumThreads = 0; fi.ForumPosts = 0; fi.ForumLogActivity = LogActivity; ForumInfoProvider.SetForumInfo(fi); ForumContext.CurrentForum.ForumID = fi.ForumID; ForumContext.ForumID = fi.ForumID; ForumID = fi.ForumID; } #endregion // Post forum fp.PostForumID = ForumContext.CurrentForum.ForumID; // Get forum post info with dependence on current state if (ForumContext.CurrentState != ForumStateEnum.EditPost) { // Post time fp.PostTime = DateTime.Now; // User IP address fp.PostInfo.IPAddress = RequestContext.UserHostAddress; // User agent fp.PostInfo.Agent = Request.UserAgent; // Post user id if (!MembershipContext.AuthenticatedUser.IsPublic()) { fp.PostUserID = MembershipContext.AuthenticatedUser.UserID; } // Post signature fp.PostUserSignature = txtSignature.Text; } // Post subject fp.PostSubject = txtSubject.Text; // Post user email fp.PostUserMail = txtEmail.Text; // Post type int forumType = ForumContext.CurrentForum.ForumType; if (forumType == 0) { if (ForumContext.CurrentReplyThread == null) { // New thread - use type which user chosen fp.PostType = (radTypeDiscussion.Checked ? 0 : 1); } else { // Reply - use parent type fp.PostType = ForumContext.CurrentReplyThread.PostType; } } else { // Fixed type - use the forum setting fp.PostType = forumType - 1; } bool newThread = (ForumContext.CurrentReplyThread == null); // Set username if change name is allowed if (fi.ForumAllowChangeName || MembershipContext.AuthenticatedUser.IsPublic() || ForumContext.UserIsModerator(fp.PostForumID, ForumContext.CommunityGroupID)) { fp.PostUserName = TextHelper.LimitLength(txtUserName.Text, POST_USERNAME_LENGTH, ""); } else { // Get forum post info with dependence on current state if (ForumContext.CurrentState != ForumStateEnum.EditPost) { fp.PostUserName = UserName; } } // Post parent id -> reply to if (ForumContext.CurrentReplyThread != null) { fp.PostParentID = ForumContext.CurrentReplyThread.PostId; // Check max relative level if ((MaxRelativeLevel > -1) && (ForumContext.CurrentReplyThread.PostLevel >= MaxRelativeLevel)) { ShowError(GetString("Forums.MaxRelativeLevelError")); return; } } // Get post text from HTML editor if is enabled fp.PostText = ForumContext.CurrentForum.ForumHTMLEditor ? htmlTemplateBody.ResolvedValue : ucBBEditor.Text; // Approve post if forum is not moderated if (newPost) { if (!ForumContext.CurrentForum.ForumModerated) { fp.PostApproved = true; } else { if (ForumContext.UserIsModerator(fp.PostForumID, CommunityGroupID)) { fp.PostApproved = true; fp.PostApprovedByUserID = MembershipContext.AuthenticatedUser.UserID; } } } // If signature is enabled then if (EnableSignature) { fp.PostUserSignature = MembershipContext.AuthenticatedUser.UserSignature; } #endregion if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { // Prepare columns to check Dictionary <string, int> columns = new Dictionary <string, int>(); columns.Add("PostText", 0); columns.Add("PostSubject", 450); columns.Add("PostUserSignature", 0); columns.Add("PostUserName", 200); // Perform bad words check string badMessage = BadWordsHelper.CheckBadWords(fp, columns, "PostApproved", "PostApprovedByUserID", fp.PostText, MembershipContext.AuthenticatedUser.UserID, () => { return(ValidatePost(fp)); }); if (String.IsNullOrEmpty(badMessage)) { if (!ValidatePost(fp)) { badMessage = GetString("ForumNewPost.EmptyBadWord"); } } if (!String.IsNullOrEmpty(badMessage)) { ShowError(badMessage); return; } } // Flood protection if (FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(GetString("General.FloodProtection")); return; } // Check banned ip if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } string baseUrl = ForumContext.CurrentForum.ForumBaseUrl; if (String.IsNullOrEmpty(baseUrl)) { baseUrl = FriendlyBaseURL; } string unsubscriptionUrl = ForumContext.CurrentForum.ForumUnsubscriptionUrl; if (String.IsNullOrEmpty(unsubscriptionUrl)) { unsubscriptionUrl = UnsubscriptionURL; } // USe parent post id for new post int subscibePostId = newPost ? fp.PostParentID : fp.PostId; // Check subscriptions if ((chkSubscribe.Checked) && (!String.IsNullOrEmpty(txtEmail.Text)) && (ForumSubscriptionInfoProvider.IsSubscribed(txtEmail.Text.Trim(), fp.PostForumID, subscibePostId))) { // Post of the forum is already subscribed to this email -> show an error chkSubscribe.Checked = false; ShowError(GetString("Forums.EmailAlreadySubscribed")); return; } // Save post object ForumPostInfoProvider.SetForumPostInfo(fp, baseUrl, unsubscriptionUrl); LogPostActivity(fp, fi); #region "Subscription" // If subscribe is checked create new subscription to the current post if ((chkSubscribe.Checked) && (!ForumSubscriptionInfoProvider.IsSubscribed(fp.PostUserMail, fp.PostForumID, fp.PostId))) { // Create new subscription info object ForumSubscriptionInfo fsi = new ForumSubscriptionInfo(); // Set info properties fsi.SubscriptionForumID = fp.PostForumID; fsi.SubscriptionEmail = fp.PostUserMail; fsi.SubscriptionPostID = fp.PostId; fsi.SubscriptionUserID = fp.PostUserID; fsi.SubscriptionGUID = Guid.NewGuid(); // Save subscription ForumSubscriptionInfoProvider.Subscribe(fsi, DateTime.Now, true, true); if (fsi.SubscriptionApproved) { LogSubscriptionActivity(fsi, fi); } } #endregion bool moderationRequired = false; if ((!fp.PostApproved) && (!ForumContext.UserIsModerator(fp.PostForumID, CommunityGroupID))) { moderationRequired = true; if (OnModerationRequired != null) { OnModerationRequired(this, null); } } // Keep current user info CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser; if (currentUser.IsAuthenticated() && chkAttachFile.Checked && (currentUser.IsGlobalAdministrator || ForumContext.CurrentForum.AllowAttachFiles != SecurityAccessEnum.Nobody)) { // Redirect to the post attachments string attachmentUrl = GetURL(fp, ForumActionType.Attachment); if (moderationRequired) { attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "moderated", "1"); } URLHelper.Redirect(attachmentUrl); } else { if (!StopProcessing) { // Redirect back to the forum or forum thread URLHelper.Redirect(ClearURL()); } } }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == "") { // Check flooding when message being inserted through the LiveSite if (CheckFloodProtection && IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(GetString("General.FloodProtection")); return; } CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser; BoardMessageInfo messageInfo = null; if (MessageID > 0) { // Get message info messageInfo = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = messageInfo.MessageBoardID; } else { // Create new info messageInfo = new BoardMessageInfo(); // User IP address messageInfo.MessageUserInfo.IPAddress = RequestContext.UserHostAddress; // User agent messageInfo.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info messageInfo.MessageEmail = txtEmail.Text.Trim(); messageInfo.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if ((url != "http://") && (url != "https://") && (url != "")) { if ((!url.ToLowerCSafe().StartsWithCSafe("http://")) && (!url.ToLowerCSafe().StartsWithCSafe("https://"))) { url = "http://" + url; } } else { url = ""; } messageInfo.MessageURL = url; messageInfo.MessageURL = messageInfo.MessageURL.ToLowerCSafe().Replace("javascript", "_javascript"); messageInfo.MessageUserName = txtUserName.Text.Trim(); if ((MessageID <= 0) && (!currentUser.IsPublic())) { messageInfo.MessageUserID = currentUser.UserID; } messageInfo.MessageIsSpam = ValidationHelper.GetBoolean(chkSpam.Checked, false); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { messageInfo.MessageRatingValue = ratingControl.CurrentRating; // Remember rating in cookie string docs = CookieHelper.GetValue(CookieName.RatedDocuments) ?? "|"; if (!docs.Contains("|" + DocumentContext.CurrentDocument.DocumentID + "|")) { docs += DocumentContext.CurrentDocument.DocumentID + "|"; // Actualize the cookie CookieHelper.SetValue(CookieName.RatedDocuments, docs, DateTime.Now.AddYears(1)); } } BoardInfo boardInfo = null; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(MessageBoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(MessageBoardID, BoardProperties.BoardModerators); } if (boardInfo != null) { // If the very new message is inserted if (MessageID == 0) { // If creating message set inserted to now and assign to board messageInfo.MessageInserted = currentUser.DateTimeNow; messageInfo.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { messageInfo.MessageApprovedByUserID = currentUser.UserID; messageInfo.MessageApproved = true; } else { // Is board moderated ? messageInfo.MessageApprovedByUserID = 0; messageInfo.MessageApproved = !boardInfo.BoardModerated; } } else { if (chkApproved.Checked) { // Set current user as approver messageInfo.MessageApproved = true; messageInfo.MessageApprovedByUserID = currentUser.UserID; } else { messageInfo.MessageApproved = false; messageInfo.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { // Columns to check Dictionary <string, int> collumns = new Dictionary <string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check errorMessage = BadWordsHelper.CheckBadWords(messageInfo, collumns, "MessageApproved", "MessageApprovedByUserID", messageInfo.MessageText, currentUser.UserID, () => { return(ValidateMessage(messageInfo)); }); // Additionally check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(messageInfo)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = messageInfo.MessageEmail; // Check for duplicate e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("((SubscriptionApproved = 1) OR (SubscriptionApproved IS NULL)) AND SubscriptionBoardID=" + MessageBoardID + " AND SubscriptionEmail='" + SecurityHelper.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); ClearForm(); if (bsi.SubscriptionApproved) { LogSubscribingActivity(bsi, boardInfo); } } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(messageInfo); LogCommentActivity(messageInfo, boardInfo); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { LogRatingActivity(ratingControl.CurrentRating); } // If the message is not approved let the user know message is waiting for approval if (messageInfo.MessageApproved == false) { ShowError(GetString("board.messageedit.waitingapproval")); } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(messageInfo); } // Hide message form if user has rated and empty rating is not allowed if (!BoardProperties.AllowEmptyRating && TreeProvider.HasRated(DocumentContext.CurrentDocument)) { pnlMessageEdit.Visible = false; lblAlreadyrated.Visible = true; } else { // Hide rating form if user has rated if (BoardProperties.EnableContentRating && (ratingControl != null) && ratingControl.GetCurrentRating() > 0) { plcRating.Visible = false; } } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Initialize resource strings rqfWordExpression.ErrorMessage = GetString("general.requiresvalue"); if (badWordId > 0) { badWordObj = BadWordInfoProvider.GetBadWordInfo(badWordId); // Set edited object EditedObject = badWordObj; if (badWordObj != null) { // Fill editing form if (!RequestHelper.IsPostBack()) { LoadData(badWordObj); // Show that the badWord was created or updated successfully if (QueryHelper.GetString("saved", string.Empty) == "1") { lblInfo.Visible = true; lblInfo.Text = GetString("General.ChangesSaved"); // Refresh header ScriptHelper.RegisterClientScriptBlock(this, GetType(), "refreshBadwordsHeader", ScriptHelper.GetScript("parent.frames['badwordsMenu'].location = 'BadWords_Edit_Header.aspx?badwordid=" + badWordObj.WordID + "';")); } } else { // Set selected action SetSelectedAction(badWordObj); } } } else { CurrentMaster.Title.TitleText = GetString("BadWords_Edit.NewItemCaption"); CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Badwords_Word/new.png"); CurrentMaster.Title.HelpTopicName = "general_badwords"; CurrentMaster.Title.HelpName = "helpTopic"; // Initialize breadcrumbs string[,] pageTitleTabs = new string[2, 3]; pageTitleTabs[0, 0] = GetString("badwords_edit.itemlistlink"); pageTitleTabs[0, 1] = "~/CMSModules/BadWords/BadWords_List.aspx"; pageTitleTabs[0, 2] = "_self"; pageTitleTabs[1, 0] = GetString("badwords_list.newitemcaption"); pageTitleTabs[1, 1] = ""; pageTitleTabs[1, 2] = ""; CurrentMaster.Title.Breadcrumbs = pageTitleTabs; SetSelectedAction(null); } // Enable / disable actions (depending on inheritance) SelectBadWordActionControl.Enabled = !chkInheritAction.Checked; txtWordReplacement.Enabled = !chkInheritReplacement.Checked; // Show / hide replacement textbox depending on action plcReplacement.Visible = ((BadWordActionEnum)Enum.Parse(typeof(BadWordActionEnum), SelectBadWordActionControl.Value.ToString())) == BadWordActionEnum.Replace; }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check if message board is opened if (!IsBoardOpen()) { return; } // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == String.Empty) { // Check flooding when message being inserted through the LiveSite if (CheckFloodProtection && IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(GetString("General.FloodProtection")); return; } var currentUser = MembershipContext.AuthenticatedUser; BoardMessageInfo message; if (MessageID > 0) { // Get message info message = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = message.MessageBoardID; } else { // Create new info message = new BoardMessageInfo(); // User IP address message.MessageUserInfo.IPAddress = RequestContext.UserHostAddress; // User agent message.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info message.MessageEmail = txtEmail.Text.Trim(); message.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if (!String.IsNullOrEmpty(url)) { string protocol = URLHelper.GetProtocol(url); if (String.IsNullOrEmpty(protocol)) { url = "http://" + url; } } message.MessageURL = TextHelper.LimitLength(url, txtURL.MaxLength); message.MessageURL = message.MessageURL.ToLowerCSafe().Replace("javascript", "_javascript"); message.MessageUserName = TextHelper.LimitLength(txtUserName.Text.Trim(), txtUserName.MaxLength); if ((message.MessageID <= 0) && (!currentUser.IsPublic())) { message.MessageUserID = currentUser.UserID; if (!plcUserName.Visible) { message.MessageUserName = GetDefaultUserName(); } } message.MessageIsSpam = ValidationHelper.GetBoolean(chkSpam.Checked, false); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { message.MessageRatingValue = ratingControl.CurrentRating; // Update document rating, remember rating in cookie TreeProvider.RememberRating(DocumentContext.CurrentDocument); } BoardInfo boardInfo; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(MessageBoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(MessageBoardID, BoardProperties.BoardModerators); } if (boardInfo != null) { if (BoardInfoProvider.IsUserAuthorizedToAddMessages(boardInfo)) { // If the very new message is inserted if (MessageID == 0) { // If creating message set inserted to now and assign to board message.MessageInserted = DateTime.Now; message.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { message.MessageApprovedByUserID = currentUser.UserID; message.MessageApproved = true; } else { // Is board moderated ? message.MessageApprovedByUserID = 0; message.MessageApproved = !boardInfo.BoardModerated; } } else { if (chkApproved.Checked) { // Set current user as approver message.MessageApproved = true; message.MessageApprovedByUserID = currentUser.UserID; } else { message.MessageApproved = false; message.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { // Columns to check Dictionary <string, int> collumns = new Dictionary <string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check bool validateUserName = plcUserName.Visible; errorMessage = BadWordsHelper.CheckBadWords(message, collumns, "MessageApproved", "MessageApprovedByUserID", message.MessageText, currentUser.UserID, () => ValidateMessage(message, validateUserName)); // Additionally check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(message, validateUserName)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = message.MessageEmail; // Check for duplicate e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("((SubscriptionApproved = 1) OR (SubscriptionApproved IS NULL)) AND SubscriptionBoardID=" + MessageBoardID + " AND SubscriptionEmail='" + SqlHelper.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); ClearForm(); if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); Service.Resolve <ICurrentContactMergeService>().UpdateCurrentContactEmail(bsi.SubscriptionEmail, MembershipContext.AuthenticatedUser); LogSubscribingActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + String.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(message); Service.Resolve <ICurrentContactMergeService>().UpdateCurrentContactEmail(message.MessageEmail, MembershipContext.AuthenticatedUser); LogCommentActivity(message, boardInfo); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { LogRatingActivity(ratingControl.CurrentRating); } // If the message is not approved let the user know message is waiting for approval if (message.MessageApproved == false) { ShowInformation(GetString("board.messageedit.waitingapproval")); } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(message); } // Hide message form if user has rated and empty rating is not allowed if (BoardProperties.CheckIfUserRated) { if (!BoardProperties.AllowEmptyRating && TreeProvider.HasRated(DocumentContext.CurrentDocument)) { pnlMessageEdit.Visible = false; lblAlreadyrated.Visible = true; } else { // Hide rating form if user has rated if (BoardProperties.EnableContentRating && (ratingControl != null) && ratingControl.GetCurrentRating() > 0) { plcRating.Visible = false; } } } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } else if (String.IsNullOrEmpty(errorMessage)) { errorMessage = ResHelper.GetString("general.actiondenied"); } } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == "") { // Check flooding when message being inserted through the LiveSite if (this.CheckFloodProtection && this.IsLiveSite && FloodProtectionHelper.CheckFlooding(CMSContext.CurrentSiteName, CMSContext.CurrentUser)) { lblError.Visible = true; lblError.Text = GetString("General.FloodProtection"); return; } CurrentUserInfo currentUser = CMSContext.CurrentUser; BoardMessageInfo messageInfo = null; if (MessageID > 0) { // Get message info messageInfo = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = messageInfo.MessageBoardID; } else { // Create new info messageInfo = new BoardMessageInfo(); // User IP adress messageInfo.MessageUserInfo.IPAddress = Request.UserHostAddress; // User agent messageInfo.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info messageInfo.MessageEmail = txtEmail.Text.Trim(); messageInfo.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if ((url != "http://") && (url != "https://") && (url != "")) { if ((!url.ToLower().StartsWith("http://")) && (!url.ToLower().StartsWith("https://"))) { url = "http://" + url; } } else { url = ""; } messageInfo.MessageURL = url; messageInfo.MessageURL = messageInfo.MessageURL.ToLower().Replace("javascript", "_javascript"); messageInfo.MessageUserName = this.txtUserName.Text.Trim(); if (!currentUser.IsPublic()) { messageInfo.MessageUserID = currentUser.UserID; } messageInfo.MessageIsSpam = ValidationHelper.GetBoolean(this.chkSpam.Checked, false); if (this.BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { messageInfo.MessageRatingValue = ratingControl.CurrentRating; } BoardInfo boardInfo = null; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(this.BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board this.MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(this.MessageBoardID, this.BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(this.MessageBoardID, this.BoardProperties.BoardModerators); } if (boardInfo != null) { // If the very new message is inserted if (this.MessageID == 0) { // If creating message set inserted to now and assign to board messageInfo.MessageInserted = currentUser.DateTimeNow; messageInfo.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { messageInfo.MessageApprovedByUserID = currentUser.UserID; messageInfo.MessageApproved = true; } else { // Is board moderated ? messageInfo.MessageApprovedByUserID = 0; messageInfo.MessageApproved = !boardInfo.BoardModerated; } } else { if (this.chkApproved.Checked) { // Set current user as approver messageInfo.MessageApproved = true; messageInfo.MessageApprovedByUserID = currentUser.UserID; } else { messageInfo.MessageApproved = false; messageInfo.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(CMSContext.CurrentUser, CMSContext.CurrentSiteName)) { // Columns to check Dictionary <string, int> collumns = new Dictionary <string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check errorMessage = BadWordsHelper.CheckBadWords(messageInfo, collumns, "MessageApproved", "MessageApprovedByUserID", messageInfo.MessageText, currentUser.UserID); // Additionaly check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(messageInfo)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = messageInfo.MessageEmail; // Check for duplicit e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("SubscriptionBoardID=" + this.MessageBoardID + " AND SubscriptionEmail='" + SqlHelperClass.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = this.MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.SetBoardSubscriptionInfo(bsi); ClearForm(); LogSubscribingActivity(bsi, boardInfo); } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(messageInfo); LogCommentActivity(messageInfo, boardInfo); // If the board is moderated let the user know message is waiting for approval if (boardInfo.BoardModerated && (messageInfo.MessageApproved == false)) { this.lblInfo.Text = GetString("board.messageedit.waitingapproval"); this.lblInfo.Visible = true; } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(messageInfo); } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } } if (errorMessage != "") { lblError.Text = errorMessage; lblError.Visible = true; } else { // Regenerate new captcha captchaElem.GenerateNew(); } }
protected void btnSendMessage_Click(object sender, EventArgs e) { // This is because of ASP.NET default behaviour // The first empty line was trimmed after each postback if (BBEditor.Text.StartsWithCSafe("\n")) { BBEditor.Text = "\n" + BBEditor.Text; } // Flood protection if (!FloodProtectionHelper.CheckFlooding(CMSContext.CurrentSiteName, CMSContext.CurrentUser)) { CurrentUserInfo currentUser = CMSContext.CurrentUser; // Check banned IP if (BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { int recipientId = ucMessageUserSelector.Visible ? ucMessageUserSelector.SelectedUserID : ValidationHelper.GetInteger(hdnUserId.Value, 0); string message = string.Empty; string nickName = HTMLHelper.HTMLEncode(txtFrom.Text.Trim()); if (!ValidateBody(DiscussionMacroHelper.RemoveTags(ucBBEditor.Text))) { message = GetString("SendMessage.EmptyBody"); } // Check sender nick name if anonymous if (isAnonymousUser && (nickName == string.Empty)) { message = GetString("SendMesage.NoNickName"); } UserInfo recipient = null; // Check recipient if (recipientId == 0) { if (string.IsNullOrEmpty(ucMessageUserSelector.UserNameTextBox.Text.Trim())) { message = GetString("SendMesage.NoRecipient"); } else { message = GetString("SendMesage.UserDoesntExists"); } } else { recipient = UserInfoProvider.GetUserInfo(recipientId); // Normal users can't send message to user from other site except for global admin if (!recipient.IsInSite(CMSContext.CurrentSiteName) && !currentUser.IsGlobalAdministrator) { message = GetString("SendMesage.UserDoesntExists"); } int defRecipientId = ValidationHelper.GetInteger(DefaultRecipient, 0); // If default recipient selected and is same as message recipient, skip check on hidden users if (recipient.UserID != defRecipientId) { // Manually disabled users Hidden users if not replying to them Not approved users bool userAllowed = (recipient.UserIsDisabledManually || (recipient.UserIsHidden && (SendMessageMode != MessageActionEnum.Reply)) || recipient.UserSettings.UserWaitingForApproval); // If live site mode hide not allowed users for all users except for global admins and public user for all users if ((IsLiveSite && userAllowed && !currentUser.IsGlobalAdministrator) || (recipient.UserName.ToLowerCSafe() == "public")) { message = GetString("SendMesage.UserDoesntExists"); } } } if (message == string.Empty) { // Send message try { // Check if current user is in recipient's ignore list bool isIgnored = IgnoreListInfoProvider.IsInIgnoreList(recipientId, currentUser.UserID); Message = new MessageInfo(); Message.MessageBody = ucBBEditor.Text; string subject = (txtSubject.Text.Trim() == string.Empty) ? GetString("Messaging.NoSubject") : txtSubject.Text.Trim(); Message.MessageSubject = TextHelper.LimitLength(subject, 200); Message.MessageRecipientUserID = recipientId; Message.MessageRecipientNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(recipient.UserName, recipient.FullName, recipient.UserNickName, IsLiveSite), 200); Message.MessageSent = DateTime.Now; // Anonymous user if (isAnonymousUser) { Message.MessageSenderNickName = TextHelper.LimitLength(nickName, 200); Message.MessageSenderDeleted = true; } else { Message.MessageSenderUserID = currentUser.UserID; Message.MessageSenderNickName = TextHelper.LimitLength(Functions.GetFormattedUserName(currentUser.UserName, currentUser.FullName, currentUser.UserNickName, IsLiveSite), 200); // If the user is ignored, delete message automatically if (isIgnored) { Message.MessageRecipientDeleted = true; } } string error = string.Empty; // Check bad words if (!BadWordInfoProvider.CanUseBadWords(currentUser, CMSContext.CurrentSiteName)) { // Prepare columns to check Dictionary <string, int> columns = new Dictionary <string, int>(); columns.Add("MessageSubject", 200); columns.Add("MessageBody", 0); columns.Add("MessageSenderNickName", 200); columns.Add("MessageRecipientNickName", 200); // Perform bad word check error = BadWordsHelper.CheckBadWords(Message, columns, currentUser.UserID, () => { return(ValidateBody(Message.MessageBody)); }); } if (error != string.Empty) { ShowError(error); } else { // Check message subject, if empty set no subject text if (Message.MessageSubject.Trim() == string.Empty) { Message.MessageSubject = GetString("Messaging.NoSubject"); } // Whole text has been removed if (!ValidateBody(Message.MessageBody)) { ShowError(GetString("SendMessage.EmptyBodyBadWords")); } else { // Save the message MessageInfoProvider.SetMessageInfo(Message); // Send notification email, if not ignored if (!isIgnored) { MessageInfoProvider.SendNotificationEmail(Message, recipient, currentUser, CMSContext.CurrentSiteName); } ShowConfirmation(GetString("SendMesage.MessageSent")); MessageId = 0; ucMessageUserSelector.SelectedUserID = 0; } } } catch (Exception ex) { ShowError(ex.Message); ErrorMessage = ex.Message; } } // Error in the form else { ShowError(message); ErrorMessage = message; } } else { ShowError(GetString("General.BannedIP")); } } else { ShowError(GetString("General.FloodProtection")); } // External event if (SendButtonClick != null) { SendButtonClick(sender, e); } }
public void PerformAction() { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } if (OnBeforeCommentSaved != null) { OnBeforeCommentSaved(); } // Validate form string errorMessage = ValidateForm(); if (errorMessage == "") { // Check flooding when message being inserted through the LiveSite if (IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { lblError.Visible = true; lblError.Text = GetString("General.FloodProtection"); return; } var currentUser = MembershipContext.AuthenticatedUser; // Create new comment BlogCommentInfo bci; if (IsInsertMode) { bci = new BlogCommentInfo(); bci.CommentDate = DateTime.Now; bci.CommentPostDocumentID = mPostDocumentId; // User IP address bci.CommentInfo.IPAddress = RequestContext.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(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { if (bci != null) { // Prepare columns to check Dictionary <string, int> columns = new Dictionary <string, int>(); columns.Add("CommentText", 0); columns.Add("CommentUserName", 200); // Perform bad words to check errorMessage = BadWordsHelper.CheckBadWords(bci, columns, "CommentApproved", "CommentApprovedByUserID", bci.CommentText, MembershipContext.AuthenticatedUser.UserID, () => 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) { // Check for duplicate subscriptions BlogPostSubscriptionInfo bpsi = BlogPostSubscriptionInfoProvider.GetBlogPostSubscriptionInfo(txtEmail.Text, mPostDocumentId); 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; } }
/// <summary> /// Checks the declared custom string for presence of the 'testbadword' bad word created by the first code example on this page. /// Expects the CreateBadWord method to be run first. /// </summary> private bool CheckSingleBadWord() { // Prepare parameters for selection of the checked bad word string where = "[WordExpression] = 'testbadword' "; // Get the data DataSet words = BadWordInfoProvider.GetBadWords(where, null); if (!DataHelper.DataSourceIsEmpty(words)) { // Get DataRow with bad word DataRow wordDr = words.Tables[0].Rows[0]; // Get BadWordInfo object BadWordInfo badWord = new BadWordInfo(wordDr); // String to be checked for presence of the bad word string text = "This is a string containing the sample testbadword, which can be created by the first code example on this page."; // Hashtable that will contain found bad words Hashtable foundWords = new Hashtable(); // Modify the string according to found bad words and return which action should be performed BadWordActionEnum action = BadWordInfoProvider.CheckBadWord(badWord, null, null, ref text, foundWords, 0); if (foundWords.Count != 0) { switch (action) { case BadWordActionEnum.Deny: // Some additional actions performed here ... break; case BadWordActionEnum.RequestModeration: // Some additional actions performed here ... break; case BadWordActionEnum.Remove: // Some additional actions performed here ... break; case BadWordActionEnum.Replace: // Some additional actions performed here ... break; case BadWordActionEnum.ReportAbuse: // Some additional actions performed here ... break; case BadWordActionEnum.None: // Some additional actions performed here ... break; } return(true); } apiCheckSingleBadWord.ErrorMessage = "Bad word 'testbadword' is not present in the checked string."; return(false); } return(false); }