Ejemplo n.º 1
0
        public ActionResult Index()
        {
            var properties = GetProperties();
            IEnumerable <Picture> pictures = new List <Picture>();

            switch (properties.Type)
            {
            case Type.Attachments:
                pictures = this.GetPage().Attachments.ToList().Where(a => a.AttachmentImageWidth > 0).Select(a => new Picture
                {
                    Url       = CMS.DocumentEngine.AttachmentURLProvider.GetAttachmentUrl(a.AttachmentName, this.GetPage().NodeAliasPath),
                    AltText   = a.AttachmentTitle,
                    Thumbnail = $"{AttachmentURLProvider.GetAttachmentUrl(a.AttachmentName, this.GetPage().NodeAliasPath)}?maxsidesize=128"
                });
                break;

            case Type.MediaLibraryFolder:
                /*var library = MediaLibraryInfoProvider.GetMediaLibraryInfo(properties.MediaLibraryFolder, this.GetPage().NodeSiteName);
                 * if (string.IsNullOrEmpty(properties.MediaLibraryFolder))
                 * {
                 *  properties.MediaLibraryFolder = "%";
                 * }
                 * var files = MediaFileInfoProvider.GetMediaFiles($"{nameof(MediaFileInfo.FileLibraryID)}={library.LibraryID} AND {nameof(MediaFileInfo.FilePath)} LIKE '{properties.MediaLibrarySubfolder}%'");
                 * pictures = files.ToList().Select(f => new Picture
                 * {
                 *  Url = MediaLibraryHelper.GetMediaFileUrl(f.FileGUID, this.GetPage().NodeSiteName),
                 *  AltText = f.FileTitle,
                 *  Thumbnail = $"{MediaFileURLProvider.GetMediaFileAbsoluteUrl(this.GetPage().NodeSiteName, f.FileGUID, f.FileName)}?maxsidesize=120"
                 * });*/
                if (properties.MediaFiles != null)
                {
                    pictures = properties.MediaFiles.Select(m => new Picture
                    {
                        Url       = MediaLibraryHelper.GetMediaFileUrl(m.FileGuid, this.GetPage().NodeSiteName),
                        AltText   = MediaFileInfoProvider.GetMediaFileInfo(m.FileGuid, this.GetPage().NodeSiteName).FileTitle,
                        Thumbnail = $"{MediaFileURLProvider.GetMediaFileAbsoluteUrl(this.GetPage().NodeSiteName, m.FileGuid, MediaFileInfoProvider.GetMediaFileInfo(m.FileGuid, this.GetPage().NodeSiteName).FileName)}?maxsidesize=128"
                    });
                }
                break;

            case Type.External:
                pictures = properties.External.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Select(f => new Picture
                {
                    Url       = f,
                    AltText   = f,
                    Thumbnail = f
                });
                break;
            }

            var viewModel = new ViewModel
            {
                Pictures = pictures
            };

            return(PartialView("Widgets/_LightboxGallery", viewModel));
        }
Ejemplo n.º 2
0
    /// <summary>
    /// Gets the attachment URL.
    /// </summary>
    protected override string GetUrl()
    {
        string nodeAliasPath = NodeAliasPath;

        // Get group sub node alias path
        if (GroupNode != null)
        {
            if (nodeAliasPath.StartsWith(GroupNode.NodeAliasPath, StringComparison.InvariantCultureIgnoreCase))
            {
                nodeAliasPath = nodeAliasPath.Remove(0, GroupNode.NodeAliasPath.Length);
            }
        }

        return(AttachmentURLProvider.GetAttachmentWebDAVUrl(SiteName, nodeAliasPath, NodeCultureCode, AttachmentFieldName, FileName, GroupName));
    }
 private static void SetArtwork(ShoppingCartItemInfo cartItem, string guid)
 {
     if (!string.IsNullOrWhiteSpace(guid))
     {
         var attachmentPath = AttachmentURLProvider.GetFilePhysicalURL(SiteContext.CurrentSiteName, guid);
         if (!Path.HasExtension(attachmentPath))
         {
             var attachment = DocumentHelper.GetAttachment(new Guid(guid), SiteContext.CurrentSiteName);
             attachmentPath = $"{attachmentPath}{attachment.AttachmentExtension}";
         }
         var storageProvider = StorageHelper.GetStorageProvider(attachmentPath);
         if (storageProvider.IsExternalStorage && storageProvider.FileProviderObject.GetType() == typeof(AmazonFileSystemProvider.File))
         {
             attachmentPath = PathHelper.GetObjectKeyFromPath(attachmentPath);
         }
         cartItem.SetValue("ArtworkLocation", attachmentPath);
     }
 }
Ejemplo n.º 4
0
    protected void libraryMenuElem_OnReloadData(object sender, EventArgs e)
    {
        string[] parameters = (libraryMenuElem.Parameter ?? string.Empty).Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
        if (parameters.Length == 2)
        {
            // Parse identifier and document culture from library parameter
            int    nodeId      = ValidationHelper.GetInteger(parameters[0], 0);
            string cultureCode = ValidationHelper.GetString(parameters[1], string.Empty);
            DocumentManager.Mode = FormModeEnum.Update;
            DocumentManager.ClearNode();
            DocumentManager.DocumentID  = 0;
            DocumentManager.NodeID      = nodeId;
            DocumentManager.CultureCode = cultureCode;
            TreeNode node = DocumentManager.Node;

            bool contextMenuVisible    = false;
            bool localizeVisible       = false;
            bool editVisible           = false;
            bool uploadVisible         = false;
            bool copyVisible           = false;
            bool deleteVisible         = false;
            bool openVisible           = false;
            bool propertiesVisible     = false;
            bool permissionsVisible    = false;
            bool versionHistoryVisible = false;

            bool checkOutVisible         = false;
            bool checkInVisible          = false;
            bool undoCheckoutVisible     = false;
            bool submitToApprovalVisible = false;
            bool rejectVisible           = false;
            bool archiveVisible          = false;

            if ((node != null) && (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed))
            {
                // Get original node (in case of linked documents)
                TreeNode originalNode = TreeProvider.GetOriginalNode(node);

                string documentType           = ValidationHelper.GetString(node.GetValue("DocumentType"), string.Empty);
                string siteName               = CMSContext.CurrentSiteName;
                string currentDocumentCulture = CMSContext.CurrentDocumentCulture.CultureCode;

                if (CMSContext.CurrentSiteID != originalNode.NodeSiteID)
                {
                    SiteInfo si = SiteInfoProvider.GetSiteInfo(originalNode.NodeSiteID);
                    siteName = si.SiteName;
                }

                if (!DocumentManager.ProcessingAction)
                {
                    // Get permissions
                    const bool authorizedToRead              = true;
                    bool       authorizedToDelete            = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Delete) == AuthorizationResultEnum.Allowed);
                    bool       authorizedToModify            = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed);
                    bool       authorizedCultureToModify     = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify, false) == AuthorizationResultEnum.Allowed) && TreeSecurityProvider.HasUserCultureAllowed(NodePermissionsEnum.Modify, currentDocumentCulture, CMSContext.CurrentUser, siteName);
                    bool       authorizedToModifyPermissions = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed);
                    bool       authorizedToCreate            = CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(node.NodeParentID, node.NodeClassName);

                    // Hide menu when user has no 'Read' permissions on document
                    libraryMenuElem.Visible = authorizedToRead;

                    // First evaluation of control's visibility
                    bool differentCulture = (CMSString.Compare(node.DocumentCulture, currentDocumentCulture, true) != 0);
                    localizeVisible       = differentCulture && authorizedToCreate && authorizedCultureToModify;
                    uploadVisible         = authorizedToModify && DocumentManager.AllowSave;
                    copyVisible           = authorizedToCreate && authorizedToModify;
                    deleteVisible         = authorizedToDelete;
                    openVisible           = authorizedToRead;
                    propertiesVisible     = authorizedToModify;
                    permissionsVisible    = authorizedToModifyPermissions;
                    versionHistoryVisible = authorizedToModify;
                    editVisible           = authorizedToModify && CMSContext.IsWebDAVEnabled(CMSContext.CurrentSiteName) && RequestHelper.IsWindowsAuthentication() && WebDAVSettings.IsExtensionAllowedForEditMode(documentType, CMSContext.CurrentSiteName);

                    // Get next step info
                    List <WorkflowStepInfo> stps     = new List <WorkflowStepInfo>();
                    WorkflowInfo            workflow = DocumentManager.Workflow;
                    bool basicWorkflow = true;
                    if (workflow != null)
                    {
                        basicWorkflow = workflow.IsBasic;
                        stps          = WorkflowManager.GetNextStepInfo(node);
                    }
                    var appSteps  = stps.FindAll(s => !s.StepIsArchived);
                    var archSteps = stps.FindAll(s => s.StepIsArchived);

                    // Workflow actions
                    submitToApprovalVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.APPROVE) && (appSteps.Count > 0);
                    rejectVisible           = DocumentManager.IsActionAllowed(DocumentComponentEvents.REJECT);
                    archiveVisible          = DocumentManager.IsActionAllowed(DocumentComponentEvents.ARCHIVE) && ((archSteps.Count > 0) || basicWorkflow);
                    checkOutVisible         = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKOUT);
                    checkInVisible          = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKIN);
                    undoCheckoutVisible     = DocumentManager.IsActionAllowed(DocumentComponentEvents.UNDO_CHECKOUT);

                    string parameterScript = "GetContextMenuParameter('" + libraryMenuElem.MenuID + "')";

                    // Initialize edit menu item
                    Guid attachmentGuid = ValidationHelper.GetGuid(node.GetValue("FileAttachment"), Guid.Empty);

                    // If attachment field doesn't allow empty value and the value is empty
                    if ((FieldInfo != null) && !FieldInfo.AllowEmpty && (attachmentGuid == Guid.Empty))
                    {
                        submitToApprovalVisible = false;
                        archiveVisible          = false;
                        checkInVisible          = false;
                    }

                    // Get attachment
                    AttachmentInfo ai = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, siteName, false);

                    Panel previousPanel = null;
                    Panel currentPanel  = pnlEdit;

                    if (editVisible)
                    {
                        if (ai != null)
                        {
                            // Load WebDAV edit control and initialize it
                            WebDAVEditControl editAttachment = Page.LoadUserControl("~/CMSModules/WebDAV/Controls/AttachmentWebDAVEditControl.ascx") as WebDAVEditControl;

                            if (editAttachment != null)
                            {
                                editAttachment.ID                  = "editAttachment";
                                editAttachment.NodeAliasPath       = node.NodeAliasPath;
                                editAttachment.NodeCultureCode     = node.DocumentCulture;
                                editAttachment.AttachmentFieldName = "FileAttachment";
                                editAttachment.FileName            = ai.AttachmentName;
                                editAttachment.IsLiveSite          = IsLiveSite;
                                editAttachment.UseImageButton      = true;
                                editAttachment.LabelText           = GetString("general.edit");
                                editAttachment.CssClass            = "Icon";
                                editAttachment.LabelCssClass       = "Name";
                                editAttachment.RefreshScript       = JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'WebDAVRefresh');";
                                // Set Group ID for live site
                                editAttachment.GroupID = IsLiveSite ? node.GetIntegerValue("NodeGroupID") : 0;
                                editAttachment.ReloadData(true);

                                pnlEditPadding.Controls.Add(editAttachment);
                                pnlEditPadding.CssClass = editAttachment.EnabledResult ? "ItemPadding" : "ItemPaddingDisabled";
                            }
                        }
                        else
                        {
                            editVisible = false;
                            openVisible = false;
                        }
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlUpload;

                    // Initialize upload menu item
                    if (authorizedToModify)
                    {
                        StringBuilder uploaderInnerHtml = new StringBuilder();
                        uploaderInnerHtml.Append("<img class=\"UploaderImage\" src=\"", GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Upload.png", IsLiveSite), "\" alt=\"", GetString("general.update"), "\" />");
                        uploaderInnerHtml.Append("<span class=\"UploaderText\">", GetString("general.update"), "</span>");

                        // Initialize direct file uploader
                        updateAttachment.InnerDivHtml             = uploaderInnerHtml.ToString();
                        updateAttachment.InnerDivClass            = "LibraryContextUploader";
                        updateAttachment.DocumentID               = node.DocumentID;
                        updateAttachment.ParentElemID             = ClientID;
                        updateAttachment.SourceType               = MediaSourceEnum.Attachment;
                        updateAttachment.AttachmentGUIDColumnName = "FileAttachment";
                        updateAttachment.IsLiveSite               = IsLiveSite;

                        // Set allowed extensions
                        if ((FieldInfo != null) && ValidationHelper.GetString(FieldInfo.Settings["extensions"], "") == "custom")
                        {
                            // Load allowed extensions
                            updateAttachment.AllowedExtensions = ValidationHelper.GetString(FieldInfo.Settings["allowed_extensions"], "");
                        }
                        else
                        {
                            // Use site settings
                            updateAttachment.AllowedExtensions = SettingsKeyProvider.GetStringValue(siteName + ".CMSUploadExtensions");
                        }

                        updateAttachment.ReloadData();
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlLocalize;

                    // Initialize localize menu item
                    if (localizeVisible)
                    {
                        lblLocalize.RefreshText();
                        imgLocalize.AlternateText = lblLocalize.Text;
                        imgLocalize.ImageUrl      = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Localize.png", IsLiveSite);
                        pnlLocalize.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Localize');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = null;
                    currentPanel  = pnlCopy;

                    // Initialize copy menu item
                    if (copyVisible)
                    {
                        lblCopy.RefreshText();
                        imgCopy.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Copy.png", IsLiveSite);
                        pnlCopy.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ",'Copy');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlDelete;

                    // Initialize delete menu item
                    if (deleteVisible)
                    {
                        lblDelete.RefreshText();
                        imgDelete.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Delete.png", IsLiveSite);
                        pnlDelete.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Delete');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlOpen;

                    // Initialize open menu item
                    if (openVisible)
                    {
                        lblOpen.RefreshText();
                        imgOpen.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Open.png", IsLiveSite);
                        if (ai != null)
                        {
                            // Get document URL
                            string attachmentUrl = CMSContext.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(node.NodeGUID, node.NodeAlias));
                            if (authorizedToModify)
                            {
                                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(node.DocumentID, string.Empty));
                                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + node.DocumentID));
                            }
                            attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                            if (!string.IsNullOrEmpty(attachmentUrl))
                            {
                                pnlOpen.Attributes.Add("onclick", "location.href = " + ScriptHelper.GetString(attachmentUrl) + ";");
                            }
                        }
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = null;
                    currentPanel  = pnlProperties;

                    // Initialize properties menu item
                    lblProperties.RefreshText();
                    imgProperties.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Properties.png", IsLiveSite);
                    pnlProperties.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Properties');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = currentPanel;
                    currentPanel  = pnlPermissions;

                    // Initialize permissions menu item
                    lblPermissions.RefreshText();
                    imgPermissions.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Permissions.png", IsLiveSite);
                    pnlPermissions.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Permissions');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = currentPanel;
                    currentPanel  = pnlVersionHistory;

                    // Initialize version history menu item
                    lblVersionHistory.RefreshText();
                    imgVersionHistory.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/VersionHistory.png", IsLiveSite);
                    pnlVersionHistory.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'VersionHistory');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = null;
                    currentPanel  = pnlCheckOut;

                    // Initialize checkout menu item
                    if (checkOutVisible)
                    {
                        lblCheckOut.RefreshText();
                        imgCheckOut.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckOut.png", IsLiveSite);
                        pnlCheckOut.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckOut');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlCheckIn;

                    // Initialize check in menu item
                    if (checkInVisible)
                    {
                        lblCheckIn.RefreshText();
                        imgCheckIn.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckIn.png", IsLiveSite);
                        pnlCheckIn.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckIn');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlUndoCheckout;

                    // Initialize undo checkout menu item
                    if (undoCheckoutVisible)
                    {
                        lblUndoCheckout.RefreshText();
                        imgUndoCheckout.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/UndoCheckout.png", IsLiveSite);
                        pnlUndoCheckout.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'UndoCheckout');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlSubmitToApproval;

                    // Initialize submit to approval / publish menu item
                    if (submitToApprovalVisible)
                    {
                        // Only one next step
                        if (appSteps.Count == 1)
                        {
                            if (appSteps[0].StepIsPublished)
                            {
                                // Set 'Publish' label
                                lblSubmitToApproval.ResourceString = "general.publish";
                                cmcApp.Parameter = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.PUBLISH);
                            }
                            pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'SubmitToApproval');");
                        }
                        // Multiple steps - display dialog
                        else
                        {
                            pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new string[] { "'" + DocumentComponentEvents.APPROVE + "'", node.DocumentID.ToString() }), null) + ";");
                            cmcApp.Enabled = false;
                        }

                        lblSubmitToApproval.RefreshText();
                        imgSubmitToApproval.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/SubmitToApproval.png", IsLiveSite);
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlReject;

                    // Initialize reject menu item
                    if (rejectVisible)
                    {
                        lblReject.RefreshText();
                        imgReject.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Reject.png", IsLiveSite);
                        pnlReject.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Reject');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlArchive;

                    // Initialize archive menu item
                    if (archiveVisible)
                    {
                        // Only one archive step
                        if ((archSteps.Count == 1) || basicWorkflow)
                        {
                            pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Archive');");
                        }
                        // Multiple archive steps - display dialog
                        else
                        {
                            pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new string[] { "'" + DocumentComponentEvents.ARCHIVE + "'", node.DocumentID.ToString() }), null) + ";");
                            cmcArch.Enabled = false;
                        }

                        lblArchive.RefreshText();
                        imgArchive.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Archive.png", IsLiveSite);
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    // Set up visibility of menu items
                    pnlLocalize.Visible       = localizeVisible;
                    pnlUpload.Visible         = uploadVisible;
                    pnlDelete.Visible         = deleteVisible;
                    pnlCopy.Visible           = copyVisible;
                    pnlOpen.Visible           = openVisible;
                    pnlProperties.Visible     = propertiesVisible;
                    pnlPermissions.Visible    = permissionsVisible;
                    pnlVersionHistory.Visible = versionHistoryVisible;
                    pnlEdit.Visible           = editVisible;

                    pnlCheckOut.Visible         = checkOutVisible;
                    pnlCheckIn.Visible          = checkInVisible;
                    pnlUndoCheckout.Visible     = undoCheckoutVisible;
                    pnlSubmitToApproval.Visible = submitToApprovalVisible;
                    pnlReject.Visible           = rejectVisible;
                    pnlArchive.Visible          = archiveVisible;

                    // Set up visibility of whole menu
                    contextMenuVisible = true;
                }

                if (DocumentManager.ProcessingAction)
                {
                    // Setup 'No action available' menu item
                    pnlNoAction.Visible        = true;
                    lblNoAction.ResourceString = null;
                    lblNoAction.Text           = DocumentManager.GetDocumentInfo(true);
                    lblNoAction.RefreshText();
                }
                else
                {
                    // Set up visibility of separators
                    bool firstGroupVisible  = editVisible || uploadVisible || localizeVisible;
                    bool secondGroupVisible = copyVisible || deleteVisible || openVisible;
                    bool thirdGroupVisible  = propertiesVisible || permissionsVisible || versionHistoryVisible;
                    bool fourthGroupVisible = checkOutVisible || checkInVisible || undoCheckoutVisible || submitToApprovalVisible || rejectVisible || archiveVisible;

                    pnlSep1.Visible = firstGroupVisible && secondGroupVisible;
                    pnlSep2.Visible = secondGroupVisible && thirdGroupVisible;
                    pnlSep3.Visible = thirdGroupVisible && fourthGroupVisible;

                    // Setup 'No action available' menu item
                    pnlNoAction.Visible = !contextMenuVisible;
                    lblNoAction.RefreshText();
                }
            }
        }
    }
Ejemplo n.º 5
0
    /// <summary>
    /// Setup media dialog from selected item.
    /// </summary>
    /// <param name="selectionTable">Hash table from selected item</param>
    /// <param name="anchorsList">List of anchors from document</param>
    /// <param name="idsList">List of ids from document</param>
    private void SelectMediaDialog(IDictionary selectionTable, ICollection anchorsList, ICollection idsList)
    {
        string insertHeaderLocation = BaseFilePath + "Header.aspx" + RequestContext.CurrentQueryString;

        if (selectionTable.Count > 0)
        {
            string siteName = null;
            string url      = null;
            // If link dialog use only link url
            if (RequestContext.CurrentQueryString.ToLowerCSafe().Contains("link=1"))
            {
                if (selectionTable[DialogParameters.LINK_URL] != null)
                {
                    url = selectionTable[DialogParameters.LINK_URL].ToString();
                    if ((selectionTable[DialogParameters.LINK_PROTOCOL] != null) && (selectionTable[DialogParameters.LINK_PROTOCOL].ToString() != "other"))
                    {
                        // Add protocol only if not already presents
                        if (!url.StartsWithCSafe(selectionTable[DialogParameters.LINK_PROTOCOL].ToString()))
                        {
                            url = selectionTable[DialogParameters.LINK_PROTOCOL] + url;
                        }
                    }
                }
                else if (selectionTable[DialogParameters.URL_URL] != null)
                {
                    url = selectionTable[DialogParameters.URL_URL].ToString();
                }
            }
            else
            {
                // Get url from selection table
                if (selectionTable[DialogParameters.IMG_URL] != null)
                {
                    url = selectionTable[DialogParameters.IMG_URL].ToString();
                }
                else if (selectionTable[DialogParameters.FLASH_URL] != null)
                {
                    url = selectionTable[DialogParameters.FLASH_URL].ToString();
                }
                else if (selectionTable[DialogParameters.AV_URL] != null)
                {
                    url = selectionTable[DialogParameters.AV_URL].ToString();
                }
                else if (selectionTable[DialogParameters.LINK_URL] != null)
                {
                    url = selectionTable[DialogParameters.LINK_URL].ToString();
                }
                else if (selectionTable[DialogParameters.URL_URL] != null)
                {
                    url      = selectionTable[DialogParameters.URL_URL].ToString();
                    siteName = (selectionTable[DialogParameters.URL_SITENAME] != null ? selectionTable[DialogParameters.URL_SITENAME].ToString() : null);
                }
            }
            string query = URLHelper.RemoveUrlParameter(RequestContext.CurrentQueryString, "hash");

            // Get the data for media source
            MediaSource ms = CMSDialogHelper.GetMediaData(url, siteName);
            if (ms != null)
            {
                SessionHelper.SetValue("MediaSource", ms);

                // Preselect the tab
                if (!selectionTable.Contains(DialogParameters.EMAIL_TO) || !selectionTable.Contains(DialogParameters.ANCHOR_NAME))
                {
                    switch (ms.SourceType)
                    {
                    case MediaSourceEnum.DocumentAttachments:
                    case MediaSourceEnum.MetaFile:
                        query = URLHelper.AddUrlParameter(query, "tab", "attachments");
                        break;

                    case MediaSourceEnum.Content:
                        query = URLHelper.AddUrlParameter(query, "tab", "content");
                        break;

                    case MediaSourceEnum.MediaLibraries:
                        query = URLHelper.AddUrlParameter(query, "tab", "libraries");
                        break;

                    default:
                        query = URLHelper.AddUrlParameter(query, "tab", "web");
                        break;
                    }
                }

                // Update old format url
                if ((selectionTable.Contains(DialogParameters.URL_OLDFORMAT)) && (selectionTable.Contains(DialogParameters.URL_GUID)))
                {
                    if (String.IsNullOrEmpty(siteName))
                    {
                        siteName = SiteContext.CurrentSiteName;
                    }
                    string outUrl = ModuleCommands.MediaLibraryGetMediaFileUrl(selectionTable[DialogParameters.URL_GUID].ToString(), siteName);
                    if (!String.IsNullOrEmpty(outUrl))
                    {
                        selectionTable[DialogParameters.URL_URL] = outUrl;
                    }
                }

                // Set extension if not exist in selection table
                if ((selectionTable[DialogParameters.URL_EXT] == null) || ((selectionTable[DialogParameters.URL_EXT] != null) && (String.IsNullOrEmpty(selectionTable[DialogParameters.URL_EXT].ToString()))))
                {
                    selectionTable[DialogParameters.URL_EXT] = ms.Extension;
                }

                // Update selection table if only URL presents
                if (selectionTable.Contains(DialogParameters.URL_URL))
                {
                    switch (ms.MediaType)
                    {
                    case MediaTypeEnum.Image:
                        // Image
                        selectionTable[DialogParameters.IMG_URL]    = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                        selectionTable[DialogParameters.IMG_WIDTH]  = selectionTable[DialogParameters.URL_WIDTH];
                        selectionTable[DialogParameters.IMG_HEIGHT] = selectionTable[DialogParameters.URL_HEIGHT];
                        break;

                    case MediaTypeEnum.AudioVideo:
                        // Media
                        selectionTable[DialogParameters.AV_URL]    = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                        selectionTable[DialogParameters.AV_WIDTH]  = selectionTable[DialogParameters.URL_WIDTH];
                        selectionTable[DialogParameters.AV_HEIGHT] = selectionTable[DialogParameters.URL_HEIGHT];
                        selectionTable[DialogParameters.AV_EXT]    = ms.Extension;
                        break;

                    case MediaTypeEnum.Flash:
                        // Flash
                        selectionTable[DialogParameters.FLASH_URL]    = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                        selectionTable[DialogParameters.FLASH_WIDTH]  = selectionTable[DialogParameters.URL_WIDTH];
                        selectionTable[DialogParameters.FLASH_HEIGHT] = selectionTable[DialogParameters.URL_HEIGHT];
                        break;
                    }

                    if ((ms.SourceType == MediaSourceEnum.Content) && (ms.FileName != null) && (OutputFormat == OutputFormatEnum.NodeGUID))
                    {
                        string fileUrl = AttachmentURLProvider.GetPermanentAttachmentUrl(ms.NodeGuid, ms.FileName);
                        selectionTable[DialogParameters.URL_URL] = UrlResolver.ResolveUrl(fileUrl);
                    }
                    else if (OutputFormat != OutputFormatEnum.URL)
                    {
                        selectionTable[DialogParameters.URL_URL] = UrlResolver.ResolveUrl(selectionTable[DialogParameters.URL_URL].ToString());
                    }

                    selectionTable[DialogParameters.FILE_NAME] = ms.FileName;
                    selectionTable[DialogParameters.FILE_SIZE] = ms.FileSize;
                }

                // Add original size into table
                selectionTable[DialogParameters.IMG_ORIGINALWIDTH]  = ms.MediaWidth;
                selectionTable[DialogParameters.IMG_ORIGINALHEIGHT] = ms.MediaHeight;
            }
            else
            {
                if (selectionTable.Contains(DialogParameters.EMAIL_TO))
                {
                    query = URLHelper.AddUrlParameter(query, "tab", "email");
                }
                if (selectionTable.Contains(DialogParameters.ANCHOR_NAME))
                {
                    query = URLHelper.AddUrlParameter(query, "tab", "anchor");
                }
            }

            query = URLHelper.AddUrlParameter(query, "hash", QueryHelper.GetHash(query));
            insertHeaderLocation = BaseFilePath + "Header.aspx" + query;
        }


        // Set selected item into session
        SessionHelper.SetValue("DialogParameters", selectionTable);

        if ((anchorsList != null) && (anchorsList.Count > 0))
        {
            SessionHelper.SetValue("Anchors", anchorsList);
        }
        if ((idsList != null) && (idsList.Count > 0))
        {
            SessionHelper.SetValue("Ids", idsList);
        }

        if (((selectionTable[DialogParameters.LINK_TEXT] != null) &&
             (selectionTable[DialogParameters.LINK_TEXT].ToString() == "##LINKTEXT##")) ||
            ((selectionTable[DialogParameters.EMAIL_LINKTEXT] != null) &&
             (selectionTable[DialogParameters.EMAIL_LINKTEXT].ToString() == "##LINKTEXT##")) ||
            ((selectionTable[DialogParameters.ANCHOR_LINKTEXT] != null) &&
             (selectionTable[DialogParameters.ANCHOR_LINKTEXT].ToString() == "##LINKTEXT##")))
        {
            SessionHelper.SetValue("HideLinkText", true);
        }

        ltlScript.Text = ScriptHelper.GetScript("if (window.parent.frames['insertHeader']) { window.parent.frames['insertHeader'].location= \"" + ResolveUrl(insertHeaderLocation) + "\";} ");
    }
    private string GetAttachmentUrl(DocumentAttachment attachment, DocumentAttachment mainAttachment, int versionHistoryId)
    {
        // Get link for attachment
        string attachmentUrl;

        var attName    = mainAttachment.AttachmentName;
        var documentId = mainAttachment.AttachmentDocumentID;
        var siteName   = SiteContext.CurrentSiteName;

        if (IsLiveSite && (documentId > 0))
        {
            attachmentUrl =
                ApplicationUrlHelper.ResolveUIUrl(
                    AttachmentURLProvider.GetAttachmentUrl(
                        mainAttachment.AttachmentGUID,
                        URLHelper.GetSafeFileName(attName, siteName)
                        )
                    );
        }
        else
        {
            attachmentUrl =
                ApplicationUrlHelper.ResolveUIUrl(
                    AttachmentURLProvider.GetAttachmentUrl(
                        mainAttachment.AttachmentGUID,
                        URLHelper.GetSafeFileName(attName, siteName),
                        null,
                        // Do not include version history ID for temporary attachment
                        // Version history ID may be present in case of new culture version where may be mix of temporary and version attachments from source
                        (mainAttachment.AttachmentFormGUID == Guid.Empty) ? versionHistoryId : 0
                        )
                    );
        }

        // Add variant identifier
        if (attachment.IsVariant())
        {
            attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "variant", attachment.AttachmentVariantDefinitionIdentifier);
        }

        // Ensure correct URL for non-temporary attachments, they need to be served from their original site (may be from linked documents)
        if (mainAttachment.AttachmentFormGUID == Guid.Empty)
        {
            var attachmentSiteName = SiteInfoProvider.GetSiteName(mainAttachment.AttachmentSiteID);
            if (attachmentSiteName != siteName)
            {
                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "sitename", attachmentSiteName);
            }
        }

        attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

        // Add latest version requirement for live site
        if (IsLiveSite && (documentId > 0))
        {
            // Add requirement for latest version of files for current document
            string newparams = "latestfordocid=" + documentId;
            newparams += "&hash=" + ValidationHelper.GetHashString("d" + documentId);

            attachmentUrl += "&" + newparams;
        }

        return(attachmentUrl);
    }
Ejemplo n.º 7
0
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        // New attachment
        DocumentAttachment 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 page 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;
                        // 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);
                    }

                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        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, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    // Update attachment field
                    DocumentHelper.UpdateDocument(node, TreeProvider);

                    // Different extension
                    if ((oldExtension != null) && !oldExtension.EqualsCSafe(node.DocumentType, true))
                    {
                        refreshTree = true;
                    }
                }
                // Handle grouped and unsorted attachments
                else
                {
                    // Grouped attachment
                    if (AttachmentGroupGUID != Guid.Empty)
                    {
                        newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);
                    }
                    // Unsorted attachment
                    else
                    {
                        newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, 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)
                {
                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckIn(node, null, null);
                    }
                }
            }

            // Temporary attachments
            if (FormGUID != Guid.Empty)
            {
                newAttachment = (DocumentAttachment)AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, SiteContext.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 safeName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, SiteContext.CurrentSiteName);
                    if (node != null)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                        if (si != null)
                        {
                            bool usePermanent = DocumentURLProvider.UsePermanentUrls(si.SiteName);
                            if (usePermanent)
                            {
                                url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName));
                            }
                            else
                            {
                                url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(safeName, node.NodeAliasPath));
                            }
                        }
                    }
                    else
                    {
                        url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName));
                    }
                    // 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.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 = TextHelper.EnsureLineEndings(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);
        }
    }
Ejemplo n.º 8
0
    /// <summary>
    /// UniGrid external data bound.
    /// </summary>
    protected object GridDocsOnExternalDataBound(object sender, string sourceName, object parameter)
    {
        string      attName;
        string      attachmentExt;
        DataRowView drv;

        switch (sourceName.ToLowerCSafe())
        {
        case "update":
        {
            drv = parameter as DataRowView;
            PlaceHolder plcUpd = new PlaceHolder();
            plcUpd.ID = "plcUdateAction";
            Panel pnlBlock = new Panel();
            pnlBlock.ID = "pnlBlock";

            plcUpd.Controls.Add(pnlBlock);

            // Add update control
            // Dynamically load uploader control
            DirectFileUploader dfuElem = Page.LoadUserControl("~/CMSModules/Content/Controls/Attachments/DirectFileUploader/DirectFileUploader.ascx") as DirectFileUploader;

            // Set uploader's properties
            if (dfuElem != null)
            {
                dfuElem.ID            = "dfuElem" + DocumentID;
                dfuElem.SourceType    = MediaSourceEnum.Attachment;
                dfuElem.DisplayInline = true;

                if (!createTempAttachment)
                {
                    dfuElem.AttachmentGUID = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);
                }

                dfuElem.ForceLoad = true;
                dfuElem.FormGUID  = FormGUID;
                dfuElem.AttachmentGUIDColumnName = GUIDColumnName;
                dfuElem.DocumentID          = DocumentID;
                dfuElem.NodeParentNodeID    = NodeParentNodeID;
                dfuElem.NodeClassName       = NodeClassName;
                dfuElem.ResizeToWidth       = ResizeToWidth;
                dfuElem.ResizeToHeight      = ResizeToHeight;
                dfuElem.ResizeToMaxSideSize = ResizeToMaxSideSize;
                dfuElem.AllowedExtensions   = AllowedExtensions;
                dfuElem.ShowIconMode        = true;
                dfuElem.InsertMode          = false;
                dfuElem.ParentElemID        = ClientID;
                dfuElem.IncludeNewItemInfo  = true;
                dfuElem.CheckPermissions    = CheckPermissions;
                dfuElem.NodeSiteName        = SiteName;
                dfuElem.IsLiveSite          = IsLiveSite;
                // Setting of the direct single mode
                dfuElem.UploadMode        = MultifileUploaderModeEnum.DirectSingle;
                dfuElem.MaxNumberToUpload = 1;

                dfuElem.PreRender += dfuElem_PreRender;
                pnlBlock.Controls.Add(dfuElem);
            }

            int  nodeGroupId       = ((Node != null) && (Node.DocumentID > 0)) ? Node.GetValue("NodeGroupID", 0) : 0;
            bool displayGroupAdmin = true;

            // Check group admin for live site
            if (IsLiveSite && (nodeGroupId > 0))
            {
                displayGroupAdmin = MembershipContext.AuthenticatedUser.IsGroupAdministrator(nodeGroupId);
            }

            // Check if external editing allowed by the form
            bool allowExt = (Form == null) || Form.AllowExternalEditing;

            if (allowExt && (FormGUID == Guid.Empty) && displayGroupAdmin)
            {
                var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlBlock, FileTypeEnum.Attachment, SiteName, new DataRowContainer(drv), IsLiveSite, Node);
                if (ctrl != null)
                {
                    ctrl.ID = "extEdit" + DocumentID;

                    // Ensure form identification
                    if ((Form != null) && (Form.Parent != null))
                    {
                        ctrl.FormID = Form.Parent.ClientID;
                    }
                    ctrl.SiteName = SiteName;

                    if (FieldInfo != null)
                    {
                        ctrl.AttachmentFieldName = FieldInfo.Name;
                    }

                    ctrl.PreRender += extEdit_PreRender;

                    // Adjust the styles
                    bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());
                    pnlBlock.Style.Add("text-align", isRTL ? "right" : "left");
                }
            }

            return(plcUpd);
        }

        case "edit":
        {
            // Get file extension
            string extension = ValidationHelper.GetString(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentExtension"], string.Empty).ToLowerCSafe();

            // Get attachment GUID
            attachmentGuid = ValidationHelper.GetGuid(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentGUID"], Guid.Empty);
            if (sender is CMSGridActionButton)
            {
                CMSGridActionButton img = (CMSGridActionButton)sender;
                if (createTempAttachment)
                {
                    img.Visible = false;
                }
                else
                {
                    img.ScreenReaderDescription = extension;
                    img.ToolTip    = attachmentGuid.ToString();
                    img.PreRender += img_PreRender;
                }
            }
        }
        break;

        case "delete":
            if (sender is CMSGridActionButton)
            {
                CMSGridActionButton imgDelete = (CMSGridActionButton)sender;
                // Turn off validation
                imgDelete.CausesValidation = false;
                imgDelete.PreRender       += imgDelete_PreRender;
            }
            break;

        case "attachmentname":
        {
            drv = parameter as DataRowView;

            // Get attachment GUID
            attachmentGuid = ValidationHelper.GetGuid(drv["AttachmentGUID"], Guid.Empty);

            // Get attachment extension
            attachmentExt = ValidationHelper.GetString(drv["AttachmentExtension"], string.Empty);
            bool isImage = ImageHelper.IsImage(attachmentExt);
            bool isTemp  = ValidationHelper.GetGuid(drv["AttachmentFormGUID"], Guid.Empty) != Guid.Empty;

            // Get link for attachment
            string attachmentUrl = null;
            attName = ValidationHelper.GetString(drv["AttachmentName"], string.Empty);
            int documentId = DocumentID;

            if (documentId > 0)
            {
                int versionHistoryId = IsLiveSite ? 0 : VersionHistoryID;
                attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attachmentGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName), null, versionHistoryId));
            }
            else
            {
                attachmentUrl = ResolveUrl(DocumentHelper.GetAttachmentUrl(attachmentGuid, 0));
            }
            attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

            // Ensure correct URL for non-temporary attachments
            if ((OriginalNodeSiteName != SiteContext.CurrentSiteName) && !isTemp)
            {
                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "sitename", OriginalNodeSiteName);
            }

            // Add latest version requirement for live site
            if (IsLiveSite && (documentId > 0))
            {
                // Add requirement for latest version of files for current document
                string newparams = "latestfordocid=" + documentId;
                newparams += "&hash=" + ValidationHelper.GetHashString("d" + documentId);

                attachmentUrl += "&" + newparams;
            }

            // Optionally trim attachment name
            string attachmentName = TextHelper.LimitLength(attName, ATTACHMENT_NAME_LIMIT);

            // Tooltip
            string tooltip = null;
            if (ShowTooltip)
            {
                string title       = ValidationHelper.GetString(drv["AttachmentTitle"], string.Empty);
                string description = ValidationHelper.GetString(drv["AttachmentDescription"], string.Empty);

                int imageWidth  = ValidationHelper.GetInteger(drv["AttachmentImageWidth"], 0);
                int imageHeight = ValidationHelper.GetInteger(drv["AttachmentImageHeight"], 0);

                tooltip = UIHelper.GetTooltipAttributes(attachmentUrl, imageWidth, imageHeight, title, attachmentName, attachmentExt, description, null, 300);
            }

            // Icon
            string iconTag = UIHelper.GetFileIcon(Page, attachmentExt, tooltip: attachmentName);

            if (isImage)
            {
                return("<a href=\"#\" onclick=\"javascript: window.open('" + attachmentUrl + "'); return false;\" class=\"cms-icon-link\"><span " + tooltip + ">" + iconTag + attachmentName + "</span></a>");
            }
            else
            {
                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "disposition", "attachment");

                // NOTE: OnClick here is needed to avoid loader to show because even for download links, the pageUnload event is fired
                return(String.Format("<a href=\"{0}\" onclick=\"javascript: {5}\" class=\"cms-icon-link\"><span id=\"{1}\" {2}>{3}{4}</span></a>", attachmentUrl, attachmentGuid, tooltip, iconTag, attachmentName, ScriptHelper.GetDisableProgressScript()));
            }
        }

        case "attachmentsize":
        {
            long size = ValidationHelper.GetLong(parameter, 0);
            return(DataHelper.GetSizeString(size));
        }
        }

        return(parameter);
    }
    /// <summary>
    /// UniGrid external data bound.
    /// </summary>
    protected object gridAttachments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView drv;

        switch (sourceName.ToLowerCSafe())
        {
        case "clone":
            CMSGridActionButton imgClone = sender as CMSGridActionButton;
            if (imgClone != null)
            {
                if (IsLiveSite)
                {
                    // Hide cloning on live site
                    imgClone.Visible = false;
                    return(imgClone);
                }

                string objectType = VersionHistoryID > 0 ? AttachmentHistoryInfo.OBJECT_TYPE : AttachmentInfo.OBJECT_TYPE;

                int id = ValidationHelper.GetInteger(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentID"], 0);

                imgClone.PreRender    += imgClone_PreRender;
                imgClone.OnClientClick = "modalDialog('" + URLHelper.ResolveUrl("~/CMSModules/Objects/Dialogs/CloneObjectDialog.aspx?objectType=" + objectType + "&objectId=" + id) + "', 'CloneObject', 750, 470); return false;";
            }
            break;

        case "update":
        {
            Panel pnlBlock = new Panel
            {
                ID = "pnlBlock"
            };

            pnlBlock.Style.Add("margin", "0 auto");
            pnlBlock.PreRender += (senderObject, args) => pnlBlock.Width = mUpdateIconPanelWidth;

            // Add update control
            // Dynamically load uploader control
            var dfuElem = Page.LoadUserControl("~/CMSModules/Content/Controls/Attachments/DirectFileUploader/DirectFileUploader.ascx") as DirectFileUploader;

            drv = parameter as DataRowView;

            // Set uploader's properties
            if (dfuElem != null)
            {
                dfuElem.SourceType = MediaSourceEnum.DocumentAttachments;
                dfuElem.ID         = "dfuElem" + DocumentID;
                dfuElem.IsLiveSite = IsLiveSite;
                dfuElem.EnableSilverlightUploader = false;
                dfuElem.ControlGroup      = "update";
                dfuElem.AttachmentGUID    = GetAttachmentGuid(drv);
                dfuElem.DisplayInline     = true;
                dfuElem.UploadMode        = MultifileUploaderModeEnum.DirectSingle;
                dfuElem.MaxNumberToUpload = 1;
                dfuElem.PreRender        += dfuElem_PreRender;
                pnlBlock.Controls.Add(dfuElem);
            }

            // Check if external edit allowed by the form
            bool allowExt = (Form == null) || Form.AllowExternalEditing;

            if (allowExt && (FormGUID == Guid.Empty))
            {
                var ctrl = ExternalEditHelper.LoadExternalEditControl(pnlBlock, FileTypeEnum.Attachment, SiteName, new DataRowContainer(drv), IsLiveSite, Node);
                if (ctrl != null)
                {
                    ctrl.Enabled = Enabled;
                    ctrl.ID      = "extEdit" + DocumentID;

                    // Ensure form identification
                    if ((Form != null) && (Form.Parent != null))
                    {
                        ctrl.FormID = Form.Parent.ClientID;
                    }
                    ctrl.SiteName = SiteName;

                    ctrl.PreRender += extEdit_PreRender;

                    if (FieldInfo != null)
                    {
                        ctrl.AttachmentFieldName = FieldInfo.Name;
                    }

                    // Adjust styles
                    bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());

                    pnlBlock.Style.Add("text-align", isRTL ? "right" : "left");
                    mUpdateIconPanelWidth = 32;
                }
            }

            return(pnlBlock);
        }

        case "edit":
            // Get file extension
            string extension        = ValidationHelper.GetString(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentExtension"], string.Empty).ToLowerCSafe();
            Guid   guid             = ValidationHelper.GetGuid(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentGUID"], Guid.Empty);
            CMSGridActionButton img = sender as CMSGridActionButton;
            if (img != null)
            {
                img.ToolTip    = String.Format("{0}|{1}", extension, guid);
                img.PreRender += img_PreRender;
            }
            break;

        case "delete":
            CMSGridActionButton imgDelete = sender as CMSGridActionButton;
            if (imgDelete != null)
            {
                // Turn off validation
                imgDelete.CausesValidation = false;
                imgDelete.PreRender       += imgDelete_PreRender;
            }
            break;

        case "moveup":
            CMSGridActionButton imgUp = sender as CMSGridActionButton;
            if (imgUp != null)
            {
                // Turn off validation
                imgUp.CausesValidation = false;
                imgUp.PreRender       += imgUp_PreRender;
            }
            break;

        case "movedown":
            CMSGridActionButton imgDown = sender as CMSGridActionButton;
            if (imgDown != null)
            {
                // Turn off validation
                imgDown.CausesValidation = false;
                imgDown.PreRender       += imgDown_PreRender;
            }
            break;

        case "attachmentname":
        {
            drv = parameter as DataRowView;

            if (drv == null)
            {
                break;
            }

            // Get attachment GUID
            Guid attachmentGuid = GetAttachmentGuid(drv);

            // Get attachment extension
            string attachmentExt = GetAttachmentExtension(drv);
            bool   isImage       = ImageHelper.IsImage(attachmentExt);

            // Get link for attachment
            string attachmentUrl;

            string attName    = ValidationHelper.GetString(drv["AttachmentName"], string.Empty);
            int    documentId = DocumentID;

            if (Node != null)
            {
                if (IsLiveSite && (documentId > 0))
                {
                    attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attachmentGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName)));
                }
                else
                {
                    attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attachmentGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName), null, VersionHistoryID));
                }
            }
            else
            {
                attachmentUrl = ResolveUrl(DocumentHelper.GetAttachmentUrl(attachmentGuid, VersionHistoryID));
            }
            attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

            // Ensure correct URL for non-temporary attachments
            if ((OriginalNodeSiteName != SiteContext.CurrentSiteName) && (documentId > 0))
            {
                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "sitename", OriginalNodeSiteName);
            }

            // Add latest version requirement for live site
            if (IsLiveSite && (documentId > 0))
            {
                // Add requirement for latest version of files for current document
                string newparams = "latestfordocid=" + documentId;
                newparams += "&hash=" + ValidationHelper.GetHashString("d" + documentId);

                attachmentUrl += "&" + newparams;
            }

            // Optionally trim attachment name
            string attachmentName = TextHelper.LimitLength(attName, ATTACHMENT_NAME_LIMIT);

            // Tooltip
            string tooltip = null;
            if (ShowTooltip)
            {
                string title       = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "AttachmentTitle"), string.Empty);
                string description = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "AttachmentDescription"), string.Empty);
                int    imageWidth  = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "AttachmentImageWidth"), 0);
                int    imageHeight = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "AttachmentImageHeight"), 0);

                tooltip = UIHelper.GetTooltipAttributes(attachmentUrl, imageWidth, imageHeight, title, attachmentName, attachmentExt, description, null, 300);
            }

            // Icon
            string imageTag = UIHelper.GetFileIcon(Page, attachmentExt);

            if (isImage)
            {
                return(String.Format("<a class=\"cms-icon-link\" href=\"#\" onclick=\"javascript: window.open('{0}'); return false;\"><span id=\"{1}\" {2}>{3}{4}</span></a>", attachmentUrl, attachmentGuid, tooltip, imageTag, attachmentName));
            }
            else
            {
                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "disposition", "attachment");

                // NOTE: OnClick here is needed to avoid loader to show because even for download links, the pageUnload event is fired
                return(String.Format("<a class=\"cms-icon-link\" onclick=\"javascript: {5}\" href=\"{0}\"><span id=\"{1}\" {2}>{3}{4}</span></a>", attachmentUrl, attachmentGuid, tooltip, imageTag, attachmentName, ScriptHelper.GetDisableProgressScript()));
            }
        }

        case "attachmentsize":
            long size = ValidationHelper.GetLong(parameter, 0);
            return(DataHelper.GetSizeString(size));
        }

        return(parameter);
    }
    /// <summary>
    /// Updates parameters used by Edit button when displaying image editor.
    /// </summary>
    /// <param name="attachmentGuidString">GUID identifying attachment</param>
    private void UpdateEditParameters(string attachmentGuidString)
    {
        if (ShowTooltip)
        {
            // Try to get attachment GUID
            var attGuid = ValidationHelper.GetGuid(attachmentGuidString, Guid.Empty);
            if (attGuid != Guid.Empty)
            {
                // Get attachment
                AttachmentInfo attInfo = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attGuid, SiteName);
                if (attInfo != null)
                {
                    string attName    = attInfo.AttachmentName;
                    int    documentId = DocumentID;

                    // Get attachment URL
                    string attachmentUrl;

                    if (Node != null)
                    {
                        if (IsLiveSite && (documentId > 0))
                        {
                            attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName)));
                        }
                        else
                        {
                            attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetAttachmentUrl(attGuid, URLHelper.GetSafeFileName(attName, SiteContext.CurrentSiteName), null, VersionHistoryID));
                        }
                    }
                    else
                    {
                        attachmentUrl = ResolveUrl(DocumentHelper.GetAttachmentUrl(attGuid, VersionHistoryID));
                    }
                    attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                    // Ensure correct URL for non-temporary attachments
                    if ((OriginalNodeSiteName != SiteContext.CurrentSiteName) && (documentId > 0))
                    {
                        attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "sitename", OriginalNodeSiteName);
                    }

                    // Generate new tooltip command
                    string newToolTip  = null;
                    string title       = attInfo.AttachmentTitle;
                    string description = attInfo.AttachmentDescription;

                    // Optionally trim attachment name
                    string attachmentName = TextHelper.LimitLength(attInfo.AttachmentName, ATTACHMENT_NAME_LIMIT);
                    int    imageWidth     = attInfo.AttachmentImageWidth;
                    int    imageHeight    = attInfo.AttachmentImageHeight;
                    bool   isImage        = ImageHelper.IsImage(attInfo.AttachmentExtension);

                    int    tooltipWidth = 300;
                    string url          = isImage ? attachmentUrl : null;

                    string tooltipBody = UIHelper.GetTooltip(url, imageWidth, imageHeight, title, attachmentName, description, null, ref tooltipWidth);
                    if (!string.IsNullOrEmpty(tooltipBody))
                    {
                        newToolTip = String.Format("Tip('{0}', WIDTH, -300)", tooltipBody);
                    }

                    // Get update script
                    string updateScript = String.Format("$j(\"#{0}\").attr('onmouseover', '').unbind('mouseover').mouseover(function(){{ {1} }});", attGuid, newToolTip);

                    // Execute update
                    ScriptHelper.RegisterStartupScript(Page, typeof(Page), "AttachmentUpdateEdit", ScriptHelper.GetScript(updateScript));
                }
            }
        }
    }
Ejemplo n.º 11
0
    protected void libraryMenuElem_OnReloadData(object sender, EventArgs e)
    {
        string[] parameters = ValidationHelper.GetString(libraryMenuElem.Parameter, string.Empty).Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
        if (parameters.Length == 2)
        {
            // Parse identifier and document culture from library parameter
            int    nodeId      = ValidationHelper.GetInteger(parameters[0], 0);
            string cultureCode = ValidationHelper.GetString(parameters[1], string.Empty);

            // Get document using based on node identifier and culture
            TreeNode node = DocumentHelper.GetDocument(nodeId, cultureCode, TreeProvider);

            bool contextMenuVisible    = false;
            bool localizeVisible       = false;
            bool editVisible           = false;
            bool uploadVisible         = false;
            bool copyVisible           = false;
            bool deleteVisible         = false;
            bool openVisible           = false;
            bool propertiesVisible     = false;
            bool permissionsVisible    = false;
            bool versionHistoryVisible = false;

            bool checkOutVisible         = false;
            bool checkInVisible          = false;
            bool undoCheckoutVisible     = false;
            bool submitToApprovalVisible = false;
            bool rejectVisible           = false;
            bool archiveVisible          = false;

            if ((node != null) && (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed))
            {
                // Get original node (in case of linked documents)
                TreeNode originalNode = TreeProvider.GetOriginalNode(node);

                string documentType           = ValidationHelper.GetString(node.GetValue("DocumentType"), string.Empty);
                string siteName               = CMSContext.CurrentSiteName;
                string currentDocumentCulture = CMSContext.CurrentDocumentCulture.CultureCode;

                if (CMSContext.CurrentSiteID != originalNode.NodeSiteID)
                {
                    SiteInfo si = SiteInfoProvider.GetSiteInfo(originalNode.NodeSiteID);
                    siteName = si.SiteName;
                }

                // Get permissions
                const bool authorizedToRead              = true;
                bool       authorizedToDelete            = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Delete) == AuthorizationResultEnum.Allowed);
                bool       authorizedToModify            = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed);
                bool       authorizedCultureToModify     = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify, false) == AuthorizationResultEnum.Allowed) && TreeSecurityProvider.HasUserCultureAllowed(NodePermissionsEnum.Modify, currentDocumentCulture, CMSContext.CurrentUser, siteName);
                bool       authorizedToModifyPermissions = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed);
                bool       authorizedToCreate            = CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(node.NodeParentID, node.NodeClassName);
                bool       allowEditByCurrentUser        = false;

                // Hide menu when user has no 'Read' permissions on document
                libraryMenuElem.Visible = authorizedToRead;

                // First evaluation of control's visibility
                bool differentCulture = (string.Compare(node.DocumentCulture, currentDocumentCulture, StringComparison.InvariantCultureIgnoreCase) != 0);
                localizeVisible       = differentCulture && authorizedToCreate && authorizedCultureToModify;
                uploadVisible         = authorizedToModify;
                copyVisible           = authorizedToCreate && authorizedToModify;
                deleteVisible         = authorizedToDelete;
                openVisible           = authorizedToRead;
                propertiesVisible     = authorizedToModify;
                permissionsVisible    = authorizedToModifyPermissions;
                versionHistoryVisible = authorizedToModify;
                editVisible           = authorizedToModify && CMSContext.IsWebDAVEnabled(CMSContext.CurrentSiteName) && RequestHelper.IsWindowsAuthentication() && WebDAVSettings.IsExtensionAllowedForEditMode(documentType, CMSContext.CurrentSiteName);

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

                if ((wi != null) && authorizedToModify)
                {
                    bool autoPublishChanges = wi.WorkflowAutoPublishChanges;
                    // Get current step info, do not update document
                    WorkflowStepInfo si = WorkflowManager.GetStepInfo(node, false) ?? WorkflowManager.GetFirstWorkflowStep(node, wi);

                    bool canApprove = true;

                    // If license does not allow custom steps, 'can approve' check is meaningless
                    if (WorkflowInfoProvider.IsCustomStepAllowed())
                    {
                        canApprove = WorkflowManager.CanUserApprove(node, CMSContext.CurrentUser);
                    }

                    // Get name of current workflow step
                    string stepName             = si.StepName.ToLower();
                    bool   useCheckinCheckout   = wi.UseCheckInCheckOut(CMSContext.CurrentSiteName);
                    int    nodeCheckedOutByUser = node.DocumentCheckedOutByUserID;
                    bool   nodeIsCheckedOut     = (nodeCheckedOutByUser != 0);
                    bool   allowEdit            = canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived");

                    // If document is checked in
                    if (nodeIsCheckedOut)
                    {
                        // If checked out by current user, add the check-in button and undo checkout button
                        if (nodeCheckedOutByUser == CMSContext.CurrentUser.UserID)
                        {
                            undoCheckoutVisible    = true;
                            checkInVisible         = true;
                            allowEditByCurrentUser = allowEdit;
                        }
                    }
                    else
                    {
                        // Hide check-out menu item if user can't apporve or document is in specific step
                        if (allowEdit)
                        {
                            // If site uses check-out / check-in
                            if (useCheckinCheckout)
                            {
                                checkOutVisible = true;
                            }
                            else
                            {
                                allowEditByCurrentUser = true;
                            }
                        }
                    }

                    rejectVisible           = canApprove && !nodeIsCheckedOut && (stepName != "edit") && (stepName != "published") && (stepName != "archived") && !autoPublishChanges;
                    submitToApprovalVisible = (canApprove || ((stepName == "edit") && authorizedToRead)) && !nodeIsCheckedOut && (stepName != "published") && (stepName != "archived") && !autoPublishChanges;
                    archiveVisible          = canApprove && !nodeIsCheckedOut && (stepName == "published");
                }
                else
                {
                    allowEditByCurrentUser = true;
                }

                // Check whether the document is not checked out by another user
                editVisible   &= allowEditByCurrentUser;
                uploadVisible &= allowEditByCurrentUser;

                string parameterScript = "GetContextMenuParameter('" + libraryMenuElem.MenuID + "')";

                // Initialize edit menu item
                Guid attachmentGuid = ValidationHelper.GetGuid(node.GetValue("FileAttachment"), Guid.Empty);

                // If attachment field doesn't allow empty value and the value is empty
                if ((FieldInfo != null) && !FieldInfo.AllowEmpty && (attachmentGuid == Guid.Empty))
                {
                    submitToApprovalVisible = false;
                    archiveVisible          = false;
                    checkInVisible          = false;
                }

                // Get attachment
                AttachmentInfo ai = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, siteName, false);

                Panel previousPanel = null;
                Panel currentPanel  = pnlEdit;

                if (editVisible)
                {
                    if (ai != null)
                    {
                        // Load WebDAV edit control and initialize it
                        WebDAVEditControl editAttachment = Page.LoadControl("~/CMSModules/WebDAV/Controls/AttachmentWebDAVEditControl.ascx") as WebDAVEditControl;

                        if (editAttachment != null)
                        {
                            editAttachment.ID                  = "editAttachment";
                            editAttachment.NodeAliasPath       = node.NodeAliasPath;
                            editAttachment.NodeCultureCode     = node.DocumentCulture;
                            editAttachment.AttachmentFieldName = "FileAttachment";
                            editAttachment.FileName            = ai.AttachmentName;
                            editAttachment.IsLiveSite          = IsLiveSite;
                            editAttachment.UseImageButton      = true;
                            editAttachment.LabelText           = GetString("general.edit");
                            editAttachment.CssClass            = "Icon";
                            editAttachment.LabelCssClass       = "Name";
                            editAttachment.RefreshScript       = JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'WebDAVRefresh');";
                            // Set Group ID for live site
                            editAttachment.GroupID = IsLiveSite ? node.GetIntegerValue("NodeGroupID") : 0;
                            editAttachment.ReloadData(true);

                            pnlEditPadding.Controls.Add(editAttachment);
                            pnlEditPadding.CssClass = editAttachment.EnabledResult ? "ItemPadding" : "ItemPaddingDisabled";
                        }
                    }
                    else
                    {
                        editVisible = false;
                        openVisible = false;
                    }
                }

                previousPanel = currentPanel;
                currentPanel  = pnlUpload;

                // Initialize upload menu item
                if (authorizedToModify)
                {
                    string uploaderImg  = "<img class=\"UploaderImage\" src=\"" + GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Upload.png", IsLiveSite) + "\" alt=\"" + GetString("general.update") + "\" />";
                    string uploaderText = "<span class=\"UploaderText\">" + GetString("general.update") + "</span>";

                    StringBuilder uploaderInnerHtml = new StringBuilder();

                    bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());
                    if (isRTL)
                    {
                        uploaderInnerHtml.Append(uploaderText);
                        uploaderInnerHtml.Append(uploaderImg);
                    }
                    else
                    {
                        uploaderInnerHtml.Append(uploaderImg);
                        uploaderInnerHtml.Append(uploaderText);
                    }

                    // Initialize direct file uploader
                    updateAttachment.InnerDivHtml             = uploaderInnerHtml.ToString();
                    updateAttachment.InnerDivClass            = "LibraryContextUploader";
                    updateAttachment.DocumentID               = node.DocumentID;
                    updateAttachment.ParentElemID             = ClientID;
                    updateAttachment.SourceType               = MediaSourceEnum.Attachment;
                    updateAttachment.AttachmentGUIDColumnName = "FileAttachment";
                    updateAttachment.DisplayInline            = true;
                    updateAttachment.IsLiveSite               = IsLiveSite;

                    // Set allowed extensions
                    if ((FieldInfo != null) && ValidationHelper.GetString(FieldInfo.Settings["extensions"], "") == "custom")
                    {
                        // Load allowed extensions
                        updateAttachment.AllowedExtensions = ValidationHelper.GetString(FieldInfo.Settings["allowed_extensions"], "");
                    }
                    else
                    {
                        // Use site settings
                        updateAttachment.AllowedExtensions = SettingsKeyProvider.GetStringValue(siteName + ".CMSUploadExtensions");
                    }

                    updateAttachment.ReloadData();
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = currentPanel;
                currentPanel  = pnlLocalize;

                // Initialize localize menu item
                if (localizeVisible)
                {
                    lblLocalize.RefreshText();
                    imgLocalize.AlternateText = lblLocalize.Text;
                    imgLocalize.ImageUrl      = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Localize.png", IsLiveSite);
                    pnlLocalize.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Localize');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = null;
                currentPanel  = pnlCopy;

                // Initialize copy menu item
                if (copyVisible)
                {
                    lblCopy.RefreshText();
                    imgCopy.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Copy.png", IsLiveSite);
                    pnlCopy.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ",'Copy');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = currentPanel;
                currentPanel  = pnlDelete;

                // Initialize delete menu item
                if (deleteVisible)
                {
                    lblDelete.RefreshText();
                    imgDelete.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Delete.png", IsLiveSite);
                    pnlDelete.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Delete');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = currentPanel;
                currentPanel  = pnlOpen;

                // Initialize open menu item
                if (openVisible)
                {
                    lblOpen.RefreshText();
                    imgOpen.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Open.png", IsLiveSite);
                    if (ai != null)
                    {
                        // Get document URL
                        string attachmentUrl = CMSContext.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(node.NodeGUID, node.NodeAlias));
                        if (authorizedToModify)
                        {
                            attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(node.DocumentID, string.Empty));
                            attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + node.DocumentID));
                        }
                        attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                        if (!string.IsNullOrEmpty(attachmentUrl))
                        {
                            pnlOpen.Attributes.Add("onclick", "location.href = " + ScriptHelper.GetString(attachmentUrl) + ";");
                        }
                    }
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = null;
                currentPanel  = pnlProperties;

                // Initialize properties menu item
                lblProperties.RefreshText();
                imgProperties.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Properties.png", IsLiveSite);
                pnlProperties.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Properties');");
                SetupPanelClasses(currentPanel, previousPanel);

                previousPanel = currentPanel;
                currentPanel  = pnlPermissions;

                // Initialize permissions menu item
                lblPermissions.RefreshText();
                imgPermissions.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Permissions.png", IsLiveSite);
                pnlPermissions.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Permissions');");
                SetupPanelClasses(currentPanel, previousPanel);

                previousPanel = currentPanel;
                currentPanel  = pnlVersionHistory;

                // Initialize version history menu item
                lblVersionHistory.RefreshText();
                imgVersionHistory.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/VersionHistory.png", IsLiveSite);
                pnlVersionHistory.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'VersionHistory');");
                SetupPanelClasses(currentPanel, previousPanel);

                previousPanel = null;
                currentPanel  = pnlCheckOut;

                // Initialize checkout menu item
                if (checkOutVisible)
                {
                    lblCheckOut.RefreshText();
                    imgCheckOut.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckOut.png", IsLiveSite);
                    pnlCheckOut.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckOut');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = currentPanel;
                currentPanel  = pnlCheckIn;

                // Initialize checkin menu item
                if (checkInVisible)
                {
                    lblCheckIn.RefreshText();
                    imgCheckIn.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckIn.png", IsLiveSite);
                    pnlCheckIn.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckIn');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = currentPanel;
                currentPanel  = pnlUndoCheckout;

                // Initialize undo checkout menu item
                if (undoCheckoutVisible)
                {
                    lblUndoCheckout.RefreshText();
                    imgUndoCheckout.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/UndoCheckout.png", IsLiveSite);
                    pnlUndoCheckout.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'UndoCheckout');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = currentPanel;
                currentPanel  = pnlSubmitToApproval;

                // Initialize submit to approval / publish menu item
                if (submitToApprovalVisible)
                {
                    if (wi != null)
                    {
                        // Get next step info
                        WorkflowStepInfo nsi = WorkflowManager.GetNextStepInfo(node);
                        if (nsi.StepName.ToLower() == "published")
                        {
                            // Set 'Publish' label
                            lblSubmitToApproval.ResourceString = "general.publish";
                        }
                    }

                    lblSubmitToApproval.RefreshText();
                    imgSubmitToApproval.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/SubmitToApproval.png", IsLiveSite);
                    pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'SubmitToApproval');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = currentPanel;
                currentPanel  = pnlReject;

                // Initialize reject menu item
                if (rejectVisible)
                {
                    lblReject.RefreshText();
                    imgReject.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Reject.png", IsLiveSite);
                    pnlReject.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Reject');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                previousPanel = currentPanel;
                currentPanel  = pnlArchive;

                // Initialize archive menu item
                if (archiveVisible)
                {
                    lblArchive.RefreshText();
                    imgArchive.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Archive.png", IsLiveSite);
                    pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Archive');");
                    SetupPanelClasses(currentPanel, previousPanel);
                }

                // Set up visibility of menu items
                pnlLocalize.Visible       = localizeVisible;
                pnlUpload.Visible         = uploadVisible;
                pnlDelete.Visible         = deleteVisible;
                pnlCopy.Visible           = copyVisible;
                pnlOpen.Visible           = openVisible;
                pnlProperties.Visible     = propertiesVisible;
                pnlPermissions.Visible    = permissionsVisible;
                pnlVersionHistory.Visible = versionHistoryVisible;
                pnlEdit.Visible           = editVisible;

                pnlCheckOut.Visible         = checkOutVisible;
                pnlCheckIn.Visible          = checkInVisible;
                pnlUndoCheckout.Visible     = undoCheckoutVisible;
                pnlSubmitToApproval.Visible = submitToApprovalVisible;
                pnlReject.Visible           = rejectVisible;
                pnlArchive.Visible          = archiveVisible;

                // Set up visibility of whole menu
                contextMenuVisible = true;
            }

            // Set up visibility of separators
            bool firstGroupVisible  = editVisible || uploadVisible || localizeVisible;
            bool secondGroupVisible = copyVisible || deleteVisible || openVisible;
            bool thirdGroupVisible  = propertiesVisible || permissionsVisible || versionHistoryVisible;
            bool fourthGroupVisible = checkOutVisible || checkInVisible || undoCheckoutVisible || submitToApprovalVisible || rejectVisible || archiveVisible;

            pnlSep1.Visible = firstGroupVisible && secondGroupVisible;
            pnlSep2.Visible = secondGroupVisible && thirdGroupVisible;
            pnlSep3.Visible = thirdGroupVisible && fourthGroupVisible;

            // Setup 'No action available' menu item
            pnlNoAction.Visible = !contextMenuVisible;
            lblNoAction.RefreshText();
        }
    }
Ejemplo n.º 12
0
    protected object gridDocuments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        sourceName = sourceName.ToLowerCSafe();
        DataRowView drv = null;
        bool        modifyPermission = true;
        string      documentCulture  = null;

        switch (sourceName)
        {
        case "documentname":
            drv = parameter as DataRowView;
            string documentName        = null;
            string encodedDocumentName = null;
            string documentType        = null;
            documentCulture = ValidationHelper.GetString(drv.Row["DocumentCulture"], string.Empty);
            string alias           = ValidationHelper.GetString(drv.Row["NodeAlias"], string.Empty);
            int    nodeId          = ValidationHelper.GetInteger(drv.Row["NodeID"], 0);
            int    documentId      = ValidationHelper.GetInteger(drv.Row["DocumentID"], 0);
            bool   isLinked        = (ValidationHelper.GetInteger(drv["NodeLinkedNodeID"], 0) != 0);
            Guid   nodeGuid        = ValidationHelper.GetGuid(drv.Row["NodeGUID"], Guid.Empty);
            string fileDescription = ValidationHelper.GetString(drv.Row["FileDescription"], string.Empty);
            Guid   fileAttachment  = ValidationHelper.GetGuid(drv.Row["FileAttachment"], Guid.Empty);

            // Get permissions flags
            modifyPermission = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Modify, documentCulture);
            bool modifyCulturePermission     = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Modify, PreferredCultureCode);
            bool deletePermission            = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Delete, documentCulture);
            bool modifyPermissionsPermission = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.ModifyPermissions, documentCulture);
            bool readPermission = !CheckPermissions || TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Read, documentCulture);

            if (modifyPermission)
            {
                documentName = ValidationHelper.GetString(drv.Row["DocumentName"], string.Empty);
                documentType = ValidationHelper.GetString(drv.Row["DocumentType"], string.Empty);
            }
            else
            {
                documentName = ValidationHelper.GetString(drv.Row["PublishedDocumentName"], string.Empty);
                documentType = ValidationHelper.GetString(drv.Row["PublishedDocumentType"], string.Empty);
            }

            encodedDocumentName = HTMLHelper.HTMLEncode(documentName);

            string fileTypeIcon = UIHelper.GetFileIcon(Page, documentType, tooltip: HTMLHelper.HTMLEncode(documentType));
            string flagIcon     = null;
            if (documentCulture.ToLowerCSafe() != PreferredCultureCode.ToLowerCSafe())
            {
                flagIcon = "<img class=\"Icon\" src=\"" + GetFlagIconUrl(documentCulture, "16x16") + "\" alt=\"" + HTMLHelper.HTMLEncode(documentCulture) + "\" />";
            }

            string menuParameter = ScriptHelper.GetString(nodeId + "|" + documentCulture);

            string attachmentName = encodedDocumentName;

            string toolTip = UIHelper.GetTooltipAttributes(null, 0, 0, null, null, null, fileDescription, null, 300);

            // Generate link to open document
            if (fileAttachment != Guid.Empty)
            {
                // Get document URL
                string attachmentUrl = AuthenticationHelper.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(nodeGuid, alias));
                if (modifyPermission)
                {
                    attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(documentId, string.Empty));
                    attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + documentId));
                }
                attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                if (!string.IsNullOrEmpty(attachmentUrl))
                {
                    attachmentName = "<a href=\"" + HTMLHelper.EncodeForHtmlAttribute(attachmentUrl) + "\" " + toolTip + ">" + encodedDocumentName + "</a> ";
                }
            }
            else
            {
                attachmentName = "<span" + toolTip + ">" + encodedDocumentName + "</span>";
            }

            // Add linked flag
            if (isLinked)
            {
                attachmentName += DocumentHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link);
            }

            bool showContextMenu = readPermission && (modifyPermission || modifyPermissionsPermission || deletePermission || (IsAuthorizedToCreate && modifyCulturePermission));
            // Generate row with icons, hover action and context menu
            StringBuilder contextMenuString = new StringBuilder();
            contextMenuString.Append("<table>");
            contextMenuString.Append("<tr>");

            if (showContextMenu)
            {
                contextMenuString.Append(ContextMenuContainer.GetStartTag("libraryMenu_" + arrowContextMenu.ClientID, menuParameter, false, HtmlTextWriterTag.Td, "ArrowIcon", null));
                contextMenuString.Append("<a class=\"btn-unigrid-action\"><i class=\"icon-ellipsis\"></i></a>");
                contextMenuString.Append(ContextMenuContainer.GetEndTag(HtmlTextWriterTag.Td));
            }
            else
            {
                contextMenuString.Append("<td class=\"NoIcon\">&nbsp;</td>");
            }

            if (showContextMenu)
            {
                contextMenuString.Append(ContextMenuContainer.GetStartTag("libraryMenu_" + rowContextMenu.ClientID, menuParameter, true, HtmlTextWriterTag.Td, "FileTypeIcon", null));
            }
            else
            {
                contextMenuString.Append("<td class=\"FileTypeIcon\">");
            }
            contextMenuString.Append(fileTypeIcon);
            contextMenuString.Append(ContextMenuContainer.GetEndTag(HtmlTextWriterTag.Td));

            if (showContextMenu)
            {
                contextMenuString.Append(ContextMenuContainer.GetStartTag("libraryMenu_" + rowContextMenu.ClientID, menuParameter, true, HtmlTextWriterTag.Td, "RowContent", "width: 100%;"));
            }
            else
            {
                contextMenuString.Append("<td class=\"RowContent\" style=\"width: 100%;\">");
            }
            contextMenuString.Append(attachmentName);
            contextMenuString.Append(ContextMenuContainer.GetEndTag(HtmlTextWriterTag.Td));

            if (!string.IsNullOrEmpty(flagIcon))
            {
                contextMenuString.Append(ContextMenuContainer.GetStartTag("libraryMenu_" + rowContextMenu.ClientID, menuParameter, true, HtmlTextWriterTag.Td, "FlagIcon", null));
                contextMenuString.Append(flagIcon);
                contextMenuString.Append(ContextMenuContainer.GetEndTag(HtmlTextWriterTag.Td));
            }
            contextMenuString.Append("  </tr>");
            contextMenuString.Append("</table>");
            return(contextMenuString.ToString());

        case "modifiedwhen":
        case "modifiedwhentooltip":
            if (string.IsNullOrEmpty(parameter.ToString()))
            {
                return(string.Empty);
            }
            else
            {
                // Handle time zones
                DateTime modifiedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME);

                if (sourceName == "modifiedwhen")
                {
                    if (IsLiveSite)
                    {
                        return(TimeZoneMethods.ConvertDateTime(modifiedWhen, this));
                    }
                    else
                    {
                        return(TimeZoneHelper.GetCurrentTimeZoneDateTimeString(modifiedWhen, CurrentUser, CurrentSite, out usedTimeZone));
                    }
                }
                else
                {
                    if (!IsLiveSite)
                    {
                        if (TimeZoneHelper.TimeZonesEnabled && (usedTimeZone == null))
                        {
                            TimeZoneHelper.GetCurrentTimeZoneDateTimeString(modifiedWhen, CurrentUser, CurrentSite, out usedTimeZone);
                        }
                        return(TimeZoneHelper.GetUTCLongStringOffset(usedTimeZone));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

        case "status":
            string stepName = string.Empty;
            string toReturn = string.Empty;

            // Extract datarow
            drv      = parameter as DataRowView;
            stepName = GetString("general.dash");
            TreeNode node = DocumentHelper.GetDocument(ValidationHelper.GetInteger(drv["DocumentID"], 0), TreeProvider);
            if (node != null)
            {
                var step = node.WorkflowStep;
                if (step != null)
                {
                    stepName = step.StepDisplayName;
                }
            }
            // Gain desired values from datarow view
            int checkedOutByUserId = ValidationHelper.GetInteger(drv["DocumentCheckedOutByUserID"], 0);
            documentCulture  = ValidationHelper.GetString(drv.Row["DocumentCulture"], string.Empty);
            modifyPermission = TreeSecurityProvider.CheckPermission(drv.Row, NodePermissionsEnum.Modify, documentCulture);

            // Add 'checked out' icon
            if ((checkedOutByUserId > 0) && modifyPermission)
            {
                toReturn = " " + DocumentHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.CheckedOut);
            }

            toReturn = stepName + toReturn;
            return(toReturn);
        }
        return(parameter);
    }