/// <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);
        }
    }
Esempio n. 2
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 (this.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;
                WorkflowManager workflowMan = new WorkflowManager(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;
                        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);
                    }

                    vm = new VersionManager(tree);
                    vm.CheckOut(node, node.IsPublished, true);
                }

                // 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)
                    {
                        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 = 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)
        {
            message       = ex.Message;
            lblError.Text = message;
        }
        finally
        {
            // Call aftersave javascript if exists
            if ((string.IsNullOrEmpty(message)) && (newAttachment != null))
            {
                string closeString = "window.close();";
                // 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(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
                    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(this.Page, typeof(Page), "refreshAfterSave", ScriptHelper.GetScript(script + closeString));
                }

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

                // 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()) + ", " + (fullRefresh ? "true" : "false") + ", false" + ((attachmentInfo != "") ? ", '" + attachmentInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}" + closeString));
            }
        }
    }