public HttpResponseMessage CreateSplit(CreateSplitDTO dto)
        {
            if (dto.NewTopicId == dto.OldTopicId) return Request.CreateResponse(HttpStatusCode.OK);

            var portalSettings = PortalSettings;
            var userInfo = portalSettings.UserInfo;
            var forumUser = new UserController().GetUser(portalSettings.PortalId, ActiveModule.ModuleID, userInfo.UserID);

            var fc = new ForumController();

            var forum_out = fc.Forums_Get(portalSettings.PortalId, ActiveModule.ModuleID, 0, forumUser.UserId, false, true, dto.OldTopicId);
            var forum_in = fc.GetForum(portalSettings.PortalId, ActiveModule.ModuleID, dto.NewForumId);
            if (forum_out != null && forum_in != null)
            {
                var perm = false;

                if (forum_out == forum_in)
                {
                    perm = Permissions.HasPerm(forum_out.Security.View, forumUser.UserRoles);
                }
                else
                {
                    perm = Permissions.HasPerm(forum_out.Security.View, forumUser.UserRoles) && Permissions.HasPerm(forum_in.Security.View, forumUser.UserRoles);
                }

                var modSplit = Permissions.HasPerm(forum_out.Security.ModSplit, forumUser.UserRoles);

                if (perm && modSplit)
                {
                    var tc = new TopicsController();

                    int topicId;

                    if (dto.NewTopicId < 1)
                    {
                        var subject = Utilities.CleanString(portalSettings.PortalId, dto.Subject, false, EditorTypes.TEXTBOX, false, false, ActiveModule.ModuleID, string.Empty, false);
                        var replies = dto.Replies.Split('|');
                        var rc = new DotNetNuke.Modules.ActiveForums.DAL2.ReplyController();
                        var firstReply = rc.Get(Convert.ToInt32(replies[0]));
                        var cc = new ContentController();
                        var firstContent = cc.Get(firstReply.ContentId);
                        topicId = tc.Topic_QuickCreate(portalSettings.PortalId, ActiveModule.ModuleID, dto.NewForumId, subject, string.Empty, firstContent.AuthorId, firstContent.AuthorName, true, Request.GetIPAddress());
                        tc.Replies_Split(dto.OldTopicId, topicId, dto.Replies, true);
                    }
                    else
                    {
                        topicId = dto.NewTopicId;
                        tc.Replies_Split(dto.OldTopicId, topicId, dto.Replies, false);
                    }
                }
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
 private void cbAdmin_Callback(object sender, Modules.ActiveForums.Controls.CallBackEventArgs e)
 {
     if (!(CurrentUserType == CurrentUserTypes.Anon) && !(CurrentUserType == CurrentUserTypes.Auth))
     {
         UserProfileController upc = new UserProfileController();
         UserController uc = new UserController();
         UserProfileInfo upi = uc.GetUser(PortalId, ForumModuleId, UID).Profile;
         if (upi != null)
         {
             upi.RewardPoints = Convert.ToInt32(e.Parameters[1]);
             upi.UserCaption = e.Parameters[2].ToString();
             upi.SignatureDisabled = Convert.ToBoolean(e.Parameters[3]);
             upi.AvatarDisabled = Convert.ToBoolean(e.Parameters[4]);
             upi.TrustLevel = Convert.ToInt32(e.Parameters[5]);
             upi.AdminWatch = Convert.ToBoolean(e.Parameters[6]);
             upi.AttachDisabled = Convert.ToBoolean(e.Parameters[7]);
             upc.Profiles_Save(upi);
         }
     }
 }
Esempio n. 3
0
        public int Subscription_Update(int PortalId, int ModuleId, int ForumId, int TopicId, int Mode, int UserId, string UserRoles = "")
        {
            if (UserId == -1)
            {
                return -1;
            }
            if (string.IsNullOrEmpty(UserRoles))
            {
                UserController uc = new UserController();
                User uu = uc.GetUser(PortalId, ModuleId, UserId);
                UserRoles = uu.UserRoles;
            }

            var fc = new ForumController();
            Forum fi = fc.Forums_Get(PortalId, ModuleId, ForumId, UserId, true, false, -1);
            if (Permissions.HasPerm(fi.Security.Subscribe, UserRoles))
            {
                return Convert.ToInt32(DataProvider.Instance().Subscription_Update(PortalId, ModuleId, ForumId, TopicId, Mode, UserId));
            }
            return -1;
        }
        protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

            btnSave.Click += new System.EventHandler(btnSave_Click);

            nsPrefPageSize.Style.Add("float", "none");
            nsPrefPageSize.EmptyMessageStyle.CssClass += "dnnformHint";
            nsPrefPageSize.NumberFormat.DecimalDigits = 0;
            nsPrefPageSize.IncrementSettings.Step = 5;
            if (Request.QueryString["UserId"] == null)
            {
                UID = UserInfo.UserID;
            }
            else
            {
                UID = Convert.ToInt32(Request.QueryString["UserId"]);
            }
            //If UID <> UserInfo.UserID And Not UserInfo.IsInRole(PortalSettings.AdministratorRoleName) Then

            //End If
            UserProfileInfo ui = null;
            if (ui == null & UID > 0)
            {
                UserController up = new UserController();
                ui = up.GetUser(PortalId, ForumModuleId, UID).Profile;
            }
            if (ui != null)
            {

                drpPrefDefaultSort.SelectedIndex = drpPrefDefaultSort.Items.IndexOf(drpPrefDefaultSort.Items.FindByValue(ui.PrefDefaultSort.Trim()));
                nsPrefPageSize.Value = ui.PrefPageSize;
                chkPrefJumpToLastPost.Checked = ui.PrefJumpLastPost;
                chkPrefTopicSubscribe.Checked = ui.PrefTopicSubscribe;
                //chkPrefUseAjax.Checked = .PrefUseAjax
                chkPrefBlockAvatars.Checked = ui.PrefBlockAvatars;
                chkPrefBlockSignatures.Checked = ui.PrefBlockSignatures;
                txtSignature.Text = ui.Signature;
            }
        }
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            if (UserId == UID || (CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.SuperUser))
            {
                UserProfileController upc = new UserProfileController();
                UserController uc = new UserController();
                UserProfileInfo upi = uc.GetUser(PortalId, ForumModuleId, UID).Profile;
                if (upi != null)
                {
                    upi.PrefDefaultSort = Utilities.XSSFilter(drpPrefDefaultSort.SelectedItem.Value, true);
                    upi.PrefPageSize = Convert.ToInt32(((Convert.ToInt32(nsPrefPageSize.Text) < 5) ? 5 : Convert.ToInt32(nsPrefPageSize.Text)));
                    upi.PrefDefaultShowReplies = false;
                    upi.PrefJumpLastPost = chkPrefJumpToLastPost.Checked;
                    upi.PrefTopicSubscribe = chkPrefTopicSubscribe.Checked;
                    upi.PrefSubscriptionType = SubscriptionTypes.Instant;
                    upi.PrefUseAjax = false;
                    upi.PrefBlockAvatars = chkPrefBlockAvatars.Checked;
                    upi.PrefBlockSignatures = chkPrefBlockSignatures.Checked;
                    if (MainSettings.AllowSignatures == 1 || MainSettings.AllowSignatures == 0)
                    {
                        upi.Signature = Utilities.XSSFilter(txtSignature.Text, true);
                        upi.Signature = Utilities.StripHTMLTag(upi.Signature);
                        upi.Signature = Utilities.HTMLEncode(upi.Signature);
                    }
                    else if (MainSettings.AllowSignatures == 2)
                    {
                        upi.Signature = Utilities.XSSFilter(txtSignature.Text, false);
                    }
                    upc.Profiles_Save(upi);



                }

            }
        }
        protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

            UserProfileInfo ui = UserProfile;
            if (ui == null & UID > 0)
            {
                UserController up = new UserController();
                ui = up.GetUser(PortalId, ForumModuleId, UID).Profile;
            }

            if (ui != null)
            {
                txtRewardPoints.Text = ui.RewardPoints.ToString();
                txtUserCaption.Text = ui.UserCaption;
                chkDisableSignature.Checked = ui.SignatureDisabled;
                chkDisableAttachments.Checked = ui.AttachDisabled;
                chkDisableAvatar.Checked = ui.AvatarDisabled;
                chkMonitor.Checked = ui.AdminWatch;
                drpDefaultTrust.SelectedIndex = drpDefaultTrust.Items.IndexOf(drpDefaultTrust.Items.FindByValue(ui.TrustLevel.ToString()));
                txtRewardPoints.Attributes.Add("onkeypress", "return onlyNumbers(event);");
            }

        }
Esempio n. 7
0
        private void cbPreview_Callback(object sender, CallBackEventArgs e)
        {
            switch (e.Parameters[0].ToLower())
            {
                case "preview":
                    var message = e.Parameters[1];

                    var topicTemplateID = ForumInfo.TopicTemplateId;
                    message = Utilities.CleanString(PortalId, message, _allowHTML, _editorType, ForumInfo.UseFilter, ForumInfo.AllowScript, ForumModuleId, ImagePath, ForumInfo.AllowEmoticons);
                    message = Utilities.ManageImagePath(message);
                    var uc = new UserController();
                    var up = uc.GetUser(PortalId, ForumModuleId, UserId) ?? new User
                                                                                {
                                                                                    UserId = -1,
                                                                                    UserName = "******",
                                                                                    Profile = {TopicCount = 0, ReplyCount = 0},
                                                                                    DateCreated = DateTime.Now
                                                                                };
                    message = TemplateUtils.PreviewTopic(topicTemplateID, PortalId, ForumModuleId, ForumTabId, ForumInfo, UserId, message, ImagePath, up, DateTime.Now, CurrentUserType, UserId, TimeZoneOffset);
                    hidPreviewText.Value = message;
                    break;
            }
            hidPreviewText.RenderControl(e.Output);
        }
        public HttpResponseMessage ToggleSecurity(ToggleSecurityDTO dto)
        {
            var db = new Data.Common();
            var sb = new StringBuilder();
            switch (dto.Action)
            {
                case "delete":
                    {
                        Permissions.RemoveObjectFromAll(dto.SecurityId, dto.SecurityType, dto.PermissionsId);
                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                case "addobject":
                    {
                        if (dto.SecurityType == 1)
                        {
                            var uc = new UserController();
                            var ui = uc.GetUser(PortalSettings.PortalId, dto.ModuleId, dto.SecurityId);
                            dto.SecurityId = ui != null ? ui.UserId.ToString() : string.Empty;
                        }
                        else
                        {
                            if (dto.SecurityId.Contains(":"))
                                dto.SecurityType = 2;
                        }
                        if (!(string.IsNullOrEmpty(dto.SecurityId)))
                        {
                            var permSet = db.GetPermSet(dto.PermissionsId, "View");
                            permSet = Permissions.AddPermToSet(dto.SecurityId, dto.SecurityType, permSet);
                            db.SavePermSet(dto.PermissionsId, "View", permSet);
                        }

                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                default:
                    {
                        var permSet = db.GetPermSet(dto.PermissionsId, dto.SecurityKey);
                        if (dto.Action == "remove")
                            permSet = Permissions.RemovePermFromSet(dto.SecurityId, dto.SecurityType, permSet);
                        else
                            permSet = Permissions.AddPermToSet(dto.SecurityId, dto.SecurityType, permSet);

                        db.SavePermSet(dto.PermissionsId, dto.SecurityKey, permSet);
                        return Request.CreateResponse(HttpStatusCode.OK, dto.Action + "|" + dto.ReturnId);
                    }
            }
        }
Esempio n. 9
0
        private string BuildRSS(int PortalId, int TabId, int ModuleId, int intPosts, int ForumID, bool IngnoreSecurity, bool IncludeBody)
        {
            DotNetNuke.Entities.Portals.PortalController pc = new DotNetNuke.Entities.Portals.PortalController();
            DotNetNuke.Entities.Portals.PortalSettings ps = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings();
            DotNetNuke.Entities.Users.UserInfo ou = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo();
            UserController uc = new UserController();
            User u = uc.GetUser(PortalId, ModuleId);

            DataSet ds = DataProvider.Instance().UI_TopicsView(PortalId, ModuleId, ForumID, ou.UserID, 0, 20, ou.IsSuperUser, SortColumns.ReplyCreated);
            if (ds.Tables.Count > 0)
            {
                offSet = ps.TimeZoneOffset;
                if (ds.Tables[0].Rows.Count == 0)
                {
                    return string.Empty;
                }
                drForum = ds.Tables[0].Rows[0];

                drSecurity = ds.Tables[1].Rows[0];
                dtTopics = ds.Tables[3];
                if (dtTopics.Rows.Count == 0)
                {
                    return string.Empty;
                }
                bView = Permissions.HasPerm(drSecurity["CanView"].ToString(), u.UserRoles);
                bRead = Permissions.HasPerm(drSecurity["CanRead"].ToString(), u.UserRoles);
                StringBuilder sb = new StringBuilder(1024);
                if (bRead)
                {
                    ForumName = drForum["ForumName"].ToString();
                    GroupName = drForum["GroupName"].ToString();
                    ForumDescription = drForum["ForumDesc"].ToString();
                    //TopicsTemplateId = CInt(drForum("TopicsTemplateId"))
                    bAllowRSS = Convert.ToBoolean(drForum["AllowRSS"]);
                    if (bAllowRSS)
                    {
                        sb.Append("<?xml version=\"1.0\" ?>" + System.Environment.NewLine);
                        sb.Append("<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:cf=\"http://www.microsoft.com/schemas/rss/core/2005\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\">" + System.Environment.NewLine);
                        string[] Params = { ParamKeys.ForumId + "=" + ForumID, ParamKeys.ViewType + "=" + Views.Topics };
                        string URL = string.Empty;
                        if (Request.QueryString["asg"] == null)
                        {
                            URL = DotNetNuke.Common.Globals.NavigateURL(TabId, "", Params);
                        }
                        else if (SimulateIsNumeric.IsNumeric(Request.QueryString["asg"]))
                        {
                            Params = new string[] { "asg=" + Request.QueryString["asg"], ParamKeys.ForumId + "=" + ForumID, ParamKeys.ViewType + "=" + Views.Topics };
                            URL = DotNetNuke.Common.Globals.NavigateURL(TabId, "", Params);
                        }

                        if (URL.IndexOf(Request.Url.Host) == -1)
                        {
                            URL = DotNetNuke.Common.Globals.AddHTTP(Request.Url.Host) + URL;
                        }
                        // build channel
                        sb.Append(WriteElement("channel", 1));
                        sb.Append(WriteElement("title", HttpUtility.HtmlEncode(ps.PortalName) + " " + ForumName, 2));
                        sb.Append(WriteElement("link", URL, 2));
                        sb.Append(WriteElement("description", ForumDescription, 2));
                        sb.Append(WriteElement("language", PortalSettings.DefaultLanguage, 2));
                        sb.Append(WriteElement("generator", "ActiveForums  5.0", 2));
                        sb.Append(WriteElement("copyright", PortalSettings.FooterText, 2));
                        sb.Append(WriteElement("lastBuildDate", "[LASTBUILDDATE]", 2));
                        if (!(ps.LogoFile == string.Empty))
                        {
                            string sLogo = "<image><url>http://" + Request.Url.Host + ps.HomeDirectory + ps.LogoFile + "</url>";
                            sLogo += "<title>" + ps.PortalName + " " + ForumName + "</title>";
                            sLogo += "<link>" + URL + "</link></image>";
                            sb.Append(sLogo);
                        }
                        foreach (DataRow dr in dtTopics.Rows)
                        {
                            if (DotNetNuke.Security.PortalSecurity.IsInRoles(PortalSettings.ActiveTab.AuthorizedRoles))
                            {
                                //objModule = objModules.GetModule(ModuleId, TabId)
                                //If DotNetNuke.Security.PortalSecurity.IsInRoles(objModule.AuthorizedViewRoles) = True Then
                                //    sb.Append(BuildItem(dr, TabId, 2, IncludeBody, PortalId))
                                //End If
                                sb.Append(BuildItem(dr, TabId, 2, IncludeBody, PortalId));
                            }
                        }
                        sb.Append("<atom:link href=\"http://" + Request.Url.Host + HttpUtility.HtmlEncode(Request.RawUrl) + "\" rel=\"self\" type=\"application/rss+xml\" />");
                        sb.Append(WriteElement("/channel", 1));
                        sb.Replace("[LASTBUILDDATE]", LastBuildDate.ToString("r"));
                        sb.Append("</rss>");
                        //Cache.Insert("RSS" & ModuleId & ForumID, sb.ToString, Nothing, DateTime.Now.AddMinutes(dblCacheTimeOut), TimeSpan.Zero)
                        return sb.ToString();
                    }
                }

            }


            return string.Empty;
        }
Esempio n. 10
0
        protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

            try
            {
                UserController uc = new UserController();
                User ui = uc.GetUser(PortalSettings.PortalId, -1);
                ForumController fc = new ForumController();
                Forum fi = fc.Forums_Get(Convert.ToInt32(Request.Params["ForumId"]), ui.UserId, true);

                if (fi != null)
                {
                    if (Permissions.HasPerm(fi.Security.Attach, ui.UserRoles))
                    {
                        if (inpFile.HasFile)
                        {
                            string sFile = string.Empty;
                            string sExt = string.Empty;
                            int maxImgHeight = fi.AttachMaxHeight;
                            int maxImgWidth = fi.AttachMaxWidth;
                            string contentType = inpFile.PostedFile.ContentType;
                            sFile = Path.GetFileName(inpFile.PostedFile.FileName).Replace(" ", "_");

                            sExt = Path.GetExtension(sFile);
                            if (sFile.Length >= 250)
                            {
                                sFile = sFile.Replace(sExt, string.Empty);
                                sFile = sFile.Substring(0, (250 - sExt.Length));
                                sFile = sFile + sExt;
                            }
                            sExt = sExt.Replace(".", string.Empty);
                            if (!(fi.AttachTypeAllowed.ToString().ToLower().Contains(sExt.ToLower())))
                            {
                                Response.Write("<script type=\"text/javascript\">window.top.af_setMessage('" + Utilities.GetSharedResource("[RESX:Error:BlockedFile]") + "');</script>");
                                return;
                            }
                            if (fi.AttachMaxSize > 0)
                            {
                                if ((inpFile.PostedFile.ContentLength / 1024.0) > fi.AttachMaxSize)
                                {
                                    Response.Write("<script type=\"text/javascript\">window.top.af_setMessage('" + string.Format(Utilities.GetSharedResource("[RESX:Error:FileTooLarge]"), fi.AttachMaxSize) + "');</script>");
                                    return;
                                }
                            }

                            Stream inpStream = inpFile.PostedFile.InputStream;
                            MemoryStream imgStream = new MemoryStream();
                            bool useMemStream = false;
                            bool allowDownload = true;
                            bool displayInline = false;
                            if (sExt.ToLower() == "jpg" || sExt.ToLower() == "gif" || sExt.ToLower() == "bmp" || sExt.ToLower() == "png" || sExt.ToLower() == "jpeg")
                            {
                                useMemStream = true;
                                imgStream = (MemoryStream)(Images.CreateImageForDB(inpStream, maxImgHeight, maxImgWidth));
                                contentType = "image/x-png";
                                allowDownload = false;
                                displayInline = true;
                            }

                            Data.AttachController ac = new Data.AttachController();
                            AttachInfo ai = new AttachInfo();
                            ai.ContentId = -1;
                            ai.UserID = ui.UserId;

                            ai.ContentType = contentType;
                            ai.DisplayInline = displayInline;
                            ai.AllowDownload = allowDownload;
                            ai.ParentAttachId = 0;
                            if (fi.AttachStore == AttachStores.DATABASE)
                            {
                                if (useMemStream)
                                {
                                    ai.FileSize = Convert.ToInt32(imgStream.Length);
                                    ai.FileData = imgStream.ToArray();
                                }
                                else
                                {

                                    byte[] byteData = new byte[Convert.ToInt32(inpStream.Length - 1) + 1];
                                    inpStream.Read(byteData, 0, Convert.ToInt32(inpStream.Length));
                                    ai.FileSize = Convert.ToInt32(inpStream.Length);
                                    ai.FileData = byteData;
                                }
                                ai.Filename = sFile;
                            }
                            else
                            {
                                if (useMemStream)
                                {
                                    ai.FileSize = Convert.ToInt32(imgStream.Length);
                                    ai.Filename = SaveToFile(imgStream, sFile);
                                }
                                else
                                {
                                    byte[] byteData = new byte[Convert.ToInt32(inpStream.Length) + 1];
                                    inpStream.Read(byteData, 0, Convert.ToInt32(inpStream.Length));
                                    ai.FileSize = Convert.ToInt32(inpStream.Length);
                                    ai.Filename = SaveToFile(inpFile, sFile);
                                }

                            }
                            int attachId = ac.Attach_Save(ai);
                            Response.Write("<script type=\"text/javascript\">window.top.af_isUploaded(" + attachId.ToString() + ");</script>");
                        }
                    }
                    else
                    {
                        inpFile.Visible = false;
                    }
                }
                else
                {
                    inpFile.Visible = false;
                }
            }
            catch (Exception ex)
            {
                Response.Write("<script type=\"text/javascript\">window.top.af_setMessage('" + ex.Message + "');</script>");
            }

        }
        public HttpResponseMessage GetForumsList()
        {
            var portalSettings = PortalSettings;
            var userInfo = portalSettings.UserInfo;
            var forumUser = new UserController().GetUser(portalSettings.PortalId, ActiveModule.ModuleID, userInfo.UserID);
            var fc = new ForumController();
            var forumIds = fc.GetForumsForUser(forumUser.UserRoles, portalSettings.PortalId, ActiveModule.ModuleID, "CanView", true);

            DataTable ForumTable = fc.GetForumView(portalSettings.PortalId, ActiveModule.ModuleID, userInfo.UserID, userInfo.IsSuperUser, forumIds);

            Dictionary<string, string> rows = new Dictionary<string, string>();;
            foreach (DataRow dr in ForumTable.Rows)
            {
                rows.Add(dr["ForumId"].ToString(),dr["ForumName"].ToString());
            }
            return Request.CreateResponse(HttpStatusCode.OK, rows.ToJson());
        }
        public Task<HttpResponseMessage> UploadFile()
        {
            // This method uploads an attachment to a temporary directory and returns a JSON object containing information about the original file
            // including the temporary file name.  When the post is saved/updated, the temporary file is moved to the appropriate attachment directory


            // Have to a reference to these variables as the internal reference isn't available.
            // in the async result.
            var request = Request;
            var portalSettings = PortalSettings;
            var userInfo = portalSettings.UserInfo;
            var forumUser = new UserController().GetUser(ActiveModule.PortalID, ActiveModule.ModuleID, userInfo.UserID);

            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotAcceptable));
            }

            const string uploadPath = "activeforums_Upload";

            var folderManager = FolderManager.Instance;
            if(!folderManager.FolderExists(ActiveModule.PortalID, uploadPath))
            {
                folderManager.AddFolder(ActiveModule.PortalID, uploadPath);
            }
            var folder = folderManager.GetFolder(ActiveModule.PortalID, uploadPath);

            var provider = new MultipartFormDataStreamProvider(folder.PhysicalPath);

            var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);

                // Make sure a temp file was uploaded and that it exists
                var file = provider.FileData.FirstOrDefault();
                if (file == null || string.IsNullOrWhiteSpace(file.LocalFileName) || !File.Exists(file.LocalFileName))
                {
                    return request.CreateErrorResponse(HttpStatusCode.NoContent, "No File Found");
                }

                // Get the file name without the full path
                var localFileName = Path.GetFileName(file.LocalFileName).TextOrEmpty();

                // Check to make sure that a forum was specified and that the the user has upload permissions
                // This is only an initial check, it will be done again when the file is saved to a post.
                
                int forumId;
                if (!int.TryParse(provider.FormData["forumId"], out forumId))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Forum Not Specified");
                }

                // Make sure that we can find the forum and that attachments are allowed
                var fc = new ForumController();
                var forum = fc.Forums_Get(ActiveModule.PortalID, ActiveModule.ModuleID, forumId, userInfo.UserID, true, true, -1);

                if (forum == null || !forum.AllowAttach)
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Forum Not Found");
                }

                // Make sure the user has permissions to attach files
                if(forumUser == null || !Permissions.HasPerm(forum.Security.Attach, forumUser.UserRoles))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized");
                }

           
                // Make sure that the file size does not exceed the limit (in KB) for the forum
                // Have to do this since content length is not available when using MultipartFormDataStreamProvider
                var di = new DirectoryInfo(folder.PhysicalPath);
                var fileSize = di.GetFiles(localFileName)[0].Length;

                var maxAllowedFileSize = (long)forum.AttachMaxSize*1024;

                if((forum.AttachMaxSize > 0) && (fileSize > maxAllowedFileSize))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Exceeds Max File Size");
                }


                // Get the original file name from the content disposition header
                var fileName = file.Headers.ContentDisposition.FileName.Replace("\"", "");

                if(string.IsNullOrWhiteSpace(fileName))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Invalid File");
                }


                // Make sure we have an acceptable extension type.
                // Check against both the forum configuration and the host configuration
                var extension = Path.GetExtension(fileName).TextOrEmpty().Replace(".", string.Empty).ToLower();
                var isForumAllowedExtension = string.IsNullOrWhiteSpace(forum.AttachTypeAllowed) || forum.AttachTypeAllowed.Replace(".", "").Split(',').Any(val => val == extension);
                if(string.IsNullOrEmpty(extension) || !isForumAllowedExtension || !Host.AllowedExtensionWhitelist.IsAllowedExtension(extension))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "File Type Not Allowed");
                }
                

                // IE<=9 Hack - can't return application/json
                var mediaType = "application/json";
                if (!request.Headers.Accept .Any(h => h.MediaType.Equals("application/json", StringComparison.OrdinalIgnoreCase)))
                    mediaType = "text/html";
                   
                var result = new ClientAttachment() {
                    ContentType = file.Headers.ContentType.MediaType,
                    FileName = fileName,
                    FileSize = fileSize,
                    UploadId =  localFileName
                };

                return Request.CreateResponse(HttpStatusCode.Accepted, result, mediaType);
            });

            return task;
        }
Esempio n. 13
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            //Put user code to initialize the page here
            try
            {
                byte[] bindata = null;
                bool canView = false;
                string sContentType = string.Empty;
                if (!Page.IsPostBack)
                {
                    int AttachId = 0;
                    int intPortalID = 0;
                    int intModuleID = 0;
                    if (Request.Params["AttachID"] != null)
                    {
                        if (SimulateIsNumeric.IsNumeric(Request.Params["AttachID"]))
                        {
                            AttachId = Int32.Parse(Request.Params["AttachID"]);
                        }
                        else
                        {
                            AttachId = 0;
                        }
                    }
                    else
                    {
                        AttachId = 0;
                    }
                    if (Request.Params["PortalID"] != null)
                    {
                        if (SimulateIsNumeric.IsNumeric(Request.Params["PortalID"]))
                        {
                            intPortalID = Int32.Parse(Request.Params["PortalID"]);
                        }
                        else
                        {
                            intPortalID = 0;
                        }
                    }
                    else
                    {
                        intPortalID = 0;
                    }
                    if (Request.Params["ModuleID"] != null)
                    {
                        if (SimulateIsNumeric.IsNumeric(Request.Params["ModuleID"]))
                        {
                            intModuleID = Int32.Parse(Request.Params["ModuleID"]);
                        }
                        else
                        {
                            intModuleID = -1;
                        }
                    }
                    else
                    {
                        intModuleID = -1;
                    }
                    IFileManager _fileManager = FileManager.Instance;
                    IFileInfo _file = null;
                    if (AttachId > 0)
                    {
                        DotNetNuke.Entities.Users.UserInfo ui = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo();
                        //DotNetNuke.Modules.ActiveForums.Settings.LoadUser(objUserInfo.UserID, intPortalID, intModuleID)
                        UserController uc = new UserController();
                        User u = uc.GetUser(intPortalID, intModuleID);

                        Data.AttachController ac = new Data.AttachController();
                        AttachInfo ai = null;
                        try
                        {
                            if (Request.UrlReferrer.AbsolutePath.Contains("HtmlEditorProviders") | (Request.UrlReferrer.AbsolutePath.Contains("afv") & Request.UrlReferrer.AbsolutePath.Contains("post")))
                            {
                                ai = ac.Attach_Get(AttachId, -1, ui.UserID, false);
                            }
                            else
                            {
                                ai = ac.Attach_Get(AttachId, -1, ui.UserID, true);
                            }
                        }
                        catch (Exception ex)
                        {
                            ai = ac.Attach_Get(AttachId, -1, ui.UserID, true);
                        }
                        if (ai == null)
                        {
                            ai = new AttachInfo();
                            _file = _fileManager.GetFile(AttachId);
                            ai.AttachID = _file.FileId;
                            ai.AllowDownload = true;
                            ai.Filename = _file.FileName;
                            ai.FileUrl = _file.PhysicalPath;
                            ai.CanRead = "0;1;-3;-1;|||";
                            ai.ContentType = _file.ContentType;
                        }

                        if (ai != null & u != null)
                        {
                            Response.ContentType = ai.ContentType.ToString();
                            if (ai.FileData != null)
                            {
                                if (Permissions.HasAccess(ai.CanRead, u.UserRoles))
                                {
                                    bindata = (byte[])ai.FileData;
                                    Response.BinaryWrite(bindata);
                                    Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.HtmlEncode(ai.Filename.ToString()));
                                }

                            }
                            else
                            {
                                if (Permissions.HasAccess(ai.CanRead, u.UserRoles))
                                {
                                    string fpath = string.Empty;
                                    string fName = string.Empty;
                                    if (string.IsNullOrEmpty(ai.FileUrl))
                                    {
                                        fpath = Server.MapPath(PortalSettings.HomeDirectory + "activeforums_Attach/");
                                        fpath += ai.Filename;
                                        fName = System.IO.Path.GetFileName(fpath);
                                    }
                                    else
                                    {

                                        _file = _fileManager.GetFile(ai.AttachID);
                                        fpath = _file.PhysicalPath;
                                        fName = _file.FileName;
                                    }

                                    if (System.IO.File.Exists(fpath))
                                    {

                                        //Dim vpath As String
                                        //vpath = PortalSettings.HomeDirectory & "activeforums_Attach/" & Server.HtmlEncode(ai.Filename)
                                        FileStream fs = new FileStream(fpath, FileMode.Open, FileAccess.Read);
                                        long contentLength = 0;
                                        if (fs != null)
                                        {
                                            bindata = GetStreamAsByteArray(fs);
                                            fs.Close();
                                        }
                                        string sExt = System.IO.Path.GetExtension(fName);
                                        Response.Clear();
                                        Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.HtmlEncode(fName));
                                        Response.AddHeader("Content-Length", bindata.LongLength.ToString());
                                        sContentType = ai.ContentType;
                                        switch (sExt.ToLowerInvariant())
                                        {
                                            case ".png":
                                                sContentType = "image/png";
                                                break;
                                            case ".jpg":
                                            case ".jpeg":
                                                sContentType = "image/jpeg";
                                                break;
                                            case ".gif":
                                                sContentType = "image/gif";
                                                break;
                                            case ".bmp":
                                                sContentType = "image/bmp";
                                                break;
                                        }

                                        Response.ContentType = sContentType;
                                        Response.OutputStream.Write(bindata, 0, bindata.Length);
                                        Response.End();
                                    }
                                    else
                                    {
                                        fpath = Server.MapPath(PortalSettings.HomeDirectory + "NTForums_Attach/");
                                        fpath += ai.Filename;
                                        if (System.IO.File.Exists(fpath))
                                        {
                                            string vpath = null;
                                            vpath = PortalSettings.HomeDirectory + "activeforums_Attach/" + Server.HtmlEncode(ai.Filename);
                                            Response.Redirect(Page.ResolveUrl(vpath));
                                        }
                                    }
                                }

                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {

            }
        }
        public Task<HttpResponseMessage> UploadFile()
        {
            // This method uploads an attachment to a temporary directory and returns a JSON object containing information about the original file
            // including the temporary file name.  When the post is saved/updated, the temporary file is moved to the appropriate attachment directory

            // Have to a reference to these variables as the internal reference isn't available.
            // in the async result.
            var request = Request;
            var portalSettings = PortalSettings;
            var userInfo = portalSettings.UserInfo;
            var forumUser = new UserController().GetUser(ActiveModule.PortalID, ActiveModule.ModuleID, userInfo.UserID);

            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotAcceptable));
            }

            const string uploadPath = "activeforums_Upload";

            var folderManager = FolderManager.Instance;
            if (!folderManager.FolderExists(ActiveModule.PortalID, uploadPath))
            {
                folderManager.AddFolder(ActiveModule.PortalID, uploadPath);
            }
            var folder = folderManager.GetFolder(ActiveModule.PortalID, uploadPath);

            var provider = new MultipartFormDataStreamProvider(folder.PhysicalPath);

            var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);

                // Make sure a temp file was uploaded and that it exists
                var file = provider.FileData.FirstOrDefault();
                if (file == null || string.IsNullOrWhiteSpace(file.LocalFileName) || !File.Exists(file.LocalFileName))
                {
                    return request.CreateErrorResponse(HttpStatusCode.NoContent, "No File Found");
                }

                // Get the file name without the full path
                var localFileName = Path.GetFileName(file.LocalFileName).TextOrEmpty();

                // Check to make sure that a forum was specified and that the the user has upload permissions
                // This is only an initial check, it will be done again when the file is saved to a post.

                int forumId;
                if (!int.TryParse(provider.FormData["forumId"], out forumId))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Forum Not Specified");
                }

                // Make sure that we can find the forum and that attachments are allowed
                var fc = new ForumController();
                var forum = fc.Forums_Get(ActiveModule.PortalID, ActiveModule.ModuleID, forumId, userInfo.UserID, true, true, -1);

                if (forum == null || !forum.AllowAttach)
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.BadRequest, "Forum Not Found");
                }

                // Make sure the user has permissions to attach files
                if (forumUser == null || !Permissions.HasPerm(forum.Security.Attach, forumUser.UserRoles))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized");
                }

                // Make sure that the file size does not exceed the limit (in KB) for the forum
                // Have to do this since content length is not available when using MultipartFormDataStreamProvider
                var di = new DirectoryInfo(folder.PhysicalPath);
                var fileSize = di.GetFiles(localFileName)[0].Length;

                var maxAllowedFileSize = (long)forum.AttachMaxSize * 1024;

                if ((forum.AttachMaxSize > 0) && (fileSize > maxAllowedFileSize))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Exceeds Max File Size");
                }

                // Get the original file name from the content disposition header
                var fileName = file.Headers.ContentDisposition.FileName.Replace("\"", "");

                if (string.IsNullOrWhiteSpace(fileName))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Invalid File");
                }

                // Make sure we have an acceptable extension type.
                // Check against both the forum configuration and the host configuration
                var extension = Path.GetExtension(fileName).TextOrEmpty().Replace(".", string.Empty).ToLower();
                var isForumAllowedExtension = string.IsNullOrWhiteSpace(forum.AttachTypeAllowed) || forum.AttachTypeAllowed.Replace(".", "").Split(',').Any(val => val == extension);
                if (string.IsNullOrEmpty(extension) || !isForumAllowedExtension || !Host.AllowedExtensionWhitelist.IsAllowedExtension(extension))
                {
                    File.Delete(file.LocalFileName);
                    return request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "File Type Not Allowed");
                }

                const string newFileName = "{0}_{1}{2}";
                var fileNameOnly = Path.GetFileNameWithoutExtension(fileName);
                var userFolder = folderManager.GetUserFolder(userInfo);
                var attachmentFolder = folderManager.GetFolder(userFolder.FolderID);
                var fileManager = FileManager.Instance;
                IFileInfo ufile = null;
                string sExt = Path.GetExtension(fileName);

                if (sExt.ToLower() == ".jpg" || sExt.ToLower() == ".bmp" || sExt.ToLower() == ".png" || sExt.ToLower() == ".jpeg")
                {
                    var sExtOut = ".jpg";
                    ImageFormat imf, imfout = ImageFormat.Jpeg;

                    Image img = Image.FromFile(file.LocalFileName);
                    Image nimg;

                    var maxWidth = forum.MaxAttachWidth;
                    var maxHeight = forum.MaxAttachHeight;

                    int imgWidth = img.Width;
                    int imgHeight = img.Height;

                    var ratioWidth = (double)imgWidth / maxWidth;
                    var ratioHeight = (double)imgHeight / maxHeight;

                    switch (sExt.ToLower())
                    {
                        case ".png":
                            {
                                imf = ImageFormat.Png;
                                if (!forum.ConvertingToJpegAllowed)
                                {
                                    sExtOut = ".png";
                                    imfout = ImageFormat.Png;
                                }
                                break;
                            }
                        case ".bmp": imf = ImageFormat.Bmp; break;
                        default: imf = ImageFormat.Jpeg; break;
                    }

                    MemoryStream mst = new MemoryStream();

                    if (ratioWidth > 1 || ratioHeight > 1)
                    {
                        if (ratioWidth > ratioHeight)
                        {
                            imgWidth = maxWidth;
                            imgHeight = (int)Math.Round(imgHeight / ratioWidth);
                        }
                        else if (ratioWidth < ratioHeight)
                        {
                            imgHeight = maxHeight;
                            imgWidth = (int)Math.Round(imgWidth / ratioHeight);
                        }
                        else
                        {
                            imgWidth = maxWidth;
                            imgHeight = maxHeight;
                        }
                    }

                    Bitmap res = new Bitmap(imgWidth, imgHeight);
                    using (Graphics gr = Graphics.FromImage(res))
                    {
                        gr.Clear(Color.Transparent);
                        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        gr.DrawImage(img, new Rectangle(0, 0, imgWidth, imgHeight), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                        gr.Dispose();
                    }

                    img.Dispose();
                    res.Save(mst, imfout);
                    res.Dispose();

                    var index = 0;
                    fileName = fileNameOnly + sExtOut;

                    while (fileManager.FileExists(attachmentFolder, fileName))
                    {
                        index++;
                        fileName = string.Format(newFileName, fileNameOnly, index, sExtOut);
                    }

                    ufile = fileManager.AddFile(attachmentFolder, fileName, (Stream)mst);
                    mst.Close();

                }
                else
                {
                    using (var fileStream = new FileStream(file.LocalFileName, FileMode.Open, FileAccess.Read))
                    {
                        var index = 0;
                        while (fileManager.FileExists(attachmentFolder, fileName))
                        {
                            index++;
                            fileName = string.Format(newFileName, fileNameOnly, index, sExt);
                        }

                        ufile = fileManager.AddFile(attachmentFolder, fileName, fileStream);
                    }
                }

                // IE<=9 Hack - can't return application/json
                var mediaType = "application/json";
                if (!request.Headers.Accept.Any(h => h.MediaType.Equals("application/json", StringComparison.OrdinalIgnoreCase)))
                    mediaType = "text/html";

                File.Delete(file.LocalFileName);

                if (ufile != null)
                {
                    var result = new ClientAttachment()
                    {
                        FileId = ufile.FileId,
                        ContentType = file.Headers.ContentType.MediaType,
                        FileName = fileName,
                        FileSize = ufile.Size,
                        UploadId = localFileName,
                    };

                    return Request.CreateResponse(HttpStatusCode.Accepted, result, mediaType);
                }
                else
                {
                    return request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "No File Found");
                }
            });

            return task;
        }
        public static string ParseProfileTemplate(string profileTemplate, int userId, int portalId, int moduleId, int currentUserId, int timeZoneOffset)
        {
            var uc = new UserController();
            var up = uc.GetUser(portalId, moduleId, userId);

            return ParseProfileTemplate(profileTemplate, up, portalId, moduleId, string.Empty, CurrentUserTypes.Anon, false, false, false, string.Empty, currentUserId, timeZoneOffset);
        }
        public static string ParseProfileTemplate(string profileTemplate, User up, int portalId, int moduleId, string imagePath, CurrentUserTypes currentUserType, bool legacyTemplate, bool userPrefHideAvatar, bool userPrefHideSignature, string ipAddress, int currentUserId, int timeZoneOffset)
        {
            try
            {
                if (legacyTemplate)
                    profileTemplate = CleanTemplate(profileTemplate);

                if (up.Profile == null)
                    up = new UserController().FillProfile(portalId, -1, up);

                // TODO figure out why/if this recurion is possible.  Seems a bit scary as it could create a loop.
                if (profileTemplate.Contains("[POSTINFO]"))
                {
                    var sPostInfo = GetPostInfo(portalId, moduleId, up.UserId, up.UserName, up, imagePath, false, ipAddress, up.Profile.IsUserOnline, currentUserType, currentUserId, userPrefHideAvatar, timeZoneOffset);
                    profileTemplate = profileTemplate.Replace("[POSTINFO]", sPostInfo);
                }

                var mainSettings = DataCache.MainSettings(moduleId);

                // Parse DNN profile fields if needed
                var pt = profileTemplate;
                if (pt.IndexOf("[DNN:PROFILE:", StringComparison.Ordinal) >= 0)
                    pt = ParseProfile(portalId, up.UserId, pt, currentUserType, currentUserId);

                // Parse Roles
                if (pt.Contains("[ROLES:"))
                    pt = ParseRoles(pt, (up.UserId == -1) ? string.Empty : up.Profile.Roles);

                var result = new StringBuilder(pt);

                // Used in a few places to determine if info should be shown or removed.
                var isMod = (currentUserType == CurrentUserTypes.Admin || currentUserType == CurrentUserTypes.ForumMod || currentUserType == CurrentUserTypes.SuperUser);

                 // Used in a few places to determine if info should be shown or removed.
                var isAdmin = (currentUserType == CurrentUserTypes.Admin || currentUserType == CurrentUserTypes.SuperUser);

                var isAuthethenticated = currentUserType != CurrentUserTypes.Anon;

                // IP Address
                result.Replace("[MODIPADDRESS]", isMod ? ipAddress : string.Empty);

                // User Edit
                result.Replace("[AF:BUTTON:EDITUSER]", isAdmin && up.UserId > 0 ? string.Format("<button class='af-button af-button-edituser' data-id='{0}' data-name='{1}'>[RESX:Edit]</button>", up.UserId, Utilities.JSON.EscapeJsonString(up.DisplayName)) : string.Empty);

                // Points
                var totalPoints = up.PostCount;
                if (mainSettings.EnablePoints && up.UserId > 0 && up.Profile != null)
                {
                    totalPoints = (up.Profile.TopicCount * mainSettings.TopicPointValue) + (up.Profile.ReplyCount * mainSettings.ReplyPointValue) + (up.Profile.AnswerCount * mainSettings.AnswerPointValue) + up.Profile.RewardPoints;
                    result.Replace("[AF:PROFILE:TOTALPOINTS]", totalPoints.ToString());
                    result.Replace("[AF:POINTS:VIEWCOUNT]", up.Profile.ViewCount.ToString());
                    result.Replace("[AF:POINTS:ANSWERCOUNT]", up.Profile.AnswerCount.ToString());
                    result.Replace("[AF:POINTS:REWARDPOINTS]", up.Profile.RewardPoints.ToString());
                }
                else
                {
                    result.Replace("[AF:PROFILE:TOTALPOINTS]", string.Empty);
                    result.Replace("[AF:POINTS:VIEWCOUNT]", string.Empty);
                    result.Replace("[AF:POINTS:ANSWERCOUNT]", string.Empty);
                    result.Replace("[AF:POINTS:REWARDPOINTS]", string.Empty);
                }

                // User Status
                var sUserStatus = string.Empty;
                if (mainSettings.UsersOnlineEnabled && up.UserId > 0 && up.Profile != null)
                    sUserStatus = UserProfiles.UserStatus(imagePath, up.Profile.IsUserOnline, up.UserId, moduleId, "[RESX:UserOnline]", "[RESX:UserOffline]");

                result.Replace("[AF:PROFILE:USERSTATUS]", sUserStatus);
                result.Replace("[AF:PROFILE:USERSTATUS:CSS]", sUserStatus.Contains("online") ? "af-status-online" : "af-status-offline");

                // Rank
                result.Replace("[AF:PROFILE:RANKDISPLAY]", (up.UserId > 0) ? UserProfiles.GetUserRank(portalId, moduleId, up.UserId, totalPoints, 0) : string.Empty);
                result.Replace("[AF:PROFILE:RANKNAME]", (up.UserId > 0) ? UserProfiles.GetUserRank(portalId, moduleId, up.UserId, totalPoints, 1) : string.Empty);

                // PM Image/link
                var pmUrl = string.Empty;
                var pmLink = string.Empty;
                if (up.UserId > 0 && currentUserId >= 0 && up.UserId != currentUserId)
                {
                    switch (mainSettings.PMType)
                    {
                        case PMTypes.Core:
                            pmLink = "<img class='ComposeMessage' data-recipient='{ \"id\": \"user-" + up.UserId + "\", \"name\": \"" + HttpUtility.JavaScriptStringEncode(up.DisplayName) + "\"}' src='" + imagePath + "/images/icon_pm.png' alt=\"[RESX:SendPM]\" title=\"[RESX:SendPM]\" border=\"0\" /></a>";
                            break;

                        case PMTypes.Ventrian:
                            pmUrl = Common.Globals.NavigateURL(mainSettings.PMTabId, string.Empty, new[] {"type=compose", "sendto=" + up.UserId});
                            pmLink = "<a href=\"" + pmUrl + "\"><img src=\"" + imagePath + "/images/icon_pm.png\" alt=\"[RESX:SendPM]\" border=\"0\" /></a>";
                            break;
                    }
                }

                result.Replace("[AF:PROFILE:PMLINK]", pmLink);
                result.Replace("[AF:PROFILE:PMURL]", pmUrl);

                // Signature
                var sSignature = string.Empty;
                if (mainSettings.AllowSignatures != 0 && ! userPrefHideSignature && up.Profile != null && !up.Profile.SignatureDisabled)
                {
                    sSignature = up.Profile.Signature;

                    if (sSignature != string.Empty)
                        sSignature = Utilities.ManageImagePath(sSignature);

                    switch (mainSettings.AllowSignatures)
                    {
                        case 1:
                            sSignature = Utilities.HTMLEncode(sSignature);
                            sSignature = sSignature.Replace(System.Environment.NewLine, "<br />");
                            break;
                        case 2:
                            sSignature = Utilities.HTMLDecode(sSignature);
                            break;
                    }
                }

                result.Replace("[AF:PROFILE:SIGNATURE]", sSignature);

                // Avatar
                var sAvatar = string.Empty;
                if (! userPrefHideAvatar && !up.Profile.AvatarDisabled)
                    sAvatar = UserProfiles.GetAvatar(up.UserId, mainSettings.AvatarWidth, mainSettings.AvatarHeight);

                result.Replace("[AF:PROFILE:AVATAR]", sAvatar);

                // Display Name
                result.Replace("[AF:PROFILE:DISPLAYNAME]", UserProfiles.GetDisplayName(moduleId, true, isMod, isAdmin, up.UserId, up.UserName, up.FirstName, up.LastName, up.DisplayName));

                // These fields are no longer used
                result.Replace("[AF:PROFILE:LOCATION]", string.Empty);
                result.Replace("[AF:PROFILE:WEBSITE]", string.Empty);
                result.Replace("[AF:PROFILE:YAHOO]", string.Empty);
                result.Replace("[AF:PROFILE:MSN]", string.Empty);
                result.Replace("[AF:PROFILE:ICQ]", string.Empty);
                result.Replace("[AF:PROFILE:AOL]", string.Empty);
                result.Replace("[AF:PROFILE:OCCUPATION]", string.Empty);
                result.Replace("[AF:PROFILE:INTERESTS]", string.Empty);
                result.Replace("[AF:CONTROL:AVATAREDIT]", string.Empty);
                result.Replace("[AF:BUTTON:PROFILEEDIT]", string.Empty);
                result.Replace("[AF:BUTTON:PROFILESAVE]", string.Empty);
                result.Replace("[AF:BUTTON:PROFILECANCEL]", string.Empty);
                result.Replace("[AF:PROFILE:BIO]", string.Empty);
                result.Replace("[MODUSERSETTINGS]", string.Empty);

                // Date Created
                var sDateCreated = string.Empty;
                var sDateCreatedReplacement = "[AF:PROFILE:DATECREATED]";
                if (up.UserId > 0 && up.Profile != null && up.Profile.DateCreated != null)
                {
                    if (pt.Contains("[AF:PROFILE:DATECREATED:"))
                    {
                        var sFormat = pt.Substring(pt.IndexOf("[AF:PROFILE:DATECREATED:", StringComparison.Ordinal) + (sDateCreatedReplacement.Length), 1);
                        sDateCreated = up.Profile.DateCreated.ToString(sFormat);
                        sDateCreatedReplacement = "[AF:PROFILE:DATECREATED:" + sFormat + "]";
                    }
                    else
                        sDateCreated = Utilities.GetDate(up.Profile.DateCreated, moduleId, timeZoneOffset);
                }
                result.Replace(sDateCreatedReplacement, sDateCreated);

                // Last Activity
                var sDateLastActivity = string.Empty;
                var sDateLastActivityReplacement = "[AF:PROFILE:DATELASTACTIVITY]";

                if (up.Profile.DateLastActivity != null && up.UserId > 0)
                {
                    if (pt.Contains("[AF:PROFILE:DATELASTACTIVITY:"))
                    {
                        string sFormat = pt.Substring(pt.IndexOf("[AF:PROFILE:DATELASTACTIVITY:", StringComparison.Ordinal) + (sDateLastActivityReplacement.Length), 1);
                        sDateLastActivity = up.Profile.DateLastActivity.ToString(sFormat);
                        sDateLastActivityReplacement = "[AF:PROFILE:DATELASTACTIVITY:" + sFormat + "]";
                    }
                    else
                        sDateLastActivity = Utilities.GetDate(up.Profile.DateLastActivity, moduleId, timeZoneOffset);
                }
                result.Replace(sDateLastActivityReplacement, sDateLastActivity);

                // Post Count
                result.Replace("[AF:PROFILE:POSTCOUNT]", (up.PostCount == 0) ? string.Empty : up.PostCount.ToString());
                result.Replace("[AF:PROFILE:USERCAPTION]", up.Profile.UserCaption);
                result.Replace("[AF:PROFILE:USERID]", up.UserId.ToString());
                result.Replace("[AF:PROFILE:USERNAME]", Utilities.HTMLEncode(up.UserName).Replace("&amp;#", "&#"));
                result.Replace("[AF:PROFILE:FIRSTNAME]", Utilities.HTMLEncode(up.FirstName).Replace("&amp;#", "&#"));
                result.Replace("[AF:PROFILE:LASTNAME]", Utilities.HTMLEncode(up.LastName).Replace("&amp;#", "&#"));
                result.Replace("[AF:PROFILE:DATELASTPOST]", (up.Profile.DateLastPost == DateTime.MinValue) ? string.Empty : Utilities.GetDate(up.Profile.DateLastPost, moduleId, timeZoneOffset));
                result.Replace("[AF:PROFILE:TOPICCOUNT]", up.Profile.TopicCount.ToString());
                result.Replace("[AF:PROFILE:REPLYCOUNT]", up.Profile.ReplyCount.ToString());
                result.Replace("[AF:PROFILE:ANSWERCOUNT]", up.Profile.AnswerCount.ToString());
                result.Replace("[AF:PROFILE:REWARDPOINTS]", up.Profile.RewardPoints.ToString());

                return result.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
Esempio n. 17
0
        private string BuildRSS(int PortalId, int TabId, int ModuleId, int intPosts, int ForumID, bool IngnoreSecurity, bool IncludeBody)
        {
            DotNetNuke.Entities.Portals.PortalController pc = new DotNetNuke.Entities.Portals.PortalController();
            DotNetNuke.Entities.Portals.PortalSettings   ps = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings();
            DotNetNuke.Entities.Users.UserInfo           ou = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo();
            UserController uc = new UserController();
            User           u  = uc.GetUser(PortalId, ModuleId);

            DataSet ds = DataProvider.Instance().UI_TopicsView(PortalId, ModuleId, ForumID, ou.UserID, 0, 20, ou.IsSuperUser, SortColumns.ReplyCreated);

            if (ds.Tables.Count > 0)
            {
                offSet = ps.TimeZoneOffset;
                if (ds.Tables[0].Rows.Count == 0)
                {
                    return(string.Empty);
                }
                drForum = ds.Tables[0].Rows[0];

                drSecurity = ds.Tables[1].Rows[0];
                dtTopics   = ds.Tables[3];
                if (dtTopics.Rows.Count == 0)
                {
                    return(string.Empty);
                }
                bView = Permissions.HasPerm(drSecurity["CanView"].ToString(), u.UserRoles);
                bRead = Permissions.HasPerm(drSecurity["CanRead"].ToString(), u.UserRoles);
                StringBuilder sb = new StringBuilder(1024);
                if (bRead)
                {
                    ForumName        = drForum["ForumName"].ToString();
                    GroupName        = drForum["GroupName"].ToString();
                    ForumDescription = drForum["ForumDesc"].ToString();
                    //TopicsTemplateId = CInt(drForum("TopicsTemplateId"))
                    bAllowRSS = Convert.ToBoolean(drForum["AllowRSS"]);
                    if (bAllowRSS)
                    {
                        sb.Append("<?xml version=\"1.0\" ?>" + System.Environment.NewLine);
                        sb.Append("<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:cf=\"http://www.microsoft.com/schemas/rss/core/2005\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\">" + System.Environment.NewLine);
                        string[] Params = { ParamKeys.ForumId + "=" + ForumID, ParamKeys.ViewType + "=" + Views.Topics };
                        string   URL    = string.Empty;
                        if (Request.QueryString["asg"] == null)
                        {
                            URL = DotNetNuke.Common.Globals.NavigateURL(TabId, "", Params);
                        }
                        else if (SimulateIsNumeric.IsNumeric(Request.QueryString["asg"]))
                        {
                            Params = new string[] { "asg=" + Request.QueryString["asg"], ParamKeys.ForumId + "=" + ForumID, ParamKeys.ViewType + "=" + Views.Topics };
                            URL    = DotNetNuke.Common.Globals.NavigateURL(TabId, "", Params);
                        }

                        if (URL.IndexOf(Request.Url.Host) == -1)
                        {
                            URL = DotNetNuke.Common.Globals.AddHTTP(Request.Url.Host) + URL;
                        }
                        // build channel
                        sb.Append(WriteElement("channel", 1));
                        sb.Append(WriteElement("title", HttpUtility.HtmlEncode(ps.PortalName) + " " + ForumName, 2));
                        sb.Append(WriteElement("link", URL, 2));
                        sb.Append(WriteElement("description", ForumDescription, 2));
                        sb.Append(WriteElement("language", PortalSettings.DefaultLanguage, 2));
                        sb.Append(WriteElement("generator", "ActiveForums  5.0", 2));
                        sb.Append(WriteElement("copyright", PortalSettings.FooterText, 2));
                        sb.Append(WriteElement("lastBuildDate", "[LASTBUILDDATE]", 2));
                        if (!(ps.LogoFile == string.Empty))
                        {
                            string sLogo = "<image><url>http://" + Request.Url.Host + ps.HomeDirectory + ps.LogoFile + "</url>";
                            sLogo += "<title>" + ps.PortalName + " " + ForumName + "</title>";
                            sLogo += "<link>" + URL + "</link></image>";
                            sb.Append(sLogo);
                        }
                        foreach (DataRow dr in dtTopics.Rows)
                        {
                            if (DotNetNuke.Security.PortalSecurity.IsInRoles(PortalSettings.ActiveTab.AuthorizedRoles))
                            {
                                //objModule = objModules.GetModule(ModuleId, TabId)
                                //If DotNetNuke.Security.PortalSecurity.IsInRoles(objModule.AuthorizedViewRoles) = True Then
                                //    sb.Append(BuildItem(dr, TabId, 2, IncludeBody, PortalId))
                                //End If
                                sb.Append(BuildItem(dr, TabId, 2, IncludeBody, PortalId));
                            }
                        }
                        sb.Append("<atom:link href=\"http://" + Request.Url.Host + HttpUtility.HtmlEncode(Request.RawUrl) + "\" rel=\"self\" type=\"application/rss+xml\" />");
                        sb.Append(WriteElement("/channel", 1));
                        sb.Replace("[LASTBUILDDATE]", LastBuildDate.ToString("r"));
                        sb.Append("</rss>");
                        //Cache.Insert("RSS" & ModuleId & ForumID, sb.ToString, Nothing, DateTime.Now.AddMinutes(dblCacheTimeOut), TimeSpan.Zero)
                        return(sb.ToString());
                    }
                }
            }


            return(string.Empty);
        }