Example #1
0
        internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList<RoleInfo> moderators, IList<UserInfo> recipients) {
            var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName);
            var tokenReplace = new GroupItemTokenReplace(group);

            var subject = Localization.GetString(notificationTypeName + ".Subject", Constants.SharedResourcesPath);
            subject = tokenReplace.ReplaceGroupItemTokens(subject);

            var body = Localization.GetString(notificationTypeName + ".Body", Constants.SharedResourcesPath);
            
            body = tokenReplace.ReplaceGroupItemTokens(body);
            body = body.Replace("Public.Text", Localization.GetString("Public.Text", Constants.SharedResourcesPath));
            body = body.Replace("Private.Text", Localization.GetString("Private.Text", Constants.SharedResourcesPath));

            bool dismiss = notificationTypeName != Constants.GroupPendingNotification;
            var notification = new Notification
                                   {
                                       NotificationTypeID = notificationType.NotificationTypeId,
                                       Subject = subject,
                                       Body = body,
                                       IncludeDismissAction = dismiss,
                                       SenderUserID = initiatingUser.UserID,
                                       Context = String.Format("{0}:{1}:{2}", tabId, moduleId, group.RoleID)
                                   };
            NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, moderators, recipients);

            return notification;
        }
        private static void AddHtmlNotification(string subject, string body, UserInfo user)
        {
            var notificationType = NotificationsController.Instance.GetNotificationType("HtmlNotification");
            var portalSettings = PortalController.GetCurrentPortalSettings();
            var sender = UserController.GetUserById(portalSettings.PortalId, portalSettings.AdministratorId);

            var notification = new Notification {NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID};
            NotificationsController.Instance.SendNotification(notification, portalSettings.PortalId, null, new List<UserInfo> { user });
        }
Example #3
0
        internal virtual Notification AddGroupOwnerNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser) 
        {
            var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName);

            var tokenReplace = new GroupItemTokenReplace(group);
            
            var subject = Localization.GetString(notificationTypeName + ".Subject", Constants.SharedResourcesPath);
            var body = Localization.GetString(notificationTypeName + ".Body", Constants.SharedResourcesPath);
            subject = subject.Replace("[DisplayName]", initiatingUser.DisplayName);
            subject = subject.Replace("[ProfileUrl]", Globals.UserProfileURL(initiatingUser.UserID));
            subject = tokenReplace.ReplaceGroupItemTokens(subject);
            body = body.Replace("[DisplayName]", initiatingUser.DisplayName);
            body = body.Replace("[ProfileUrl]", Globals.UserProfileURL(initiatingUser.UserID));
            body = tokenReplace.ReplaceGroupItemTokens(body);
            var roleCreator = UserController.GetUserById(group.PortalID, group.CreatedByUserID);

            var roleOwners = new List<UserInfo>();

            foreach (UserInfo userInfo in RoleController.Instance.GetUsersByRole(group.PortalID, group.RoleName))
            {
                var userRoleInfo = RoleController.Instance.GetUserRole(group.PortalID, userInfo.UserID, group.RoleID);
                if (userRoleInfo.IsOwner && userRoleInfo.UserID != group.CreatedByUserID)
                {
                    roleOwners.Add(UserController.GetUserById(group.PortalID, userRoleInfo.UserID));
                }
            }
            roleOwners.Add(roleCreator);
            


            //Need to add from sender details
            var notification = new Notification
            {
                NotificationTypeID = notificationType.NotificationTypeId,
                Subject = subject,
                Body = body,
                IncludeDismissAction = true,
                SenderUserID = initiatingUser.UserID,
                Context = String.Format("{0}:{1}:{2}:{3}", tabId, moduleId, group.RoleID, initiatingUser.UserID)
            };
            NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, null, roleOwners);

            return notification;
        }
        /// <summary>
        /// This method will create a new notification message in the data store.
        /// </summary>
        /// <param name="objEntity"></param>
        /// <param name="portalId"></param>
        /// <param name="tabId"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <remarks>The last part of this method is commented out but was setup to send to a role (based on a group). You can utilize this and/or also pass a list of users.</remarks>
        internal void ItemNotification(AlbumInfo objEntity, int portalId, int tabId, string subject, string body)
        {
            var notificationType = NotificationsController.Instance.GetNotificationType(Constants.NotificationQaFlag);

            var notificationKey = string.Format("{0}:{1}:{2}", Constants.ContentTypeName, objEntity.PostId, tabId);
            var objNotification = new Notification
            {
                NotificationTypeID = notificationType.NotificationTypeId,
                Subject = subject,
                Body = body,
                IncludeDismissAction = true,
                SenderUserID = objEntity.CreatedByUserID,
                Context = notificationKey
            };

            //// invite the members of the group
            //var colRoles = new List<RoleInfo>();
            //var objGroup = TestableRoleController.Instance.GetRole(portalId, r => r.RoleID == objEntity.GroupId);
            //colRoles.Add(objGroup);

            //NotificationsController.Instance.SendNotification(objNotification, portalId, colRoles, null);
        }
        private void btnSend_Click(object sender, System.EventArgs e)
        {
            if (Request.IsAuthenticated)
            {
                Email objEmail = new Email();
                string Comments = null;
                Comments = drpReasons.SelectedItem.Value + "<br>";
                Comments += Utilities.CleanString(PortalId, txtComments.Text, false, EditorTypes.TEXTBOX, false, false, ModuleId, string.Empty, false);
                int templateId = 0;
                TemplateController tc = new TemplateController();
                TemplateInfo ti = tc.Template_Get("ModAlert", PortalId, ModuleId);
                string sUrl = NavigateUrl(Convert.ToInt32(Request.QueryString["TabId"]), "", new string[] { ParamKeys.ForumId + "=" + ForumId, ParamKeys.TopicId + "=" + TopicId, ParamKeys.ViewType + "=confirmaction", ParamKeys.ConfirmActionId + "=" + ConfirmActions.AlertSent });

                NotificationType notificationType = NotificationsController.Instance.GetNotificationType("AF-ContentAlert");
                TopicsController topicController = new TopicsController();
                TopicInfo topic = topicController.Topics_Get(PortalId, ModuleId, TopicId, ForumId, -1, false);
                string sBody = string.Empty;
                string authorName = string.Empty;
                string sSubject = string.Empty;
                string sTopicURL = string.Empty;
                sTopicURL = topic.TopicUrl;
                if (ReplyId > 0 & TopicId != ReplyId)
                {
                    ReplyController rc = new ReplyController();
                    ReplyInfo reply = rc.Reply_Get(PortalId, ModuleId, TopicId, ReplyId);
                    sBody = reply.Content.Body;
                    sSubject = reply.Content.Subject;
                    authorName = reply.Author.DisplayName;

                }
                else
                {
                    sBody = topic.Content.Body;
                    sSubject = topic.Content.Subject;
                    authorName = topic.Author.DisplayName;

                }
                ControlUtils ctlUtils = new ControlUtils();
                string fullURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, ForumInfo.PrefixURL, ForumInfo.ForumGroupId, ForumInfo.ForumID, TopicId, sTopicURL, -1, -1, string.Empty, 1, ReplyId, SocialGroupId);
                string subject = Utilities.GetSharedResource("AlertSubject");
                subject = subject.Replace("[DisplayName]", authorName);
                subject = subject.Replace("[Subject]", sSubject);
                string body = Utilities.GetSharedResource("AlertBody");
                body = body.Replace("[Post]", sBody);
                body = body.Replace("[Comment]", Comments);
                body = body.Replace("[URL]", fullURL);
                body = body.Replace("[Reason]", drpReasons.SelectedItem.Value);
                List<Entities.Users.UserInfo> mods = Utilities.GetListOfModerators(PortalId, ForumId);


                string notificationKey = string.Format("{0}:{1}:{2}:{3}:{4}", TabId, ForumModuleId, ForumId, TopicId, ReplyId);

                Notification notification = new Notification();
                notification.NotificationTypeID = notificationType.NotificationTypeId;
                notification.Subject = subject;
                notification.Body = body;
                notification.IncludeDismissAction = false;
                notification.SenderUserID = UserInfo.UserID;
                notification.Context = notificationKey;


                NotificationsController.Instance.SendNotification(notification, PortalId, null, mods);



                Response.Redirect(sUrl);
            }
        }
        public virtual void SendNotification(Notification notification, int portalId, IList<RoleInfo> roles, IList<UserInfo> users)
        {
            Requires.NotNull("notification", notification);

            if (notification.SenderUserID < 1)
            {
                notification.SenderUserID = GetAdminUser().UserID;
            }

            if (string.IsNullOrEmpty(notification.Subject) && string.IsNullOrEmpty(notification.Body))
            {
                throw new ArgumentException(Localization.Localization.GetString("MsgSubjectOrBodyRequiredError", Localization.Localization.ExceptionsResourceFile));
            }

            if (roles == null && users == null)
            {
                throw new ArgumentException(Localization.Localization.GetString("MsgRolesOrUsersRequiredError", Localization.Localization.ExceptionsResourceFile));
            }

            if (!string.IsNullOrEmpty(notification.Subject) && notification.Subject.Length > ConstMaxSubject)
            {
                throw new ArgumentException(string.Format(Localization.Localization.GetString("MsgSubjectTooBigError", Localization.Localization.ExceptionsResourceFile), ConstMaxSubject, notification.Subject.Length));
            }

            var sbTo = new StringBuilder();
            if (roles != null)
            {
                foreach (var role in roles.Where(role => !string.IsNullOrEmpty(role.RoleName)))
                {
                    sbTo.Append(role.RoleName + ",");
                }
            }

            if (users != null)
            {
                foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) sbTo.Append(user.DisplayName + ",");
            }

            if (sbTo.Length == 0)
            {
                throw new ArgumentException(Localization.Localization.GetString("MsgEmptyToListFoundError", Localization.Localization.ExceptionsResourceFile));
            }

            if (sbTo.Length > ConstMaxTo)
            {
                throw new ArgumentException(string.Format(Localization.Localization.GetString("MsgToListTooBigError", Localization.Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length));
            }

            //Cannot exceed RecipientLimit
            var recipientCount = 0;
            if (users != null) recipientCount += users.Count;
            if (roles != null) recipientCount += roles.Count;
            if (recipientCount > InternalMessagingController.Instance.RecipientLimit(portalId))
            {
                throw new RecipientLimitExceededException(Localization.Localization.GetString("MsgRecipientLimitExceeded", Localization.Localization.ExceptionsResourceFile));
            }

            //Profanity Filter
            var profanityFilterSetting = GetPortalSetting("MessagingProfanityFilters", portalId, "NO");
            if (profanityFilterSetting.Equals("YES", StringComparison.InvariantCultureIgnoreCase))
            {
                notification.Subject = InputFilter(notification.Subject);
                notification.Body = InputFilter(notification.Body);
            }

            notification.To = sbTo.ToString().Trim(',');
            if (notification.ExpirationDate != new DateTime())
            {
                notification.ExpirationDate = GetExpirationDate(notification.NotificationTypeID);
            }

            notification.NotificationID = _dataService.SendNotification(notification, portalId);

            //send message to Roles
            if (roles != null)
            {
                var roleIds = string.Empty;
                roleIds = roles
                    .Select(r => r.RoleID)
                    .Aggregate(roleIds, (current, roleId) => current + (roleId + ","))
                    .Trim(',');

                _messagingDataService.CreateMessageRecipientsForRole(
                    notification.NotificationID,
                    roleIds,
                    UserController.GetCurrentUserInfo().UserID);
            }

            //send message to each User - this should be called after CreateMessageRecipientsForRole.
            if (users == null)
            {
                users = new List<UserInfo>();
            }

            var recipients = from user in users
                             where InternalMessagingController.Instance.GetMessageRecipient(notification.NotificationID, user.UserID) == null
                             select new MessageRecipient
                                        {
                                            MessageID = notification.NotificationID,
                                            UserID = user.UserID,
                                            Read = false,
                                            RecipientID = Null.NullInteger
                                        };

            foreach (var recipient in recipients)
            {
                _messagingDataService.SaveMessageRecipient(
                    recipient,
                    UserController.GetCurrentUserInfo().UserID);
            }
        }
        private XmlRpcStruct NewTopic(int forumId, string subject, string body, string prefixId, IEnumerable<string> attachmentIds, string groupId)
        {
            var aftContext = ActiveForumsTapatalkModuleContext.Create(Context);

            Context.Response.AddHeader("Mobiquo_is_login", aftContext.UserId > 0 ? "true" : "false");

            var portalId = aftContext.Module.PortalID;
            var forumModuleId = aftContext.ModuleSettings.ForumModuleId;

            var fc = new AFTForumController();

            var forumInfo = fc.GetForum(portalId, forumModuleId, forumId);

            // Verify Post Permissions
            if (!ActiveForums.Permissions.HasPerm(forumInfo.Security.Create, aftContext.ForumUser.UserRoles))
            {
                return new XmlRpcStruct
                                {
                                    {"result", "false"}, //"true" for success
                                    {"result_text", "Not Authorized to Post".ToBytes()}, 
                                };
            }

            // Build User Permissions
            var canModApprove = ActiveForums.Permissions.HasPerm(forumInfo.Security.ModApprove, aftContext.ForumUser.UserRoles);
            var canTrust = ActiveForums.Permissions.HasPerm(forumInfo.Security.Trust, aftContext.ForumUser.UserRoles);
            var userProfile = aftContext.UserId > 0 ? aftContext.ForumUser.Profile : new UserProfileInfo { TrustLevel = -1 };
            var userIsTrusted = Utilities.IsTrusted((int)forumInfo.DefaultTrustValue, userProfile.TrustLevel, canTrust, forumInfo.AutoTrustLevel, userProfile.PostCount);

            // Determine if the post should be approved
            var isApproved = !forumInfo.IsModerated || userIsTrusted || canModApprove;

            var mainSettings = new SettingsInfo { MainSettings = new Entities.Modules.ModuleController().GetModuleSettings(forumModuleId) };

            var dnnUser = Entities.Users.UserController.GetUserById(portalId, aftContext.UserId);

            var authorName = GetAuthorName(mainSettings, dnnUser);

            var themePath = string.Format("{0}://{1}{2}", Context.Request.Url.Scheme, Context.Request.Url.Host, VirtualPathUtility.ToAbsolute("~/DesktopModules/activeforums/themes/" + mainSettings.Theme + "/"));

            subject = Utilities.CleanString(portalId, subject, false, EditorTypes.TEXTBOX, forumInfo.UseFilter, false, forumModuleId, themePath, false);
            body = Utilities.CleanString(portalId, TapatalkToHtml(body), forumInfo.AllowHTML, EditorTypes.HTMLEDITORPROVIDER, forumInfo.UseFilter, false, forumModuleId, themePath, forumInfo.AllowEmoticons);

            // Create the topic

            var ti = new TopicInfo();
            var dt = DateTime.Now;
            ti.Content.DateCreated = dt;
            ti.Content.DateUpdated = dt;
            ti.Content.AuthorId = aftContext.UserId;
            ti.Content.AuthorName = authorName;
            ti.Content.IPAddress = Context.Request.UserHostAddress;
            ti.TopicUrl = string.Empty;
            ti.Content.Body = body;
            ti.Content.Subject = subject;
            ti.Content.Summary = string.Empty;

            ti.IsAnnounce = false;
            ti.IsPinned = false;
            ti.IsLocked = false;
            ti.IsDeleted = false;
            ti.IsArchived = false;

            ti.StatusId = -1;
            ti.TopicIcon = string.Empty;
            ti.TopicType = 0;

            ti.IsApproved = isApproved;

            // Save the topic
            var tc = new TopicsController();
            var topicId = tc.TopicSave(portalId, ti);
            ti = tc.Topics_Get(portalId, forumModuleId, topicId, forumId, -1, false);

            if (ti == null)
            {
                return new XmlRpcStruct
                                {
                                    {"result", "false"}, //"true" for success
                                    {"result_text", "Error Creating Post".ToBytes()}, 
                                };
            }

            // Update stats
            tc.Topics_SaveToForum(forumId, topicId, portalId, forumModuleId);
            if (ti.IsApproved && ti.Author.AuthorId > 0)
            {
                var uc = new ActiveForums.Data.Profiles();
                uc.Profile_UpdateTopicCount(portalId, ti.Author.AuthorId);
            }


            try
            {
                // Clear the cache
                var cachekey = string.Format("AF-FV-{0}-{1}", portalId, forumModuleId);
                DataCache.CacheClearPrefix(cachekey);

                // Subscribe the user if they have auto-subscribe set.
                if (userProfile.PrefSubscriptionType != SubscriptionTypes.Disabled && !(Subscriptions.IsSubscribed(portalId, forumModuleId, forumId, topicId, SubscriptionTypes.Instant, aftContext.UserId)))
                {
                    new SubscriptionController().Subscription_Update(portalId, forumModuleId, forumId, topicId, (int)userProfile.PrefSubscriptionType, aftContext.UserId, aftContext.ForumUser.UserRoles);
                }

                if (isApproved)
                {
                    // Send User Notifications
                    Subscriptions.SendSubscriptions(portalId, forumModuleId, aftContext.ModuleSettings.ForumTabId, forumInfo, topicId, 0, ti.Content.AuthorId);

                    // Add Journal entry
                    var forumTabId = aftContext.ModuleSettings.ForumTabId;
                    var fullURL = new ControlUtils().BuildUrl(forumTabId, forumModuleId, forumInfo.ForumGroup.PrefixURL, forumInfo.PrefixURL, forumInfo.ForumGroupId, forumInfo.ForumID, topicId, ti.TopicUrl, -1, -1, string.Empty, 1, -1, forumInfo.SocialGroupId);
                    new Social().AddTopicToJournal(portalId, forumModuleId, forumId, topicId, ti.Author.AuthorId, fullURL, ti.Content.Subject, string.Empty, ti.Content.Body, forumInfo.ActiveSocialSecurityOption, forumInfo.Security.Read, forumInfo.SocialGroupId);
                }
                else
                {
                    // Send Mod Notifications
                    var mods = Utilities.GetListOfModerators(portalId, forumId);
                    var notificationType = NotificationsController.Instance.GetNotificationType("AF-ForumModeration");
                    var notifySubject = Utilities.GetSharedResource("NotificationSubjectTopic");
                    notifySubject = notifySubject.Replace("[DisplayName]", dnnUser.DisplayName);
                    notifySubject = notifySubject.Replace("[TopicSubject]", ti.Content.Subject);
                    var notifyBody = Utilities.GetSharedResource("NotificationBodyTopic");
                    notifyBody = notifyBody.Replace("[Post]", ti.Content.Body);
                    var notificationKey = string.Format("{0}:{1}:{2}:{3}:{4}", aftContext.ModuleSettings.ForumTabId, forumModuleId, forumId, topicId, 0);

                    var notification = new Notification
                    {
                        NotificationTypeID = notificationType.NotificationTypeId,
                        Subject = notifySubject,
                        Body = notifyBody,
                        IncludeDismissAction = false,
                        SenderUserID = dnnUser.UserID,
                        Context = notificationKey
                    };

                    NotificationsController.Instance.SendNotification(notification, portalId, null, mods);
                }

            }
            catch (Exception ex)
            {
                Services.Exceptions.Exceptions.LogException(ex);
            }


            var result = new XmlRpcStruct
            {
                {"result", true}, //"true" for success
               // {"result_text", "OK".ToBytes()}, 
                {"topic_id", ti.TopicId.ToString()},
            };

            if (!isApproved)
                result.Add("state", 1);

            return result;

        }
        private void SaveQuickReply()
        {
            SettingsInfo ms = DataCache.MainSettings(ForumModuleId);
            int iFloodInterval = MainSettings.FloodInterval;
            if (iFloodInterval > 0)
            {

                UserProfileInfo upi = ForumUser.Profile;
                if (upi != null)
                {
                    if (SimulateDateDiff.DateDiff(SimulateDateDiff.DateInterval.Second, upi.DateLastPost, DateTime.Now) < iFloodInterval)
                    {
                        Controls.InfoMessage im = new Controls.InfoMessage();
                        im.Message = "<div class=\"afmessage\">" + string.Format(GetSharedResource("[RESX:Error:FloodControl]"), iFloodInterval) + "</div>";
                        plhMessage.Controls.Add(im);
                        return;
                    }
                }
            }
            if (!Request.IsAuthenticated)
            {
                if ((!ctlCaptcha.IsValid) || txtUserName.Value == "")
                {
                    return;
                }
            }
            UserProfileInfo ui = new UserProfileInfo();
            if (UserId > 0)
            {
                ui = ForumUser.Profile;
            }
            else
            {
                ui.TopicCount = 0;
                ui.ReplyCount = 0;
                ui.RewardPoints = 0;
                ui.IsMod = false;
                ui.TrustLevel = -1;

            }
            bool UserIsTrusted = false;
            UserIsTrusted = Utilities.IsTrusted((int)ForumInfo.DefaultTrustValue, ui.TrustLevel, Permissions.HasPerm(ForumInfo.Security.Trust, ForumUser.UserRoles), ForumInfo.AutoTrustLevel, ui.PostCount);
            bool isApproved = false;
            isApproved = Convert.ToBoolean(((ForumInfo.IsModerated == true) ? false : true));
            if (UserIsTrusted || Permissions.HasPerm(ForumInfo.Security.ModApprove, ForumUser.UserRoles))
            {
                isApproved = true;
            }
            ReplyInfo ri = new ReplyInfo();
            ReplyController rc = new ReplyController();
            int ReplyId = -1;
            string sUsername = string.Empty;
            if (Request.IsAuthenticated)
            {
                switch (MainSettings.UserNameDisplay.ToUpperInvariant())
                {
                    case "USERNAME":
                        sUsername = UserInfo.Username.Trim(' ');
                        break;
                    case "FULLNAME":
                        sUsername = Convert.ToString(UserInfo.FirstName + " " + UserInfo.LastName).Trim(' ');
                        break;
                    case "FIRSTNAME":
                        sUsername = UserInfo.FirstName.Trim(' ');
                        break;
                    case "LASTNAME":
                        sUsername = UserInfo.LastName.Trim(' ');
                        break;
                    case "DISPLAYNAME":
                        sUsername = UserInfo.DisplayName.Trim(' ');
                        break;
                    default:
                        sUsername = UserInfo.DisplayName;
                        break;
                }

            }
            else
            {
                sUsername = Utilities.CleanString(PortalId, txtUserName.Value, false, EditorTypes.TEXTBOX, true, false, ForumModuleId, ThemePath, false);
            }

            //Dim sSubject As String = Server.HtmlEncode(Request.Form("txtSubject"))
            //If (UseFilter) Then
            //    sSubject = Utilities.FilterWords(PortalId,  ForumModuleId, ThemePath, sSubject)
            //End If
            string sBody = string.Empty;
            if (AllowHTML)
            {
                AllowHTML = IsHtmlPermitted(ForumInfo.EditorPermittedUsers, IsTrusted, Permissions.HasPerm(ForumInfo.Security.ModEdit, ForumUser.UserRoles));
            }
            sBody = Utilities.CleanString(PortalId, Request.Form["txtBody"], AllowHTML, EditorTypes.TEXTBOX, UseFilter, AllowScripts, ForumModuleId, ThemePath, ForumInfo.AllowEmoticons);
            DateTime createDate = DateTime.Now;
            ri.TopicId = TopicId;
            ri.ReplyToId = TopicId;
            ri.Content.AuthorId = UserId;
            ri.Content.AuthorName = sUsername;
            ri.Content.Body = sBody;
            ri.Content.DateCreated = createDate;
            ri.Content.DateUpdated = createDate;
            ri.Content.IsDeleted = false;
            ri.Content.Subject = Subject;
            ri.Content.Summary = string.Empty;
            ri.IsApproved = isApproved;
            ri.IsDeleted = false;
            ri.Content.IPAddress = Request.UserHostAddress;
            ReplyId = rc.Reply_Save(PortalId, ri);
            //Check if is subscribed
            string cachekey = string.Format("AF-FV-{0}-{1}", PortalId, ModuleId);
            DataCache.CacheClearPrefix(cachekey);


            // Subscribe or unsubscribe if needed
            if (AllowSubscribe && UserId > 0)
            {
                var subscribe = Request.Params["chkSubscribe"] == "1";
                var currentlySubscribed = Subscriptions.IsSubscribed(PortalId, ForumModuleId, ForumId, TopicId, SubscriptionTypes.Instant, UserId);

                if (subscribe != currentlySubscribed)
                {
                    // Will need to update this to support multiple subscrition types later
                    // Subscription_Update works as a toggle, so you only call it if you want to change the value.
                    var sc = new SubscriptionController();
                    sc.Subscription_Update(PortalId, ForumModuleId, ForumId, TopicId, 1, UserId, ForumUser.UserRoles);
                }
            }



            ControlUtils ctlUtils = new ControlUtils();
            TopicsController tc = new TopicsController();
            TopicInfo ti = tc.Topics_Get(PortalId, ForumModuleId, TopicId, ForumId, -1, false);
            string fullURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, ForumInfo.PrefixURL, ForumInfo.ForumGroupId, ForumInfo.ForumID, TopicId, ti.TopicUrl, -1, -1, string.Empty, -1, ReplyId, SocialGroupId);

            if (fullURL.Contains("~/") || Request.QueryString["asg"] != null)
            {
                fullURL = Utilities.NavigateUrl(TabId, "", new string[] { ParamKeys.TopicId + "=" + TopicId, ParamKeys.ContentJumpId + "=" + ReplyId });
            }
            if (fullURL.EndsWith("/"))
            {
                fullURL += "?" + ParamKeys.ContentJumpId + "=" + ReplyId;
            }
            if (isApproved)
            {

                //Send Subscriptions

                try
                {
                    //Dim sURL As String = Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & ReplyId})
                    Subscriptions.SendSubscriptions(PortalId, ForumModuleId, TabId, ForumId, TopicId, ReplyId, UserId);
                    try
                    {
                        Social amas = new Social();
                        amas.AddReplyToJournal(PortalId, ForumModuleId, ForumId, TopicId, ReplyId, UserId, fullURL, Subject, string.Empty, sBody, ForumInfo.ActiveSocialSecurityOption, ForumInfo.Security.Read, SocialGroupId);
                        //If Request.QueryString["asg"] Is Nothing And Not String.IsNullOrEmpty(MainSettings.ActiveSocialTopicsKey) And ForumInfo.ActiveSocialEnabled And Not ForumInfo.ActiveSocialTopicsOnly Then
                        //    amas.AddReplyToJournal(PortalId, ForumModuleId, ForumId, TopicId, ReplyId, UserId, fullURL, Subject, String.Empty, sBody, ForumInfo.ActiveSocialSecurityOption, ForumInfo.Security.Read)
                        //Else
                        //    amas.AddForumItemToJournal(PortalId, ForumModuleId, UserId, "forumreply", fullURL, Subject, sBody)
                        //End If

                    }
                    catch (Exception ex)
                    {
                        DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                    }
                }
                catch (Exception ex)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
                }
                //Redirect to show post

                Response.Redirect(fullURL, false);
            }
            else if (isApproved == false)
            {
                List<Entities.Users.UserInfo> mods = Utilities.GetListOfModerators(PortalId, ForumId);
                NotificationType notificationType = NotificationsController.Instance.GetNotificationType("AF-ForumModeration");
                string subject = Utilities.GetSharedResource("NotificationSubjectReply");
                subject = subject.Replace("[DisplayName]", UserInfo.DisplayName);
                subject = subject.Replace("[TopicSubject]", ti.Content.Subject);
                string body = Utilities.GetSharedResource("NotificationBodyReply");
                body = body.Replace("[Post]", sBody);
                string notificationKey = string.Format("{0}:{1}:{2}:{3}:{4}", TabId, ForumModuleId, ForumId, TopicId, ReplyId);

                Notification notification = new Notification();
                notification.NotificationTypeID = notificationType.NotificationTypeId;
                notification.Subject = subject;
                notification.Body = body;
                notification.IncludeDismissAction = false;
                notification.SenderUserID = UserInfo.UserID;
                notification.Context = notificationKey;

                NotificationsController.Instance.SendNotification(notification, PortalId, null, mods);

                var @params = new List<string> { ParamKeys.ForumId + "=" + ForumId, ParamKeys.ViewType + "=confirmaction", "afmsg=pendingmod", ParamKeys.TopicId + "=" + TopicId };
                if (SocialGroupId > 0)
                {
                    @params.Add("GroupId=" + SocialGroupId);
                }
                Response.Redirect(Utilities.NavigateUrl(TabId, "", @params.ToArray()), false);
            }
            else
            {
                //Dim fullURL As String = Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & ReplyId})
                //If MainSettings.UseShortUrls Then
                //    fullURL = Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & ReplyId})
                //End If

                try
                {
                    Social amas = new Social();
                    amas.AddReplyToJournal(PortalId, ForumModuleId, ForumId, TopicId, ReplyId, UserId, fullURL, Subject, string.Empty, sBody, ForumInfo.ActiveSocialSecurityOption, ForumInfo.Security.Read, SocialGroupId);
                    //If Request.QueryString["asg"] Is Nothing And Not String.IsNullOrEmpty(MainSettings.ActiveSocialTopicsKey) And ForumInfo.ActiveSocialEnabled Then
                    //    amas.AddReplyToJournal(PortalId, ForumModuleId, ForumId, TopicId, ReplyId, UserId, fullURL, Subject, String.Empty, sBody, ForumInfo.ActiveSocialSecurityOption, ForumInfo.Security.Read)
                    //Else
                    //    amas.AddForumItemToJournal(PortalId, ForumModuleId, UserId, "forumreply", fullURL, Subject, sBody)
                    //End If

                }
                catch (Exception ex)
                {
                    DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                }
                Response.Redirect(fullURL, false);
            }

            //End If


        }
 public void MarkReadyForToast(Notification notification, UserInfo userInfo)
 {
     this.MarkReadyForToast(notification, userInfo.UserID);
 }
Example #10
0
        private void SaveReply()
        {
            var subject = ctlForm.Subject;
            var body = ctlForm.Body;
            subject = Utilities.CleanString(PortalId, subject, false, EditorTypes.TEXTBOX, _fi.UseFilter, false, ForumModuleId, _themePath, false);
            body = Utilities.CleanString(PortalId, body, _allowHTML, _editorType, _fi.UseFilter, _fi.AllowScript, ForumModuleId, _themePath, _fi.AllowEmoticons);
            // This HTML decode is used to make Quote functionality work properly even when it appears in Text Box instead of Editor
            if (Request.Params[ParamKeys.QuoteId] != null)
            {
                body = Utilities.HTMLDecode(body);
            }
            int authorId;
            string authorName;
            if (Request.IsAuthenticated)
            {
                authorId = UserInfo.UserID;
                switch (MainSettings.UserNameDisplay.ToUpperInvariant())
                {
                    case "USERNAME":
                        authorName = UserInfo.Username.Trim(' ');
                        break;
                    case "FULLNAME":
                        authorName = Convert.ToString(UserInfo.FirstName + " " + UserInfo.LastName).Trim(' ');
                        break;
                    case "FIRSTNAME":
                        authorName = UserInfo.FirstName.Trim(' ');
                        break;
                    case "LASTNAME":
                        authorName = UserInfo.LastName.Trim(' ');
                        break;
                    case "DISPLAYNAME":
                        authorName = UserInfo.DisplayName.Trim(' ');
                        break;
                    default:
                        authorName = UserInfo.DisplayName;
                        break;
                }
            }
            else
            {
                authorId = -1;
                authorName = Utilities.CleanString(PortalId, ctlForm.AuthorName, false, EditorTypes.TEXTBOX, true, false, ForumModuleId, _themePath, false);
                if (authorName.Trim() == string.Empty)
                    return;
            }

            var tc = new TopicsController();
            var rc = new ReplyController();
            ReplyInfo ri;

            if (PostId > 0)
            {
                ri = rc.Reply_Get(PortalId, ForumModuleId, TopicId, PostId);
                ri.Content.DateUpdated = DateTime.Now;
            }
            else
            {
                ri = new ReplyInfo();
                var dt = DateTime.Now;
                ri.Content.DateCreated = dt;
                ri.Content.DateUpdated = dt;
            }

            if (!_isEdit)
            {
                ri.Content.AuthorId = authorId;
                ri.Content.AuthorName = authorName;
                ri.Content.IPAddress = Request.UserHostAddress;
            }

            if (Regex.IsMatch(body, "<CODE([^>]*)>", RegexOptions.IgnoreCase))
            {
                foreach (Match m in Regex.Matches(body, "<CODE([^>]*)>(.*?)</CODE>", RegexOptions.IgnoreCase))
                    body = body.Replace(m.Value, m.Value.Replace("<br>", System.Environment.NewLine));
            }

            ri.Content.Body = body;
            ri.Content.Subject = subject;
            ri.Content.Summary = string.Empty;

            if (_canModApprove && ri.Content.AuthorId != UserId)
                ri.IsApproved = ctlForm.IsApproved;
            else
                ri.IsApproved = _isApproved;

            var bSend = ri.IsApproved;
            ri.IsDeleted = false;
            ri.StatusId = ctlForm.StatusId;
            ri.TopicId = TopicId;
            var tmpReplyId = rc.Reply_Save(PortalId, ri);
            ri = rc.Reply_Get(PortalId, ForumModuleId, TopicId, tmpReplyId);
            SaveAttachments(ri.ContentId);
            //tc.ForumTopicSave(ForumID, TopicId, ReplyId)
            var cachekey = string.Format("AF-FV-{0}-{1}", PortalId, ModuleId);
            DataCache.CacheClearPrefix(cachekey);
            try
            {
                if (ctlForm.Subscribe && authorId == UserId)
                {
                    if (!(Subscriptions.IsSubscribed(PortalId, ForumModuleId, ForumId, TopicId, SubscriptionTypes.Instant, authorId)))
                    {
                        var sc = new SubscriptionController();
                        sc.Subscription_Update(PortalId, ForumModuleId, ForumId, TopicId, 1, authorId, ForumUser.UserRoles);
                    }
                }
                else if (_isEdit)
                {
                    var isSub = Subscriptions.IsSubscribed(PortalId, ForumModuleId, ForumId, TopicId, SubscriptionTypes.Instant, authorId);
                    if (isSub && !ctlForm.Subscribe)
                    {
                        var sc = new SubscriptionController();
                        sc.Subscription_Update(PortalId, ForumModuleId, ForumId, TopicId, 1, authorId, ForumUser.UserRoles);
                    }
                }
                if (bSend && !_isEdit)
                {
                    Subscriptions.SendSubscriptions(PortalId, ForumModuleId, ForumTabId, _fi, TopicId, tmpReplyId, ri.Content.AuthorId);
                }
                if (ri.IsApproved == false)
                {
                    var ti = tc.Topics_Get(PortalId, ForumModuleId, TopicId);

                    var mods = Utilities.GetListOfModerators(PortalId, ForumId);
                    var notificationType = NotificationsController.Instance.GetNotificationType("AF-ForumModeration");
                    var notifySubject = Utilities.GetSharedResource("NotificationSubjectReply");
                    notifySubject = notifySubject.Replace("[DisplayName]", UserInfo.DisplayName);
                    notifySubject = notifySubject.Replace("[TopicSubject]", ti.Content.Subject);
                    var notifyBody = Utilities.GetSharedResource("NotificationBodyReply");
                    notifyBody = notifyBody.Replace("[Post]", ri.Content.Body);
                    var notificationKey = string.Format("{0}:{1}:{2}:{3}:{4}", TabId, ForumModuleId, ForumId, TopicId, ri.ReplyId);

                    var notification = new Notification
                                           {
                                               NotificationTypeID = notificationType.NotificationTypeId,
                                               Subject = notifySubject,
                                               Body = notifyBody,
                                               IncludeDismissAction = false,
                                               SenderUserID = UserInfo.UserID,
                                               Context = notificationKey
                                           };

                    NotificationsController.Instance.SendNotification(notification, PortalId, null, mods);

                    string[] @params = { ParamKeys.ForumId + "=" + ForumId, ParamKeys.TopicId + "=" + TopicId, ParamKeys.ViewType + "=confirmaction", ParamKeys.ConfirmActionId + "=" + ConfirmActions.MessagePending };
                    Response.Redirect(Utilities.NavigateUrl(ForumTabId, "", @params), false);
                }
                else
                {
                    var ctlUtils = new ControlUtils();
                    var ti = tc.Topics_Get(PortalId, ForumModuleId, TopicId, ForumId, -1, false);
                    var fullURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, ForumInfo.PrefixURL, ForumInfo.ForumGroupId, ForumInfo.ForumID, TopicId, ti.TopicUrl, -1, -1, string.Empty, 1, tmpReplyId, SocialGroupId);

                    if (fullURL.Contains("~/") || Request.QueryString["asg"] != null)
                        fullURL = Utilities.NavigateUrl(ForumTabId, "", new[] { ParamKeys.TopicId + "=" + TopicId, ParamKeys.ContentJumpId + "=" + tmpReplyId });

                    if (fullURL.EndsWith("/"))
                        fullURL += "?" + ParamKeys.ContentJumpId + "=" + tmpReplyId;

                    if (!_isEdit)
                    {
                        try
                        {
                            var amas = new Social();
                            amas.AddReplyToJournal(PortalId, ForumModuleId, ForumId, TopicId, ReplyId, UserId, fullURL, subject, string.Empty, body, ForumInfo.ActiveSocialSecurityOption, ForumInfo.Security.Read, SocialGroupId);
                            //If Request.QueryString["asg"] Is Nothing And Not String.IsNullOrEmpty(MainSettings.ActiveSocialTopicsKey) And ForumInfo.ActiveSocialEnabled And Not ForumInfo.ActiveSocialTopicsOnly Then
                            //    amas.AddReplyToJournal(PortalId, ForumModuleId, ForumId, TopicId, ReplyId, UserId, fullURL, Subject, String.Empty, Body, ForumInfo.ActiveSocialSecurityOption, ForumInfo.Security.Read)
                            //Else
                            //    amas.AddForumItemToJournal(PortalId, ForumModuleId, UserId, "forumreply", fullURL, Subject, Body)
                            //End If

                        }
                        catch (Exception ex)
                        {
                            Services.Exceptions.Exceptions.LogException(ex);
                        }

                    }
                    Response.Redirect(fullURL);
                }
            }
            catch (Exception)
            {

            }
        }
 private void AddAnnouncementNotification(string subject, string body, UserInfo user, UserInfo sender, int portalId)
 {
     var notificationType = NotificationsController.Instance.GetNotificationType(Common.NotificationType.Announcements);
     var notification = new Notification { NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID };
     NotificationsController.Instance.SendNotification(notification, portalId, null, new List<UserInfo> { user });
 }
		private object ToExpandoObject(Notification notification)
		{
			return new {Subject = notification.Subject, Body = notification.Body};
		}
 public void MarkReadyForToast(Notification notification, int userId)
 {
     DataCache.RemoveCache(string.Format(ToastsCacheKey, userId));
     this._dataService.MarkReadyForToast(notification.NotificationID, userId);
 }
        private void AddFollowerRequestNotification(UserInfo initiatingUser, UserInfo targetUser)
        {
            var notificationType = NotificationsController.Instance.GetNotificationType(IsFollowing(targetUser, initiatingUser) ? FollowerRequest : FollowBackRequest);
            var subject = string.Format(Localization.GetString("AddFollowerRequestSubject", Localization.GlobalResourceFile),
                              initiatingUser.DisplayName);

            var body = string.Format(Localization.GetString("AddFollowerRequestBody", Localization.GlobalResourceFile),
                              initiatingUser.DisplayName);

            var notification = new Notification
            {
                NotificationTypeID = notificationType.NotificationTypeId,
                Subject = subject,
                Body = body,
                IncludeDismissAction = true,
                Context = initiatingUser.UserID.ToString(CultureInfo.InvariantCulture),
                SenderUserID = initiatingUser.UserID
            };

            NotificationsController.Instance.SendNotification(notification, initiatingUser.PortalID, null, new List<UserInfo> { targetUser });
        }
Example #15
0
        internal virtual Notification AddMemberNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo sender, UserInfo recipient) {
            var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName);

            var subject = Localization.GetString(notificationTypeName + ".Subject", Constants.SharedResourcesPath);

            var body = Localization.GetString(notificationTypeName + ".Body", Constants.SharedResourcesPath);
            var tokenReplace = new GroupItemTokenReplace(group);
            subject = subject.Replace("[DisplayName]", recipient.DisplayName);
            subject = subject.Replace("[ProfileUrl]", Globals.UserProfileURL(recipient.UserID));
            subject = tokenReplace.ReplaceGroupItemTokens(subject);
            body = body.Replace("[DisplayName]", recipient.DisplayName);
            body = body.Replace("[ProfileUrl]", Globals.UserProfileURL(recipient.UserID));
            body = tokenReplace.ReplaceGroupItemTokens(body);

            //Need to add from sender details
            var notification = new Notification
            {
                NotificationTypeID = notificationType.NotificationTypeId,
                Subject = subject,
                Body = body,
                IncludeDismissAction = true,
                SenderUserID = sender.UserID,
                Context = String.Format("{0}:{1}:{2}", tabId, moduleId, group.RoleID)
            };
            NotificationsController.Instance.SendNotification(notification, recipient.PortalID, null, new List<UserInfo> { recipient });

            return notification;
        }
Example #16
0
 private void SendAdminNotification(UserInfo newUser, PortalSettings portalSettings)
 {
     var notificationType = newUser.Membership.Approved ? "NewUserRegistration" : "NewUnauthorizedUserRegistration";
     var locale = LocaleController.Instance.GetDefaultLocale(portalSettings.PortalId).Code;
     var notification = new Notification
     {
         NotificationTypeID = NotificationsController.Instance.GetNotificationType(notificationType).NotificationTypeId,
         IncludeDismissAction = newUser.Membership.Approved,
         SenderUserID = portalSettings.AdministratorId,
         Subject = GetNotificationSubject(locale, newUser, portalSettings),
         Body = GetNotificationBody(locale, newUser, portalSettings),
         Context = newUser.UserID.ToString(CultureInfo.InvariantCulture)
     };
     var adminrole = RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.AdministratorRoleId);
     var roles = new List<RoleInfo> { adminrole };
     NotificationsController.Instance.SendNotification(notification, portalSettings.PortalId, roles, new List<UserInfo>());
 }
Example #17
0
        private void SendAdminNotification(UserInfo newUser, string notificationType, PortalSettings portalSettings)
        {
            var notification = new Notification
            {
                NotificationTypeID = NotificationsController.Instance.GetNotificationType(notificationType).NotificationTypeId,                
                IncludeDismissAction = true,
                SenderUserID = portalSettings.AdministratorId
            };
            notification.Subject = GetNotificationSubject(notificationType, newUser.Profile.PreferredLocale, newUser, portalSettings);
            notification.Body = GetNotificationBody(notificationType, newUser.Profile.PreferredLocale, newUser, portalSettings);
            var roleController = new RoleController();
            var adminrole = roleController.GetRole(portalSettings.AdministratorRoleId, portalSettings.PortalId);
            var roles = new List<RoleInfo>();
            roles.Add(adminrole);
            NotificationsController.Instance.SendNotification(notification, portalSettings.PortalId, roles, new List<UserInfo>());

        }
        private void AddTranslationSubmittedNotification(TabInfo tabInfo, UserInfo translator)
        {
            var notificationType = NotificationsController.Instance.GetNotificationType("TranslationSubmitted");

            var subject = Localization.GetString("NewContentMessage.Subject", LocalResourceFile);
            var body = string.Format(Localization.GetString("NewContentMessage.Body", LocalResourceFile),
                tabInfo.TabName,
                Globals.NavigateURL(tabInfo.TabID, false, PortalSettings, Null.NullString, tabInfo.CultureCode, new string[] { }),
                txtTranslationComment.Text);

            var sender = UserController.GetUserById(PortalSettings.PortalId, PortalSettings.AdministratorId);

            var notification = new Notification { NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID };

            NotificationsController.Instance.SendNotification(notification, PortalSettings.PortalId, null, new List<UserInfo> { translator });
        }
        private void SendMentionNotifications(IDictionary<string, UserInfo> mentionedUsers, JournalItem item, string originalSummary, string type = "Post")
        {
            //send notification to the mention users
            var subjectTemplate = Utilities.GetSharedResource("Notification_Mention.Subject");
            var bodyTemplate = Utilities.GetSharedResource("Notification_Mention.Body");
            var mentionType = Utilities.GetSharedResource("Notification_MentionType_" + type);
            var notificationType = DotNetNuke.Services.Social.Notifications.NotificationsController.Instance.GetNotificationType("JournalMention");

            foreach (var key in mentionedUsers.Keys)
            {
                var mentionUser = mentionedUsers[key];
                var mentionText = originalSummary.Substring(originalSummary.IndexOf(MentionIdentityChar + key, StringComparison.InvariantCultureIgnoreCase));
                if (mentionText.Length > MentionNotificationLength)
                {
                    mentionText = mentionText.Substring(0, MentionNotificationLength) + MentionNotificationSuffix;
                }
                var notification = new Notification
                {
                    Subject = string.Format(subjectTemplate, UserInfo.DisplayName, mentionType),
                    Body = string.Format(bodyTemplate, mentionText),
                    NotificationTypeID = notificationType.NotificationTypeId,
                    SenderUserID = UserInfo.UserID,
                    IncludeDismissAction = true,
                    Context = string.Format("{0}_{1}", UserInfo.UserID, item.JournalId)
                };

                Services.Social.Notifications.NotificationsController.Instance.SendNotification(notification, PortalSettings.PortalId, null, new List<UserInfo> { mentionUser });
            }
        }
Example #20
0
        private void SaveTopic()
        {
            var subject = ctlForm.Subject;
            var body = ctlForm.Body;
            subject = Utilities.CleanString(PortalId, subject, false, EditorTypes.TEXTBOX, ForumInfo.UseFilter, false, ForumModuleId, _themePath, false);
            body = Utilities.CleanString(PortalId, body, _allowHTML, _editorType, ForumInfo.UseFilter, ForumInfo.AllowScript, ForumModuleId, _themePath, ForumInfo.AllowEmoticons);
            var summary = ctlForm.Summary;
            int authorId;
            string authorName;
            if (Request.IsAuthenticated)
            {
                authorId = UserInfo.UserID;
                switch (MainSettings.UserNameDisplay.ToUpperInvariant())
                {
                    case "USERNAME":
                        authorName = UserInfo.Username.Trim(' ');
                        break;
                    case "FULLNAME":
                        authorName = Convert.ToString(UserInfo.FirstName + " " + UserInfo.LastName).Trim(' ');
                        break;
                    case "FIRSTNAME":
                        authorName = UserInfo.FirstName.Trim(' ');
                        break;
                    case "LASTNAME":
                        authorName = UserInfo.LastName.Trim(' ');
                        break;
                    case "DISPLAYNAME":
                        authorName = UserInfo.DisplayName.Trim(' ');
                        break;
                    default:
                        authorName = UserInfo.DisplayName;
                        break;
                }
            }
            else
            {
                authorId = -1;
                authorName = Utilities.CleanString(PortalId, ctlForm.AuthorName, false, EditorTypes.TEXTBOX, true, false, ForumModuleId, _themePath, false);
                if (authorName.Trim() == string.Empty)
                    return;
            }

            var tc = new TopicsController();
            TopicInfo ti;

            if (TopicId > 0)
            {
                ti = tc.Topics_Get(PortalId, ForumModuleId, TopicId);
                ti.Content.DateUpdated = DateTime.Now;
                authorId = ti.Author.AuthorId;
            }
            else
            {
                ti = new TopicInfo();
                var dt = DateTime.Now;
                ti.Content.DateCreated = dt;
                ti.Content.DateUpdated = dt;
            }

            ti.AnnounceEnd = ctlForm.AnnounceEnd;
            ti.AnnounceStart = ctlForm.AnnounceStart;
            ti.Priority = ctlForm.TopicPriority;

            if (!_isEdit)
            {
                ti.Content.AuthorId = authorId;
                ti.Content.AuthorName = authorName;
                ti.Content.IPAddress = Request.UserHostAddress;
            }

            if (Regex.IsMatch(body, "<CODE([^>]*)>", RegexOptions.IgnoreCase))
            {
                foreach (Match m in Regex.Matches(body, "<CODE([^>]*)>(.*?)</CODE>", RegexOptions.IgnoreCase))
                    body = body.Replace(m.Value, m.Value.Replace("<br>", System.Environment.NewLine));
            }

            if (!(string.IsNullOrEmpty(ForumInfo.PrefixURL)))
            {
                var cleanSubject = Utilities.CleanName(subject).ToLowerInvariant();
                if (SimulateIsNumeric.IsNumeric(cleanSubject))
                    cleanSubject = "Topic-" + cleanSubject;

                var topicUrl = cleanSubject;
                var urlPrefix = "/";

                if (!(string.IsNullOrEmpty(ForumInfo.ForumGroup.PrefixURL)))
                    urlPrefix += ForumInfo.ForumGroup.PrefixURL + "/";

                if (!(string.IsNullOrEmpty(ForumInfo.PrefixURL)))
                    urlPrefix += ForumInfo.PrefixURL + "/";

                var urlToCheck = urlPrefix + cleanSubject;

                var topicsDb = new Data.Topics();
                for (var u = 0; u <= 200; u++)
                {
                    var tid = topicsDb.TopicIdByUrl(PortalId, ModuleId, urlToCheck);
                    if (tid > 0 && tid == TopicId)
                        break;

                    if (tid <= 0)
                        break;

                    topicUrl = (u + 1) + "-" + cleanSubject;
                    urlToCheck = urlPrefix + topicUrl;
                }
                if (topicUrl.Length > 150)
                {
                    topicUrl = topicUrl.Substring(0, 149);
                    topicUrl = topicUrl.Substring(0, topicUrl.LastIndexOf("-", StringComparison.Ordinal));
                }

                ti.TopicUrl = topicUrl;
            }
            else
            {
                //.URL = String.Empty
                ti.TopicUrl = string.Empty;
            }

            ti.Content.Body = body; //Utilities.CleanString(PortalId, Body, fi.AllowHTML, fi.EditorType, fi.UseFilter, fi.AllowScript, ForumModuleId, String.Empty)
            ti.Content.Subject = subject;
            ti.Content.Summary = summary;
            ti.IsAnnounce = ti.AnnounceEnd != Utilities.NullDate() && ti.AnnounceStart != Utilities.NullDate();

            if (_canModApprove && _fi.IsModerated)
                ti.IsApproved = ctlForm.IsApproved;
            else
                ti.IsApproved = _isApproved;

            bool bSend = ti.IsApproved;

            ti.IsArchived = false;
            ti.IsDeleted = false;
            ti.IsLocked = _canLock && ctlForm.Locked;
            ti.IsPinned = _canPin && ctlForm.Pinned;
            ti.StatusId = ctlForm.StatusId;
            ti.TopicIcon = ctlForm.TopicIcon;
            ti.TopicType = 0;
            if (ForumInfo.Properties != null)
            {
                var tData = new StringBuilder();
                tData.Append("<topicdata>");
                tData.Append("<properties>");
                foreach (var p in ForumInfo.Properties)
                {
                    var pkey = "afprop-" + p.PropertyId.ToString();

                    tData.Append("<property id=\"" + p.PropertyId.ToString() + "\">");
                    tData.Append("<name><![CDATA[");
                    tData.Append(p.Name);
                    tData.Append("]]></name>");
                    if (Request.Form[pkey] != null)
                    {
                        tData.Append("<value><![CDATA[");
                        tData.Append(Utilities.XSSFilter(Request.Form[pkey]));
                        tData.Append("]]></value>");
                    }
                    else
                    {
                        tData.Append("<value></value>");
                    }
                    tData.Append("</property>");
                }
                tData.Append("</properties>");
                tData.Append("</topicdata>");
                ti.TopicData = tData.ToString();
            }

            TopicId = tc.TopicSave(PortalId, ti);
            ti = tc.Topics_Get(PortalId, ForumModuleId, TopicId, ForumId, -1, false);
            if (ti != null)
            {
                tc.Topics_SaveToForum(ForumId, TopicId, PortalId, ModuleId);
                SaveAttachments(ti.ContentId);
                if (ti.IsApproved && ti.Author.AuthorId > 0)
                {
                    var uc = new Data.Profiles();
                    uc.Profile_UpdateTopicCount(PortalId, ti.Author.AuthorId);
                }
            }

            if (Permissions.HasPerm(ForumInfo.Security.Tag, ForumUser.UserRoles))
            {
                DataProvider.Instance().Tags_DeleteByTopicId(PortalId, ForumModuleId, TopicId);
                var tagForm = string.Empty;
                if (Request.Form["txtTags"] != null)
                    tagForm = Request.Form["txtTags"];

                if (tagForm != string.Empty)
                {
                    var tags = tagForm.Split(',');
                    foreach (var tag in tags)
                    {
                        var sTag = Utilities.CleanString(PortalId, tag.Trim(), false, EditorTypes.TEXTBOX, false, false, ForumModuleId, string.Empty, false);
                        DataProvider.Instance().Tags_Save(PortalId, ForumModuleId, -1, sTag, 0, 1, 0, TopicId, false, -1, -1);
                    }
                }
            }

            if (Permissions.HasPerm(ForumInfo.Security.Categorize, ForumUser.UserRoles))
            {
                if (Request.Form["amaf-catselect"] != null)
                {
                    var cats = Request.Form["amaf-catselect"].Split(';');
                    DataProvider.Instance().Tags_DeleteTopicToCategory(PortalId, ForumModuleId, -1, TopicId);
                    foreach (var c in cats)
                    {
                        if (string.IsNullOrEmpty(c) || !SimulateIsNumeric.IsNumeric(c))
                            continue;

                        var cid = Convert.ToInt32(c);
                        if (cid > 0)
                            DataProvider.Instance().Tags_AddTopicToCategory(PortalId, ForumModuleId, cid, TopicId);
                    }
                }
            }

            if (!String.IsNullOrEmpty(ctlForm.PollQuestion) && !String.IsNullOrEmpty(ctlForm.PollOptions))
            {
                //var sPollQ = ctlForm.PollQuestion.Trim();
                //sPollQ = Utilities.CleanString(PortalId, sPollQ, false, EditorTypes.TEXTBOX, true, false, ForumModuleId, string.Empty, false);
                var pollId = DataProvider.Instance().Poll_Save(-1, TopicId, UserId, ctlForm.PollQuestion.Trim(), ctlForm.PollType);
                if (pollId > 0)
                {
                    var options = ctlForm.PollOptions.Split(new[] { System.Environment.NewLine }, StringSplitOptions.None);

                    foreach (string opt in options)
                    {
                        if (opt.Trim() != string.Empty)
                        {
                            var value = Utilities.CleanString(PortalId, opt, false, EditorTypes.TEXTBOX, true, false, ForumModuleId, string.Empty, false);
                            DataProvider.Instance().Poll_Option_Save(-1, pollId, value.Trim(), TopicId);
                        }
                    }
                }

                ti = tc.Topics_Get(PortalId, ForumModuleId, TopicId, ForumId, -1, false);
                ti.TopicType = TopicTypes.Poll;
                tc.TopicSave(PortalId, ti);
            }

            try
            {
                var cachekey = string.Format("AF-FV-{0}-{1}", PortalId, ModuleId);
                DataCache.CacheClearPrefix(cachekey);
                if (ctlForm.Subscribe && authorId == UserId)
                {
                    if (!(Subscriptions.IsSubscribed(PortalId, ForumModuleId, ForumId, TopicId, SubscriptionTypes.Instant, authorId)))
                    {
                        var sc = new SubscriptionController();
                        sc.Subscription_Update(PortalId, ForumModuleId, ForumId, TopicId, 1, authorId, ForumUser.UserRoles);
                    }
                }
                else if (_isEdit)
                {
                    bool isSub = Subscriptions.IsSubscribed(PortalId, ForumModuleId, ForumId, TopicId, SubscriptionTypes.Instant, authorId);
                    if (isSub && !ctlForm.Subscribe)
                    {
                        var sc = new SubscriptionController();
                        sc.Subscription_Update(PortalId, ForumModuleId, ForumId, TopicId, 1, authorId, ForumUser.UserRoles);
                    }
                }

                if (bSend && !_isEdit)
                    Subscriptions.SendSubscriptions(PortalId, ForumModuleId, ForumTabId, _fi, TopicId, 0, ti.Content.AuthorId);

                if (ti.IsApproved == false)
                {
                    var mods = Utilities.GetListOfModerators(PortalId, ForumId);
                    var notificationType = NotificationsController.Instance.GetNotificationType("AF-ForumModeration");

                    var notifySubject = Utilities.GetSharedResource("NotificationSubjectTopic");
                    notifySubject = notifySubject.Replace("[DisplayName]", UserInfo.DisplayName);
                    notifySubject = notifySubject.Replace("[TopicSubject]", ti.Content.Subject);

                    var notifyBody = Utilities.GetSharedResource("NotificationBodyTopic");
                    notifyBody = notifyBody.Replace("[Post]", ti.Content.Body);

                    var notificationKey = string.Format("{0}:{1}:{2}:{3}:{4}", TabId, ForumModuleId, ForumId, TopicId, ReplyId);

                    var notification = new Notification
                                           {
                                               NotificationTypeID = notificationType.NotificationTypeId,
                                               Subject = notifySubject,
                                               Body = notifyBody,
                                               IncludeDismissAction = false,
                                               SenderUserID = UserInfo.UserID,
                                               Context = notificationKey
                                           };

                    NotificationsController.Instance.SendNotification(notification, PortalId, null, mods);

                    string[] @params = { ParamKeys.ForumId + "=" + ForumId, ParamKeys.ViewType + "=confirmaction", ParamKeys.ConfirmActionId + "=" + ConfirmActions.MessagePending };
                    Response.Redirect(NavigateUrl(ForumTabId, "", @params), false);
                }
                else
                {
                    if (ti != null)
                        ti.TopicId = TopicId;

                    var ctlUtils = new ControlUtils();

                    var sUrl = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, ForumInfo.PrefixURL, ForumInfo.ForumGroupId, ForumInfo.ForumID, TopicId, ti.TopicUrl, -1, -1, string.Empty, 1, -1, SocialGroupId);

                    if (sUrl.Contains("~/") || Request.QueryString["asg"] != null)
                        sUrl = Utilities.NavigateUrl(ForumTabId, "", ParamKeys.TopicId + "=" + TopicId);

                    if (!_isEdit)
                    {
                        try
                        {
                            var amas = new Social();
                            amas.AddTopicToJournal(PortalId, ForumModuleId, ForumId, TopicId, UserId, sUrl, subject, summary, body, ForumInfo.ActiveSocialSecurityOption, ForumInfo.Security.Read, SocialGroupId);
                            if (Request.QueryString["asg"] == null && !(string.IsNullOrEmpty(MainSettings.ActiveSocialTopicsKey)) && ForumInfo.ActiveSocialEnabled)
                            {
                                // amas.AddTopicToJournal(PortalId, ForumModuleId, ForumId, UserId, sUrl, Subject, Summary, Body, ForumInfo.ActiveSocialSecurityOption, ForumInfo.Security.Read)
                            }
                            else
                            {
                                amas.AddForumItemToJournal(PortalId, ForumModuleId, UserId, "forumtopic", sUrl, subject, body);
                            }
                        }
                        catch (Exception ex)
                        {
                            Services.Exceptions.Exceptions.LogException(ex);
                        }
                    }

                    Response.Redirect(sUrl, false);
                }
            }
            catch (Exception ex)
            {
                Services.Exceptions.Exceptions.LogException(ex);
            }
        }
        public virtual void SendNotification(Notification notification, int portalId, IList <RoleInfo> roles, IList <UserInfo> users)
        {
            Requires.NotNull("notification", notification);

            var pid = portalId;

            if (PortalController.IsMemberOfPortalGroup(portalId))
            {
                pid = PortalController.GetEffectivePortalId(portalId);
            }

            if (notification.SenderUserID < 1)
            {
                notification.SenderUserID = this.GetAdminUser().UserID;
            }

            if (string.IsNullOrEmpty(notification.Subject) && string.IsNullOrEmpty(notification.Body))
            {
                throw new ArgumentException(Localization.GetString("MsgSubjectOrBodyRequiredError", Localization.ExceptionsResourceFile));
            }

            if (roles == null && users == null)
            {
                throw new ArgumentException(Localization.GetString("MsgRolesOrUsersRequiredError", Localization.ExceptionsResourceFile));
            }

            if (!string.IsNullOrEmpty(notification.Subject) && notification.Subject.Length > ConstMaxSubject)
            {
                throw new ArgumentException(string.Format(Localization.GetString("MsgSubjectTooBigError", Localization.ExceptionsResourceFile), ConstMaxSubject, notification.Subject.Length));
            }

            var sbTo = new StringBuilder();

            if (roles != null)
            {
                foreach (var role in roles.Where(role => !string.IsNullOrEmpty(role.RoleName)))
                {
                    sbTo.Append(role.RoleName + ",");
                }
            }

            if (users != null)
            {
                foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName)))
                {
                    sbTo.Append(user.DisplayName + ",");
                }
            }

            if (sbTo.Length == 0)
            {
                throw new ArgumentException(Localization.GetString("MsgEmptyToListFoundError", Localization.ExceptionsResourceFile));
            }

            if (sbTo.Length > ConstMaxTo)
            {
                throw new ArgumentException(string.Format(Localization.GetString("MsgToListTooBigError", Localization.ExceptionsResourceFile), ConstMaxTo, sbTo.Length));
            }

            notification.To = sbTo.ToString().Trim(',');
            if (notification.ExpirationDate != default(DateTime))
            {
                notification.ExpirationDate = this.GetExpirationDate(notification.NotificationTypeID);
            }

            notification.NotificationID = this._dataService.SendNotification(notification, pid);

            // send message to Roles
            if (roles != null)
            {
                var roleIds = string.Empty;
                roleIds = roles
                          .Select(r => r.RoleID)
                          .Aggregate(roleIds, (current, roleId) => current + (roleId + ","))
                          .Trim(',');

                this._messagingDataService.CreateMessageRecipientsForRole(
                    notification.NotificationID,
                    roleIds,
                    UserController.Instance.GetCurrentUserInfo().UserID);
            }

            // send message to each User - this should be called after CreateMessageRecipientsForRole.
            if (users == null)
            {
                users = new List <UserInfo>();
            }

            var recipients = from user in users
                             where InternalMessagingController.Instance.GetMessageRecipient(notification.NotificationID, user.UserID) == null
                             select new MessageRecipient
            {
                MessageID   = notification.NotificationID,
                UserID      = user.UserID,
                Read        = false,
                RecipientID = Null.NullInteger,
            };

            foreach (var recipient in recipients)
            {
                this._messagingDataService.SaveMessageRecipient(
                    recipient,
                    UserController.Instance.GetCurrentUserInfo().UserID);
            }

            // if sendToast is true, then mark all recipients' as ready for toast.
            if (notification.SendToast)
            {
                foreach (var messageRecipient in InternalMessagingController.Instance.GetMessageRecipients(notification.NotificationID))
                {
                    this.MarkReadyForToast(notification, messageRecipient.UserID);
                }
            }
        }