Example #1
0
        public void Topics_Move(int PortalId, int ModuleId, int ForumId, int TopicId)
        {
            SettingsInfo settings = DataCache.MainSettings(ModuleId);

            if (settings.URLRewriteEnabled)
            {
                try
                {
                    Data.ForumsDB db         = new Data.ForumsDB();
                    int           oldForumId = -1;
                    oldForumId = db.Forum_GetByTopicId(TopicId);
                    ForumController fc = new ForumController();
                    Forum           fi = fc.Forums_Get(oldForumId, -1, false);
                    if (!(string.IsNullOrEmpty(fi.PrefixURL)))
                    {
                        Data.Common dbC  = new Data.Common();
                        string      sURL = dbC.GetUrl(ModuleId, fi.ForumGroupId, oldForumId, TopicId, -1, -1);
                        if (!(string.IsNullOrEmpty(sURL)))
                        {
                            dbC.ArchiveURL(PortalId, fi.ForumGroupId, ForumId, TopicId, sURL);
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
            DataProvider.Instance().Topics_Move(PortalId, ModuleId, ForumId, TopicId);
        }
        public HttpResponseMessage RunMaintenance(RunMaintenanceDTO dto)
        {
            var objModules = new Entities.Modules.ModuleController();
            var objSettings = new SettingsInfo {MainSettings = objModules.GetModuleSettings(dto.ModuleId)};
            var rows = DataProvider.Instance().Forum_Maintenance(dto.ForumId, dto.OlderThan, dto.LastActive, dto.ByUserId, dto.WithNoReplies, dto.DryRun, objSettings.DeleteBehavior);
            if (dto.DryRun)
                return Request.CreateResponse(HttpStatusCode.OK, new { Result = string.Format(Utilities.GetSharedResource("[RESX:Maint:DryRunResults]", true), rows.ToString()) });

            return Request.CreateResponse(HttpStatusCode.OK, new { Result = Utilities.GetSharedResource("[RESX:ProcessComplete]", true) });
        }
Example #3
0
        public ReplyInfo ApproveReply(int PortalId, int TabId, int ModuleId, int ForumId, int TopicId, int ReplyId)
        {
            SettingsInfo    ms = DataCache.MainSettings(ModuleId);
            ForumController fc = new ForumController();
            Forum           fi = fc.Forums_Get(ForumId, -1, false, true);

            ReplyController rc    = new ReplyController();
            ReplyInfo       reply = rc.Reply_Get(PortalId, ModuleId, TopicId, ReplyId);

            if (reply == null)
            {
                return(null);
            }
            reply.IsApproved = true;
            rc.Reply_Save(PortalId, reply);
            TopicsController tc = new TopicsController();

            tc.Topics_SaveToForum(ForumId, TopicId, PortalId, ModuleId, ReplyId);
            TopicInfo topic = tc.Topics_Get(PortalId, ModuleId, TopicId, ForumId, -1, false);

            if (fi.ModApproveTemplateId > 0 & reply.Author.AuthorId > 0)
            {
                Email oEmail = new Email();
                oEmail.SendEmail(fi.ModApproveTemplateId, PortalId, ModuleId, TabId, ForumId, TopicId, ReplyId, string.Empty, reply.Author);
            }

            Subscriptions.SendSubscriptions(PortalId, ModuleId, TabId, ForumId, TopicId, ReplyId, reply.Content.AuthorId);

            try
            {
                ControlUtils ctlUtils = new ControlUtils();
                string       fullURL  = ctlUtils.BuildUrl(TabId, ModuleId, fi.ForumGroup.PrefixURL, fi.PrefixURL, fi.ForumGroupId, ForumId, TopicId, topic.TopicUrl, -1, -1, string.Empty, 1, fi.SocialGroupId);

                if (fullURL.Contains("~/"))
                {
                    fullURL = Utilities.NavigateUrl(TabId, "", new string[] { ParamKeys.TopicId + "=" + TopicId, ParamKeys.ContentJumpId + "=" + ReplyId });
                }
                if (fullURL.EndsWith("/"))
                {
                    fullURL += "?" + ParamKeys.ContentJumpId + "=" + ReplyId;
                }
                Social amas = new Social();
                amas.AddReplyToJournal(PortalId, ModuleId, ForumId, TopicId, ReplyId, reply.Author.AuthorId, fullURL, reply.Content.Subject, string.Empty, reply.Content.Body, fi.ActiveSocialSecurityOption, fi.Security.Read, fi.SocialGroupId);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
            }
            return(reply);
        }
Example #4
0
        public void SendEmail(int TemplateId, int PortalId, int ModuleId, int TabId, int ForumId, int TopicId, int ReplyId, string Comments, Author author)
        {
            var          _portalSettings = (Entities.Portals.PortalSettings)(HttpContext.Current.Items["PortalSettings"]);
            SettingsInfo MainSettings    = DataCache.MainSettings(ModuleId);
            string       Subject;
            string       BodyText;
            string       BodyHTML;
            string       sTemplate = string.Empty;
            var          tc        = new TemplateController();
            TemplateInfo ti        = tc.Template_Get(TemplateId, PortalId, ModuleId);

            Subject  = TemplateUtils.ParseEmailTemplate(ti.Subject, string.Empty, PortalId, ModuleId, TabId, ForumId, TopicId, ReplyId, string.Empty, author.AuthorId, _portalSettings.TimeZoneOffset);
            BodyText = TemplateUtils.ParseEmailTemplate(ti.TemplateText, string.Empty, PortalId, ModuleId, TabId, ForumId, TopicId, ReplyId, string.Empty, author.AuthorId, _portalSettings.TimeZoneOffset);
            BodyHTML = TemplateUtils.ParseEmailTemplate(ti.TemplateHTML, string.Empty, PortalId, ModuleId, TabId, ForumId, TopicId, ReplyId, string.Empty, author.AuthorId, _portalSettings.TimeZoneOffset);
            BodyText = BodyText.Replace("[REASON]", Comments);
            BodyHTML = BodyHTML.Replace("[REASON]", Comments);
            string sFrom;
            var    fc = new ForumController();
            Forum  fi = fc.Forums_Get(ForumId, -1, false, true);

            sFrom = fi.EmailAddress != string.Empty ? fi.EmailAddress : _portalSettings.Email;
            //Send now
            var oEmail = new Email();
            var subs   = new List <SubscriptionInfo>();
            var si     = new SubscriptionInfo
            {
                DisplayName = author.DisplayName,
                Email       = author.Email,
                FirstName   = author.FirstName,
                LastName    = author.LastName,
                UserId      = author.AuthorId,
                Username    = author.Username
            };

            subs.Add(si);
            oEmail.UseQueue           = MainSettings.MailQueue;
            oEmail.Recipients         = subs;
            oEmail.Subject            = Subject;
            oEmail.From               = sFrom;
            oEmail.BodyText           = BodyText;
            oEmail.BodyHTML           = BodyHTML;
            oEmail.SmtpServer         = Host.SMTPServer;         // Convert.ToString(_portalSettings.HostSettings["SMTPServer"]);
            oEmail.SmtpUserName       = Host.SMTPUsername;       // Convert.ToString(_portalSettings.HostSettings["SMTPUsername"]);
            oEmail.SmtpPassword       = Host.SMTPPassword;       // Convert.ToString(_portalSettings.HostSettings["SMTPPassword"]);
            oEmail.SmtpAuthentication = Host.SMTPAuthentication; //  Convert.ToString(_portalSettings.HostSettings["SMTPAuthentication"]);
            var objThread = new System.Threading.Thread(oEmail.Send);

            objThread.Start();
        }
        public HttpResponseMessage RunMaintenance(RunMaintenanceDTO dto)
        {
            var objModules  = new Entities.Modules.ModuleController();
            var objSettings = new SettingsInfo {
                MainSettings = objModules.GetModuleSettings(dto.ModuleId)
            };
            var rows = DataProvider.Instance().Forum_Maintenance(dto.ForumId, dto.OlderThan, dto.LastActive, dto.ByUserId, dto.WithNoReplies, dto.DryRun, objSettings.DeleteBehavior);

            if (dto.DryRun)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, new { Result = string.Format(Utilities.GetSharedResource("[RESX:Maint:DryRunResults]", true), rows.ToString()) }));
            }

            return(Request.CreateResponse(HttpStatusCode.OK, new { Result = Utilities.GetSharedResource("[RESX:ProcessComplete]", true) }));
        }
        public HttpResponseMessage ToggleURLHandler(ToggleUrlHandlerDTO dto)
        {
            var objModules = new Entities.Modules.ModuleController();
            var objSettings = new SettingsInfo { MainSettings = objModules.GetModuleSettings(dto.ModuleId) };
            var cfg = new ConfigUtils();
            bool success;
            if (Utilities.IsRewriteLoaded())
            {
                cfg.DisableRewriter(HttpContext.Current.Server.MapPath("~/web.config"));
                return Request.CreateResponse(HttpStatusCode.OK, "disabled");
            }

            cfg.EnableRewriter(HttpContext.Current.Server.MapPath("~/web.config"));
            return Request.CreateResponse(HttpStatusCode.OK, "enabled");
        }
Example #7
0
        public static void SendSubscriptions(int TemplateId, int PortalId, int ModuleId, int TabId, Forum fi, int TopicId, int ReplyId, int AuthorId)
        {
            var                     _portalSettings = (Entities.Portals.PortalSettings)(HttpContext.Current.Items["PortalSettings"]);
            SettingsInfo            MainSettings    = DataCache.MainSettings(ModuleId);
            var                     sc   = new SubscriptionController();
            List <SubscriptionInfo> subs = sc.Subscription_GetSubscribers(PortalId, fi.ForumID, TopicId, SubscriptionTypes.Instant, AuthorId, fi.Security.Subscribe);

            if (subs.Count <= 0)
            {
                return;
            }

            string       Subject;
            string       BodyText;
            string       BodyHTML;
            string       sTemplate = string.Empty;
            var          tc        = new TemplateController();
            TemplateInfo ti;

            ti       = TemplateId > 0 ? tc.Template_Get(TemplateId) : tc.Template_Get("SubscribedEmail", PortalId, ModuleId);
            Subject  = TemplateUtils.ParseEmailTemplate(ti.Subject, string.Empty, PortalId, ModuleId, TabId, fi.ForumID, TopicId, ReplyId, string.Empty, AuthorId, _portalSettings.TimeZoneOffset);
            BodyText = TemplateUtils.ParseEmailTemplate(ti.TemplateText, string.Empty, PortalId, ModuleId, TabId, fi.ForumID, TopicId, ReplyId, string.Empty, AuthorId, _portalSettings.TimeZoneOffset);
            BodyHTML = TemplateUtils.ParseEmailTemplate(ti.TemplateHTML, string.Empty, PortalId, ModuleId, TabId, fi.ForumID, TopicId, ReplyId, string.Empty, AuthorId, _portalSettings.TimeZoneOffset);
            string sFrom;

            sFrom = fi.EmailAddress != string.Empty ? fi.EmailAddress : _portalSettings.Email;
            var oEmail = new Email
            {
                Recipients         = subs,
                Subject            = Subject,
                From               = sFrom,
                BodyText           = BodyText,
                BodyHTML           = BodyHTML,
                SmtpServer         = Host.SMTPServer,                     // Convert.ToString(_portalSettings.HostSettings["SMTPServer"]),
                SmtpUserName       = Host.SMTPUsername,                   // Convert.ToString(_portalSettings.HostSettings["SMTPUsername"]),
                SmtpPassword       = Host.SMTPPassword,                   // Convert.ToString(_portalSettings.HostSettings["SMTPPassword"]),
                SmtpAuthentication = Host.SMTPAuthentication,             // Convert.ToString(_portalSettings.HostSettings["SMTPAuthentication"]),
                SmtpSSL            = Host.EnableSMTPSSL.ToString(),       // Convert.ToString(_portalSettings.HostSettings["SMTPEnableSSL"]),
                UseQueue           = MainSettings.MailQueue
            };


            var objThread = new System.Threading.Thread(oEmail.Send);

            objThread.Start();
        }
        public HttpResponseMessage ToggleURLHandler(ToggleUrlHandlerDTO dto)
        {
            var objModules  = new Entities.Modules.ModuleController();
            var objSettings = new SettingsInfo {
                MainSettings = objModules.GetModuleSettings(dto.ModuleId)
            };
            var  cfg = new ConfigUtils();
            bool success;

            if (Utilities.IsRewriteLoaded())
            {
                cfg.DisableRewriter(HttpContext.Current.Server.MapPath("~/web.config"));
                return(Request.CreateResponse(HttpStatusCode.OK, "disabled"));
            }

            cfg.EnableRewriter(HttpContext.Current.Server.MapPath("~/web.config"));
            return(Request.CreateResponse(HttpStatusCode.OK, "enabled"));
        }
Example #9
0
        public static SettingsInfo MainSettings(int MID)
        {
            object obj = CacheRetrieve(string.Format(CacheKeys.MainSettings, MID));

            if (obj == null || disableCache)
            {
                var objSettings = new SettingsInfo();
                var sb          = new SettingsBase {
                    ForumModuleId = MID
                };
                obj = sb.MainSettings;
                if (disableCache == false)
                {
                    CacheStore(string.Format(CacheKeys.MainSettings, MID), obj);
                }
            }

            return((SettingsInfo)obj);
        }
        public static void SendSubscriptions(int TemplateId, int PortalId, int ModuleId, int TabId, Forum fi, int TopicId, int ReplyId, int AuthorId)
        {
            var                     _portalSettings = (Entities.Portals.PortalSettings)(HttpContext.Current.Items["PortalSettings"]);
            SettingsInfo            MainSettings    = DataCache.MainSettings(ModuleId);
            var                     sc   = new SubscriptionController();
            List <SubscriptionInfo> subs = sc.Subscription_GetSubscribers(PortalId, fi.ForumID, TopicId, SubscriptionTypes.Instant, AuthorId, fi.Security.Subscribe);

            if (subs.Count <= 0)
            {
                return;
            }

            string       Subject;
            string       BodyText;
            string       BodyHTML;
            string       sTemplate = string.Empty;
            var          tc        = new TemplateController();
            TemplateInfo ti;

            ti = TemplateId > 0 ? tc.Template_Get(TemplateId) : tc.Template_Get("SubscribedEmail", PortalId, ModuleId);
            TemplateUtils.lstSubscriptionInfo = subs;
            Subject  = TemplateUtils.ParseEmailTemplate(ti.Subject, string.Empty, PortalId, ModuleId, TabId, fi.ForumID, TopicId, ReplyId, string.Empty, AuthorId, Convert.ToInt32(_portalSettings.TimeZone.BaseUtcOffset.TotalMinutes));
            BodyText = TemplateUtils.ParseEmailTemplate(ti.TemplateText, string.Empty, PortalId, ModuleId, TabId, fi.ForumID, TopicId, ReplyId, string.Empty, AuthorId, Convert.ToInt32(_portalSettings.TimeZone.BaseUtcOffset.TotalMinutes));
            BodyHTML = TemplateUtils.ParseEmailTemplate(ti.TemplateHTML, string.Empty, PortalId, ModuleId, TabId, fi.ForumID, TopicId, ReplyId, string.Empty, AuthorId, Convert.ToInt32(_portalSettings.TimeZone.BaseUtcOffset.TotalMinutes));
            string sFrom;

            sFrom = fi.EmailAddress != string.Empty ? fi.EmailAddress : _portalSettings.Email;
            var oEmail = new Email
            {
                Recipients = subs,
                Subject    = Subject,
                From       = sFrom,
                BodyText   = BodyText,
                BodyHTML   = BodyHTML,
                UseQueue   = MainSettings.MailQueue
            };


            var objThread = new System.Threading.Thread(oEmail.Send);

            objThread.Start();
        }
Example #11
0
        public TopicInfo ApproveTopic(int PortalId, int TabId, int ModuleId, int ForumId, int TopicId)
        {
            SettingsInfo    ms = DataCache.MainSettings(ModuleId);
            ForumController fc = new ForumController();
            Forum           fi = fc.Forums_Get(ForumId, -1, false, true);

            TopicsController tc    = new TopicsController();
            TopicInfo        topic = tc.Topics_Get(PortalId, ModuleId, TopicId, ForumId, -1, false);

            if (topic == null)
            {
                return(null);
            }
            topic.IsApproved = true;
            tc.TopicSave(PortalId, topic);
            tc.Topics_SaveToForum(ForumId, TopicId, PortalId, ModuleId);

            if (fi.ModApproveTemplateId > 0 & topic.Author.AuthorId > 0)
            {
                Email oEmail = new Email();
                oEmail.SendEmail(fi.ModApproveTemplateId, PortalId, ModuleId, TabId, ForumId, TopicId, 0, string.Empty, topic.Author);
            }

            Subscriptions.SendSubscriptions(PortalId, ModuleId, TabId, ForumId, TopicId, 0, topic.Content.AuthorId);

            try
            {
                ControlUtils ctlUtils = new ControlUtils();
                string       sUrl     = ctlUtils.BuildUrl(TabId, ModuleId, fi.ForumGroup.PrefixURL, fi.PrefixURL, fi.ForumGroupId, fi.ForumID, TopicId, topic.TopicUrl, -1, -1, string.Empty, 1, fi.SocialGroupId);
                Social       amas     = new Social();
                amas.AddTopicToJournal(PortalId, ModuleId, ForumId, TopicId, topic.Author.AuthorId, sUrl, topic.Content.Subject, string.Empty, topic.Content.Body, fi.ActiveSocialSecurityOption, fi.Security.Read, fi.SocialGroupId);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
            }
            return(topic);
        }
Example #12
0
        public void SendEmailToModerators(int TemplateId, int PortalId, int ForumId, int TopicId, int ReplyId, int ModuleID, int TabID, string Comments, DotNetNuke.Entities.Users.UserInfo User)
        {
            var          _portalSettings = (Entities.Portals.PortalSettings)(HttpContext.Current.Items["PortalSettings"]);
            SettingsInfo MainSettings    = DataCache.MainSettings(ModuleID);
            var          fc = new ForumController();
            Forum        fi = fc.Forums_Get(ForumId, -1, false, true);

            if (fi == null)
            {
                return;
            }
            var subs = new List <SubscriptionInfo>();
            var rc   = new Security.Roles.RoleController();
            var uc   = new Entities.Users.UserController();
            SubscriptionInfo si;
            string           modApprove = fi.Security.ModApprove;

            string[] modRoles = modApprove.Split('|')[0].Split(';');
            if (modRoles != null)
            {
                foreach (string r in modRoles)
                {
                    if (!(string.IsNullOrEmpty(r)))
                    {
                        int    rid   = Convert.ToInt32(r);
                        string rName = rc.GetRole(rid, PortalId).RoleName;
                        foreach (Entities.Users.UserRoleInfo usr in rc.GetUserRolesByRoleName(PortalId, rName))
                        {
                            var ui = uc.GetUser(PortalId, usr.UserID);
                            si = new SubscriptionInfo
                            {
                                UserId      = ui.UserID,
                                DisplayName = ui.DisplayName,
                                Email       = ui.Email,
                                FirstName   = ui.FirstName,
                                LastName    = ui.LastName
                            };
                            if (!(subs.Contains(si)))
                            {
                                subs.Add(si);
                            }
                        }
                    }
                }
            }

            if (subs.Count <= 0)
            {
                return;
            }
            string       Subject;
            string       BodyText;
            string       BodyHTML;
            string       sTemplate = string.Empty;
            var          tc        = new TemplateController();
            TemplateInfo ti        = tc.Template_Get(TemplateId, PortalId, ModuleID);

            Subject  = TemplateUtils.ParseEmailTemplate(ti.Subject, string.Empty, PortalId, ModuleID, TabID, ForumId, TopicId, ReplyId, _portalSettings.TimeZoneOffset);
            BodyText = TemplateUtils.ParseEmailTemplate(ti.TemplateText, string.Empty, PortalId, ModuleID, TabID, ForumId, TopicId, ReplyId, Comments, User, -1, _portalSettings.TimeZoneOffset);
            BodyHTML = TemplateUtils.ParseEmailTemplate(ti.TemplateHTML, string.Empty, PortalId, ModuleID, TabID, ForumId, TopicId, ReplyId, Comments, User, -1, _portalSettings.TimeZoneOffset);
            string sFrom;

            sFrom = fi.EmailAddress != string.Empty ? fi.EmailAddress : _portalSettings.Email;

            var oEmail = new Email
            {
                Recipients         = subs,
                Subject            = Subject,
                From               = sFrom,
                BodyText           = BodyText,
                BodyHTML           = BodyHTML,
                SmtpServer         = Host.SMTPServer,                     // Convert.ToString(_portalSettings.HostSettings["SMTPServer"]),
                SmtpUserName       = Host.SMTPUsername,                   // Convert.ToString(_portalSettings.HostSettings["SMTPUsername"]),
                SmtpPassword       = Host.SMTPPassword,                   // Convert.ToString(_portalSettings.HostSettings["SMTPPassword"]),
                SmtpAuthentication = Host.SMTPAuthentication              // Convert.ToString(_portalSettings.HostSettings["SMTPAuthentication"])
            };

//#if SKU_ENTERPRISE
            oEmail.UseQueue = MainSettings.MailQueue;
//#endif
            var objThread = new System.Threading.Thread(oEmail.Send);

            objThread.Start();
        }
        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 XmlRpcStruct GetLatestTopics(int startIndex, int endIndex, string searchId, object filters)
        {
            var aftContext = ActiveForumsTapatalkModuleContext.Create(Context);

            if (aftContext == null || aftContext.Module == null)
                throw new XmlRpcFaultException(100, "Invalid Context");

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

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

            // Build a list of forums the user has access to
            var fc = new AFTForumController();
            var forumIds = fc.GetForumsForUser(aftContext.ForumUser.UserRoles, portalId, forumModuleId, "CanRead");

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

            var maxRows = endIndex + 1 - startIndex;

            var latestTopics = fc.GetLatestTopics(portalId, forumModuleId, userId, forumIds, startIndex, maxRows).ToList();

            return new XmlRpcStruct
                       {
                           {"result", true},
                           {"total_topic_num", latestTopics.Count > 0 ? latestTopics[0].TopicCount : 0},
                           {"topics", latestTopics.Select(t => new ExtendedTopicStructure{ 
                                                   TopicId = t.TopicId.ToString(),
                                                   AuthorAvatarUrl = GetAvatarUrl(t.LastReplyAuthorId),
                                                   AuthorId = t.LastReplyAuthorId.ToString(),
                                                   AuthorName = GetLastReplyAuthorName(mainSettings, t).ToBytes(),
                                                   ForumId = t.ForumId.ToString(),
                                                   ForumName = t.ForumName.ToBytes(),
                                                   HasNewPosts =  (t.LastReplyId < 0 && t.TopicId > t.UserLastTopicRead) || t.LastReplyId > t.UserLastReplyRead,
                                                   IsLocked = t.IsLocked,
                                                   IsSubscribed = t.SubscriptionType > 0,
                                                   CanSubscribe = ActiveForums.Permissions.HasPerm(aftContext.ForumUser.UserRoles, fc.GetForumPermissions(t.ForumId).CanSubscribe), // GetforumPermissions uses cache so it shouldn't be a performance issue
                                                   ReplyCount = t.ReplyCount,
                                                   Summary = GetSummary(null, t.LastReplyBody).ToBytes(),
                                                   ViewCount = t.ViewCount,
                                                   DateCreated = t.LastReplyDate,
                                                   Title = HttpUtility.HtmlDecode(t.Subject + string.Empty).ToBytes()
                                               }).ToArray()}
                       };
        }
        public void OnBeginRequest(object s, EventArgs e)
        {
            _forumId      = -1;
            _tabId        = -1;
            _moduleId     = -1;
            _topicId      = -1;
            _page         = 1;
            _contentId    = -1;
            _archived     = 0;
            _forumgroupId = -1;
            _mainSettings = null;
            _categoryId   = -1;
            _tagId        = -1;

            HttpApplication   app           = (HttpApplication)s;
            HttpServerUtility Server        = app.Server;
            HttpRequest       Request       = app.Request;
            HttpResponse      Response      = app.Response;
            string            requestedPath = app.Request.Url.AbsoluteUri;
            HttpContext       Context       = ((HttpApplication)s).Context;
            int PortalId = -1;

            DotNetNuke.Entities.Portals.PortalAliasInfo objPortalAliasInfo = null;
            string sUrl = HttpContext.Current.Request.RawUrl.Replace("http://", string.Empty).Replace("https://", string.Empty);

            objPortalAliasInfo = PortalAliasController.Instance.GetPortalAlias(HttpContext.Current.Request.Url.Host);
            if (Request.RawUrl.ToLowerInvariant().Contains("404.aspx"))
            {
                string sEx = ".jpg,.gif,.png,.swf,.js,.css,.html,.htm,desktopmodules,portals,.ashx,.ico,.txt,.doc,.docx,.pdf,.xml,.xls,.xlsx,.ppt,.pptx,.csv,.zip,.asmx,.aspx";
                foreach (string sn in sEx.Split(','))
                {
                    if (sUrl.Contains(sn))
                    {
                        // IO.File.AppendAllText(sPath, Request.RawUrl & "165<br />")
                        return;
                    }
                }
            }
            if (Request.Url.LocalPath.ToLower().Contains("scriptresource.axd") || Request.Url.LocalPath.ToLower().Contains("webresource.axd") || Request.Url.LocalPath.ToLower().Contains("viewer.aspx") || Request.Url.LocalPath.ToLower().Contains("cb.aspx") || Request.Url.LocalPath.ToLower().Contains("filesupload.aspx") || Request.Url.LocalPath.ToLower().Contains(".gif") || Request.Url.LocalPath.ToLower().Contains(".jpg") || Request.Url.LocalPath.ToLower().Contains(".css") || Request.Url.LocalPath.ToLower().Contains(".png") || Request.Url.LocalPath.ToLower().Contains(".swf") || Request.Url.LocalPath.ToLower().Contains(".htm") || Request.Url.LocalPath.ToLower().Contains(".html") || Request.Url.LocalPath.ToLower().Contains(".ashx") || Request.Url.LocalPath.ToLower().Contains(".cur") || Request.Url.LocalPath.ToLower().Contains(".ico") || Request.Url.LocalPath.ToLower().Contains(".txt") || Request.Url.LocalPath.ToLower().Contains(".pdf") || Request.Url.LocalPath.ToLower().Contains(".xml") || Request.Url.LocalPath.ToLower().Contains("/portals/") || Request.Url.LocalPath.ToLower().Contains("/desktopmodules/") || Request.Url.LocalPath.ToLower().Contains("evexport.aspx") || Request.Url.LocalPath.ToLower().Contains("signupjs.aspx") || Request.Url.LocalPath.ToLower().Contains("evsexport.aspx") || Request.Url.LocalPath.ToLower().Contains("fbcomm.aspx") || Request.Url.LocalPath.ToLower().Contains(".aspx") || Request.Url.LocalPath.ToLower().Contains(".js"))
            {
                return;
            }
            if (Request.Url.LocalPath.ToLower().Contains("install.aspx") || Request.Url.LocalPath.ToLower().Contains("installwizard.aspx") || Request.Url.LocalPath.ToLower().Contains("captcha.aspx") || Request.RawUrl.Contains("viewer.aspx") || Request.RawUrl.Contains("blank.html") || Request.RawUrl.Contains("default.htm") || Request.RawUrl.Contains("autosuggest.aspx"))
            {
                return;
            }
            PortalId = objPortalAliasInfo.PortalID;
            string searchURL = sUrl;

            searchURL = searchURL.Replace(objPortalAliasInfo.HTTPAlias, string.Empty);
            if (searchURL.Length < 2)
            {
                return;
            }
            string query = string.Empty;

            if (searchURL.Contains("?"))
            {
                query     = searchURL.Substring(searchURL.IndexOf("?"));
                searchURL = searchURL.Substring(0, searchURL.IndexOf("?") - 1);
            }
            string newSearchURL = string.Empty;

            foreach (string up in searchURL.Split('/'))
            {
                if (!(string.IsNullOrEmpty(up)))
                {
                    if (!(SimulateIsNumeric.IsNumeric(up)))
                    {
                        newSearchURL += up + "/";
                    }
                }
            }
            bool canContinue = false;

            Data.Common db      = new Data.Common();
            string      tagName = string.Empty;
            string      catName = string.Empty;

            if (newSearchURL.Contains("/category/") || newSearchURL.Contains("/tag/"))
            {
                if (newSearchURL.Contains("/category/"))
                {
                    string cat       = "/category/";
                    int    iEnd      = newSearchURL.IndexOf("/", newSearchURL.IndexOf(cat) + cat.Length + 1);
                    string catString = newSearchURL.Substring(newSearchURL.IndexOf(cat), iEnd - newSearchURL.IndexOf(cat));
                    catName      = catString.Replace(cat, string.Empty);
                    catName      = catName.Replace("/", string.Empty);
                    newSearchURL = newSearchURL.Replace(catString, string.Empty);
                }
                if (newSearchURL.Contains("/tag/"))
                {
                    string tag       = "/tag/";
                    int    iEnd      = newSearchURL.IndexOf("/", newSearchURL.IndexOf(tag) + tag.Length + 1);
                    string tagString = newSearchURL.Substring(newSearchURL.IndexOf(tag), iEnd - newSearchURL.IndexOf(tag));
                    tagName      = tagString.Replace(tag, string.Empty);
                    tagName      = tagName.Replace("/", string.Empty);
                    newSearchURL = newSearchURL.Replace(tagString, string.Empty);
                }
            }
            if ((sUrl.Contains("afv") && sUrl.Contains("post")) | (sUrl.Contains("afv") && sUrl.Contains("confirmaction")) | (sUrl.Contains("afv") && sUrl.Contains("sendto")) | (sUrl.Contains("afv") && sUrl.Contains("modreport")) | (sUrl.Contains("afv") && sUrl.Contains("search")) | sUrl.Contains("dnnprintmode") || sUrl.Contains("asg") || (sUrl.Contains("afv") && sUrl.Contains("modtopics")))
            {
                return;
            }
            try
            {
                using (IDataReader dr = db.URLSearch(PortalId, newSearchURL))
                {
                    while (dr.Read())
                    {
                        _tabId        = int.Parse(dr["TabID"].ToString());
                        _moduleId     = int.Parse(dr["ModuleId"].ToString());
                        _forumgroupId = int.Parse(dr["ForumGroupId"].ToString());
                        _forumId      = int.Parse(dr["ForumId"].ToString());
                        _topicId      = int.Parse(dr["TopicId"].ToString());
                        _archived     = int.Parse(dr["Archived"].ToString());
                        _otherId      = int.Parse(dr["OtherId"].ToString());
                        _urlType      = int.Parse(dr["UrlType"].ToString());
                        canContinue   = true;
                    }
                    dr.Close();
                }
            }
            catch (Exception ex)
            {
            }
            if (!(string.IsNullOrEmpty(catName)))
            {
                _categoryId = db.Tag_GetIdByName(PortalId, _moduleId, catName, true);
                _otherId    = _categoryId;
                _urlType    = 2;
            }
            if (!(string.IsNullOrEmpty(tagName)))
            {
                _tagId   = db.Tag_GetIdByName(PortalId, _moduleId, tagName, false);
                _otherId = _tagId;
                _urlType = 3;
            }

            if (_archived == 1)
            {
                sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1);
                if (!(string.IsNullOrEmpty(sUrl)))
                {
                    string sHost = objPortalAliasInfo.HTTPAlias;
                    if (sUrl.StartsWith("/"))
                    {
                        sUrl = sUrl.Substring(1);
                    }
                    if (!(sHost.EndsWith("/")))
                    {
                        sHost += "/";
                    }
                    sUrl = sHost + sUrl;
                    if (!(sUrl.EndsWith("/")))
                    {
                        sUrl += "/";
                    }
                    if (!(sUrl.StartsWith("http")))
                    {
                        if (Request.IsSecureConnection)
                        {
                            sUrl = "https://" + sUrl;
                        }
                        else
                        {
                            sUrl = "http://" + sUrl;
                        }
                    }
                    Response.Clear();
                    Response.Status = "301 Moved Permanently";
                    Response.AddHeader("Location", sUrl);
                    Response.End();
                }
            }
            if (_moduleId > 0)
            {
                Entities.Modules.ModuleController objModules = new Entities.Modules.ModuleController();
                SettingsInfo objSettings = new SettingsInfo();
                objSettings.MainSettings = objModules.GetModuleSettings(_moduleId);
                _mainSettings            = objSettings;      // DataCache.MainSettings(_moduleId)
            }
            if (_mainSettings == null)
            {
                return;
            }
            if (!_mainSettings.URLRewriteEnabled)
            {
                return;
            }
            if (!canContinue && (Request.RawUrl.Contains(ParamKeys.TopicId) || Request.RawUrl.Contains(ParamKeys.ForumId) || Request.RawUrl.Contains(ParamKeys.GroupId)))
            {
                sUrl = HandleOldUrls(Request.RawUrl, objPortalAliasInfo.HTTPAlias);
                if (!(string.IsNullOrEmpty(sUrl)))
                {
                    if (!(sUrl.StartsWith("http")))
                    {
                        if (Request.IsSecureConnection)
                        {
                            sUrl = "https://" + sUrl;
                        }
                        else
                        {
                            sUrl = "http://" + sUrl;
                        }
                    }
                    Response.Clear();
                    Response.Status = "301 Moved Permanently";
                    Response.AddHeader("Location", sUrl);
                    Response.End();
                }
            }
            if (!canContinue)
            {
                string topicUrl = string.Empty;
                if (newSearchURL.EndsWith("/"))
                {
                    newSearchURL = newSearchURL.Substring(0, newSearchURL.Length - 1);
                }
                if (newSearchURL.Contains("/"))
                {
                    topicUrl = newSearchURL.Substring(newSearchURL.LastIndexOf("/"));
                }
                topicUrl = topicUrl.Replace("/", string.Empty);
                if (!(string.IsNullOrEmpty(topicUrl)))
                {
                    Data.Topics topicsDb = new Data.Topics();
                    _topicId = topicsDb.TopicIdByUrl(PortalId, _moduleId, topicUrl.ToLowerInvariant());
                    if (_topicId > 0)
                    {
                        sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1);
                    }
                    else
                    {
                        sUrl = string.Empty;
                    }
                    if (!(string.IsNullOrEmpty(sUrl)))
                    {
                        string sHost = objPortalAliasInfo.HTTPAlias;
                        if (sHost.EndsWith("/") && sUrl.StartsWith("/"))
                        {
                            sUrl = sHost.Substring(0, sHost.Length - 1) + sUrl;
                        }
                        else if (!(sHost.EndsWith("/")) && !(sUrl.StartsWith("/")))
                        {
                            sUrl = sHost + "/" + sUrl;
                        }
                        else
                        {
                            sUrl = sHost + sUrl;
                        }
                        if (sUrl.StartsWith("/"))
                        {
                            sUrl = sUrl.Substring(1);
                        }
                        if (!(sUrl.StartsWith("http")))
                        {
                            if (Request.IsSecureConnection)
                            {
                                sUrl = "https://" + sUrl;
                            }
                            else
                            {
                                sUrl = "http://" + sUrl;
                            }
                        }
                        if (!(string.IsNullOrEmpty(sUrl)))
                        {
                            Response.Clear();
                            Response.Status = "301 Moved Permanently";
                            Response.AddHeader("Location", sUrl);
                            Response.End();
                        }
                    }
                }
            }

            if (canContinue)
            {
                if (searchURL != newSearchURL)
                {
                    string urlTail = searchURL.Replace(newSearchURL, string.Empty);
                    if (urlTail.StartsWith("/"))
                    {
                        urlTail = urlTail.Substring(1);
                    }
                    if (urlTail.EndsWith("/"))
                    {
                        urlTail = urlTail.Substring(0, urlTail.Length - 1);
                    }
                    if (urlTail.Contains("/"))
                    {
                        urlTail = urlTail.Substring(0, urlTail.IndexOf("/") - 1);
                    }
                    if (SimulateIsNumeric.IsNumeric(urlTail))
                    {
                        _page = Convert.ToInt32(urlTail);
                    }
                }

                string sPage = string.Empty;
                sPage = "&afpg=" + _page.ToString();
                string qs = string.Empty;
                if (sUrl.Contains("?"))
                {
                    qs = "&" + sUrl.Substring(sUrl.IndexOf("?") + 1);
                }
                string catQS = string.Empty;
                if (_categoryId > 0)
                {
                    catQS = "&act=" + _categoryId.ToString();
                }
                string sendTo = string.Empty;
                if (_topicId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&aft=" + _topicId + sPage + qs);
                }
                else if (_forumId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&aff=" + _forumId + sPage + qs + catQS);
                }
                else if (_forumgroupId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afg=" + _forumgroupId + sPage + qs + catQS);
                }
                else if (_urlType == 2 && _otherId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&act=" + _otherId + sPage + qs);
                }
                else if (_urlType == 3 && _otherId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=tags&aftg=" + _otherId + sPage + qs);
                }
                else if (_urlType == 1)
                {
                    string v = string.Empty;
                    switch (_otherId)
                    {
                    case 1:
                        v = "unanswered";
                        break;

                    case 2:
                        v = "notread";
                        break;

                    case 3:
                        v = "mytopics";
                        break;

                    case 4:
                        v = "activetopics";
                        break;

                    case 5:
                        v = "afprofile";
                        break;
                    }
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=" + v + sPage + qs);
                }
                else if (_tabId > 0)
                {
                    sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + sPage + qs);
                }

                RewriteUrl(app.Context, sendTo);
            }
        }
        private TopicListStructure GetTopic(int forumId, int startIndex, int endIndex, string mode = null)
        {
            var aftContext = ActiveForumsTapatalkModuleContext.Create(Context);

            if (aftContext == null || aftContext.Module == null)
                throw new XmlRpcFaultException(100, "Invalid 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 fp = fc.GetForumPermissions(forumId);

            if (!ActiveForums.Permissions.HasPerm(aftContext.ForumUser.UserRoles, fp.CanRead))
                throw new XmlRpcFaultException(100, "No Read Permissions");

            var maxRows = endIndex + 1 - startIndex;

            var forumTopicsSummary = fc.GetForumTopicSummary(portalId, forumModuleId, forumId, aftContext.UserId, mode);
            var forumTopics = fc.GetForumTopics(portalId, forumModuleId, forumId, aftContext.UserId, startIndex, maxRows, mode);

            var canSubscribe = ActiveForums.Permissions.HasPerm(aftContext.ForumUser.UserRoles, fp.CanSubscribe);

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

            var profilePath = string.Format("{0}://{1}{2}", Context.Request.Url.Scheme, Context.Request.Url.Host, VirtualPathUtility.ToAbsolute("~/profilepic.ashx"));

            var forumTopicsStructure = new TopicListStructure
                                           {
                                               CanPost = ActiveForums.Permissions.HasPerm(aftContext.ForumUser.UserRoles, fp.CanCreate),
                                               ForumId = forumId.ToString(),
                                               ForumName = forumTopicsSummary.ForumName.ToBytes(),
                                               TopicCount = forumTopicsSummary.TopicCount,
                                               Topics = forumTopics.Select(t => new TopicStructure{ 
                                                   TopicId = t.TopicId.ToString(),
                                                   AuthorAvatarUrl = string.Format("{0}?userId={1}&w=64&h=64", profilePath, t.AuthorId),
                                                   AuthorName = GetAuthorName(mainSettings, t).ToBytes(),
                                                   CanSubscribe = canSubscribe,
                                                   ForumId = forumId.ToString(),
                                                   HasNewPosts = (t.LastReplyId < 0 && t.TopicId > t.UserLastTopicRead) || t.LastReplyId > t.UserLastReplyRead,
                                                   IsLocked = t.IsLocked,
                                                   IsSubscribed = t.SubscriptionType > 0,
                                                   LastReplyDate = t.LastReplyDate,
                                                   ReplyCount = t.ReplyCount,
                                                   Summary = GetSummary(t.Summary, t.Body).ToBytes(),
                                                   ViewCount = t.ViewCount,
                                                   Title = HttpUtility.HtmlDecode(t.Subject + string.Empty).ToBytes()
                                               }).ToArray()
                                           };



            return forumTopicsStructure;
        }
Example #17
0
		public void OnBeginRequest(object s, EventArgs e)
		{
			_forumId = -1;
			_tabId = -1;
			_moduleId = -1;
			_topicId = -1;
			_page = 1;
			_contentId = -1;
			_archived = 0;
			_forumgroupId = -1;
			_mainSettings = null;
			_categoryId = -1;
			_tagId = -1;

			HttpApplication app = (HttpApplication)s;
			HttpServerUtility Server = app.Server;
			HttpRequest Request = app.Request;
			HttpResponse Response = app.Response;
			string requestedPath = app.Request.Url.AbsoluteUri;
			HttpContext Context = ((HttpApplication)s).Context;
			int PortalId = -1;
			DotNetNuke.Entities.Portals.PortalAliasInfo objPortalAliasInfo = null;
			string sUrl = HttpContext.Current.Request.RawUrl.Replace("http://", string.Empty).Replace("https://", string.Empty);
			objPortalAliasInfo = DotNetNuke.Entities.Portals.PortalSettings.GetPortalAliasInfo(HttpContext.Current.Request.Url.Host);
			if (Request.RawUrl.ToLowerInvariant().Contains("404.aspx"))
			{
				string sEx = ".jpg,.gif,.png,.swf,.js,.css,.html,.htm,desktopmodules,portals,.ashx,.ico,.txt,.doc,.docx,.pdf,.xml,.xls,.xlsx,.ppt,.pptx,.csv,.zip,.asmx,.aspx";
				foreach (string sn in sEx.Split(','))
				{
					if (sUrl.Contains(sn))
					{
						// IO.File.AppendAllText(sPath, Request.RawUrl & "165<br />")
						return;
					}
				}
			}
			if (Request.Url.LocalPath.ToLower().Contains("scriptresource.axd") || Request.Url.LocalPath.ToLower().Contains("webresource.axd") || Request.Url.LocalPath.ToLower().Contains("viewer.aspx") || Request.Url.LocalPath.ToLower().Contains("cb.aspx") || Request.Url.LocalPath.ToLower().Contains("filesupload.aspx") || Request.Url.LocalPath.ToLower().Contains(".gif") || Request.Url.LocalPath.ToLower().Contains(".jpg") || Request.Url.LocalPath.ToLower().Contains(".css") || Request.Url.LocalPath.ToLower().Contains(".png") || Request.Url.LocalPath.ToLower().Contains(".swf") || Request.Url.LocalPath.ToLower().Contains(".htm") || Request.Url.LocalPath.ToLower().Contains(".html") || Request.Url.LocalPath.ToLower().Contains(".ashx") || Request.Url.LocalPath.ToLower().Contains(".cur") || Request.Url.LocalPath.ToLower().Contains(".ico") || Request.Url.LocalPath.ToLower().Contains(".txt") || Request.Url.LocalPath.ToLower().Contains(".pdf") || Request.Url.LocalPath.ToLower().Contains(".xml") || Request.Url.LocalPath.ToLower().Contains("/portals/") || Request.Url.LocalPath.ToLower().Contains("/desktopmodules/") || Request.Url.LocalPath.ToLower().Contains("evexport.aspx") || Request.Url.LocalPath.ToLower().Contains("signupjs.aspx") || Request.Url.LocalPath.ToLower().Contains("evsexport.aspx") || Request.Url.LocalPath.ToLower().Contains("fbcomm.aspx") || Request.Url.LocalPath.ToLower().Contains(".aspx") || Request.Url.LocalPath.ToLower().Contains(".js"))
			{
				return;
			}
			if (Request.Url.LocalPath.ToLower().Contains("install.aspx") || Request.Url.LocalPath.ToLower().Contains("installwizard.aspx") || Request.Url.LocalPath.ToLower().Contains("captcha.aspx") || Request.RawUrl.Contains("viewer.aspx") || Request.RawUrl.Contains("blank.html") || Request.RawUrl.Contains("default.htm") || Request.RawUrl.Contains("autosuggest.aspx"))
			{
				return;
			}
			PortalId = objPortalAliasInfo.PortalID;
			string searchURL = sUrl;
			searchURL = searchURL.Replace(objPortalAliasInfo.HTTPAlias, string.Empty);
			if (searchURL.Length < 2)
			{
				return;
			}
			string query = string.Empty;
			if (searchURL.Contains("?"))
			{
				query = searchURL.Substring(searchURL.IndexOf("?"));
				searchURL = searchURL.Substring(0, searchURL.IndexOf("?") - 1);
			}
			string newSearchURL = string.Empty;
			foreach (string up in searchURL.Split('/'))
			{
				if (! (string.IsNullOrEmpty(up)))
				{
					if (! (SimulateIsNumeric.IsNumeric(up)))
					{
						newSearchURL += up + "/";
					}
				}
			}
			bool canContinue = false;
			Data.Common db = new Data.Common();
			string tagName = string.Empty;
			string catName = string.Empty;
			if (newSearchURL.Contains("/category/") || newSearchURL.Contains("/tag/"))
			{
				if (newSearchURL.Contains("/category/"))
				{
					string cat = "/category/";
					int iEnd = newSearchURL.IndexOf("/", newSearchURL.IndexOf(cat) + cat.Length + 1);
					string catString = newSearchURL.Substring(newSearchURL.IndexOf(cat), iEnd - newSearchURL.IndexOf(cat));
					catName = catString.Replace(cat, string.Empty);
					catName = catName.Replace("/", string.Empty);
					newSearchURL = newSearchURL.Replace(catString, string.Empty);
				}
				if (newSearchURL.Contains("/tag/"))
				{
					string tag = "/tag/";
					int iEnd = newSearchURL.IndexOf("/", newSearchURL.IndexOf(tag) + tag.Length + 1);
					string tagString = newSearchURL.Substring(newSearchURL.IndexOf(tag), iEnd - newSearchURL.IndexOf(tag));
					tagName = tagString.Replace(tag, string.Empty);
					tagName = tagName.Replace("/", string.Empty);
					newSearchURL = newSearchURL.Replace(tagString, string.Empty);
				}
			}
			if ((sUrl.Contains("afv") && sUrl.Contains("post")) | (sUrl.Contains("afv") && sUrl.Contains("confirmaction")) | (sUrl.Contains("afv") && sUrl.Contains("sendto")) | (sUrl.Contains("afv") && sUrl.Contains("modreport")) | (sUrl.Contains("afv") && sUrl.Contains("search")) | sUrl.Contains("dnnprintmode") || sUrl.Contains("asg") || (sUrl.Contains("afv") && sUrl.Contains("modtopics")))
			{
				return;
			}
			try
			{
				using (IDataReader dr = db.URLSearch(PortalId, newSearchURL))
				{
					while (dr.Read())
					{
						_tabId = int.Parse(dr["TabID"].ToString());
						_moduleId = int.Parse(dr["ModuleId"].ToString());
						_forumgroupId = int.Parse(dr["ForumGroupId"].ToString());
						_forumId = int.Parse(dr["ForumId"].ToString());
						_topicId = int.Parse(dr["TopicId"].ToString());
						_archived = int.Parse(dr["Archived"].ToString());
						_otherId = int.Parse(dr["OtherId"].ToString());
						_urlType = int.Parse(dr["UrlType"].ToString());
						canContinue = true;
					}
					dr.Close();
				}
			}
			catch (Exception ex)
			{

			}
			if (! (string.IsNullOrEmpty(catName)))
			{
				_categoryId = db.Tag_GetIdByName(PortalId, _moduleId, catName, true);
				_otherId = _categoryId;
				_urlType = 2;
			}
			if (! (string.IsNullOrEmpty(tagName)))
			{
				_tagId = db.Tag_GetIdByName(PortalId, _moduleId, tagName, false);
				_otherId = _tagId;
				_urlType = 3;
			}

			if (_archived == 1)
			{
				sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1);
				if (! (string.IsNullOrEmpty(sUrl)))
				{
					string sHost = objPortalAliasInfo.HTTPAlias;
					if (sUrl.StartsWith("/"))
					{
						sUrl = sUrl.Substring(1);
					}
					if (! (sHost.EndsWith("/")))
					{
						sHost += "/";
					}
					sUrl = sHost + sUrl;
					if (! (sUrl.EndsWith("/")))
					{
						sUrl += "/";
					}
					if (! (sUrl.StartsWith("http")))
					{
						if (Request.IsSecureConnection)
						{
							sUrl = "https://" + sUrl;
						}
						else
						{
							sUrl = "http://" + sUrl;
						}
					}
					Response.Clear();
					Response.Status = "301 Moved Permanently";
					Response.AddHeader("Location", sUrl);
					Response.End();

				}
			}
			if (_moduleId > 0)
			{
				Entities.Modules.ModuleController objModules = new Entities.Modules.ModuleController();
				SettingsInfo objSettings = new SettingsInfo();
				objSettings.MainSettings = objModules.GetModuleSettings(_moduleId);
				_mainSettings = objSettings; // DataCache.MainSettings(_moduleId)
			}
			if (_mainSettings == null)
			{
				return;
			}
			if (! _mainSettings.URLRewriteEnabled)
			{
				return;
			}
			if (! canContinue && (Request.RawUrl.Contains(ParamKeys.TopicId) || Request.RawUrl.Contains(ParamKeys.ForumId) || Request.RawUrl.Contains(ParamKeys.GroupId)))
			{
				sUrl = HandleOldUrls(Request.RawUrl, objPortalAliasInfo.HTTPAlias);
				if (! (string.IsNullOrEmpty(sUrl)))
				{
					if (! (sUrl.StartsWith("http")))
					{
						if (Request.IsSecureConnection)
						{
							sUrl = "https://" + sUrl;
						}
						else
						{
							sUrl = "http://" + sUrl;
						}
					}
					Response.Clear();
					Response.Status = "301 Moved Permanently";
					Response.AddHeader("Location", sUrl);
					Response.End();
				}
			}
			if (! canContinue)
			{
				string topicUrl = string.Empty;
				if (newSearchURL.EndsWith("/"))
				{
					newSearchURL = newSearchURL.Substring(0, newSearchURL.Length - 1);
				}
				if (newSearchURL.Contains("/"))
				{
					topicUrl = newSearchURL.Substring(newSearchURL.LastIndexOf("/"));
				}
				topicUrl = topicUrl.Replace("/", string.Empty);
				if (! (string.IsNullOrEmpty(topicUrl)))
				{
					Data.Topics topicsDb = new Data.Topics();
					_topicId = topicsDb.TopicIdByUrl(PortalId, _moduleId, topicUrl.ToLowerInvariant());
					if (_topicId > 0)
					{
						sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1);
					}
					else
					{
						sUrl = string.Empty;
					}
					if (! (string.IsNullOrEmpty(sUrl)))
					{
						string sHost = objPortalAliasInfo.HTTPAlias;
						if (sHost.EndsWith("/") && sUrl.StartsWith("/"))
						{
							sUrl = sHost.Substring(0, sHost.Length - 1) + sUrl;
						}
						else if (! (sHost.EndsWith("/")) && ! (sUrl.StartsWith("/")))
						{
							sUrl = sHost + "/" + sUrl;
						}
						else
						{
							sUrl = sHost + sUrl;
						}
						if (sUrl.StartsWith("/"))
						{
							sUrl = sUrl.Substring(1);
						}
						if (! (sUrl.StartsWith("http")))
						{
							if (Request.IsSecureConnection)
							{
								sUrl = "https://" + sUrl;
							}
							else
							{
								sUrl = "http://" + sUrl;
							}
						}
						if (! (string.IsNullOrEmpty(sUrl)))
						{
							Response.Clear();
							Response.Status = "301 Moved Permanently";
							Response.AddHeader("Location", sUrl);
							Response.End();
						}
					}
				}

			}

			if (canContinue)
			{
				if (searchURL != newSearchURL)
				{
					string urlTail = searchURL.Replace(newSearchURL, string.Empty);
					if (urlTail.StartsWith("/"))
					{
						urlTail = urlTail.Substring(1);
					}
					if (urlTail.EndsWith("/"))
					{
						urlTail = urlTail.Substring(0, urlTail.Length - 1);
					}
					if (urlTail.Contains("/"))
					{
						urlTail = urlTail.Substring(0, urlTail.IndexOf("/") - 1);
					}
					if (SimulateIsNumeric.IsNumeric(urlTail))
					{
						_page = Convert.ToInt32(urlTail);
					}
				}

				string sPage = string.Empty;
				sPage = "&afpg=" + _page.ToString();
				string qs = string.Empty;
				if (sUrl.Contains("?"))
				{
					qs = "&" + sUrl.Substring(sUrl.IndexOf("?") + 1);
				}
				string catQS = string.Empty;
				if (_categoryId > 0)
				{
					catQS = "&act=" + _categoryId.ToString();
				}
				string sendTo = string.Empty;
				if (_topicId > 0)
				{
					sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&aft=" + _topicId + sPage + qs);
				}
				else if (_forumId > 0)
				{
					sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&aff=" + _forumId + sPage + qs + catQS);
				}
				else if (_forumgroupId > 0)
				{
					sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afg=" + _forumgroupId + sPage + qs + catQS);
				}
				else if (_urlType == 2 && _otherId > 0)
				{
					sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&act=" + _otherId + sPage + qs);
				}
				else if (_urlType == 3 && _otherId > 0)
				{
					sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=tags&aftg=" + _otherId + sPage + qs);
				}
				else if (_urlType == 1)
				{
					string v = string.Empty;
					switch (_otherId)
					{
						case 1:
							v = "unanswered";
							break;
						case 2:
							v = "notread";
							break;
						case 3:
							v = "mytopics";
							break;
						case 4:
							v = "activetopics";
							break;
					}
					sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=" + v + sPage + qs);
				}
				else if (_tabId > 0)
				{
					sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + sPage + qs);
				}

				RewriteUrl(app.Context, sendTo);
			}
		}
Example #18
0
        private void cbMod_Callback(object sender, Modules.ActiveForums.Controls.CallBackEventArgs e)
        {
            SettingsInfo ms = DataCache.MainSettings(ForumModuleId);
            Forum        fi = null;

            if (e.Parameters.Length > 0)
            {
                if (ForumId < 1)
                {
                    SetPermissions(Convert.ToInt32(e.Parameters[1]));
                    ForumController fc = new ForumController();
                    fi = fc.Forums_Get(Convert.ToInt32(e.Parameters[1]), -1, false, true);
                }
                else
                {
                    fi = ForumInfo;
                }
                switch (e.Parameters[0].ToLowerInvariant())
                {
                case "moddel":
                {
                    if (bModDelete)
                    {
                        int delAction  = ms.DeleteBehavior;
                        int tmpForumId = -1;
                        int tmpTopicId = -1;
                        int tmpReplyId = -1;
                        tmpForumId = Convert.ToInt32(e.Parameters[1]);
                        tmpTopicId = Convert.ToInt32(e.Parameters[2]);
                        tmpReplyId = Convert.ToInt32(e.Parameters[3]);
                        Author auth = null;
                        if (fi.ModDeleteTemplateId > 0)
                        {
                            try
                            {
                                //Email.SendEmail(fi.ModDeleteTemplateId, PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, string.Empty, auth);
                                Email.SendEmailToModerators(fi.ModDeleteTemplateId, PortalId, tmpForumId, tmpTopicId, tmpReplyId, ForumModuleId, ForumTabId, string.Empty);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                        if (tmpForumId > 0 & tmpTopicId > 0 && tmpReplyId == 0)
                        {
                            TopicsController tc = new TopicsController();
                            TopicInfo        ti = tc.Topics_Get(PortalId, ForumModuleId, tmpTopicId);
                            if (ti != null)
                            {
                                auth = ti.Author;
                            }
                            tc.Topics_Delete(PortalId, ModuleId, tmpForumId, tmpTopicId, delAction);
                        }
                        else if (tmpForumId > 0 & tmpTopicId > 0 & tmpReplyId > 0)
                        {
                            ReplyController rc = new ReplyController();
                            ReplyInfo       ri = rc.Reply_Get(PortalId, ForumModuleId, tmpTopicId, tmpReplyId);
                            if (ri != null)
                            {
                                auth = ri.Author;
                            }
                            rc.Reply_Delete(PortalId, tmpForumId, tmpTopicId, tmpReplyId, delAction);
                        }
                    }
                    break;
                }

                case "modreject":
                {
                    int tmpForumId  = 0;
                    int tmpTopicId  = 0;
                    int tmpReplyId  = 0;
                    int tmpAuthorId = 0;
                    tmpForumId  = Convert.ToInt32(e.Parameters[1]);
                    tmpTopicId  = Convert.ToInt32(e.Parameters[2]);
                    tmpReplyId  = Convert.ToInt32(e.Parameters[3]);
                    tmpAuthorId = Convert.ToInt32(e.Parameters[4]);
                    ModController mc = new ModController();
                    mc.Mod_Reject(PortalId, ForumModuleId, UserId, tmpForumId, tmpTopicId, tmpReplyId);
                    if (fi.ModRejectTemplateId > 0 & tmpAuthorId > 0)
                    {
                        DotNetNuke.Entities.Users.UserController uc = new DotNetNuke.Entities.Users.UserController();
                        DotNetNuke.Entities.Users.UserInfo       ui = uc.GetUser(PortalId, tmpAuthorId);
                        if (ui != null)
                        {
                            Author au = new Author();
                            au.AuthorId    = tmpAuthorId;
                            au.DisplayName = ui.DisplayName;
                            au.Email       = ui.Email;
                            au.FirstName   = ui.FirstName;
                            au.LastName    = ui.LastName;
                            au.Username    = ui.Username;
                            Email.SendEmail(fi.ModRejectTemplateId, PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, string.Empty, au);
                        }
                    }

                    break;
                }

                case "modappr":
                {
                    int tmpForumId = -1;
                    int tmpTopicId = -1;
                    int tmpReplyId = -1;
                    tmpForumId = Convert.ToInt32(e.Parameters[1]);
                    tmpTopicId = Convert.ToInt32(e.Parameters[2]);
                    tmpReplyId = Convert.ToInt32(e.Parameters[3]);
                    string sSubject = string.Empty;
                    string sBody    = string.Empty;
                    if (tmpForumId > 0 & tmpTopicId > 0 && tmpReplyId == 0)
                    {
                        TopicsController tc = new TopicsController();
                        TopicInfo        ti = tc.Topics_Get(PortalId, ForumModuleId, tmpTopicId, tmpForumId, -1, false);
                        if (ti != null)
                        {
                            sSubject      = ti.Content.Subject;
                            sBody         = ti.Content.Body;
                            ti.IsApproved = true;
                            tc.TopicSave(PortalId, ti);
                            tc.Topics_SaveToForum(tmpForumId, tmpTopicId, PortalId, ModuleId);
                            //TODO: Add Audit log for who approved topic
                            if (fi.ModApproveTemplateId > 0 & ti.Author.AuthorId > 0)
                            {
                                Email.SendEmail(fi.ModApproveTemplateId, PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, string.Empty, ti.Author);
                            }

                            Subscriptions.SendSubscriptions(PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, 0, ti.Content.AuthorId);

                            try
                            {
                                ControlUtils ctlUtils = new ControlUtils();
                                string       sUrl     = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, fi.ForumGroup.PrefixURL, fi.PrefixURL, fi.ForumGroupId, fi.ForumID, TopicId, ti.TopicUrl, -1, -1, string.Empty, 1, -1, fi.SocialGroupId); // Utilities.NavigateUrl(ForumTabId, "", ParamKeys.ViewType & "=" & Views.Topic & "&" & ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId)
                                if (sUrl.Contains("~/") || Request.QueryString["asg"] != null)
                                {
                                    sUrl = Utilities.NavigateUrl(ForumTabId, "", ParamKeys.TopicId + "=" + TopicId);
                                }
                                Social amas = new Social();
                                if (Request.QueryString["asg"] == null & !(string.IsNullOrEmpty(MainSettings.ActiveSocialTopicsKey)) && fi.ActiveSocialEnabled)
                                {
                                    amas.AddTopicToJournal(PortalId, ForumModuleId, ForumId, ti.TopicId, ti.Author.AuthorId, sUrl, sSubject, ti.Content.Summary, sBody, fi.ActiveSocialSecurityOption, fi.Security.Read, SocialGroupId);
                                }
                                else
                                {
                                    amas.AddForumItemToJournal(PortalId, ForumModuleId, ti.Author.AuthorId, "forumtopic", sUrl, sSubject, sBody);
                                }
                            }
                            catch (Exception ex)
                            {
                                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                            }
                        }
                    }
                    else if (tmpForumId > 0 & tmpTopicId > 0 & tmpReplyId > 0)
                    {
                        ReplyController rc = new ReplyController();
                        ReplyInfo       ri = rc.Reply_Get(PortalId, ForumModuleId, tmpTopicId, tmpReplyId);
                        if (ri != null)
                        {
                            ri.IsApproved = true;
                            sSubject      = ri.Content.Subject;
                            sBody         = ri.Content.Body;
                            rc.Reply_Save(PortalId, ri);
                            TopicsController tc = new TopicsController();
                            tc.Topics_SaveToForum(tmpForumId, tmpTopicId, PortalId, ModuleId, tmpReplyId);
                            TopicInfo ti = tc.Topics_Get(PortalId, ForumModuleId, tmpTopicId, tmpForumId, -1, false);
                            //TODO: Add Audit log for who approved topic
                            if (fi.ModApproveTemplateId > 0 & ri.Author.AuthorId > 0)
                            {
                                Email.SendEmail(fi.ModApproveTemplateId, PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, string.Empty, ri.Author);
                            }

                            Subscriptions.SendSubscriptions(PortalId, ForumModuleId, ForumTabId, tmpForumId, tmpTopicId, tmpReplyId, ri.Content.AuthorId);

                            try
                            {
                                ControlUtils ctlUtils = new ControlUtils();
                                string       fullURL  = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, fi.ForumGroup.PrefixURL, fi.PrefixURL, fi.ForumGroupId, fi.ForumID, TopicId, ti.TopicUrl, -1, -1, string.Empty, 1, -1, fi.SocialGroupId);
                                if (fullURL.Contains("~/") || Request.QueryString["asg"] != null)
                                {
                                    fullURL = Utilities.NavigateUrl(ForumTabId, "", new string[] { ParamKeys.TopicId + "=" + TopicId, ParamKeys.ContentJumpId + "=" + tmpReplyId });
                                }
                                Social amas = new Social();
                                if (Request.QueryString["asg"] == null & !(string.IsNullOrEmpty(MainSettings.ActiveSocialTopicsKey)) && fi.ActiveSocialEnabled && !fi.ActiveSocialTopicsOnly)
                                {
                                    amas.AddReplyToJournal(PortalId, ForumModuleId, ForumId, ri.TopicId, ri.ReplyId, ri.Author.AuthorId, fullURL, ri.Content.Subject, string.Empty, sBody, fi.ActiveSocialSecurityOption, fi.Security.Read, fi.SocialGroupId);
                                }
                                else
                                {
                                    amas.AddForumItemToJournal(PortalId, ForumModuleId, ri.Author.AuthorId, "forumreply", fullURL, sSubject, sBody);
                                }
                            }
                            catch (Exception ex)
                            {
                                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                            }
                        }
                    }


                    break;
                }
                }
                string cachekey = string.Format("AF-FV-{0}-{1}", PortalId, ModuleId);
                DataCache.CacheClearPrefix(cachekey);
            }
            BuildModList();
            litTopics.RenderControl(e.Output);
        }
        private static string GetAuthorName(SettingsInfo settings, Entities.Users.UserInfo user)
        {
            if (user == null || user.UserID <= 0)
                return "Guest";

            switch (settings.UserNameDisplay.ToUpperInvariant())
            {
                case "USERNAME":
                    return user.Username.Trim();
                case "FULLNAME":
                    return (user.FirstName.Trim() + " " + user.LastName.Trim());
                case "FIRSTNAME":
                    return user.FirstName.Trim();
                case "LASTNAME":
                    return user.LastName.Trim();
                default:
                    return user.DisplayName.Trim();
            }

        }
        private static string GetLastReplyAuthorName(SettingsInfo settings, ForumTopic topic)
        {
            if (topic == null || topic.AuthorId <= 0)
                return "Guest";

            switch (settings.UserNameDisplay.ToUpperInvariant())
            {
                case "USERNAME":
                    return topic.LastReplyUserName.Trim();
                case "FULLNAME":
                    return (topic.LastReplyFirstName.Trim() + " " + topic.LastReplyLastName.Trim());
                case "FIRSTNAME":
                    return topic.LastReplyFirstName.Trim();
                case "LASTNAME":
                    return topic.LastReplyLastName.Trim();
                default:
                    return topic.LastReplyDisplayName.Trim();
            }

        }
        public PostSearchResults SearchPosts(int portalId, int moduleId, int userId, string forumIds, string searchText, int rowIndex, int maxRows, string searchId, SettingsInfo mainSettings)
        {
            int searchIdValue;
            int.TryParse(searchId, out searchIdValue);

            var result = new PostSearchResults();

            if (!string.IsNullOrWhiteSpace(forumIds))
                forumIds = forumIds.Replace(';', ':');

            var ds = ActiveForums.DataProvider.Instance().Search(portalId, moduleId, userId, searchIdValue, rowIndex, maxRows, searchText, 0, 0, 0, 0, null, forumIds, null, 1, 0, 1, mainSettings.FullText);

            if (ds.Tables.Count > 2)
                return null;

            var dtSummary = ds.Tables[0];
            var dtResults = ds.Tables[1];

            result.SearchId = dtSummary.Rows[0].GetInt("SearchId");
            result.TotalPosts = dtSummary.Rows[0].GetInt("TotalRecords");
            result.Topics = new List<ForumPost>(dtResults.Rows.Count);

            foreach (var row in dtResults.AsEnumerable())
            {
                ((List<ForumPost>)result.Topics).Add(new ForumPost
                {
                    ForumId = row.GetInt("ForumId"),
                    ForumName = row.GetString("ForumName"),
                    TopicId = row.GetInt("TopicId"),
                    ReplyId = row.GetInt("ReplyId"),
                    ContentId = row.GetInt("ContentId"),
                    Subject = row.GetString("Subject"),
                    PostSubject = row.GetString("PostSubject"),
                    Summary = row.GetString("Summary"),
                    AuthorId = row.GetInt("AuthorId"),
                    AuthorName = row.GetString("AuthorName"),
                    UserName = row.GetString("AuthorUserName"),
                    FirstName = row.GetString("AuthorFirstName"),
                    LastName = row.GetString("AuthorLastName"),
                    DisplayName = row.GetString("AuthorDisplayName"),
                    Body = row.GetString("Body"),
                    DateCreated = row.GetDateTime("DateCreated"),
                    DateUpdated = row.GetDateTime("DateCreated")
                });
            }

            return result;
        }
        private XmlRpcStruct SearchPosts(string searchString, int startIndex, int endIndex, string searchId)
        {
            var aftContext = ActiveForumsTapatalkModuleContext.Create(Context);

            if (aftContext == null || aftContext.Module == null)
                throw new XmlRpcFaultException(100, "Invalid Context");

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

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

            // Verify Search Permissions
            var searchPermissions = aftContext.ModuleSettings.SearchPermission;
            if (searchPermissions == ActiveForumsTapatalkModuleSettings.SearchPermissions.Disabled || (userId <= 0 && searchPermissions == ActiveForumsTapatalkModuleSettings.SearchPermissions.RegisteredUsers))
                throw new XmlRpcFaultException(102, "Insufficent Search Permissions");

            // Build a list of forums the user has access to
            var fc = new AFTForumController();
            var forumIds = fc.GetForumsForUser(aftContext.ForumUser.UserRoles, portalId, forumModuleId, "CanRead");

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

            var maxRows = endIndex + 1 - startIndex;

            var searchResults = fc.SearchPosts(portalId, forumModuleId, userId, forumIds, searchString, startIndex, maxRows, searchId, mainSettings);

            if (searchResults == null)
                throw new XmlRpcFaultException(101, "Search Error");

            return new XmlRpcStruct
            {
                {"total_post_num", searchResults.TotalPosts },
                {"search_id", searchResults.SearchId.ToString() },
                {"posts", searchResults.Topics.Select(t => new ExtendedPostStructure { 
                                        TopicId = t.TopicId.ToString(),
                                        AuthorAvatarUrl = GetAvatarUrl(t.AuthorId),
                                        AuthorId = t.AuthorId.ToString(),
                                        AuthorName = GetAuthorName(mainSettings, t).ToBytes(),
                                        ForumId = t.ForumId.ToString(),
                                        ForumName = t.ForumName.ToBytes(),
                                        PostID = t.ContentId.ToString(),
                                        Summary = GetSummary(null, t.Body).ToBytes(),
                                        PostDate = t.DateCreated,
                                        TopicTitle = HttpUtility.HtmlDecode(t.Subject + string.Empty).ToBytes(),
                                        PostTitle = HttpUtility.HtmlDecode(t.PostSubject + string.Empty).ToBytes()
                                    }).ToArray()}
            };
        }
        private XmlRpcStruct GetUser(string username, int userId)
        {
            var aftContext = ActiveForumsTapatalkModuleContext.Create(Context);

            if (aftContext == null || aftContext.Module == null)
                throw new XmlRpcFaultException(100, "Invalid Context");

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

            // Not fully implemented...  Disable for now.

            // for our purposes, we ignore the username and require userId
            // If we don't have a userid, pass back a anonymous user object
            if (true || userId <= 0)
            {
                return new XmlRpcStruct
                           {
                               { "user_id", userId.ToString() },
                               { "user_name", username.ToBytes() },
                               { "post_count", 1 }
                           };
            }

            var portalId = aftContext.Module.PortalID;
            var currentUserId = aftContext.UserId;

            var fc = new AFTForumController();

            var user = fc.GetUser(portalId, userId, currentUserId);

            const bool allowPM = false; //TODO : Tie in with PM's
            const bool acceptFollow = false;

            if (user == null)
            {
                return new XmlRpcStruct
                           {
                               { "user_id", userId.ToString() },
                               { "user_name", username.ToBytes() },
                               { "post_count", 1 }
                           };
            }

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

            return new XmlRpcStruct
                           {
                               { "user_id", userId.ToString() },
                               { "user_name", GetUserName(mainSettings, user).ToBytes() },
                               { "post_count", user.PostCount },
                               { "reg_time", user.DateCreated },
                               { "last_activity_date", user.DateLastActivity },
                               { "is_online", user.IsUserOnline },
                               { "accept_pm", allowPM },
                               { "i_follow_u", user.Following },
                               { "u_follow_me", user.IsFollower },
                               { "accept_follow", acceptFollow },
                               { "following_count", user.FollowingCount },
                               { "follower", user.FollowerCount },
                               { "display_text", user.UserCaption.ToBytes() },
                               { "icon_url", GetAvatarUrl(userId) }, 
                           };
        }
        private XmlRpcStruct GetQuote(string postIds)
        {
            var aftContext = ActiveForumsTapatalkModuleContext.Create(Context);

            if (aftContext == null || aftContext.Module == null)
                throw new XmlRpcFaultException(100, "Invalid 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();

            // Load our forum settings
            var mainSettings = new SettingsInfo { MainSettings = new Entities.Modules.ModuleController().GetModuleSettings(forumModuleId) };

            // Get our quote template info
            var postedByTemplate = Utilities.GetSharedResource("[RESX:PostedBy]") + " {0} {1} {2}";
            var sharedOnText = Utilities.GetSharedResource("On.Text");

            var contentIds = postIds.Split('-').Select(int.Parse).ToList();

            if (contentIds.Count > 25) // Let's be reasonable
                throw new XmlRpcFaultException(100, "Bad Request");


            var postContent = new StringBuilder();

            foreach (var contentId in contentIds)
            {
                // Retrieve the forum post
                var forumPost = fc.GetForumPost(portalId, forumModuleId, contentId);

                if (forumPost == null)
                    throw new XmlRpcFaultException(100, "Bad Request");

                // Verify read permissions - Need to do this for every content id as we can not assume they are all from the same forum (even though they probably should be)
                var fp = fc.GetForumPermissions(forumPost.ForumId);

                if (!ActiveForums.Permissions.HasPerm(aftContext.ForumUser.UserRoles, fp.CanRead))
                    continue;


                // Build our sanitized quote
                var postedBy = string.Format(postedByTemplate, GetAuthorName(mainSettings, forumPost), sharedOnText,
                                             GetServerDateTime(mainSettings, forumPost.DateCreated));

                postContent.Append(HtmlToTapatalkQuote(postedBy, forumPost.Body));
                postContent.Append("\r\n");
                // add the result

            }

            return new XmlRpcStruct
            {
                {"post_id", postIds},
                {"post_title", string.Empty.ToBytes()},
                {"post_content", postContent.ToString().ToBytes()}
            };
        }
        private PostListStructure GetThread(int topicId, int startIndex, int endIndex, bool returnHtml)
        {
            var aftContext = ActiveForumsTapatalkModuleContext.Create(Context);

            if (aftContext == null || aftContext.Module == null)
                throw new XmlRpcFaultException(100, "Invalid 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 forumId = fc.GetTopicForumId(topicId);

            if (forumId <= 0)
                throw new XmlRpcFaultException(100, "Invalid Topic");

            var fp = fc.GetForumPermissions(forumId);

            if (!ActiveForums.Permissions.HasPerm(aftContext.ForumUser.UserRoles, fp.CanRead))
                throw new XmlRpcFaultException(100, "No Read Permissions");

            var maxRows = endIndex + 1 - startIndex;

            var forumPostSummary = fc.GetForumPostSummary(aftContext.Module.PortalID, aftContext.ModuleSettings.ForumModuleId, forumId, topicId, aftContext.UserId);
            var forumPosts = fc.GetForumPosts(aftContext.Module.PortalID, aftContext.ModuleSettings.ForumModuleId, forumId, topicId, aftContext.UserId, startIndex, maxRows);

            var breadCrumbs = new List<BreadcrumbStructure>
                                  {
                                      new BreadcrumbStructure
                                          {
                                              ForumId = 'G' + forumPostSummary.ForumGroupId.ToString(),
                                              IsCategory = true,
                                              Name = forumPostSummary.GroupName.ToBytes()
                                          },
                                  };

            // If we're in a sub forum, add the parent to the breadcrumb
            if (forumPostSummary.ParentForumId > 0)
                breadCrumbs.Add(new BreadcrumbStructure
                {
                    ForumId = forumPostSummary.ParentForumId.ToString(),
                    IsCategory = false,
                    Name = forumPostSummary.ParentForumName.ToBytes()
                });

            breadCrumbs.Add(new BreadcrumbStructure
            {
                ForumId = forumId.ToString(),
                IsCategory = false,
                Name = forumPostSummary.ForumName.ToBytes()
            });

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

            var profilePath = string.Format("{0}://{1}{2}", Context.Request.Url.Scheme, Context.Request.Url.Host, VirtualPathUtility.ToAbsolute("~/profilepic.ashx"));

            var result = new PostListStructure
                             {
                                 PostCount = forumPostSummary.ReplyCount + 1,
                                 CanReply = ActiveForums.Permissions.HasPerm(aftContext.ForumUser.UserRoles, fp.CanReply),
                                 CanSubscribe = ActiveForums.Permissions.HasPerm(aftContext.ForumUser.UserRoles, fp.CanSubscribe),
                                 ForumId = forumId,
                                 ForumName = forumPostSummary.ForumName.ToBytes(),
                                 IsLocked = forumPostSummary.IsLocked,
                                 IsSubscribed = forumPostSummary.SubscriptionType > 0,
                                 Subject = forumPostSummary.Subject.ToBytes(),
                                 TopicId = topicId,
                                 Posts = forumPosts.Select(p => new PostStructure
                                    {
                                        PostID = p.ContentId.ToString(),
                                        AuthorAvatarUrl = string.Format("{0}?userId={1}&w=64&h=64", profilePath, p.AuthorId),
                                        AuthorName = GetAuthorName(mainSettings, p).ToBytes(),
                                        AuthorId = p.AuthorId.ToString(),
                                        Body = HtmlToTapatalk(p.Body, returnHtml).ToBytes(),
                                        CanEdit = false, // TODO: Fix this
                                        IsOnline = p.IsUserOnline,
                                        PostDate = p.DateCreated,
                                        Subject = p.Subject.ToBytes()
                                    }).ToArray(),
                                 Breadcrumbs = breadCrumbs.ToArray()

                             };

            return result;
        }
Example #26
0
        private string BuildItem(DataRow dr, int PostTabID, int Indent, bool IncludeBody, int PortalId)
        {
            SettingsInfo  MainSettings = DataCache.MainSettings(ModuleID);
            StringBuilder sb           = new StringBuilder(1024);

            string[] Params = { ParamKeys.ForumId + "=" + dr["ForumID"].ToString(), ParamKeys.TopicId + "=" + dr["TopicId"].ToString(), ParamKeys.ViewType + "=" + Views.Topic };
            string   URL    = DotNetNuke.Common.Globals.NavigateURL(PostTabID, "", Params);

            if (Request.QueryString["asg"] != null)
            {
                if (SimulateIsNumeric.IsNumeric(Request.QueryString["asg"]))
                {
                    Params = new string[] { "asg=" + Request.QueryString["asg"], ParamKeys.ForumId + "=" + dr["ForumId"].ToString(), ParamKeys.ViewType + "=" + Views.Topic, ParamKeys.TopicId + "=" + dr["TopicId"].ToString() };
                    URL    = DotNetNuke.Common.Globals.NavigateURL(PostTabID, "", Params);
                }
            }
            else if (MainSettings.URLRewriteEnabled && !(string.IsNullOrEmpty(dr["FullUrl"].ToString())))
            {
                string sTopicURL = string.Empty;
                if (!(string.IsNullOrEmpty(MainSettings.PrefixURLBase)))
                {
                    sTopicURL = "/" + MainSettings.PrefixURLBase;
                }
                sTopicURL += dr["FullUrl"].ToString();

                URL = sTopicURL;
            }
            if (URL.IndexOf(Request.Url.Host) == -1)
            {
                URL = DotNetNuke.Common.Globals.AddHTTP(Request.Url.Host) + URL;
            }
            if (LastBuildDate == new DateTime())
            {
                LastBuildDate = Convert.ToDateTime(dr["DateCreated"]).AddMinutes(offSet);
            }
            else
            {
                if (Convert.ToDateTime(dr["DateCreated"]).AddMinutes(offSet) > LastBuildDate)
                {
                    LastBuildDate = Convert.ToDateTime(dr["DateCreated"]).AddMinutes(offSet);
                }
            }
            sb.Append(WriteElement("item", Indent));
            string body = dr["Body"].ToString();

            if (body.IndexOf("<body>") > 0)
            {
                body = TemplateUtils.GetTemplateSection(body, "<body>", "</body>");
            }

            /*
             * if (body.Contains("&#91;IMAGE:"))
             * {
             *  string strHost = DotNetNuke.Common.Globals.AddHTTP(DotNetNuke.Common.Globals.GetDomainName(Request)) + "/";
             *  string pattern = "(&#91;IMAGE:(.+?)&#93;)";
             *  Regex regExp = new Regex(pattern);
             *  MatchCollection matches = null;
             *  matches = regExp.Matches(body);
             *  foreach (Match match in matches)
             *  {
             *      string sImage = "";
             *      sImage = "<img src=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleID + "&attachid=" + match.Groups[2].Value + "\" border=\"0\" />";
             *      body = body.Replace(match.Value, sImage);
             *  }
             * }
             * if (body.Contains("&#91;THUMBNAIL:"))
             * {
             *  string strHost = DotNetNuke.Common.Globals.AddHTTP(DotNetNuke.Common.Globals.GetDomainName(Request)) + "/";
             *  string pattern = "(&#91;THUMBNAIL:(.+?)&#93;)";
             *  Regex regExp = new Regex(pattern);
             *  MatchCollection matches = null;
             *  matches = regExp.Matches(body);
             *  foreach (Match match in matches)
             *  {
             *      string sImage = "";
             *      string thumbId = match.Groups[2].Value.Split(':')[0];
             *      string parentId = match.Groups[2].Value.Split(':')[1];
             *      sImage = "<a href=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleID + "&attachid=" + parentId + "\" target=\"_blank\"><img src=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleID + "&attachid=" + thumbId + "\" border=\"0\" /></a>";
             *      body = body.Replace(match.Value, sImage);
             *  }
             * }
             */
            body = body.Replace("src=\"/Portals", "src=\"" + DotNetNuke.Common.Globals.AddHTTP(Request.Url.Host) + "/Portals");
            body = Utilities.ManageImagePath(body, DotNetNuke.Common.Globals.AddHTTP(Request.Url.Host));

            sb.Append(WriteElement("title", dr["Subject"].ToString(), Indent + 1));
            sb.Append(WriteElement("description", body, Indent + 1));
            sb.Append(WriteElement("link", URL, Indent + 1));
            sb.Append(WriteElement("dc:creator", UserProfiles.GetDisplayName(ModuleID, -1, dr["AuthorUserName"].ToString(), dr["AuthorFirstName"].ToString(), dr["AuthorLastName"].ToString(), dr["AuthorDisplayName"].ToString(), null), Indent + 1));
            sb.Append(WriteElement("pubDate", Convert.ToDateTime(dr["DateCreated"]).AddMinutes(offSet).ToString("r"), Indent + 1));
            sb.Append(WriteElement("guid", URL, Indent + 1));
            sb.Append(WriteElement("slash:comments", dr["ReplyCount"].ToString(), Indent + 1));
            sb.Append(WriteElement("/item", Indent));

            return(sb.ToString());
        }
        private static string GetAuthorName(SettingsInfo settings, ForumPost post)
        {
            if (post == null || post.AuthorId <= 0)
                return "Guest";

            switch (settings.UserNameDisplay.ToUpperInvariant())
            {
                case "USERNAME":
                    return post.UserName.Trim();
                case "FULLNAME":
                    return (post.FirstName.Trim() + " " + post.LastName.Trim());
                case "FIRSTNAME":
                    return post.FirstName.Trim();
                case "LASTNAME":
                    return post.LastName.Trim();
                default:
                    return post.DisplayName.Trim();
            }

        }
Example #28
0
		public static SettingsInfo MainSettings(int MID)
		{
			object obj = CacheRetrieve(string.Format(CacheKeys.MainSettings, MID));
			if (obj == null || disableCache)
			{
				var objSettings = new SettingsInfo();
				var sb = new SettingsBase {ForumModuleId = MID};
			    obj = sb.MainSettings;
				if (disableCache == false)
				{
					CacheStore(string.Format(CacheKeys.MainSettings, MID), obj);
				}
			}

			return (SettingsInfo)obj;
		}
        private static string GetUserName(SettingsInfo settings, Classes.UserInfo userInfo)
        {
            if (userInfo == null || userInfo.UserId <= 0)
                return "Guest";

            switch (settings.UserNameDisplay.ToUpperInvariant())
            {
                case "USERNAME":
                    return userInfo.UserName.Trim();
                case "FULLNAME":
                    return (userInfo.FirstName.Trim() + " " + userInfo.LastName.Trim());
                case "FIRSTNAME":
                    return userInfo.FirstName.Trim();
                case "LASTNAME":
                    return userInfo.LastName.Trim();
                default:
                    return userInfo.DisplayName.Trim();
            }

        }
        public TopicSearchResults SearchTopics(int portalId, int moduleId, int userId, string forumIds, string searchText, int rowIndex, int maxRows, string searchId, SettingsInfo mainSettings)
        {
            int searchIdValue;
            int.TryParse(searchId, out searchIdValue);

            var result = new TopicSearchResults();

            if (!string.IsNullOrWhiteSpace(forumIds))
                forumIds = forumIds.Replace(';', ':');

            var ds = ActiveForums.DataProvider.Instance().Search(portalId, moduleId, userId, searchIdValue, rowIndex, maxRows, searchText, 0, 0, 0, 0, null, forumIds, null, 0, 0, 1, mainSettings.FullText);

            if(ds.Tables.Count > 2)
                return null;

            var dtSummary = ds.Tables[0];
            var dtResults = ds.Tables[1];

            result.SearchId = dtSummary.Rows[0].GetInt("SearchId");
            result.TotalTopics = dtSummary.Rows[0].GetInt("TotalRecords");
            result.Topics = new List<ForumTopic>(dtResults.Rows.Count);

            foreach(var row in dtResults.AsEnumerable())
            {
                ((List<ForumTopic>)result.Topics).Add(new ForumTopic
                                                          {
                                                            ForumId = row.GetInt("ForumId"),
                                                            ForumName = row.GetString("ForumName"),
                                                            LastReplyId = row.GetInt("LastReplyId"),
                                                            TopicId = row.GetInt("TopicId"),
                                                            ViewCount = row.GetInt("ViewCount"),
                                                            ReplyCount = row.GetInt("ReplyCount"),
                                                            IsLocked = row.GetBoolean("IsLocked"),
                                                            IsPinned = row.GetBoolean("IsPinned"),
                                                            TopicIcon = row.GetString("TopicIcon"),
                                                            StatusId = row.GetInt("StatusId"),
                                                            AnnounceStart = row.GetDateTime("AnnounceStart"),
                                                            AnnounceEnd = row.GetDateTime("AnnounceEnd"),
                                                            TopicType = row.GetString("TopicType"),
                                                            Subject = row.GetString("Subject"),
                                                            Summary = row.GetString("Summary"),
                                                            AuthorId = row.GetInt("AuthorId"),
                                                            AuthorName = row.GetString("AuthorName"),
                                                            Body = row.GetString("Body"),
                                                            LastReplyBody = row.GetString("LastReplyBody"),
                                                            DateCreated = row.GetDateTime("DateCreated"),
                                                            AuthorUserName = row.GetString("AuthorUserName"),
                                                            AuthorFirstName = row.GetString("AuthorFirstName"),
                                                            AuthorLastName = row.GetString("AuthorLastName"),
                                                            AuthorDisplayName = row.GetString("AuthorDisplayName"),
                                                            LastReplySubject = row.GetString("LastReplySubject"),
                                                            LastReplySummary = row.GetString("LastReplySummary"),
                                                            LastReplyAuthorId = row.GetInt("LastReplyAuthorId"),
                                                            LastReplyAuthorName = row.GetString("LastReplyAuthorName"),
                                                            LastReplyUserName = row.GetString("LastReplyUserName"),
                                                            LastReplyFirstName = row.GetString("LastReplyFirstName"),
                                                            LastReplyLastName = row.GetString("LastReplyLastName"),
                                                            LastReplyDisplayName = row.GetString("LastReplyDisplayName"),
                                                            LastReplyDate = row.GetDateTime("LastReplyDate"),
                                                            UserLastReplyRead = row.GetInt("UserLastReplyRead"),
                                                            UserLastTopicRead = row.GetInt("UserLastTopicRead"),
                                                            SubscriptionType = row.GetInt("SubscriptionType")
                                                          });
            }

            return result;
        }
 private static string GetServerDateTime(SettingsInfo settings, DateTime displayDate)
 {
     //Dim newDate As Date 
     string dateString;
     try
     {
         dateString = displayDate.ToString(settings.DateFormatString + " " + settings.TimeFormatString);
         return dateString;
     }
     catch (Exception ex)
     {
         dateString = displayDate.ToString();
         return dateString;
     }
 }
        private XmlRpcStruct GetSubscribedTopics(int startIndex, int endIndex)
        {
            var aftContext = ActiveForumsTapatalkModuleContext.Create(Context);

            if (aftContext == null || aftContext.Module == null)
                throw new XmlRpcFaultException(100, "Invalid Context");

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

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

            // Build a list of forums the user has access to
            var fc = new AFTForumController();
            var forumIds = fc.GetForumsForUser(aftContext.ForumUser.UserRoles, portalId, forumModuleId, "CanRead");

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

            var profilePath = string.Format("{0}://{1}{2}", Context.Request.Url.Scheme, Context.Request.Url.Host, VirtualPathUtility.ToAbsolute("~/profilepic.ashx"));

            var maxRows = endIndex + 1 - startIndex;

            var subscribedTopics = fc.GetSubscribedTopics(portalId, forumModuleId, userId, forumIds, startIndex, maxRows).ToList();



            return new XmlRpcStruct
                       {
                           {"total_topic_num", subscribedTopics.Count > 0 ? subscribedTopics[0].TopicCount : 0},
                           {"topics", subscribedTopics.Select(t => new ExtendedTopicStructure{ 
                                                   TopicId = t.TopicId.ToString(),
                                                   AuthorAvatarUrl = string.Format("{0}?userId={1}&w=64&h=64", profilePath, t.LastReplyAuthorId),
                                                   AuthorName = GetLastReplyAuthorName(mainSettings, t).ToBytes(),
                                                   AuthorId = t.LastReplyAuthorId.ToString(),
                                                   ForumId = t.ForumId.ToString(),
                                                   ForumName = t.ForumName.ToBytes(),
                                                   HasNewPosts =  (t.LastReplyId < 0 && t.TopicId > t.UserLastTopicRead) || t.LastReplyId > t.UserLastReplyRead,
                                                   IsLocked = t.IsLocked,
                                                   ReplyCount = t.ReplyCount,
                                                   Summary = GetSummary(null, t.LastReplyBody).ToBytes(),
                                                   ViewCount = t.ViewCount,
                                                   DateCreated = t.LastReplyDate,
                                                   Title = HttpUtility.HtmlDecode(t.Subject + string.Empty).ToBytes()
                                               }).ToArray()}
                       };
        }
Example #33
0
        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
        }