public void ProcessRequest(HttpContext context)
        {
            try
            {
                // Get arguments passed via query string
                UploaderHelper args    = new UploaderHelper(context);
                String         appPath = context.Server.MapPath("~/");
                DirectoryHelper.EnsureDiskPath(args.FilePath, appPath);

                if (args.Canceled)
                {
                    // Remove file from server if canceled
                    args.CleanTempFile();
                }
                else
                {
                    args.ProcessFile();
                    if (args.Complete)
                    {
                        if (args.IsForumAttachmentUpload)
                        {
                            HandleForumUpload(args, context);
                        }
                        args.CleanTempFile();
                    }
                }
            }
            catch (Exception ex)
            {
                // Send error message
                context.Response.Write(String.Format(@"0|{0}", HTMLHelper.EnsureLineEnding(ex.Message, " ")));
                context.Response.Flush();
            }
        }
    /// <summary>
    /// Loads data of specific EventLog from DB.
    /// </summary>
    protected void LoadData()
    {
        EventLogInfo ev = EventLogProvider.GetEventLogInfo(eventId);

        //Set edited object
        EditedObject = ev;

        if (ev != null)
        {
            string eventType = ValidationHelper.GetString(ev.GetValue("EventType"), string.Empty);

            // Rewrite event type text.
            lblEventTypeValue.Text = EventLogHelper.GetEventTypeText(eventType);
            lblEventIDValue.Text   = ValidationHelper.GetString(ev.GetValue("EventID"), string.Empty);
            lblEventTimeValue.Text = ValidationHelper.GetString(ev.GetValue("EventTime"), string.Empty);
            lblSourceValue.Text    = HTMLHelper.HTMLEncode(ValidationHelper.GetString(ev.GetValue("Source"), string.Empty));
            lblEventCodeValue.Text = HTMLHelper.HTMLEncode(ValidationHelper.GetString(ev.GetValue("EventCode"), string.Empty));

            lblUserIDValue.Text = ValidationHelper.GetString(ev.GetValue("UserID"), string.Empty);
            plcUserID.Visible   = (lblUserIDValue.Text != string.Empty);

            lblUserNameValue.Text = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ValidationHelper.GetString(ev.GetValue("UserName"), string.Empty)));
            plcUserName.Visible   = (lblUserNameValue.Text != string.Empty);

            lblIPAddressValue.Text = ValidationHelper.GetString(ev.GetValue("IPAddress"), string.Empty);

            lblNodeIDValue.Text = ValidationHelper.GetString(ev.GetValue("NodeID"), string.Empty);
            plcNodeID.Visible   = (lblNodeIDValue.Text != string.Empty);

            lblNodeNameValue.Text = HTMLHelper.HTMLEncode(ValidationHelper.GetString(ev.GetValue("DocumentName"), string.Empty));
            plcNodeName.Visible   = (lblNodeNameValue.Text != string.Empty);

            string description = HTMLHelper.StripTags(ValidationHelper.GetString(ev.GetValue("EventDescription"), string.Empty).Replace("<br />", "\r\n").Replace("<br/>", "\r\n"));
            lblEventDescriptionValue.Text = HTMLHelper.EnsureLineEnding(HTMLHelper.HTMLEncode(description), "<br />");

            if (!DataHelper.IsEmpty(ev.GetValue("SiteID")))
            {
                SiteInfo si = SiteInfoProvider.GetSiteInfo(Convert.ToInt32(ev.GetValue("SiteID")));
                if (si != null)
                {
                    lblSiteNameValue.Text = HTMLHelper.HTMLEncode(si.DisplayName);
                }
            }
            else
            {
                plcSite.Visible = false;
            }

            lblMachineNameValue.Text = HTMLHelper.HTMLEncode(ValidationHelper.GetString(ev.GetValue("EventMachineName"), string.Empty));
            lblEventUrlValue.Text    = HTMLHelper.HTMLEncode(ValidationHelper.GetString(ev.GetValue("EventUrl"), string.Empty));
            lblUrlReferrerValue.Text = HTMLHelper.HTMLEncode(ValidationHelper.GetString(ev.GetValue("EventUrlReferrer"), string.Empty));
            lblUserAgentValue.Text   = HTMLHelper.HTMLEncode(ValidationHelper.GetString(ev.GetValue("EventUserAgent"), string.Empty));
        }
    }
    public void LoadData()
    {
        if (node != null)
        {
            string layoutText = String.Empty;

            // get template info
            pti = PageTemplateInfoProvider.GetPageTemplateInfo(node.GetUsedPageTemplateId());
            if ((pti == null) && (DocumentContext.CurrentPageInfo != null) && (DocumentContext.CurrentPageInfo.UsedPageTemplateInfo != null))
            {
                pti = DocumentContext.CurrentPageInfo.UsedPageTemplateInfo;
            }

            if (pti != null)
            {
                PageTemplateLayoutTypeEnum type = PageTemplateLayoutTypeEnum.PageTemplateLayout;
                // Try get device layout
                object layoutObject = PageTemplateDeviceLayoutInfoProvider.GetLayoutObject(pti, DeviceContext.CurrentDeviceProfile, out type);
                layoutText = pti.PageTemplateLayout;

                // Set layout text with dependence on current layout type
                switch (type)
                {
                // Shared layouts
                case PageTemplateLayoutTypeEnum.SharedLayout:
                case PageTemplateLayoutTypeEnum.DeviceSharedLayout:
                case PageTemplateLayoutTypeEnum.SharedLayoutMapped:
                    layoutText = (layoutObject as LayoutInfo).LayoutCode;
                    break;

                // Custom device layout
                case PageTemplateLayoutTypeEnum.DeviceLayout:
                    layoutText = (layoutObject as PageTemplateDeviceLayoutInfo).LayoutCode;
                    break;
                }
            }
            ltlLayoutCode.Text = HTMLHelper.EnsureLineEnding(HTMLHelper.HighlightHTML(layoutText), "<br />");
            ltlLayoutCode.Text = RegexHelper.GetRegex("[ ](?![^<>]*>)").Replace(ltlLayoutCode.Text, "&nbsp;");

            // Load node data
            if (!RequestHelper.IsPostBack())
            {
                txtBodyCss.Text   = node.NodeBodyElementAttributes;
                txtDocType.Text   = node.NodeDocType;
                txtHeadTags.Value = node.NodeHeadTags;
            }
        }

        lblAfterDocType.Text  = HighlightHTML("<html>") + "<br />" + AddSpaces(1) + HighlightHTML("<head>");
        lblAfterHeadTags.Text = AddSpaces(1) + HighlightHTML("</head>");
        lblAfterLayout.Text   = AddSpaces(1) + HighlightHTML("</body>") + "<br />" + HighlightHTML("</html>");
        lblBodyEnd.Text       = HighlightHTML(">");
        lblBodyStart.Text     = AddSpaces(1) + HighlightHTML("<body " + HttpUtility.HtmlDecode(mBody));
    }
Exemple #4
0
    /// <summary>
    /// Loads data of specific EventLog from DB.
    /// </summary>
    protected void LoadData()
    {
        EventLogInfo ev = EventInfo;

        //Set edited object
        EditedObject = ev;

        if (ev != null)
        {
            // Rewrite event type text.
            lblEventTypeValue.Text = EventLogHelper.GetEventTypeText(ev.EventType);
            lblEventIDValue.Text   = ev.EventID.ToString();
            lblEventTimeValue.Text = ev.EventTime.ToString();
            lblSourceValue.Text    = HTMLHelper.HTMLEncode(ev.Source);
            lblEventCodeValue.Text = HTMLHelper.HTMLEncode(ev.EventCode);

            lblUserIDValue.Text = ev.UserID.ToString();
            plcUserID.Visible   = (ev.UserID > 0);

            lblUserNameValue.Text = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ev.UserName));
            plcUserName.Visible   = !string.IsNullOrEmpty(lblUserNameValue.Text);

            lblIPAddressValue.Text = ev.IPAddress;

            lblNodeIDValue.Text = ev.NodeID.ToString();
            plcNodeID.Visible   = (ev.NodeID > 0);

            lblNodeNameValue.Text = HTMLHelper.HTMLEncode(ev.DocumentName);
            plcNodeName.Visible   = !string.IsNullOrEmpty(lblNodeNameValue.Text);

            string description = HTMLHelper.StripTags(ev.EventDescription.Replace("<br />", "\r\n").Replace("<br/>", "\r\n"));
            lblEventDescriptionValue.Text = HTMLHelper.EnsureLineEnding(HTMLHelper.HTMLEncode(description), "<br />");

            if (ev.SiteID > 0)
            {
                SiteInfo si = SiteInfoProvider.GetSiteInfo(ev.SiteID);
                if (si != null)
                {
                    lblSiteNameValue.Text = HTMLHelper.HTMLEncode(si.DisplayName);
                }
            }
            else
            {
                plcSite.Visible = false;
            }

            lblMachineNameValue.Text = HTMLHelper.HTMLEncode(ev.EventMachineName);
            lblEventUrlValue.Text    = HTMLHelper.HTMLEncode(ev.EventUrl);
            lblUrlReferrerValue.Text = HTMLHelper.HTMLEncode(ev.EventUrlReferrer);
            lblUserAgentValue.Text   = HTMLHelper.HTMLEncode(ev.EventUserAgent);
        }
    }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                // Get arguments passed via query string
                UploaderHelper args    = new UploaderHelper(context);
                String         appPath = context.Server.MapPath("~/");
                DirectoryHelper.EnsureDiskPath(args.FilePath, appPath);

                if (args.Canceled)
                {
                    // Remove file from server if canceled
                    args.CleanTempFile();
                }
                else
                {
                    args.ProcessFile();
                    if (args.Complete)
                    {
                        switch (args.SourceType)
                        {
                        case MediaSourceEnum.Attachment:
                        case MediaSourceEnum.DocumentAttachments:
                            HandleAttachmentUpload(args, context);
                            break;

                        case MediaSourceEnum.Content:
                            HandleContentUpload(args, context);
                            break;

                        case MediaSourceEnum.PhysicalFile:
                            HandlePhysicalFilesUpload(args, context);
                            break;

                        case MediaSourceEnum.MetaFile:
                            HandleMetafileUpload(args, context);
                            break;
                        }

                        args.CleanTempFile();
                    }
                }
            }
            catch (Exception ex)
            {
                // Send error message
                context.Response.Write(String.Format(@"0|{0}", HTMLHelper.EnsureLineEnding(ex.Message, " ")));
                context.Response.Flush();
            }
        }
    /// <summary>
    /// Preview button click handler.
    /// </summary>
    protected void btnPreview_Click(object sender, EventArgs e)
    {
        // If external preview is enabled fire OnPreview event
        if (UseExternalPreview)
        {
            #region "Forum properties"

            // Get forum post info with dependence on current state
            ForumPostInfo fp = ForumContext.CurrentState == ForumStateEnum.EditPost ? ForumContext.CurrentPost : new ForumPostInfo();

            // Post forum
            fp.PostForumID = ForumContext.CurrentForum.ForumID;
            // Post time
            fp.PostTime = DateTime.Now;
            // Post subject
            fp.PostSubject = txtSubject.Text;
            // Post user email
            fp.PostUserMail = txtEmail.Text;
            // Post signature
            fp.PostUserSignature = txtSignature.Text;

            // Post user id
            if (!MembershipContext.AuthenticatedUser.IsPublic())
            {
                fp.PostUserID = MembershipContext.AuthenticatedUser.UserID;
            }

            // Post user name
            if (ForumContext.CurrentForum.ForumAllowChangeName || MembershipContext.AuthenticatedUser.IsPublic() || (ForumContext.UserIsModerator(ForumContext.CurrentForum.ForumID, ForumContext.CommunityGroupID)))
            {
                fp.PostUserName = TextHelper.LimitLength(txtUserName.Text, POST_USERNAME_LENGTH, "");
            }
            else
            {
                fp.PostUserName = UserName;
            }

            // Post parent id -> reply to
            if (ForumContext.CurrentReplyThread != null)
            {
                fp.PostParentID = ForumContext.CurrentReplyThread.PostId;
            }

            // Get post text from HTML editor if is enabled
            fp.PostText = ForumContext.CurrentForum.ForumHTMLEditor ? htmlTemplateBody.ResolvedValue : ucBBEditor.Text;

            #endregion


            if (OnPreview != null)
            {
                OnPreview(fp, null);
            }
        }
        else
        {
            pnlReplyPost.Visible   = true;
            lblSubjectPreview.Text = txtSubject.Text;

            // Get forum text from HTML editor or text area
            if (ForumContext.CurrentForum.ForumHTMLEditor)
            {
                lblTextPreview.Text = htmlTemplateBody.ResolvedValue;
            }
            else
            {
                lblTextPreview.Text = HTMLHelper.EnsureLineEnding(HTMLHelper.HTMLEncode(ucBBEditor.Text), "<br />");
            }
        }
    }
Exemple #7
0
    /// <summary>
    /// Provides operations necessary to create and store new library file.
    /// </summary>
    private void HandleLibrariesUpload()
    {
        // Get related library info
        if (LibraryInfo != null)
        {
            MediaFileInfo mediaFile = null;

            // Get the site name
            SiteInfo si       = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID);
            string   siteName = (si != null) ? si.SiteName : SiteContext.CurrentSiteName;

            string message = string.Empty;
            try
            {
                // Check the allowed extensions
                CheckAllowedExtensions();

                if (MediaFileID > 0)
                {
                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileModify"))
                    {
                        throw new Exception(GetString("media.security.nofilemodify"));
                    }

                    #endregion


                    mediaFile = MediaFileInfoProvider.GetMediaFileInfo(MediaFileID);
                    if (mediaFile != null)
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mediaFile);

                        if (IsMediaThumbnail)
                        {
                            string newFileExt = Path.GetExtension(ucFileUpload.FileName).TrimStart('.');
                            if ((ImageHelper.IsImage(newFileExt)) && (newFileExt.ToLowerCSafe() != "ico") &&
                                (newFileExt.ToLowerCSafe() != "wmf"))
                            {
                                // Update or creation of Media File update
                                string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(siteName);

                                if (!String.IsNullOrEmpty(previewSuffix))
                                {
                                    string previewExtension = Path.GetExtension(ucFileUpload.PostedFile.FileName);
                                    string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, previewExtension, siteName, previewSuffix));
                                    string previewFolder    = DirectoryHelper.CombinePath(Path.EnsureSlashes(LibraryFolderPath.TrimEnd('/')), MediaLibraryHelper.GetMediaFileHiddenFolder(siteName));

                                    byte[] previewFileBinary = new byte[ucFileUpload.PostedFile.ContentLength];
                                    ucFileUpload.PostedFile.InputStream.Read(previewFileBinary, 0, ucFileUpload.PostedFile.ContentLength);

                                    // Delete current preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreview(siteName, mediaFile.FileLibraryID, mediaFile.FilePath);

                                    // Save preview file
                                    MediaFileInfoProvider.SaveFileToDisk(siteName, LibraryInfo.LibraryFolder, previewFolder, previewName, previewExtension, mediaFile.FileGUID, previewFileBinary, false, false);

                                    // Log synchronization task
                                    SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                                }

                                // Drop the cache dependencies
                                CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(mediaFile, true));
                            }
                            else
                            {
                                message = GetString("media.file.onlyimgthumb");
                            }
                        }
                        else
                        {
                            // Get folder path
                            string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(LibraryInfo.LibraryID), mediaFile.FilePath));

                            // If file system permissions are sufficient for file update
                            if (DirectoryHelper.CheckPermissions(path, false, true, true, true))
                            {
                                // Delete existing media file
                                MediaFileInfoProvider.DeleteMediaFile(LibraryInfo.LibrarySiteID, LibraryInfo.LibraryID, mediaFile.FilePath, true);

                                // Update media file preview
                                if (MediaLibraryHelper.HasPreview(siteName, LibraryInfo.LibraryID, mediaFile.FilePath))
                                {
                                    // Get new unique file name
                                    string newName = URLHelper.GetSafeFileName(ucFileUpload.PostedFile.FileName, siteName);

                                    // Get new file path
                                    string newPath = DirectoryHelper.CombinePath(path, newName);
                                    newPath = MediaLibraryHelper.EnsureUniqueFileName(newPath);
                                    newName = Path.GetFileName(newPath);

                                    // Rename preview
                                    MediaLibraryHelper.MoveMediaFilePreview(mediaFile, newName);

                                    // Delete preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mediaFile);
                                }

                                // Receive media info on newly posted file
                                mediaFile = GetUpdatedFile(mediaFile);

                                // Save media file information
                                MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                            }
                            else
                            {
                                // Set error message
                                message = String.Format(GetString("media.accessdeniedtopath"), path);
                            }
                        }
                    }
                }
                else
                {
                    #region "Check permissions"

                    // Creation of new media file
                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileCreate"))
                    {
                        throw new Exception(GetString("media.security.nofilecreate"));
                    }

                    #endregion


                    // No file for upload specified
                    if (!ucFileUpload.HasFile)
                    {
                        throw new Exception(GetString("media.newfile.errorempty"));
                    }

                    // Create new media file record
                    mediaFile = new MediaFileInfo(ucFileUpload.PostedFile, LibraryID, LibraryFolderPath, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, LibraryInfo.LibrarySiteID);

                    mediaFile.FileDescription = "";

                    // Save the new file info
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                }
            }
            catch (Exception ex)
            {
                // Creation of new media file failed
                message = ex.Message;
            }
            finally
            {
                // Create media file info string
                string mediaInfo = "";
                if ((mediaFile != null) && (mediaFile.FileID > 0) && (IncludeNewItemInfo))
                {
                    mediaInfo = mediaFile.FileID + "|" + LibraryFolderPath.Replace('\\', '>').Replace("'", "\\'");
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                if (RaiseOnClick)
                {
                    ScriptHelper.RegisterStartupScript(Page, typeof(Page), "UploaderOnClick", ScriptHelper.GetScript("if (parent.UploaderOnClick) { parent.UploaderOnClick('" + MediaFileName.Replace(" ", "").Replace(".", "").Replace("-", "") + "'); }"));
                }

                string script = String.Format(@"
if (typeof(parent.DFU) !== 'undefined') {{ 
    parent.DFU.OnUploadCompleted('{0}'); 
}} 
if ((window.parent != null) && (/parentelemid={1}/i.test(window.location.href)) && (window.parent.InitRefresh_{1} != null)){{
    window.parent.InitRefresh_{1}({2}, false, '{3}'{4});
}}", QueryHelper.GetString("containerid", ""), ParentElemID, ScriptHelper.GetString(message.Trim()), mediaInfo, (InsertMode ? ", 'insert'" : ", 'update'"));

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(Page, typeof(Page), "RefreshParrent", ScriptHelper.GetScript(script));
            }
        }
    }
Exemple #8
0
    /// <summary>
    /// Provides operations necessary to create and store new library file.
    /// </summary>
    private void HandleLibrariesUpload()
    {
        // Get related library info
        if (LibraryInfo != null)
        {
            MediaFileInfo mediaFile = null;

            // Get the site name
            string   siteName = CMSContext.CurrentSiteName;
            SiteInfo si       = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID);
            if (si != null)
            {
                siteName = si.SiteName;
            }

            string message = string.Empty;
            try
            {
                // Check the allowed extensions
                CheckAllowedExtensions();

                if (MediaFileID > 0)
                {
                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileModify"))
                    {
                        throw new Exception(GetString("media.security.nofilemodify"));
                    }

                    #endregion

                    mediaFile = MediaFileInfoProvider.GetMediaFileInfo(MediaFileID);
                    if (mediaFile != null)
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mediaFile);

                        if (IsMediaThumbnail)
                        {
                            string newFileExt = Path.GetExtension(ucFileUpload.FileName).TrimStart('.');
                            if ((ImageHelper.IsImage(newFileExt)) && (newFileExt.ToLower() != "ico") &&
                                (newFileExt.ToLower() != "wmf"))
                            {
                                // Update or creation of Media File update
                                string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(siteName);

                                if (!String.IsNullOrEmpty(previewSuffix))
                                {
                                    string previewExtension = Path.GetExtension(ucFileUpload.PostedFile.FileName);
                                    string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, previewExtension, siteName, previewSuffix));
                                    string previewFolder    = DirectoryHelper.CombinePath(MediaLibraryHelper.EnsurePath(LibraryFolderPath.TrimEnd('/')), MediaLibraryHelper.GetMediaFileHiddenFolder(siteName));

                                    byte[] previewFileBinary = new byte[ucFileUpload.PostedFile.ContentLength];
                                    ucFileUpload.PostedFile.InputStream.Read(previewFileBinary, 0, ucFileUpload.PostedFile.ContentLength);

                                    // Delete current preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreview(siteName, mediaFile.FileLibraryID, mediaFile.FilePath, false);

                                    // Save preview file
                                    MediaFileInfoProvider.SaveFileToDisk(siteName, LibraryInfo.LibraryFolder, previewFolder, previewName, previewExtension, mediaFile.FileGUID, previewFileBinary, false, false);

                                    // Log synchronization task
                                    SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                                }

                                // Drop the cache dependencies
                                CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(mediaFile, true));
                            }
                            else
                            {
                                message = GetString("media.file.onlyimgthumb");
                            }
                        }
                        else
                        {
                            // Delete existing media file
                            MediaFileInfoProvider.DeleteMediaFile(LibraryInfo.LibrarySiteID, LibraryInfo.LibraryID, mediaFile.FilePath, true, false);

                            // Update media file preview
                            if (MediaLibraryHelper.HasPreview(siteName, LibraryInfo.LibraryID, mediaFile.FilePath))
                            {
                                // Get new file path
                                string newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(mediaFile.FilePath).TrimEnd('/'), ucFileUpload.PostedFile.FileName);
                                newPath = MediaLibraryHelper.EnsureUniqueFileName(newPath);

                                // Get new unique file name
                                string newName = Path.GetFileName(newPath);

                                // Rename preview
                                MediaLibraryHelper.MoveMediaFilePreview(mediaFile, newName);

                                // Delete preview thumbnails
                                MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mediaFile);
                            }

                            // Receive media info on newly posted file
                            mediaFile = GetUpdatedFile(mediaFile.Generalized.DataClass);

                            MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                        }
                    }
                }
                else
                {
                    // Creation of new media file

                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileCreate"))
                    {
                        throw new Exception(GetString("media.security.nofilecreate"));
                    }

                    #endregion

                    // No file for upload specified
                    if (!ucFileUpload.HasFile)
                    {
                        throw new Exception(GetString("media.newfile.errorempty"));
                    }

                    // Create new media file record
                    mediaFile = new MediaFileInfo(ucFileUpload.PostedFile, LibraryID, LibraryFolderPath, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, LibraryInfo.LibrarySiteID);

                    mediaFile.FileDescription = "";

                    // Save the new file info
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                }
            }
            catch (Exception ex)
            {
                // Creation of new media file failed
                message = ex.Message;
            }
            finally
            {
                // Create media file info string
                string mediaInfo = "";
                if ((mediaFile != null) && (mediaFile.FileID > 0) && (IncludeNewItemInfo))
                {
                    mediaInfo = mediaFile.FileID + "|" + LibraryFolderPath.Replace('\\', '>').Replace("'", "\\'");
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(this.Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false" + ((mediaInfo != "") ? ", '" + mediaInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}window.close();"));
            }
        }
    }
    /// <summary>
    /// Provides operations necessary to create and store new content file.
    /// </summary>
    private void HandleContentUpload()
    {
        string message            = string.Empty;
        bool   newDocumentCreated = false;

        try
        {
            if (NodeParentNodeID == 0)
            {
                throw new Exception(GetString("dialogs.document.parentmissing"));
            }

            // Check license limitations
            if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert))
            {
                throw new Exception(GetString("cmsdesk.documentslicenselimits"));
            }

            // Check if class exists
            DataClassInfo ci = DataClassInfoProvider.GetDataClass("CMS.File");
            if (ci == null)
            {
                throw new Exception(string.Format(GetString("dialogs.newfile.classnotfound"), "CMS.File"));
            }

            #region "Check permissions"

            // Get the node
            TreeNode parentNode = TreeProvider.SelectSingleNode(NodeParentNodeID, CMSContext.PreferredCultureCode, true);
            if (parentNode != null)
            {
                if (!DataClassInfoProvider.IsChildClassAllowed(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ci.ClassID))
                {
                    throw new Exception(GetString("Content.ChildClassNotAllowed"));
                }
            }

            // Check user permissions
            if (!RaiseOnCheckPermissions("Create", this))
            {
                if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(parentNode, "CMS.File"))
                {
                    throw new Exception(string.Format(GetString("dialogs.newfile.notallowed"), NodeClassName));
                }
            }

            #endregion

            // Check the allowed extensions
            CheckAllowedExtensions();

            // Create new document
            string fileName = Path.GetFileNameWithoutExtension(ucFileUpload.FileName);
            string ext      = Path.GetExtension(ucFileUpload.FileName);

            if (IncludeExtension)
            {
                fileName += ext;
            }

            // Make sure the file name with extension respects maximum file name
            fileName = TextHelper.LimitFileNameLength(fileName, TreePathUtils.MaxNameLength);

            node = TreeNode.New("CMS.File", TreeProvider);
            node.DocumentCulture = CMSContext.PreferredCultureCode;
            node.DocumentName    = fileName;
            if (NodeGroupID > 0)
            {
                node.SetValue("NodeGroupID", NodeGroupID);
            }

            // Load default values
            FormHelper.LoadDefaultValues(node);
            node.SetValue("FileDescription", "");
            node.SetValue("FileName", fileName);
            node.SetValue("FileAttachment", Guid.Empty);

            // Set default template ID
            node.DocumentPageTemplateID = ci.ClassDefaultPageTemplateID;

            // Insert the document
            DocumentHelper.InsertDocument(node, parentNode, TreeProvider);

            newDocumentCreated = true;

            // Add the file
            DocumentHelper.AddAttachment(node, "FileAttachment", ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);

            // Create default SKU if configured
            if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))
            {
                node.CreateDefaultSKU();
            }

            // Update the document
            DocumentHelper.UpdateDocument(node, TreeProvider);

            // Get workflow info
            wi = WorkflowManager.GetNodeWorkflow(node);

            // Check if auto publish changes is allowed
            if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName))
            {
                // Automatically publish document
                WorkflowManager.AutomaticallyPublish(node, wi, null);
            }
        }
        catch (Exception ex)
        {
            // Delete the document if something failed
            if (newDocumentCreated && (node != null) && (node.DocumentID > 0))
            {
                DocumentHelper.DeleteDocument(node, TreeProvider, false, true, true);
            }

            message = ex.Message;
        }
        finally
        {
            // Create node info string
            string nodeInfo = "";
            if ((node != null) && (node.NodeID > 0) && (IncludeNewItemInfo))
            {
                nodeInfo = node.NodeID.ToString();
            }

            // Ensure message text
            message = HTMLHelper.EnsureLineEnding(message, " ");

            // Call function to refresh parent window
            string afterSaveScript = null;
            if (!string.IsNullOrEmpty(AfterSaveJavascript))
            {
                afterSaveScript = String.Format(@"
if (window.{0} != null){{
    window.{0}();
}} else if ((window.parent != null) && (window.parent.{0} != null)){{
    window.parent.{0}();
}}", AfterSaveJavascript);
            }

            afterSaveScript += String.Format(@"
if (typeof(parent.DFU) !== 'undefined') {{ 
    parent.DFU.OnUploadCompleted('{0}'); 
}} 
if ((window.parent != null) && (/parentelemid={1}/i.test(window.location.href)) && (window.parent.InitRefresh_{1} != null)){{
    window.parent.InitRefresh_{1}({2}, false, false{3}{4});
}}", QueryHelper.GetString("containerid", ""), ParentElemID, ScriptHelper.GetString(message.Trim()), ((nodeInfo != "") ? ", '" + nodeInfo + "'" : ""), (InsertMode ? ", 'insert'" : ", 'update'"));

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, ScriptHelper.GetScript(afterSaveScript));
        }
    }
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        // New attachment
        AttachmentInfo newAttachment = null;

        string message     = string.Empty;
        bool   fullRefresh = false;
        bool   refreshTree = false;

        try
        {
            // Get the existing document
            if (DocumentID != 0)
            {
                // Get document
                node = DocumentHelper.GetDocument(DocumentID, TreeProvider);
                if (node == null)
                {
                    throw new Exception("Given document doesn't exist!");
                }
            }

            #region "Check permissions"

            if (CheckPermissions)
            {
                CheckNodePermissions(node);
            }

            #endregion

            // Check the allowed extensions
            CheckAllowedExtensions();

            // Standard attachments
            if (DocumentID != 0)
            {
                // Check out the document
                if (AutoCheck)
                {
                    // Get original step Id
                    int originalStepId = node.DocumentWorkflowStepID;

                    // Get current step info
                    WorkflowStepInfo si = WorkflowManager.GetStepInfo(node);
                    if (si != null)
                    {
                        // Decide if full refresh is needed
                        bool   automaticPublish = wi.WorkflowAutoPublishChanges;
                        string stepName         = si.StepName.ToLower();
                        // Document is published or archived or uses automatic publish or step is different than original (document was updated)
                        fullRefresh = (stepName == "published") || (stepName == "archived") || (automaticPublish && (stepName != "published")) || (originalStepId != node.DocumentWorkflowStepID);
                    }

                    VersionManager.CheckOut(node, node.IsPublished, true);
                }

                // Handle field attachment
                if (fieldAttachment)
                {
                    // Extension of CMS file before saving
                    string oldExtension = node.DocumentType;

                    newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    // Update attachment field
                    DocumentHelper.UpdateDocument(node, TreeProvider);

                    // Different extension
                    if ((oldExtension != null) && !oldExtension.Equals(node.DocumentType, StringComparison.InvariantCultureIgnoreCase))
                    {
                        refreshTree = true;
                    }
                }
                // Handle grouped and unsorted attachments
                else
                {
                    // Grouped attachment
                    if (AttachmentGroupGUID != Guid.Empty)
                    {
                        newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                    // Unsorted attachment
                    else
                    {
                        newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }

                    // Log synchronization task if not under workflow
                    if (wi == null)
                    {
                        DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider);
                    }
                }

                // Check in the document
                if (AutoCheck)
                {
                    VersionManager.CheckIn(node, null, null);
                }
            }

            // Temporary attachments
            if (FormGUID != Guid.Empty)
            {
                newAttachment = AttachmentManager.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, CMSContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
            }

            // Ensure properties update
            if ((newAttachment != null) && !InsertMode)
            {
                AttachmentGUID = newAttachment.AttachmentGUID;
            }

            if (newAttachment == null)
            {
                throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied.");
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Content", "UploadAttachment", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;
            // Call aftersave javascript if exists
            if (!String.IsNullOrEmpty(AfterSaveJavascript))
            {
                if ((message == string.Empty) && (newAttachment != null))
                {
                    string url      = null;
                    string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName);
                    if (node != null)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                        if (si != null)
                        {
                            bool usePermanent = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs");
                            if (usePermanent)
                            {
                                url = ResolveUrl(AttachmentManager.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                            }
                            else
                            {
                                url = ResolveUrl(AttachmentManager.GetAttachmentUrl(saveName, node.NodeAliasPath));
                            }
                        }
                    }
                    else
                    {
                        url = ResolveUrl(AttachmentManager.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                    }
                    // Calling javascript function with parameters attachments url, name, width, height
                    if (!string.IsNullOrEmpty(AfterSaveJavascript))
                    {
                        Hashtable obj = new Hashtable();
                        if (ImageHelper.IsImage(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.IMG_URL]     = url;
                            obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName;
                            obj[DialogParameters.IMG_WIDTH]   = newAttachment.AttachmentImageWidth;
                            obj[DialogParameters.IMG_HEIGHT]  = newAttachment.AttachmentImageHeight;
                        }
                        else if (MediaHelper.IsFlash(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE]  = "flash";
                            obj[DialogParameters.FLASH_URL]    = url;
                            obj[DialogParameters.FLASH_EXT]    = newAttachment.AttachmentExtension;
                            obj[DialogParameters.FLASH_TITLE]  = newAttachment.AttachmentName;
                            obj[DialogParameters.FLASH_WIDTH]  = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.FLASH_HEIGHT] = DEFAULT_OBJECT_HEIGHT;
                        }
                        else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE] = "audiovideo";
                            obj[DialogParameters.AV_URL]      = url;
                            obj[DialogParameters.AV_EXT]      = newAttachment.AttachmentExtension;
                            obj[DialogParameters.AV_WIDTH]    = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.AV_HEIGHT]   = DEFAULT_OBJECT_HEIGHT;
                        }
                        else
                        {
                            obj[DialogParameters.LINK_URL]  = url;
                            obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName;
                        }

                        // Calling javascript function with parameters attachments url, name, width, height
                        afterSaveScript += ScriptHelper.GetScript(string.Format(@"{5}
                        if (window.{0})
                        {{
                            window.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}
                        else if((window.parent != null) && window.parent.{0})
                        {{
                            window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj);
                        }}", AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj)));
                    }
                }
                else
                {
                    afterSaveScript += ScriptHelper.GetAlertScript(message);
                }
            }

            // Create attachment info string
            string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : "";

            // Ensure message text
            message = HTMLHelper.EnsureLineEnding(message, " ");

            // Call function to refresh parent window
            afterSaveScript += ScriptHelper.GetScript(String.Format(@"
if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0} != null)){{ 
    window.parent.InitRefresh_{0}({1}, {2}, {3}, {4});
}}",
                                                                    ParentElemID,
                                                                    ScriptHelper.GetString(message.Trim()),
                                                                    (fullRefresh ? "true" : "false"),
                                                                    (refreshTree ? "true" : "false"),
                                                                    attachmentInfo + (InsertMode ? "'insert'" : "'update'")));

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript);
        }
    }
        /// <summary>
        /// Provides operations necessary to create and store new cms file.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleContentUpload(UploaderHelper args, HttpContext context)
        {
            bool   newDocumentCreated = false;
            string name = args.Name;

            try
            {
                if (args.FileArgs.NodeID == 0)
                {
                    throw new Exception(ResHelper.GetString("dialogs.document.parentmissing"));
                }
                // Check license limitations
                if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert))
                {
                    throw new Exception(ResHelper.GetString("cmsdesk.documentslicenselimits"));
                }

                // Check user permissions
                if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(args.FileArgs.NodeID, "CMS.File"))
                {
                    throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.notallowed"), "CMS.File"));
                }

                // Check if class exists
                DataClassInfo ci = DataClassInfoProvider.GetDataClass("CMS.File");
                if (ci == null)
                {
                    throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.classnotfound"), "CMS.File"));
                }


                #region "Check permissions"

                // Get the node
                using (TreeNode parentNode = TreeProvider.SelectSingleNode(args.FileArgs.NodeID, args.FileArgs.Culture, true))
                {
                    if (parentNode != null)
                    {
                        if (!DataClassInfoProvider.IsChildClassAllowed(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ci.ClassID))
                        {
                            throw new Exception(ResHelper.GetString("Content.ChildClassNotAllowed"));
                        }
                    }
                    // Check user permissions
                    if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(parentNode, "CMS.File"))
                    {
                        throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.notallowed"), args.AttachmentArgs.NodeClassName));
                    }
                }

                #endregion

                args.IsExtensionAllowed();

                if (args.FileArgs.IncludeExtension)
                {
                    name += args.Extension;
                }

                // Make sure the file name with extension respects maximum file name
                name = TextHelper.LimitFileNameLength(name, TreePathUtils.MaxNameLength);

                node = TreeNode.New("CMS.File", TreeProvider);
                node.DocumentCulture = args.FileArgs.Culture;
                node.DocumentName    = name;
                if (args.FileArgs.NodeGroupID > 0)
                {
                    node.SetValue("NodeGroupID", args.FileArgs.NodeGroupID);
                }

                // Load default values
                FormHelper.LoadDefaultValues(node);
                node.SetValue("FileDescription", "");
                node.SetValue("FileName", name);
                node.SetValue("FileAttachment", Guid.Empty);
                node.SetValue("DocumentType", args.Extension);
                node.DocumentPageTemplateID = ci.ClassDefaultPageTemplateID;

                // Insert the document
                DocumentHelper.InsertDocument(node, args.FileArgs.NodeID, TreeProvider);
                newDocumentCreated = true;

                // Add the attachment data
                DocumentHelper.AddAttachment(node, "FileAttachment", args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);

                // Create default SKU if configured
                if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))
                {
                    node.CreateDefaultSKU();
                }

                DocumentHelper.UpdateDocument(node, TreeProvider);

                // Get workflow info
                wi = WorkflowManager.GetNodeWorkflow(node);

                // Check if auto publish changes is allowed
                if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName))
                {
                    // Automatically publish document
                    WorkflowManager.AutomaticallyPublish(node, wi, null);
                }
            }
            catch (Exception ex)
            {
                // Delete the document if something failed
                if (newDocumentCreated && (node != null) && (node.DocumentID > 0))
                {
                    DocumentHelper.DeleteDocument(node, TreeProvider, false, true, true);
                }
                args.Message = ex.Message;
            }
            finally
            {
                // Create node info string
                string nodeInfo = ((node != null) && (node.NodeID > 0) && args.IncludeNewItemInfo) ? String.Format("'{0}', ", node.NodeID) : "";

                // Ensure message text
                args.Message = HTMLHelper.EnsureLineEnding(args.Message, " ");

                // Call function to refresh parent window
                if (!string.IsNullOrEmpty(args.AfterSaveJavascript))
                {
                    // Calling javascript function with parameters attachments url, name, width, height
                    args.AfterScript += string.Format(@"
                    if (window.{0} != null)
                    {{
                        window.{0}();
                    }}
                    else if((window.parent != null) && (window.parent.{0} != null))
                    {{
                        window.parent.{0}();
                    }}", args.AfterSaveJavascript);
                }

                // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end
                args.AfterScript += string.Format(@"
                if (window.InitRefresh_{0} != null)
                {{
                    window.InitRefresh_{0}('{1}', false, false, {2});
                }}
                else {{ 
                    if ('{1}' != '') {{
                        alert('{1}');
                    }}
                }}",
                                                  args.ParentElementID,
                                                  ScriptHelper.GetString(args.Message.Trim(), false),
                                                  nodeInfo + (args.IsInsertMode ? "'insert'" : "'update'"));

                args.AddEventTargetPostbackReference();
                context.Response.Write(args.AfterScript);
                context.Response.Flush();
            }
        }
Exemple #12
0
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        TreeProvider tree = null;
        TreeNode     node = null;

        // New attachment
        AttachmentInfo newAttachment = null;

        string message     = string.Empty;
        bool   fullRefresh = false;

        try
        {
            // Get the existing document
            if (DocumentID != 0)
            {
                // Get document
                tree = new TreeProvider(CMSContext.CurrentUser);
                node = DocumentHelper.GetDocument(DocumentID, tree);
                if (node == null)
                {
                    throw new Exception("Given document doesn't exist!");
                }
            }


            #region "Check permissions"

            if (CheckPermissions)
            {
                CheckNodePermissions(node);
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

            // Standard attachments
            if (DocumentID != 0)
            {
                // Ensure automatic check-in/check-out
                bool            useWorkflow = false;
                bool            autoCheck   = false;
                bool            checkin     = false;
                WorkflowManager workflowMan = WorkflowManager.GetInstance(tree);
                VersionManager  vm          = null;

                // Get workflow info
                WorkflowInfo wi = workflowMan.GetNodeWorkflow(node);

                // Check if the document uses workflow
                if (wi != null)
                {
                    useWorkflow = true;
                    autoCheck   = !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName);
                }

                // Check out the document
                if (autoCheck)
                {
                    // Get original step Id
                    int originalStepId = node.DocumentWorkflowStepID;

                    // Get current step info
                    WorkflowStepInfo si = workflowMan.GetStepInfo(node);
                    if (si != null)
                    {
                        // Decide if full refresh is needed
                        bool automaticPublish = wi.WorkflowAutoPublishChanges;
                        // Document is published or archived or uses automatic publish or step is different than original (document was updated)
                        fullRefresh = si.StepIsPublished || si.StepIsArchived || (automaticPublish && !si.StepIsPublished) || (originalStepId != node.DocumentWorkflowStepID);
                    }

                    vm = VersionManager.GetInstance(tree);
                    var step = vm.CheckOut(node, node.IsPublished, true);
                    checkin = (step != null);
                }

                // Handle field attachment
                if (fieldAttachment)
                {
                    newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    // Update attachment field
                    DocumentHelper.UpdateDocument(node, tree);
                }
                // Handle grouped and unsorted attachments
                else
                {
                    // Grouped attachment
                    if (AttachmentGroupGUID != Guid.Empty)
                    {
                        newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                    // Unsorted attachment
                    else
                    {
                        newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                }

                // Check in the document
                if (autoCheck)
                {
                    if ((vm != null) && checkin)
                    {
                        vm.CheckIn(node, null, null);
                    }
                }

                // Log synchronization task if not under workflow
                if (!useWorkflow)
                {
                    DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree);
                }
            }

            // Temporary attachments
            if (FormGUID != Guid.Empty)
            {
                newAttachment = AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, CMSContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
            }

            // Ensure properties update
            if ((newAttachment != null) && !InsertMode)
            {
                AttachmentGUID = newAttachment.AttachmentGUID;
            }

            if (newAttachment == null)
            {
                throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied.");
            }
        }
        catch (Exception ex)
        {
            message       = ex.Message;
            lblError.Text = message;
        }
        finally
        {
            // Call aftersave javascript if exists
            if ((string.IsNullOrEmpty(message)) && (newAttachment != null))
            {
                string closeString = "CloseDialog();";
                // Register wopener script
                ScriptHelper.RegisterWOpenerScript(Page);

                if (!String.IsNullOrEmpty(AfterSaveJavascript))
                {
                    string url      = null;
                    string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName);
                    if (node != null)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                        if (si != null)
                        {
                            bool usePermanent = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs");
                            if (usePermanent)
                            {
                                url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                            }
                            else
                            {
                                url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(saveName, node.NodeAliasPath));
                            }
                        }
                    }
                    else
                    {
                        url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName));
                    }
                    // Calling javascript function with parameters attachments url, name, width, height
                    string jsParams = "('" + url + "', '" + newAttachment.AttachmentName + "', '" + newAttachment.AttachmentImageWidth + "', '" + newAttachment.AttachmentImageHeight + "');";
                    string script   = "if ((wopener.parent != null) && (wopener.parent." + AfterSaveJavascript + " != null)){wopener.parent." + AfterSaveJavascript + jsParams + "}";
                    script += "else if (wopener." + AfterSaveJavascript + " != null){wopener." + AfterSaveJavascript + jsParams + "}";

                    ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refreshAfterSave", ScriptHelper.GetScript(script + closeString));
                }

                // Create attachment info string
                string attachmentInfo = "";
                if ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo))
                {
                    attachmentInfo = newAttachment.AttachmentGUID.ToString();
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", " + (fullRefresh ? "true" : "false") + ", false" + ((attachmentInfo != "") ? ", '" + attachmentInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}" + closeString));
            }
        }
    }
Exemple #13
0
    /// <summary>
    /// Provides operations necessary to create and store new content file.
    /// </summary>
    private void HandleContentUpload()
    {
        TreeNode     node = null;
        TreeProvider tree = null;

        string message            = string.Empty;
        bool   newDocumentCreated = false;

        try
        {
            if (NodeParentNodeID == 0)
            {
                throw new Exception(GetString("dialogs.document.parentmissing"));
            }

            // Check license limitations
            if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert))
            {
                throw new Exception(GetString("cmsdesk.documentslicenselimits"));
            }

            // Check if class exists
            DataClassInfo ci = DataClassInfoProvider.GetDataClass("CMS.File");
            if (ci == null)
            {
                throw new Exception("Class 'CMS.File' not found.");
            }


            #region "Check permissions"

            // Get the node
            tree = new TreeProvider(CMSContext.CurrentUser);
            TreeNode parentNode = tree.SelectSingleNode(NodeParentNodeID, TreeProvider.ALL_CULTURES);
            if (parentNode != null)
            {
                if (!DataClassInfoProvider.IsChildClassAllowed(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ci.ClassID))
                {
                    throw new Exception(GetString("Content.ChildClassNotAllowed"));
                }
            }

            // Check user permissions
            if (!RaiseOnCheckPermissions("Create", this))
            {
                if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(NodeParentNodeID, NodeClassName))
                {
                    throw new Exception("You aren not allowed to create document of type '" + NodeClassName + "' in required location.");
                }
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

            // Create new document
            string fileName = Path.GetFileNameWithoutExtension(ucFileUpload.FileName);

            node = TreeNode.New("CMS.File", tree);
            node.DocumentCulture = CMSContext.PreferredCultureCode;
            node.DocumentName    = fileName;

            // Load default values
            FormHelper.LoadDefaultValues(node.NodeClassName, node);

            node.SetValue("FileDescription", "");
            node.SetValue("FileName", fileName);
            node.SetValue("FileAttachment", Guid.Empty);

            // Set default template ID
            node.SetDefaultPageTemplateID(ci.ClassDefaultPageTemplateID);

            // Insert the document
            DocumentHelper.InsertDocument(node, parentNode, tree);

            newDocumentCreated = true;

            // Add the file
            DocumentHelper.AddAttachment(node, "FileAttachment", ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);

            // Create default SKU if configured
            if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))
            {
                node.CreateDefaultSKU();
            }

            // Update the document
            DocumentHelper.UpdateDocument(node, tree);

            // Get workflow info
            WorkflowInfo workflowInfo = node.GetWorkflow();

            // Check if auto publish changes is allowed
            if ((workflowInfo != null) && workflowInfo.WorkflowAutoPublishChanges && !workflowInfo.UseCheckInCheckOut(CMSContext.CurrentSiteName))
            {
                // Automatically publish document
                node.MoveToPublishedStep(null);
            }
        }
        catch (Exception ex)
        {
            // Delete the document if something failed
            if (newDocumentCreated && (node != null) && (node.DocumentID > 0))
            {
                DocumentHelper.DeleteDocument(node, tree, false, true, true);
            }

            message       = ex.Message;
            lblError.Text = message;
        }
        finally
        {
            if (string.IsNullOrEmpty(message))
            {
                // Create node info string
                string nodeInfo = "";
                if ((node != null) && (node.NodeID > 0) && (IncludeNewItemInfo))
                {
                    nodeInfo = node.NodeID.ToString();
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                // Register wopener script
                ScriptHelper.RegisterWOpenerScript(Page);

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false, false" + ((nodeInfo != "") ? ", '" + nodeInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}CloseDialog();"));
            }
        }
    }
Exemple #14
0
    /// <summary>
    /// Check out layout event handler.
    /// </summary>
    protected void btnCheckOut_Click(object sender, EventArgs e)
    {
        // Ensure version before check-out
        using (CMSActionContext context = new CMSActionContext())
        {
            context.AllowAsyncActions = false;

            // Save first
            if (!SaveLayout())
            {
                return;
            }
        }

        LayoutInfo       li  = this.PagePlaceholder.LayoutInfo;
        PageTemplateInfo pti = this.PagePlaceholder.PageTemplateInfo;

        if ((li != null) || (pti != null))
        {
            try
            {
                string         filename   = "";
                string         tmpCode    = "";
                LayoutTypeEnum layoutType = LayoutTypeEnum.Ascx;

                if (li != null)
                {
                    filename   = LayoutInfoProvider.GetLayoutUrl(li.LayoutCodeName, null, li.LayoutType);
                    layoutType = li.LayoutType;

                    tmpCode = li.LayoutCode;
                }
                else
                {
                    filename   = PageTemplateInfoProvider.GetLayoutUrl(pti.CodeName, null, pti.PageTemplateLayoutType);
                    layoutType = pti.PageTemplateLayoutType;

                    tmpCode = pti.PageTemplateLayout;
                }

                // Write the code to the file
                string fullfilename = "";
                if (HttpContext.Current != null)
                {
                    fullfilename = HttpContext.Current.Server.MapPath(filename);
                    DirectoryHelper.EnsureDiskPath(fullfilename, HttpContext.Current.Server.MapPath("~/"));
                }

                StringBuilder sb = new StringBuilder();
                if (layoutType == LayoutTypeEnum.Ascx)
                {
                    sb.Append(LayoutInfoProvider.GetLayoutDirectives());
                }
                sb.Append(tmpCode);

                string content = HTMLHelper.EnsureLineEnding(sb.ToString(), "\r\n");
                File.WriteAllText(fullfilename, content);

                // Set the layout data
                if (li != null)
                {
                    // Shared layout
                    li.LayoutCheckedOutByUserID    = user.UserID;
                    li.LayoutCheckedOutMachineName = "";
                    if (HttpContext.Current != null)
                    {
                        li.LayoutCheckedOutMachineName = HTTPHelper.MachineName;
                    }
                    li.LayoutCheckedOutFilename = filename;

                    LayoutInfoProvider.SetLayoutInfo(li);
                }
                else
                {
                    // Page template layout
                    pti.PageTemplateLayoutCheckedOutByUserID    = user.UserID;
                    pti.PageTemplateLayoutCheckedOutMachineName = "";
                    if (HttpContext.Current != null)
                    {
                        pti.PageTemplateLayoutCheckedOutMachineName = HTTPHelper.MachineName;
                    }
                    pti.PageTemplateLayoutCheckedOutFileName = filename;

                    PageTemplateInfoProvider.SetPageTemplateInfo(pti);
                }
            }
            catch
            {
                return;
            }
        }
    }