Example #1
0
 /// <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));
 }
Example #2
0
        protected string GetThreadedRow([NotNull] object o)
        {
            var row       = (DataRow)o;
            int messageId = (int)row["MessageID"];

            if (!this.IsThreaded || this.CurrentMessage == messageId)
            {
                return(string.Empty);
            }

            var html = new StringBuilder();

            // Threaded
            string brief =
                StringHelper.RemoveMultipleWhitespace(
                    BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(row["Message"].ToString()))));

            brief = StringHelper.Truncate(this.Get <YafBadWordReplace>().Replace(brief), 100);
            brief = YafFormatMessage.AddSmiles(brief);

            if (brief.IsNotSet())
            {
                brief = "...";
            }

            html.AppendFormat(@"<tr class=""post""><td colspan=""3"" style=""white-space:nowrap;"">");
            html.AppendFormat(this.GetIndentImage(row["Indent"]));

            string avatarUrl = this.Get <YafAvatars>().GetAvatarUrlForUser(row.Field <int>("UserID"));

            if (avatarUrl.IsNotSet())
            {
                avatarUrl = "{0}images/noavatar.gif".FormatWith(YafForumInfo.ForumClientFileRoot);
            }

            html.Append(@"<span class=""threadedRowCollapsed"">");
            html.AppendFormat(@"<img src=""{0}"" alt="""" class=""avatarimage"" />", avatarUrl);
            html.AppendFormat(@"<a href=""{0}"" class=""threadUrl"">{1}</a>", YafBuildLink.GetLink(ForumPages.posts, "m={0}#post{0}", messageId), brief);

            html.Append(" (");
            html.Append(
                new UserLink()
            {
                ID = "UserLinkForRow{0}".FormatWith(messageId), UserID = row.Field <int>("UserID")
            }.
                RenderToString());

            html.AppendFormat(" - {0})</span>",
                              new DisplayDateTime()
            {
                DateTime = row["Posted"], Format = DateTimeFormat.BothTopic
            }.
                              RenderToString());

            html.AppendFormat("</td></tr>");

            return(html.ToString());
        }
        public void StripBBCode_Test()
        {
            const string TestMessage =
                "This is a test text containing [b]bold[/b] and [i]italic[i] text and other bbcodes [img]http://test.com/testimage.jpg[/img]";

            Assert.AreEqual(
                "This is a test text containing bold and italic text and other bbcodes http://test.com/testimage.jpg",
                BBCodeHelper.StripBBCode(TestMessage));
        }
Example #4
0
        /// <summary>
        /// Adds the Reply 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 AddReplyToStream(int forumID, long topicID, int messageID, string topicTitle, string message)
        {
            message = BBCodeHelper.StripBBCode(
                HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message)))
                      .RemoveMultipleWhitespace();

            var user           = UserController.GetCurrentUserInfo();
            var portalSettings = PortalSettings.Current;

            var ji = new JournalItem
            {
                PortalId  = portalSettings.PortalId,
                ProfileId = user.UserID,
                UserId    = user.UserID,
                Title     = topicTitle,
                ItemData  =
                    new ItemData
                {
                    Url =
                        YafBuildLink.GetLink(
                            ForumPages.posts,
                            "m={0}#post{0}",
                            messageID)
                },
                Summary       = message.Truncate(150),
                Body          = message,
                JournalTypeId = 6,
                SecuritySet   = this.GetSecuritySet(forumID, portalSettings.PortalId),
                ObjectKey     =
                    "{0}:{1}:{2}".FormatWith(
                        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);
        }
Example #5
0
        /// <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()
                                  ? $"@{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 Re-tweet Directly 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 auth = new OAuthTwitter
                {
                    ConsumerKey    = Config.TwitterConsumerKey,
                    ConsumerSecret = Config.TwitterConsumerSecret,
                    Token          = this.Get <IYafSession>().TwitterToken,
                    TokenSecret    = this.Get <IYafSession>().TwitterTokenSecret
                };

                var tweets = new TweetAPI(auth);

                tweets.UpdateStatus(
                    TweetAPI.ResponseFormat.json,
                    this.Server.UrlEncode(
                        string.Format("RT {1}: {0} {2}", twitterMsg.Truncate(100), twitterName, topicUrl)),
                    string.Empty);
            }
            else
            {
                this.Get <HttpResponseBase>().Redirect(
                    $"http://twitter.com/share?url={this.Server.UrlEncode(topicUrl)}&text={this.Server.UrlEncode(s: $"RT {twitterName}: {twitterMsg.Truncate(100)}")}");
            }
Example #6
0
        /// <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, int 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 = BoardContext.Current.Get <LinkBuilder>().GetTopicLink(topicID, topicTitle)
                },
                Summary       = message.Truncate(150),
                Body          = message,
                JournalTypeId = 5,
                SecuritySet   = GetSecuritySet(forumID, portalSettings.PortalId),
                ObjectKey     = $"{forumID}:{topicID}:{messageID}"
            };

            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);
        }
Example #7
0
        /// <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);
                }
            }
        }
Example #8
0
        /// <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);
                }
            }
        }
Example #9
0
        /// <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);
        }
Example #10
0
        /// <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);
            }
        }
Example #11
0
        /// <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);
            }
        }
Example #12
0
    /// <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 });
            }
        }
    }
Example #13
0
        /// <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);
            });
        }
Example #15
0
    /// <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 });
            }
        }
    }
Example #16
0
        /// <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>
        /// 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);
        }
Example #18
0
        /// <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));
            }
        }