/// <summary>
    /// UniGrid external data bound.
    /// </summary>
    protected object GridDocsOnExternalDataBound(object sender, string sourceName, object parameter)
    {
        string      attName       = null;
        string      attachmentExt = null;
        DataRowView drv           = null;

        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 disabled image
            ImageButton imgUpdate = new ImageButton();
            imgUpdate.ID         = "imgUpdate";
            imgUpdate.PreRender += imgUpdate_PreRender;
            pnlBlock.Controls.Add(imgUpdate);

            // 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.ImageUrl            = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/upload.png"));
                dfuElem.ImageHeight         = 16;
                dfuElem.ImageWidth          = 16;
                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.Width             = 16;
                dfuElem.Height            = 16;
                dfuElem.MaxNumberToUpload = 1;

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

            attName       = ValidationHelper.GetString(drv["AttachmentName"], string.Empty);
            attachmentExt = ValidationHelper.GetString(drv["AttachmentExtension"], string.Empty);

            int  nodeGroupId       = (Node != null) ? Node.GetIntegerValue("NodeGroupID") : 0;
            bool displayGroupAdmin = true;

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

            // Check if WebDAV allowed by the form
            bool allowWebDAV = (Form == null) ? true : Form.AllowWebDAV;

            // Add WebDAV edit control
            if (allowWebDAV && CMSContext.IsWebDAVEnabled(SiteName) && RequestHelper.IsWindowsAuthentication() && (FormGUID == Guid.Empty) && WebDAVSettings.IsExtensionAllowedForEditMode(attachmentExt, SiteName) && displayGroupAdmin)
            {
                // Dynamically load control
                WebDAVEditControl webdavElem = Page.LoadUserControl("~/CMSModules/WebDAV/Controls/AttachmentWebDAVEditControl.ascx") as WebDAVEditControl;

                // Set editor's properties
                if (webdavElem != null)
                {
                    webdavElem.ID = "webdavElem" + DocumentID;

                    // Ensure form identification
                    if ((Form != null) && (Form.Parent != null))
                    {
                        webdavElem.FormID = Form.Parent.ClientID;
                    }
                    webdavElem.PreRender      += webdavElem_PreRender;
                    webdavElem.SiteName        = SiteName;
                    webdavElem.FileName        = attName;
                    webdavElem.NodeAliasPath   = Node.NodeAliasPath;
                    webdavElem.NodeCultureCode = Node.DocumentCulture;
                    if (FieldInfo != null)
                    {
                        webdavElem.AttachmentFieldName = FieldInfo.Name;
                    }

                    // Set Group ID for live site
                    webdavElem.GroupID    = IsLiveSite ? nodeGroupId : 0;
                    webdavElem.IsLiveSite = IsLiveSite;

                    // Align left if WebDAV is enabled and windows authentication is enabled
                    bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());
                    pnlBlock.Style.Add("text-align", isRTL ? "right" : "left");

                    pnlBlock.Controls.Add(webdavElem);
                }
            }

            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 ImageButton)
            {
                ImageButton img = (ImageButton)sender;
                if (createTempAttachment)
                {
                    img.Visible = false;
                }
                else
                {
                    img.AlternateText = extension;
                    img.ToolTip       = attachmentGuid.ToString();
                    img.PreRender    += img_PreRender;
                }
            }
            break;

        case "delete":
            if (sender is ImageButton)
            {
                ImageButton imgDelete = (ImageButton)sender;
                // Turn off validation
                imgDelete.CausesValidation = false;
                imgDelete.PreRender       += imgDelete_PreRender;
                // Explicitly initialize confirmation
                imgDelete.OnClientClick = "if(DeleteConfirmation() == false){return false;}";
            }
            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);
            string iconUrl = GetFileIconUrl(attachmentExt, "List");

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

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

            // Ensure correct URL
            if (OriginalNodeSiteName != CMSContext.CurrentSiteName)
            {
                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 imageTag = "<img class=\"Icon\" src=\"" + iconUrl + "\" alt=\"" + attachmentName + "\" />";
            if (isImage)
            {
                return("<a href=\"#\" onclick=\"javascript: window.open('" + attachmentUrl + "'); return false;\"><span " + tooltip + ">" + imageTag + attachmentName + "</span></a>");
            }
            else
            {
                return("<a href=\"" + attachmentUrl + "\"><span id=\"" + attachmentGuid + "\" " + tooltip + ">" + imageTag + attachmentName + "</span></a>");
            }
        }

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

        return(parameter);
    }
Beispiel #2
0
    protected object gridFiles_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        GridViewRow gvr      = null;
        DataRowView drv      = null;
        string      fileGuid = null;

        switch (sourceName.ToLower())
        {
        case "edit":
            if (sender is ImageButton)
            {
                gvr = (GridViewRow)parameter;
                drv = (DataRowView)gvr.DataItem;

                fileGuid = ValidationHelper.GetString(drv["MetaFileGUID"], "");
                string fileExtension = ValidationHelper.GetString(drv["MetaFileExtension"], "");

                // Initialize properties
                ImageButton btnImageEditor = (ImageButton)sender;
                btnImageEditor.Visible = true;

                // Display button only if 'Modify' is allowed
                if (AllowModify)
                {
                    string query = String.Format("?metafileguid={0}&clientid={1}", fileGuid, ClientID);
                    query = URLHelper.AddUrlParameter(query, "hash", QueryHelper.GetHash(query));

                    // Display button only if metafile is in supported image format
                    if (ImageHelper.IsSupportedByImageEditor(fileExtension))
                    {
                        // Initialize button with script
                        btnImageEditor.Attributes.Add("onclick", String.Format("OpenImageEditor({0}); return false;", ScriptHelper.GetString(query)));
                    }
                    // Non-image metafile
                    else
                    {
                        // Initialize button with script
                        btnImageEditor.Attributes.Add("onclick", String.Format("OpenEditor({0}); return false;", ScriptHelper.GetString(query)));
                    }
                }
                else
                {
                    btnImageEditor.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/editdisabled.png");
                    btnImageEditor.Enabled  = false;
                }
            }
            break;

        case "paste":
            if (sender is ImageButton)
            {
                gvr = (GridViewRow)parameter;
                drv = (DataRowView)gvr.DataItem;

                fileGuid = ValidationHelper.GetString(drv["MetaFileGUID"], "");
                int fileWidth  = ValidationHelper.GetInteger(drv["MetaFileImageWidth"], 0);
                int fileHeight = ValidationHelper.GetInteger(drv["MetaFileImageHeight"], 0);

                ImageButton btnPaste = (ImageButton)sender;
                btnPaste.Visible = AllowPasteAttachments;
                if (AllowPasteAttachments)
                {
                    if ((fileWidth > 0) && (fileHeight > 0))
                    {
                        string appPath = URLHelper.ApplicationPath;
                        if ((appPath == null) || (appPath == "/"))
                        {
                            appPath = String.Empty;
                        }
                        btnPaste.OnClientClick = String.Format("PasteImage('{0}/CMSPages/GetMetaFile.aspx?fileguid={1}'); return false", appPath, fileGuid);
                    }
                    else
                    {
                        btnPaste.Visible = false;
                    }
                }
                else
                {
                    btnPaste.Visible = false;
                }
            }
            break;

        case "delete":
            if (sender is ImageButton)
            {
                ImageButton btnDelete = ((ImageButton)sender);
                btnDelete.Visible = AllowModify;
                if (!AllowModify)
                {
                    btnDelete.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/deletedisabled.png");
                }
            }
            break;

        case "name":
            drv = (DataRowView)parameter;

            string fileName = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileName"), string.Empty);
            fileGuid = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileGUID"), string.Empty);
            string fileExt = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileExtension"), string.Empty);
            string iconUrl = GetFileIconUrl(fileExt, "List");

            bool   isImage = ImageHelper.IsImage(fileExt);
            string fileUrl = String.Format("{0}?fileguid={1}&chset={2}", URLHelper.GetAbsoluteUrl("~/CMSPages/GetMetaFile.aspx"), fileGuid, Guid.NewGuid());

            // Tooltip
            string title       = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileTitle"), string.Empty);;
            string description = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(drv, "MetaFileDescription"), string.Empty);
            int    imageWidth  = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "MetaFileImageWidth"), 0);
            int    imageHeight = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "MetaFileImageHeight"), 0);
            string tooltip     = UIHelper.GetTooltipAttributes(fileUrl, imageWidth, imageHeight, title, fileName, fileExt, description, null, 300);

            // Icon
            string imageTag = String.Format("<img class=\"Icon\" src=\"{0}\" alt=\"{1}\" />", iconUrl, fileName);
            if (isImage)
            {
                return(String.Format("<a href=\"#\" onclick=\"javascript: window.open('{0}'); return false;\"><span id=\"{1}\" {2}>{3}{4}</span></a>", fileUrl, fileGuid, tooltip, imageTag, fileName));
            }
            else
            {
                return(String.Format("<a href=\"{0}\"><span id=\"{1}\" {2}>{3}{4}</span></a>", fileUrl, fileGuid, tooltip, imageTag, fileName));
            }

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

        case "update":
        {
            // Display buttons only if 'Modify' is allowed
            if (AllowModify)
            {
                drv = (DataRowView)parameter;
                Panel pnlBlock = new Panel()
                {
                    ID = "pnlBlock"
                };

                string fileExtension = ValidationHelper.GetString(drv["MetaFileExtension"], null);
                string siteName      = null;

                if (SiteID > 0)
                {
                    SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteID);
                    if (si != null)
                    {
                        siteName = si.SiteName;
                    }
                }
                else
                {
                    siteName = CMSContext.CurrentSiteName;
                }

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

                // Set uploader's properties
                if (dfuElem != null)
                {
                    dfuElem.ID                 = "dfuElem" + ObjectID;
                    dfuElem.SourceType         = MediaSourceEnum.MetaFile;
                    dfuElem.ControlGroup       = "Uploader_" + ObjectID;
                    dfuElem.DisplayInline      = true;
                    dfuElem.ForceLoad          = true;
                    dfuElem.MetaFileID         = ValidationHelper.GetInteger(drv["MetaFileID"], 0);
                    dfuElem.ObjectID           = ObjectID;
                    dfuElem.ObjectType         = ObjectType;
                    dfuElem.Category           = Category;
                    dfuElem.ParentElemID       = ClientID;
                    dfuElem.ImageUrl           = ResolveUrl(GetImageUrl("Design/Controls/DirectUploader/upload.png"));
                    dfuElem.ImageHeight        = 16;
                    dfuElem.ImageWidth         = 16;
                    dfuElem.InsertMode         = false;
                    dfuElem.ParentElemID       = ClientID;
                    dfuElem.IncludeNewItemInfo = true;
                    dfuElem.SiteID             = SiteID;
                    dfuElem.IsLiveSite         = IsLiveSite;
                    // Setting of the direct single mode
                    dfuElem.UploadMode                = MultifileUploaderModeEnum.DirectSingle;
                    dfuElem.Width                     = 16;
                    dfuElem.Height                    = 16;
                    dfuElem.MaxNumberToUpload         = 1;
                    dfuElem.EnableSilverlightUploader = false;

                    pnlBlock.Controls.Add(dfuElem);
                }

                // If the WebDAV is enabled and windows authentication
                if (CMSContext.IsWebDAVEnabled(siteName) && RequestHelper.IsWindowsAuthentication() &&
                    WebDAVSettings.IsExtensionAllowedForEditMode(fileExtension, siteName))
                {
                    // Dynamically load control
                    WebDAVEditControl webDAVElem = Page.LoadControl("~/CMSModules/WebDAV/Controls/MetaFileWebDAVEditControl.ascx") as WebDAVEditControl;

                    // Set editor's properties
                    if (webDAVElem != null)
                    {
                        // Initialize WebDAV control
                        fileGuid = ValidationHelper.GetString(drv["MetaFileGUID"], "");
                        webDAVElem.MetaFileGUID = ValidationHelper.GetGuid(fileGuid, Guid.Empty);
                        webDAVElem.FileName     = ValidationHelper.GetString(drv["MetaFileName"], null);

                        webDAVElem.Enabled = AllowModify;

                        // Initialize general info
                        webDAVElem.ID         = "webDAVElem";
                        webDAVElem.IsLiveSite = IsLiveSite;
                        // Add to panel
                        pnlBlock.Controls.Add(webDAVElem);
                    }
                }

                return(pnlBlock);
            }
            return(null);
        }
        }
        return(parameter);
    }
Beispiel #3
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();
                }
            }
        }
    }
Beispiel #4
0
    /// <summary>
    /// UniGrid external data bound.
    /// </summary>
    protected object gridAttachments_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView rowView       = null;
        string      attName       = null;
        string      attachmentExt = null;

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

                Guid   attGuid    = ValidationHelper.GetGuid(((DataRowView)((GridViewRow)parameter).DataItem).Row["AttachmentGUID"], Guid.Empty);
                string objectType = null;
                int    id         = 0;
                if (VersionHistoryID > 0)
                {
                    objectType = PredefinedObjectType.ATTACHMENTHISTORY;
                }
                else
                {
                    objectType = PredefinedObjectType.ATTACHMENT;
                }
                BaseInfo att = AttachmentHistoryInfoProvider.GetInfoByGuid(objectType, attGuid);
                if (att != null)
                {
                    id = att.Generalized.ObjectID;
                }

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

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

            bool isWebDAVEnabled         = CMSContext.IsWebDAVEnabled(SiteName);
            bool isWindowsAuthentication = RequestHelper.IsWindowsAuthentication();
            pnlBlock.Style.Add("margin", "0 auto");
            pnlBlock.Width = ((isWebDAVEnabled && isWindowsAuthentication) ? 32 : 16);

            // Add disabled image
            ImageButton imgUpdate = new ImageButton {
                ID = "imgUpdate"
            };
            imgUpdate.PreRender += imgUpdate_PreRender;
            pnlBlock.Controls.Add(imgUpdate);

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

            rowView = 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(rowView);
                dfuElem.DisplayInline       = true;
                dfuElem.UploadMode          = MultifileUploaderModeEnum.DirectSingle;
                dfuElem.InnerLoadingDivHtml = "&nbsp;";
                dfuElem.MaxNumberToUpload   = 1;
                dfuElem.Height     = 16;
                dfuElem.Width      = 16;
                dfuElem.PreRender += dfuElem_PreRender;
                pnlBlock.Controls.Add(dfuElem);
            }

            attName       = GetAttachmentName(rowView);
            attachmentExt = GetAttachmentExtension(rowView);

            int nodeGroupId = (Node != null) ? Node.GetIntegerValue("NodeGroupID") : 0;

            // Check if WebDAV allowed by the form
            bool allowWebDAV = (Form == null) || Form.AllowWebDAV;

            // Add WebDAV edit control
            if (allowWebDAV && isWebDAVEnabled && isWindowsAuthentication && (FormGUID == Guid.Empty) && WebDAVSettings.IsExtensionAllowedForEditMode(attachmentExt, SiteName))
            {
                // Dynamically load control
                WebDAVEditControl webdavElem = Page.LoadUserControl("~/CMSModules/WebDAV/Controls/AttachmentWebDAVEditControl.ascx") as WebDAVEditControl;

                // Set editor's properties
                if (webdavElem != null)
                {
                    webdavElem.Enabled = Enabled;
                    webdavElem.ID      = "webdavElem" + DocumentID;

                    // Ensure form identification
                    if ((Form != null) && (Form.Parent != null))
                    {
                        webdavElem.FormID = Form.Parent.ClientID;
                    }
                    webdavElem.SiteName        = SiteName;
                    webdavElem.FileName        = attName;
                    webdavElem.NodeAliasPath   = Node.NodeAliasPath;
                    webdavElem.NodeCultureCode = Node.DocumentCulture;
                    webdavElem.PreRender      += webdavElem_PreRender;

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

                    // Set Group ID for live site
                    webdavElem.GroupID    = IsLiveSite ? nodeGroupId : 0;
                    webdavElem.IsLiveSite = IsLiveSite;

                    // Align left if WebDAV is enabled and windows authentication is enabled
                    bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL());
                    pnlBlock.Style.Add("text-align", isRTL ? "right" : "left");

                    pnlBlock.Controls.Add(webdavElem);
                }
            }
            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);
            ImageButton img       = sender as ImageButton;
            if (img != null)
            {
                img.AlternateText = String.Format("{0}|{1}", extension, guid);
                img.PreRender    += img_PreRender;
            }
            break;

        case "delete":
            ImageButton imgDelete = sender as ImageButton;
            if (imgDelete != null)
            {
                // Turn off validation
                imgDelete.CausesValidation = false;
                imgDelete.PreRender       += imgDelete_PreRender;
                // Explicitly initialize confirmation
                imgDelete.OnClientClick = "if(DeleteConfirmation() == false){return false;}";
            }
            break;

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

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

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

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

            // Get attachment extension
            attachmentExt = GetAttachmentExtension(rowView);
            bool   isImage = ImageHelper.IsImage(attachmentExt);
            string iconUrl = GetFileIconUrl(attachmentExt, "List");

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

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

            // Ensure correct URL
            if (OriginalNodeSiteName != CMSContext.CurrentSiteName)
            {
                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(rowView, "AttachmentTitle"), string.Empty);
                string description = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(rowView, "AttachmentDescription"), string.Empty);
                int    imageWidth  = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(rowView, "AttachmentImageWidth"), 0);
                int    imageHeight = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(rowView, "AttachmentImageHeight"), 0);

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

            // Icon
            string imageTag = String.Format("<img class=\"Icon\" src=\"{0}\" alt=\"{1}\" />", iconUrl, attachmentName);

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

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

        return(parameter);
    }
    /// <summary>
    /// Gets HTML code of rendered DirectFileUploader control.
    /// </summary>
    /// <param name="mfi">Media file information</param>
    public string GetWebDavHTML(MediaFileInfo mfi)
    {
        SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);

        if (si != null)
        {
            // If the WebDAV is enabled and windows authentication and extension is allowed
            if (CMSContext.IsWebDAVEnabled(si.SiteName) && RequestHelper.IsWindowsAuthentication() && WebDAVSettings.IsExtensionAllowedForEditMode(mfi.FileExtension, si.SiteName))
            {
                StringBuilder sb = new StringBuilder();
                using (StringWriter tw = new StringWriter(sb))
                {
                    HtmlTextWriter    hw         = new HtmlTextWriter(tw);
                    WebDAVEditControl wabDavElem = Page.LoadUserControl("~/CMSModules/MediaLibrary/Controls/WebDAV/MediaFileWebDAVEditControl.ascx") as WebDAVEditControl;
                    if (wabDavElem != null)
                    {
                        // Initialize update control
                        innermedia.GetWebDAVEditControl(ref wabDavElem, mfi);
                        wabDavElem.ReloadData(true);
                        wabDavElem.RenderControl(hw);
                    }
                }

                return(sb.ToString());
            }
        }
        return(null);
    }
    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();
        }
    }