private void BindAttach(string AttachIds)
        {
            if (UserId > 0)
            {
                string sOut = string.Empty;
                Literal lit = new Literal();

                if (AttachIds == string.Empty)
                {
                    Data.AttachController adb = new Data.AttachController();
                    AttachIds = adb.GetAttachIds(AuthorId, ContentId);
                }

                sOut = BuildAttachGrid(AttachIds);
                if (PendingAttach >= ForumInfo.AttachCount)
                {
                    sOut += "<script type=\"text/javascript\">disableUpload();</script>";
                }
                else if (cbAttach.IsCallback)
                {
                    sOut += "<script type=\"text/javascript\">enableUpload();</script>";
                }
                if (!(AttachIds == string.Empty))
                {
                    sOut += "<script type=\"text/javascript\">window.amaf_setAttachIds('" + AttachIds + "');</script>";
                }
                lit.Text = sOut;
                plhAttach.Controls.Add(lit);

            }
        }
Beispiel #2
0
        public void Reply_Delete(int PortalId, int ForumId, int TopicId, int ReplyId, int DelBehavior)
        {
            DataProvider.Instance().Reply_Delete(ForumId, TopicId, ReplyId, DelBehavior);
            var objectKey = string.Format("{0}:{1}:{2}", ForumId, TopicId, ReplyId);

            JournalController.Instance.DeleteJournalItemByKey(PortalId, objectKey);

            if (DelBehavior != 0)
            {
                return;
            }

            // If it's a hard delete, delete associated attachments
            var attachmentController = new Data.AttachController();
            var fileManager          = FileManager.Instance;
            var folderManager        = FolderManager.Instance;
            var attachmentFolder     = folderManager.GetFolder(PortalId, "activeforums_Attach");

            foreach (var attachment in attachmentController.ListForPost(TopicId, ReplyId))
            {
                attachmentController.Delete(attachment.AttachmentId);

                var file = attachment.FileId.HasValue ? fileManager.GetFile(attachment.FileId.Value) : fileManager.GetFile(attachmentFolder, attachment.FileName);

                // Only delete the file if it exists in the attachment folder
                if (file != null && file.FolderId == attachmentFolder.FolderID)
                {
                    fileManager.DeleteFile(file);
                }
            }
        }
        private void BindAttach(string AttachIds)
        {
            if (UserId > 0)
            {
                string  sOut = string.Empty;
                Literal lit  = new Literal();

                if (AttachIds == string.Empty)
                {
                    Data.AttachController adb = new Data.AttachController();
                    AttachIds = adb.GetAttachIds(AuthorId, ContentId);
                }


                sOut = BuildAttachGrid(AttachIds);
                if (PendingAttach >= ForumInfo.AttachCount)
                {
                    sOut += "<script type=\"text/javascript\">disableUpload();</script>";
                }
                else if (cbAttach.IsCallback)
                {
                    sOut += "<script type=\"text/javascript\">enableUpload();</script>";
                }
                if (!(AttachIds == string.Empty))
                {
                    sOut += "<script type=\"text/javascript\">window.amaf_setAttachIds('" + AttachIds + "');</script>";
                }
                lit.Text = sOut;
                plhAttach.Controls.Add(lit);
            }
        }
        private void cbMyFiles_Callback(object sender, Modules.ActiveForums.Controls.CallBackEventArgs e)
        {
            string attachIds = e.Parameters[1].ToString();

            switch (e.Parameters[0].ToLowerInvariant())
            {
            case "del":
                if (SimulateIsNumeric.IsNumeric(e.Parameters[2]))
                {
                    int aid = Convert.ToInt32(e.Parameters[2]);
                    Data.AttachController ac = new Data.AttachController();
                    int uid = -1;
                    if (SimulateIsNumeric.IsNumeric(e.Parameters[3]))
                    {
                        uid = Convert.ToInt32(e.Parameters[3]);
                    }
                    if ((uid == this.UserId && !(this.UserId == -1)) | Permissions.HasPerm(ForumInfo.Security.ModDelete, ForumUser.UserRoles) || UserInfo.IsSuperUser)
                    {
                        ac.Attach_Delete(aid, -1, uid);
                    }
                }


                break;
            }
            PendingAttach = 0;
            plhMyFiles.Controls.Clear();
            BindMyFiles();
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            HtmlTextWriter         htmlWriter   = new HtmlTextWriter(stringWriter);

            plhMyFiles.RenderControl(htmlWriter);
            string html = stringWriter.GetStringBuilder().ToString();

            html = Utilities.LocalizeControl(html);
            LiteralControl lit = new LiteralControl();

            lit.Text = html;
            lit.RenderControl(e.Output);
        }
Beispiel #5
0
        public void Topics_Delete(int PortalId, int ModuleId, int ForumId, int TopicId, int DelBehavior)
        {
            DataProvider.Instance().Topics_Delete(ForumId, TopicId, DelBehavior);
            var cachekey = string.Format("AF-FV-{0}-{1}", PortalId, ModuleId);

            DataCache.CacheClearPrefix(cachekey);
            try
            {
                var objectKey = string.Format("{0}:{1}", ForumId, TopicId);
                JournalController.Instance.DeleteJournalItemByKey(PortalId, objectKey);
            }
            catch (Exception ex)
            {
            }

            if (DelBehavior != 0)
            {
                return;
            }

            // If it's a hard delete, delete associated attachments
            var attachmentController = new Data.AttachController();
            var fileManager          = FileManager.Instance;
            var folderManager        = FolderManager.Instance;
            var attachmentFolder     = folderManager.GetFolder(PortalId, "activeforums_Attach");

            foreach (var attachment in attachmentController.ListForPost(TopicId, null))
            {
                attachmentController.Delete(attachment.AttachmentId);

                var file = attachment.FileId.HasValue ? fileManager.GetFile(attachment.FileId.Value) : fileManager.GetFile(attachmentFolder, attachment.FileName);

                // Only delete the file if it exists in the attachment folder
                if (file != null && file.FolderId == attachmentFolder.FolderID)
                {
                    fileManager.DeleteFile(file);
                }
            }
        }
        private void PrepareAttachments(int? contentId = null)
        {
            // Handle the case where we don't yet have a topic id (new posts)
            if(!contentId.HasValue || contentId.Value <= 0)
            {
                hidAttachments.Value = "[]"; // JSON for an empty array
                return;
            }

            var adb = new Data.AttachController();
            var attachments = adb.ListForContent(contentId.Value);

            var clientAttachments = attachments.Select(attachment => new ClientAttachment
            {
                AttachmentId = attachment.AttachmentId,
                ContentType = attachment.ContentType,
                FileId = attachment.FileId,
                FileName = Regex.Replace(attachment.FileName.TextOrEmpty(), @"^__\d+__\d+__", string.Empty), // Remove our unique file prefix before sending to the client.
                FileSize = attachment.FileSize
            }).ToList();

            var serializer = new DataContractJsonSerializer(typeof(List<ClientAttachment>));

            using(var ms = new MemoryStream())
            {
                serializer.WriteObject(ms, clientAttachments);
                ms.Seek(0, 0);
                using(var sr = new StreamReader(ms, Encoding.UTF8))
                {
                    hidAttachments.Value = sr.ReadToEnd();
                }
            }
        }
Beispiel #7
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var attachmentId = Utilities.SafeConvertInt(Request.Params["AttachmentID"], -1); // Used for new attachments where the attachment is the actual file link (shouldn't appear in posts)
            var attachFileId = Utilities.SafeConvertInt(Request.Params["AttachID"], -1);     // Used for legacy attachments where the attachid was actually the file id. (appears in posts)
            var portalId     = Utilities.SafeConvertInt(Request.Params["PortalID"], -1);
            var moduleId     = Utilities.SafeConvertInt(Request.Params["ModuleID"], -1);

            if (Page.IsPostBack || (attachmentId < 0 && attachFileId < 0) || portalId < 0 || moduleId < 0)
            {
                Response.StatusCode = 400;
                Response.Write("Invalid Request");
                Response.End();
                return;
            }

            // Get the attachment including the "Can Read" permission for the associated content id.
            var attachment = new Data.AttachController().Get(attachmentId, attachFileId, true);

            // Make sure the attachment exists
            if (attachment == null)
            {
                Response.StatusCode = 404;
                Response.Write("Not Found");
                Response.End();
                return;
            }

            // Make sure the user has read access
            var u = new UserController().GetUser(portalId, moduleId);

            if (u == null || !Permissions.HasAccess(attachment.CanRead, u.UserRoles))
            {
                Response.StatusCode = 401;
                Response.Write("Unauthorized");
                Response.End();
                return;
            }

            // Get the filename with the unique identifier prefix removed.
            var filename = Regex.Replace(attachment.FileName.TextOrEmpty(), @"__\d+__\d+__", string.Empty);

            // Some legacy attachments may still be stored in the DB.
            if (attachment.FileData != null)
            {
                Response.ContentType = attachment.ContentType;

                if (attachmentId > 0)
                {
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.HtmlEncode(filename));
                }
                else // Handle legacy inline attachments a bit differently
                {
                    Response.AddHeader("Content-Disposition", "filename=" + Server.HtmlEncode(filename));
                }

                Response.BinaryWrite(attachment.FileData);
                Response.End();
                return;
            }

            var fileManager = FileManager.Instance;

            string filePath = null;

            // If there is a file id, access the file using the file manager
            if (attachment.FileId.HasValue && attachment.FileId.Value > 0)
            {
                var file = fileManager.GetFile(attachment.FileId.Value);
                if (file != null)
                {
                    filePath = file.PhysicalPath;
                }
            }
            // Otherwise check the attachments directory (current and legacy)
            else
            {
                filePath = Server.MapPath(PortalSettings.HomeDirectory + "activeforums_Attach/") + attachment.FileName;

                // This is another check to support legacy attachments.
                if (!File.Exists(filePath))
                {
                    filePath = Server.MapPath(PortalSettings.HomeDirectory + "NTForums_Attach/") + attachment.FileName;
                }
            }

            // At this point, we should have a valid file path
            if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
            {
                Response.StatusCode = 404;
                Response.Write("Not Found");
                Response.End();
                return;
            }

            var length = attachment.FileSize;

            if (length <= 0)
            {
                length = new System.IO.FileInfo(filePath).Length;
            }

            Response.Clear();
            Response.ContentType = attachment.ContentType;

            if (attachmentId > 0)
            {
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.HtmlEncode(filename));
            }
            else // Handle legacy inline attachments a bit differently
            {
                Response.AddHeader("Content-Disposition", "filename=" + Server.HtmlEncode(filename));
            }

            Response.AddHeader("Content-Length", length.ToString());
            Response.WriteFile(filePath);
            Response.Flush();
            Response.Close();
            Response.End();
        }
Beispiel #8
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>");
            }

        }
Beispiel #9
0
        public void Reply_Delete(int PortalId, int ForumId, int TopicId, int ReplyId, int DelBehavior)
        {
            DataProvider.Instance().Reply_Delete(ForumId, TopicId, ReplyId, DelBehavior);
            var objectKey = string.Format("{0}:{1}:{2}", ForumId, TopicId, ReplyId);
            JournalController.Instance.DeleteJournalItemByKey(PortalId, objectKey);

            if (DelBehavior != 0)
                return;

            // If it's a hard delete, delete associated attachments
            var attachmentController = new Data.AttachController();
            var fileManager = FileManager.Instance;
            var folderManager = FolderManager.Instance;
            var attachmentFolder = folderManager.GetFolder(PortalId, "activeforums_Attach");

            foreach(var attachment in attachmentController.ListForPost(TopicId, ReplyId))
            {
                attachmentController.Delete(attachment.AttachmentId);

                var file = attachment.FileId.HasValue ? fileManager.GetFile(attachment.FileId.Value) : fileManager.GetFile(attachmentFolder, attachment.FileName);

                // Only delete the file if it exists in the attachment folder
                if (file != null && file.FolderId == attachmentFolder.FolderID)
                    fileManager.DeleteFile(file);
            }
        }
Beispiel #10
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)
            {

            }
        }
Beispiel #11
0
        public void Topics_Delete(int PortalId, int ModuleId, int ForumId, int TopicId, int DelBehavior)
        {
            DataProvider.Instance().Topics_Delete(ForumId, TopicId, DelBehavior);
            var cachekey = string.Format("AF-FV-{0}-{1}", PortalId, ModuleId);
            DataCache.CacheClearPrefix(cachekey);
            try
            {
                var objectKey = string.Format("{0}:{1}", ForumId, TopicId);
                JournalController.Instance.DeleteJournalItemByKey(PortalId, objectKey);
            }
            catch (Exception ex)
            {

            }

            if (DelBehavior != 0)
                return;

            // If it's a hard delete, delete associated attachments
            var attachmentController = new Data.AttachController();
            var fileManager = FileManager.Instance;
            var folderManager = FolderManager.Instance;
            var attachmentFolder = folderManager.GetFolder(PortalId, "activeforums_Attach");

            foreach (var attachment in attachmentController.ListForPost(TopicId, null))
            {
                attachmentController.Delete(attachment.AttachmentId);

                var file = attachment.FileId.HasValue ? fileManager.GetFile(attachment.FileId.Value) : fileManager.GetFile(attachmentFolder, attachment.FileName);

                // Only delete the file if it exists in the attachment folder
                if (file != null && file.FolderId == attachmentFolder.FolderID)
                    fileManager.DeleteFile(file);
            }
        }
Beispiel #12
0
        private void SaveAttach(int contentId)
        {
            var attachIds = hidAttachIds.Value;
            var fileManager = FileManager.Instance;

            if (attachIds == string.Empty)
                return;

            foreach (var attachid in attachIds.Split(';'))
            {
                if (attachid.Trim() == string.Empty)
                    continue;

                var tmpAttachId = Convert.ToInt32(attachid);
                var file = fileManager.GetFile(tmpAttachId);
                var adb = new Data.AttachController();

                if (file == null)
                    adb.SaveToContent(contentId, tmpAttachId, null, null, false, null);
                else
                {
                    var fileUrl = "~/LinkClick.aspx?fileticket={0}";
                    var url = Page.ResolveUrl("~/LinkClick.aspx?fileid=" + file.FileId);
                    fileUrl = string.Format(fileUrl, UrlUtils.EncryptParameter(UrlUtils.GetParameterValue(url)));
                    adb.SaveToContent(contentId, tmpAttachId, fileUrl, file.FileName, true, file.ContentType);
                }
            }
        }
Beispiel #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)
            {
            }
        }
Beispiel #14
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>");
            }
        }
        // Note attachments are currently saved into the authors file directory
        private void SaveAttachments(int contentId)
        {
            var fileManager = FileManager.Instance;
            var folderManager = FolderManager.Instance;
            var adb = new Data.AttachController();

            var userFolder = folderManager.GetUserFolder(UserInfo);

            const string uploadFolderName = "activeforums_Upload";
            const string attachmentFolderName = "activeforums_Attach";
            const string fileNameTemplate = "__{0}__{1}__{2}";

            var attachmentFolder = folderManager.GetFolder(PortalId, attachmentFolderName) ?? folderManager.AddFolder(PortalId, attachmentFolderName);

            // Read the attachment list sent in the hidden field as json
            var attachmentsJson = hidAttachments.Value;
            var serializer = new DataContractJsonSerializer(typeof (List<ClientAttachment>));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(attachmentsJson));
            var attachmentsNew = (List<ClientAttachment>)serializer.ReadObject(ms);
            ms.Close();

            // Read the list of existing attachments for the content.  Must do this before saving any of the new attachments!
            // Ignore any legacy inline attachments
            var attachmentsOld = adb.ListForContent(contentId).Where(o => !o.AllowDownload.HasValue || o.AllowDownload.Value);

            // Save all of the new attachments
            foreach(var attachment in attachmentsNew)
            {
                // Don't need to do anything with existing attachments
                if(attachment.AttachmentId.HasValue && attachment.AttachmentId.Value > 0)
                    continue;

                IFileInfo file = null;

                var fileId = attachment.FileId.GetValueOrDefault();
                if(fileId > 0 && userFolder != null)
                {
                    // Make sure that the file exists and it actually belongs to the user who is trying to attach it
                    file = fileManager.GetFile(fileId);
                    if(file == null || file.FolderId != userFolder.FolderID) continue;
                }
                else if(!string.IsNullOrWhiteSpace(attachment.UploadId) && !string.IsNullOrWhiteSpace(attachment.FileName))
                {
                    if (!Regex.IsMatch(attachment.UploadId, @"^[\w\-. ]+$")) // Check for shenanigans.
                        continue;

                    var uploadFilePath = PathUtils.Instance.GetPhysicalPath(PortalId, uploadFolderName + "/" + attachment.UploadId);

                    if (!File.Exists(uploadFilePath))
                        continue;

                    // Store the files with a filename format that prevents overwrites.
                    var index = 0;
                    var fileName = string.Format(fileNameTemplate, contentId, index, Regex.Replace(attachment.FileName, @"[^\w\-. ]+", string.Empty));
                    while(fileManager.FileExists(attachmentFolder, fileName))
                    {
                        index++;
                        fileName = string.Format(fileNameTemplate, contentId, index, Regex.Replace(attachment.FileName, @"[^\w\-. ]+", string.Empty));
                    }

                    // Copy the file into the attachment folder with the correct name.
                    using (var fileStream = new FileStream(uploadFilePath, FileMode.Open, FileAccess.Read))
                    {
                        file = fileManager.AddFile(attachmentFolder, fileName, fileStream);
                    }

                    File.Delete(uploadFilePath);
                }

                if(file == null)
                    continue;

                adb.Save(contentId, UserId, file.FileName, file.ContentType, file.Size, file.FileId);
            }

            // Remove any attachments that are no longer in the list of attachments
            var attachmentsToRemove = attachmentsOld.Where(a1 => attachmentsNew.All(a2 => a2.AttachmentId != a1.AttachmentId));
            foreach(var attachment in attachmentsToRemove)
            {
                adb.Delete(attachment.AttachmentId);

                var file = attachment.FileId.HasValue ? fileManager.GetFile(attachment.FileId.Value) : fileManager.GetFile(attachmentFolder, attachment.FileName);

                // Only delete the file if it exists in the attachment folder
                if(file != null && file.FolderId == attachmentFolder.FolderID)
                    fileManager.DeleteFile(file);
            }
        }
        private string BuildAttachGrid(int Uid, string AttachIds, int RowIndex, int MaxRows, string SortColumn, string Sort)
        {
            int mode = 0;

            if (RowIndex > -1)
            {
                mode = 1;
            }
            PendingAttach = 0;
            string sOut = string.Empty;

            Data.AttachController ac  = new Data.AttachController();
            int               i       = 0;
            string            strHost = DotNetNuke.Common.Globals.AddHTTP(DotNetNuke.Common.Globals.GetDomainName(Request)) + "/";
            List <AttachInfo> al      = null;

            if (RowIndex == -1)
            {
                al = ac.Attach_ListAttachFiles(Uid, AttachIds);
            }
            else
            {
                al = ac.Attach_ListMyFiles(Uid, RowIndex, MaxRows, SortColumn, Sort);
            }
            foreach (AttachInfo ai in al)
            {
                PendingAttach += 1;
                string insertHTML   = string.Empty;
                string insertThumb  = string.Empty;
                string toggleInline = string.Empty;
                string deleteAttach = Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/delete12.png");
                if (mode == 1)
                {
                    deleteAttach = "<img src=\"" + deleteAttach + "\" style=\"cursor:pointer;\" onclick=\"af_delAttach(" + ai.AttachID.ToString() + "," + ai.UserID.ToString() + ");\" />";
                }
                else
                {
                    deleteAttach = "<img src=\"" + deleteAttach + "\" style=\"cursor:pointer;\" onclick=\"af_delContAttach(" + ai.AttachID.ToString() + "," + ai.UserID.ToString() + ");\" />";
                }
                if (ai.Filename.ToLowerInvariant().Contains(".jpg") | ai.Filename.ToLowerInvariant().Contains(".bmp") | ai.Filename.ToLowerInvariant().Contains(".gif") | ai.Filename.ToLowerInvariant().Contains(".png") | ai.Filename.ToLowerInvariant().Contains(".jpeg"))
                {
                    int    w     = 0;
                    int    h     = 0;
                    string fpath = null;
                    fpath  = Server.MapPath(PortalSettings.HomeDirectory + "activeforums_Attach/");
                    fpath += ai.Filename;
                    byte[] bindata = null;
                    bindata = (byte[])ai.FileData;
                    if (bindata != null)
                    {
                        System.IO.MemoryStream memStream = new System.IO.MemoryStream(bindata);
                        try
                        {
                            System.Drawing.Image g = System.Drawing.Image.FromStream(memStream);
                            if (g != null)
                            {
                                w = g.Width;
                                h = g.Height;
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    else
                    {
                        try
                        {
                            System.Drawing.Image g = System.Drawing.Image.FromFile(fpath);
                            if (g != null)
                            {
                                w = g.Width;
                                h = g.Height;
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }

                    if (mode == 0)
                    {
                        string sInsert = string.Empty;
                        string sClose  = string.Empty;
                        if (ai.ParentAttachId > 0)
                        {
                            sInsert = "<a href=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/viewer.aspx") + "?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + ai.ParentAttachId + "\" target=\"_blank\">";
                            sClose  = "</a>";
                        }
                        if (ai.FileData == null)
                        {
                            string vpath = null;
                            vpath    = PortalSettings.HomeDirectory + "activeforums_Attach/";
                            sInsert += "<img src=\"" + vpath + ai.Filename + "\" border=\"0\" class=\"afimg\" />";
                        }
                        else
                        {
                            sInsert += "<img src=" + Page.ResolveUrl("~/DesktopModules/ActiveForums/viewer.aspx") + "?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + ai.AttachID + " border=0 class=\"afimg\" />";
                        }

                        sInsert += sClose;
                        if (ForumInfo.AllowHTML && ForumInfo.EditorType != EditorTypes.TEXTBOX)
                        {
                            insertHTML = "<a href=\"javascript:amaf_insertHTML('" + Server.HtmlEncode(sInsert) + "');amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",0);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:InsertImage]\" /></a>";
                        }
                        else
                        {
                            if (ai.ParentAttachId > 0)
                            {
                                insertHTML = "<a href=\"javascript:amaf_insertHTML('[THUMBNAIL:" + ai.AttachID + ":" + ai.ParentAttachId + "]');amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",0);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:InsertImage]\" /></a>";
                            }
                            else
                            {
                                insertHTML = "<a href=\"javascript:amaf_insertHTML('[IMAGE:" + ai.AttachID + "]');amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",0);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:InsertImage]\" /></a>";
                            }
                        }
                        insertThumb = "<a href=\"javascript:amaf_insertThumbnail(" + ai.AttachID + "," + ai.UserID + "," + w + "," + h + ");\"><img src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_thumb.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:CreateThumbnail]\" border=\"0\" /></a>";
                        if (ai.AllowDownload)
                        {
                            toggleInline = "<a href=\"javascript:amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",1);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/checkbox.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:AllowDownload]\" /></a>";
                        }
                        else
                        {
                            toggleInline = "<a href=\"javascript:amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",1);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/checkbox_unchecked.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:AllowDownload]\" /></a>";
                        }
                    }
                    else
                    {
                        toggleInline = "<a href=\"javascript:amaf_addAttach(" + ai.AttachID + "," + ai.UserID + ");\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/add.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:AddAttach]\" /></a>";
                    }
                }
                else
                {
                    if (mode == 1)
                    {
                        toggleInline = "<a href=\"javascript:amaf_addAttach(" + ai.AttachID + "," + ai.UserID + ");\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/add.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:AddAttach]\" /></a>";
                    }
                }
                string rClass = "afrow";
                if (i % 2 == 0)
                {
                    rClass += " afhighlight";
                }
                sOut += "<tr onmouseout=\"this.className='" + rClass + "';\" class=\"" + rClass + "\"><td>" + ai.Filename + "</td><td>" + Utilities.FormatFileSize(ai.FileSize) + "</td><td align=\"center\">" + insertThumb + "</td><td align=\"center\">" + insertHTML + "</td><td align=\"center\">" + toggleInline + "</td><td align=\"center\">" + deleteAttach + "</td></tr>";
                i    += 1;
            }
            string tbl           = string.Empty;
            string createThumbHD = string.Empty;
            string insertImageHD = string.Empty;
            string downloadHD    = string.Empty;

            if (sOut != "")
            {
                if (mode == 0)
                {
                    createThumbHD = "[RESX:CreateThumbnail]";
                    insertImageHD = "[RESX:InsertImage]";
                    downloadHD    = "[RESX:AllowDownload]";
                }
                else
                {
                    downloadHD = "[RESX:AddAttach]";
                }
                tbl  = "<table cellpadding=\"0\" cellspacing=\"0\" width=\"95%\"><tr><td class=\"afattachhead\">[RESX:FileName]</td><td class=\"afattachhead\">[RESX:FileSize]</td><td class=\"afattachhead\" align=\"center\">" + createThumbHD + "</td><td class=\"afattachhead\" align=\"center\">" + insertImageHD + "</td><td class=\"afattachhead\" align=\"center\">" + downloadHD;
                tbl += "</td><td class=\"afattachhead\" align=\"center\">[RESX:Delete]</td></tr>" + sOut + "</table>";
            }
            return(tbl);
        }
        private string BuildAttachGrid(int Uid, string AttachIds, int RowIndex, int MaxRows, string SortColumn, string Sort)
        {
            int mode = 0;
            if (RowIndex > -1)
            {
                mode = 1;
            }
            PendingAttach = 0;
            string sOut = string.Empty;
            Data.AttachController ac = new Data.AttachController();
            int i = 0;
            string strHost = DotNetNuke.Common.Globals.AddHTTP(DotNetNuke.Common.Globals.GetDomainName(Request)) + "/";
            List<AttachInfo> al = null;
            if (RowIndex == -1)
            {
                al = ac.Attach_ListAttachFiles(Uid, AttachIds);
            }
            else
            {
                al = ac.Attach_ListMyFiles(Uid, RowIndex, MaxRows, SortColumn, Sort);
            }
            foreach (AttachInfo ai in al)
            {
                PendingAttach += 1;
                string insertHTML = string.Empty;
                string insertThumb = string.Empty;
                string toggleInline = string.Empty;
                string deleteAttach = Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/delete12.png");
                if (mode == 1)
                {
                    deleteAttach = "<img src=\"" + deleteAttach + "\" style=\"cursor:pointer;\" onclick=\"af_delAttach(" + ai.AttachID.ToString() + "," + ai.UserID.ToString() + ");\" />";
                }
                else
                {
                    deleteAttach = "<img src=\"" + deleteAttach + "\" style=\"cursor:pointer;\" onclick=\"af_delContAttach(" + ai.AttachID.ToString() + "," + ai.UserID.ToString() + ");\" />";
                }
                if (ai.Filename.ToLowerInvariant().Contains(".jpg") | ai.Filename.ToLowerInvariant().Contains(".bmp") | ai.Filename.ToLowerInvariant().Contains(".gif") | ai.Filename.ToLowerInvariant().Contains(".png") | ai.Filename.ToLowerInvariant().Contains(".jpeg"))
                {
                    int w = 0;
                    int h = 0;
                    string fpath = null;
                    fpath = Server.MapPath(PortalSettings.HomeDirectory + "activeforums_Attach/");
                    fpath += ai.Filename;
                    byte[] bindata = null;
                    bindata = (byte[])ai.FileData;
                    if (bindata != null)
                    {
                        System.IO.MemoryStream memStream = new System.IO.MemoryStream(bindata);
                        try
                        {
                            System.Drawing.Image g = System.Drawing.Image.FromStream(memStream);
                            if (g != null)
                            {
                                w = g.Width;
                                h = g.Height;
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                    else
                    {

                        try
                        {
                            System.Drawing.Image g = System.Drawing.Image.FromFile(fpath);
                            if (g != null)
                            {
                                w = g.Width;
                                h = g.Height;
                            }
                        }
                        catch (Exception ex)
                        {

                        }

                    }

                    if (mode == 0)
                    {
                        string sInsert = string.Empty;
                        string sClose = string.Empty;
                        if (ai.ParentAttachId > 0)
                        {
                            sInsert = "<a href=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/viewer.aspx") + "?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + ai.ParentAttachId + "\" target=\"_blank\">";
                            sClose = "</a>";
                        }
                        if (ai.FileData == null)
                        {
                            string vpath = null;
                            vpath = PortalSettings.HomeDirectory + "activeforums_Attach/";
                            sInsert += "<img src=\"" + vpath + ai.Filename + "\" border=\"0\" class=\"afimg\" />";
                        }
                        else
                        {
                            sInsert += "<img src=" + Page.ResolveUrl("~/DesktopModules/ActiveForums/viewer.aspx") + "?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + ai.AttachID + " border=0 class=\"afimg\" />";
                        }

                        sInsert += sClose;
                        if (ForumInfo.AllowHTML && ForumInfo.EditorType != EditorTypes.TEXTBOX)
                        {
                            insertHTML = "<a href=\"javascript:amaf_insertHTML('" + Server.HtmlEncode(sInsert) + "');amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",0);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:InsertImage]\" /></a>";
                        }
                        else
                        {
                            if (ai.ParentAttachId > 0)
                            {
                                insertHTML = "<a href=\"javascript:amaf_insertHTML('[THUMBNAIL:" + ai.AttachID + ":" + ai.ParentAttachId + "]');amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",0);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:InsertImage]\" /></a>";
                            }
                            else
                            {
                                insertHTML = "<a href=\"javascript:amaf_insertHTML('[IMAGE:" + ai.AttachID + "]');amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",0);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_insert.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:InsertImage]\" /></a>";
                            }

                        }
                        insertThumb = "<a href=\"javascript:amaf_insertThumbnail(" + ai.AttachID + "," + ai.UserID + "," + w + "," + h + ");\"><img src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/image_thumb.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:CreateThumbnail]\" border=\"0\" /></a>";
                        if (ai.AllowDownload)
                        {
                            toggleInline = "<a href=\"javascript:amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",1);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/checkbox.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:AllowDownload]\" /></a>";
                        }
                        else
                        {
                            toggleInline = "<a href=\"javascript:amaf_toggleInline(" + ai.AttachID + "," + ai.UserID + ",1);\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/checkbox_unchecked.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:AllowDownload]\" /></a>";
                        }
                    }
                    else
                    {
                        toggleInline = "<a href=\"javascript:amaf_addAttach(" + ai.AttachID + "," + ai.UserID + ");\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/add.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:AddAttach]\" /></a>";
                    }
                }
                else
                {
                    if (mode == 1)
                    {
                        toggleInline = "<a href=\"javascript:amaf_addAttach(" + ai.AttachID + "," + ai.UserID + ");\"><img border=\"0\" src=\"" + Page.ResolveUrl("~/DesktopModules/ActiveForums/Images/add.png") + "\" style=\"cursor:pointer;\" alt=\"[RESX:AddAttach]\" /></a>";
                    }
                }
                string rClass = "afrow";
                if (i % 2 == 0)
                {
                    rClass += " afhighlight";
                }
                sOut += "<tr onmouseout=\"this.className='" + rClass + "';\" class=\"" + rClass + "\"><td>" + ai.Filename + "</td><td>" + Utilities.FormatFileSize(ai.FileSize) + "</td><td align=\"center\">" + insertThumb + "</td><td align=\"center\">" + insertHTML + "</td><td align=\"center\">" + toggleInline + "</td><td align=\"center\">" + deleteAttach + "</td></tr>";
                i += 1;
            }
            string tbl = string.Empty;
            string createThumbHD = string.Empty;
            string insertImageHD = string.Empty;
            string downloadHD = string.Empty;
            if (sOut != "")
            {

                if (mode == 0)
                {
                    createThumbHD = "[RESX:CreateThumbnail]";
                    insertImageHD = "[RESX:InsertImage]";
                    downloadHD = "[RESX:AllowDownload]";
                }
                else
                {
                    downloadHD = "[RESX:AddAttach]";
                }
                tbl = "<table cellpadding=\"0\" cellspacing=\"0\" width=\"95%\"><tr><td class=\"afattachhead\">[RESX:FileName]</td><td class=\"afattachhead\">[RESX:FileSize]</td><td class=\"afattachhead\" align=\"center\">" + createThumbHD + "</td><td class=\"afattachhead\" align=\"center\">" + insertImageHD + "</td><td class=\"afattachhead\" align=\"center\">" + downloadHD;
                tbl += "</td><td class=\"afattachhead\" align=\"center\">[RESX:Delete]</td></tr>" + sOut + "</table>";
            }
            return tbl;
        }
        private void cbAttach_Callback(object sender, Modules.ActiveForums.Controls.CallBackEventArgs e)
        {
            string attachIds = e.Parameters[1].ToString();
            switch (e.Parameters[0].ToLowerInvariant())
            {

                case "delcont":
                    {
                        if (SimulateIsNumeric.IsNumeric(e.Parameters[2]))
                        {
                            int aid = Convert.ToInt32(e.Parameters[2]);
                            int uid = -1;
                            if (SimulateIsNumeric.IsNumeric(e.Parameters[3]))
                            {
                                uid = Convert.ToInt32(e.Parameters[3]);
                            }
                            if ((uid == this.UserId && !(this.UserId == -1)) | Permissions.HasPerm(ForumInfo.Security.ModDelete, ForumUser.UserRoles) || UserInfo.IsSuperUser)
                            {
                                Data.AttachController adb = new Data.AttachController();
                                adb.Attach_Delete(aid, ContentId);
                                //ac.Attach_Delete(aid, -1, uid)
                            }

                        }
                        break;
                    }
                case "thumb":
                    {
                        if (SimulateIsNumeric.IsNumeric(e.Parameters[2]))
                        {
                            int aid = Convert.ToInt32(e.Parameters[2]);
                            Data.AttachController ac = new Data.AttachController();
                            int uid = -1;
                            if (SimulateIsNumeric.IsNumeric(e.Parameters[3]))
                            {
                                uid = Convert.ToInt32(e.Parameters[3]);
                            }
                            AttachInfo ai = ac.Attach_Get(aid, -1, uid, false);
                            if (ai != null)
                            {
                                int w = Convert.ToInt32(e.Parameters[4]);
                                int h = Convert.ToInt32(e.Parameters[5]);
                                System.IO.MemoryStream imgStream = new System.IO.MemoryStream();
                                string fpath = string.Empty;
                                int fileSize = 0;
                                string tmpFilename = string.Empty;
                                if (ai.FileData != null)
                                {
                                    byte[] bindata = null;
                                    bindata = (byte[])ai.FileData;
                                    System.IO.MemoryStream memStream = new System.IO.MemoryStream(bindata);
                                    imgStream = (System.IO.MemoryStream)(Images.CreateImageForDB(memStream, h, w));
                                    fileSize = Convert.ToInt32(imgStream.Length);
                                    tmpFilename = "thumb_" + ai.Filename;
                                }
                                else
                                {

                                    fpath = Server.MapPath(PortalSettings.HomeDirectory + "activeforums_Attach/");
                                    //fpath &= "thumb_" & ai.Filename
                                    tmpFilename = "thumb_" + ai.Filename;
                                    string sFullFile = fpath + tmpFilename;
                                    int i = 0;

                                    while (File.Exists(sFullFile))
                                    {
                                        i += 1;
                                        tmpFilename = i.ToString().PadLeft(3, '0') + "_thumb_" + ai.Filename;
                                        sFullFile = fpath + tmpFilename;
                                    }
                                    File.Copy(fpath + ai.Filename, sFullFile);
                                    Images.CreateImage(sFullFile, h, w);
                                    fileSize = (int)new FileInfo(sFullFile).Length;
                                }
                                AttachInfo aiThumb = new AttachInfo();
                                aiThumb.ContentId = -1;
                                aiThumb.UserID = ai.UserID;
                                aiThumb.Filename = tmpFilename;
                                aiThumb.ContentType = "image/x-png";
                                aiThumb.FileSize = fileSize;
                                if (ForumInfo.AttachStore == AttachStores.DATABASE)
                                {
                                    aiThumb.FileData = imgStream.ToArray();
                                    //File.Delete(fpath & "thumb_" & ai.Filename)
                                }
                                aiThumb.ParentAttachId = aid;
                                int thumbId = ac.Attach_Save(aiThumb);
                                attachIds += thumbId.ToString() + ";";
                                BindMyFiles();
                                if (Convert.ToBoolean(e.Parameters[4]))
                                {
                                    string strHost = DotNetNuke.Common.Globals.AddHTTP(DotNetNuke.Common.Globals.GetDomainName(Request)) + "/";
                                    string s = "<script type=\"text/javascript\">";
                                    string sInsert = string.Empty;
                                    if (ForumInfo.AllowHTML && ForumInfo.EditorType != EditorTypes.TEXTBOX)
                                    {
                                        sInsert = "<a href=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + aid + "\" target=\"_blank\"><img src=" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + thumbId + " border=0 /></a>";
                                    }
                                    else
                                    {
                                        sInsert = "[THUMBNAIL:" + thumbId.ToString() + ":" + aid + "]";
                                    }

                                    s += "amaf_insertHTML('" + sInsert + "');";
                                    s += "</script>";
                                    LiteralControl litScript = new LiteralControl();
                                    litScript.Text = s;
                                    plhAttach.Controls.Add(litScript);

                                }

                            }

                        }
                        break;
                    }
                case "inline":
                    {
                        if (SimulateIsNumeric.IsNumeric(e.Parameters[2]))
                        {
                            int aid = Convert.ToInt32(e.Parameters[2]);
                            Data.AttachController ac = new Data.AttachController();
                            int uid = -1;
                            if (SimulateIsNumeric.IsNumeric(e.Parameters[3]))
                            {
                                uid = Convert.ToInt32(e.Parameters[3]);
                            }
                            AttachInfo ai = ac.Attach_Get(aid, -1, uid, false);
                            if (ai != null)
                            {
                                int opt = Convert.ToInt32(e.Parameters[4]);
                                if (opt == 0)
                                {
                                    ai.DisplayInline = true;
                                    ai.AllowDownload = false;
                                }
                                else
                                {
                                    if (ai.AllowDownload)
                                    {
                                        ai.DisplayInline = true;
                                        ai.AllowDownload = false;
                                    }
                                    else
                                    {
                                        ai.DisplayInline = false;
                                        ai.AllowDownload = true;
                                    }
                                }

                                ac.Attach_Save(ai);
                            }
                        }
                        break;
                    }
            }

            BindAttach(attachIds);
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
            plhAttach.RenderControl(htmlWriter);
            string html = stringWriter.GetStringBuilder().ToString();
            html = Utilities.LocalizeControl(html);
            LiteralControl lit = new LiteralControl();
            lit.Text = html;
            lit.RenderControl(e.Output);
        }
        private void cbMyFiles_Callback(object sender, Modules.ActiveForums.Controls.CallBackEventArgs e)
        {
            string attachIds = e.Parameters[1].ToString();
            switch (e.Parameters[0].ToLowerInvariant())
            {

                case "del":
                    if (SimulateIsNumeric.IsNumeric(e.Parameters[2]))
                    {
                        int aid = Convert.ToInt32(e.Parameters[2]);
                        Data.AttachController ac = new Data.AttachController();
                        int uid = -1;
                        if (SimulateIsNumeric.IsNumeric(e.Parameters[3]))
                        {
                            uid = Convert.ToInt32(e.Parameters[3]);
                        }
                        if ((uid == this.UserId && !(this.UserId == -1)) | Permissions.HasPerm(ForumInfo.Security.ModDelete, ForumUser.UserRoles) || UserInfo.IsSuperUser)
                        {
                            ac.Attach_Delete(aid, -1, uid);
                        }

                    }

                    break;
            }
            PendingAttach = 0;
            plhMyFiles.Controls.Clear();
            BindMyFiles();
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

            plhMyFiles.RenderControl(htmlWriter);
            string html = stringWriter.GetStringBuilder().ToString();
            html = Utilities.LocalizeControl(html);
            LiteralControl lit = new LiteralControl();
            lit.Text = html;
            lit.RenderControl(e.Output);
        }
        private void cbAttach_Callback(object sender, Modules.ActiveForums.Controls.CallBackEventArgs e)
        {
            string attachIds = e.Parameters[1].ToString();

            switch (e.Parameters[0].ToLowerInvariant())
            {
            case "delcont":
            {
                if (SimulateIsNumeric.IsNumeric(e.Parameters[2]))
                {
                    int aid = Convert.ToInt32(e.Parameters[2]);
                    int uid = -1;
                    if (SimulateIsNumeric.IsNumeric(e.Parameters[3]))
                    {
                        uid = Convert.ToInt32(e.Parameters[3]);
                    }
                    if ((uid == this.UserId && !(this.UserId == -1)) | Permissions.HasPerm(ForumInfo.Security.ModDelete, ForumUser.UserRoles) || UserInfo.IsSuperUser)
                    {
                        Data.AttachController adb = new Data.AttachController();
                        adb.Attach_Delete(aid, ContentId);
                        //ac.Attach_Delete(aid, -1, uid)
                    }
                }
                break;
            }

            case "thumb":
            {
                if (SimulateIsNumeric.IsNumeric(e.Parameters[2]))
                {
                    int aid = Convert.ToInt32(e.Parameters[2]);
                    Data.AttachController ac = new Data.AttachController();
                    int uid = -1;
                    if (SimulateIsNumeric.IsNumeric(e.Parameters[3]))
                    {
                        uid = Convert.ToInt32(e.Parameters[3]);
                    }
                    AttachInfo ai = ac.Attach_Get(aid, -1, uid, false);
                    if (ai != null)
                    {
                        int w = Convert.ToInt32(e.Parameters[4]);
                        int h = Convert.ToInt32(e.Parameters[5]);
                        System.IO.MemoryStream imgStream = new System.IO.MemoryStream();
                        string fpath       = string.Empty;
                        int    fileSize    = 0;
                        string tmpFilename = string.Empty;
                        if (ai.FileData != null)
                        {
                            byte[] bindata = null;
                            bindata = (byte[])ai.FileData;
                            System.IO.MemoryStream memStream = new System.IO.MemoryStream(bindata);
                            imgStream   = (System.IO.MemoryStream)(Images.CreateImageForDB(memStream, h, w));
                            fileSize    = Convert.ToInt32(imgStream.Length);
                            tmpFilename = "thumb_" + ai.Filename;
                        }
                        else
                        {
                            fpath = Server.MapPath(PortalSettings.HomeDirectory + "activeforums_Attach/");
                            //fpath &= "thumb_" & ai.Filename
                            tmpFilename = "thumb_" + ai.Filename;
                            string sFullFile = fpath + tmpFilename;
                            int    i         = 0;

                            while (File.Exists(sFullFile))
                            {
                                i          += 1;
                                tmpFilename = i.ToString().PadLeft(3, '0') + "_thumb_" + ai.Filename;
                                sFullFile   = fpath + tmpFilename;
                            }
                            File.Copy(fpath + ai.Filename, sFullFile);
                            Images.CreateImage(sFullFile, h, w);
                            fileSize = (int)new FileInfo(sFullFile).Length;
                        }
                        AttachInfo aiThumb = new AttachInfo();
                        aiThumb.ContentId   = -1;
                        aiThumb.UserID      = ai.UserID;
                        aiThumb.Filename    = tmpFilename;
                        aiThumb.ContentType = "image/x-png";
                        aiThumb.FileSize    = fileSize;
                        if (ForumInfo.AttachStore == AttachStores.DATABASE)
                        {
                            aiThumb.FileData = imgStream.ToArray();
                            //File.Delete(fpath & "thumb_" & ai.Filename)
                        }
                        aiThumb.ParentAttachId = aid;
                        int thumbId = ac.Attach_Save(aiThumb);
                        attachIds += thumbId.ToString() + ";";
                        BindMyFiles();
                        if (Convert.ToBoolean(e.Parameters[4]))
                        {
                            string strHost = DotNetNuke.Common.Globals.AddHTTP(DotNetNuke.Common.Globals.GetDomainName(Request)) + "/";
                            string s       = "<script type=\"text/javascript\">";
                            string sInsert = string.Empty;
                            if (ForumInfo.AllowHTML && ForumInfo.EditorType != EditorTypes.TEXTBOX)
                            {
                                sInsert = "<a href=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + aid + "\" target=\"_blank\"><img src=" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + thumbId + " border=0 /></a>";
                            }
                            else
                            {
                                sInsert = "[THUMBNAIL:" + thumbId.ToString() + ":" + aid + "]";
                            }

                            s += "amaf_insertHTML('" + sInsert + "');";
                            s += "</script>";
                            LiteralControl litScript = new LiteralControl();
                            litScript.Text = s;
                            plhAttach.Controls.Add(litScript);
                        }
                    }
                }
                break;
            }

            case "inline":
            {
                if (SimulateIsNumeric.IsNumeric(e.Parameters[2]))
                {
                    int aid = Convert.ToInt32(e.Parameters[2]);
                    Data.AttachController ac = new Data.AttachController();
                    int uid = -1;
                    if (SimulateIsNumeric.IsNumeric(e.Parameters[3]))
                    {
                        uid = Convert.ToInt32(e.Parameters[3]);
                    }
                    AttachInfo ai = ac.Attach_Get(aid, -1, uid, false);
                    if (ai != null)
                    {
                        int opt = Convert.ToInt32(e.Parameters[4]);
                        if (opt == 0)
                        {
                            ai.DisplayInline = true;
                            ai.AllowDownload = false;
                        }
                        else
                        {
                            if (ai.AllowDownload)
                            {
                                ai.DisplayInline = true;
                                ai.AllowDownload = false;
                            }
                            else
                            {
                                ai.DisplayInline = false;
                                ai.AllowDownload = true;
                            }
                        }


                        ac.Attach_Save(ai);
                    }
                }
                break;
            }
            }

            BindAttach(attachIds);
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            HtmlTextWriter         htmlWriter   = new HtmlTextWriter(stringWriter);

            plhAttach.RenderControl(htmlWriter);
            string html = stringWriter.GetStringBuilder().ToString();

            html = Utilities.LocalizeControl(html);
            LiteralControl lit = new LiteralControl();

            lit.Text = html;
            lit.RenderControl(e.Output);
        }
Beispiel #21
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var attachmentId = Utilities.SafeConvertInt(Request.Params["AttachmentID"], -1);// Used for new attachments where the attachment is the actual file link (shouldn't appear in posts)
            var attachFileId = Utilities.SafeConvertInt(Request.Params["AttachID"], -1); // Used for legacy attachments where the attachid was actually the file id. (appears in posts)
            var portalId = Utilities.SafeConvertInt(Request.Params["PortalID"], -1);
            var moduleId = Utilities.SafeConvertInt(Request.Params["ModuleID"], -1);

            if (Page.IsPostBack || (attachmentId < 0 && attachFileId < 0) || portalId < 0 || moduleId < 0)
            {
                Response.StatusCode = 400;
                Response.Write("Invalid Request");
                Response.End();
                return;
            }

            // Get the attachment including the "Can Read" permission for the associated content id.
            var attachment = new Data.AttachController().Get(attachmentId, attachFileId, true);

            // Make sure the attachment exists
            if (attachment == null)
            {
                Response.StatusCode = 404;
                Response.Write("Not Found");
                Response.End();
                return;
            }

            // Make sure the user has read access
            var u = new UserController().GetUser(portalId, moduleId);
            if (u == null || !Permissions.HasAccess(attachment.CanRead, u.UserRoles))
            {
                Response.StatusCode = 401;
                Response.Write("Unauthorized");
                Response.End();
                return;
            }

            // Get the filename with the unique identifier prefix removed.
            var filename = Regex.Replace(attachment.FileName.TextOrEmpty(), @"__\d+__\d+__", string.Empty);

            // Some legacy attachments may still be stored in the DB.
            if (attachment.FileData != null)
            {
                Response.ContentType = attachment.ContentType;
                
                if (attachmentId > 0)
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.HtmlEncode(filename));
                else // Handle legacy inline attachments a bit differently
                    Response.AddHeader("Content-Disposition", "filename=" + Server.HtmlEncode(filename));
                
                Response.BinaryWrite(attachment.FileData);
                Response.End();
                return;
            }

            var fileManager = FileManager.Instance;

            string filePath = null;

            // If there is a file id, access the file using the file manager
            if (attachment.FileId.HasValue && attachment.FileId.Value > 0)
            {
                var file = fileManager.GetFile(attachment.FileId.Value);
                if (file != null)
                {
                    filePath = file.PhysicalPath;
                }
            }
                // Otherwise check the attachments directory (current and legacy)
            else
            {
                filePath = Server.MapPath(PortalSettings.HomeDirectory + "activeforums_Attach/") + attachment.FileName;

                // This is another check to support legacy attachments.
                if (!File.Exists(filePath))
                {
                    filePath = Server.MapPath(PortalSettings.HomeDirectory + "NTForums_Attach/") + attachment.FileName;
                }
            }

            // At this point, we should have a valid file path
            if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
            {
                Response.StatusCode = 404;
                Response.Write("Not Found");
                Response.End();
                return;
            }

            var length = attachment.FileSize;
            if (length <= 0)
                length = new System.IO.FileInfo(filePath).Length;

            Response.Clear();
            Response.ContentType = attachment.ContentType;

            if(attachmentId > 0)
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.HtmlEncode(filename));
            else // Handle legacy inline attachments a bit differently
                Response.AddHeader("Content-Disposition", "filename=" + Server.HtmlEncode(filename));

            Response.AddHeader("Content-Length", length.ToString());
            Response.WriteFile(filePath);
            Response.Flush();
            Response.Close();
            Response.End();
        }