Beispiel #1
0
        /// <summary>
        ///     Sends the pm message.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="receiver">The receiver.</param>
        /// <param name="title">The title.</param>
        /// <param name="body">The body.</param>
        /// <param name="messageId">The message identifier.</param>
        public static void SendPmMessage(int? sender, int? receiver, string title, string body, int messageId = -1)
        {
            Contract.Requires<NullReferenceException>(sender != null);
            Contract.Requires<NullReferenceException>(receiver != null);
            Contract.Requires<NullReferenceException>(!string.IsNullOrEmpty(title));
            Contract.Requires<NullReferenceException>(!string.IsNullOrEmpty(body));
            var messageFlags = new MessageFlags
            {
                IsHtml = true,
                IsBBCode = true
            };

            LegacyDb.pmessage_save(
                sender,
                receiver,
                title,
                body,
                messageFlags.BitValue,
                messageId);
            try
            {
                _notifer.NotifyPrivateMessage((int) receiver, (int) sender, "You received a private message now.");
            }
            catch (Exception)
            {
            }
        }
Beispiel #2
0
        /// <summary>
        /// Format message.
        /// </summary>
        /// <param name="row">
        /// Message data row.
        /// </param>
        /// <returns>
        /// Formatted string with escaped HTML markup and formatted.
        /// </returns>
        protected string FormatMessage([NotNull] DataRowView row)
        {
            // get message flags
            var messageFlags = new MessageFlags(row["Flags"]);

            // message
            string msg;

            // format message?
            if (messageFlags.NotFormatted)
            {
                // just encode it for HTML output
                msg = this.HtmlEncode(row["Message"].ToString());
            }
            else
            {
                // fully format message (YafBBCode, smilies)
                msg = this.Get<IFormatMessage>().FormatMessage(
                  row["Message"].ToString(), messageFlags, Convert.ToBoolean(row["IsModeratorChanged"]));
            }

            // return formatted message
            return msg;
        }
Beispiel #3
0
        /// <summary>
        /// The render signature.
        /// </summary>
        /// <param name="writer">
        /// The writer.
        /// </param>
        protected void RenderSignature([NotNull] HtmlTextWriter writer)
        {
            if (!this.DisplayUserID.HasValue)
            {
                return;
            }

            // don't allow any HTML on signatures
            var signatureFlags = new MessageFlags { IsHtml = false };

            string signatureRendered = this.Get<IFormatMessage>().FormatMessage(this.Signature, signatureFlags);

            this.RenderModulesInBBCode(writer, signatureRendered, signatureFlags, this.DisplayUserID, this.MessageID);
        }
Beispiel #4
0
        /// <summary>
        /// The quick reply_ click.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void QuickReply_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            if (!this.PageContext.ForumReplyAccess
                || (this._topicFlags.IsLocked && !this.PageContext.ForumModeratorAccess))
            {
                YafBuildLink.AccessDenied();
            }

            if (this._quickReplyEditor.Text.Length <= 0)
            {
                this.PageContext.AddLoadMessage(this.GetText("EMPTY_MESSAGE"), MessageTypes.Warning);
                return;
            }

            // No need to check whitespace if they are actually posting something
            if (this.Get<YafBoardSettings>().MaxPostSize > 0
                && this._quickReplyEditor.Text.Length >= this.Get<YafBoardSettings>().MaxPostSize)
            {
                this.PageContext.AddLoadMessage(this.GetText("ISEXCEEDED"), MessageTypes.Warning);
                return;
            }

            if (((this.PageContext.IsGuest && this.Get<YafBoardSettings>().EnableCaptchaForGuests)
                 || (this.Get<YafBoardSettings>().EnableCaptchaForPost && !this.PageContext.IsCaptchaExcluded))
                && !CaptchaHelper.IsValid(this.tbCaptcha.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("BAD_CAPTCHA"), MessageTypes.Warning);
                return;
            }

            if (!(this.PageContext.IsAdmin || this.PageContext.ForumModeratorAccess)
                && this.Get<YafBoardSettings>().PostFloodDelay > 0)
            {
                if (YafContext.Current.Get<IYafSession>().LastPost
                    > DateTime.UtcNow.AddSeconds(-this.Get<YafBoardSettings>().PostFloodDelay))
                {
                    this.PageContext.AddLoadMessage(
                        this.GetTextFormatted(
                            "wait",
                            (YafContext.Current.Get<IYafSession>().LastPost
                             - DateTime.UtcNow.AddSeconds(-this.Get<YafBoardSettings>().PostFloodDelay)).Seconds),
                        MessageTypes.Warning);
                    return;
                }
            }

            YafContext.Current.Get<IYafSession>().LastPost = DateTime.UtcNow;

            // post message...
            long messageId = 0;
            object replyTo = -1;
            string msg = this._quickReplyEditor.Text;
            long topicID = this.PageContext.PageTopicID;

            // SPAM Check

            // Check if Forum is Moderated
            DataRow forumInfo;
            bool isForumModerated = false;

            using (DataTable dt = LegacyDb.forum_list(this.PageContext.PageBoardID, this.PageContext.PageForumID))
            {
                forumInfo = dt.Rows[0];
            }

            if (forumInfo != null)
            {
                isForumModerated = this.CheckForumModerateStatus(forumInfo);
            }

            var spamApproved = true;
            var isPossibleSpamMessage = false;

            // Check for SPAM
            if (!this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess && !this.Get<YafBoardSettings>().SpamServiceType.Equals(0))
            {
                var spamChecker = new YafSpamCheck();
                string spamResult;

                // Check content for spam
                if (spamChecker.CheckPostForSpam(
                    this.PageContext.IsGuest ? "Guest" : this.PageContext.PageUserName,
                    YafContext.Current.Get<HttpRequestBase>().GetUserRealIPAddress(),
                    this._quickReplyEditor.Text,
                    this.PageContext.IsGuest ? null : this.PageContext.User.Email,
                    out spamResult))
                {
                    switch (this.Get<YafBoardSettings>().SpamMessageHandling)
                    {
                        case 0:
                            this.Logger.Log(
                                this.PageContext.PageUserID,
                                "Spam Message Detected",
                                "Spam Check detected possible SPAM ({1}) posted by User: {0}"
                                    .FormatWith(
                                        this.PageContext.IsGuest ? "Guest" : this.PageContext.PageUserName,
                                        spamResult),
                                EventLogTypes.SpamMessageDetected);
                            break;
                        case 1:
                            spamApproved = false;
                            isPossibleSpamMessage = true;
                            this.Logger.Log(
                                this.PageContext.PageUserID,
                                "Spam Message Detected",
                                "Spam Check detected possible SPAM ({1}) posted by User: {0}, it was flagged as unapproved post"
                                    .FormatWith(
                                        this.PageContext.IsGuest ? "Guest" : this.PageContext.PageUserName,
                                        spamResult),
                                EventLogTypes.SpamMessageDetected);
                            break;
                        case 2:
                            this.Logger.Log(
                                this.PageContext.PageUserID,
                                "Spam Message Detected",
                                "Spam Check detected possible SPAM ({1}) posted by User: {0}, post was rejected"
                                    .FormatWith(
                                        this.PageContext.IsGuest ? "Guest" : this.PageContext.PageUserName,
                                        spamResult),
                                EventLogTypes.SpamMessageDetected);
                            this.PageContext.AddLoadMessage(this.GetText("SPAM_MESSAGE"), MessageTypes.Error);
                            return;
                        case 3:
                            this.Logger.Log(
                                this.PageContext.PageUserID,
                                "Spam Message Detected",
                                "Spam Check detected possible SPAM ({1}) posted by User: {0}, user was deleted and bannded"
                                    .FormatWith(
                                        this.PageContext.IsGuest ? "Guest" : this.PageContext.PageUserName,
                                        spamResult),
                                EventLogTypes.SpamMessageDetected);
                            
                            var userIp =
                                new CombinedUserDataHelper(
                                    this.PageContext.CurrentUserData.Membership,
                                    this.PageContext.PageUserID).LastIP;

                            UserMembershipHelper.DeleteAndBanUser(
                                this.PageContext.PageUserID,
                                this.PageContext.CurrentUserData.Membership,
                                userIp);

                            return;
                    }
                }
            }

            // If Forum is Moderated
            if (isForumModerated)
            {
                spamApproved = false;
            }

            // Bypass Approval if Admin or Moderator
            if (this.PageContext.IsAdmin || this.PageContext.ForumModeratorAccess)
            {
                spamApproved = true;
            }

            var tFlags = new MessageFlags
                {
                    IsHtml = this._quickReplyEditor.UsesHTML,
                    IsBBCode = this._quickReplyEditor.UsesBBCode,
                    IsApproved = spamApproved
                };

            // Bypass Approval if Admin or Moderator.
            if (
                !LegacyDb.message_save(
                    topicID,
                    this.PageContext.PageUserID,
                    msg,
                    null,
                    this.Get<HttpRequestBase>().GetUserRealIPAddress(),
                    null,
                    replyTo,
                    tFlags.BitValue,
                    ref messageId))
            {
                topicID = 0;
            }

            // Check to see if the user has enabled "auto watch topic" option in his/her profile.
            if (this.PageContext.CurrentUserData.AutoWatchTopics)
            {
                var watchTopicId = this.GetRepository<WatchTopic>().Check(this.PageContext.PageUserID, this.PageContext.PageTopicID);

                if (!watchTopicId.HasValue)
                {
                    // subscribe to this topic
                    this.GetRepository<WatchTopic>().Add(this.PageContext.PageUserID, this.PageContext.PageTopicID);
                }
            }

            bool bApproved = false;

            using (DataTable dt = LegacyDb.message_list(messageId))
            {
                foreach (DataRow row in dt.Rows)
                {
                    bApproved = ((int)row["Flags"] & 16) == 16;
                }
            }

            if (bApproved)
            {
                // send new post notification to users watching this topic/forum
                this.Get<ISendNotification>().ToWatchingUsers(messageId.ToType<int>());

                if (Config.IsDotNetNuke && !this.PageContext.IsGuest)
                {
                    this.Get<IActivityStream>()
                           .AddReplyToStream(
                               this.PageContext.PageForumID,
                               this.PageContext.PageTopicID,
                               messageId.ToType<int>(),
                               this.PageContext.PageTopicName,
                               msg);
                }

                // redirect to newly posted message
                YafBuildLink.Redirect(ForumPages.posts, "m={0}&#post{0}", messageId);
            }
            else
            {
                if (this.Get<YafBoardSettings>().EmailModeratorsOnModeratedPost)
                {
                    // not approved, notifiy moderators
                    this.Get<ISendNotification>()
                        .ToModeratorsThatMessageNeedsApproval(
                            this.PageContext.PageForumID,
                            messageId.ToType<int>(),
                            isPossibleSpamMessage);
                }

                string url = YafBuildLink.GetLink(ForumPages.topics, "f={0}", this.PageContext.PageForumID);
                if (Config.IsRainbow)
                {
                    YafBuildLink.Redirect(ForumPages.info, "i=1");
                }
                else
                {
                    YafBuildLink.Redirect(ForumPages.info, "i=1&url={0}", this.Server.UrlEncode(url));
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// The get message flags.
        /// </summary>
        /// <returns>
        /// The method returns message flags.
        /// </returns>
        private int GetMessageFlags()
        {
            var editorModule = this.PageContext.Get<IModuleManager<ForumEditor>>().GetBy(this.Get<YafBoardSettings>().ForumEditor);

            var topicFlags = new MessageFlags
                {
                    IsHtml = editorModule.UsesHTML,
                    IsBBCode = editorModule.UsesBBCode,
                    IsPersistent = false,
                    IsApproved = this.PageContext.IsAdmin
                };

            // Bypass Approval if Admin or Moderator.
            return topicFlags.BitValue;
        }
Beispiel #6
0
        /// <summary>
        /// The post reply handle reply to topic.
        /// </summary>
        /// <param name="isSpamApproved">
        /// The is Spam Approved. 
        /// </param>
        /// <returns>
        /// Returns the Message Id. 
        /// </returns>
        protected long PostReplyHandleReplyToTopic(bool isSpamApproved)
        {
            long messageId = 0;

            if (!this.PageContext.ForumReplyAccess)
            {
                YafBuildLink.AccessDenied();
            }

            // Check if Forum is Moderated
            DataRow forumInfo;
            bool isForumModerated = false;

            using (DataTable dt = LegacyDb.forum_list(this.PageContext.PageBoardID, this.PageContext.PageForumID))
            {
                forumInfo = dt.Rows[0];
            }

            if (forumInfo != null)
            {
                isForumModerated = forumInfo["Flags"].BinaryAnd(ForumFlags.Flags.IsModerated);
            }

            // If Forum is Moderated
            if (isForumModerated)
            {
                isSpamApproved = false;
            }

            // Bypass Approval if Admin or Moderator
            if (this.PageContext.IsAdmin || this.PageContext.ForumModeratorAccess)
            {
                isSpamApproved = true;
            }

            object replyTo = (this.QuotedMessageID != null) ? this.QuotedMessageID.Value : -1;

            // make message flags
            var messageFlags = new MessageFlags
                               {
                                   IsHtml = this._forumEditor.UsesHTML,
                                   IsBBCode = this._forumEditor.UsesBBCode,
                                   IsPersistent = this.PostOptions1.PersistantChecked,
                                   IsApproved = isSpamApproved
                               };

            LegacyDb.message_save(
                this.TopicID.Value,
                this.PageContext.PageUserID,
                this._forumEditor.Text,
                this.User != null ? null : this.From.Text,
                this.Get<HttpRequestBase>().GetUserRealIPAddress(),
                DateTime.UtcNow,
                replyTo,
                messageFlags.BitValue,
                ref messageId);

            this.UpdateWatchTopic(this.PageContext.PageUserID, this.PageContext.PageTopicID);

            if (messageFlags.IsApproved)
            {
                this.Get<IDataCache>().Remove(Constants.Cache.BoardStats);
                this.Get<IDataCache>().Remove(Constants.Cache.BoardUserStats);
            }

            return messageId;
        }
Beispiel #7
0
        /// <summary>
        /// The post reply handle new post.
        /// </summary>
        /// <param name="topicId">
        /// The topic Id. 
        /// </param>
        /// <returns>
        /// Returns the Message Id. 
        /// </returns>
        protected long PostReplyHandleNewPost(out long topicId)
        {
            long messageId = 0;

            if (!this.PageContext.ForumPostAccess)
            {
                YafBuildLink.AccessDenied();
            }

            // Check if Forum is Moderated
            DataRow forumInfo;
            bool isForumModerated = false;

            using (DataTable dt = LegacyDb.forum_list(this.PageContext.PageBoardID, this.PageContext.PageForumID))
            {
                forumInfo = dt.Rows[0];
            }

            if (forumInfo != null)
            {
                isForumModerated = forumInfo["Flags"].BinaryAnd(ForumFlags.Flags.IsModerated);
            }

            // If Forum is Moderated
            if (isForumModerated)
            {
                this.spamApproved = false;
            }

            // Bypass Approval if Admin or Moderator
            if (this.PageContext.IsAdmin || this.PageContext.ForumModeratorAccess)
            {
                this.spamApproved = true;
            }

            // make message flags
            var messageFlags = new MessageFlags
                               {
                                   IsHtml = this._forumEditor.UsesHTML,
                                   IsBBCode = this._forumEditor.UsesBBCode,
                                   IsPersistent = this.PostOptions1.PersistantChecked,
                                   IsApproved = this.spamApproved
                               };

            string blogPostID = this.HandlePostToBlog(this._forumEditor.Text, this.TopicSubjectTextBox.Text);

            // Save to Db
            topicId = LegacyDb.topic_save(
                this.PageContext.PageForumID,
                this.TopicSubjectTextBox.Text.Trim(),
                this.TopicStatus.SelectedValue.Equals("-1") || this.TopicStatus.SelectedIndex.Equals(0)
                    ? string.Empty
                    : this.TopicStatus.SelectedValue,
                this.TopicStylesTextBox.Text.Trim(),
                this.TopicDescriptionTextBox.Text.Trim(),
                this._forumEditor.Text,
                this.PageContext.PageUserID,
                this.Priority.SelectedValue,
                this.User != null ? null : this.From.Text,
                this.Get<HttpRequestBase>().GetUserRealIPAddress(),
                DateTime.UtcNow,
                blogPostID,
                messageFlags.BitValue,
                ref messageId);

            this.UpdateWatchTopic(this.PageContext.PageUserID, (int)topicId);

            // clear caches as stats changed
            if (messageFlags.IsApproved)
            {
                this.Get<IDataCache>().Remove(Constants.Cache.BoardStats);
                this.Get<IDataCache>().Remove(Constants.Cache.BoardUserStats);
            }

            return messageId;
        }
Beispiel #8
0
        /// <summary>
        /// The post reply handle edit post.
        /// </summary>
        /// <returns>
        /// Returns the Message Id 
        /// </returns>
        protected long PostReplyHandleEditPost()
        {
            if (!this.PageContext.ForumEditAccess)
            {
                YafBuildLink.AccessDenied();
            }

            string subjectSave = string.Empty;
            string descriptionSave = string.Empty;
            string 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(LegacyDb.message_list(this.EditMessageID).Rows[0]["Flags"])
                               {
                                   IsHtml =
                                       this
                                       ._forumEditor
                                       .UsesHTML,
                                   IsBBCode
                                       =
                                       this
                                       ._forumEditor
                                       .UsesBBCode,
                                   IsPersistent
                                       =
                                       this
                                       .PostOptions1
                                       .PersistantChecked
                               };

            bool isModeratorChanged = this.PageContext.PageUserID != this._ownerUserId;

            LegacyDb.message_update(
                this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("m"),
                this.Priority.SelectedValue,
                this._forumEditor.Text.Trim(),
                descriptionSave.Trim(),
                this.TopicStatus.SelectedValue.Equals("-1") || this.TopicStatus.SelectedIndex.Equals(0)
                    ? string.Empty
                    : this.TopicStatus.SelectedValue,
                stylesSave.Trim(),
                subjectSave.Trim(),
                messageFlags.BitValue,
                this.HtmlEncode(this.ReasonEditor.Text),
                isModeratorChanged,
                this.PageContext.IsAdmin || this.PageContext.ForumModeratorAccess,
                this.OriginalMessage,
                this.PageContext.PageUserID);

            long messageId = this.EditMessageID.Value;

            this.UpdateWatchTopic(this.PageContext.PageUserID, this.PageContext.PageTopicID);

            this.HandlePostToBlog(this._forumEditor.Text, this.TopicSubjectTextBox.Text);

            // remove cache if it exists...
            this.Get<IDataCache>()
                .Remove(Constants.Cache.FirstPostCleaned.FormatWith(this.PageContext.PageBoardID, this.TopicID));

            return messageId;
        }
Beispiel #9
0
        /// <summary>
        /// Send Private Message
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            var replyTo = this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("p").IsSet()
                              ? this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("p").ToType<int>()
                              : -1;

            // recipient was set in dropdown
            if (this.ToList.Visible)
            {
                this.To.Text = this.ToList.SelectedItem.Text;
            }

            if (this.To.Text.Length <= 0)
            {
                // recipient is required field
                YafContext.Current.AddLoadMessage(this.GetText("need_to"), MessageTypes.Warning);
                return;
            }

            // subject is required
            if (this.PmSubjectTextBox.Text.Trim().Length <= 0)
            {
                YafContext.Current.AddLoadMessage(this.GetText("need_subject"), MessageTypes.Warning);
                return;
            }

            // message is required
            if (this._editor.Text.Trim().Length <= 0)
            {
                YafContext.Current.AddLoadMessage(this.GetText("need_message"), MessageTypes.Warning);
                return;
            }

            if (this.ToList.SelectedItem != null && this.ToList.SelectedItem.Value == "0")
            {
                // administrator is sending PMs tp all users           
                string body = this._editor.Text;
                var messageFlags = new MessageFlags
                                       {
                                           IsHtml = this._editor.UsesHTML,
                                           IsBBCode = this._editor.UsesBBCode
                                       };

                // test user's PM count
                if (!this.VerifyMessageAllowed(1))
                {
                    return;
                }

                var receivingPMInfo = LegacyDb.user_pmcount(replyTo).Rows[0];

                // test receiving user's PM count
                if (!YafContext.Current.IsAdmin
                    || !(bool)
                        Convert.ChangeType(UserMembershipHelper.GetUserRowForID(replyTo, true)["IsAdmin"], typeof(bool)))
                {
                    if (receivingPMInfo["NumberTotal"].ToType<int>() + 1
                        <= receivingPMInfo["NumberAllowed"].ToType<int>())
                    {
                        return;
                    }

                    // recipient has full PM box
                    YafContext.Current.AddLoadMessage(
                        this.GetTextFormatted("RECIPIENTS_PMBOX_FULL", this.To.Text),
                        MessageTypes.Error);
                    return;
                }

                LegacyDb.pmessage_save(
                    YafContext.Current.PageUserID,
                    0,
                    this.PmSubjectTextBox.Text,
                    body,
                    messageFlags.BitValue,
                    replyTo);

                // redirect to outbox (sent items), not control panel
                YafBuildLink.Redirect(ForumPages.cp_pm, "v={0}", "out");
            }
            else
            {
                // remove all abundant whitespaces and separators
                var rx = new Regex(@";(\s|;)*;");
                this.To.Text = rx.Replace(this.To.Text, ";");

                if (this.To.Text.StartsWith(";"))
                {
                    this.To.Text = this.To.Text.Substring(1);
                }

                if (this.To.Text.EndsWith(";"))
                {
                    this.To.Text = this.To.Text.Substring(0, this.To.Text.Length - 1);
                }

                rx = new Regex(@"\s*;\s*");
                this.To.Text = rx.Replace(this.To.Text, ";");

                // list of recipients
                var recipients = new List<string>(this.To.Text.Trim().Split(';'));

                if (recipients.Count > this.Get<YafBoardSettings>().PrivateMessageMaxRecipients
                    && !YafContext.Current.IsAdmin && this.Get<YafBoardSettings>().PrivateMessageMaxRecipients != 0)
                {
                    // to many recipients
                    YafContext.Current.AddLoadMessage(
                        this.GetTextFormatted(
                            "TOO_MANY_RECIPIENTS",
                            this.Get<YafBoardSettings>().PrivateMessageMaxRecipients),
                        MessageTypes.Warning);

                    return;
                }

                if (!this.VerifyMessageAllowed(recipients.Count))
                {
                    return;
                }

                // list of recipient's ids
                var recipientIds = new List<int>();

                // get recipients' IDs
                foreach (string recipient in recipients)
                {
                    int? userId = this.Get<IUserDisplayName>().GetId(recipient);

                    if (!userId.HasValue)
                    {
                        YafContext.Current.AddLoadMessage(
                            this.GetTextFormatted("NO_SUCH_USER", recipient),
                            MessageTypes.Warning);
                        return;
                    }

                    if (UserMembershipHelper.IsGuestUser(userId.Value))
                    {
                        YafContext.Current.AddLoadMessage(this.GetText("NOT_GUEST"), MessageTypes.Error);
                        return;
                    }

                    // get recipient's ID from the database
                    if (!recipientIds.Contains(userId.Value))
                    {
                        recipientIds.Add(userId.Value);
                    }

                    var receivingPMInfo = LegacyDb.user_pmcount(userId.Value).Rows[0];

                    // test receiving user's PM count
                    if ((receivingPMInfo["NumberTotal"].ToType<int>() + 1
                         < receivingPMInfo["NumberAllowed"].ToType<int>()) || YafContext.Current.IsAdmin
                        || (bool)
                           Convert.ChangeType(
                               UserMembershipHelper.GetUserRowForID(userId.Value, true)["IsAdmin"],
                               typeof(bool)))
                    {
                        continue;
                    }

                    // recipient has full PM box
                    YafContext.Current.AddLoadMessage(
                        this.GetTextFormatted("RECIPIENTS_PMBOX_FULL", recipient),
                        MessageTypes.Error);
                    return;
                }

                // send PM to all recipients
                foreach (var userId in recipientIds)
                {
                    string body = this._editor.Text;

                    var messageFlags = new MessageFlags
                                           {
                                               IsHtml = this._editor.UsesHTML,
                                               IsBBCode = this._editor.UsesBBCode
                                           };

                    LegacyDb.pmessage_save(
                        YafContext.Current.PageUserID,
                        userId,
                        this.PmSubjectTextBox.Text,
                        body,
                        messageFlags.BitValue,
                        replyTo);

                    // reset reciever's lazy data as he should be informed at once
                    this.Get<IDataCache>().Remove(Constants.Cache.ActiveUserLazyData.FormatWith(userId));

                    if (this.Get<YafBoardSettings>().AllowPMEmailNotification)
                    {
                        this.Get<ISendNotification>()
                            .ToPrivateMessageRecipient(userId, this.PmSubjectTextBox.Text.Trim());
                    }
                }

                // redirect to outbox (sent items), not control panel
                YafBuildLink.Redirect(ForumPages.cp_pm, "v={0}", "out");
            }
        }
Beispiel #10
0
        /// <summary>
        /// The get shout box messages.
        /// </summary>
        /// <param name="boardId">
        /// The board id.
        /// </param>
        /// <returns>
        /// Returns the shout box messages.
        /// </returns>
        public IEnumerable<DataRow> GetShoutBoxMessages(int boardId)
        {
            return this.DataCache.GetOrSet(
                Constants.Cache.Shoutbox, 
                () =>
                    {
                        var messages = CommonDb.shoutbox_getmessages(
                            YafContext.Current.PageModuleID,
                            boardId,
                            this.Get<YafBoardSettings>().ShoutboxShowMessageCount,
                            this.Get<YafBoardSettings>().UseStyledNicks);

                        // Set colorOnly parameter to false, as we get all color info from data base
                        if (this.Get<YafBoardSettings>().UseStyledNicks)
                        {
                            this.Get<IStyleTransform>().DecodeStyleByTable(ref messages, false);
                        }

                        var flags = new MessageFlags { IsBBCode = true, IsHtml = false };

                        foreach (var row in messages.AsEnumerable())
                        {
                            string formattedMessage =
                                this.Get<IFormatMessage>().FormatMessage(row.Field<string>("Message"), flags);

                            // Extra Formating not needed already done tru this.Get<IFormatMessage>().FormatMessage
                            // formattedMessage = FormatHyperLink(formattedMessage);
                            row["Message"] = formattedMessage;
                        }

                        return messages;
                    }, 
                TimeSpan.FromMilliseconds(30000)).AsEnumerable();
        }
        /// <summary>
        /// Sends the user welcome notification.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="userId">The user identifier.</param>
        public void SendUserWelcomeNotification([NotNull] MembershipUser user, int? userId)
        {
            if (this.BoardSettings.SendWelcomeNotificationAfterRegister.Equals(0))
            {
                return;
            }

            var notifyUser = new YafTemplateEmail();

            var subject =
                this.Get<ILocalization>()
                    .GetText("COMMON", "NOTIFICATION_ON_WELCOME_USER_SUBJECT")
                    .FormatWith(this.BoardSettings.Name);

            notifyUser.TemplateParams["{user}"] = user.UserName;

            notifyUser.TemplateParams["{forumname}"] = this.BoardSettings.Name;
            notifyUser.TemplateParams["{forumurl}"] = YafForumInfo.ForumURL;

            var emailBody = notifyUser.ProcessTemplate("NOTIFICATION_ON_WELCOME_USER");

            var messageFlags = new MessageFlags { IsHtml = false, IsBBCode = true };

            if (this.BoardSettings.AllowPrivateMessages
                && this.BoardSettings.SendWelcomeNotificationAfterRegister.Equals(2))
            {
                var users = LegacyDb.UserList(YafContext.Current.PageBoardID, null, true, null, null, null).ToList();

                var hostUser = users.FirstOrDefault(u => u.IsHostAdmin > 0);

                LegacyDb.pmessage_save(hostUser.UserID.Value, userId, subject, emailBody, messageFlags.BitValue, -1);
            }
            else
            {
                this.GetRepository<Mail>()
                    .Create(
                        user.Email,
                        user.UserName,
                        subject,
                        emailBody);
            }
        }
        /// <summary>
        /// Send an Private Message to the Newly Created User with
        /// his Account Info (Pass, Security Question and Answer)
        /// </summary>
        /// <param name="user">
        /// The user.
        /// </param>
        /// <param name="pass">
        /// The pass.
        /// </param>
        /// <param name="securityAnswer">
        /// The security answer.
        /// </param>
        /// <param name="userId">
        /// The user Id.
        /// </param>
        /// <param name="oAuth">
        /// The o Auth.
        /// </param>
        private static void SendRegistrationMessageToUser([NotNull] MembershipUser user, [NotNull] string pass, [NotNull] string securityAnswer, [NotNull] int userId, OAuthTwitter oAuth)
        {
            var notifyUser = new YafTemplateEmail();

            string subject =
                YafContext.Current.Get<ILocalization>().GetText("COMMON", "NOTIFICATION_ON_NEW_FACEBOOK_USER_SUBJECT").FormatWith(
                    YafContext.Current.Get<YafBoardSettings>().Name);

            notifyUser.TemplateParams["{user}"] = user.UserName;
            notifyUser.TemplateParams["{email}"] = user.Email;
            notifyUser.TemplateParams["{pass}"] = pass;
            notifyUser.TemplateParams["{answer}"] = securityAnswer;
            notifyUser.TemplateParams["{forumname}"] = YafContext.Current.Get<YafBoardSettings>().Name;

            string emailBody = notifyUser.ProcessTemplate("NOTIFICATION_ON_FACEBOOK_REGISTER");

            var messageFlags = new MessageFlags { IsHtml = false, IsBBCode = true };

            // Send Message also as DM to Twitter.
            var tweetApi = new TweetAPI(oAuth);

            if (YafContext.Current.Get<YafBoardSettings>().AllowPrivateMessages)
            {
                LegacyDb.pmessage_save(2, userId, subject, emailBody, messageFlags.BitValue);

                string message = "{0}. {1}".FormatWith(
                subject, YafContext.Current.Get<ILocalization>().GetText("LOGIN", "TWITTER_DM"));

                tweetApi.SendDirectMessage(TweetAPI.ResponseFormat.json, user.UserName, message.Truncate(140));
            }
            else
            {
                string message = YafContext.Current.Get<ILocalization>().GetTextFormatted(
                    "LOGIN", "TWITTER_DM", YafContext.Current.Get<YafBoardSettings>().Name, user.UserName, pass);

                tweetApi.SendDirectMessage(TweetAPI.ResponseFormat.json, user.UserName, message.Truncate(140));
            }
        }
		/// <summary>
		/// The quick reply_ click.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void QuickReply_Click([NotNull] object sender, [NotNull] EventArgs e)
		{
			if (!this.PageContext.ForumReplyAccess ||
					(this._topicFlags.IsLocked && !this.PageContext.ForumModeratorAccess))
			{
				YafBuildLink.AccessDenied();
			}

			if (this._quickReplyEditor.Text.Length <= 0)
			{
				this.PageContext.AddLoadMessage(this.GetText("EMPTY_MESSAGE"));
				return;
			}

			// No need to check whitespace if they are actually posting something
			if (this.Get<YafBoardSettings>().MaxPostSize > 0
					&& this._quickReplyEditor.Text.Length >= this.Get<YafBoardSettings>().MaxPostSize)
			{
				this.PageContext.AddLoadMessage(this.GetText("ISEXCEEDED"));
				return;
			}

			if (((this.PageContext.IsGuest && this.Get<YafBoardSettings>().EnableCaptchaForGuests) ||
					 (this.Get<YafBoardSettings>().EnableCaptchaForPost && !this.PageContext.IsCaptchaExcluded)) &&
					!CaptchaHelper.IsValid(this.tbCaptcha.Text.Trim()))
			{
				this.PageContext.AddLoadMessage(this.GetText("BAD_CAPTCHA"));
				return;
			}

			if (!(this.PageContext.IsAdmin || this.PageContext.IsModerator) &&
					this.Get<YafBoardSettings>().PostFloodDelay > 0)
			{
				if (YafContext.Current.Get<IYafSession>().LastPost >
						DateTime.UtcNow.AddSeconds(-this.Get<YafBoardSettings>().PostFloodDelay))
				{
					this.PageContext.AddLoadMessage(
							this.GetTextFormatted(
									"wait",
									(YafContext.Current.Get<IYafSession>().LastPost -
									 DateTime.UtcNow.AddSeconds(-this.Get<YafBoardSettings>().PostFloodDelay)).Seconds));
					return;
				}
			}

			YafContext.Current.Get<IYafSession>().LastPost = DateTime.UtcNow;

			// post message...
			long nMessageId = 0;
			object replyTo = -1;
			string msg = this._quickReplyEditor.Text;
			long topicID = this.PageContext.PageTopicID;

			// SPAM Check

			// Check if Forum is Moderated
			DataRow forumInfo;
			bool isForumModerated = false;

			using (DataTable dt = LegacyDb.forum_list(this.PageContext.PageBoardID, this.PageContext.PageForumID))
			{
				forumInfo = dt.Rows[0];
			}

			if (forumInfo != null)
			{
				isForumModerated = forumInfo["Flags"].BinaryAnd(ForumFlags.Flags.IsModerated);
			}

			bool spamApproved = true;

			// Check for SPAM
			if (!this.PageContext.IsAdmin || !this.PageContext.IsModerator)
			{
				if (YafSpamCheck.IsPostSpam(this.PageContext.IsGuest ? "Guest" : this.PageContext.PageUserName, this.PageContext.PageTopicName, this._quickReplyEditor.Text))
				{
					if (this.Get<YafBoardSettings>().SpamMessageHandling.Equals(1))
					{
						spamApproved = false;
					}
					else if (this.Get<YafBoardSettings>().SpamMessageHandling.Equals(2))
					{
						this.PageContext.AddLoadMessage(this.GetText("SPAM_MESSAGE"));
						return;
					}
				}
			}

			// If Forum is Moderated
			if (isForumModerated)
			{
				spamApproved = false;
			}

			// Bypass Approval if Admin or Moderator
			if (this.PageContext.IsAdmin || this.PageContext.IsModerator)
			{
				spamApproved = true;
			}

			var tFlags = new MessageFlags
					{
						IsHtml = this._quickReplyEditor.UsesHTML,
						IsBBCode = this._quickReplyEditor.UsesBBCode,
						IsApproved = spamApproved
					};

			// Bypass Approval if Admin or Moderator.
			if (
					!LegacyDb.message_save(
							topicID,
							this.PageContext.PageUserID,
							msg,
							null,
							this.Get<HttpRequestBase>().UserHostAddress,
							null,
							replyTo,
							tFlags.BitValue,
							ref nMessageId))
			{
				topicID = 0;
			}

			// Check to see if the user has enabled "auto watch topic" option in his/her profile.
			if (this.PageContext.CurrentUserData.AutoWatchTopics)
			{
				using (
						DataTable dt = LegacyDb.watchtopic_check(this.PageContext.PageUserID, this.PageContext.PageTopicID))
				{
					if (dt.Rows.Count == 0)
					{
						// subscribe to this forum
						LegacyDb.watchtopic_add(this.PageContext.PageUserID, this.PageContext.PageTopicID);
					}
				}
			}

			bool bApproved = false;

			using (DataTable dt = LegacyDb.message_list(nMessageId))
			{
				foreach (DataRow row in dt.Rows)
				{
					bApproved = ((int)row["Flags"] & 16) == 16;
				}
			}

			if (bApproved)
			{
				// send new post notification to users watching this topic/forum
				this.Get<ISendNotification>().ToWatchingUsers(nMessageId.ToType<int>());

				// redirect to newly posted message
				YafBuildLink.Redirect(ForumPages.posts, "m={0}&#post{0}", nMessageId);
			}
			else
			{
				if (this.Get<YafBoardSettings>().EmailModeratorsOnModeratedPost)
				{
					// not approved, notifiy moderators
					this.Get<ISendNotification>().ToModeratorsThatMessageNeedsApproval(
							this.PageContext.PageForumID, (int)nMessageId);
				}

				string url = YafBuildLink.GetLink(ForumPages.topics, "f={0}", this.PageContext.PageForumID);
				if (Config.IsRainbow)
				{
					YafBuildLink.Redirect(ForumPages.info, "i=1");
				}
				else
				{
					YafBuildLink.Redirect(ForumPages.info, "i=1&url={0}", this.Server.UrlEncode(url));
				}
			}
		}
Beispiel #14
0
        /// <summary>
        ///     The get shout box messages.
        /// </summary>
        /// <param name="boardId"> The board id. </param>
        /// <returns> Returns the shout box messages. </returns>
        public IEnumerable<DataRow> GetShoutBoxMessages(int boardId)
        {
            return this.DataCache.GetOrSet(
                Constants.Cache.Shoutbox,
                () =>
                    {
                        var messages =
                            this.GetRepository<ShoutboxMessage>()
                                .GetMessages(
                                    this.BoardSettings.ShoutboxShowMessageCount,
                                    this.BoardSettings.UseStyledNicks,
                                    boardId);
                        var flags = new MessageFlags { IsBBCode = true, IsHtml = false };

                        foreach (var row in messages.AsEnumerable())
                        {
                            string formattedMessage =
                                this.Get<IFormatMessage>().FormatMessage(row.Field<string>("Message"), flags);

                            // Extra Formating not needed already done tru this.Get<IFormatMessage>().FormatMessage
                            // formattedMessage = FormatHyperLink(formattedMessage);
                            row["Message"] = formattedMessage;
                        }

                        return messages;
                    },
                TimeSpan.FromMilliseconds(30000)).AsEnumerable();
        }
        /// <summary>
        /// Handles preview button click event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Preview_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            // make preview row visible
            this.PreviewRow.Visible = true;

            this.PreviewMessagePost.MessageFlags.IsHtml = this._editor.UsesHTML;
            this.PreviewMessagePost.MessageFlags.IsBBCode = this._editor.UsesBBCode;
            this.PreviewMessagePost.Message = this._editor.Text;

            // set message flags
            var tFlags = new MessageFlags { IsHtml = this._editor.UsesHTML, IsBBCode = this._editor.UsesBBCode };

            if (!this.Get<YafBoardSettings>().AllowSignatures)
            {
                return;
            }

            using (DataTable userDT = LegacyDb.user_list(YafContext.Current.PageBoardID, YafContext.Current.PageUserID, true))
            {
                if (!userDT.Rows[0].IsNull("Signature"))
                {
                    this.PreviewMessagePost.Signature = userDT.Rows[0]["Signature"].ToString();
                }
            }
        }