예제 #1
0
    /// <summary>
    /// If the document hasn't been checked out, creates a new modified version of the document. If it has, the example modifies the checked out version. Called when the "Edit document" button is pressed.
    /// Expects the "CreateExampleObjects" method and optionally the "CheckOut" method to be run first.
    /// </summary>
    private bool EditDocument()
    {
        TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);

        // Prepare parameters
        string siteName  = CMSContext.CurrentSiteName;
        string aliasPath = "/API-Example";
        string culture   = "en-us";
        bool   combineWithDefaultCulture = false;
        string classNames = TreeProvider.ALL_CLASSNAMES;

        string where = null;
        string orderBy             = null;
        int    maxRelativeLevel    = -1;
        bool   selectOnlyPublished = false;
        string columns             = null;

        // Get the document
        TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree);

        if (node != null)
        {
            WorkflowManager workflowmanager = WorkflowManager.GetInstance(tree);

            // Make sure the document uses workflow
            WorkflowInfo workflow = workflowmanager.GetNodeWorkflow(node);

            if (workflow != null)
            {
                // Check if the workflow uses check-in/check-out
                bool autoCheck = !workflow.UseCheckInCheckOut(CMSContext.CurrentSiteName);

                // Create a new version manager instance
                VersionManager versionmanager = VersionManager.GetInstance(tree);

                // If it does not use check-in/check-out, check out the document automatically
                if (autoCheck)
                {
                    versionmanager.CheckOut(node);
                }

                if (node.IsCheckedOut)
                {
                    // Edit the last version of the document
                    string newName = node.DocumentName.ToLower();

                    node.DocumentName = newName;
                    node.SetValue("MenuItemName", newName);

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

                    // Automatically check in
                    if (autoCheck)
                    {
                        versionmanager.CheckIn(node, null, null);
                    }

                    return(true);
                }
                else
                {
                    apiEditDocument.ErrorMessage = "The document hasn't been checked out.";
                }
            }
            else
            {
                apiEditDocument.ErrorMessage = "The document doesn't use workflow.";
            }
        }

        return(false);
    }
예제 #2
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (CurrentPageInfo != null)
            {
                PageInfo pi = CurrentPageInfo;

                // Make visible, visibility according to the current state will be set later (solves issue with changing visibility during postbacks)
                Visible = true;

                CMSPagePlaceholder parentPlaceHolder = PortalHelper.FindParentPlaceholder(this);

                // Nothing to render, nothing to do
                if ((!DisplayAddButton && !DisplayResetButton) ||
                    ((parentPlaceHolder != null) && (parentPlaceHolder.UsingDefaultPage || (parentPlaceHolder.PageInfo.DocumentID != pi.DocumentID))))
                {
                    Visible = false;
                    return;
                }

                var currentUser = MembershipContext.AuthenticatedUser;
                zoneType = WidgetZoneType.ToEnum <WidgetZoneTypeEnum>();


                // Check security
                if (((zoneType == WidgetZoneTypeEnum.Group) && !currentUser.IsGroupAdministrator(pi.NodeGroupID)) ||
                    ((zoneType == WidgetZoneTypeEnum.User || zoneType == WidgetZoneTypeEnum.Dashboard) && !AuthenticationHelper.IsAuthenticated()))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Displaying - Editor zone only in edit mode, User/Group zone only in Live site/Preview mode
                if (((zoneType == WidgetZoneTypeEnum.Editor) && !PortalManager.ViewMode.IsOneOf(ViewModeEnum.Edit, ViewModeEnum.EditDisabled, ViewModeEnum.EditLive)) ||
                    (((zoneType == WidgetZoneTypeEnum.User) || (zoneType == WidgetZoneTypeEnum.Group)) && !PortalManager.ViewMode.IsOneOf(ViewModeEnum.LiveSite, ViewModeEnum.Preview)) ||
                    ((zoneType == WidgetZoneTypeEnum.Dashboard) && ((PortalManager.ViewMode != ViewModeEnum.DashboardWidgets) || (String.IsNullOrEmpty(PortalContext.DashboardName)))))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Get current document
                TreeNode currentNode = DocumentHelper.GetDocument(pi.DocumentID, TreeProvider);
                if (((zoneType == WidgetZoneTypeEnum.Editor) && (!currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName) || (currentUser.IsAuthorizedPerDocument(currentNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied))))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // If use checkin checkout enabled, check if document is checkout by current user
                if (zoneType == WidgetZoneTypeEnum.Editor)
                {
                    if (currentNode != null)
                    {
                        WorkflowManager wm = WorkflowManager.GetInstance(TreeProvider);
                        // Get workflow info
                        WorkflowInfo wi = wm.GetNodeWorkflow(currentNode);

                        // Check if node is under workflow and if use checkin checkout enabled
                        if ((wi != null) && (wi.UseCheckInCheckOut(SiteContext.CurrentSiteName)))
                        {
                            int checkedOutBy = currentNode.DocumentCheckedOutByUserID;

                            // Check if document is checkout by current user
                            if (checkedOutBy != MembershipContext.AuthenticatedUser.UserID)
                            {
                                Visible      = false;
                                resetAllowed = false;
                                return;
                            }
                        }
                    }
                }

                // Find widget zone
                PageTemplateInfo pti = pi.UsedPageTemplateInfo;

                // ZodeID specified directly
                if (!String.IsNullOrEmpty(WidgetZoneID))
                {
                    zoneInstance = pti.TemplateInstance.GetZone(WidgetZoneID);
                }

                // Zone not find or specified zone is not of correct type
                if ((zoneInstance != null) && (zoneInstance.WidgetZoneType != zoneType))
                {
                    zoneInstance = null;
                }

                // For delete all variants all zones are necessary
                if (parentPlaceHolder != null)
                {
                    var zones = parentPlaceHolder.WebPartZones;
                    if (zones != null)
                    {
                        foreach (CMSWebPartZone zone in zones)
                        {
                            if ((zone.ZoneInstance != null) && (zone.ZoneInstance.WidgetZoneType == zoneType))
                            {
                                zoneInstances.Add(zone.ZoneInstance);
                                if (zoneInstance == null)
                                {
                                    zoneInstance = zone.ZoneInstance;
                                }
                            }
                        }
                    }
                }

                // No suitable zones on the page, nothing to do
                if (zoneInstance == null)
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Adding is enabled
                if (DisplayAddButton)
                {
                    btnAddWidget.Visible = true;
                    btnAddWidget.Text    = GetAddWidgetButtonText();

                    int templateId = 0;
                    if (pi.UsedPageTemplateInfo != null)
                    {
                        templateId = pi.UsedPageTemplateInfo.PageTemplateId;
                    }

                    addScript = (PortalContext.ViewMode == ViewModeEnum.EditLive ? "OEDeactivateWebPartBorder({ webPartSpanId: $cmsj('.OnSiteMenuTable').parent().attr('id').replace('OE_OE_', 'OE_')}, null );" : String.Empty) + "NewWidget(new zoneProperties('" + zoneInstance.ZoneID + "', '" + pi.NodeAliasPath + "', '" + templateId + "')); return false;";
                    btnAddWidget.Attributes.Add("onclick", addScript);
                }

                // Reset is enabled
                if (DisplayResetButton)
                {
                    btnReset.Visible = true;
                    btnReset.Text    = GetResetButtonText();
                    btnReset.Click  += new EventHandler(btnReset_Click);

                    // Add confirmation if required
                    if (ResetConfirmationRequired)
                    {
                        btnReset.Attributes.Add("onclick", "if (!confirm(" + ScriptHelper.GetString(PortalHelper.LocalizeStringForUI("widgets.resetzoneconfirmtext")) + ")) return false;");
                    }
                }

                // Set the panel css clas with dependence on actions zone type
                switch (zoneType)
                {
                // Editor
                case WidgetZoneTypeEnum.Editor:
                    pnlWidgetActions.CssClass = "EditorWidgetActions";
                    break;

                // User
                case WidgetZoneTypeEnum.User:
                    pnlWidgetActions.CssClass = "UserWidgetActions";
                    break;

                // Group
                case WidgetZoneTypeEnum.Group:
                    pnlWidgetActions.CssClass = "GroupWidgetActions";
                    break;
                }
            }
        }
    }
예제 #3
0
    /// <summary>
    /// Creates new document under API Example folder and applies workflow. Called when the "Create document" button is pressed.
    /// Expects the "CreateExampleFolder" and "CreateWorkflowScope" methods to be run first.
    /// </summary>
    private bool CreateDocument()
    {
        // Get the "Versioning without workflow" workflow
        WorkflowInfo workflow = WorkflowInfoProvider.GetWorkflowInfo("versioningWithoutWorkflow");

        if (workflow != null)
        {
            // Workflow is configured to automatically publish changes
            if (workflow.WorkflowAutoPublishChanges)
            {
                // Workflow doesn't use check-in/check-out
                if (!workflow.UseCheckInCheckOut(CurrentSiteName))
                {
                    // Create new tree provider
                    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                    // Prepare parameters
                    string siteName  = SiteContext.CurrentSiteName;
                    string aliasPath = "/API-Example";
                    string culture   = "en-us";
                    bool   combineWithDefaultCulture = false;
                    string classNames = TreeProvider.ALL_CLASSNAMES;
                    string where = null;
                    string orderBy             = null;
                    int    maxRelativeLevel    = -1;
                    bool   selectOnlyPublished = false;
                    string columns             = null;

                    // Get the example folder
                    TreeNode parentNode = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree);

                    if (parentNode != null)
                    {
                        // Create a new node
                        TreeNode node = TreeNode.New("CMS.MenuItem", tree);

                        // Set the required document properties
                        node.DocumentName    = "My new page";
                        node.DocumentCulture = "en-us";

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

                        // Document must be published manually if check-in/check-out is not used
                        node.MoveToPublishedStep();

                        return(true);
                    }
                    else
                    {
                        apiCreateDocument.ErrorMessage = "Example folder was not found";
                    }
                }
                else
                {
                    apiCreateDocument.ErrorMessage = "Workflow 'Versioning without workflow' uses check-in/check-out. You must disable it before you run this example.";
                }
            }
            else
            {
                apiCreateDocument.ErrorMessage = "Workflow 'Versioning without workflow' is not configured to automatically publish changes.";
            }
        }

        return(false);
    }
예제 #4
0
    /// <summary>
    /// Checks out the document. If check-in/check-out is disabled for the default workflow, the example can't be used. Called when the "Check out document" button is pressed.
    /// Expects the "CreateExampleObjects" method to be run first.
    /// </summary>
    private bool CheckOut()
    {
        TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);

        // Prepare parameters
        string siteName  = CMSContext.CurrentSiteName;
        string aliasPath = "/API-Example";
        string culture   = "en-us";
        bool   combineWithDefaultCulture = false;
        string classNames = TreeProvider.ALL_CLASSNAMES;

        string where = null;
        string orderBy             = null;
        int    maxRelativeLevel    = -1;
        bool   selectOnlyPublished = false;
        string columns             = null;

        // Get the document
        TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree);

        if (node != null)
        {
            // Create a new Workflow manager instance
            WorkflowManager workflowmanager = WorkflowManager.GetInstance(tree);

            // Make sure the document uses workflow
            WorkflowInfo workflow = workflowmanager.GetNodeWorkflow(node);

            if (workflow != null)
            {
                // Check if the workflow uses check-in/check-out functionality
                if (workflow.UseCheckInCheckOut(CMSContext.CurrentSiteName))
                {
                    // The document has to be checked in
                    if (!node.IsCheckedOut)
                    {
                        // Create a new version manager instance
                        VersionManager versionmanager = VersionManager.GetInstance(tree);

                        // Check out the document to create a new document version
                        versionmanager.CheckOut(node);

                        return(true);
                    }
                    else
                    {
                        apiCheckOut.ErrorMessage = "The document has already been checked out.";
                    }
                }
                else
                {
                    apiCheckOut.ErrorMessage = "The workflow does not use check-in/check-out. See the \"Edit document\" example, which checks the document out and in automatically.";
                }
            }
            else
            {
                apiCheckOut.ErrorMessage = "The document doesn't use workflow.";
            }
        }

        return(false);
    }
예제 #5
0
    public void ReloadMenu()
    {
        newLink     = (Action == "newlink");
        newDocument = ((Action == "new") || newLink || Action == "newvariant");
        newCulture  = (Action == "newculture");

        if (Action == "newvariant")
        {
            ShowSpellCheck = false;
        }

        MenuItem newItem = null;

        // Create the edit menu
        menuElem.Items.Clear();

        mMenuItems = 0;

        // Save button
        MenuItem saveItem = null;

        if (mShowSave)
        {
            saveItem                   = new MenuItem();
            saveItem.ToolTip           = GetString("EditMenu.Save");
            saveItem.JavascriptCommand = FunctionsPrefix + "SaveDocument(" + NodeID + ");";
            saveItem.ImageAltText      = saveItem.ToolTip;
            saveItem.Text              = GetString("general.save");
            saveItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/save.png");
            saveItem.MouseOverImage    = saveItem.Image;
            saveItem.MouseOverCssClass = "MenuItemEdit";
            saveItem.CssClass          = "MenuItemEdit";
            menuElem.Items.Add(saveItem);
            mMenuItems += 1;
        }

        mWorkflowInfo = "";

        mAllowEdit = true;
        mAllowSave = true;
        bool showDelete = false;

        if (!newDocument)
        {
            if (Node != null && !newCulture)
            {
                bool authorized = true;

                // If the perrmisions should be checked
                if (CheckPermissions)
                {
                    // Check read permissions
                    if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied)
                    {
                        RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), Node.NodeAliasPath));
                    }
                    // Check modify permissions
                    else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
                    {
                        mAllowSave    = false;
                        mWorkflowInfo = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath);
                        authorized    = false;
                    }
                }

                // If authorized
                if (authorized)
                {
                    WorkflowInfo wi = WorkflowMan.GetNodeWorkflow(Node);
                    // If workflow not null, process the workflow information to display the items
                    if (wi != null)
                    {
                        // Get current step info, do not update document
                        WorkflowStepInfo si = null;
                        if (Node.IsPublished && (Node.DocumentCheckedOutVersionHistoryID <= 0))
                        {
                            si = WorkflowStepInfoProvider.GetWorkflowStepInfo("published", wi.WorkflowID);
                        }
                        else
                        {
                            si = WorkflowMan.GetStepInfo(Node, false) ??
                                 WorkflowMan.GetFirstWorkflowStep(Node, wi);
                        }

                        bool allowApproval      = true;
                        bool canApprove         = true;
                        bool autoPublishChanges = wi.WorkflowAutoPublishChanges;

                        // If license does not allow custom steps, can approve check is useless
                        if (WorkflowInfoProvider.IsCustomStepAllowed())
                        {
                            canApprove = WorkflowMan.CanUserApprove(Node, CMSContext.CurrentUser);
                        }

                        string stepName = si.StepName.ToLower();
                        if (!(canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived")))
                        {
                            mAllowSave = false;
                        }

                        bool useCheckInCheckOut = wi.UseCheckInCheckOut(CMSContext.CurrentSiteName);

                        // Check-in, Check-out
                        if (useCheckInCheckOut)
                        {
                            if (!Node.IsCheckedOut)
                            {
                                mAllowSave = false;
                                mAllowEdit = false;

                                // If not checked out, add the check-out button
                                if (mShowCheckOut && (canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived")))
                                {
                                    newItem                   = new MenuItem();
                                    newItem.ToolTip           = GetString("EditMenu.CheckOut");
                                    newItem.JavascriptCommand = FunctionsPrefix + "CheckOut(" + NodeID + ");";
                                    newItem.ImageAltText      = newItem.ToolTip;
                                    newItem.Text              = GetString("EditMenu.IconCheckOut");
                                    newItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/checkout.png");
                                    newItem.MouseOverImage    = newItem.Image;
                                    newItem.MouseOverCssClass = "MenuItemEdit";
                                    newItem.CssClass          = "MenuItemEdit";
                                    menuElem.Items.Add(newItem);
                                    mMenuItems += 1;
                                }
                                // Set workflow info
                                // If not checked out, add the check-out information
                                if (canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived"))
                                {
                                    mWorkflowInfo += GetString("EditContent.DocumentCheckedIn");
                                }
                            }
                        }
                        if (Node.IsCheckedOut)
                        {
                            // If checked out by current user, add the check-in button
                            int checkedOutBy = Node.DocumentCheckedOutByUserID;
                            if (checkedOutBy == CMSContext.CurrentUser.UserID)
                            {
                                if (mShowUndoCheckOut)
                                {
                                    newItem                   = new MenuItem();
                                    newItem.ToolTip           = GetString("EditMenu.UndoCheckout");
                                    newItem.JavascriptCommand = FunctionsPrefix + "UndoCheckOut(" + NodeID + ");";
                                    newItem.ImageAltText      = newItem.ToolTip;
                                    newItem.Text              = GetString("EditMenu.IconUndoCheckout");
                                    newItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/undocheckout.png");
                                    newItem.MouseOverImage    = newItem.Image;
                                    newItem.MouseOverCssClass = "MenuItemEdit";
                                    newItem.CssClass          = "MenuItemEdit";
                                    menuElem.Items.Add(newItem);
                                    mMenuItems += 1;
                                }

                                if (mShowCheckIn)
                                {
                                    newItem                   = new MenuItem();
                                    newItem.ToolTip           = GetString("EditMenu.CheckIn");
                                    newItem.JavascriptCommand = FunctionsPrefix + "CheckIn(" + NodeID + ");";
                                    newItem.ImageAltText      = newItem.ToolTip;
                                    newItem.Text              = GetString("EditMenu.IconCheckIn");
                                    newItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/checkin.png");
                                    newItem.MouseOverImage    = newItem.Image;
                                    newItem.MouseOverCssClass = "MenuItemEdit";
                                    newItem.CssClass          = "MenuItemEdit";
                                    menuElem.Items.Add(newItem);
                                    mMenuItems += 1;
                                }

                                // Set workflow info
                                mWorkflowInfo += GetString("EditContent.DocumentCheckedOut");
                            }
                            else
                            {
                                mAllowSave = false;
                                mAllowEdit = false;

                                string userName = UserInfoProvider.GetUserNameById(checkedOutBy);
                                // Set workflow info
                                mWorkflowInfo += String.Format(GetString("EditContent.DocumentCheckedOutByAnother"), userName);
                            }
                            allowApproval = false;
                        }

                        // Document approval
                        if (allowApproval)
                        {
                            MenuItem approveItem = null;

                            switch (stepName)
                            {
                            case "edit":
                                // When edit step and not allowed 'auto publish changes', display submit to approval
                                if (mShowSubmitToApproval && !autoPublishChanges)
                                {
                                    approveItem                   = new MenuItem();
                                    approveItem.ToolTip           = GetString("EditMenu.SubmitToApproval");
                                    approveItem.JavascriptCommand = FunctionsPrefix + "Approve(" + NodeID + ");";
                                    approveItem.ImageAltText      = approveItem.ToolTip;
                                    approveItem.Text              = GetString("EditMenu.IconSubmitToApproval");
                                    approveItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/approve.png");
                                    approveItem.MouseOverImage    = approveItem.Image;
                                    approveItem.MouseOverCssClass = "MenuItemEdit";
                                    approveItem.CssClass          = "MenuItemEdit";
                                    menuElem.Items.Add(approveItem);
                                    mMenuItems += 1;
                                }
                                break;

                            case "published":
                            case "archived":
                                // No workflow options in these steps
                                break;

                            default:
                                // If the user is authorized to perform the step, display the approve and reject buttons
                                if (canApprove)
                                {
                                    if (mShowApprove && !autoPublishChanges)
                                    {
                                        approveItem                   = new MenuItem();
                                        approveItem.ToolTip           = GetString("EditMenu.Approve");
                                        approveItem.JavascriptCommand = FunctionsPrefix + "Approve(" + NodeID + ");";
                                        approveItem.ImageAltText      = approveItem.ToolTip;
                                        approveItem.Text              = GetString("general.approve");
                                        approveItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/approve.png");
                                        approveItem.MouseOverImage    = approveItem.Image;
                                        approveItem.MouseOverCssClass = "MenuItemEdit";
                                        approveItem.CssClass          = "MenuItemEdit";
                                        menuElem.Items.Add(approveItem);
                                        mMenuItems += 1;
                                    }

                                    if (mShowReject && !autoPublishChanges)
                                    {
                                        newItem                   = new MenuItem();
                                        newItem.ToolTip           = GetString("EditMenu.Reject");
                                        newItem.JavascriptCommand = FunctionsPrefix + "Reject(" + NodeID + ");";
                                        newItem.ImageAltText      = newItem.ToolTip;
                                        newItem.Text              = GetString("general.reject");
                                        newItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/reject.png");
                                        newItem.MouseOverImage    = newItem.Image;
                                        newItem.MouseOverCssClass = "MenuItemEdit";
                                        newItem.CssClass          = "MenuItemEdit";
                                        menuElem.Items.Add(newItem);
                                        mMenuItems += 1;
                                    }
                                }
                                break;
                            }

                            if (approveItem != null)
                            {
                                // Get next step info
                                WorkflowStepInfo nsi = WorkflowMan.GetNextStepInfo(Node);
                                if (nsi.StepName.ToLower() == "published")
                                {
                                    approveItem.ToolTip = GetString("EditMenu.Publish");
                                    approveItem.Text    = GetString("EditMenu.IconPublish");
                                }
                            }

                            // Set workflow info
                            if (!(canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived")))
                            {
                                if (!string.IsNullOrEmpty(mWorkflowInfo))
                                {
                                    mWorkflowInfo += "<br />";
                                }
                                mWorkflowInfo += GetString("EditContent.NotAuthorizedToApprove");
                            }
                            if (!string.IsNullOrEmpty(mWorkflowInfo))
                            {
                                mWorkflowInfo += "<br />";
                            }
                            // If workflow isn't auto publish or step name isn't 'published' or 'check-in/check-out' is allowed then show current step name
                            if (!wi.WorkflowAutoPublishChanges || (stepName != "published") || useCheckInCheckOut)
                            {
                                mWorkflowInfo += String.Format(GetString("EditContent.CurrentStepInfo"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(si.StepDisplayName)));
                            }
                        }
                    }
                }

                if (mShowProperties)
                {
                    newItem                   = new MenuItem();
                    newItem.ToolTip           = GetString("EditMenu.Properties");
                    newItem.JavascriptCommand = FunctionsPrefix + "Properties(" + NodeID + ");";
                    newItem.ImageAltText      = newItem.ToolTip;
                    newItem.Text              = GetString("EditMenu.IconProperties");
                    newItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/properties.png");
                    newItem.MouseOverImage    = newItem.Image;
                    newItem.MouseOverCssClass = "MenuItemEdit";
                    newItem.CssClass          = "MenuItemEdit";
                    menuElem.Items.Add(newItem);
                    mMenuItems += 1;
                }

                if (mShowDelete)
                {
                    showDelete = true;
                }
            }

            // If not allowed to save, disable the save item
            if (!mAllowSave && mShowSave && (saveItem != null))
            {
                saveItem.JavascriptCommand = "";
                saveItem.MouseOverCssClass = "MenuItemEditDisabled";
                saveItem.CssClass          = "MenuItemEditDisabled";
                saveItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/savedisabled.png");
                saveItem.MouseOverImage    = saveItem.Image;
            }
        }
        else if (mAllowSave && mShowCreateAnother)
        {
            newItem                   = new MenuItem();
            newItem.ToolTip           = GetString("EditMenu.SaveAndAnother");
            newItem.JavascriptCommand = FunctionsPrefix + "SaveDocument(" + NodeID + ", true);";
            newItem.ImageAltText      = newItem.ToolTip;
            newItem.Text              = GetString("editmenu.iconsaveandanother");
            newItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/saveandanother.png");
            newItem.MouseOverImage    = newItem.Image;
            newItem.MouseOverCssClass = "MenuItemEdit";
            newItem.CssClass          = "MenuItemEdit";
            menuElem.Items.Add(newItem);
            mMenuItems += 1;
        }

        if (mAllowSave && mShowSave && mShowSpellCheck && !newLink)
        {
            newItem                   = new MenuItem();
            newItem.ToolTip           = GetString("EditMenu.SpellCheck");
            newItem.JavascriptCommand = FunctionsPrefix + "SpellCheck(spellURL);";
            newItem.ImageAltText      = newItem.ToolTip;
            newItem.Text              = GetString("EditMenu.IconSpellCheck");
            newItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/spellcheck.png");
            newItem.MouseOverImage    = newItem.Image;
            newItem.MouseOverCssClass = "MenuItemEdit";
            newItem.CssClass          = "MenuItemEdit";
            menuElem.Items.Add(newItem);
            mMenuItems += 1;
        }

        if (showDelete)
        {
            newItem                   = new MenuItem();
            newItem.ToolTip           = GetString("EditMenu.Delete");
            newItem.JavascriptCommand = FunctionsPrefix + "Delete(" + NodeID + ");";
            newItem.ImageAltText      = newItem.ToolTip;
            newItem.Text              = GetString("general.delete");
            newItem.Image             = GetImageUrl("CMSModules/CMS_Content/EditMenu/delete.png");
            newItem.MouseOverImage    = newItem.Image;
            newItem.MouseOverCssClass = "MenuItemEdit";
            newItem.CssClass          = "MenuItemEdit";
            menuElem.Items.Add(newItem);
            mMenuItems += 1;
        }
    }
        /// <summary>
        /// Provides operations necessary to create and store new cms file.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleContentUpload(UploaderHelper args, HttpContext context)
        {
            bool newDocumentCreated = false;
            string name = args.Name;

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

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

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

                #region "Check permissions"

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

                #endregion

                args.IsExtensionAllowed();

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

                // Make sure the file name with extension respects maximum file name
                name = TreePathUtils.EnsureMaxFileNameLength(name, ci.ClassName);

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

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

                node.SetValue("FileDescription", "");
                node.SetValue("FileName", name);
                node.SetValue("FileAttachment", Guid.Empty);
                node.SetValue("DocumentType", args.Extension);

                node.SetDefaultPageTemplateID(ci.ClassDefaultPageTemplateID);

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

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

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

                DocumentHelper.UpdateDocument(node, TreeProvider);

                // Get workflow info
                wi = node.GetWorkflow();

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

                args.Message = ex.Message;

                // Log the error
                EventLogProvider.LogException("MultiFileUploader", "UPLOADATTACHMENT", ex);
            }
            finally
            {
                // Create node info string
                string nodeInfo = ((node != null) && (node.NodeID > 0) && args.IncludeNewItemInfo) ? String.Format("'{0}', ", node.NodeID) : "";

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

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

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

                args.AddEventTargetPostbackReference();
                context.Response.Write(args.AfterScript);
                context.Response.Flush();
            }
        }
예제 #7
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();
        }
    }
예제 #8
0
    /// <summary>
    /// Saves metadata and file name of attachment.
    /// </summary>
    /// <param name="newFileName">New attachment file name</param>
    /// <returns>Returns True if attachment was succesfully saved.</returns>
    private bool SaveAttachment(string newFileName)
    {
        bool saved = false;

        // Save new data
        try
        {
            AttachmentInfo attachmentInfo = InfoObject as AttachmentInfo;

            if (attachmentInfo != null)
            {
                // Set new file name
                if (!string.IsNullOrEmpty(newFileName))
                {
                    string name = newFileName + attachmentInfo.AttachmentExtension;
                    if (IsAttachmentNameUnique(attachmentInfo, name))
                    {
                        attachmentInfo.AttachmentName = name;
                    }
                    else
                    {
                        // Attachment already exists.
                        LabelError = GetString("img.errors.fileexists");
                        return(false);
                    }
                }

                // Ensure automatic check-in/ check-out
                bool            useWorkflow = false;
                bool            autoCheck   = false;
                WorkflowManager workflowMan = new WorkflowManager(TreeProvider);

                if (Node != null)
                {
                    // Get workflow info
                    WorkflowInfo wi = workflowMan.GetNodeWorkflow(Node);

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

                    // Check out the document
                    if (autoCheck)
                    {
                        VersionManager.CheckOut(Node, Node.IsPublished, true);
                        VersionHistoryID = Node.DocumentCheckedOutVersionHistoryID;
                    }

                    // Workflow has been lost, get published attachment
                    if (useWorkflow && (VersionHistoryID == 0))
                    {
                        attachmentInfo = AttachmentManager.GetAttachmentInfo(attachmentInfo.AttachmentGUID, SiteName);
                    }
                }

                if (attachmentInfo != null)
                {
                    // Set filename title and description
                    attachmentInfo.AttachmentTitle       = ObjectTitle;
                    attachmentInfo.AttachmentDescription = ObjectDescription;

                    // Document uses workflow and document is already saved (attachment is not temporary)
                    if ((VersionHistoryID > 0) && !nodeIsParent)
                    {
                        attachmentInfo.AllowPartialUpdate = true;
                        VersionManager.SaveAttachmentVersion(attachmentInfo, VersionHistoryID);
                    }
                    else
                    {
                        // Update without binary
                        attachmentInfo.AllowPartialUpdate = true;
                        AttachmentManager.SetAttachmentInfo(attachmentInfo);

                        // Log the sycnhronization and search task for the document
                        if (Node != null)
                        {
                            // Update search index for given document
                            if ((Node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled))
                            {
                                SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, Node.GetSearchID());
                            }

                            DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider);
                        }
                    }

                    // Check in the document
                    if (autoCheck)
                    {
                        if (VersionManager != null)
                        {
                            if (VersionHistoryID > 0 && (Node != null))
                            {
                                VersionManager.CheckIn(Node, null, null);
                            }
                        }
                    }

                    saved = true;

                    string fullRefresh = "false";

                    if (autoCheck || (Node == null))
                    {
                        fullRefresh = "true";
                    }

                    // Refresh parent update panel
                    LtlScript.Text = ScriptHelper.GetScript("RefreshMetaData(" + ScriptHelper.GetString(ExternalControlID) + ", '" + fullRefresh + "', '" + attachmentInfo.AttachmentGUID + "', 'refresh')");
                }
            }
        }
        catch (Exception ex)
        {
            lblError.Text = GetString("metadata.errors.processing");
            EventLogProvider.LogException("Metadata editor", "SAVEATTACHMENT", ex);
        }

        return(saved);
    }
예제 #9
0
    /// <summary>
    /// Provides operations necessary to create and store new content file.
    /// </summary>
    private void HandleContentUpload()
    {
        TreeNode     node = null;
        TreeProvider tree = null;

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

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

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

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


            #region "Check permissions"

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

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

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

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

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

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

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

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

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

            newDocumentCreated = true;

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

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

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

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

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

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

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

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

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false, false" + ((nodeInfo != "") ? ", '" + nodeInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}CloseDialog();"));
            }
        }
    }
예제 #10
0
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        TreeProvider tree = null;
        TreeNode     node = null;

        // New attachment
        AttachmentInfo newAttachment = null;

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

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


            #region "Check permissions"

            if (CheckPermissions)
            {
                CheckNodePermissions(node);
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", " + (fullRefresh ? "true" : "false") + ", false" + ((attachmentInfo != "") ? ", '" + attachmentInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}" + closeString));
            }
        }
    }
예제 #11
0
    public void RaisePostBackEvent(string eventArgument)
    {
        try
        {
            // Parse action to perform
            Action action = (Action)Enum.Parse(typeof(Action), eventArgument);
            // Parse action parameter
            string[] parameters = ValidationHelper.GetString(hdnParameter.Value, string.Empty).Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            // Check whether all parameters are present for parameterized pop-ups
            if (parameters.Length == 2)
            {
                // Initialize document manager
                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 currentNode = DocumentManager.Node;

                switch (action)
                {
                case Action.Localize:
                    // Initialize localization dialog
                    localizeElem.Action = "newculture";
                    localizeElem.NodeID = nodeId;
                    localizeElem.AlternativeFormName           = DocumentForm;
                    localizeElem.CopyDefaultDataFromDocumentID = currentNode.DocumentID;
                    localizeElem.CheckPermissions = true;
                    pnlLocalizePopup.Visible      = true;
                    localizeElem.ReloadData(true);
                    ShowPopup(pnlLocalizePopup, mdlLocalize);
                    break;

                case Action.Copy:
                    // Initialize copy dialog
                    copyElem.CopiedNodeID          = nodeId;
                    copyElem.CopiedDocumentCulture = cultureCode;
                    copyElem.TargetNodeID          = LibraryNode.NodeID;
                    copyElem.ReloadData(true);
                    copyElem.CancelButton.OnClientClick = Action.HidePopup + "_" + ClientID + "();return false;";
                    ShowPopup(pnlCopyPopup, mdlCopy);
                    break;

                case Action.Delete:
                    // Initialize delete dialog
                    deleteElem.DeletedNodeID          = nodeId;
                    deleteElem.DeletedDocumentCulture = cultureCode;
                    deleteElem.ReloadData(true);
                    deleteElem.CancelButton.OnClientClick = Action.HidePopup + "_" + ClientID + "();return false;";
                    ShowPopup(pnlDeletePopup, mdlDelete);
                    break;

                case Action.Properties:
                    // Initialize properties dialog
                    propertiesElem.NodeID              = nodeId;
                    propertiesElem.CultureCode         = cultureCode;
                    propertiesElem.AlternativeFormName = DocumentForm;
                    propertiesElem.CheckPermissions    = true;
                    pnlPropertiesPopup.Visible         = true;
                    propertiesElem.ReloadData(true);
                    ShowPopup(pnlPropertiesPopup, mdlProperties);
                    break;

                case Action.VersionHistory:
                    // Initialize version history dialog
                    versionsElem.Heading.Visible = false;
                    versionsElem.NodeID          = nodeId;
                    versionsElem.DocumentCulture = cultureCode;
                    versionsElem.SetupControl();
                    versionsElem.ReloadData();
                    ShowPopup(pnlVersionsPopup, mdlVersions);
                    break;

                case Action.Permissions:
                    // Initialize permissions dialog
                    permissionsElem.Node           = currentNode;
                    permissionsElem.DisplayButtons = false;
                    permissionsElem.ReloadData(true);
                    ReloadPermissions();
                    ShowPopup(pnlPermissionsPopup, mdlPermissions);
                    break;

                case Action.CheckOut:
                    // Perform document checkout
                    DocumentManager.CheckOutDocument();
                    break;

                case Action.CheckIn:
                    // Perform document check-in
                    DocumentManager.CheckInDocument(null);
                    break;

                case Action.UndoCheckout:
                    // Perform undo checkout on document
                    DocumentManager.UndoCheckOutDocument();
                    break;

                case Action.SubmitToApproval:
                    // Approve document
                    DocumentManager.ApproveDocument(0, null);
                    break;

                case Action.Reject:
                    // Reject document
                    DocumentManager.RejectDocument(0, null);
                    break;

                case Action.Archive:
                    // Archive document
                    DocumentManager.ArchiveDocument(0, null);
                    break;

                case Action.ExternalRefresh:
                    WorkflowInfo wi = DocumentManager.Workflow;

                    // Check if document uses workflow  and check-out/check-in is disabled
                    if ((wi != null) && !wi.UseCheckInCheckOut(currentNode.NodeSiteName) && !wi.WorkflowAutoPublishChanges)
                    {
                        // Check permission to modify document
                        if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(currentNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)
                        {
                            // Get current step
                            WorkflowStepInfo currentStep = DocumentManager.Step;

                            // Check if document uses workflow and step is 'published' or 'archived'
                            if ((currentStep != null) && (currentStep.StepIsPublished || currentStep.StepIsArchived))
                            {
                                // Ensure version for later detection whether node is published
                                VersionManager.EnsureVersion(currentNode, currentNode.IsPublished);

                                // Move to first step
                                WorkflowManager.MoveToFirstStep(currentNode, null);

                                // Refresh grid
                                RefreshGrid();
                            }
                        }
                    }
                    break;
                }
            }
            // General actions
            switch (action)
            {
            case Action.RefreshGrid:
                // Refresh unigrid
                RefreshGrid();
                break;

            case Action.HidePopup:
                // Find and hide current popup
                HideCurrentPopup();
                break;
            }
        }
        catch (Exception ex)
        {
            AddAlert(GetString("general.erroroccurred") + " " + ex.Message);
        }
    }
예제 #12
0
    /// <summary>
    /// Reloads the page data.
    /// </summary>
    private void ReloadData()
    {
        // If no workflow set for node, hide the data
        if (WorkflowInfo == null)
        {
            lblInfo.Text = GetString("properties.scopenotset");
            DisableForm();
            pnlVersions.Visible = false;
        }
        else
        {
            string stepName = WorkflowStepInfo.StepName.ToLower();

            if ((stepName != "edit") && (stepName != "published") && (stepName != "archived") && !versionsElem.CanApprove)
            {
                lblApprove.Visible = true;
                lblApprove.Text    = GetString("EditContent.NotAuthorizedToApprove") + "<br />";
            }
        }

        bool useCheckInCheckOut = false;

        if (WorkflowInfo != null)
        {
            useCheckInCheckOut = WorkflowInfo.UseCheckInCheckOut(CMSContext.CurrentSiteName);
        }

        // Check modify permissions
        if (!versionsElem.CanModify)
        {
            DisableForm();
            plcForm.Visible = false;
            lblInfo.Text    = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath);
        }
        else if (useCheckInCheckOut || (versionsElem.CheckedOutByUserID != 0))
        {
            btnCheckout.Visible     = false;
            btnCheckout.Enabled     = true;
            btnCheckin.Visible      = false;
            btnCheckin.Enabled      = true;
            btnUndoCheckout.Visible = false;
            btnUndoCheckout.Enabled = true;
            txtComment.Enabled      = true;
            txtVersion.Enabled      = true;
            lblComment.Enabled      = true;
            lblVersion.Enabled      = true;

            // Check whether to check out or in
            if (WorkflowInfo == null)
            {
                btnCheckout.Visible = true;
                lblCheckInfo.Text   = GetString("VersionsProperties.CheckOut");
                lblInfo.Text        = GetString("properties.scopenotset");
                DisableForm();
            }
            else if (!Node.IsCheckedOut)
            {
                lblCheckInfo.Text = GetString("VersionsProperties.CheckOut");
                lblInfo.Text      = GetString("VersionsProperties.InfoCheckedIn");
                DisableForm();
                btnCheckout.Visible = true;
                btnCheckout.Enabled = true;
            }
            else
            {
                // If checked out by current user, allow to check-in
                if (versionsElem.CheckedOutByUserID == CMSContext.CurrentUser.UserID)
                {
                    btnCheckin.Visible      = true;
                    btnUndoCheckout.Visible = true;
                    lblCheckInfo.Text       = GetString("VersionsProperties.CheckIn");
                    lblInfo.Text            = GetString("VersionsProperties.InfoCheckedOut");
                }
                else
                {
                    // Else checked out by somebody else
                    btnCheckout.Visible = true;
                    btnCheckin.Visible  = true;
                    btnCheckout.Visible = false;
                    lblCheckInfo.Text   = GetString("VersionsProperties.CheckIn");

                    // Get checked out message
                    string userName = UserInfoProvider.GetUserNameById(versionsElem.CheckedOutByUserID);
                    lblInfo.Text = String.Format(GetString("editcontent.documentcheckedoutbyanother"), userName);

                    btnUndoCheckout.Visible = versionsElem.CanCheckIn;
                    btnUndoCheckout.Enabled = versionsElem.CanCheckIn;
                    btnCheckin.Enabled      = versionsElem.CanCheckIn;
                    txtComment.Enabled      = versionsElem.CanCheckIn;
                    txtVersion.Enabled      = versionsElem.CanCheckIn;
                }
            }

            if (!versionsElem.CanApprove)
            {
                DisableForm();
            }
        }
        else
        {
            plcForm.Visible = false;
            if (WorkflowInfo != null)
            {
                lblInfo.Text = String.Empty;
            }
        }
    }
예제 #13
0
    /// <summary>
    /// Updates the document under workflow. Called when the "Update document" button is pressed.
    /// Expects the "CreateDocument" method to be run first.
    /// </summary>
    private bool UpdateDocument()
    {
        // Get the "Versioning without workflow" workflow
        WorkflowInfo workflow = WorkflowInfoProvider.GetWorkflowInfo("versioningWithoutWorkflow");

        if (workflow != null)
        {
            // Workflow is configured to automatically publish changes
            if (workflow.WorkflowAutoPublishChanges)
            {
                // Workflow doesn't use check-in/check-out
                if (!workflow.UseCheckInCheckOut(CurrentSiteName))
                {
                    // Create an instance of the Tree provider first
                    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                    // Prepare parameters
                    string siteName  = SiteContext.CurrentSiteName;
                    string aliasPath = "/API-Example/My-new-page";
                    string culture   = "en-us";
                    bool   combineWithDefaultCulture = false;
                    string classNames = TreeProvider.ALL_CLASSNAMES;
                    string where = null;
                    string orderBy             = null;
                    int    maxRelativeLevel    = -1;
                    bool   selectOnlyPublished = false;
                    string columns             = null;

                    // Get the document "My new document"
                    TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree);

                    if (node != null)
                    {
                        // Document must be checked-out manually if check-in/check-out is not used
                        node.CheckOut();

                        // Update document
                        node.DocumentMenuCaption = "My new page menu";
                        DocumentHelper.UpdateDocument(node);

                        // Document must be checked-in manually in order to create new version
                        node.CheckIn();

                        return(true);
                    }
                    else
                    {
                        apiUpdateDocument.ErrorMessage = "Page 'My new page' was not found.";
                    }
                }
                else
                {
                    apiUpdateDocument.ErrorMessage = "Workflow 'Versioning without workflow' uses check-in/check-out. You must disable it before you run this example.";
                }
            }
            else
            {
                apiUpdateDocument.ErrorMessage = "Workflow 'Versioning without workflow' is not configured to automatically publish changes.";
            }
        }

        return(false);
    }
예제 #14
0
        /// <summary>
        /// Provides operations necessary to create and store new cms file.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleContentUpload(UploaderHelper args, HttpContext context)
        {
            bool   newDocumentCreated = false;
            string name = args.Name;

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

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

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


                #region "Check permissions"

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

                #endregion

                args.IsExtensionAllowed();

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

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

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

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

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

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

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

                DocumentHelper.UpdateDocument(node, TreeProvider);

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

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

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

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

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

                args.AddEventTargetPostbackReference();
                context.Response.Write(args.AfterScript);
                context.Response.Flush();
            }
        }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            pi = CMSContext.CurrentPageInfo;
            if (pi != null)
            {
                CMSPagePlaceholder parentPlaceHolder = PortalHelper.FindParentPlaceholder(this);

                // Nothing to render, nothing to do
                if ((!DisplayAddButton && !DisplayResetButton) || ((parentPlaceHolder != null) && (parentPlaceHolder.UsingDefaultPage)))
                {
                    Visible = false;
                    return;
                }

                CurrentUserInfo currentUser = CMSContext.CurrentUser;
                zoneType = WidgetZoneTypeCode.ToEnum(WidgetZoneType);


                // Check security
                if (((zoneType == WidgetZoneTypeEnum.Group) && !currentUser.IsGroupAdministrator(pi.NodeGroupID)) ||
                    ((zoneType == WidgetZoneTypeEnum.User || zoneType == WidgetZoneTypeEnum.Dashboard) && !currentUser.IsAuthenticated()))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Displaying - Editor zone only in edit mode, User/Group zone only in Live site/Preview mode
                if (((zoneType == WidgetZoneTypeEnum.Editor) && ((CMSContext.ViewMode != ViewModeEnum.Edit) && (CMSContext.ViewMode != ViewModeEnum.EditLive))) ||
                    (((zoneType == WidgetZoneTypeEnum.User) || (zoneType == WidgetZoneTypeEnum.Group)) && ((CMSContext.ViewMode != ViewModeEnum.LiveSite) && (CMSContext.ViewMode != ViewModeEnum.Preview))) || ((zoneType == WidgetZoneTypeEnum.Dashboard) && ((CMSContext.ViewMode != ViewModeEnum.DashboardWidgets) || (String.IsNullOrEmpty(PortalContext.DashboardName)))))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Get current document
                TreeNode currentNode = DocumentHelper.GetDocument(pi.DocumentID, TreeProvider);
                if (((zoneType == WidgetZoneTypeEnum.Editor) && (!currentUser.IsEditor || (currentUser.IsAuthorizedPerDocument(currentNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied))))
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // If use checkin checkout enabled, check if document is checkout by current user
                if (zoneType == WidgetZoneTypeEnum.Editor)
                {
                    if (currentNode != null)
                    {
                        WorkflowManager wm = WorkflowManager.GetInstance(TreeProvider);
                        // Get workflow info
                        WorkflowInfo wi = wm.GetNodeWorkflow(currentNode);

                        // Check if node is under workflow and if use checkin checkout enabled
                        if ((wi != null) && (wi.UseCheckInCheckOut(CMSContext.CurrentSiteName)))
                        {
                            int checkedOutBy = currentNode.DocumentCheckedOutByUserID;

                            // Check if document is checkout by current user
                            if (checkedOutBy != CMSContext.CurrentUser.UserID)
                            {
                                Visible      = false;
                                resetAllowed = false;
                                return;
                            }
                        }
                    }
                }

                // Find widget zone
                PageTemplateInfo pti = pi.UsedPageTemplateInfo;

                // ZodeID specified directly
                if (!String.IsNullOrEmpty(WidgetZoneID))
                {
                    zoneInstance = pti.GetZone(WidgetZoneID);
                }

                // Zone not find or specified zone is not of correct type
                if ((zoneInstance != null) && (zoneInstance.WidgetZoneType != zoneType))
                {
                    zoneInstance = null;
                }

                // For delete all variants all zones are necessary
                if (parentPlaceHolder != null)
                {
                    var zones = parentPlaceHolder.WebPartZones;
                    if (zones != null)
                    {
                        foreach (CMSWebPartZone zone in zones)
                        {
                            if ((zone.ZoneInstance != null) && (zone.ZoneInstance.WidgetZoneType == zoneType))
                            {
                                zoneInstances.Add(zone.ZoneInstance);
                                if (zoneInstance == null)
                                {
                                    zoneInstance = zone.ZoneInstance;
                                }
                            }
                        }
                    }
                }

                // No suitable zones on the page, nothing to do
                if (zoneInstance == null)
                {
                    Visible      = false;
                    resetAllowed = false;
                    return;
                }

                // Adding is enabled
                if (DisplayAddButton)
                {
                    pnlAdd.Visible       = true;
                    lnkAddWidget.Visible = true;
                    lnkAddWidget.Text    = HTMLHelper.HTMLEncode(DataHelper.GetNotEmpty(AddButtonText, GetString("widgets.addwidget")));

                    int templateId = 0;
                    if (pi.UsedPageTemplateInfo != null)
                    {
                        templateId = pi.UsedPageTemplateInfo.PageTemplateId;
                    }

                    addScript = "NewWidget('" + HttpUtility.UrlEncode(zoneInstance.ZoneID) + "', '" + HttpUtility.UrlEncode(pi.NodeAliasPath) + "', '" + templateId + "'); return false;";
                    lnkAddWidget.Attributes.Add("onclick", addScript);
                }

                // Reset is enabled
                if (DisplayResetButton)
                {
                    pnlReset.Visible = true;
                    btnReset.Text    = HTMLHelper.HTMLEncode(DataHelper.GetNotEmpty(ResetButtonText, GetString("widgets.resettodefault")));
                    btnReset.Click  += new EventHandler(btnReset_Click);

                    // Add confirmation if required
                    if (ResetConfirmationRequired)
                    {
                        btnReset.Attributes.Add("onclick", "if (!confirm('" + GetString("widgets.resetzoneconfirmtext") + "')) return false;");
                    }
                }

                // Set the panel css clas with dependence on actions zone type
                switch (zoneType)
                {
                // Editor
                case WidgetZoneTypeEnum.Editor:
                    pnlWidgetActions.CssClass = "EditorWidgetActions";
                    break;

                // User
                case WidgetZoneTypeEnum.User:
                    pnlWidgetActions.CssClass = "UserWidgetActions";
                    break;

                // Group
                case WidgetZoneTypeEnum.Group:
                    pnlWidgetActions.CssClass = "GroupWidgetActions";
                    break;

                // Dashboard
                case WidgetZoneTypeEnum.Dashboard:
                {
                    if (pnlContextHelp.Controls.Count == 0)
                    {
                        // Load help control dynamically (due to faster start compilation)
                        var help = this.LoadUserControl("~/CMSAdminControls/UI/PageElements/Help.ascx") as HelpControl;
                        help.TopicName = "dashboard";
                    }
                }
                break;
                }
            }
        }
    }
    /// <summary>
    /// Provides operations necessary to create and store new content file.
    /// </summary>
    private void HandleContentUpload()
    {
        string message = string.Empty;
        bool newDocumentCreated = false;

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

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

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

            #region "Check permissions"

            // Get the node
            TreeNode parentNode = TreeProvider.SelectSingleNode(NodeParentNodeID, LocalizationContext.PreferredCultureCode, true);
            if (parentNode != null)
            {
                // Check whether node class is allowed on site and parent node
                if (!DocumentHelper.IsDocumentTypeAllowed(parentNode, ci.ClassID) || (ClassSiteInfoProvider.GetClassSiteInfo(ci.ClassID, parentNode.NodeSiteID) == null))
                {
                    throw new Exception(GetString("Content.ChildClassNotAllowed"));
                }
            }

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

            #endregion

            // Check the allowed extensions
            CheckAllowedExtensions();

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

            if (IncludeExtension)
            {
                fileName += ext;
            }

            // Make sure the file name with extension respects maximum file name
            fileName = TreePathUtils.EnsureMaxFileNameLength(fileName, ci.ClassName);

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

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

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

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

            newDocumentCreated = true;

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

            // Create default SKU if configured
            if (ModuleManager.CheckModuleLicense(ModuleName.ECOMMERCE, RequestContext.CurrentDomain, FeatureEnum.Ecommerce, ObjectActionEnum.Insert))
            {
                node.CreateDefaultSKU();
            }

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

            // Get workflow info
            wi = node.GetWorkflow();

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

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

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

            string containerId = QueryHelper.GetString("containerid", "");

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

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

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, ScriptHelper.GetScript(afterSaveScript));
        }
    }
예제 #17
0
    private void ReloadForm()
    {
        lblWorkflowInfo.Text = "";

        if ((node != null) && !newdocument && !newculture)
        {
            // Check read permissions
            if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied)
            {
                RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath));
            }
            // Check modify permissions
            else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
            {
                formElem.Enabled = false;
                lblWorkflowInfo.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), node.NodeAliasPath);
            }
            else
            {
                // Setup the workflow information
                wi = WorkflowManager.GetNodeWorkflow(node);
                if ((wi != null) && (!newculture))
                {
                    // Get current step info, do not update document
                    WorkflowStepInfo si = null;
                    if (node.IsPublished && (node.DocumentCheckedOutVersionHistoryID <= 0))
                    {
                        si = WorkflowStepInfoProvider.GetWorkflowStepInfo("published", wi.WorkflowID);
                    }
                    else
                    {
                        si = WorkflowManager.GetStepInfo(node, false) ??
                             WorkflowManager.GetFirstWorkflowStep(node, wi);
                    }

                    bool canApprove = WorkflowManager.CanUserApprove(node, CMSContext.CurrentUser);
                    string stepName = si.StepName.ToLower();
                    if (!(canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived")))
                    {
                        formElem.Enabled = false;
                    }

                    bool useCheckInCheckOut = wi.UseCheckInCheckOut(CMSContext.CurrentSiteName);
                    if (!node.IsCheckedOut)
                    {
                        // Check-in, Check-out
                        if (useCheckInCheckOut)
                        {
                            // If not checked out, add the check-out information
                            if (canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived"))
                            {
                                lblWorkflowInfo.Text = GetString("EditContent.DocumentCheckedIn");
                            }
                            formElem.Enabled = newculture;
                        }
                    }
                    else
                    {
                        // If checked out by current user, add the check-in button
                        int checkedOutBy = node.DocumentCheckedOutByUserID;
                        if (checkedOutBy == CMSContext.CurrentUser.UserID)
                        {
                            // Document is checked out
                            lblWorkflowInfo.Text = GetString("EditContent.DocumentCheckedOut");
                        }
                        else
                        {
                            // Checked out by somebody else
                            string userName = UserInfoProvider.GetUserNameById(checkedOutBy);
                            lblWorkflowInfo.Text = String.Format(GetString("EditContent.DocumentCheckedOutByAnother"), userName);
                            formElem.Enabled = newculture;
                        }
                    }

                    // Document approval
                    switch (stepName)
                    {
                        case "edit":
                        case "published":
                        case "archived":
                            break;

                        default:
                            // If the user is authorized to perform the step, display the approve and reject buttons
                            if (!canApprove)
                            {
                                lblWorkflowInfo.Text += " " + GetString("EditContent.NotAuthorizedToApprove");
                            }
                            break;
                    }
                    // If workflow isn't auto publish or step name isn't 'published' or 'check-in/check-out' is allowed then show current step name
                    if (!wi.WorkflowAutoPublishChanges || (stepName != "published") || useCheckInCheckOut)
                    {
                        lblWorkflowInfo.Text += " " + String.Format(GetString("EditContent.CurrentStepInfo"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(si.StepDisplayName)));
                    }
                }
            }
        }
        pnlWorkflowInfo.Visible = (lblWorkflowInfo.Text != "");
    }
예제 #18
0
    /// <summary>
    /// Provides operations necessary to create and store new content file.
    /// </summary>
    private void HandleContentUpload()
    {
        string message            = string.Empty;
        bool   newDocumentCreated = false;

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

            // Check license limitations
            if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Insert))
            {
                throw new LicenseException(GetString("cmsdesk.documentslicenselimits"));
            }

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


            #region "Check permissions"

            // Get the node
            TreeNode parentNode = TreeProvider.SelectSingleNode(NodeParentNodeID, LocalizationContext.PreferredCultureCode, true);
            if (parentNode != null)
            {
                // Check whether node class is allowed on site and parent node
                if (!DocumentHelper.IsDocumentTypeAllowed(parentNode, ci.ClassID) || (ClassSiteInfoProvider.GetClassSiteInfo(ci.ClassID, parentNode.NodeSiteID) == null))
                {
                    throw new Exception(GetString("Content.ChildClassNotAllowed"));
                }
            }

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

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

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

            if (IncludeExtension)
            {
                fileName += ext;
            }

            // Make sure the file name with extension respects maximum file name
            fileName = TreePathUtils.EnsureMaxFileNameLength(fileName, ci.ClassName);

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

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

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

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

            newDocumentCreated = true;

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

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

            // Get workflow info
            wi = node.GetWorkflow();

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

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

            // Ensure message text
            message = TextHelper.EnsureLineEndings(message, " ");

            string containerId = QueryHelper.GetString("containerid", "");

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

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

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, ScriptHelper.GetScript(afterSaveScript));
        }
    }
예제 #19
0
    private void ReloadForm()
    {
        lblWorkflowInfo.Text = "";

        if ((node != null) && !newdocument && !newculture)
        {
            // Check read permissions
            if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied)
            {
                RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath));
            }
            // Check modify permissions
            else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
            {
                formElem.Enabled     = false;
                lblWorkflowInfo.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), node.NodeAliasPath);
            }
            else
            {
                // Setup the workflow information
                wi = WorkflowManager.GetNodeWorkflow(node);
                if ((wi != null) && (!newculture))
                {
                    // Get current step info, do not update document
                    WorkflowStepInfo si = null;
                    if (node.IsPublished && (node.DocumentCheckedOutVersionHistoryID <= 0))
                    {
                        si = WorkflowStepInfoProvider.GetWorkflowStepInfo("published", wi.WorkflowID);
                    }
                    else
                    {
                        si = WorkflowManager.GetStepInfo(node, false) ??
                             WorkflowManager.GetFirstWorkflowStep(node, wi);
                    }

                    bool   canApprove = WorkflowManager.CanUserApprove(node, CMSContext.CurrentUser);
                    string stepName   = si.StepName.ToLower();
                    if (!(canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived")))
                    {
                        formElem.Enabled = false;
                    }

                    bool useCheckInCheckOut = wi.UseCheckInCheckOut(CMSContext.CurrentSiteName);
                    if (!node.IsCheckedOut)
                    {
                        // Check-in, Check-out
                        if (useCheckInCheckOut)
                        {
                            // If not checked out, add the check-out information
                            if (canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived"))
                            {
                                lblWorkflowInfo.Text = GetString("EditContent.DocumentCheckedIn");
                            }
                            formElem.Enabled = newculture;
                        }
                    }
                    else
                    {
                        // If checked out by current user, add the check-in button
                        int checkedOutBy = node.DocumentCheckedOutByUserID;
                        if (checkedOutBy == CMSContext.CurrentUser.UserID)
                        {
                            // Document is checked out
                            lblWorkflowInfo.Text = GetString("EditContent.DocumentCheckedOut");
                        }
                        else
                        {
                            // Checked out by somebody else
                            string userName = UserInfoProvider.GetUserNameById(checkedOutBy);
                            lblWorkflowInfo.Text = String.Format(GetString("EditContent.DocumentCheckedOutByAnother"), userName);
                            formElem.Enabled     = newculture;
                        }
                    }

                    // Document approval
                    switch (stepName)
                    {
                    case "edit":
                    case "published":
                    case "archived":
                        break;

                    default:
                        // If the user is authorized to perform the step, display the approve and reject buttons
                        if (!canApprove)
                        {
                            lblWorkflowInfo.Text += " " + GetString("EditContent.NotAuthorizedToApprove");
                        }
                        break;
                    }
                    // If workflow isn't auto publish or step name isn't 'published' or 'check-in/check-out' is allowed then show current step name
                    if (!wi.WorkflowAutoPublishChanges || (stepName != "published") || useCheckInCheckOut)
                    {
                        lblWorkflowInfo.Text += " " + String.Format(GetString("EditContent.CurrentStepInfo"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(si.StepDisplayName)));
                    }
                }
            }
        }
        pnlWorkflowInfo.Visible = (lblWorkflowInfo.Text != "");
    }
예제 #20
0
    /// <summary>
    /// Reloads the page data.
    /// </summary>
    private void ReloadData()
    {
        // If no workflow set for node, hide the data
        if (WorkflowInfo == null)
        {
            headCheckOut.ResourceString = "properties.scopenotset";
            DisableForm();
            pnlVersions.Visible = false;
        }
        else
        {
            if (!WorkflowStepInfo.StepIsDefault && !WorkflowManager.CheckStepPermissions(Node, WorkflowActionEnum.Approve))
            {
                ShowInfo(GetString("EditContent.NotAuthorizedToApprove"), true);
            }
        }

        bool useCheckInCheckOut = false;

        if (WorkflowInfo != null)
        {
            useCheckInCheckOut = WorkflowInfo.UseCheckInCheckOut(SiteContext.CurrentSiteName);
        }

        // Check modify permissions
        if (!versionsElem.CanModify)
        {
            DisableForm();
            plcForm.Visible = false;
            ShowInfo(String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath), true);
        }
        else if (useCheckInCheckOut || (versionsElem.CheckedOutByUserID != 0))
        {
            btnCheckout.Visible     = false;
            btnCheckout.Enabled     = true;
            btnCheckin.Visible      = false;
            btnCheckin.Enabled      = true;
            btnUndoCheckout.Visible = false;
            btnUndoCheckout.Enabled = true;
            txtComment.Enabled      = true;
            txtVersion.Enabled      = true;
            lblComment.Enabled      = true;
            lblVersion.Enabled      = true;

            // Check whether to check out or in
            if (WorkflowInfo == null)
            {
                btnCheckout.Visible         = true;
                headCheckOut.ResourceString = "VersionsProperties.CheckOut";
                DisableForm();
            }
            else if (!Node.IsCheckedOut)
            {
                headCheckOut.ResourceString = "VersionsProperties.CheckOut";
                DisableForm();
                btnCheckout.Visible = true;
                // Do not allow checkout for published or archived step in advanced workflow
                btnCheckout.Enabled = (WorkflowInfo.IsBasic || (!WorkflowStepInfo.StepIsPublished && !WorkflowStepInfo.StepIsArchived));
            }
            else
            {
                // If checked out by current user, allow to check-in
                if (versionsElem.CheckedOutByUserID == MembershipContext.AuthenticatedUser.UserID)
                {
                    btnCheckin.Visible      = true;
                    btnUndoCheckout.Visible = true;
                }
                else
                {
                    // Else checked out by somebody else
                    btnCheckin.Visible  = true;
                    btnCheckout.Visible = false;

                    btnUndoCheckout.Visible = versionsElem.CanCheckIn;
                    btnUndoCheckout.Enabled = versionsElem.CanCheckIn;
                    btnCheckin.Enabled      = versionsElem.CanCheckIn;
                    txtComment.Enabled      = versionsElem.CanCheckIn;
                    txtVersion.Enabled      = versionsElem.CanCheckIn;
                }

                headCheckOut.ResourceString = "VersionsProperties.CheckIn";
            }

            if (!WorkflowManager.CheckStepPermissions(Node, WorkflowActionEnum.Approve))
            {
                DisableForm();
            }
        }
        else
        {
            plcForm.Visible = false;
        }
    }
예제 #21
0
    protected void btnOk_Click(object sender, EventArgs e)
    {
        // Check allowed cultures
        if (!CMSContext.CurrentUser.IsCultureAllowed(CMSContext.PreferredCultureCode, CMSContext.CurrentSiteName))
        {
            lblError.Text   = GetString("Content.NotAuthorizedFile");
            pnlForm.Visible = false;
            return;
        }

        TreeNode     node = null;
        TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);

        if ((UseFileUploader && !FileUpload.HasFile) || (!UseFileUploader && !ucDirectUploader.HasData()))
        {
            lblError.Text = GetString("NewFile.ErrorEmpty");
        }
        else
        {
            // Get file extension
            string fileExtension = UseFileUploader ? FileUpload.FileName : ucDirectUploader.AttachmentName;
            fileExtension = Path.GetExtension(fileExtension).TrimStart('.');

            // Check file extension
            if (IsExtensionAllowed(fileExtension))
            {
                bool newDocumentCreated = false;

                try
                {
                    if (UseFileUploader)
                    {
                        // Process file using file upload
                        node = ProcessFileUploader(tree);
                    }
                    else
                    {
                        // Process file using direct uploader
                        node = ProcessDirectUploader(tree);

                        // Save temporary attachments
                        DocumentHelper.SaveTemporaryAttachments(node, Guid, CMSContext.CurrentSiteName, tree);
                    }

                    newDocumentCreated = true;

                    // Create default SKU if configured
                    if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))
                    {
                        bool?skuCreated = node.CreateDefaultSKU();
                        if (skuCreated.HasValue && !skuCreated.Value)
                        {
                            lblError.Text = GetString("com.CreateDefaultSKU.Error");
                        }
                    }

                    // Set additional values
                    if (!string.IsNullOrEmpty(fileExtension))
                    {
                        // Update document extensions if no custom are used
                        if (!node.DocumentUseCustomExtensions)
                        {
                            node.DocumentExtensions = "." + fileExtension;
                        }
                        node.SetValue("DocumentType", "." + fileExtension);
                    }

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

                    WorkflowManager workflowManager = new WorkflowManager(tree);
                    // Get workflow info
                    WorkflowInfo workflowInfo = workflowManager.GetNodeWorkflow(node);

                    // Check if auto publish changes is allowed
                    if ((workflowInfo != null) && workflowInfo.WorkflowAutoPublishChanges && !workflowInfo.UseCheckInCheckOut(CMSContext.CurrentSiteName))
                    {
                        // Automatically publish document
                        workflowManager.AutomaticallyPublish(node, workflowInfo, null);
                    }

                    bool createAnother = ValidationHelper.GetBoolean(Request.Params["hidAnother"], false);

                    // Added from CMSDesk->Content
                    if (!isDialog)
                    {
                        if (createAnother)
                        {
                            ltlScript.Text += ScriptHelper.GetScript("PassiveRefresh(" + node.NodeParentID + ", " + node.NodeParentID + "); CreateAnother();");
                        }
                        else
                        {
                            ltlScript.Text += ScriptHelper.GetScript(
                                "   RefreshTree(" + node.NodeID + ", " + node.NodeID + "); SelectNode(" + node.NodeID + "); \n"
                                );
                        }
                    }
                    // Added from dialog window
                    else
                    {
                        if (createAnother)
                        {
                            txtFileDescription.Text = "";
                            ltlScript.Text         += ScriptHelper.GetScript("FileCreated(" + node.NodeID + ", " + node.NodeParentID + ", false);");
                        }
                        else
                        {
                            ltlScript.Text += ScriptHelper.GetScript("FileCreated(" + node.NodeID + ", " + node.NodeParentID + ", true);");
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Delete the document if something failed
                    if (newDocumentCreated && (node != null) && (node.DocumentID > 0))
                    {
                        DocumentHelper.DeleteDocument(node, tree, false, true, true);
                    }
                    lblError.Text = GetString("NewFile.Failed") + ": " + ex.Message;
                }
            }
            else
            {
                lblError.Text = String.Format(GetString("NewFile.ExtensionNotAllowed"), fileExtension);
            }
        }
    }
예제 #22
0
    /// <summary>
    /// Saves modified image data.
    /// </summary>
    /// <param name="name">Image name</param>
    /// <param name="extension">Image extension</param>
    /// <param name="mimetype">Image mimetype</param>
    /// <param name="title">Image title</param>
    /// <param name="description">Image description</param>
    /// <param name="binary">Image binary data</param>
    /// <param name="width">Image width</param>
    /// <param name="height">Image height</param>
    private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height)
    {
        LoadInfos();

        // Save image data depending to image type
        switch (baseImageEditor.ImageType)
        {
        // Process attachment
        case ImageHelper.ImageTypeEnum.Attachment:
            if (ai != null)
            {
                // Save new data
                try
                {
                    // Get the node
                    TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree);

                    // Check Create permission when saving temporary attachment, check Modify permission else
                    NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create;

                    // Check permission
                    if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed)
                    {
                        baseImageEditor.ShowError(GetString("attach.actiondenied"));
                        SavingFailed = true;

                        return;
                    }

                    if (!IsNameUnique(name, extension))
                    {
                        baseImageEditor.ShowError(GetString("img.namenotunique"));
                        SavingFailed = true;

                        return;
                    }


                    // Ensure automatic check-in/ check-out
                    bool            useWorkflow = false;
                    bool            autoCheck   = false;
                    WorkflowManager workflowMan = WorkflowManager.GetInstance(baseImageEditor.Tree);
                    if (node != null)
                    {
                        // Get workflow info
                        WorkflowInfo wi = workflowMan.GetNodeWorkflow(node);

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

                        // Check out the document
                        if (autoCheck)
                        {
                            VersionManager.CheckOut(node, node.IsPublished, true);
                            VersionHistoryID = node.DocumentCheckedOutVersionHistoryID;
                        }

                        // Workflow has been lost, get published attachment
                        if (useWorkflow && (VersionHistoryID == 0))
                        {
                            ai = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName);
                        }

                        // If extension changed update CMS.File extension
                        if ((node.NodeClassName.ToLowerCSafe() == "cms.file") && (node.DocumentExtensions != extension))
                        {
                            // Update document extensions if no custom are used
                            if (!node.DocumentUseCustomExtensions)
                            {
                                node.DocumentExtensions = extension;
                            }
                            node.SetValue("DocumentType", extension);

                            DocumentHelper.UpdateDocument(node, baseImageEditor.Tree);
                        }
                    }

                    if (ai != null)
                    {
                        // Test all parameters to empty values and update new value if available
                        if (name != "")
                        {
                            if (!name.EndsWithCSafe(extension))
                            {
                                ai.AttachmentName = name + extension;
                            }
                            else
                            {
                                ai.AttachmentName = name;
                            }
                        }
                        if (extension != "")
                        {
                            ai.AttachmentExtension = extension;
                        }
                        if (mimetype != "")
                        {
                            ai.AttachmentMimeType = mimetype;
                        }

                        ai.AttachmentTitle       = title;
                        ai.AttachmentDescription = description;

                        if (binary != null)
                        {
                            ai.AttachmentBinary = binary;
                            ai.AttachmentSize   = binary.Length;
                        }
                        if (width > 0)
                        {
                            ai.AttachmentImageWidth = width;
                        }
                        if (height > 0)
                        {
                            ai.AttachmentImageHeight = height;
                        }
                        // Ensure object
                        ai.MakeComplete(true);
                        if (VersionHistoryID > 0)
                        {
                            VersionManager.SaveAttachmentVersion(ai, VersionHistoryID);
                        }
                        else
                        {
                            AttachmentInfoProvider.SetAttachmentInfo(ai);

                            // Log the synchronization and search task for the document
                            if (node != null)
                            {
                                // Update search index for given document
                                if (DocumentHelper.IsSearchTaskCreationAllowed(node))
                                {
                                    SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID);
                                }

                                DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree);
                            }
                        }

                        // Check in the document
                        if ((autoCheck) && (VersionManager != null) && (VersionHistoryID > 0) && (node != null))
                        {
                            VersionManager.CheckIn(node, null);
                        }
                    }
                }
                catch (Exception ex)
                {
                    baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                    EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                    SavingFailed = true;
                }
            }
            break;

        case ImageHelper.ImageTypeEnum.PhysicalFile:
            if (!String.IsNullOrEmpty(filePath))
            {
                var currentUser = MembershipContext.AuthenticatedUser;
                if ((currentUser != null) && currentUser.IsGlobalAdministrator)
                {
                    try
                    {
                        string physicalPath = Server.MapPath(filePath);
                        string newPath      = physicalPath;

                        // Write binary data to the disk
                        File.WriteAllBytes(physicalPath, binary);

                        // Handle rename of the file
                        if (!String.IsNullOrEmpty(name))
                        {
                            newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name);
                        }
                        if (!String.IsNullOrEmpty(extension))
                        {
                            string oldExt = Path.GetExtension(physicalPath);
                            newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension;
                        }

                        // Move the file
                        if (newPath != physicalPath)
                        {
                            File.Move(physicalPath, newPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                        EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                        SavingFailed = true;
                    }
                }
                else
                {
                    baseImageEditor.ShowError(GetString("img.errors.rights"));
                    SavingFailed = true;
                }
            }
            break;

        // Process metafile
        case ImageHelper.ImageTypeEnum.Metafile:

            if (mf != null)
            {
                if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser))
                {
                    try
                    {
                        // Test all parameters to empty values and update new value if available
                        if (name.CompareToCSafe("") != 0)
                        {
                            if (!name.EndsWithCSafe(extension))
                            {
                                mf.MetaFileName = name + extension;
                            }
                            else
                            {
                                mf.MetaFileName = name;
                            }
                        }
                        if (extension.CompareToCSafe("") != 0)
                        {
                            mf.MetaFileExtension = extension;
                        }
                        if (mimetype.CompareToCSafe("") != 0)
                        {
                            mf.MetaFileMimeType = mimetype;
                        }

                        mf.MetaFileTitle       = title;
                        mf.MetaFileDescription = description;

                        if (binary != null)
                        {
                            mf.MetaFileBinary = binary;
                            mf.MetaFileSize   = binary.Length;
                        }
                        if (width > 0)
                        {
                            mf.MetaFileImageWidth = width;
                        }
                        if (height > 0)
                        {
                            mf.MetaFileImageHeight = height;
                        }

                        // Save new data
                        MetaFileInfoProvider.SetMetaFileInfo(mf);

                        if (RefreshAfterAction)
                        {
                            if (String.IsNullOrEmpty(externalControlID))
                            {
                                baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();");
                            }
                            else
                            {
                                baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message);
                        EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex);
                        SavingFailed = true;
                    }
                }
                else
                {
                    baseImageEditor.ShowError(GetString("img.errors.rights"));
                    SavingFailed = true;
                }
            }
            break;
        }
    }
예제 #23
0
    /// <summary>
    /// Creates new page(CMS.MenuItem) and assignes selected template.
    /// </summary>
    protected void Save(bool createAnother)
    {
        // Check security
        CheckSecurity(true);

        string newPageName = txtPageName.Text.Trim();

        string errorMessage = null;

        if (!String.IsNullOrEmpty(newPageName))
        {
            // Limit length to 100 characters
            newPageName = TextHelper.LimitLength(newPageName, TreePathUtils.MaxNameLength, String.Empty);
        }
        else
        {
            errorMessage = GetString("newpage.nameempty");
        }

        if (parentNodeId == 0)
        {
            errorMessage = GetString("newpage.invalidparentnode");
        }

        // If error, show error message and return
        if (String.IsNullOrEmpty(errorMessage))
        {
            TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
            TreeNode     node = TreeNode.New("CMS.MenuItem", tree);

            // Load default data
            FormHelper.LoadDefaultValues(node);

            node.DocumentName = newPageName;
            lblError.Style.Remove("display");

            node.DocumentPageTemplateID = selTemplate.EnsureTemplate(node.DocumentName, ref errorMessage);

            // Switch to design mode (the template is empty at this moment)
            if (selTemplate.NewTemplateIsEmpty && !createAnother)
            {
                CMSContext.ViewMode = ViewModeEnum.Design;
            }

            // Insert node if no error
            if (String.IsNullOrEmpty(errorMessage))
            {
                node.DocumentCulture = CMSContext.PreferredCultureCode;

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

                // Create default SKU if configured
                if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))
                {
                    bool?skuCreated = node.CreateDefaultSKU();
                    if (skuCreated.HasValue && !skuCreated.Value)
                    {
                        lblError.Text = GetString("com.CreateDefaultSKU.Error");
                    }
                }

                if (node.NodeSKUID > 0)
                {
                    DocumentHelper.UpdateDocument(node, tree);
                }

                // Automatically publish
                // Check if allowed 'Automatically publish changes'
                WorkflowManager wm = new WorkflowManager(tree);
                WorkflowInfo    wi = wm.GetNodeWorkflow(node);
                if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName))
                {
                    wm.AutomaticallyPublish(node, wi, null);
                }

                // Process create another flag
                string script = null;
                if (createAnother)
                {
                    script = ScriptHelper.GetScript("parent.PassiveRefresh(" + node.NodeParentID + ", " + node.NodeParentID + "); parent.CreateAnother();");
                }
                else
                {
                    script  = ScriptHelper.GetScript("parent.RefreshTree(" + node.NodeID + ", " + node.NodeID + ");");
                    script += ScriptHelper.GetScript("parent.SelectNode(" + node.NodeID + ");");
                }

                ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "Refresh", script);
            }
        }

        // Insert node if no error
        if (!String.IsNullOrEmpty(errorMessage))
        {
            lblError.Text    = errorMessage;
            lblError.Visible = true;
            return;
        }
    }