/// <summary> /// Re-tweets Message thru the Twitter API /// </summary> /// <param name="sender"> /// The source of the event. /// </param> /// <param name="e"> /// The <see cref="System.EventArgs"/> instance containing the event data. /// </param> protected void Retweet_Click(object sender, EventArgs e) { var twitterName = this.Get <YafBoardSettings>().TwitterUserName.IsSet() ? "@{0} ".FormatWith(this.Get <YafBoardSettings>().TwitterUserName) : string.Empty; // process message... clean html, strip html, remove bbcode, etc... var twitterMsg = BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString((string)this.DataRow["Message"]))).RemoveMultipleWhitespace(); var topicUrl = YafBuildLink.GetLinkNotEscaped(ForumPages.posts, true, "m={0}#post{0}", this.DataRow["MessageID"]); // Send Retweet Directlly thru the Twitter API if User is Twitter User if (Config.TwitterConsumerKey.IsSet() && Config.TwitterConsumerSecret.IsSet() && this.Get <IYafSession>().TwitterToken.IsSet() && this.Get <IYafSession>().TwitterTokenSecret.IsSet() && this.Get <IYafSession>().TwitterTokenSecret.IsSet() && this.PageContext.IsTwitterUser) { var oAuth = new OAuthTwitter { ConsumerKey = Config.TwitterConsumerKey, ConsumerSecret = Config.TwitterConsumerSecret, Token = this.Get <IYafSession>().TwitterToken, TokenSecret = this.Get <IYafSession>().TwitterTokenSecret }; var tweets = new TweetAPI(oAuth); tweets.UpdateStatus( TweetAPI.ResponseFormat.json, this.Server.UrlEncode("RT {1}: {0} {2}".FormatWith(twitterMsg.Truncate(100), twitterName, topicUrl)), string.Empty); } else { this.Get <HttpResponseBase>().Redirect( "http://twitter.com/share?url={0}&text={1}".FormatWith( this.Server.UrlEncode(topicUrl), this.Server.UrlEncode( "RT {1}: {0}".FormatWith(twitterMsg.Truncate(100), twitterName)))); } }
/// <summary> /// Formats the forum post text /// </summary> /// <param name="post">Forum post</param> /// <returns>Formatted text</returns> public static string FormatPostText(this ForumPost post) { Guard.NotNull(post, nameof(post)); var text = post.Text; if (text.IsEmpty()) { return(string.Empty); } text = HtmlUtils.ConvertPlainTextToHtml(text.HtmlEncode()); if (EngineContext.Current.Resolve <ForumSettings>().ForumEditor == EditorType.BBCodeEditor) { text = BBCodeHelper.ToHtml(text); } return(text); }
/// <summary> /// Adds the New Topic to the User's ActivityStream /// </summary> /// <param name="forumID">The forum unique identifier.</param> /// <param name="topicID">The topic unique identifier.</param> /// <param name="messageID">The message unique identifier.</param> /// <param name="topicTitle">The topic title.</param> /// <param name="message">The message.</param> public void AddTopicToStream(int forumID, long topicID, int messageID, string topicTitle, string message) { message = BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message))) .RemoveMultipleWhitespace(); var user = UserController.Instance.GetCurrentUserInfo(); var portalSettings = PortalSettings.Current; var ji = new JournalItem { PortalId = portalSettings.PortalId, ProfileId = user.UserID, UserId = user.UserID, Title = topicTitle, ItemData = new ItemData { Url = BuildLink.GetLink(ForumPages.Posts, "t={0}", topicID) }, Summary = message.Truncate(150), Body = message, JournalTypeId = 5, SecuritySet = GetSecuritySet(forumID, portalSettings.PortalId), ObjectKey = $"{forumID.ToString()}:{topicID.ToString()}:{messageID.ToString()}" }; if (JournalController.Instance.GetJournalItemByKey(portalSettings.PortalId, ji.ObjectKey) != null) { JournalController.Instance.DeleteJournalItemByKey(portalSettings.PortalId, ji.ObjectKey); } // TODO: /*if (SocialGroupId > 0) * { * ji.SocialGroupId = SocialGroupId; * }*/ JournalController.Instance.SaveJournalItem(ji, -1); }
/// <summary> /// The options menu_ item click. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The Pop Event Arguments.</param> private void ShareMenuItemClick([NotNull] object sender, [NotNull] PopEventArgs e) { var topicUrl = BuildLink.GetLink( ForumPages.Posts, true, "t={0}&name={1}", this.PageContext.PageTopicID, this.PageContext.PageTopicName); switch (e.Item.ToLower()) { case "email": this.EmailTopic_Click(sender, e); break; case "tumblr": { // process message... clean html, strip html, remove BBCode, etc... var tumblrTopicName = BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(this.topic.TopicName))).RemoveMultipleWhitespace(); var meta = this.Page.Header.FindControlType <HtmlMeta>().ToList(); var description = string.Empty; if (meta.Any(x => x.Name.Equals("description"))) { var descriptionMeta = meta.FirstOrDefault(x => x.Name.Equals("description")); if (descriptionMeta != null) { description = $"&description={descriptionMeta.Content}"; } } var tumblrUrl = $"http://www.tumblr.com/share/link?url={this.Server.UrlEncode(topicUrl)}&name={tumblrTopicName}{description}"; this.Get <HttpResponseBase>().Redirect(tumblrUrl); } break; case "retweet": { var twitterName = this.PageContext.BoardSettings.TwitterUserName.IsSet() ? $"@{this.PageContext.BoardSettings.TwitterUserName} " : string.Empty; // process message... clean html, strip html, remove bbcode, etc... var twitterMsg = BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(this.topic.TopicName))).RemoveMultipleWhitespace(); var tweetUrl = $"http://twitter.com/share?url={this.Server.UrlEncode(topicUrl)}&text={this.Server.UrlEncode(string.Format("RT {1}Thread: {0}", twitterMsg.Truncate(100), twitterName))}"; this.Get <HttpResponseBase>().Redirect(tweetUrl); } break; case "reddit": { var redditUrl = $"http://www.reddit.com/submit?url={this.Server.UrlEncode(topicUrl)}&title={this.Server.UrlEncode(this.topic.TopicName)}"; this.Get <HttpResponseBase>().Redirect(redditUrl); } break; default: throw new ApplicationException(e.Item); } }
/// <summary> /// The to watching users. /// </summary> /// <param name="newMessageId"> /// The new message id. /// </param> public void ToWatchingUsers(int newMessageId) { var mailMessages = new List <MailMessage>(); var boardName = this.BoardSettings.Name; var forumEmail = this.BoardSettings.ForumEmail; var message = this.GetRepository <Message>().GetById(newMessageId); var messageAuthorUserID = message.UserID; // cleaned body as text... var bodyText = this.Get <IBadWordReplace>() .Replace(BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message.MessageText)))) .RemoveMultipleWhitespace(); var watchUsers = this.GetRepository <User>() .WatchMailListAsDataTable(message.TopicID, messageAuthorUserID); var watchEmail = new TemplateEmail("TOPICPOST") { TemplateParams = { ["{topic}"] = HttpUtility.HtmlDecode( this.Get <IBadWordReplace>().Replace(message.Topic)), ["{postedby}"] = this.Get <IUserDisplayName>().GetName(messageAuthorUserID), ["{body}"] = bodyText, ["{bodytruncated}"] = bodyText.Truncate(160), ["{link}"] = BuildLink.GetLinkNotEscaped( ForumPages.Posts, true, "m={0}&name={1}#post{0}", newMessageId, message.Topic), ["{subscriptionlink}"] = BuildLink.GetLinkNotEscaped( ForumPages.Profile_Subscriptions, true) } }; var currentContext = HttpContext.Current; watchUsers.Rows.Cast <DataRow>().AsParallel().ForAll( row => { HttpContext.Current = currentContext; try { var languageFile = row.Field <string>("LanguageFile").IsSet() && this.Get <BoardSettings>().AllowUserLanguage ? row.Field <string>("LanguageFile") : this.Get <BoardSettings>().Language; var subject = string.Format( this.Get <ILocalization>().GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile), boardName); watchEmail.TemplateLanguageFile = languageFile; mailMessages.Add(watchEmail.CreateEmail( new MailAddress(forumEmail, boardName), new MailAddress( row.Field <string>("Email"), this.BoardSettings.EnableDisplayName ? row.Field <string>("DisplayName") : row.Field <string>("Name")), subject)); } finally { HttpContext.Current = null; } }); if (this.BoardSettings.AllowNotificationAllPostsAllTopics) { var usersWithAll = this.GetRepository <User>().FindUserTyped( false, notificationType: UserNotificationSetting.AllTopics.ToInt()); // create individual watch emails for all users who have All Posts on... usersWithAll.Where(x => x.ID != messageAuthorUserID && x.ProviderUserKey != null).AsParallel().ForAll( user => { HttpContext.Current = currentContext; try { if (user.Email.IsNotSet()) { return; } var languageFile = user.LanguageFile.IsSet() && this.Get <BoardSettings>().AllowUserLanguage ? user.LanguageFile : this.Get <BoardSettings>().Language; var subject = string.Format( this.Get <ILocalization>().GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile), boardName); watchEmail.TemplateLanguageFile = languageFile; mailMessages.Add( watchEmail.CreateEmail( new MailAddress(forumEmail, boardName), new MailAddress( user.Email, this.BoardSettings.EnableDisplayName ? user.DisplayName : user.Name), subject)); } finally { HttpContext.Current = null; } }); } if (mailMessages.Any()) { // Now send all mails.. this.Get <ISendMail>().SendAll( mailMessages, (mailMessage, exception) => this.Get <ILogger>().Log( "Mail Error", EventLogTypes.Error, "SYSTEM", null, exception)); } }
private void BindData() { pnlError.Visible = false; txtTopicBodySimple.Visible = false; txtTopicBodyBBCode.Visible = false; txtTopicBodyHtml.Visible = false; switch (this.ForumService.ForumEditor) { case EditorTypeEnum.SimpleTextBox: { txtTopicBodySimple.Visible = true; rfvTopicBody.ControlToValidate = "txtTopicBodySimple"; } break; case EditorTypeEnum.BBCodeEditor: { txtTopicBodyBBCode.Visible = true; rfvTopicBody.ControlToValidate = "txtTopicBodyBBCode"; } break; case EditorTypeEnum.HtmlEditor: { txtTopicBodyHtml.Visible = true; rfvTopicBody.Enabled = false; } break; default: break; } if (this.AddTopic) { #region Adding topic var forum = this.ForumService.GetForumById(this.ForumId); if (forum == null) { Response.Redirect(SEOHelper.GetForumMainUrl()); } if (NopContext.Current.User == null && this.ForumService.AllowGuestsToCreateTopics) { this.CustomerService.CreateAnonymousUser(); } if (!this.ForumService.IsUserAllowedToCreateTopic(NopContext.Current.User, forum)) { string loginURL = SEOHelper.GetLoginPageUrl(true); Response.Redirect(loginURL); } lblTitle.Text = GetLocaleResourceString("Forum.NewTopic"); phForumName.Visible = true; lblForumName.Text = Server.HtmlEncode(forum.Name); txtTopicTitle.Visible = true; txtTopicTitle.Text = string.Empty; lblTopicTitle.Visible = false; lblTopicTitle.Text = string.Empty; ctrlForumBreadcrumb.ForumId = forum.ForumId; ctrlForumBreadcrumb.BindData(); phPriority.Visible = this.ForumService.IsUserAllowedToSetTopicPriority(NopContext.Current.User); phSubscribe.Visible = this.ForumService.IsUserAllowedToSubscribe(NopContext.Current.User); #endregion } else if (this.EditTopic) { #region Editing topic var forumTopic = this.ForumService.GetTopicById(this.ForumTopicId); if (forumTopic == null) { Response.Redirect(SEOHelper.GetForumMainUrl()); } if (!this.ForumService.IsUserAllowedToEditTopic(NopContext.Current.User, forumTopic)) { string loginURL = SEOHelper.GetLoginPageUrl(true); Response.Redirect(loginURL); } var forum = forumTopic.Forum; if (forum == null) { Response.Redirect(SEOHelper.GetForumMainUrl()); } lblTitle.Text = GetLocaleResourceString("Forum.EditTopic"); phForumName.Visible = true; lblForumName.Text = Server.HtmlEncode(forum.Name); txtTopicTitle.Visible = true; txtTopicTitle.Text = forumTopic.Subject; lblTopicTitle.Visible = false; lblTopicTitle.Text = string.Empty; ctrlForumBreadcrumb.ForumTopicId = forumTopic.ForumTopicId; ctrlForumBreadcrumb.BindData(); CommonHelper.SelectListItem(this.ddlPriority, forumTopic.TopicTypeId); var firstPost = forumTopic.FirstPost; if (firstPost != null) { switch (this.ForumService.ForumEditor) { case EditorTypeEnum.SimpleTextBox: { txtTopicBodySimple.Text = firstPost.Text; } break; case EditorTypeEnum.BBCodeEditor: { txtTopicBodyBBCode.Text = firstPost.Text; } break; case EditorTypeEnum.HtmlEditor: { txtTopicBodyHtml.Value = firstPost.Text; } break; default: break; } } phPriority.Visible = this.ForumService.IsUserAllowedToSetTopicPriority(NopContext.Current.User); //subscription if (this.ForumService.IsUserAllowedToSubscribe(NopContext.Current.User)) { phSubscribe.Visible = true; var forumSubscription = this.ForumService.GetAllSubscriptions(NopContext.Current.User.CustomerId, 0, forumTopic.ForumTopicId, 0, 1).FirstOrDefault(); cbSubscribe.Checked = forumSubscription != null; } else { phSubscribe.Visible = false; } #endregion } else if (this.AddPost) { #region Adding post var forumTopic = this.ForumService.GetTopicById(this.ForumTopicId); if (forumTopic == null) { Response.Redirect(SEOHelper.GetForumMainUrl()); } if (NopContext.Current.User == null && this.ForumService.AllowGuestsToCreatePosts) { this.CustomerService.CreateAnonymousUser(); } if (!this.ForumService.IsUserAllowedToCreatePost(NopContext.Current.User, forumTopic)) { string loginURL = SEOHelper.GetLoginPageUrl(true); Response.Redirect(loginURL); } ctrlForumBreadcrumb.ForumTopicId = forumTopic.ForumTopicId; ctrlForumBreadcrumb.BindData(); lblTitle.Text = GetLocaleResourceString("Forum.NewPost"); phForumName.Visible = false; lblForumName.Text = string.Empty; txtTopicTitle.Visible = false; txtTopicTitle.Text = string.Empty; lblTopicTitle.Visible = true; lblTopicTitle.Text = Server.HtmlEncode(forumTopic.Subject); var quotePost = this.ForumService.GetPostById(QuotePostId); if (quotePost != null && quotePost.TopicId == forumTopic.ForumTopicId) { switch (this.ForumService.ForumEditor) { case EditorTypeEnum.SimpleTextBox: txtTopicBodySimple.Text = String.Format("{0}:\n{1}\n", quotePost.User.FormatUserName(), quotePost.Text); break; case EditorTypeEnum.BBCodeEditor: txtTopicBodyBBCode.Text = String.Format("[quote={0}]{1}[/quote]", quotePost.User.FormatUserName(), BBCodeHelper.RemoveQuotes(quotePost.Text)); break; case EditorTypeEnum.HtmlEditor: txtTopicBodyHtml.Value = String.Format("<b>{0}:</b><p style=\"padding: 5px 5px 5px 5px; border: dashed 1px black; background-color: #ffffff;\">{1}</p>", quotePost.User.FormatUserName(), quotePost.Text); break; } } phPriority.Visible = false; //subscription if (this.ForumService.IsUserAllowedToSubscribe(NopContext.Current.User)) { phSubscribe.Visible = true; var forumSubscription = this.ForumService.GetAllSubscriptions(NopContext.Current.User.CustomerId, 0, forumTopic.ForumTopicId, 0, 1).FirstOrDefault(); cbSubscribe.Checked = forumSubscription != null; } else { phSubscribe.Visible = false; } #endregion } else if (this.EditPost) { #region Editing post var forumPost = this.ForumService.GetPostById(this.ForumPostId); if (forumPost == null) { Response.Redirect(SEOHelper.GetForumMainUrl()); } if (!this.ForumService.IsUserAllowedToEditPost(NopContext.Current.User, forumPost)) { string loginURL = SEOHelper.GetLoginPageUrl(true); Response.Redirect(loginURL); } var forumTopic = forumPost.Topic; if (forumTopic == null) { Response.Redirect(SEOHelper.GetForumMainUrl()); } lblTitle.Text = GetLocaleResourceString("Forum.EditPost"); phForumName.Visible = false; lblForumName.Text = string.Empty; txtTopicTitle.Visible = false; txtTopicTitle.Text = string.Empty; lblTopicTitle.Visible = true; lblTopicTitle.Text = Server.HtmlEncode(forumTopic.Subject); ctrlForumBreadcrumb.ForumTopicId = forumTopic.ForumTopicId; ctrlForumBreadcrumb.BindData(); switch (this.ForumService.ForumEditor) { case EditorTypeEnum.SimpleTextBox: { txtTopicBodySimple.Text = forumPost.Text; } break; case EditorTypeEnum.BBCodeEditor: { txtTopicBodyBBCode.Text = forumPost.Text; } break; case EditorTypeEnum.HtmlEditor: { txtTopicBodyHtml.Value = forumPost.Text; } break; default: break; } phPriority.Visible = false; //subscription if (this.ForumService.IsUserAllowedToSubscribe(NopContext.Current.User)) { phSubscribe.Visible = true; var forumSubscription = this.ForumService.GetAllSubscriptions(NopContext.Current.User.CustomerId, 0, forumTopic.ForumTopicId, 0, 1).FirstOrDefault(); cbSubscribe.Checked = forumSubscription != null; } else { phSubscribe.Visible = false; } #endregion } else { Response.Redirect(SEOHelper.GetForumMainUrl()); } }
/// <summary> /// Handles the PostReply click including: Replying, Editing and New post. /// </summary> /// <param name="sender"> /// The Sender Object. /// </param> /// <param name="e"> /// The Event Arguments. /// </param> protected void PostReply_Click([NotNull] object sender, [NotNull] EventArgs e) { if (!this.IsPostReplyVerified()) { return; } var isPossibleSpamMessage = false; // Check for SPAM if (!this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess && !this.PageContext.BoardSettings.SpamServiceType.Equals(0)) { // Check content for spam if ( this.Get <ISpamCheck>().CheckPostForSpam( this.PageContext.IsGuest ? this.From.Text : this.PageContext.User.DisplayOrUserName(), this.Get <HttpRequestBase>().GetUserRealIPAddress(), BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(this.forumEditor.Text))) .RemoveMultipleWhitespace(), this.PageContext.IsGuest ? null : this.PageContext.MembershipUser.Email, out var spamResult)) { var description = $"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? "Guest" : this.PageContext.User.DisplayOrUserName())}"; switch (this.PageContext.BoardSettings.SpamMessageHandling) { case 0: this.Logger.SpamMessageDetected( this.PageContext.PageUserID, description); break; case 1: isPossibleSpamMessage = true; this.Logger.SpamMessageDetected( this.PageContext.PageUserID, $"{description}, it was flagged as unapproved post."); break; case 2: this.Logger.SpamMessageDetected( this.PageContext.PageUserID, $"{description}, post was rejected"); this.PageContext.AddLoadMessage(this.GetText("SPAM_MESSAGE"), MessageTypes.danger); return; case 3: this.Logger.SpamMessageDetected( this.PageContext.PageUserID, $"{description}, user was deleted and banned"); this.Get <IAspNetUsersHelper>().DeleteAndBanUser( this.PageContext.PageUserID, this.PageContext.MembershipUser, this.PageContext.User.IP); return; } } } if (this.Get <ISpamCheck>().ContainsSpamUrls(this.forumEditor.Text)) { return; } // update the last post time... this.Get <ISession>().LastPost = DateTime.UtcNow.AddSeconds(30); // Edit existing post var editMessage = this.PostReplyHandleEditPost(); // Check if message is approved var isApproved = editMessage.MessageFlags.IsApproved; var messageId = editMessage.ID; // vzrus^ the poll access controls are enabled and this is a new topic - we add the variables var attachPollParameter = string.Empty; var returnForum = string.Empty; if (this.PageContext.ForumPollAccess && this.PostOptions1.PollOptionVisible) { // new topic poll token attachPollParameter = $"&t={this.PageContext.PageTopicID}"; // new return forum poll token returnForum = $"&f={this.PageContext.PageForumID}"; } // Create notification emails if (isApproved) { if (attachPollParameter.IsNotSet() || !this.PostOptions1.PollChecked) { // regular redirect... BuildLink.Redirect(ForumPages.Posts, "m={0}&name={1}#post{0}", messageId, this.PageContext.PageTopicName); } else { // poll edit redirect... BuildLink.Redirect(ForumPages.PollEdit, "{0}", attachPollParameter); } } else { // Not Approved if (this.PageContext.BoardSettings.EmailModeratorsOnModeratedPost) { // not approved, notify moderators this.Get <ISendNotification>() .ToModeratorsThatMessageNeedsApproval( this.PageContext.PageForumID, messageId.ToType <int>(), isPossibleSpamMessage); } // 't' variable is required only for poll and this is a attach poll token for attachments page if (!this.PostOptions1.PollChecked) { attachPollParameter = string.Empty; } // Tell user that his message will have to be approved by a moderator var url = BuildLink.GetForumLink(this.PageContext.PageForumID, this.PageContext.PageForumName); if (this.PageContext.PageTopicID > 0 && this.topic.NumPosts > 1) { url = BuildLink.GetTopicLink(this.PageContext.PageTopicID, this.PageContext.PageTopicName); } if (attachPollParameter.Length <= 0) { BuildLink.Redirect(ForumPages.Info, "i=1&url={0}", this.Server.UrlEncode(url)); } else { BuildLink.Redirect(ForumPages.PollEdit, "&ra=1{0}{1}", attachPollParameter, returnForum); } } }
/// <summary> /// Gets the message formatted and truncated. /// </summary> /// <param name="lastMessage">The last message.</param> /// <param name="maxlength">The max length.</param> /// <returns> /// The get message formatted and truncated. /// </returns> protected string GetMessageFormattedAndTruncated([NotNull] string lastMessage, int maxlength) { return(BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(lastMessage))) .RemoveMultipleWhitespace().Truncate(maxlength)); }
/// <summary> /// The to watching users. /// </summary> /// <param name="newMessageId"> /// The new message id. /// </param> public void ToWatchingUsers(int newMessageId) { IEnumerable <TypedUserFind> usersWithAll = new List <TypedUserFind>(); if (this.BoardSettings.AllowNotificationAllPostsAllTopics) { // TODO: validate permissions! usersWithAll = LegacyDb.UserFind( YafContext.Current.PageBoardID, false, null, null, null, UserNotificationSetting.AllTopics.ToInt(), null); } // TODO : Rewrite Watch Topic code to allow watch mails in the users language, as workaround send all messages in the default board language string languageFile = this.BoardSettings.Language; string boardName = this.BoardSettings.Name; string forumEmail = this.BoardSettings.ForumEmail; foreach (var message in LegacyDb.MessageList(newMessageId)) { int userId = message.UserID ?? 0; var watchEmail = new YafTemplateEmail("TOPICPOST") { TemplateLanguageFile = languageFile }; // cleaned body as text... var bodyText = BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message.Message))) .RemoveMultipleWhitespace(); // Send track mails var subject = this.Get <ILocalization>() .GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile) .FormatWith(boardName); watchEmail.TemplateParams["{forumname}"] = boardName; watchEmail.TemplateParams["{topic}"] = HttpUtility.HtmlDecode(message.Topic); watchEmail.TemplateParams["{postedby}"] = UserMembershipHelper.GetDisplayNameFromID(userId); watchEmail.TemplateParams["{body}"] = bodyText; watchEmail.TemplateParams["{bodytruncated}"] = bodyText.Truncate(160); watchEmail.TemplateParams["{link}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.posts, true, "m={0}#post{0}", newMessageId); watchEmail.CreateWatch(message.TopicID ?? 0, userId, new MailAddress(forumEmail, boardName), subject); // create individual watch emails for all users who have All Posts on... foreach (var user in usersWithAll.Where(x => x.UserID.HasValue && x.UserID.Value != userId)) { // Make sure its not a guest if (user.ProviderUserKey == null) { continue; } var membershipUser = UserMembershipHelper.GetUser(user.ProviderUserKey); if (membershipUser == null || !membershipUser.Email.IsSet()) { continue; } watchEmail.TemplateLanguageFile = !string.IsNullOrEmpty(user.LanguageFile) ? user.LanguageFile : this.Get <ILocalization>().LanguageFileName; watchEmail.SendEmail( new MailAddress(forumEmail, boardName), new MailAddress(membershipUser.Email, membershipUser.UserName), subject, true); } } }
/// <summary> /// The post reply handle edit post. /// </summary> /// <returns> /// Returns the Message Id /// </returns> protected Tuple <Topic, Message, User, Forum> PostReplyHandleEditPost() { if (!this.PageBoardContext.ForumEditAccess) { this.Get <LinkBuilder>().AccessDenied(); } var subjectSave = string.Empty; var descriptionSave = string.Empty; var stylesSave = string.Empty; if (this.TopicSubjectTextBox.Enabled) { subjectSave = this.TopicSubjectTextBox.Text; } if (this.TopicDescriptionTextBox.Enabled) { descriptionSave = this.TopicDescriptionTextBox.Text; } if (this.TopicStylesTextBox.Enabled) { stylesSave = this.TopicStylesTextBox.Text; } // Mek Suggestion: This should be removed, resetting flags on edit is a bit lame. // Ederon : now it should be better, but all this code around forum/topic/message flags needs revamp // retrieve message flags var messageFlags = new MessageFlags(this.editedMessage.Item2.Flags) { IsHtml = this .forumEditor .UsesHTML, IsBBCode = this .forumEditor .UsesBBCode, IsPersistent = this .PostOptions1 .PersistentChecked }; this.editedMessage.Item2.Flags = messageFlags.BitValue; var isModeratorChanged = this.PageBoardContext.PageUserID != this.ownerUserId; this.GetRepository <Message>().Update( this.Priority.SelectedValue.ToType <short>(), HtmlHelper.StripHtml(BBCodeHelper.EncodeCodeBlocks(this.forumEditor.Text)), descriptionSave.Trim(), string.Empty, stylesSave.Trim(), subjectSave.Trim(), this.HtmlEncode(this.ReasonEditor.Text), isModeratorChanged, this.PageBoardContext.IsAdmin || this.PageBoardContext.ForumModeratorAccess, this.editedMessage, this.PageBoardContext.PageUserID); // Update Topic Tags?! if (this.TagsHolder.Visible) { this.GetRepository <TopicTag>().Delete(x => x.TopicID == this.PageBoardContext.PageTopicID); this.GetRepository <TopicTag>().AddTagsToTopic(this.TagsValue.Value, this.PageBoardContext.PageTopicID); } this.UpdateWatchTopic(this.PageBoardContext.PageUserID, this.PageBoardContext.PageTopicID); // remove cache if it exists... this.Get <IDataCache>() .Remove(string.Format(Constants.Cache.FirstPostCleaned, this.PageBoardContext.PageBoardID, this.PageBoardContext.PageTopicID)); return(this.editedMessage); }
public async Task <EditForumPostModel> Handle(GetEditForumPost request, CancellationToken cancellationToken) { var model = new EditForumPostModel { Id = "", ForumTopicId = request.ForumTopic.Id, IsEdit = false, ForumEditor = _forumSettings.ForumEditor, ForumName = request.Forum.Name, ForumTopicSubject = request.ForumTopic.Subject, ForumTopicSeName = request.ForumTopic.GetSeName(), IsCustomerAllowedToSubscribe = _forumService.IsCustomerAllowedToSubscribe(request.Customer), Subscribed = false, }; //subscription if (model.IsCustomerAllowedToSubscribe) { var forumSubscription = (await _forumService.GetAllSubscriptions(request.Customer.Id, "", request.ForumTopic.Id, 0, 1)).FirstOrDefault(); model.Subscribed = forumSubscription != null; } // Insert the quoted text string text = string.Empty; if (!String.IsNullOrEmpty(request.Quote)) { var quotePost = await _forumService.GetPostById(request.Quote); if (quotePost != null && quotePost.TopicId == request.ForumTopic.Id) { var quotePostText = quotePost.Text; var customer = await _customerService.GetCustomerById(quotePost.CustomerId); switch (_forumSettings.ForumEditor) { case EditorType.SimpleTextBox: text = String.Format("{0}:\n{1}\n", customer.FormatUserName(_customerSettings.CustomerNameFormat), quotePostText); break; case EditorType.BBCodeEditor: text = String.Format("[quote={0}]{1}[/quote]", customer.FormatUserName(_customerSettings.CustomerNameFormat), BBCodeHelper.RemoveQuotes(quotePostText)); break; } model.Text = text; } } return(model); }
/// <summary> /// Update character data /// </summary> private void UpdateCharacterData() { try { if (_characterId == -1) { return; } var cred = CredentialManager.GetCredentials(App.CredDb); if (cred == null || cred.UserName.Length < 1) { return; } using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'")) { var charInfo = db.GetCollection <VnCharacterInfo>(DbVnCharacter.VnCharacter.ToString()).Query() .Where(x => x.CharacterId == _characterId).FirstOrDefault(); var imagePath = $@"{App.AssetDirPath}\sources\vndb\images\characters\{VndbContentViewModel.VnId}\{Path.GetFileName(charInfo.ImageLink)}"; CharacterImage = ImageHelper.CreateBitmapFromPath(imagePath); SetupDefaultVisProps(); Name = charInfo.Name; SetGenderIcon(charInfo.Gender); if (!string.IsNullOrEmpty(charInfo.Original)) { OriginalName = new Tuple <string, Visibility>(charInfo.Original, Visibility.Visible); } if (!string.IsNullOrEmpty(charInfo.Birthday)) { Birthday = new Tuple <string, Visibility>($"{App.ResMan.GetString("BirthdayColon")} {charInfo.Birthday}", Visibility.Visible); } if (!string.IsNullOrEmpty(charInfo.Age)) { Birthday = new Tuple <string, Visibility>($"{App.ResMan.GetString("AgeColon")} {charInfo.Age}", Visibility.Visible); } if (!string.IsNullOrEmpty(charInfo.BloodType)) { BloodType = new Tuple <string, Visibility>($"{App.ResMan.GetString("BloodTypeColon")} {charInfo.BloodType}", Visibility.Visible); } if (!charInfo.Height.Equals(0)) { Height = new Tuple <string, Visibility>($"{App.ResMan.GetString("HeightColon")} {charInfo.Height}", Visibility.Visible); } if (!charInfo.Weight.Equals(0)) { Weight = new Tuple <string, Visibility>($"{App.ResMan.GetString("WeightColon")} {charInfo.Weight}", Visibility.Visible); } SetBustWaistHips(charInfo); Description = BBCodeHelper.Helper(charInfo.Description); } UpdateTraits(); } catch (Exception e) { App.Logger.Error(e, "Failed to update character data"); SentryHelper.SendException(e, null, SentryLevel.Warning); } }
/// <summary> /// Processes the item. /// </summary> /// <param name="e"> /// The <see cref="RepeaterItemEventArgs"/> instance containing the event data. /// </param> /// <returns> /// Returns the Item as string /// </returns> private string ProcessItem(RepeaterItemEventArgs e) { var dataItem = (LatestTopic)e.Item.DataItem; var currentItem = this.itemTemplate; var messageUrl = FriendlyUrlProvider.Instance().FriendlyUrl( this.yafTabInfo, $"{Globals.ApplicationURL(this.yafTabInfo.TabID)}&g=posts&m={dataItem.LastMessageID}", UrlRewriteHelper.CleanStringForURL( BoardContext.Current.Get <IBadWordReplace>().Replace(dataItem.Topic))); currentItem = currentItem.Replace("[LASTPOSTICON]", string.Empty); // Render TOPICLINK var textMessageLink = new HyperLink { Text = BoardContext.Current.Get <IBadWordReplace>() .Replace(dataItem.Topic), NavigateUrl = messageUrl }; currentItem = currentItem.Replace("[TOPICLINK]", textMessageLink.RenderToString()); // Render FORUMLINK var forumLink = new HyperLink { Text = dataItem.Forum, NavigateUrl = FriendlyUrlProvider.Instance().FriendlyUrl( this.yafTabInfo, $"{Globals.ApplicationURL(this.yafTabInfo.TabID)}&g=topics&f={dataItem.ForumID}", UrlRewriteHelper.CleanStringForURL( BoardContext.Current.Get <IBadWordReplace>() .Replace(dataItem.Forum))) }; currentItem = currentItem.Replace("[FORUMLINK]", forumLink.RenderToString()); // Render BYTEXT currentItem = currentItem.Replace( "[BYTEXT]", BoardContext.Current.Get <IHaveLocalization>().GetText("SEARCH", "BY")); // Render LASTUSERLINK // Just in case... if (dataItem.LastUserID.HasValue) { var userName = BoardContext.Current.Get <BoardSettings>().EnableDisplayName ? dataItem.LastUserDisplayName : dataItem.LastUserName; userName = new UnicodeEncoder().XSSEncode(userName); var lastUserLink = new HyperLink { Text = userName, ToolTip = userName, NavigateUrl = FriendlyUrlProvider.Instance().FriendlyUrl( this.yafTabInfo, $"{Globals.ApplicationURL(this.yafTabInfo.TabID)}&g=profile&u={dataItem.LastUserID}", userName) }; currentItem = currentItem.Replace("[LASTUSERLINK]", lastUserLink.RenderToString()); } // Render LASTMESSAGE var lastMessage = BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(dataItem.LastMessage))) .RemoveMultipleWhitespace(); try { var match = Regex.Match(currentItem, @"\[LASTMESSAGE\:(?<count>[0-9]*)\]", RegexOptions.Compiled); if (match.Success) { var messageLimit = match.Groups["count"].Value.ToType <int>(); currentItem = currentItem.Replace( $"[LASTMESSAGE:{match.Groups["count"].Value}]", lastMessage.Truncate(messageLimit)); } else { currentItem = currentItem.Replace("[LASTMESSAGE]", lastMessage); } } catch (Exception) { currentItem = currentItem.Replace("[LASTMESSAGE]", lastMessage); } // Render LASTPOSTEDDATETIME var displayDateTime = new DisplayDateTime { DateTime = (DateTime)dataItem.LastPosted }; currentItem = currentItem.Replace("[LASTPOSTEDDATETIME]", displayDateTime.RenderToString()); return(currentItem); }
/// <summary> /// The to watching users. /// </summary> /// <param name="newMessageId"> /// The new message id. /// </param> public void ToWatchingUsers(int newMessageId) { // Always send watch mails with boards default language var languageFile = this.BoardSettings.Language; var boardName = this.BoardSettings.Name; var forumEmail = this.BoardSettings.ForumEmail; var message = this.GetRepository <Message>().MessageList(newMessageId).FirstOrDefault(); var messageAuthorUserID = message.UserID ?? 0; var watchEmail = new YafTemplateEmail("TOPICPOST") { TemplateLanguageFile = languageFile }; // cleaned body as text... var bodyText = this.Get <IBadWordReplace>() .Replace(BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message.Message)))) .RemoveMultipleWhitespace(); // Send track mails var subject = string.Format( this.Get <ILocalization>().GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile), boardName); var logoUrl = $"{YafForumInfo.ForumClientFileRoot}{YafBoardFolders.Current.Logos}/{this.BoardSettings.ForumLogo}"; var themeCss = $"{this.Get<YafBoardSettings>().BaseUrlMask}{this.Get<ITheme>().BuildThemePath("bootstrap-forum.min.css")}"; watchEmail.TemplateParams["{forumname}"] = boardName; watchEmail.TemplateParams["{topic}"] = HttpUtility.HtmlDecode(this.Get <IBadWordReplace>().Replace(message.Topic)); watchEmail.TemplateParams["{postedby}"] = UserMembershipHelper.GetDisplayNameFromID(messageAuthorUserID); watchEmail.TemplateParams["{body}"] = bodyText; watchEmail.TemplateParams["{bodytruncated}"] = bodyText.Truncate(160); watchEmail.TemplateParams["{link}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.posts, true, "m={0}#post{0}", newMessageId); watchEmail.TemplateParams["{subscriptionlink}"] = YafBuildLink.GetLinkNotEscaped(ForumPages.cp_subscriptions, true); watchEmail.TemplateParams["{forumname}"] = this.BoardSettings.Name; watchEmail.TemplateParams["{forumlink}"] = $"{YafForumInfo.ForumURL}"; watchEmail.TemplateParams["{themecss}"] = themeCss; watchEmail.TemplateParams["{logo}"] = $"{this.Get<YafBoardSettings>().BaseUrlMask}{logoUrl}"; watchEmail.CreateWatch( message.TopicID ?? 0, messageAuthorUserID, new MailAddress(forumEmail, boardName), subject); if (!this.BoardSettings.AllowNotificationAllPostsAllTopics) { return; } var usersWithAll = this.GetRepository <User>().FindUserTyped( false, notificationType: UserNotificationSetting.AllTopics.ToInt()); // create individual watch emails for all users who have All Posts on... usersWithAll.Where(x => x.ID != messageAuthorUserID && x.ProviderUserKey != null).ForEach( user => { if (user.Email.IsNotSet()) { return; } watchEmail.TemplateLanguageFile = user.LanguageFile.IsSet() ? user.LanguageFile : this.Get <ILocalization>().LanguageFileName; watchEmail.SendEmail( new MailAddress(forumEmail, boardName), new MailAddress( user.Email, this.BoardSettings.EnableDisplayName ? user.DisplayName : user.Name), subject, true); }); }
/// <summary> /// Handles the PostReply click including: Replying, Editing and New post. /// </summary> /// <param name="sender"> /// The Sender Object. /// </param> /// <param name="e"> /// The Event Arguments. /// </param> protected void PostReply_Click([NotNull] object sender, [NotNull] EventArgs e) { if (!this.IsPostReplyVerified()) { return; } if (this.IsPostReplyDelay()) { return; } var isPossibleSpamMessage = false; var message = HtmlHelper.StripHtml(this.forumEditor.Text); // Check for SPAM if (!this.PageBoardContext.IsAdmin && !this.PageBoardContext.ForumModeratorAccess) { // Check content for spam if ( this.Get <ISpamCheck>().CheckPostForSpam( this.PageBoardContext.IsGuest ? this.From.Text : this.PageBoardContext.PageUser.DisplayOrUserName(), this.Get <HttpRequestBase>().GetUserRealIPAddress(), BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(this.forumEditor.Text))) .RemoveMultipleWhitespace(), this.PageBoardContext.IsGuest ? null : this.PageBoardContext.MembershipUser.Email, out var spamResult)) { var description = $@"Spam Check detected possible SPAM ({spamResult}) posted by PageUser: {(this.PageBoardContext.IsGuest ? "Guest" : this.PageBoardContext.PageUser.DisplayOrUserName())}"; switch (this.PageBoardContext.BoardSettings.SpamPostHandling) { case SpamPostHandling.DoNothing: this.Logger.SpamMessageDetected( this.PageBoardContext.PageUserID, description); break; case SpamPostHandling.FlagMessageUnapproved: this.spamApproved = false; isPossibleSpamMessage = true; this.Logger.SpamMessageDetected( this.PageBoardContext.PageUserID, $"{description}, it was flagged as unapproved post."); break; case SpamPostHandling.RejectMessage: this.Logger.SpamMessageDetected( this.PageBoardContext.PageUserID, $"S{description}, post was rejected"); this.PageBoardContext.Notify(this.GetText("SPAM_MESSAGE"), MessageTypes.danger); return; case SpamPostHandling.DeleteBanUser: this.Logger.SpamMessageDetected( this.PageBoardContext.PageUserID, $"{description}, user was deleted and banned"); this.Get <IAspNetUsersHelper>().DeleteAndBanUser( this.PageBoardContext.PageUserID, this.PageBoardContext.MembershipUser, this.PageBoardContext.PageUser.IP); return; } } } // update the last post time... this.Get <ISession>().LastPost = DateTime.UtcNow.AddSeconds(30); // New Topic var newMessage = this.PostReplyHandleNewTopic(); // Check if message is approved var isApproved = newMessage.MessageFlags.IsApproved; // vzrus^ the poll access controls are enabled and this is a new topic - we add the variables var attachPollParameter = this.PageBoardContext.ForumPollAccess && this.PostOptions1.PollOptionVisible; // Create notification emails if (isApproved) { this.Get <ISendNotification>().ToWatchingUsers(newMessage, true); if (!this.PageBoardContext.IsGuest && this.PageBoardContext.PageUser.Activity) { // Handle Mentions BBCodeHelper.FindMentions(message).ForEach( user => { var userId = this.Get <IUserDisplayName>().FindUserByName(user).ID; if (userId != this.PageBoardContext.PageUserID) { this.Get <IActivityStream>().AddMentionToStream( userId, newMessage.TopicID, newMessage.ID, this.PageBoardContext.PageUserID); } }); // Handle User Quoting BBCodeHelper.FindUserQuoting(message).ForEach( user => { var userId = this.Get <IUserDisplayName>().FindUserByName(user).ID; if (userId != this.PageBoardContext.PageUserID) { this.Get <IActivityStream>().AddQuotingToStream( userId, newMessage.TopicID, newMessage.ID, this.PageBoardContext.PageUserID); } }); this.Get <IActivityStream>().AddTopicToStream( Config.IsDotNetNuke ? this.PageBoardContext.PageForumID : this.PageBoardContext.PageUserID, newMessage.TopicID, newMessage.ID, HtmlHelper.StripHtml(this.TopicSubjectTextBox.Text), message); // Add tags if (this.TagsValue.Value.IsSet()) { this.GetRepository <TopicTag>().AddTagsToTopic(this.TagsValue.Value, newMessage.TopicID); } } if (!attachPollParameter || !this.PostOptions1.PollChecked) { // regular redirect... this.Get <LinkBuilder>().Redirect(ForumPages.Posts, new { m = newMessage.ID, name = newMessage.Topic.TopicName }); } else { // poll edit redirect... this.Get <LinkBuilder>().Redirect(ForumPages.PollEdit, new { t = newMessage.TopicID }); } } else { // Not Approved if (this.PageBoardContext.BoardSettings.EmailModeratorsOnModeratedPost) { // not approved, notify moderators this.Get <ISendNotification>() .ToModeratorsThatMessageNeedsApproval( this.PageBoardContext.PageForumID, newMessage.ID, isPossibleSpamMessage); } // 't' variable is required only for poll and this is a attach poll token for attachments page if (!this.PostOptions1.PollChecked) { attachPollParameter = false; } // Tell user that his message will have to be approved by a moderator var url = this.Get <LinkBuilder>().GetForumLink(this.PageBoardContext.PageForum); if (!attachPollParameter) { this.Get <LinkBuilder>().Redirect(ForumPages.Info, new { i = 1, url = this.Server.UrlEncode(url) }); } else { this.Get <LinkBuilder>().Redirect( ForumPages.PollEdit, new { ra = 1, t = newMessage.TopicID, f = this.PageBoardContext.PageForumID }); } } }
/// <summary> /// The get cleaned topic message. Caches cleaned topic message by TopicID. /// </summary> /// <param name="topicMessage"> /// The message to clean. /// </param> /// <param name="topicId"> /// The topic id. /// </param> /// <returns> /// The get cleaned topic message. /// </returns> public MessageCleaned GetCleanedTopicMessage([NotNull] object topicMessage, [NotNull] object topicId) { CodeContracts.VerifyNotNull(topicMessage, "topicMessage"); CodeContracts.VerifyNotNull(topicId, "topicId"); // get the common words for the language -- should be all lower case. var commonWords = this.Get <ILocalization>().GetText("COMMON", "COMMON_WORDS").StringToList(','); var cacheKey = string.Format(Constants.Cache.FirstPostCleaned, BoardContext.Current.PageBoardID, topicId); var message = new MessageCleaned(); if (!topicMessage.IsNullOrEmptyDBField()) { message = this.Get <IDataCache>().GetOrSet( cacheKey, () => { var returnMsg = topicMessage.ToString(); var keywordList = new List <string>(); if (returnMsg.IsNotSet()) { return(new MessageCleaned(returnMsg.Truncate(200), keywordList)); } // process message... clean html, strip html, remove bbcode, etc... returnMsg = BBCodeHelper .StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(returnMsg))) .RemoveMultipleWhitespace(); // encode Message For Security Reasons returnMsg = this.HttpServer.HtmlEncode(returnMsg); if (returnMsg.IsNotSet()) { returnMsg = string.Empty; } else { // get string without punctuation var keywordCleaned = new string( returnMsg.Where(c => !char.IsPunctuation(c) || char.IsWhiteSpace(c)) .ToArray()) .Trim().ToLower(); if (keywordCleaned.Length <= 5) { return(new MessageCleaned(returnMsg.Truncate(200), keywordList)); } // create keywords... keywordList = keywordCleaned.StringToList(' ', commonWords); // clean up the list a bit... keywordList = keywordList.GetNewNoEmptyStrings().GetNewNoSmallStrings(5) .Where(x => !char.IsNumber(x[0])).Distinct().ToList(); // sort... keywordList.Sort(); // get maximum of 20 keywords... if (keywordList.Count > 20) { keywordList = keywordList.GetRange(0, 20); } } return(new MessageCleaned(returnMsg.Truncate(200), keywordList)); }, TimeSpan.FromMinutes(this.Get <BoardSettings>().FirstPostCacheTimeout)); } return(message); }
/// <summary> /// Handles the PostReply click including: Replying, Editing and New post. /// </summary> /// <param name="sender"> /// The Sender Object. /// </param> /// <param name="e"> /// The Event Arguments. /// </param> protected void PostReply_Click([NotNull] object sender, [NotNull] EventArgs e) { if (!this.IsPostReplyVerified()) { return; } if (this.IsPostReplyDelay()) { return; } var isPossibleSpamMessage = false; // Check for SPAM if (!this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess && !this.PageContext.BoardSettings.SpamServiceType.Equals(0)) { // Check content for spam if ( this.Get <ISpamCheck>().CheckPostForSpam( this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName, this.Get <HttpRequestBase>().GetUserRealIPAddress(), BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(this.forumEditor.Text))) .RemoveMultipleWhitespace(), this.PageContext.IsGuest ? null : this.PageContext.User.Email, out var spamResult)) { switch (this.PageContext.BoardSettings.SpamMessageHandling) { case 0: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", $"Spam Check detected possible SPAM posted by User: {(this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName)}", EventLogTypes.SpamMessageDetected); break; case 1: this.spamApproved = false; isPossibleSpamMessage = true; this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", $"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName)}, it was flagged as unapproved post.", EventLogTypes.SpamMessageDetected); break; case 2: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", $"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName)}, post was rejected", EventLogTypes.SpamMessageDetected); this.PageContext.AddLoadMessage(this.GetText("SPAM_MESSAGE"), MessageTypes.danger); return; case 3: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", $"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName)}, user was deleted and banned", EventLogTypes.SpamMessageDetected); var userIp = new CombinedUserDataHelper( this.PageContext.CurrentUserData.Membership, this.PageContext.PageUserID).LastIP; this.Get <IAspNetUsersHelper>().DeleteAndBanUser( this.PageContext.PageUserID, this.PageContext.CurrentUserData.Membership, userIp); return; } } } // Check posts for urls if the user has only x posts if (BoardContext.Current.CurrentUserData.NumPosts <= BoardContext.Current.Get <BoardSettings>().IgnoreSpamWordCheckPostCount&& !this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess) { var urlCount = UrlHelper.CountUrls(this.forumEditor.Text); if (urlCount > this.PageContext.BoardSettings.AllowedNumberOfUrls) { var spamResult = $"The user posted {urlCount} urls but allowed only {this.PageContext.BoardSettings.AllowedNumberOfUrls}"; switch (this.PageContext.BoardSettings.SpamMessageHandling) { case 0: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", $"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName)}", EventLogTypes.SpamMessageDetected); break; case 1: this.spamApproved = false; isPossibleSpamMessage = true; this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", $"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName)}, it was flagged as unapproved post.", EventLogTypes.SpamMessageDetected); break; case 2: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", $"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName)}, post was rejected", EventLogTypes.SpamMessageDetected); this.PageContext.AddLoadMessage(this.GetText("SPAM_MESSAGE"), MessageTypes.danger); return; case 3: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", $"Spam Check detected possible SPAM ({spamResult}) posted by User: {(this.PageContext.IsGuest ? this.From.Text : this.PageContext.PageUserName)}, user was deleted and banned", EventLogTypes.SpamMessageDetected); var userIp = new CombinedUserDataHelper( this.PageContext.CurrentUserData.Membership, this.PageContext.PageUserID).LastIP; this.Get <IAspNetUsersHelper>().DeleteAndBanUser( this.PageContext.PageUserID, this.PageContext.CurrentUserData.Membership, userIp); return; } } } // update the last post time... this.Get <ISession>().LastPost = DateTime.UtcNow.AddSeconds(30); // New Topic var messageId = this.PostReplyHandleNewPost(out var newTopic); // Check if message is approved var isApproved = this.GetRepository <Message>().GetById(messageId.ToType <int>()).MessageFlags.IsApproved; // vzrus^ the poll access controls are enabled and this is a new topic - we add the variables var attachPollParameter = string.Empty; var returnForum = string.Empty; if (this.PageContext.ForumPollAccess && this.PostOptions1.PollOptionVisible) { // new topic poll token attachPollParameter = $"&t={newTopic}"; // new return forum poll token returnForum = $"&f={this.PageContext.PageForumID}"; } // Create notification emails if (isApproved) { this.Get <ISendNotification>().ToWatchingUsers(messageId.ToType <int>()); if (!this.PageContext.IsGuest && this.PageContext.CurrentUserData.Activity) { // Handle Mentions BBCodeHelper.FindMentions(this.forumEditor.Text).ForEach( user => { var userId = this.Get <IUserDisplayName>().GetId(user).Value; if (userId != this.PageContext.PageUserID) { this.Get <IActivityStream>().AddMentionToStream( userId, newTopic.ToType <int>(), messageId.ToType <int>(), this.PageContext.PageUserID); } }); // Handle User Quoting BBCodeHelper.FindUserQuoting(this.forumEditor.Text).ForEach( user => { var userId = this.Get <IUserDisplayName>().GetId(user).Value; if (userId != this.PageContext.PageUserID) { this.Get <IActivityStream>().AddQuotingToStream( userId, newTopic.ToType <int>(), messageId.ToType <int>(), this.PageContext.PageUserID); } }); this.Get <IActivityStream>().AddTopicToStream( Config.IsDotNetNuke ? this.PageContext.PageForumID : this.PageContext.PageUserID, newTopic, messageId.ToType <int>(), this.TopicSubjectTextBox.Text, this.forumEditor.Text); // Add tags if (this.Tags.Text.IsSet()) { var tags = this.Tags.Text.Split(','); var boardTags = this.GetRepository <Tag>().GetByBoardId(); tags.ForEach( tag => { var existTag = boardTags.FirstOrDefault(t => t.TagName == tag); if (existTag != null) { // add to topic this.GetRepository <TopicTag>().Add( existTag.ID, newTopic.ToType <int>()); } else { // save new Tag var newTagId = this.GetRepository <Tag>().Add(tag); // add to topic this.GetRepository <TopicTag>().Add(newTagId, newTopic.ToType <int>()); } }); } } if (attachPollParameter.IsNotSet() || !this.PostOptions1.PollChecked) { // regular redirect... BuildLink.Redirect(ForumPages.Posts, "m={0}#post{0}", messageId); } else { // poll edit redirect... BuildLink.Redirect(ForumPages.PollEdit, "{0}", attachPollParameter); } } else { // Not Approved if (this.PageContext.BoardSettings.EmailModeratorsOnModeratedPost) { // not approved, notify moderators this.Get <ISendNotification>() .ToModeratorsThatMessageNeedsApproval( this.PageContext.PageForumID, messageId.ToType <int>(), isPossibleSpamMessage); } // 't' variable is required only for poll and this is a attach poll token for attachments page if (!this.PostOptions1.PollChecked) { attachPollParameter = string.Empty; } // Tell user that his message will have to be approved by a moderator var url = BuildLink.GetLink(ForumPages.Topics, "f={0}", this.PageContext.PageForumID); if (attachPollParameter.Length <= 0) { BuildLink.Redirect(ForumPages.Info, "i=1&url={0}", this.Server.UrlEncode(url)); } else { BuildLink.Redirect(ForumPages.PollEdit, "&ra=1{0}{1}", attachPollParameter, returnForum); } } }
/// <summary> /// Handles the PostReply click including: Replying, Editing and New post. /// </summary> /// <param name="sender"> /// The Sender Object. /// </param> /// <param name="e"> /// The Event Arguments. /// </param> protected void PostReply_Click([NotNull] object sender, [NotNull] EventArgs e) { if (!this.IsPostReplyVerified()) { return; } var isPossibleSpamMessage = false; // Check for SPAM if (!this.PageBoardContext.IsAdmin && !this.PageBoardContext.ForumModeratorAccess) { // Check content for spam if ( this.Get <ISpamCheck>().CheckPostForSpam( this.PageBoardContext.IsGuest ? this.From.Text : this.PageBoardContext.PageUser.DisplayOrUserName(), this.Get <HttpRequestBase>().GetUserRealIPAddress(), BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(this.forumEditor.Text))) .RemoveMultipleWhitespace(), this.PageBoardContext.IsGuest ? null : this.PageBoardContext.MembershipUser.Email, out var spamResult)) { var description = $@"Spam Check detected possible SPAM ({spamResult}) Original message: [{this.forumEditor.Text}] posted by User: {(this.PageBoardContext.IsGuest ? "Guest" : this.PageBoardContext.PageUser.DisplayOrUserName())}"; switch (this.PageBoardContext.BoardSettings.SpamPostHandling) { case SpamPostHandling.DoNothing: this.Logger.SpamMessageDetected( this.PageBoardContext.PageUserID, description); break; case SpamPostHandling.FlagMessageUnapproved: isPossibleSpamMessage = true; this.Logger.SpamMessageDetected( this.PageBoardContext.PageUserID, $"{description}, it was flagged as unapproved post."); break; case SpamPostHandling.RejectMessage: this.Logger.SpamMessageDetected( this.PageBoardContext.PageUserID, $"{description}, post was rejected"); this.PageBoardContext.Notify(this.GetText("SPAM_MESSAGE"), MessageTypes.danger); return; case SpamPostHandling.DeleteBanUser: this.Logger.SpamMessageDetected( this.PageBoardContext.PageUserID, $"{description}, user was deleted and banned"); this.Get <IAspNetUsersHelper>().DeleteAndBanUser( this.PageBoardContext.PageUserID, this.PageBoardContext.MembershipUser, this.PageBoardContext.PageUser.IP); return; } } } // update the last post time... this.Get <ISession>().LastPost = DateTime.UtcNow.AddSeconds(30); // Edit existing post var editMessage = this.PostReplyHandleEditPost(); // Check if message is approved var isApproved = editMessage.Item2.MessageFlags.IsApproved; var messageId = editMessage.Item2.ID; // vzrus^ the poll access controls are enabled and this is a new topic - we add the variables var attachPollParameter = this.PageBoardContext.ForumPollAccess && this.PostOptions1.PollOptionVisible; // Create notification emails if (isApproved) { if (!attachPollParameter || !this.PostOptions1.PollChecked) { // regular redirect... this.Get <LinkBuilder>().Redirect(ForumPages.Posts, new { m = messageId, name = this.PageBoardContext.PageTopic.TopicName }); } else { // poll edit redirect... this.Get <LinkBuilder>().Redirect(ForumPages.PollEdit, new { t = this.PageBoardContext.PageTopicID }); } } else { // Not Approved if (this.PageBoardContext.BoardSettings.EmailModeratorsOnModeratedPost) { // not approved, notify moderators this.Get <ISendNotification>() .ToModeratorsThatMessageNeedsApproval( this.PageBoardContext.PageForumID, messageId.ToType <int>(), isPossibleSpamMessage); } // 't' variable is required only for poll and this is a attach poll token for attachments page if (!this.PostOptions1.PollChecked) { attachPollParameter = false; } // Tell user that his message will have to be approved by a moderator var url = this.Get <LinkBuilder>().GetForumLink(this.PageBoardContext.PageForum); if (this.PageBoardContext.PageTopicID > 0 && this.PageBoardContext.PageTopic.NumPosts > 1) { url = this.Get <LinkBuilder>().GetTopicLink(this.PageBoardContext.PageTopicID, this.PageBoardContext.PageTopic.TopicName); } if (!attachPollParameter) { this.Get <LinkBuilder>().Redirect(ForumPages.Info, new { i = 1, url = this.Server.UrlEncode(url) }); } else { this.Get <LinkBuilder>().Redirect( ForumPages.PollEdit, new { ra = 1, t = this.PageBoardContext.PageTopicID, f = this.PageBoardContext.PageForumID }); } } }
/// <summary> /// Prepare the forum post create model /// </summary> /// <param name="forumTopic">Forum topic</param> /// <param name="quote">Identifier of the quoted post; pass null to load the empty text</param> /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param> /// <returns>Edit forum post model</returns> public virtual EditForumPostModel PreparePostCreateModel(ForumTopic forumTopic, int?quote, bool excludeProperties) { if (forumTopic == null) { throw new ArgumentNullException(nameof(forumTopic)); } var forum = forumTopic.Forum; if (forum == null) { throw new ArgumentException("forum cannot be loaded"); } var model = new EditForumPostModel { ForumTopicId = forumTopic.Id, IsEdit = false, ForumEditor = _forumSettings.ForumEditor, ForumName = forum.Name, ForumTopicSubject = forumTopic.Subject, ForumTopicSeName = forumTopic.GetSeName(), IsCustomerAllowedToSubscribe = _forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer) }; if (!excludeProperties) { //subscription if (model.IsCustomerAllowedToSubscribe) { var forumSubscription = _forumService.GetAllSubscriptions(_workContext.CurrentCustomer.Id, 0, forumTopic.Id, 0, 1).FirstOrDefault(); model.Subscribed = forumSubscription != null; } // Insert the quoted text var text = string.Empty; if (quote.HasValue) { var quotePost = _forumService.GetPostById(quote.Value); if (quotePost != null && quotePost.TopicId == forumTopic.Id) { var quotePostText = quotePost.Text; switch (_forumSettings.ForumEditor) { case EditorType.SimpleTextBox: text = $"{quotePost.Customer.FormatUserName()}:\n{quotePostText}\n"; break; case EditorType.BBCodeEditor: text = $"[quote={quotePost.Customer.FormatUserName()}]{BBCodeHelper.RemoveQuotes(quotePostText)}[/quote]"; break; } model.Text = text; } } } return(model); }
/// <summary> /// The initializes the edited post. /// </summary> /// <param name="currentMessage"> /// The current message. /// </param> private void InitEditedPost([NotNull] Tuple <Topic, Message, User, Forum> currentMessage) { /*if (this.forumEditor.UsesHTML && currentMessage.Flags.IsBBCode) * { * // If the message is in YafBBCode but the editor uses HTML, convert the message text to HTML * currentMessage.Message = this.Get<IBBCode>().ConvertBBCodeToHtmlForEdit(currentMessage.Message); * }*/ if (this.forumEditor.UsesBBCode && currentMessage.Item2.MessageFlags.IsHtml) { // If the message is in HTML but the editor uses YafBBCode, convert the message text to BBCode currentMessage.Item2.MessageText = this.Get <IBBCode>().ConvertHtmlToBBCodeForEdit(currentMessage.Item2.MessageText); } this.forumEditor.Text = BBCodeHelper.DecodeCodeBlocks(currentMessage.Item2.MessageText); if (this.forumEditor.UsesHTML && currentMessage.Item2.MessageFlags.IsBBCode) { this.forumEditor.Text = this.Get <IBBCode>().FormatMessageWithCustomBBCode( this.forumEditor.Text, currentMessage.Item2.MessageFlags, currentMessage.Item2.UserID, currentMessage.Item2.ID); } this.Title.Text = this.GetText("EDIT"); this.PostReply.TextLocalizedTag = "SAVE"; this.PostReply.TextLocalizedPage = "COMMON"; // add topic link... this.PageLinks.AddTopic(this.PageBoardContext.PageTopic.TopicName, this.PageBoardContext.PageTopicID); // editing.. this.PageLinks.AddLink(this.GetText("EDIT")); this.TopicSubjectTextBox.Text = this.Server.HtmlDecode(this.PageBoardContext.PageTopic.TopicName); this.TopicDescriptionTextBox.Text = this.Server.HtmlDecode(this.PageBoardContext.PageTopic.Description); if (this.PageBoardContext.PageTopic.UserID == currentMessage.Item2.UserID || this.PageBoardContext.ForumModeratorAccess) { // allow editing of the topic subject this.TopicSubjectTextBox.Enabled = true; } else { this.TopicSubjectTextBox.Enabled = false; this.TopicDescriptionTextBox.Enabled = false; } // Allow the Styling of Topic Titles only for Mods or Admins if (this.PageBoardContext.BoardSettings.UseStyledTopicTitles && (this.PageBoardContext.ForumModeratorAccess || this.PageBoardContext.IsAdmin)) { this.StyleRow.Visible = true; } else { this.StyleRow.Visible = false; this.TopicStylesTextBox.Enabled = false; } this.TopicStylesTextBox.Text = this.PageBoardContext.PageTopic.Styles; this.Priority.SelectedItem.Selected = false; this.Priority.Items.FindByValue(this.PageBoardContext.PageTopic.Priority.ToString()).Selected = true; this.EditReasonRow.Visible = true; this.ReasonEditor.Text = this.Server.HtmlDecode(currentMessage.Item2.EditReason); this.PostOptions1.PersistentChecked = currentMessage.Item2.MessageFlags.IsPersistent; var topicsList = this.GetRepository <TopicTag>().List(this.PageBoardContext.PageTopicID); if (topicsList.Any()) { this.TagsValue.Value = topicsList.Select(t => t.Item2.TagName).ToDelimitedString(","); } // Ederon : 9/9/2007 - moderators can reply in locked topics if (this.PageBoardContext.PageTopic.TopicFlags.IsLocked && !this.PageBoardContext.ForumModeratorAccess) { var urlReferrer = this.Get <HttpRequestBase>().UrlReferrer; if (urlReferrer != null) { this.Get <HttpResponseBase>().Redirect(urlReferrer.ToString()); } } this.HandleUploadControls(); }
public virtual async Task <EditForumPostModel> PrepareEditForumPost(Forum forum, ForumTopic forumTopic, string quote) { var model = new EditForumPostModel { Id = "", ForumTopicId = forumTopic.Id, IsEdit = false, ForumEditor = _forumSettings.ForumEditor, ForumName = forum.Name, ForumTopicSubject = forumTopic.Subject, ForumTopicSeName = forumTopic.GetSeName(), IsCustomerAllowedToSubscribe = _forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer), Subscribed = false, }; //subscription if (model.IsCustomerAllowedToSubscribe) { var forumSubscription = (await _forumService.GetAllSubscriptions(_workContext.CurrentCustomer.Id, "", forumTopic.Id, 0, 1)).FirstOrDefault(); model.Subscribed = forumSubscription != null; } // Insert the quoted text string text = string.Empty; if (!String.IsNullOrEmpty(quote)) { var quotePost = await _forumService.GetPostById(quote); if (quotePost != null && quotePost.TopicId == forumTopic.Id) { var quotePostText = quotePost.Text; var customer = await _serviceProvider.GetRequiredService <ICustomerService>().GetCustomerById(quotePost.CustomerId); switch (_forumSettings.ForumEditor) { case EditorType.SimpleTextBox: text = String.Format("{0}:\n{1}\n", customer.FormatUserName(_customerSettings.CustomerNameFormat), quotePostText); break; case EditorType.BBCodeEditor: text = String.Format("[quote={0}]{1}[/quote]", customer.FormatUserName(_customerSettings.CustomerNameFormat), BBCodeHelper.RemoveQuotes(quotePostText)); break; } model.Text = text; } } return(model); }
/// <summary> /// Prepare the forum post create model /// </summary> /// <param name="forumTopic">Forum topic</param> /// <param name="quote">Identifier of the quoted post; pass null to load the empty text</param> /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the edit forum post model /// </returns> public virtual async Task <EditForumPostModel> PreparePostCreateModelAsync(ForumTopic forumTopic, int?quote, bool excludeProperties) { if (forumTopic == null) { throw new ArgumentNullException(nameof(forumTopic)); } var forum = await _forumService.GetForumByIdAsync(forumTopic.ForumId); if (forum == null) { throw new ArgumentException("forum cannot be loaded"); } var model = new EditForumPostModel { ForumTopicId = forumTopic.Id, IsEdit = false, ForumEditor = _forumSettings.ForumEditor, ForumName = forum.Name, ForumTopicSubject = forumTopic.Subject, ForumTopicSeName = await _forumService.GetTopicSeNameAsync(forumTopic), IsCustomerAllowedToSubscribe = await _forumService.IsCustomerAllowedToSubscribeAsync(await _workContext.GetCurrentCustomerAsync()), DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnForum }; if (!excludeProperties) { //subscription if (model.IsCustomerAllowedToSubscribe) { var forumSubscription = (await _forumService.GetAllSubscriptionsAsync((await _workContext.GetCurrentCustomerAsync()).Id, 0, forumTopic.Id, 0, 1)).FirstOrDefault(); model.Subscribed = forumSubscription != null; } // Insert the quoted text var text = string.Empty; if (quote.HasValue) { var quotePost = await _forumService.GetPostByIdAsync(quote.Value); if (quotePost != null && quotePost.TopicId == forumTopic.Id) { var customer = await _customerService.GetCustomerByIdAsync(quotePost.CustomerId); var quotePostText = quotePost.Text; switch (_forumSettings.ForumEditor) { case EditorType.SimpleTextBox: text = $"{await _customerService.FormatUsernameAsync(customer)}:\n{quotePostText}\n"; break; case EditorType.BBCodeEditor: text = $"[quote={await _customerService.FormatUsernameAsync(customer)}]{BBCodeHelper.RemoveQuotes(quotePostText)}[/quote]"; break; } model.Text = text; } } } return(model); }
/// <summary> /// Processes the item. /// </summary> /// <param name="e">The <see cref="RepeaterItemEventArgs" /> instance containing the event data.</param> /// <returns>Returns the Item as string</returns> private string ProcessItem(RepeaterItemEventArgs e) { var currentRow = (DataRowView)e.Item.DataItem; var currentItem = this.itemTemplate; var messageUrl = this.ResolveUrl( "~/Default.aspx?tabid={1}&g=posts&m={0}#post{0}".FormatWith( currentRow["LastMessageID"], this.yafTabId)); // make message url... if (Classes.Config.EnableURLRewriting) { messageUrl = Globals.ResolveUrl( "~/tabid/{0}/g/posts/m/{1}/{2}.aspx#post{1}".FormatWith( this.yafTabId, currentRow["LastMessageID"], UrlRewriteHelper.CleanStringForURL(YafContext.Current.Get <IBadWordReplace>().Replace(currentRow["Topic"].ToString())))); } // Render [LASTPOSTICON] var lastPostedImage = new ThemeImage { LocalizedTitlePage = "DEFAULT", LocalizedTitleTag = "GO_LAST_POST", LocalizedTitle = Localization.GetString("LastPost.Text", this.LocalResourceFile), ThemeTag = "TOPIC_NEW", Style = "width:16px;height:16px" }; currentItem = currentItem.Replace("[LASTPOSTICON]", lastPostedImage.RenderToString()); // Render [TOPICLINK] var textMessageLink = new HyperLink { Text = YafContext.Current.Get <IBadWordReplace>() .Replace(currentRow["Topic"].ToString()), NavigateUrl = messageUrl }; currentItem = currentItem.Replace("[TOPICLINK]", textMessageLink.RenderToString()); // Render [FORUMLINK] var forumLink = new HyperLink { Text = currentRow["Forum"].ToString(), NavigateUrl = Classes.Config.EnableURLRewriting ? Globals.ResolveUrl( "~/tabid/{0}/g/topics/f/{1}/{2}.aspx".FormatWith( this.yafTabId, currentRow["ForumID"], currentRow["Forum"])) : this.ResolveUrl( "~/Default.aspx?tabid={1}&g=topics&f={0}".FormatWith( currentRow["ForumID"], this.yafTabId)) }; currentItem = currentItem.Replace("[FORUMLINK]", forumLink.RenderToString()); // Render [BYTEXT] currentItem = currentItem.Replace( "[BYTEXT]", YafContext.Current.Get <IHaveLocalization>().GetText("SEARCH", "BY")); // Render [LASTUSERLINK] // Just in case... if (currentRow["LastUserID"] != DBNull.Value) { var userName = YafContext.Current.Get <YafBoardSettings>().EnableDisplayName ? currentRow["LastUserDisplayName"].ToString() : currentRow["LastUserName"].ToString(); userName = this.HtmlEncode(userName); var lastUserLink = new HyperLink { Text = userName, ToolTip = userName, NavigateUrl = Classes.Config.EnableURLRewriting ? Globals.ResolveUrl( "~/tabid/{0}/g/profile/u/{1}/{2}.aspx".FormatWith( this.yafTabId, currentRow["LastUserID"], userName)) : this.ResolveUrl( "~/Default.aspx?tabid={1}&g=profile&u={0}".FormatWith( currentRow["LastUserID"], this.yafTabId)) }; currentItem = currentItem.Replace("[LASTUSERLINK]", lastUserLink.RenderToString()); } // Render [LASTMESSAGE] var lastMessage = BBCodeHelper.StripBBCode( HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(currentRow["LastMessage"].ToType <string>()))) .RemoveMultipleWhitespace(); try { var match = Regex.Match(currentItem, @"\[LASTMESSAGE\:(?<count>[0-9]*)\]", RegexOptions.Compiled); if (match.Success) { var messageLimit = match.Groups["count"].Value.ToType <int>(); currentItem = currentItem.Replace( "[LASTMESSAGE:{0}]".FormatWith(match.Groups["count"].Value), lastMessage.Truncate(messageLimit)); } else { currentItem = currentItem.Replace("[LASTMESSAGE]", lastMessage); } } catch (Exception) { currentItem = currentItem.Replace("[LASTMESSAGE]", lastMessage); } // Render [LASTPOSTEDDATETIME] var displayDateTime = new DisplayDateTime { DateTime = currentRow["LastPosted"].ToType <DateTime>() }; currentItem = currentItem.Replace("[LASTPOSTEDDATETIME]", displayDateTime.RenderToString()); return(currentItem); }
/// <summary> /// The to watching users. /// </summary> /// <param name="newMessageId"> /// The new message id. /// </param> public void ToWatchingUsers(int newMessageId) { IList <User> usersWithAll = new List <User>(); if (this.BoardSettings.AllowNotificationAllPostsAllTopics) { usersWithAll = this.GetRepository <User>() .FindUserTyped(filter: false, notificationType: UserNotificationSetting.AllTopics.ToInt()); } // TODO : Rewrite Watch Topic code to allow watch mails in the users language, as workaround send all messages in the default board language var languageFile = this.BoardSettings.Language; var boardName = this.BoardSettings.Name; var forumEmail = this.BoardSettings.ForumEmail; var message = LegacyDb.MessageList(newMessageId).FirstOrDefault(); var messageAuthorUserID = message.UserID ?? 0; var watchEmail = new YafTemplateEmail("TOPICPOST") { TemplateLanguageFile = languageFile }; // cleaned body as text... var bodyText = BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message.Message))) .RemoveMultipleWhitespace(); // Send track mails var subject = this.Get <ILocalization>() .GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile) .FormatWith(boardName); watchEmail.TemplateParams["{forumname}"] = boardName; watchEmail.TemplateParams["{topic}"] = HttpUtility.HtmlDecode(message.Topic); watchEmail.TemplateParams["{postedby}"] = UserMembershipHelper.GetDisplayNameFromID(messageAuthorUserID); watchEmail.TemplateParams["{body}"] = bodyText; watchEmail.TemplateParams["{bodytruncated}"] = bodyText.Truncate(160); watchEmail.TemplateParams["{link}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.posts, true, "m={0}#post{0}", newMessageId); watchEmail.CreateWatch( message.TopicID ?? 0, messageAuthorUserID, new MailAddress(forumEmail, boardName), subject); // create individual watch emails for all users who have All Posts on... foreach (var user in usersWithAll.Where(x => x.UserID != messageAuthorUserID && x.ProviderUserKey != null)) { var membershipUser = UserMembershipHelper.GetUser(user.ProviderUserKey); if (membershipUser == null || membershipUser.Email.IsNotSet()) { continue; } watchEmail.TemplateLanguageFile = user.LanguageFile.IsSet() ? user.LanguageFile : this.Get <ILocalization>().LanguageFileName; watchEmail.SendEmail( new MailAddress(forumEmail, boardName), new MailAddress(membershipUser.Email, membershipUser.UserName), subject, true); } }