Exemplo n.º 1
0
    private void RemoveWorkflow(object parameter)
    {
        VersionManager verMan = new VersionManager(Tree);
        TreeNode       node   = null;

        // Custom logging
        Tree.LogEvents         = false;
        Tree.AllowAsyncActions = false;
        CanceledString         = ResHelper.GetString("workflowdocuments.removingcanceled", currentCulture);
        try
        {
            // Begin log
            AddLog(ResHelper.GetString("content.preparingdocuments", currentCulture));

            // Get the documents
            DataSet documents = GetDocumentsToProcess();

            if (!DataHelper.DataSourceIsEmpty(documents))
            {
                // Begin log
                AddLog(ResHelper.GetString("workflowdocuments.removingwf", currentCulture));

                foreach (DataTable classTable in documents.Tables)
                {
                    foreach (DataRow nodeRow in classTable.Rows)
                    {
                        // Get the current document
                        string className  = ValidationHelper.GetString(nodeRow["ClassName"], string.Empty);
                        string aliasPath  = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty);
                        string docCulture = ValidationHelper.GetString(nodeRow["DocumentCulture"], string.Empty);
                        string siteName   = ValidationHelper.GetString(nodeRow["SiteName"], string.Empty);

                        // Get published version
                        node = Tree.SelectSingleNode(siteName, aliasPath, docCulture, false, className, false);
                        string encodedAliasPath = HTMLHelper.HTMLEncode(ValidationHelper.GetString(aliasPath, string.Empty) + " (" + node.GetValue("DocumentCulture") + ")");

                        // Destroy document history
                        verMan.DestroyDocumentHistory(node.DocumentID);

                        // Clear workflow
                        DocumentHelper.ClearWorkflowInformation(node);
                        node.Update();

                        // Add log record
                        AddLog(encodedAliasPath);

                        // Add record to eventlog
                        LogContext.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Content", "REMOVEDOCWORKFLOW", currentUser.UserID,
                                            currentUser.UserName, node.NodeID, node.DocumentName,
                                            HTTPHelper.UserHostAddress, string.Format(GetString("workflowdocuments.removeworkflowsuccess"), encodedAliasPath),
                                            node.NodeSiteID, HTTPHelper.GetAbsoluteUri(), HTTPHelper.MachineName, HTTPHelper.GetUrlReferrer(), HTTPHelper.GetUserAgent());
                    }
                }
                CurrentInfo = GetString("workflowdocuments.removecomplete");
            }
            else
            {
                AddError(ResHelper.GetString("workflowdocuments.nodocumentstoclear", currentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                CurrentInfo = CanceledString;
            }
            else
            {
                int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID;
                // Log error
                LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId);
            }
        }
        catch (Exception ex)
        {
            int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID;
            // Log error
            LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId);
        }
    }
 /// <summary>
 /// Delete documents section.
 /// </summary>
 /// <param name="node">Node to be deleted</param>
 /// <param name="tree">Tree provider</param>
 private void DeleteDocumentSection(TreeNode node, TreeProvider tree)
 {
     // Delete all document cultures
     DocumentHelper.DeleteDocument(node, tree, true);
 }
Exemplo n.º 3
0
 public HelpLine()
 {
     _logger        = IoC.ContainerRegistrar.Container.Resolve <ILogger>();
     _editorHelper  = new EditorHelper(Application.DocumentManager.MdiActiveDocument);
     _drawingHelper = new DocumentHelper(Application.DocumentManager.MdiActiveDocument);
 }
Exemplo n.º 4
0
 public void Should_Validate_Correctly_The_CPJ()
 {
     Assert.IsTrue(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_CPJ, "1234567894"));
     Assert.IsFalse(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_CPJ, "123456789"));
 }
    /// <summary>
    /// Generate control output.
    /// </summary>
    public void GenerateContent()
    {
        string templatePath = DepartmentTemplatePath;

        if (String.IsNullOrEmpty(templatePath))
        {
            ltlContent.Text    = ResHelper.GetString("departmentsectionsmanager.notemplate");
            ltlContent.Visible = true;
        }
        else
        {
            if (!DataHelper.DataSourceIsEmpty(TemplateDocuments))
            {
                int   counter = 0;
                Table tb      = new Table();

                string value      = ValidationHelper.GetString(mSelectedValue, "");
                string docAliases = ";" + value.ToLowerCSafe() + ";";

                TreeNode editedNode = (TreeNode)Form.EditedObject;

                if (Form.IsInsertMode)
                {
                    // Alias path for new department has to have special 'child node path' because of correct check for document type scopes
                    editedNode.SetValue("NodeAliasPath", ((TreeNode)Form.ParentObject).NodeAliasPath + "/department");
                }

                TableRow tr = new TableRow();
                foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows)
                {
                    // For each section td element is generated
                    string docAlias = ValidationHelper.GetString(drDoc["NodeAlias"], "");

                    TableCell   td     = new TableCell();
                    CMSCheckBox cbCell = new CMSCheckBox();
                    cbCell.ID   = "chckSection" + counter;
                    cbCell.Text = docAlias;
                    cbCell.Attributes.Add("Value", docAlias);

                    // Check if child allowed
                    int sourceClassId = ValidationHelper.GetInteger(drDoc["NodeClassID"], 0);
                    if (!DocumentHelper.IsDocumentTypeAllowed(editedNode, sourceClassId))
                    {
                        cbCell.Enabled = false;
                        cbCell.ToolTip = ResHelper.GetString("departmentsectionsmanager.notallowedchild");
                    }

                    // Disable default hidden documents
                    if (HIDDEN_DOCUMENT_ALIAS.Contains(";" + docAlias.ToLowerCSafe() + ";"))
                    {
                        cbCell.Checked = cbCell.Enabled;
                        cbCell.Enabled = false;
                    }


                    // Check for selected value
                    if (docAliases.Contains(";" + docAlias.ToLowerCSafe() + ";") || ((mSelectedValue == null) && (Form.Mode == FormModeEnum.Insert)))
                    {
                        if (cbCell.Enabled)
                        {
                            cbCell.Checked = true;
                        }
                    }

                    // If editing existing document register alert script
                    if ((Form.Mode != FormModeEnum.Insert) && cbCell.Checked)
                    {
                        cbCell.Attributes.Add("OnClick", "if(!this.checked){alert(" + ScriptHelper.GetString(ResHelper.GetString("departmentsectionsmanagerformcontrol.removesectionwarning")) + ");}");
                    }

                    // Add reference to checkbox arraylist
                    CheckboxReferences.Add(cbCell);
                    counter++;

                    td.Controls.Add(cbCell);
                    tr.Cells.Add(td);

                    // If necessary create new row
                    if ((counter % ITEMS_PER_ROW) == 0)
                    {
                        tr.CssClass = "Row";
                        tb.Rows.Add(tr);
                        tr = new TableRow();
                    }
                }
                // If last row contains data add it
                if (counter > 0)
                {
                    tb.Rows.Add(tr);
                }
                pnlContent.Controls.Add(tb);
            }
            else
            {
                ltlContent.Text    = ResHelper.GetString("departmentsectionsmanager.notemplate");
                ltlContent.Visible = true;
            }
        }
    }
Exemplo n.º 6
0
 public void Should_Validate_Correctly_The_CI()
 {
     Assert.IsTrue(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_CI, "1002606430"));
 }
Exemplo n.º 7
0
 public void Should_Validate_Correctly_The_DNI()
 {
     Assert.IsTrue(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_DNI, "12345678"));
     Assert.IsFalse(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_DNI, "1234859"));
 }
Exemplo n.º 8
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));
        }
    }
Exemplo n.º 9
0
        public static Tree GetTree()
        {
            Settings = ReadSettings();

            var tree = new Tree();

            tree.Nodes = new List <Node>();

            var rootName = DocumentHelper.RootName;

            if (Settings.ContainsKey(rootName))
            {
                var setting = Settings[rootName];
                if (setting != null)
                {
                    var node = new Node()
                    {
                        ShowName = rootName,
                        setting  = setting,
                        Url      = DocumentHelper.GetTypeUrl(rootName)
                    };
                    node.Nodes = new List <Node>();
                    var kscriptSetting = setting as KScriptSetting;

                    foreach (var prop in kscriptSetting.Props)
                    {
                        var childNode = new Node()
                        {
                            ShowName = prop.Name,
                            setting  = prop,
                            Url      = DocumentHelper.GetTypeUrl(prop.Type)
                        };
                        if (prop.Childrens.Count > 0)
                        {
                            foreach (var child in prop.Childrens)
                            {
                                childNode.Nodes = new List <Node>();
                                var childSetting = Settings[child.ToLower()];
                                if (childSetting != null)
                                {
                                    childNode.Nodes.Add(new Node()
                                    {
                                        ShowName = child,
                                        setting  = Settings[child.ToLower()],
                                        Url      = DocumentHelper.GetTypeUrl(child)
                                    });
                                }
                            }
                        }
                        node.Nodes.Add(childNode);
                    }

                    foreach (var method in kscriptSetting.Methods)
                    {
                        var paramBuilder = new StringBuilder();
                        foreach (var param in method.Params)
                        {
                            paramBuilder.Append(param.Name);
                        }

                        node.Nodes.Add(new Node()
                        {
                            ShowName = method.Name,
                            setting  = method,
                            Url      = DocumentHelper.GetMethodUrl("k", method.Name, paramBuilder.ToString())
                        });
                    }

                    tree.Nodes.Add(node);
                }
            }

            return(tree);
        }
Exemplo n.º 10
0
    /// <summary>
    /// Page_Load event.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.StopProcessing)
        {
            return;
        }

        // Create and set category provider
        UniTreeProvider categoryProvider = new UniTreeProvider();

        categoryProvider.DisplayNameColumn = "DisplayName";
        categoryProvider.IDColumn          = "ObjectID";
        categoryProvider.LevelColumn       = "ObjectLevel";
        categoryProvider.OrderColumn       = "CategoryOrder";
        categoryProvider.ParentIDColumn    = "ParentID";
        categoryProvider.PathColumn        = "ObjectPath";
        categoryProvider.ValueColumn       = "ObjectID";
        categoryProvider.ChildCountColumn  = "CompleteChildCount";
        categoryProvider.QueryName         = "cms.pagetemplatecategory.selectallview";
        categoryProvider.ObjectTypeColumn  = "ObjectType";
        categoryProvider.Columns           = "DisplayName, CodeName, ObjectID, ObjectLevel, CategoryOrder, ParentID, ObjectPath, CompleteChildCount, ObjectType, CategoryChildCount, CategoryImagePath, Parameter";
        categoryProvider.ImageColumn       = "CategoryImagePath";
        categoryProvider.ParameterColumn   = "Parameter";

        if (!SelectPageTemplates)
        {
            categoryProvider.WhereCondition   = "ObjectType = 'pagetemplatecategory'";
            categoryProvider.ChildCountColumn = "CategoryChildCount";
            categoryProvider.ObjectTypeColumn = "";
            treeElem.DefaultImagePath         = GetImageUrl("Objects/CMS_PageTemplateCategory/list.png");
        }
        else
        {
            categoryProvider.OrderBy = "ObjectType DESC, DisplayName ASC";
            treeElem.OnGetImage     += new CMSAdminControls_UI_Trees_UniTree.GetImageEventHandler(treeElem_OnGetImage);
        }

        // Do not show AdHoc category
        if (!this.ShowAdHocCategory)
        {
            categoryProvider.WhereCondition = SqlHelperClass.AddWhereCondition(categoryProvider.WhereCondition, "CodeName <> 'AdHoc'");
        }

        // Do not show empty categories
        if (!this.ShowEmptyCategories)
        {
            categoryProvider.WhereCondition = SqlHelperClass.AddWhereCondition(categoryProvider.WhereCondition, "CategoryTemplateChildCount > 0 OR CategoryChildCount > 0");

            TreeProvider tp      = new TreeProvider(CMSContext.CurrentUser);
            TreeNode     node    = DocumentHelper.GetDocument(DocumentID, tp);
            string       culture = CMSContext.PreferredCultureCode;
            int          level   = 0;
            string       path    = string.Empty;

            if (node != null)
            {
                level = node.NodeLevel;
                path  = node.NodeAliasPath;
                if (IsNewPage)
                {
                    level++;
                    path = path + "/%";
                }
                else
                {
                    culture = node.DocumentCulture;
                }
            }

            // Add where condition for scopes
            categoryProvider.WhereCondition += " AND (ObjectLevel = 0 OR (SELECT TOP 1 ObjectID FROM View_CMS_PageTemplateCategoryPageTemplate_Joined AS X WHERE X.ObjectType = 'pagetemplate' ";

            categoryProvider.WhereCondition += " AND (X.PageTemplateType IS NULL OR X.PageTemplateType <> N'" + PageTemplateInfoProvider.GetPageTemplateTypeCode(PageTemplateTypeEnum.Dashboard) + "')";


            if (ShowOnlySiteTemplates)
            {
                categoryProvider.WhereCondition += " AND X.ObjectID IN (SELECT PageTemplateID FROM CMS_PageTemplateSite WHERE SiteID = " + CMSContext.CurrentSiteID + ") ";
            }

            if (node != null)
            {
                categoryProvider.WhereCondition += " AND (" + PageTemplateScopeInfoProvider.GetScopeWhereCondition(path, culture, node.NodeClassName, level, CMSContext.CurrentSiteName, "X", "ObjectID") + ") ";
            }

            categoryProvider.WhereCondition += " AND (X.ObjectPath LIKE View_CMS_PageTemplateCategoryPageTemplate_Joined.ObjectPath + '/%')) IS NOT NULL)";

            // Add column count column - minimal number of childs
            categoryProvider.Columns += @", (SELECT TOP 1 Count(*) FROM View_CMS_PageTemplateCategoryPageTemplate_Joined AS Y WHERE 
            (Y.ObjectID = View_CMS_PageTemplateCategoryPageTemplate_Joined.ObjectID AND Y.ObjectLevel = 0)
            OR ( View_CMS_PageTemplateCategoryPageTemplate_Joined.ObjectType = 'PageTemplateCategory' 
            AND View_CMS_PageTemplateCategoryPageTemplate_Joined.CategoryChildCount > 0 
            AND Y.ObjectType = 'PageTemplate' AND Y.ObjectLevel > View_CMS_PageTemplateCategoryPageTemplate_Joined.ObjectLevel + 1 ";

            if (ShowOnlySiteTemplates)
            {
                categoryProvider.Columns += "AND Y.ObjectID IN (SELECT PageTemplateID FROM CMS_PageTemplateSite WHERE SiteID = " + CMSContext.CurrentSiteID + ") ";
            }

            if (node != null)
            {
                categoryProvider.Columns += " AND ( " + PageTemplateScopeInfoProvider.GetScopeWhereCondition(path, culture, node.NodeClassName, level, CMSContext.CurrentSiteName, "Y", "ObjectID") + " ) ";
            }

            categoryProvider.Columns         += " AND Y.ObjectPath LIKE  View_CMS_PageTemplateCategoryPageTemplate_Joined.ObjectPath + '/%')) AS MinNumberOfChilds";
            categoryProvider.ChildCountColumn = "MinNumberOfChilds";
        }

        // Set up tree
        treeElem.ProviderObject = categoryProvider;

        if (SelectPageTemplates)
        {
            treeElem.NodeTemplate         = "<span id=\"##OBJECTTYPE##_##NODEID##\" onclick=\"SelectNode(##NODEID##,'##OBJECTTYPE##', ##PARENTNODEID##, '##PARAMETER##');\" name=\"treeNode\" class=\"ContentTreeItem\">##ICON## <span class=\"Name\">##NODENAME##</span></span>";
            treeElem.SelectedNodeTemplate = "<span id=\"##OBJECTTYPE##_##NODEID##\" onclick=\"SelectNode(##NODEID##,'##OBJECTTYPE##', ##PARENTNODEID##, '##PARAMETER##');\" name=\"treeNode\"  class=\"ContentTreeItem ContentTreeSelectedItem\">##ICON## <span class=\"Name\">##NODENAME##</span></span>";
        }
        else
        {
            treeElem.NodeTemplate                = "<span onclick=\"SelectNode(##NODEID##, this);\" class=\"ContentTreeItem\">##ICON## <span class=\"Name\">##NODENAME##</span></span>";
            treeElem.DefaultItemTemplate         = "<span onclick=\"SelectNode('recentlyused', this);\" class=\"ContentTreeItem\">##ICON##<span class=\"Name\">##NODENAME##</span></span><div style=\"clear:both\"></div>";
            treeElem.SelectedDefaultItemTemplate = "<span onclick=\"SelectNode('recentlyused', this);\" class=\"ContentTreeItem ContentTreeSelectedItem\">##ICON##<span class=\"Name\">##NODENAME##</span></span><div style=\"clear:both\"></div>";
            treeElem.SelectedNodeTemplate        = "<span onclick=\"SelectNode(##NODEID##, this);\" class=\"ContentTreeItem ContentTreeSelectedItem\">##ICON## <span class=\"Name\">##NODENAME##</span></span>";

            // Register jquery
            ScriptHelper.RegisterJQuery(this.Page);

            string js =
                "function SelectNode(nodeid, sender){ " +
                "var selectedItem = $j('.ContentTreeSelectedItem'); " +
                "selectedItem.removeClass('ContentTreeSelectedItem'); " +
                "selectedItem.addClass('ContentTreeItem');" +
                "selectedItem = $j(sender);" +
                "selectedItem.removeClass('ContentTreeItem'); " +
                "selectedItem.addClass('ContentTreeSelectedItem'); " +
                "document.getElementById('" + this.treeElem.SelectedItemFieldId + "').value = nodeid;" +
                treeElem.GetOnSelectedItemBackEventReference() +
                "}";

            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "SelectTreeNode", ScriptHelper.GetScript(js));
        }

        // Setup event handler
        treeElem.OnItemSelected += new CMSAdminControls_UI_Trees_UniTree.ItemSelectedEventHandler(treeElem_OnItemSelected);
        treeElem.OnNodeCreated  += new CMSAdminControls_UI_Trees_UniTree.NodeCreatedEventHandler(treeElem_OnNodeCreated);
    }
Exemplo n.º 11
0
    /// <summary>
    /// Provides operations necessary to create and store new attachment.
    /// </summary>
    private void HandleAttachmentUpload(bool fieldAttachment)
    {
        // New attachment
        DocumentAttachment newAttachment = null;

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

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


            #region "Check permissions"

            if (CheckPermissions)
            {
                CheckNodePermissions(node);
            }

            #endregion


            // Check the allowed extensions
            CheckAllowedExtensions();

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

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

                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckOut(node, node.IsPublished, true);
                    }
                }

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

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

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

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

                // Check in the document
                if (AutoCheck)
                {
                    using (CMSActionContext ctx = new CMSActionContext()
                    {
                        LogEvents = false
                    })
                    {
                        VersionManager.CheckIn(node, null, null);
                    }
                }
            }

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

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

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

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;

            // Call aftersave javascript if exists
            if (!String.IsNullOrEmpty(AfterSaveJavascript))
            {
                if ((message == string.Empty) && (newAttachment != null))
                {
                    string url      = null;
                    string safeName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, SiteContext.CurrentSiteName);
                    if (node != null)
                    {
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID);
                        if (si != null)
                        {
                            bool usePermanent = DocumentURLProvider.UsePermanentUrls(si.SiteName);
                            if (usePermanent)
                            {
                                url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName));
                            }
                            else
                            {
                                url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(safeName, node.NodeAliasPath));
                            }
                        }
                    }
                    else
                    {
                        url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, safeName));
                    }
                    // Calling javascript function with parameters attachments url, name, width, height
                    if (!string.IsNullOrEmpty(AfterSaveJavascript))
                    {
                        Hashtable obj = new Hashtable();
                        if (ImageHelper.IsImage(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.IMG_URL]     = url;
                            obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName;
                            obj[DialogParameters.IMG_WIDTH]   = newAttachment.AttachmentImageWidth;
                            obj[DialogParameters.IMG_HEIGHT]  = newAttachment.AttachmentImageHeight;
                        }
                        else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension))
                        {
                            obj[DialogParameters.OBJECT_TYPE] = "audiovideo";
                            obj[DialogParameters.AV_URL]      = url;
                            obj[DialogParameters.AV_EXT]      = newAttachment.AttachmentExtension;
                            obj[DialogParameters.AV_WIDTH]    = DEFAULT_OBJECT_WIDTH;
                            obj[DialogParameters.AV_HEIGHT]   = DEFAULT_OBJECT_HEIGHT;
                        }
                        else
                        {
                            obj[DialogParameters.LINK_URL]  = url;
                            obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName;
                        }

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

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

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

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

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript);
        }
    }
Exemplo n.º 12
0
    /// <summary>
    /// Yes button click event handler.
    /// </summary>
    protected void btnYes_Click(object sender, EventArgs e)
    {
        // Prepare the where condition
        string where = "NodeID = " + NodeID;

        // Get the documents
        DataSet ds = null;

        if (chkAllCultures.Checked)
        {
            ds = TreeProvider.SelectNodes(SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, -1, false);
        }
        else
        {
            ds = TreeProvider.SelectNodes(SiteName, "/%", CultureCode, false, null, where, null, -1, false);
        }

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            // Get node alias
            var nodeAlias = DataHelper.GetStringValue(ds.Tables[0].Rows[0], "NodeAlias", string.Empty);
            // Get parent alias path

            var parentAliasPath = TreePathUtils.GetParentPath(DataHelper.GetStringValue(ds.Tables[0].Rows[0], "NodeAliasPath", string.Empty));

            // Delete the documents
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                var aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], string.Empty);
                var culture   = ValidationHelper.GetString(dr["DocumentCulture"], string.Empty);
                var className = ValidationHelper.GetString(dr["ClassName"], string.Empty);

                // Get the node
                var treeNode = TreeProvider.SelectSingleNode(SiteName, aliasPath, culture, false, className, false);

                if (treeNode != null)
                {
                    // Check delete permissions
                    var hasUserDeletePermission = !CheckPermissions || IsUserAuthorizedToDeleteDocument(treeNode, chkDestroy.Checked);

                    if (hasUserDeletePermission)
                    {
                        // Delete the document
                        try
                        {
                            DocumentHelper.DeleteDocument(treeNode, TreeProvider, chkAllCultures.Checked, chkDestroy.Checked);
                        }
                        catch (Exception ex)
                        {
                            var logData = new EventLogData(EventTypeEnum.Error, "Content", "DELETEDOC")
                            {
                                EventDescription = EventLogProvider.GetExceptionLogMessage(ex),
                                EventUrl         = RequestContext.RawURL,
                                UserID           = MembershipContext.AuthenticatedUser.UserID,
                                UserName         = MembershipContext.AuthenticatedUser.UserName,
                                NodeID           = treeNode.NodeID,
                                DocumentName     = treeNode.GetDocumentName(),
                                IPAddress        = RequestContext.UserHostAddress,
                                SiteID           = SiteContext.CurrentSiteID
                            };

                            Service.Resolve <IEventLogService>().LogEvent(logData);
                            AddAlert(GetString("ContentRequest.DeleteFailed") + ": " + ex.Message);
                            return;
                        }
                    }
                    // Access denied - not authorized to delete the document
                    else
                    {
                        AddAlert(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(treeNode.GetDocumentName())));
                        return;
                    }
                }
                else
                {
                    AddAlert(GetString("ContentRequest.ErrorMissingSource"));
                    return;
                }
            }

            RaiseOnAfterDelete();
        }
        else
        {
            AddAlert(GetString("DeleteDocument.CultureNotExists"));
        }
    }
Exemplo n.º 13
0
    private void DeleteAttachmentAction(Guid attGuid)
    {
        if (!createTempAttachment)
        {
            if (attGuid != Guid.Empty)
            {
                // Delete attachment
                if (FormGUID == Guid.Empty)
                {
                    // Ensure automatic check-in/ check-out
                    VersionManager vm = null;

                    // Check out the document
                    if (AutoCheck)
                    {
                        vm = VersionManager.GetInstance(TreeProvider);
                        vm.CheckOut(Node, Node.IsPublished, true);
                    }

                    // If the GUID column is set, use it to process additional actions for field attachments
                    if (!String.IsNullOrEmpty(GUIDColumnName))
                    {
                        DocumentHelper.DeleteAttachment(Node, GUIDColumnName);
                    }
                    else
                    {
                        DocumentHelper.DeleteAttachment(Node, attGuid);
                    }
                    DocumentHelper.UpdateDocument(Node, TreeProvider);

                    // Ensure full page refresh
                    if (AutoCheck)
                    {
                        ScriptHelper.RegisterStartupScript(Page, typeof(Page), "deleteRefresh", ScriptHelper.GetScript("InitRefresh_" + ClientID + "('', true, true, '" + attGuid + "', 'delete');"));
                    }
                    else
                    {
                        string script = "if (window.RefreshTree) { RefreshTree(" + Node.NodeParentID + ", " + Node.NodeID + "); }";
                        ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refreshTree", ScriptHelper.GetScript(script));
                    }

                    // Check in the document
                    if (AutoCheck)
                    {
                        if (vm != null)
                        {
                            vm.CheckIn(Node, null);
                        }
                    }

                    // Log synchronization task if not under workflow
                    if (!UsesWorkflow)
                    {
                        DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider);
                    }
                }
                else
                {
                    AttachmentInfoProvider.DeleteTemporaryAttachment(attGuid, SiteContext.CurrentSiteName);
                }
            }
        }

        LastAction = "delete";
        Value      = Guid.Empty;
    }
Exemplo n.º 14
0
    /// <summary>
    /// Gets a set of documents to be processed.
    /// </summary>
    /// <returns>Set of documents based on where condition and other settings</returns>
    private DataSet GetDocumentsToProcess()
    {
        string columns = SqlHelperClass.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture, SiteName");

        return(DocumentHelper.GetDocuments(TreeProvider.ALL_SITES, "/%", TreeProvider.ALL_CULTURES, false, TreeProvider.ALL_CLASSNAMES, GetCurrentWhere(), "NodeAliasPath DESC", -1, false, -1, columns, Tree));
    }
Exemplo n.º 15
0
    protected void wzdImport_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        var settings = ImportSettings;

        ClearErrorLabel();
        switch (e.CurrentStepIndex)
        {
        // Import type
        case 0:
        {
            if (!siteType.SelectTemplate)
            {
                try
                {
                    // Get blank web template
                    WebTemplateInfo wi = WebTemplateInfoProvider.GetWebTemplateInfo("BlankSite");
                    if (wi == null)
                    {
                        e.Cancel = true;
                        return;
                    }

                    WebTemplateID = wi.WebTemplateId;

                    string path = Server.MapPath(wi.WebTemplateFileName);
                    if (File.Exists(path + "\\template.zip"))
                    {
                        // Template from zip file
                        path += "\\" + ZipStorageProvider.GetZipFileName("template.zip");

                        settings.TemporaryFilesPath    = path;
                        settings.SourceFilePath        = path;
                        settings.TemporaryFilesCreated = true;
                        settings.RefreshMacroSecurity  = true;
                    }
                    else
                    {
                        // Init the settings
                        settings.TemporaryFilesCreated = false;
                        settings.SourceFilePath        = Server.MapPath(wi.WebTemplateFileName);
                        settings.RefreshMacroSecurity  = true;
                    }

                    if (!File.Exists(settings.SourceFilePath))
                    {
                        try
                        {
                            ImportProvider.CreateTemporaryFiles(settings);
                        }
                        catch (Exception ex)
                        {
                            SetErrorLabel(ex.Message);
                            e.Cancel = true;
                            return;
                        }
                    }

                    // Import all, but only add new data
                    settings.ImportType           = ImportTypeEnum.AllNonConflicting;
                    settings.ImportOnlyNewObjects = true;
                    settings.CopyFiles            = false;

                    // Allow bulk inserts for faster import, web templates must be consistent enough to allow this without collisions
                    settings.AllowBulkInsert = true;

                    ltlScriptAfter.Text = ScriptHelper.GetScript(
                        "var actDiv = document.getElementById('actDiv'); \n" +
                        "if (actDiv != null) { actDiv.style.display='block'; } \n" +
                        "var buttonsDiv = document.getElementById('buttonsDiv'); if (buttonsDiv != null) { buttonsDiv.disabled=true; } \n" +
                        "BTN_Disable('" + NextButton.ClientID + "'); \n" +
                        "StartSelectionTimer();"
                        );

                    // Preselect objects asynchronously
                    ctrlAsyncSelection.Parameter = "N";
                    ctrlAsyncSelection.RunAsync(SelectObjects, WindowsIdentity.GetCurrent());

                    e.Cancel = true;
                }
                catch (Exception ex)
                {
                    SetErrorLabel(ex.Message);
                    e.Cancel = true;
                    return;
                }
            }
            else
            {
                siteDetails.SiteName        = null;
                siteDetails.SiteDisplayName = null;
                selectTemplate.ReloadData();
            }

            wzdImport.ActiveStepIndex++;
        }
        break;

        // Template selection
        case 1:
        {
            if (!selectTemplate.ApplySettings())
            {
                e.Cancel = true;
                return;
            }

            // Init the settings
            WebTemplateInfo wi = WebTemplateInfoProvider.GetWebTemplateInfo(selectTemplate.WebTemplateId);
            if (wi == null)
            {
                throw new Exception("Web template not found.");
            }

            settings.IsWebTemplate = true;

            string path = Server.MapPath(wi.WebTemplateFileName);
            if (File.Exists(path + "\\template.zip"))
            {
                // Template from zip file
                path += "\\" + ZipStorageProvider.GetZipFileName("template.zip");

                settings.TemporaryFilesPath    = path;
                settings.SourceFilePath        = path;
                settings.TemporaryFilesCreated = true;
                settings.RefreshMacroSecurity  = true;
            }
            else
            {
                // Template from folder
                settings.TemporaryFilesCreated = false;
                settings.SourceFilePath        = path;
                settings.RefreshMacroSecurity  = true;
                try
                {
                    ImportProvider.CreateTemporaryFiles(settings);
                }
                catch (Exception ex)
                {
                    SetErrorLabel(ex.Message);
                    e.Cancel = true;
                    return;
                }
            }

            // Import all, but only add new data
            settings.ImportType           = ImportTypeEnum.AllNonConflicting;
            settings.ImportOnlyNewObjects = true;
            settings.CopyFiles            = false;

            // Allow bulk inserts for faster import, web templates must be consistent enough to allow this without collisions
            settings.AllowBulkInsert = true;

            ltlScriptAfter.Text = ScriptHelper.GetScript(
                "var actDiv = document.getElementById('actDiv');\n" +
                "if (actDiv != null) { actDiv.style.display='block'; }\n" +
                "var buttonsDiv = document.getElementById('buttonsDiv');\n" +
                "if (buttonsDiv != null) { buttonsDiv.disabled=true; }\n" +
                "BTN_Disable('" + NextButton.ClientID + "');\n" +
                "BTN_Disable('" + PreviousButton.ClientID + "');\n" +
                "StartSelectionTimer();"
                );

            // Preselect objects asynchronously
            ctrlAsyncSelection.Parameter = "T";
            ctrlAsyncSelection.RunAsync(SelectObjects, WindowsIdentity.GetCurrent());

            e.Cancel = true;
        }
        break;

        // Site details
        case 2:
            if (!siteDetails.ApplySettings())
            {
                e.Cancel = true;
                return;
            }

            // Update settings
            ImportSettings = siteDetails.Settings;

            if (!siteType.SelectTemplate && (ImportSettings.SiteName == InfoHelper.CODENAME_AUTOMATIC))
            {
                ImportSettings.SiteName = ValidationHelper.GetCodeName(settings.SiteDisplayName);
            }

            Culture = siteDetails.Culture;

            pnlImport.ReloadData(true);
            wzdImport.ActiveStepIndex++;
            break;

        // Objects selection
        case 3:
            if (!pnlImport.ApplySettings())
            {
                e.Cancel = true;
                return;
            }

            // Check licenses
            string error = ImportExportControl.CheckLicenses(settings);
            if (!string.IsNullOrEmpty(error))
            {
                SetErrorLabel(error);

                e.Cancel = true;
                return;
            }

            ImportSettings = pnlImport.Settings;

            PreviousButton.Enabled = false;
            NextButton.Enabled     = false;

            SiteName = settings.SiteName;
            Domain   = settings.SiteDomain;

            // Start asynchronous Import
            settings.SetSettings(ImportExportHelper.SETTINGS_DELETE_TEMPORARY_FILES, false);
            settings.DefaultProcessObjectType = ProcessObjectEnum.Selected;

            var manager = ImportManager;

            settings.LogContext = ctlAsyncImport.CurrentLog;
            manager.Settings    = settings;

            // Import site asynchronously
            ctlAsyncImport.RunAsync(ImportManager.Import, WindowsIdentity.GetCurrent());

            wzdImport.ActiveStepIndex++;
            break;

        // Import progress
        case 4:
            PreviousButton.Visible = false;

            CultureHelper.SetPreferredCulture(Culture);
            if (siteType.SelectTemplate)
            {
                // Done
                finishSite.Domain         = Domain;
                finishSite.SiteIsRunning  = SiteIsRunning;
                wzdImport.ActiveStepIndex = 6;
            }
            else
            {
                if (ImportManager.Settings.IsWarning())
                {
                    try
                    {
                        // Convert default culture
                        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
                        tree.ChangeSiteDefaultCulture(SiteName, Culture, "en-US");

                        // Change root GUID
                        TreeNode root = DocumentHelper.GetDocument(SiteName, "/", Culture, false, SystemDocumentTypes.Root, null, null, 1, false, null, tree);
                        if (root != null)
                        {
                            root.NodeGUID = Guid.NewGuid();
                            DocumentHelper.UpdateDocument(root, tree);
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("NewSiteWizard", "FINISH", ex);
                        SetErrorLabel(ex.Message);
                        e.Cancel = true;

                        NextButton.Enabled   = false;
                        CancelButton.Enabled = false;
                        mImportCanceled      = true;
                        return;
                    }
                }
                selectMaster.SiteName = SiteName;
                selectMaster.ReloadData();
            }
            break;

        case 5:
            if (!selectMaster.ApplySettings())
            {
                e.Cancel = true;
                return;
            }

            finishSite.Domain        = Domain;
            finishSite.SiteIsRunning = SiteIsRunning;
            break;

        // Other steps
        default:
            wzdImport.ActiveStepIndex = e.NextStepIndex;
            break;
        }
    }
    /// <summary>
    /// Saves metadata and file name of attachment.
    /// </summary>
    /// <param name="newFileName">New attachment file name</param>
    /// <returns>Returns True if attachment was successfully saved.</returns>
    private bool SaveAttachment(string newFileName)
    {
        bool saved = false;

        // Save new data
        try
        {
            DocumentAttachment attachment = InfoObject as DocumentAttachment;

            if (attachment != null)
            {
                // Set new file name
                if (!string.IsNullOrEmpty(newFileName))
                {
                    string name = newFileName + attachment.AttachmentExtension;
                    attachment.AttachmentName = name;

                    if (!IsAttachmentNameUnique(attachment))
                    {
                        // Attachment already exists.
                        ShowError(GetString("img.errors.fileexists"));
                        return(false);
                    }
                }

                // Ensure automatic check-in/ check-out
                bool autoCheck = false;

                var wm = WorkflowManager.GetInstance(TreeProvider);

                if (!nodeIsParent && (Node != null))
                {
                    var wi = wm.GetNodeWorkflow(Node);
                    if (wi != null)
                    {
                        autoCheck = !wi.UseCheckInCheckOut(SiteName);
                    }

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

                        if (IsWorkflowFinished(nextStep))
                        {
                            attachment = (DocumentAttachment)AttachmentInfo.Provider.Get(attachment.AttachmentGUID, SiteInfoProvider.GetSiteID(SiteName));
                        }
                    }
                }

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

                    attachment.AllowPartialUpdate = true;

                    if (!nodeIsParent && (Node != null))
                    {
                        DocumentHelper.UpdateAttachment(Node, attachment);

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

                    saved = true;

                    string fullRefresh = "false";

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

                    // Refresh parent update panel
                    LtlScript.Text = ScriptHelper.GetScript("RefreshMetaData(" + ScriptHelper.GetString(ExternalControlID) + ", '" + fullRefresh + "', '" + attachment.AttachmentGUID + "', 'refresh')");
                }
            }
        }
        catch (Exception ex)
        {
            ShowError(GetString("metadata.errors.processing"));
            Service.Resolve <IEventLogService>().LogException("Metadata editor", "SAVEATTACHMENT", ex);
        }

        return(saved);
    }
        // TODO Load element with XMLBeans or dynamic table
        // TODO Check every element/namespace for compliance
        public PackagePart Unmarshall(UnmarshallContext context, Stream in1)
        {
            PackagePropertiesPart coreProps = new PackagePropertiesPart(context
                                                                        .Package, context.PartName);

            // If the input stream is null then we try to get it from the
            // package.
            if (in1 == null)
            {
                if (context.ZipEntry != null)
                {
                    in1 = ((ZipPackage)context.Package).ZipArchive
                          .GetInputStream(context.ZipEntry);
                }
                else if (context.Package != null)
                {
                    // Try to retrieve the part inputstream from the URI
                    ZipEntry zipEntry;
                    try
                    {
                        zipEntry = ZipHelper
                                   .GetCorePropertiesZipEntry((ZipPackage)context
                                                              .Package);
                    }
                    catch (OpenXml4NetException)
                    {
                        throw new IOException(
                                  "Error while trying to get the part input stream.");
                    }
                    in1 = ((ZipPackage)context.Package).ZipArchive
                          .GetInputStream(zipEntry);
                }
                else
                {
                    throw new IOException(
                              "Error while trying to get the part input stream.");
                }
            }

            XmlDocument xmlDoc = null;

            try
            {
                xmlDoc = DocumentHelper.LoadDocument(in1);

                nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsmgr.AddNamespace("cp", namespaceCP);
                nsmgr.AddNamespace("dc", namespaceDC);
                nsmgr.AddNamespace("dcterms", namespaceDcTerms);
                nsmgr.AddNamespace("xsi", namespaceXSI);
                nsmgr.AddNamespace("cml", PackageNamespaces.MARKUP_COMPATIBILITY);
                nsmgr.AddNamespace("dcmitype", PackageNamespaces.DCMITYPE);


                //xmlDoc.ReadNode(reader);
                //try {
                //xmlDoc = xmlReader.read(in1);


                /* Check OPC compliance */

                // Rule M4.2, M4.3, M4.4 and M4.5/
                CheckElementForOPCCompliance(xmlDoc.DocumentElement);

                /* End OPC compliance */

                //} catch (DocumentException e) {
                //    throw new IOException(e.getMessage());
                //}
            }
            catch (XmlException ex)
            {
                throw new IOException(ex.Message, ex);
            }
            if (xmlDoc != null && xmlDoc.DocumentElement != null)
            {
                coreProps.SetCategoryProperty(LoadCategory(xmlDoc));
                coreProps.SetContentStatusProperty(LoadContentStatus(xmlDoc));
                coreProps.SetContentTypeProperty(LoadContentType(xmlDoc));
                coreProps.SetCreatedProperty(LoadCreated(xmlDoc));
                coreProps.SetCreatorProperty(LoadCreator(xmlDoc));
                coreProps.SetDescriptionProperty(LoadDescription(xmlDoc));
                coreProps.SetIdentifierProperty(LoadIdentifier(xmlDoc));
                coreProps.SetKeywordsProperty(LoadKeywords(xmlDoc));
                coreProps.SetLanguageProperty(LoadLanguage(xmlDoc));
                coreProps.SetLastModifiedByProperty(LoadLastModifiedBy(xmlDoc));
                coreProps.SetLastPrintedProperty(LoadLastPrinted(xmlDoc));
                coreProps.SetModifiedProperty(LoadModified(xmlDoc));
                coreProps.SetRevisionProperty(LoadRevision(xmlDoc));
                coreProps.SetSubjectProperty(LoadSubject(xmlDoc));
                coreProps.SetTitleProperty(LoadTitle(xmlDoc));
                coreProps.SetVersionProperty(LoadVersion(xmlDoc));
            }
            return(coreProps);
        }
Exemplo n.º 18
0
    /// <summary>
    /// Copies document(s).
    /// </summary>
    private void Copy(object parameter)
    {
        int      nodeId    = 0;
        int      oldSiteId = 0;
        int      newSiteId = 0;
        TreeNode node      = null;

        // Process Action parameters
        string[] parameters = ValidationHelper.GetString(parameter, "False;False").Split(';');
        if (parameters.Length != 2)
        {
            parameters = "False;False".Split(';');
        }
        bool includeChildNodes = ValidationHelper.GetBoolean(parameters[0], false);
        bool copyPermissions   = ValidationHelper.GetBoolean(parameters[1], false);

        ctlAsyncLog.Parameter = null;
        string siteName = CurrentSite.SiteName;

        AddLog(GetString("ContentRequest.StartCopy"));

        if (targetId == 0)
        {
            AddError(GetString("ContentRequest.ErrorMissingTarget"));
            return;
        }
        // Get target document
        TreeNode targetNode = TreeProvider.SelectSingleNode(targetId, TreeProvider.ALL_CULTURES);

        if (targetNode == null)
        {
            AddError(GetString("ContentRequest.ErrorMissingTarget"));
            return;
        }

        // No pages are allowed to be created under linked page.
        if (targetNode.IsLink)
        {
            AddError(GetString("contentrequest.errorlinkparent"));
            return;
        }

        try
        {
            PrepareNodeIdsForAllDocuments(siteName);
            if (DataHelper.DataSourceIsEmpty(documentsToProcess))
            {
                // Create where condition
                string where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true);
                string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture");

                documentsToProcess = TreeProvider.SelectNodes(siteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, TreeProvider.ALL_LEVELS, false, 0, columns);
            }

            if (!DataHelper.DataSourceIsEmpty(documentsToProcess))
            {
                foreach (DataRow nodeRow in documentsToProcess.Tables[0].Rows)
                {
                    // Get the current document
                    nodeId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0);
                    string className  = nodeRow["ClassName"].ToString();
                    string aliasPath  = nodeRow["NodeAliasPath"].ToString();
                    string docCulture = nodeRow["DocumentCulture"].ToString();
                    node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, TreeProvider);

                    if (node == null)
                    {
                        AddLog(string.Format(GetString("ContentRequest.DocumentNoLongerExists"), HTMLHelper.HTMLEncode(aliasPath)));
                        continue;
                    }

                    oldSiteId = node.NodeSiteID;

                    // Copy the document
                    TreeNode copiedNode = CopyNode(node, targetNode, includeChildNodes, TreeProvider, copyPermissions);
                    if (copiedNode != null)
                    {
                        node = copiedNode;
                    }
                    newSiteId = node.NodeSiteID;
                }
            }
        }
        catch (ThreadAbortException ex)
        {
            if (!CMSThread.Stopped(ex))
            {
                // Try to get ID of site
                int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
                // Log event to event log
                LogExceptionToEventLog("COPYDOC", "ContentRequest.CopyFailed", nodeId, ex, siteId);
            }
        }
        catch (Exception ex)
        {
            // Try to get ID of site
            int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
            // Log event to event log
            LogExceptionToEventLog("COPYDOC", "ContentRequest.CopyFailed", nodeId, ex, siteId);
            HandlePossibleErrors();
        }
        finally
        {
            if (multiple)
            {
                AddLog(GetString("ContentRequest.CopyOK"));
                ctlAsyncLog.Parameter = GetRefreshListingScript();
            }
            else
            {
                // Set moved document in current site or parent node if copy to other site
                if (oldSiteId == newSiteId)
                {
                    if (nodeId == 0)
                    {
                        // If processed node does not exist
                        HandleNonExistentDocument(siteName);
                    }
                    else
                    {
                        // Process result
                        if (node != null)
                        {
                            nodeId = (multiple ? nodeId : node.NodeID);

                            ctlAsyncLog.Parameter = "SelectNode(" + nodeId + ");RefreshTree(" + targetId + ", " + nodeId + ");";
                        }
                        else
                        {
                            AddError(GetString("ContentRequest.CopyFailed"));
                        }
                    }
                }
                else
                {
                    AddLog(GetString("ContentRequest.CopyOK"));
                    ctlAsyncLog.Parameter = string.Empty;
                }
            }
        }
    }
Exemplo n.º 19
0
 public void Should_Validate_Correctly_The_RUC()
 {
     Assert.IsTrue(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_RUC, "1798288377001"));
     Assert.IsFalse(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_RUC, "1798288377"));
 }
Exemplo n.º 20
0
    /// <summary>
    /// Links selected document(s).
    /// </summary>
    /// <param name="targetNodeId">Target node ID</param>
    /// <param name="sourceNodes">Nodes</param>
    /// <param name="performedAction">Action to be performed</param>
    /// <param name="copyPermissions">Indicates if the document permissions should be copied</param>
    private void Link(int targetNodeId, List <int> sourceNodes, Action performedAction, bool copyPermissions)
    {
        int      nodeId    = 0;
        int      oldSiteId = 0;
        int      newSiteId = 0;
        TreeNode node      = null;

        string siteName = (performedAction == Action.LinkDoc) ? targetSite.SiteName : CurrentSite.SiteName;

        AddLog(GetString("ContentRequest.StartLink"));

        if (targetNodeId == 0)
        {
            AddError(GetString("ContentRequest.ErrorMissingTarget"));
            return;
        }

        // Check if allow child type
        TreeNode targetNode = TreeProvider.SelectSingleNode(targetNodeId, TreeProvider.ALL_CULTURES);

        if (targetNode == null)
        {
            AddError(GetString("ContentRequest.ErrorMissingTarget"));
            return;
        }

        // No pages are allowed to be created under linked page.
        if (targetNode.IsLink)
        {
            AddError(GetString("contentrequest.errorlinkparent"));
            return;
        }

        try
        {
            PrepareNodeIdsForAllDocuments(siteName);

            if (DataHelper.DataSourceIsEmpty(documentsToProcess))
            {
                // Create where condition
                string where = new WhereCondition().WhereIn("NodeID", sourceNodes).ToString(true);
                string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName, NodeAliasPath, NodeLinkedNodeID");

                documentsToProcess = TreeProvider.SelectNodes(siteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, TreeProvider.ALL_LEVELS, false, 0, columns);
            }

            if (!DataHelper.DataSourceIsEmpty(documentsToProcess))
            {
                foreach (DataRow nodeRow in documentsToProcess.Tables[0].Rows)
                {
                    nodeId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0);
                    string className  = nodeRow["ClassName"].ToString();
                    string aliasPath  = nodeRow["NodeAliasPath"].ToString();
                    string docCulture = nodeRow["DocumentCulture"].ToString();

                    // Get document to link
                    node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, TreeProvider);

                    if (node == null)
                    {
                        AddLog(string.Format(GetString("ContentRequest.DocumentNoLongerExists"), HTMLHelper.HTMLEncode(aliasPath)));
                        continue;
                    }

                    oldSiteId = node.NodeSiteID;

                    // Link the document
                    TreeNode linkedNode = LinkNode(node, targetNode, TreeProvider, copyPermissions);
                    if (linkedNode != null)
                    {
                        node = linkedNode;
                    }
                    newSiteId = node.NodeSiteID;
                }
            }
        }
        catch (ThreadAbortException ex)
        {
            if (!CMSThread.Stopped(ex))
            {
                // Try to get ID of site
                int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
                // Log event to event log
                LogExceptionToEventLog("LINKDOC", "ContentRequest.LinkFailed", nodeId, ex, siteId);
            }
        }
        catch (Exception ex)
        {
            // Try to get ID of site
            int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID;
            // Log event to event log
            LogExceptionToEventLog("LINKDOC", "ContentRequest.LinkFailed", nodeId, ex, siteId);
            HandlePossibleErrors();
        }
        finally
        {
            if (multiple)
            {
                AddLog(GetString("ContentRequest.LinkOK"));
                ctlAsyncLog.Parameter = GetRefreshListingScript();
            }
            else
            {
                if (nodeId == 0)
                {
                    // If processed node does not exist
                    HandleNonExistentDocument(siteName);
                }
                else
                {
                    // Set linked document in current site or parent node if linked to other site
                    if (oldSiteId == newSiteId)
                    {
                        if (node == null)
                        {
                            AddError(GetString("ContentRequest.LinkFailed"));
                        }
                    }
                    else
                    {
                        AddLog(GetString("ContentRequest.LinkOK"));
                    }

                    // Process result
                    if (node != null)
                    {
                        ctlAsyncLog.Parameter = "SelectNode(" + targetNodeId + ");RefreshTree(" + targetNodeId + ", " + targetNodeId + ");";
                    }
                }
            }
        }
    }
Exemplo n.º 21
0
 public void Should_Validate_Correctly_The_CRCPF()
 {
     Assert.IsTrue(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_CRCPF, "123485989"));
     Assert.IsFalse(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_CRCPF, "12348598"));
     Assert.IsFalse(DocumentHelper.IsValidDocument(DocumentHelper.TYPE_CRCPF, "02348598"));
 }
Exemplo n.º 22
0
    /// <summary>
    /// Raises event postback event.
    /// </summary>
    /// <param name="eventArgument">Event argument</param>
    /// <param name="uniqueCode">Unique code</param>
    /// <param name="variantId">Variant ID</param>
    public void RaisePostBackEvent(string eventArgument, string uniqueCode, int variantId)
    {
        // Check permissions
        if (!CheckPermissions("Manage") ||
            stopProcessing)
        {
            return;
        }

        // Get the argument
        string arg = eventArgument.ToLowerCSafe();

        if (arg == "remove")
        {
            // Remove variant action
            int documentId = 0;

            if (VariantMode == VariantModeEnum.MVT)
            {
                // Is MVT zone => remove the MVT variant
                MVTVariantInfo variantObj = MVTVariantInfoProvider.GetMVTVariantInfo(variantId);
                if (variantObj != null)
                {
                    // Delete the variant
                    MVTVariantInfoProvider.DeleteMVTVariantInfo(variantObj);
                    documentId = variantObj.MVTVariantDocumentID;
                }
            }
            else if (VariantMode == VariantModeEnum.ContentPersonalization)
            {
                // Is Content personalization zone => remove the Content personalization variant
                ContentPersonalizationVariantInfo variantObj = ContentPersonalizationVariantInfoProvider.GetContentPersonalizationVariant(variantId);
                if (variantObj != null)
                {
                    // Delete the variant
                    ContentPersonalizationVariantInfoProvider.DeleteContentPersonalizationVariant(variantObj);
                    documentId = variantObj.VariantDocumentID;
                }
            }
            else
            {
                return;
            }

            // Log widget variant synchronization
            if (documentId > 0)
            {
                TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
                TreeNode     node = DocumentHelper.GetDocument(documentId, tree);
                DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree);
            }

            switch (SliderMode)
            {
            // Remove zone variant
            case VariantTypeEnum.Zone:
                if ((WebPartZoneControl != null) && (WebPartZoneControl.ZoneInstance != null))
                {
                    // Remove the variant from WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.
                    // It is necessary to remove the variants from the PartInstanceVariants list manually because the PageLoad method has already run
                    // and the PartInstanceVariants list was populated with the old values.
                    WebPartZoneControl.RemoveVariantFromCache(variantId);
                }
                break;

            // Remove web part or widget variant
            case VariantTypeEnum.WebPart:
            case VariantTypeEnum.Widget:
                if ((WebPartControl != null) && (WebPartControl.PartInstance != null))
                {
                    // Remove the variant from WebPartControls.PartInstance.PartInstanceVariants.
                    // It is necessary to remove the variants from the PartInstanceVariants list manually because the PageLoad method has already run
                    // and the PartInstanceVariants list was populated with the old values.
                    WebPartControl.RemoveVariantFromCache(variantId);

                    // If there are no other variants present, set the VariantMode to None to allow refreshing the add variant buttons.
                    if ((WebPartControl.PartInstance.PartInstanceVariants == null) || (WebPartControl.PartInstance.PartInstanceVariants.Count == 0))
                    {
                        mVariantMode = VariantModeEnum.None;
                    }
                }
                break;

            default:
                break;
            }

            // Refresh the variant slider position => choose the last variant
            ltrScript.Text = ScriptHelper.GetScript(
                @"cpVariantSliderPositionElem = GetCPVariantSliderPositionElem();
                UpdateVariantPosition('" + uniqueCode + @"', '-1');
                SaveSlidersConfiguration();");
        }
    }
Exemplo n.º 23
0
    /// <summary>
    /// Creates document.
    /// </summary>
    public int Save()
    {
        // Validate input data
        string message = new Validator().NotEmpty(txtDocumentName.Text.Trim(), GetString("om.enterdocumentname")).Result;

        if (message != String.Empty)
        {
            ShowError(message);
            return(0);
        }

        if (mNode == null)
        {
            ShowError(GetString("general.invalidparameters"));
            return(0);
        }

        // Select parent node
        TreeNode parent = mTree.SelectSingleNode(SiteContext.CurrentSiteName, ucPath.Value.ToString(), TreeProvider.ALL_CULTURES, false, null, false);

        if (parent == null)
        {
            ShowError(GetString("om.pathdoesnotexists"));
            return(0);
        }

        // Check security
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(parent.NodeID, mNode.NodeClassName))
        {
            RedirectToAccessDenied(GetString("cmsdesk.notauthorizedtocreatedocument"));
            return(0);
        }

        var newDocument = ProcessAction(mNode, parent, "copynode", false, true, true);

        if (newDocument == null)
        {
            ShowError(string.Format(GetString("om.invalidchildtype"), parent.ClassName));
            return(0);
        }

        // Get all language translations
        var documents = DocumentHelper.GetDocuments()
                        .All()
                        .OnCurrentSite()
                        .AllCultures()
                        .WhereEquals("NodeID", newDocument.NodeID);

        // Limit length to 100 characters
        string documentName = TextHelper.LimitLength(txtDocumentName.Text.Trim(), 100, String.Empty);

        // Update all documents and delete all aliases
        foreach (var document in documents)
        {
            UpdateDocument(document, documentName);
            DocumentAliasInfoProvider.DeleteNodeAliases(document.NodeID);

            // Set new node to any updated document to have updated info
            newDocument = document;
        }

        // Create new AB variant if AB test defined
        if (!CreateABVariant(newDocument))
        {
            return(0);
        }

        // Get the page mode
        if (PortalContext.ViewMode != ViewModeEnum.EditLive)
        {
            PortalContext.ViewMode = ViewModeEnum.EditForm;
        }
        txtDocumentName.Text = String.Empty;

        return(newDocument.NodeID);
    }
Exemplo n.º 24
0
 /// <summary>
 /// Returns a query that selects published pages of type Song.
 /// </summary>
 public static DocumentQuery <Song> GetSongs()
 {
     return(DocumentHelper.GetDocuments <Song>().PublishedVersion().Published());
 }
 /// <summary>
 /// Copy documents section.
 /// </summary>
 /// <param name="source">Source document</param>
 /// <param name="target">Target document</param>
 /// <param name="tree">Tree provider</param>
 private void CopyDocumentSection(TreeNode source, TreeNode target, TreeProvider tree)
 {
     DocumentHelper.CopyDocument(source, target, true, tree);
 }
    private void ReloadData()
    {
        if (StopProcessing)
        {
            // Do nothing
            gridDocs.StopProcessing = true;
            editDoc.StopProcessing  = true;
        }
        else
        {
            if (((AllowUsers == UserContributionAllowUserEnum.Authenticated) || (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)) &&
                !AuthenticationHelper.IsAuthenticated())
            {
                // Not authenticated, do not display anything
                pnlList.Visible = false;
                pnlEdit.Visible = false;

                StopProcessing = true;
            }
            else
            {
                SetContext();

                // Hide document list
                gridDocs.Visible = false;

                // If the list of documents should be displayed ...
                if (DisplayList)
                {
                    // Get all documents of the current user
                    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

                    // Generate additional where condition
                    WhereCondition condition = new WhereCondition(WhereCondition);

                    if (!String.IsNullOrEmpty(ClassNames))
                    {
                        condition.WhereIn("ClassName", ClassNames.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries));
                    }

                    // Add user condition
                    if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)
                    {
                        condition.WhereEquals("NodeOwner", MembershipContext.AuthenticatedUser.UserID);
                    }

                    // Get the documents
                    var query =
                        DocumentHelper.GetDocuments()
                        .OnSite(SiteName)
                        .Path(MacroResolver.ResolveCurrentPath(Path))
                        .Where(condition)
                        .OrderBy(OrderBy)
                        .Published(SelectOnlyPublished)
                        .NestingLevel(MaxRelativeLevel)
                        .CheckPermissions(CheckPermissions);

                    TreeProvider.SetQueryCultures(query, CultureCode, CombineWithDefaultCulture);

                    // Do not apply published from / to columns to make sure the published information is correctly evaluated
                    query.Properties.ExcludedVersionedColumns = new[] { "DocumentPublishFrom", "DocumentPublishTo" };

                    var ds = query.Result;

                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        // Display and initialize grid if datasource is not empty
                        gridDocs.Visible            = true;
                        gridDocs.DataSource         = ds;
                        gridDocs.OrderBy            = OrderBy;
                        editDoc.AlternativeFormName = AlternativeFormName;
                    }
                }

                bool isAuthorizedToCreateDoc = false;
                if (ParentNode != null)
                {
                    // Check if single class name is set
                    string className = (!string.IsNullOrEmpty(AllowedChildClasses) && !AllowedChildClasses.Contains(";")) ? AllowedChildClasses : null;

                    // Check user's permission to create new document if allowed
                    isAuthorizedToCreateDoc = !CheckPermissions || MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(ParentNodeID, className);
                    // Check group's permission to create new document if allowed
                    isAuthorizedToCreateDoc &= CheckGroupPermission("createpages");

                    if (!CheckDocPermissionsForInsert && CheckPermissions)
                    {
                        // If document permissions are not required check create permission on parent document
                        isAuthorizedToCreateDoc = MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(ParentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed;
                    }

                    if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)
                    {
                        if (VirtualContext.ReadonlyMode)
                        {
                            isAuthorizedToCreateDoc = false;
                        }
                        else
                        {
                            // Check if user is document owner (or global admin)
                            isAuthorizedToCreateDoc = isAuthorizedToCreateDoc &&
                                                      ((ParentNode.NodeOwner == MembershipContext.AuthenticatedUser.UserID) ||
                                                       MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin));
                        }
                    }
                }

                // Enable/disable inserting new document
                pnlNewDoc.Visible = (isAuthorizedToCreateDoc && AllowInsert);

                if (!gridDocs.Visible && !pnlNewDoc.Visible && pnlList.Visible)
                {
                    // Not authenticated to create new docs and grid is hidden
                    StopProcessing = true;
                }

                ReleaseContext();
            }
        }
    }
    /// <summary>
    /// Process additional department tasks.
    /// </summary>
    public void ProcessDepartment(object sender, EventArgs e)
    {
        TreeNode editedNode = Form.EditedObject as TreeNode;

        // Get department template source document
        TreeNode sourceNode = DocumentHelper.GetDocument(SiteContext.CurrentSiteName, DepartmentTemplatePath, null, true, null, null, null, TreeProvider.ALL_LEVELS, false, null, TreeProvider);

        // Copy relevant template data to department document. Proceed only when creating a department, updating a department must not rewrite its data with template's data.
        if (Form.IsInsertMode && (sourceNode != null))
        {
            var excludeColumns = new []
            {
                "DocumentName",
                "NodeAlias",
                "DocumentTagGroupID",
                "DocumentStylesheetID",
                "DocumentPublishFrom",
                "DocumentPublishTo"
            };
            DocumentHelper.CopyNodeData(sourceNode, editedNode, new CopyNodeDataSettings(true, true, false, true, true, false, false, false, excludeColumns));
            DocumentHelper.UpdateDocument(editedNode, TreeProvider);
        }


        #region "Create department tag group"

        // Get tag group info
        TagGroupInfo tgi = TagGroupInfoProvider.GetTagGroupInfo(editedNode.DocumentTagGroupID);

        // If not exist, create new tag group and set it to document
        if (tgi == null)
        {
            // Populate tag group info fields
            tgi = new TagGroupInfo();
            tgi.TagGroupDisplayName = editedNode.GetDocumentName();
            tgi.TagGroupName        = editedNode.NodeGUID.ToString();
            tgi.TagGroupDescription = "";
            tgi.TagGroupSiteID      = SiteContext.CurrentSiteID;
            tgi.TagGroupIsAdHoc     = false;

            // Store tag group info to DB
            TagGroupInfoProvider.SetTagGroupInfo(tgi);

            // Update document Tag group ID
            editedNode.DocumentTagGroupID = tgi.TagGroupID;
            DocumentHelper.UpdateDocument(editedNode, TreeProvider);
        }

        #endregion


        if (!DataHelper.DataSourceIsEmpty(TemplateDocuments))
        {
            // List of selected documents
            string selectedDocs = ";" + Value + ";";

            // Get already created documents under edited document
            DataSet       dsExistingDocs = DocumentHelper.GetDocuments(SiteContext.CurrentSiteName, editedNode.NodeAliasPath + "/%", editedNode.DocumentCulture, true, null, null, null, 1, false, 0, "NodeAlias, " + DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, null);
            StringBuilder sbExistDocs    = new StringBuilder();

            // Process existing documents to obtain list of aliases
            foreach (DataRow drExistDoc in dsExistingDocs.Tables[0].Rows)
            {
                sbExistDocs.Append(";");
                sbExistDocs.Append(drExistDoc["NodeAlias"].ToString().ToLowerCSafe());
            }
            sbExistDocs.Append(";");
            string existingDocs = sbExistDocs.ToString();

            // Set same ordering as for original template documents
            bool orgUseAutomaticOrdering = TreeProvider.UseAutomaticOrdering;
            TreeProvider.UseAutomaticOrdering = false;

            // Process template documents
            foreach (DataRow drDoc in TemplateDocuments.Tables[0].Rows)
            {
                if (DocumentHelper.IsDocumentTypeAllowed(editedNode, ValidationHelper.GetInteger(drDoc["NodeClassID"], 0)))
                {
                    string nodeAlias     = drDoc["NodeAlias"].ToString().ToLowerCSafe();
                    string contNodeAlias = ";" + nodeAlias + ";";

                    // Set marks
                    bool existing = existingDocs.Contains(contNodeAlias);
                    bool selected = selectedDocs.Contains(contNodeAlias);

                    int      nodeId     = ValidationHelper.GetInteger(drDoc["NodeID"], 0);
                    string   docCulture = ValidationHelper.GetString(drDoc["DocumentCulture"], "");
                    TreeNode srcNode    = DocumentHelper.GetDocument(nodeId, docCulture, editedNode.TreeProvider);

                    // Check if section exists
                    if (srcNode != null)
                    {
                        // Copy or remove marked document sections
                        if (selected)
                        {
                            if (!existing)
                            {
                                CopyDocumentSection(srcNode, editedNode, TreeProvider);
                            }
                        }
                        else
                        {
                            if (existing)
                            {
                                // Select node to delete
                                var aliasPath = editedNode.NodeAliasPath + "/" + nodeAlias;
                                var combineWithDefaultCulture = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSCombineWithDefaultCulture");

                                TreeProvider tree    = new TreeProvider(MembershipContext.AuthenticatedUser);
                                TreeNode     delNode = tree.SelectSingleNode(SiteContext.CurrentSiteName, aliasPath, LocalizationContext.PreferredCultureCode, combineWithDefaultCulture);

                                if (delNode != null)
                                {
                                    DeleteDocumentSection(delNode, TreeProvider);
                                }
                            }
                        }

                        // Process additional operations
                        if (selected && !existing)
                        {
                            switch (nodeAlias)
                            {
                            // Create department forum
                            case FORUM_DOCUMENT_ALIAS:
                                CreateDepartmentForumGroup(editedNode);
                                CreateDepartmentForumSearchIndex(editedNode);
                                break;

                            // Create media library
                            case MEDIA_DOCUMENT_ALIAS:
                                CreateDepartmentMediaLibrary(editedNode);
                                break;
                            }
                        }
                    }
                }
            }

            // Set previous ordering
            TreeProvider.UseAutomaticOrdering = orgUseAutomaticOrdering;
        }
        mDocumentSaved = true;
    }
 /// <summary>
 /// Returns a query that selects published pages of type LandingPage.
 /// </summary>
 public static DocumentQuery <LandingPage> GetLandingPages()
 {
     return(DocumentHelper.GetDocuments <LandingPage>().PublishedVersion().Published());
 }
Exemplo n.º 29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        const string CONTENT_CMSDESK_FOLDER = "~/CMSModules/Content/CMSDesk/";

        // Register script files
        ScriptHelper.RegisterScriptFile(this, CONTENT_CMSDESK_FOLDER + "EditTabs.js");

        bool   checkCulture       = false;
        bool   splitViewSupported = false;
        string action             = QueryHelper.GetString("action", "edit").ToLowerCSafe();

        switch (action)
        {
        // New dialog / new page form
        case "new":
            int classId = QueryHelper.GetInteger("classid", 0);
            if (classId <= 0)
            {
                // Get by class name if specified
                string className = QueryHelper.GetString("classname", string.Empty);
                if (className != string.Empty)
                {
                    classInfo = DataClassInfoProvider.GetDataClassInfo(className);
                    if (classInfo != null)
                    {
                        classId = classInfo.ClassID;
                    }
                }
            }

            const string EC_PRODUCTS_FOLDER = "~/CMSModules/Ecommerce/Pages/Tools/Products/";

            if (classId > 0)
            {
                viewpage = ResolveUrl(CONTENT_CMSDESK_FOLDER + "Edit/Edit.aspx");

                // Check if document type is allowed under parent node
                if (parentNodeID > 0)
                {
                    // Get the node
                    TreeNode = Tree.SelectSingleNode(parentNodeID, TreeProvider.ALL_CULTURES);
                    if (TreeNode != null)
                    {
                        if (!DocumentHelper.IsDocumentTypeAllowed(TreeNode, classId))
                        {
                            viewpage = CONTENT_CMSDESK_FOLDER + "NotAllowed.aspx?action=child";
                        }
                    }
                }

                // Use product page when product type is selected
                classInfo = classInfo ?? DataClassInfoProvider.GetDataClassInfo(classId);
                if ((classInfo != null) && (classInfo.ClassIsProduct))
                {
                    viewpage = ResolveUrl(EC_PRODUCTS_FOLDER + "Product_New.aspx");
                }
            }
            else
            {
                if (parentNodeID > 0)
                {
                    viewpage = EC_PRODUCTS_FOLDER + "New_ProductOrSection.aspx";
                }
                else
                {
                    viewpage = EC_PRODUCTS_FOLDER + "Product_New.aspx?parentNodeId=0";
                }
            }
            break;

        case "delete":
            // Delete dialog
            viewpage = CONTENT_CMSDESK_FOLDER + "Delete.aspx";
            break;

        default:
            // Edit mode
            viewpage           = CONTENT_CMSDESK_FOLDER + "Edit/edit.aspx?mode=editform";
            splitViewSupported = true;

            // Ensure class info
            if ((classInfo == null) && (Node != null))
            {
                classInfo = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName);
            }

            // Check explicit editing page url
            if ((classInfo != null) && !string.IsNullOrEmpty(classInfo.ClassEditingPageURL))
            {
                viewpage = URLHelper.AppendQuery(ResolveUrl(classInfo.ClassEditingPageURL), RequestContext.CurrentQueryString);
            }

            checkCulture = true;
            break;
        }

        // If culture version should be checked, check
        if (checkCulture)
        {
            // Check (and ensure) the proper content culture
            if (!CheckPreferredCulture())
            {
                RefreshParentWindow();
            }

            // Check split mode
            bool isSplitMode = PortalUIHelper.DisplaySplitMode;
            bool combineWithDefaultCulture = !isSplitMode && SiteInfoProvider.CombineWithDefaultCulture(SiteContext.CurrentSiteName);

            var nodeId = QueryHelper.GetInteger("nodeid", 0);
            TreeNode = Tree.SelectSingleNode(nodeId, CultureCode, combineWithDefaultCulture);
            if (TreeNode == null)
            {
                // Document does not exist -> redirect to new culture version creation dialog
                viewpage = ProductUIHelper.GetNewCultureVersionPageUrl();
            }
        }

        // Apply the additional transformations to the view page URL
        viewpage = URLHelper.AppendQuery(viewpage, RequestContext.CurrentQueryString);
        viewpage = URLHelper.RemoveParameterFromUrl(viewpage, "mode");
        viewpage = URLHelper.AddParameterToUrl(viewpage, "mode", "productssection");
        viewpage = ResolveUrl(viewpage);
        viewpage = URLHelper.AddParameterToUrl(viewpage, "hash", QueryHelper.GetHash(viewpage));

        // Split mode enabled
        if (splitViewSupported && PortalUIHelper.DisplaySplitMode && (TreeNode != null) && (action == "edit" || action == "preview" || (TreeNode.IsPublished && action == "livesite")))
        {
            viewpage = DocumentUIHelper.GetSplitViewUrl(viewpage);
        }

        URLHelper.Redirect(UrlResolver.ResolveUrl(viewpage));
    }
Exemplo n.º 30
0
    private void PublishAndFinish(object parameter)
    {
        TreeNode node = null;

        Tree.AllowAsyncActions = false;
        CanceledString         = ResHelper.GetString("content.publishcanceled", currentCulture);
        try
        {
            // Begin log
            AddLog(ResHelper.GetString("content.preparingdocuments", currentCulture));

            // Get the documents
            DataSet documents = GetDocumentsToProcess();

            if (!DataHelper.DataSourceIsEmpty(documents))
            {
                // Create instance of workflow manager class
                WorkflowManager wm = new WorkflowManager(Tree);

                // Begin publishing
                AddLog(ResHelper.GetString("content.publishingdocuments", currentCulture));
                foreach (DataTable classTable in documents.Tables)
                {
                    foreach (DataRow nodeRow in classTable.Rows)
                    {
                        // Get the current document
                        string className  = ValidationHelper.GetString(nodeRow["ClassName"], string.Empty);
                        string aliasPath  = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty);
                        string docCulture = ValidationHelper.GetString(nodeRow["DocumentCulture"], string.Empty);
                        string siteName   = ValidationHelper.GetString(nodeRow["SiteName"], string.Empty);

                        node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, -1, false, null, Tree);

                        // Publish document
                        if (!Publish(node, wm))
                        {
                            // Add log record
                            AddLog(HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.GetValue("DocumentCulture") + ")"));
                        }
                        else
                        {
                            AddLog(string.Format(ResHelper.GetString("content.publishedalready"), HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.GetValue("DocumentCulture") + ")")));
                        }
                    }
                }
                CurrentInfo = GetString("workflowdocuments.publishcomplete");
            }
            else
            {
                AddError(ResHelper.GetString("content.nothingtopublish", currentCulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty);
            if (state == CMSThread.ABORT_REASON_STOP)
            {
                // When canceled
                CurrentInfo = CanceledString;
            }
            else
            {
                int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID;
                // Log error
                LogExceptionToEventLog("PUBLISHDOC", "content.publishfailed", ex, siteId);
            }
        }
        catch (Exception ex)
        {
            int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID;
            // Log error
            LogExceptionToEventLog("PUBLISHDOC", "content.publishfailed", ex, siteId);
        }
    }