protected void Page_Load(object sender, EventArgs e) { // Initialize modal page RegisterEscScript(); ScriptHelper.RegisterWOpenerScript(Page); if (QueryHelper.ValidateHash("hash")) { externalControlID = QueryHelper.GetString("externalControlID", string.Empty); string title = GetString("Relationship.AddRelatedDocs"); Page.Title = title; CurrentMaster.Title.TitleText = title; CurrentMaster.Title.TitleImage = GetImageUrl("/Objects/CMS_RelationshipName/new.png"); btnSave.Click += new EventHandler(btnSave_Click); btnClose.Attributes.Add("onclick", "return CloseDialog();"); AddNoCacheTag(); addRelatedDocument.ShowButtons = false; nodeId = QueryHelper.GetInteger("nodeid", 0); if (nodeId > 0) { // Get the node node = TreeProvider.SelectSingleNode(nodeId, CMSContext.PreferredCultureCode, TreeProvider.CombineWithDefaultCulture); if (node != null) { // Check read permissions if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } else { lblInfo.Visible = false; } // Set tree node addRelatedDocument.TreeNode = node; } else { btnSave.Enabled = false; } } } else { // Hide all controls btnSave.Visible = false; btnClose.Visible = false; addRelatedDocument.Visible = false; string url = ResolveUrl("~/CMSMessages/Error.aspx?title=" + GetString("dialogs.badhashtitle") + "&text=" + GetString("dialogs.badhashtext") + "&cancel=1"); ltlScript.Text = ScriptHelper.GetScript("window.location = '" + url + "';"); } }
protected void Page_Load(object sender, EventArgs e) { // Initialize modal page RegisterEscScript(); ScriptHelper.RegisterWOpenerScript(Page); if (QueryHelper.ValidateHash("hash")) { externalControlID = QueryHelper.GetString("externalControlID", string.Empty); string title = GetString("Relationship.AddRelatedDocs"); Page.Title = title; PageTitle.TitleText = title; Save += btnSave_Click; AddNoCacheTag(); addRelatedDocument.ShowButtons = false; if (EditedDocument != null) { // Get the node node = EditedDocument; if (node != null) { // Check read permissions if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } else { lblInfo.Visible = false; } // Set tree node addRelatedDocument.TreeNode = node; } } } else { addRelatedDocument.Visible = false; string url = ResolveUrl("~/CMSMessages/Error.aspx?title=" + GetString("dialogs.badhashtitle") + "&text=" + GetString("dialogs.badhashtext") + "&cancel=1"); ltlScript.Text = ScriptHelper.GetScript("window.location = '" + url + "';"); } }
/// <summary> /// Handles the OnAfterSave event of the EditForm control. /// </summary> protected void EditForm_OnAfterSave(object sender, EventArgs e) { if (EditForm.EditedObject != null) { // Log widget variant synchronization ContentPersonalizationVariantInfo variantInfo = (ContentPersonalizationVariantInfo)UIFormControl.EditedObject; // Clear cache CacheHelper.TouchKey("om.personalizationvariant|bytemplateid|" + variantInfo.VariantPageTemplateID); if (variantInfo.VariantDocumentID > 0) { // Log synchronization TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode node = tree.SelectSingleDocument(variantInfo.VariantDocumentID); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } }
protected void Page_Load(object sender, EventArgs e) { string culture = RequiredCulture; newCultureVersion.RequiresDialog = RequiresDialog; newCultureVersion.Tree = Tree; newCultureVersion.NodeID = NodeID; newCultureVersion.Node = Node; newCultureVersion.Mode = Mode; newCultureVersion.RequiredCulture = culture; // Register progress script ScriptHelper.RegisterLoader(Page); // Check if the culture is valid bool isCultureAllowed = CheckPreferredCulture(culture); if (!isCultureAllowed) { ShowWarning(GetString("licensevalidation.newdocumentcultureversion")); newCultureVersion.Visible = false; return; } if (NodeID > 0) { // Fill in the existing culture versions TreeNode node = Tree.SelectSingleNode(NodeID, TreeProvider.ALL_CULTURES); if (node != null) { EnsureProductBreadcrumbs(PageBreadcrumbs, GetString("content.newcultureversiontitle"), !node.IsProduct(), true, false); } else { RedirectToInformation("editeddocument.notexists"); } } else { RedirectToInformation("editeddocument.notexists"); } }
private void UniGridAlias_OnAction(string actionName, object actionArgument) { // Manage edit and delete int aliasID = ValidationHelper.GetInteger(actionArgument, 0); string action = DataHelper.GetNotEmpty(actionName, String.Empty).ToLowerCSafe(); TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); DocumentAliasInfo dai = DocumentAliasInfoProvider.GetDocumentAliasInfo(aliasID); if (dai != null) { // Find node TreeNode node = tree.SelectSingleNode(dai.AliasNodeID); if (node != null) { // Check modify permissions if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { return; } // Edit only if node exists if (action == "edit") { URLHelper.Redirect("Alias_Edit.aspx?nodeid=" + node.NodeID + "&aliasid=" + aliasID + "&defaultNodeID=" + NodeID + "&dialog=1"); } } // Delete even if node does not exist if (action == "delete") { if (aliasID > 0) { // Delete DocumentAliasInfoProvider.DeleteDocumentAliasInfo(aliasID); // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } } }
/// <summary> /// Publishes document. /// </summary> /// <param name="node">Node to publish</param> /// <param name="wm">Workflow manager</param> /// <param name="currentStep">Current workflow step</param> /// <returns>TRUE if operation fails</returns> private bool Publish(TreeNode node, WorkflowManager wm, WorkflowStepInfo currentStep) { string pathCulture = HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"); bool alreadyPublished = (currentStep == null) || currentStep.StepIsPublished; if (!alreadyPublished) { // Publish document currentStep = wm.PublishDocument(node, null); } // Document is already published, check if still under workflow if (alreadyPublished && (currentStep != null) && currentStep.StepIsPublished) { WorkflowScopeInfo wsi = wm.GetNodeWorkflowScope(node); if (wsi == null) { DocumentHelper.ClearWorkflowInformation(node); VersionManager vm = VersionManager.GetInstance(node.TreeProvider); vm.RemoveWorkflow(node); } } // Document already published if (alreadyPublished) { AddLog(string.Format(ResHelper.GetString("content.publishedalready"), pathCulture)); } else if (!currentStep.StepIsPublished) { AddError(string.Format(ResHelper.GetString("content.PublishWasApproved"), pathCulture)); return(true); } else { // Add log record AddLog(pathCulture); } return(false); }
/// <summary> /// Creates forum search index. /// </summary> /// <param name="departmentNode">Department node</param> private void CreateDepartmentForumSearchIndex(TreeNode departmentNode) { string codeName = "forums_department_" + departmentNode.NodeGUID; string departmentName = departmentNode.GetDocumentName(); SearchIndexInfo sii = SearchIndexInfoProvider.GetSearchIndexInfo(codeName); if (sii == null) { // Create search index info sii = new SearchIndexInfo(); sii.IndexName = codeName; string suffix = " - Forums"; sii.IndexDisplayName = TextHelper.LimitLength(departmentName, 200 - suffix.Length, "") + suffix; sii.IndexAnalyzerType = SearchAnalyzerTypeEnum.StandardAnalyzer; sii.IndexType = PredefinedObjectType.FORUM; sii.IndexIsCommunityGroup = false; sii.IndexProvider = SearchIndexInfo.LUCENE_SEARCH_PROVIDER; // Create search index settings info SearchIndexSettingsInfo sisi = new SearchIndexSettingsInfo(); sisi.ID = Guid.NewGuid(); sisi.Type = SearchIndexSettingsInfo.TYPE_ALLOWED; sisi.SiteName = SiteContext.CurrentSiteName; sisi.ForumNames = "*_department_" + departmentNode.NodeGUID; // Create settings item SearchIndexSettings sis = new SearchIndexSettings(); // Update settings item sis.SetSearchIndexSettingsInfo(sisi); // Update xml value sii.IndexSettings = sis; SearchIndexInfoProvider.SetSearchIndexInfo(sii); // Assign to current website and current culture SearchIndexSiteInfoProvider.AddSearchIndexToSite(sii.IndexID, SiteContext.CurrentSiteID); CultureInfo ci = CultureInfoProvider.GetCultureInfo(departmentNode.DocumentCulture); SearchIndexCultureInfoProvider.AddSearchIndexCulture(sii.IndexID, ci.CultureID); } }
private static List <NavigationNode> GetColumnNavigationNodes(List <TreeNode> children, string siteName, string cultureCode) { var items = new List <NavigationNode>(); foreach (var item in children) { if (item.ClassName.Equals("Zurn.NavigationColumnComponent")) { var node = new NavigationNode(); node.Section1Title = ValidationHelper.GetString(item["Title1"], string.Empty); TreeNode section1Link = tree.SelectSingleNode(ValidationHelper.GetGuid(item["TitleLink1"], new Guid()), cultureCode, siteName); if (section1Link != null) { node.Section1Link = ResolveLinkSrc(section1Link); node.Section1Target = ResolveLinkTarget(section1Link); } node.Section1Items = SetSectionItems(siteName, cultureCode, item, relationshipRow1); node.Section2Title = ValidationHelper.GetString(item["Title2"], string.Empty); TreeNode section2Link = tree.SelectSingleNode(ValidationHelper.GetGuid(item["TitleLink2"], new Guid()), cultureCode, siteName); if (section2Link != null) { node.Section2Link = ResolveLinkSrc(section2Link); node.Section2Target = ResolveLinkTarget(section2Link); } node.Section2Items = SetSectionItems(siteName, cultureCode, item, relationshipRow2); node.Section3Title = ValidationHelper.GetString(item["Title3"], string.Empty); TreeNode section3Link = tree.SelectSingleNode(ValidationHelper.GetGuid(item["TitleLink3"], new Guid()), cultureCode, siteName); if (section3Link != null) { node.Section3Link = ResolveLinkSrc(section3Link); node.Section3Target = ResolveLinkTarget(section3Link); } node.Section3Items = SetSectionItems(siteName, cultureCode, item, relationshipRow3); items.Add(node); } } return(items); }
/// <summary> /// Returns the text of the specified region. /// </summary> /// <param name="aliasPath">Alias path of the region MenuItem</param> /// <param name="regionID">Region ID to get the text from</param> public static string GetEditableRegionText(string aliasPath, string regionID) { try { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode node = tree.SelectSingleNode(SiteContext.CurrentSiteName, aliasPath, LocalizationContext.PreferredCultureCode); if (node != null) { PageInfo pi = new PageInfo(); pi.LoadContentXml(Convert.ToString(node.GetValue("DocumentContent"))); return(Convert.ToString(pi.EditableRegions[regionID.ToLowerCSafe()])); } } catch { } return(null); }
/// <summary> /// Reloads comment list. /// </summary> public void ReloadComments() { SetContext(); pnlComment.Visible = AreCommentsOpened; if (PostNode != null) { var currentUser = MembershipContext.AuthenticatedUser; // Check permissions for blog if (BlogProperties.CheckPermissions) { if (currentUser.IsAuthorizedPerDocument(PostNode, NodePermissionsEnum.Read) != AuthorizationResultEnum.Allowed) { Visible = false; return; } } ctrlCommentEdit.PostDocumentId = PostNode.DocumentID; ctrlCommentEdit.PostNodeId = PostNode.NodeID; ctrlCommentEdit.PostCulture = PostNode.DocumentCulture; if (!BlogProperties.StopProcessing) { // Get parent blog bool selectOnlyPublished = PortalContext.ViewMode.IsLiveSite(); TreeNode blogNode = BlogHelper.GetParentBlog(AliasPath, SiteName, selectOnlyPublished); // Determine whether user is authorized to manage comments isUserAuthorized = BlogHelper.IsUserAuthorizedToManageComments(blogNode); // Get all post comments rptComments.DataSource = BlogCommentInfoProvider.GetPostComments(PostNode.DocumentID, !isUserAuthorized, isUserAuthorized); rptComments.DataBind(); } } ReleaseContext(); }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void ugRecycleBin_OnAction(string actionName, object actionArgument) { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); VersionManager verMan = VersionManager.GetInstance(tree); int versionHistoryId = ValidationHelper.GetInteger(actionArgument, 0); TreeNode doc = null; if (actionName == "restore") { try { if (IsAuthorizedPerDocument(versionHistoryId, "Create", currentUser, out doc, verMan)) { verMan.RestoreDocument(versionHistoryId, doc); ShowConfirmation(GetString("Recyclebin.RestorationOK")); } else { ShowError(String.Format(ResHelper.GetString("Recyclebin.RestorationFailedPermissions", currentCulture), doc.DocumentNamePath)); } } catch (Exception ex) { ShowError(GetString("recyclebin.errorrestoringdocument"), ex.Message, null); } } else if (actionName == "destroy") { if (IsAuthorizedPerDocument(versionHistoryId, "Destroy", currentUser, out doc, verMan)) { verMan.DestroyDocumentHistory(doc.DocumentID); ShowConfirmation(GetString("recyclebin.destroyok")); } else { ShowError(String.Format(ResHelper.GetString("recyclebin.destructionfailedpermissions", currentCulture), doc.DocumentNamePath)); } } ugRecycleBin.ResetSelection(false); }
/// <summary> /// Loads the URL path to the UI /// </summary> private void LoadURLPath(TreeNode treeNode) { ctrlURL.URLPath = treeNode.DocumentUrlPath; txtExtensions.Enabled = chkCustomExtensions.Checked; if (mIsRoot) { txtAlias.Enabled = false; valAlias.Enabled = false; ctrlURL.Enabled = false; chkCustomExtensions.Enabled = false; } if (treeNode.IsLink) { ctrlURL.Enabled = false; } }
private void txtGuid_TextChanged(object sender, EventArgs e) { int nodeId = ValidationHelper.GetInteger(txtGuid.Text, 0); if (FieldIsInteger()) { txtName.Text = GetNodeName(nodeId); return; } if (nodeId > 0) { TreeNode node = TreeProvider.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES, true); if (node != null) { string site = (node.NodeSiteID != SiteContext.CurrentSiteID ? ";" + node.NodeSiteName : ""); txtName.Text = node.NodeAliasPath; txtGuid.Text = node.NodeGUID + site; } } }
private void SetAliasPath(object valueObj, bool isNodeId) { if (valueObj != null) { if (!isNodeId) { string[] split = valueObj.ToString().Split(';'); string siteName = null; // Check if site name is presented in value if (split.Length > 1) { siteName = split[1]; } else { if ((Form != null) && (Form.EditedObject != null)) { TreeNode editedNode = Form.EditedObject as TreeNode; if (editedNode != null) { int linkedSiteId = editedNode.OriginalNodeSiteID; if ((linkedSiteId > 0) && (linkedSiteId != SiteContext.CurrentSiteID)) { siteName = SiteInfoProvider.GetSiteName(linkedSiteId); } } } } if (ValidationHelper.GetGuid(split[0], Guid.Empty) != Guid.Empty) { txtName.Text = GetNodeName(split[0], siteName); } } else { txtName.Text = GetNodeName(ValidationHelper.GetInteger(valueObj, 0)); } } }
protected CMS.DocumentEngine.TreeNode FindProductCategory(string nodeAliasPath) { string path = TreePathUtils.GetSafeNodeAliasPath(nodeAliasPath, CurrentSiteName); var subCategory = TreeHelper.GetDocument(CurrentSiteName, path, Culture, true, "PbcLinear.ProductSubCategory", true, true, CurrentUser); var category = TreeHelper.GetDocument(CurrentSiteName, path, Culture, true, "PbcLinear.ProductCategory", true, true, CurrentUser); var returnedCategory = new CMS.DocumentEngine.TreeNode(); if (subCategory != null) { returnedCategory = subCategory; } if (category != null) { returnedCategory = category; } return(returnedCategory); }
/// <summary> /// Performs necessary checks and archives document. /// </summary> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PerformArchive(WorkflowManager wm, TreeProvider tree, TreeNode node, string aliasPath) { if (node != null) { if (!UndoPossibleCheckOut(tree, node)) { return(true); } try { if (currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(node.DocumentCulture, node.NodeSiteName)) { AddLog(string.Format(GetString("content.notallowedtomodifycultureversion"), node.DocumentCulture, node.NodeAliasPath)); } else { // Add log record AddLog(HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")")); // Archive document wm.ArchiveDocument(node, string.Empty); } } catch (ThreadAbortException te) { AddLog(te.Message); } catch { AddLog(string.Format(ResHelper.GetString("content.archivenowf"), HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"))); } return(false); } else { AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath))); return(false); } }
/// <summary> /// Initializes filter form. /// </summary> private void InitializeFilterForm() { // If ClassID is not used don't initialize if (ClassID != UniSelector.US_NONE_RECORD) { if (ClassID > 0) { var className = DataClassInfoProvider.GetClassName(ClassID); var formName = className + ".filter"; var form = AlternativeFormInfoProvider.GetAlternativeFormInfo(formName); formName += (form != null) ? "+cms.document.simplefilter" : "+cms.document.filter"; gridDocuments.FilterFormName = formName; gridDocuments.FilterFormData = TreeNode.New(className); } else { gridDocuments.FilterFormName = "cms.document.filter"; gridDocuments.FilterFormData = TreeNode.New(); } } }
/// <summary> /// Check user permissions for document. /// </summary> /// <param name="document">Document</param> /// <param name="permission">Permissions</param> /// <param name="user">User</param> /// <returns>TreeNode if authorized, null otherwise</returns> public bool IsAuthorizedPerDocument(TreeNode document, string permission, CurrentUserInfo user) { // Initialize variables string className = null; // Check global permission bool userHasGlobalPerm = user.IsAuthorizedPerResource("CMS.Content", permission); // Get node properties try { // Get the values form deleted node className = document.NodeClassName; } catch (ThreadAbortException) { throw; } catch (Exception ex) { CurrentError = "Error occurred: " + ex.Message; AddLog(CurrentError); } bool additionalPermission = false; if (permission.ToLowerCSafe() == "create") { additionalPermission = user.IsAuthorizedPerClassName(className, "CreateSpecific"); } // Check permissions if (userHasGlobalPerm || user.IsAuthorizedPerClassName(className, permission) || additionalPermission) { return(true); } return(false); }
protected void Page_Load(object sender, EventArgs e) { UIContext.PropertyTab = PropertyTabEnum.Wireframe; // Register the scripts ScriptHelper.RegisterProgress(Page); // Init node EditMenu.HandleWorkflow = false; DocumentManager.HandleWorkflow = false; node = DocumentManager.Node; if (node != null) { if (node.NodeWireframeTemplateID > 0) { EditMenu.ShowRemoveWireframe = true; } else { // Document does not have the wireframe ShowInformation(GetString("Wireframe.NotSet")); EditMenu.ShowSave = false; EditMenu.ShowCreateWireframe = true; pnlForm.Visible = false; } } pnlInherits.GroupingText = GetString("PageProperties.InheritLevels"); if (!RequestHelper.IsPostBack()) { ReloadData(); } }
/// <summary> /// Ensures dialog breadcrumbs /// </summary> /// <param name="node">Current node</param> private void EnsureBreadcrumbs(TreeNode node) { if (node != null) { // Loop thru all levels and generate breadcrumbs int parentNodeId = 0; PageTitle.HideBreadcrumbs = false; for (int i = node.NodeLevel; i >= 0; i--) { if (node == null) { // Document is not translated in the current culture -> get parent node from the default culture TreeProvider treeProvider = new TreeProvider(); TreeNode parentNode = DocumentHelper.GetDocument(parentNodeId, CultureCode, true, treeProvider); node = parentNode; } if (node != null) { PageBreadcrumbs.Items.Add(new BreadcrumbItem { Text = node.GetDocumentName(), Index = i, RedirectUrl = "#", OnClientClick = "SelectItem(" + node.NodeID + "); return false;" }); parentNodeId = node.NodeParentID; node = node.Parent; } } // Add additional css class for correct design CurrentMaster.PanelHeader.CssClass += " SimpleHeader"; } }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void UniGrid_OnAction(string actionName, object actionArgument) { // Check 'Modify' permission (because of delete action in unigrid) if (!CheckPermissions("cms.eventmanager", "Modify")) { return; } switch (actionName) { case "delete": EventAttendeeInfoProvider.DeleteEventAttendeeInfo(ValidationHelper.GetInteger(actionArgument, 0)); // Refresh parent frame header ltlScript.Text = ScriptHelper.GetScript("RefreshHeader();"); UniGrid.ReloadData(); ShowEventInfo(); break; case "sendemail": // Resend invitation email TreeProvider mTree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode node = mTree.SelectSingleNode(EventID); EventAttendeeInfo eai = EventAttendeeInfoProvider.GetEventAttendeeInfo(ValidationHelper.GetInteger(actionArgument, 0)); if ((node != null) && (node.NodeClassName.EqualsCSafe("cms.bookingevent", true)) && (eai != null)) { EventProvider.SendInvitation(SiteContext.CurrentSiteName, node, eai, TimeZoneHelper.ServerTimeZone); ShowConfirmation(GetString("eventmanager.invitationresend")); } break; case "edit": SelectedAttendeeID = ValidationHelper.GetInteger(actionArgument, 0); break; } }
/// <summary> /// Check user permissions for document. /// </summary> /// <param name="document">Document</param> /// <param name="permission">Permissions</param> /// <param name="user">User</param> /// <returns>TreeNode if authorized, null otherwise</returns> public bool IsAuthorizedPerDocument(TreeNode document, string permission, CurrentUserInfo user) { // Check global permission bool userHasGlobalPerm = user.IsAuthorizedPerResource("CMS.Content", permission); // Get the values form deleted node string className = document.NodeClassName; bool additionalPermission = false; if (permission.ToLowerCSafe() == "create") { additionalPermission = user.IsAuthorizedPerClassName(className, "CreateSpecific"); } // Check permissions if (userHasGlobalPerm || user.IsAuthorizedPerClassName(className, permission) || additionalPermission) { return(true); } return(false); }
/// <summary> /// Submits the node for translation. Does not check the permissions, you need to chek it before calling this method. /// </summary> public string SubmitToTranslation() { string err = ValidateData(); if (!string.IsNullOrEmpty(err)) { return(err); } TranslationSettings settings = TranslationSettings ?? new TranslationSettings(); if (string.IsNullOrEmpty(settings.TargetLanguage)) { settings.TargetLanguage = CMSContext.PreferredCultureCode; } settings.TranslateWebpartProperties = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSTranslateWebpartProperties"); settings.SourceLanguage = FromLanguage; settings.Instructions = Instructions; settings.Priority = Priority; settings.ProcessBinary = ProcessBinary; settings.TranslateAttachments = ProcessBinary; settings.TranslationDeadline = Deadline; settings.TranslationServiceName = hdnSelectedName.Value; settings.GenerateTargetTag = ValidationHelper.GetBoolean(hdnGenerateTarget.Value, false); TreeProvider tree = TreeProvider; if (tree == null) { tree = new TreeProvider(); } TreeNode node = DocumentHelper.GetDocument(NodeID, settings.SourceLanguage, true, tree); //tree.SelectSingleNode(NodeID, settings.SourceLanguage, true, settings.TranslateDocCoupledData); TranslationSubmissionInfo submissionInfo = null; return(TranslationServiceHelper.SubmitToTranslation(settings, node, out submissionInfo)); }
protected void Page_Load(object sender, EventArgs e) { if (DocumentManager != null) { CMS.DocumentEngine.TreeNode node = DocumentManager.Node; if (node != null) { DocumentSettings = true; // Try get info whether exist linked document in path DataSet ds = DocumentManager.Tree.SelectNodes(CMSContext.CurrentSiteName, "/%", node.DocumentCulture, false, null, "NodeLinkedNodeID IS NOT NULL AND (N'" + SqlHelperClass.GetSafeQueryString(node.NodeAliasPath) + "' LIKE NodeAliasPath + '%')", null, -1, false, 1, "Count(*) AS NumOfDocs"); // If node is not link or none of parent documents is not linked document use document name path if (!node.IsLink && ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NumOfDocs"), 0) == 0) { TreePath = TreePathUtils.GetParentPath("/" + node.DocumentNamePath); } else { // Otherwise use alias path TreePath = TreePathUtils.GetParentPath("/" + node.NodeAliasPath); } } } if (DocumentSettings) { radInheritAll.Text = GetString("InheritLevels.UseTemplateSettigns"); } else { radInheritAll.Text = GetString("InheritLevels.InheritAll"); } radNonInherit.Text = GetString("InheritLevels.NonInherit"); radSelect.Text = GetString("InheritLevels.Select"); radInheritMaster.Text = GetString("InheritLevels.InheritMaster"); }
/// <summary> /// Click Event which will save a category /// // Creates a new page of the "CMS.MenuItem" page type /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Save(object sender, EventArgs e) { string categoryName = txtName.Text; string categroyDes = txtDescription.Text; try { if (!string.IsNullOrEmpty(categoryName)) { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); CMS.DocumentEngine.TreeNode parentPage = tree.SelectNodes().Path(folderpath).OnCurrentSite().Culture(DocumentContext.CurrentDocument.DocumentCulture).FirstObject; if (parentPage != null) { CMS.DocumentEngine.TreeNode newPage = CMS.DocumentEngine.TreeNode.New("KDA.ProductCategory", tree); newPage.DocumentName = categoryName; newPage.DocumentCulture = DocumentContext.CurrentDocument.DocumentCulture; newPage.SetValue("ProductCategoryTitle", categoryName); newPage.SetValue("ProductCategoryDescription", categroyDes); newPage.SetValue("Status", ValidationHelper.GetBoolean(ddlStatus.SelectedValue, false)); newPage.Insert(parentPage); lblSuccessMsg.Visible = true; lblFailureText.Visible = false; Response.Cookies["status"].Value = QueryStringStatus.Added; Response.Cookies["status"].HttpOnly = false; URLHelper.Redirect($"{CurrentDocument.Parent.DocumentUrlPath}?status={QueryStringStatus.Added}"); } else { lblFailureText.Visible = true; } } } catch (Exception ex) { EventLogProvider.LogException("CategroyCreateForm", "EXCEPTION", ex); } }
/// <summary> /// Ensures dialog breadcrumbs /// </summary> /// <param name="node">Current node</param> private void EnsureBreadcrumbs(TreeNode node) { if (node != null) { // Loop thru all levels and generate breadcrumbs string[,] breadcrumbs = new String[node.NodeLevel + 1, 4]; int parentNodeId = 0; for (int i = node.NodeLevel; i >= 0; i--) { if (node == null) { // Document is not translated in the current culture -> get parent node from the default culture TreeProvider treeProvider = new TreeProvider(); TreeNode parentNode = treeProvider.SelectSingleNode(parentNodeId, CultureCode, true); node = parentNode; } if (node != null) { breadcrumbs[i, 0] = DataHelper.GetNotEmpty(node.NodeName, CurrentSiteName); breadcrumbs[i, 1] = "#"; breadcrumbs[i, 3] = "SelectItem(" + node.NodeID + "); return false;"; parentNodeId = node.NodeParentID; node = node.Parent; } } // Set breadcrumb CurrentMaster.Title.Breadcrumbs = breadcrumbs; // Add additional css class for correct design CurrentMaster.PanelHeader.CssClass += " SimpleHeader"; } }
protected object gridBlogs_OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName.ToLowerCSafe()) { case "edit": case "newpost": GridViewRow gvr = (parameter as GridViewRow); if (gvr != null) { DataRowView dr = (gvr.DataItem as DataRowView); if (dr != null) { TreeNode blogNode = TreeNode.New(dr.Row, ValidationHelper.GetString(dr.Row["ClassName"], "")); if (blogNode != null) { isAuthorized = isAuthorized || BlogHelper.IsUserBlogOwner(currentUser.UserID, blogNode); if (!isAuthorized) { ImageButton button = ((ImageButton)sender); if (sourceName.ToLowerCSafe() == "edit") { button.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/editdisabled.png"); } else { button.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/addpostdisabled.png"); } button.Enabled = false; } } } } break; } return(parameter); }
protected void ProcessDirectUploader() { TreeNode node = DocumentManager.Node; // Create new document string fileName = Path.GetFileNameWithoutExtension(ucDirectUploader.AttachmentName); int maxFileNameLength = FileNameFieldInfo.Size; if (fileName.Length > maxFileNameLength) { fileName = fileName.Substring(0, maxFileNameLength); } node.DocumentName = fileName; if (node.ContainsColumn("FileDescription")) { string fileDescription = txtFileDescription.Text.Trim(); fileDescription = TextHelper.LimitLength(fileDescription, txtFileDescription.MaxLength); node.SetValue("FileDescription", fileDescription); } node.SetValue("FileAttachment", Guid.Empty); // Set default template ID node.SetDefaultPageTemplateID(DataClass.ClassDefaultPageTemplateID); // Ensures documents consistency (blog post hierarchy etc.) DocumentManager.EnsureDocumentsConsistency(); // Insert the document DocumentHelper.InsertDocument(node, DocumentManager.ParentNode, DocumentManager.Tree); // Set the attachment GUID later - important when document is under workflow and using check-in/check-out node.SetValue("FileAttachment", ucDirectUploader.Value); }
protected void Page_Load(object sender, EventArgs e) { // Register the scripts ScriptHelper.RegisterLoader(Page); // Init node EditMenu.HandleWorkflow = false; DocumentManager.HandleWorkflow = false; node = DocumentManager.Node; // Setup child controls inheritElem.Node = node; if (node != null) { if (node.NodeWireframeTemplateID > 0) { EditMenu.ShowRemoveWireframe = true; } else { // Document does not have the wireframe ShowInformation(GetString("Wireframe.NotSet")); EditMenu.ShowSave = false; EditMenu.ShowCreateWireframe = true; pnlForm.Visible = false; } } if (!RequestHelper.IsPostBack()) { ReloadData(); } }
private void SaveDocumentStylesheet(TreeNode node) { if (pnlUIDesign.IsHidden) { return; } if (!chkCssStyle.Checked) { // Set style sheet int selectedCssId = ValidationHelper.GetInteger(ctrlSiteSelectStyleSheet.Value, 0); node.DocumentStylesheetID = (selectedCssId > 0) ? selectedCssId : 0; node.DocumentInheritsStylesheet = false; ctrlSiteSelectStyleSheet.Enabled = true; } else { ctrlSiteSelectStyleSheet.Enabled = false; node.DocumentInheritsStylesheet = true; node.DocumentStylesheetID = 0; } }
protected void ProcessFileUploader() { TreeNode node = DocumentManager.Node; // Create new document string fileName = Path.GetFileNameWithoutExtension(FileUpload.FileName); int maxFileNameLength = FileNameFieldInfo.Size; if (fileName.Length > maxFileNameLength) { fileName = fileName.Substring(0, maxFileNameLength); } node.DocumentName = fileName; if (node.ContainsColumn("FileDescription")) { string fileDescription = txtFileDescription.Text.Trim(); fileDescription = TextHelper.LimitLength(fileDescription, txtFileDescription.MaxLength); node.SetValue("FileDescription", fileDescription); } node.SetValue("FileAttachment", Guid.Empty); // Set default template ID node.SetDefaultPageTemplateID(DataClass.ClassDefaultPageTemplateID); // Ensures documents consistency (blog post hierarchy etc.) DocumentManager.EnsureDocumentsConsistency(); // Insert the document DocumentHelper.InsertDocument(node, DocumentManager.ParentNode, DocumentManager.Tree); // Add the file DocumentHelper.AddAttachment(node, "FileAttachment", FileUpload.PostedFile, DocumentManager.Tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); }
private static DataSet GetSubDocuments(TreeNode parentNode, TreeProvider tree, string cultureCode, string siteName) { string columns = SqlHelperClass.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture"); // Get subdocuments return tree.SelectNodes(siteName, parentNode.NodeAliasPath + "/%", cultureCode, false, null, null, null, TreeProvider.ALL_LEVELS, false, 0, columns); }
/// <summary> /// Ensures dialog breadcrumbs /// </summary> /// <param name="node">Current node</param> private void EnsureBreadcrumbs(TreeNode node) { if (node == null) { return; } PageTitle.HideBreadcrumbs = false; // Loop thru all levels and generate breadcrumbs for (int i = node.NodeLevel; i >= 0; i--) { if (node == null) { continue; } PageBreadcrumbs.Items.Add(new BreadcrumbItem { Text = node.GetDocumentName(), Index = i, RedirectUrl = "#", OnClientClick = "SelectItem(" + node.NodeID + "); return false;" }); node = node.Parent; } // Add additional css class for correct design CurrentMaster.PanelHeader.CssClass += " SimpleHeader"; }
/// <summary> /// Check user permissions for document. /// </summary> /// <param name="document">Document</param> /// <param name="permission">Permissions</param> /// <param name="user">User</param> /// <returns>TreeNode if authorized, null otherwise</returns> public bool IsAuthorizedPerDocument(TreeNode document, string permission, CurrentUserInfo user) { // Initialize variables string className = null; // Check global permission bool userHasGlobalPerm = user.IsAuthorizedPerResource("CMS.Content", permission); // Get node properties try { // Get the values form deleted node className = document.NodeClassName; } catch (ThreadAbortException) { throw; } catch (Exception ex) { CurrentError = "Error occurred: " + ex.Message; AddLog(CurrentError); } bool additionalPermission = false; if (permission.ToLowerCSafe() == "create") { additionalPermission = user.IsAuthorizedPerClassName(className, "CreateSpecific"); } // Check permissions if (userHasGlobalPerm || user.IsAuthorizedPerClassName(className, permission) || additionalPermission) { return true; } return false; }
private string GetWhereConditionUrlField(bool generateConditionForActivityURL, TreeNode document) { if (generateConditionForActivityURL) { return " AND (ISNULL([ActivityURL], '') LIKE N'%" + document.RelativeURL.Substring(2) + "%')"; } return String.Empty; }
/// <summary> /// Returns true when given node has product related child. /// </summary> /// <param name="tree">Tree provider to use</param> /// <param name="node">Node to check</param> protected bool NodeHasChildWithProduct(TreeProvider tree, TreeNode node) { string aliasPath = node.NodeAliasPath.TrimEnd('/') + "/%"; return 0 < tree.SelectNodesCount(node.NodeSiteName, aliasPath, TreeProvider.ALL_CULTURES, true, null, "NodeLinkedNodeID IS NULL AND NodeSKUID IS NOT NULL", null, TreeProvider.ALL_LEVELS, false); }
/// <summary> /// Adds the field to the form. /// </summary> /// <param name="node">Document node</param> /// <param name="compareNode">Document compare node</param> /// <param name="columnName">Column name</param> private void AddField(TreeNode node, TreeNode compareNode, string columnName) { FormFieldInfo ffi = null; if (fi != null) { ffi = fi.GetFormField(columnName); } TableCell valueCell = new TableCell(); valueCell.EnableViewState = false; TableCell valueCompare = new TableCell(); valueCompare.EnableViewState = false; TableCell labelCell = new TableCell(); labelCell.EnableViewState = false; TextComparison comparefirst; TextComparison comparesecond; bool loadValue = true; bool empty = true; bool allowLabel = true; // Get the caption if ((columnName == UNSORTED) || (ffi != null)) { AttachmentInfo aiCompare = null; // Compare attachments if ((columnName == UNSORTED) || ((ffi != null) && (ffi.DataType == FieldDataType.DocAttachments))) { allowLabel = false; string title = String.Empty; if (columnName == UNSORTED) { title = GetString("attach.unsorted") + ":"; } else if (ffi != null) { string caption = ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver); title = (String.IsNullOrEmpty(caption) ? ffi.Name : caption) + ":"; } // Prepare DataSource for original node loadValue = false; dsAttachments = new AttachmentsDataSource(); dsAttachments.DocumentVersionHistoryID = versionHistoryId; if ((ffi != null) && (columnName != UNSORTED)) { dsAttachments.AttachmentGroupGUID = ffi.Guid; } dsAttachments.Path = node.NodeAliasPath; dsAttachments.CultureCode = LocalizationContext.PreferredCultureCode; SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); dsAttachments.SiteName = si.SiteName; dsAttachments.OrderBy = "AttachmentOrder, AttachmentName, AttachmentHistoryID"; dsAttachments.SelectedColumns = "AttachmentHistoryID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription"; dsAttachments.IsLiveSite = false; dsAttachments.DataSource = null; dsAttachments.DataBind(); // Get the attachments table attachments = GetAttachmentsTable((DataSet)dsAttachments.DataSource, versionHistoryId, node.DocumentID); // Prepare data source for compared node if (compareNode != null) { dsAttachmentsCompare = new AttachmentsDataSource(); dsAttachmentsCompare.DocumentVersionHistoryID = versionCompare; if ((ffi != null) && (columnName != UNSORTED)) { dsAttachmentsCompare.AttachmentGroupGUID = ffi.Guid; } dsAttachmentsCompare.Path = compareNode.NodeAliasPath; dsAttachmentsCompare.CultureCode = LocalizationContext.PreferredCultureCode; dsAttachmentsCompare.SiteName = si.SiteName; dsAttachmentsCompare.OrderBy = "AttachmentOrder, AttachmentName, AttachmentHistoryID"; dsAttachmentsCompare.SelectedColumns = "AttachmentHistoryID, AttachmentGUID, AttachmentImageWidth, AttachmentImageHeight, AttachmentExtension, AttachmentName, AttachmentSize, AttachmentOrder, AttachmentTitle, AttachmentDescription"; dsAttachmentsCompare.IsLiveSite = false; dsAttachmentsCompare.DataSource = null; dsAttachmentsCompare.DataBind(); // Get the table to compare attachmentsCompare = GetAttachmentsTable((DataSet)dsAttachmentsCompare.DataSource, versionCompare, node.DocumentID); // Switch the sides if older version is on the right if (versionHistoryId > versionCompare) { Hashtable dummy = attachmentsCompare; attachmentsCompare = attachments; attachments = dummy; } // Add comparison AddTableComparison(attachments, attachmentsCompare, "<strong>" + title + "</strong>", true, true); } else { // Normal display if (attachments.Count != 0) { bool first = true; foreach (DictionaryEntry item in attachments) { string itemValue = ValidationHelper.GetString(item.Value, null); if (!String.IsNullOrEmpty(itemValue)) { valueCell = new TableCell(); labelCell = new TableCell(); if (first) { labelCell.Text = "<strong>" + String.Format(title, item.Key) + "</strong>"; first = false; } valueCell.Text = itemValue; AddRow(labelCell, valueCell); } } } } } // Compare single file attachment else if ((ffi != null) && (ffi.DataType == FieldDataType.File)) { // Get the attachment AttachmentInfo ai = DocumentHelper.GetAttachment(ValidationHelper.GetGuid(node.GetValue(columnName), Guid.Empty), versionHistoryId, TreeProvider, false); if (compareNode != null) { aiCompare = DocumentHelper.GetAttachment(ValidationHelper.GetGuid(compareNode.GetValue(columnName), Guid.Empty), versionCompare, TreeProvider, false); } loadValue = false; // Prepare text comparison controls if ((ai != null) || (aiCompare != null)) { string textorig = null; if (ai != null) { textorig = CreateAttachment(ai.Generalized.DataClass, versionHistoryId); } string textcompare = null; if (aiCompare != null) { textcompare = CreateAttachment(aiCompare.Generalized.DataClass, versionCompare); } comparefirst = new TextComparison(); comparefirst.SynchronizedScrolling = false; comparefirst.IgnoreHTMLTags = true; comparefirst.ConsiderHTMLTagsEqual = true; comparefirst.BalanceContent = false; comparesecond = new TextComparison(); comparesecond.SynchronizedScrolling = false; comparesecond.IgnoreHTMLTags = true; // Source text must be older version if (versionHistoryId < versionCompare) { comparefirst.SourceText = textorig; comparefirst.DestinationText = textcompare; } else { comparefirst.SourceText = textcompare; comparefirst.DestinationText = textorig; } comparefirst.PairedControl = comparesecond; comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText; valueCell.Controls.Add(comparefirst); valueCompare.Controls.Add(comparesecond); // Add both cells if (compareNode != null) { AddRow(labelCell, valueCell, valueCompare); } // Add one cell only else { valueCell.Controls.Clear(); Literal ltl = new Literal(); ltl.Text = textorig; valueCell.Controls.Add(ltl); AddRow(labelCell, valueCell); } } } } if (allowLabel && String.IsNullOrEmpty(labelCell.Text)) { labelCell.Text = "<strong>" + columnName + ":</strong>"; } if (loadValue) { string textcompare = null; switch (columnName.ToLowerCSafe()) { // Document content - display content of editable regions and editable web parts case "documentcontent": EditableItems ei = new EditableItems(); ei.LoadContentXml(ValidationHelper.GetString(node.GetValue(columnName), String.Empty)); // Add text comparison control if (compareNode != null) { EditableItems eiCompare = new EditableItems(); eiCompare.LoadContentXml(ValidationHelper.GetString(compareNode.GetValue(columnName), String.Empty)); // Create editable regions comparison Hashtable hashtable; Hashtable hashtableCompare; // Source text must be older version if (versionHistoryId < versionCompare) { hashtable = ei.EditableRegions; hashtableCompare = eiCompare.EditableRegions; } else { hashtable = eiCompare.EditableRegions; hashtableCompare = ei.EditableRegions; } // Add comparison AddTableComparison(hashtable, hashtableCompare, "<strong>" + columnName + " ({0}):</strong>", false, false); // Create editable webparts comparison // Source text must be older version if (versionHistoryId < versionCompare) { hashtable = ei.EditableWebParts; hashtableCompare = eiCompare.EditableWebParts; } else { hashtable = eiCompare.EditableWebParts; hashtableCompare = ei.EditableWebParts; } // Add comparison AddTableComparison(hashtable, hashtableCompare, "<strong>" + columnName + " ({0}):</strong>", false, false); } // No compare node else { // Editable regions Hashtable hashtable = ei.EditableRegions; if (hashtable.Count != 0) { foreach (DictionaryEntry region in hashtable) { string regionValue = ValidationHelper.GetString(region.Value, null); if (!String.IsNullOrEmpty(regionValue)) { string regionKey = ValidationHelper.GetString(region.Key, null); valueCell = new TableCell(); labelCell = new TableCell(); labelCell.Text = "<strong>" + columnName + " (" + DictionaryHelper.GetFirstKey(regionKey) + "):</strong>"; valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(regionValue, false)); AddRow(labelCell, valueCell); } } } // Editable web parts hashtable = ei.EditableWebParts; if (hashtable.Count != 0) { foreach (DictionaryEntry part in hashtable) { string partValue = ValidationHelper.GetString(part.Value, null); if (!String.IsNullOrEmpty(partValue)) { string partKey = ValidationHelper.GetString(part.Key, null); valueCell = new TableCell(); labelCell = new TableCell(); labelCell.Text = "<strong>" + columnName + " (" + DictionaryHelper.GetFirstKey(partKey) + "):</strong>"; valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(partValue, false)); AddRow(labelCell, valueCell); } } } } break; case "documentwebparts": StringBuilder sbOriginal = new StringBuilder(); StringBuilder sbCompared = new StringBuilder(); // Set original web parts string originalWebParts = Convert.ToString(node.GetValue(columnName)); GenerateWebPartsMarkup(ref sbOriginal, originalWebParts, true); // Add text comparison control if (compareNode != null) { string compareWebParts = Convert.ToString(compareNode.GetValue(columnName)); GenerateWebPartsMarkup(ref sbCompared, compareWebParts, false); } // Set empty flag empty = ((sbOriginal.Length == 0) && (sbCompared.Length == 0)); if (!empty) { valueCell.Text += sbOriginal.ToString(); valueCompare.Text = sbCompared.ToString(); } break; // Others, display the string value default: // Shift date time values to user time zone object origobject = node.GetValue(columnName); string textorig; if (origobject is DateTime) { textorig = TimeZoneHelper.ConvertToUserTimeZone(ValidationHelper.GetDateTime(origobject, DateTimeHelper.ZERO_TIME), true, CurrentUser, SiteContext.CurrentSite); } else { textorig = ValidationHelper.GetString(origobject, String.Empty); } // Add text comparison control if (compareNode != null) { // Shift date time values to user time zone object compareobject = compareNode.GetValue(columnName); if (compareobject is DateTime) { textcompare = TimeZoneHelper.ConvertToUserTimeZone(ValidationHelper.GetDateTime(compareobject, DateTimeHelper.ZERO_TIME), true, CurrentUser, SiteContext.CurrentSite); } else { textcompare = ValidationHelper.GetString(compareobject, String.Empty); } comparefirst = new TextComparison(); comparefirst.SynchronizedScrolling = false; comparesecond = new TextComparison(); comparesecond.SynchronizedScrolling = false; comparesecond.RenderingMode = TextComparisonTypeEnum.DestinationText; // Source text must be older version if (versionHistoryId < versionCompare) { comparefirst.SourceText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false)); comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textcompare, false)); } else { comparefirst.SourceText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textcompare, false)); comparefirst.DestinationText = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false)); } comparefirst.PairedControl = comparesecond; if (Math.Max(comparefirst.SourceText.Length, comparefirst.DestinationText.Length) < 100) { comparefirst.BalanceContent = false; } valueCell.Controls.Add(comparefirst); valueCompare.Controls.Add(comparesecond); } else { valueCell.Text = HttpUtility.HtmlDecode(HTMLHelper.StripTags(textorig, false)); } empty = (String.IsNullOrEmpty(textorig)) && (String.IsNullOrEmpty(textcompare)); break; } } if (!empty) { if (compareNode != null) { AddRow(labelCell, valueCell, valueCompare); } else { AddRow(labelCell, valueCell); } } }
/// <summary> /// Check user permissions for document version. /// </summary> /// <param name="versionId">Document version</param> /// <param name="permission">Permission</param> /// <param name="user">User</param> /// <param name="checkedNode">Checked node</param> /// <param name="versionManager">Version manager</param> /// <returns>True if authorized, false otherwise</returns> public bool IsAuthorizedPerDocument(int versionId, string permission, CurrentUserInfo user, out TreeNode checkedNode, VersionManager versionManager) { if (versionManager == null) { TreeProvider tree = new TreeProvider(user); tree.AllowAsyncActions = false; versionManager = VersionManager.GetInstance(tree); } // Get the values form deleted node checkedNode = versionManager.GetVersion(versionId); return IsAuthorizedPerDocument(checkedNode, permission, user); }
protected void Page_Load(object sender, EventArgs e) { RegisterResizeHeaders(); CMSContext.ViewMode = ViewModeEnum.MasterPage; previewState = GetPreviewStateFromCookies(MASTERPAGE); // Keep current user user = CMSContext.CurrentUser; // Get document node tree = new TreeProvider(user); node = CMSContext.EditedObject as TreeNode; // Register the dialog script ScriptHelper.RegisterDialogScript(Page); // Register save changes ScriptHelper.RegisterSaveChanges(Page); // Save changes support bool confirmChanges = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSConfirmChanges"); string script = string.Empty; if (confirmChanges) { script = "var confirmLeave='" + ResHelper.GetString("Content.ConfirmLeave", user.PreferredUICultureCode) + "'; \n"; } else { script += "confirmChanges = false;"; } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "saveChangesScript", ScriptHelper.GetScript(script)); try { if (node != null) { CMSContext.CurrentPageInfo = PageInfoProvider.GetPageInfo(CMSContext.CurrentSiteName, node.NodeAliasPath, node.DocumentCulture, null, false); // Title string title = CMSContext.CurrentTitle; if (!string.IsNullOrEmpty(title)) { title = "<title>" + title + "</title>"; } // Body class string bodyCss = CMSContext.CurrentBodyClass; if (bodyCss != null && bodyCss.Trim() != "") { bodyCss = "class=\"" + bodyCss + "\""; } else { bodyCss = ""; } // Metadata string meta = "<meta http-equiv=\"pragma\" content=\"no-cache\" />"; string description = CMSContext.CurrentDescription; if (description != "") { meta += "<meta name=\"description\" content=\"" + description + "\" />"; } string keywords = CMSContext.CurrentKeyWords; if (keywords != "") { meta += "<meta name=\"keywords\" content=\"" + keywords + "\" />"; } // Site style sheet string cssSiteSheet = ""; int stylesheetId = CMSContext.CurrentPageInfo.DocumentStylesheetID; CssStylesheetInfo cssInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo((stylesheetId > 0) ? stylesheetId : CMSContext.CurrentSite.SiteDefaultStylesheetID); if (cssInfo != null) { cssSiteSheet = CSSHelper.GetCSSFileLink(CSSHelper.GetStylesheetUrl(cssInfo.StylesheetName)); } // Theme CSS files string themeCssFiles = ""; if (cssInfo != null) { try { string directory = URLHelper.GetPhysicalPath(string.Format("~/App_Themes/{0}/", cssInfo.StylesheetName)); if (Directory.Exists(directory)) { foreach (string file in Directory.GetFiles(directory, "*.css")) { themeCssFiles += CSSHelper.GetCSSFileLink(CSSHelper.GetPhysicalCSSUrl(cssInfo.StylesheetName, Path.GetFileName(file))); } } } catch { } } // Add values to page mHead = FormatHTML(HighlightHTML(title + meta + cssSiteSheet + themeCssFiles), 2); mBody = bodyCss; } } catch { ShowError(GetString("MasterPage.PageEditErr")); } LoadData(); // Add save action SaveAction save = new SaveAction(Page); save.CommandArgument = ComponentEvents.SAVE_DATA; save.CommandName = ComponentEvents.SAVE_DATA; headerActions.ActionsList.Add(save); if (pti != null) { // Edit layout HeaderAction action = new HeaderAction { Text = GetString("content.ui.pagelayout"), Tooltip = GetString("pageplaceholder.editlayouttooltip"), OnClientClick = "EditLayout();return false;", ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/Edit.png") }; headerActions.ActionsList.Add(action); // Edit page properties action action = new HeaderAction { Text = GetString("PageProperties.EditTemplateProperties"), Tooltip = GetString("PageProperties.EditTemplateProperties"), OnClientClick = "modalDialog('" + ResolveUrl("~/CMSModules/PortalEngine/UI/PageTemplates/PageTemplate_Edit.aspx") + "?templateid=" + pti.PageTemplateId + "&nobreadcrumbs=1&dialog=1', 'TemplateSelection', 850, 680, false);return false;", ImageUrl = GetImageUrl("CMSModules/CMS_Content/Template/edit.png") }; CMSPagePlaceholder.RegisterEditLayoutScript(this, pti.PageTemplateId, node.NodeAliasPath, null); headerActions.ActionsList.Add(action); // Preview HeaderAction preview = new HeaderAction { ControlType = HeaderActionTypeEnum.LinkButton, Text = GetString("general.preview"), OnClientClick = "performToolbarAction('split');return false;", ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/Preview.png"), SmallImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/16/Preview.png"), Visible = ((previewState == 0) && !CMSContext.DisplaySplitMode), Tooltip = GetString("preview.tooltip") }; headerActions.ActionsList.Add(preview); headerActions.ActionPerformed += new CommandEventHandler(headerActions_ActionPerformed); } RegisterInitScripts(pnlBody.ClientID, pnlMenu.ClientID, false); }
/// <summary> /// Gets the refresh node ID. /// This method checks all parent nodes and indicates whether any of them is contained in the selected node ids list. /// If none of the parent nodes is contained in the list, this method returns 0 (it means that the current wopener node can be used for refreshing the dialog). /// If any of the parent nodes is contained in the list, this method returns the parent node id (this node will be used for refreshing the dialog). /// </summary> /// <param name="node">The node</param> /// <param name="selectedNodeIds">The selected node ids</param> private int GetRefreshNodeID(TreeNode node, List<int> selectedNodeIds) { if (selectedNodeIds.Contains(node.NodeID) || (node.NodeParentID == 0)) { return node.NodeParentID; } return GetRefreshNodeID(node.Parent, selectedNodeIds); }
/// <summary> /// Ensures the given node within the tree. /// </summary> /// <param name="node">Node to ensure</param> /// <param name="nodeId">Ensure by NodeID</param> protected void EnsureNode(TreeNode node, int nodeId) { if (node == null) { // If not already exists, do not add if (allNodes[nodeId] != null) { return; } else { // Get the node node = TreeProvider.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES, true); if (!SelectPublishedData) { node = DocumentHelper.GetDocument(node, TreeProvider); } } } else { nodeId = node.NodeID; } if (node != null) { // Get the correct parent node System.Web.UI.WebControls.TreeNode parentNode = (System.Web.UI.WebControls.TreeNode)allNodes[node.NodeParentID]; if (parentNode != null) { // Expand the parent parentNode.Expanded = true; // If still not present, add the node if (allNodes[nodeId] == null) { TreeSiteMapNode sourceNode = new TreeSiteMapNode(MapProvider, nodeId.ToString()); sourceNode.TreeNode = node; System.Web.UI.WebControls.TreeNode newNode = CreateNode(sourceNode, 0, true); parentNode.ChildNodes.Add(newNode); } } else { // Get the correct node and add it to list of processed nodes TreeSiteMapNode targetNode = MapProvider.GetNodeByAliasPath(node.NodeAliasPath); if (targetNode != null) { List<int> procNodes = new List<int>(); procNodes.Add((int)targetNode.NodeData["NodeID"]); if (targetNode.ParentNode != null) { // Repeat until existing parent node in allNodes is found do { int targetParentNodeId = (int)((TreeSiteMapNode)targetNode.ParentNode).NodeData["NodeID"]; procNodes.Add(targetParentNodeId); targetNode = (TreeSiteMapNode)targetNode.ParentNode; } while ((targetNode.ParentNode != null) && (allNodes[(int)(((TreeSiteMapNode)(targetNode.ParentNode)).NodeData["NodeID"])] == null)); } // Process nodes in reverse order procNodes.Reverse(); if (!procNodes.Any(p => (p <= 0))) { foreach (int nodeID in procNodes) { EnsureNode(null, nodeID); } } } } } }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { rfvDocumentName.ErrorMessage = GetString("om.enterdocumentname"); nodeId = QueryHelper.GetInteger("parentnodeid", 0); ucABTestSelector.NodeID = nodeId; // Get alias path tree = new TreeProvider(CMSContext.CurrentUser); node = tree.SelectSingleNode(nodeId); if (!URLHelper.IsPostback()) { if (node != null) { ucPath.Value = node.NodeAliasPath; } } }
/// <summary> /// Archives sub documents of given node. /// </summary> /// <param name="parentNode">Parent node</param> /// <param name="tree">Tree provider</param> /// <param name="wm">Workflow manager</param> /// <param name="cultureCode">Culture code</param> /// <param name="siteName">Site name</param> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool ArchiveSubDocuments(TreeNode parentNode, TreeProvider tree, WorkflowManager wm, string cultureCode, string siteName) { DataSet subDocuments = GetSubDocuments(parentNode, tree, cultureCode, siteName); if (!DataHelper.DataSourceIsEmpty(subDocuments)) { foreach (DataRow nodeRow in subDocuments.Tables[0].Rows) { // Get the current document string aliasPath = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty); if (PerformArchive(wm, tree, GetDocument(tree, siteName, nodeRow), aliasPath)) { return true; } } } return false; }
/// <summary> /// Indicates whether specified node can be destroyed by current user. /// </summary> /// <param name="node">Tree node to check</param> private bool CanDestroy(TreeNode node) { bool canDestroy = currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Destroy) == AuthorizationResultEnum.Allowed; if (node.HasSKU) { canDestroy &= currentUser.IsAuthorizedPerResource("CMS.Ecommerce", "Destroy"); } return (canDestroy); }
protected void Page_Load(object sender, EventArgs e) { previewState = GetPreviewStateFromCookies(MASTERPAGE); // Keep current user user = MembershipContext.AuthenticatedUser; // Get document node tree = new TreeProvider(user); node = UIContext.EditedObject as TreeNode; // Register the dialog script ScriptHelper.RegisterDialogScript(Page); // Register save changes ScriptHelper.RegisterSaveChanges(Page); // Save changes support bool confirmChanges = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSConfirmChanges"); string script = string.Empty; if (confirmChanges) { script = "CMSContentManager.confirmLeave=" + ScriptHelper.GetString(ResHelper.GetString("Content.ConfirmLeave", user.PreferredUICultureCode), true, false) + "; \n"; script += "CMSContentManager.confirmLeaveShort=" + ScriptHelper.GetString(ResHelper.GetString("Content.ConfirmLeaveShort", user.PreferredUICultureCode), true, false) + "; \n"; } else { script += "CMSContentManager.confirmChanges = false;"; } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "saveChangesScript", script, true); try { if (node != null) { DocumentContext.CurrentPageInfo = PageInfoProvider.GetPageInfo(node.NodeSiteName, node.NodeAliasPath, node.DocumentCulture, null, node.NodeID, false); // Title string title = DocumentContext.CurrentTitle; if (!string.IsNullOrEmpty(title)) { title = "<title>" + title + "</title>"; } // Body class string bodyCss = DocumentContext.CurrentBodyClass; // Remove bootstrap default class bodyCss = bodyCss.Replace(" cms-bootstrap", String.Empty); if (bodyCss != null && bodyCss.Trim() != "") { bodyCss = "class=\"" + bodyCss + "\""; } else { bodyCss = ""; } // Metadata string meta = "<meta http-equiv=\"pragma\" content=\"no-cache\" />"; string description = DocumentContext.CurrentDescription; if (description != "") { meta += "<meta name=\"description\" content=\"" + description + "\" />"; } string keywords = DocumentContext.CurrentKeyWords; if (keywords != "") { meta += "<meta name=\"keywords\" content=\"" + keywords + "\" />"; } // Site style sheet string cssSiteSheet = ""; int stylesheetId = DocumentContext.CurrentPageInfo.DocumentStylesheetID; CssStylesheetInfo cssInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo((stylesheetId > 0) ? stylesheetId : SiteContext.CurrentSite.SiteDefaultStylesheetID); if (cssInfo != null) { cssSiteSheet = CSSHelper.GetCSSFileLink(CSSHelper.GetStylesheetUrl(cssInfo.StylesheetName)); } // Theme CSS files string themeCssFiles = ""; if (cssInfo != null) { try { string directory = URLHelper.GetPhysicalPath(string.Format("~/App_Themes/{0}/", cssInfo.StylesheetName)); if (Directory.Exists(directory)) { foreach (string file in Directory.GetFiles(directory, "*.css")) { themeCssFiles += CSSHelper.GetCSSFileLink(CSSHelper.GetPhysicalCSSUrl(cssInfo.StylesheetName, Path.GetFileName(file))); } } } catch { } } // Add values to page mHead = FormatHTML(HighlightHTML(title + meta + cssSiteSheet + themeCssFiles), 2); mBody = bodyCss; } } catch { ShowError(GetString("MasterPage.PageEditErr")); } LoadData(); // Add save action SaveAction save = new SaveAction(); save.CommandArgument = ComponentEvents.SAVE_DATA; save.CommandName = ComponentEvents.SAVE_DATA; headerActions.ActionsList.Add(save); if (pti != null) { // Disable buttons for no-template bool actionsEnabled = (pti.PageTemplateId > 0); // Edit layout HeaderAction action = new HeaderAction { Text = GetString("content.ui.pagelayout"), Tooltip = GetString("pageplaceholder.editlayouttooltip"), OnClientClick = "EditLayout();return false;", Enabled = actionsEnabled }; headerActions.ActionsList.Add(action); string elemUrl = UIContextHelper.GetElementDialogUrl("cms.design", "PageTemplate.EditPageTemplate", pti.PageTemplateId); // Edit page properties action action = new HeaderAction { Text = GetString("PageProperties.EditTemplateProperties"), Tooltip = GetString("PageProperties.EditTemplateProperties"), OnClientClick = "modalDialog('" + elemUrl + "', 'TemplateSelection', '85%', '85%', false);return false;", Enabled = actionsEnabled }; CMSPagePlaceholder.RegisterEditLayoutScript(this, pti.PageTemplateId, node.NodeAliasPath, null); headerActions.ActionsList.Add(action); // Preview HeaderAction preview = new HeaderAction { Text = GetString("general.preview"), OnClientClick = "performToolbarAction('split');return false;", Visible = ((previewState == 0) && !UIContext.DisplaySplitMode), Tooltip = GetString("preview.tooltip") }; headerActions.ActionsList.Add(preview); headerActions.ActionPerformed += headerActions_ActionPerformed; } RegisterInitScripts(pnlBody.ClientID, pnlMenu.ClientID, false); }
/// <summary> /// Saves relationship. /// </summary> /// <returns>True, if relatioship was successfully saved.</returns> public bool SaveRelationship() { bool saved = false; // Check modify permissions if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(TreeNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { return saved; } bool currentNodeIsOnLeftSide = ValidationHelper.GetBoolean(Request.Params[hdnCurrentOnLeft.UniqueID], false); int selectedNodeId = ValidationHelper.GetInteger(hdnSelectedNodeId.Value, 0); TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); // Try to get by path if not selected if (selectedNodeId <= 0) { string aliaspath = currentNodeIsOnLeftSide ? txtRightNode.Text.Trim() : txtLeftNode.Text.Trim(); if (aliaspath != string.Empty) { node = tree.SelectSingleNode(SiteContext.CurrentSiteName, aliaspath, TreeProvider.ALL_CULTURES); if (node != null) { selectedNodeId = node.NodeID; } else { ShowError(GetString("relationship.selectcorrectrelateddoc")); } } else { ShowError(GetString("relationship.selectrelateddoc")); } } int selectedValue = 0; // Only one relationship name in textbox if ((relationshipNameInfo != null) && (lblRelName.Visible)) { selectedValue = relationshipNameInfo.RelationshipNameId; } // Value from relationship name selector else if (relNameSelector.Visible) { selectedValue = ValidationHelper.GetInteger(relNameSelector.Value, 0); } if ((currentNodeId > 0) && (selectedNodeId > 0) && (selectedValue > 0)) { int relationshipNameId = selectedValue; try { // Left side if (currentNodeIsOnLeftSide) { RelationshipInfoProvider.AddRelationship(currentNodeId, selectedNodeId, relationshipNameId); } // Right side else { RelationshipInfoProvider.AddRelationship(selectedNodeId, currentNodeId, relationshipNameId); } // Log synchronization for single document TreeNode currentNode = node ?? tree.SelectSingleNode(currentNodeId); DocumentSynchronizationHelper.LogDocumentChange(currentNode, TaskTypeEnum.UpdateDocument, tree); saved = true; ShowChangesSaved(); } catch (Exception ex) { ShowError(ex.Message); } } return saved; }
/// <summary> /// Indicates if there is needed fallback to root document. /// </summary> /// <param name="selectedNode">Selected node</param> private bool UseFallbackToRoot(TreeNode selectedNode) { if (selectedNode != null) { bool useFallback = false; string currentAliasPath = selectedNode.NodeAliasPath; // Check user's starting path string userStartingPath = CurrentUser.UserStartingAliasPath; if (!String.IsNullOrEmpty(userStartingPath)) { useFallback = !currentAliasPath.StartsWithCSafe(userStartingPath, true) && (TreePathUtils.GetNodeIdByAliasPath(selectedNode.NodeSiteName, userStartingPath) > 0); } if (IsProductTree) { // Check products starting path if in Products UI string productsStartingPath = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSStoreProductsStartingPath"); if (!String.IsNullOrEmpty(productsStartingPath)) { useFallback |= !currentAliasPath.StartsWithCSafe(productsStartingPath, true) && (TreePathUtils.GetNodeIdByAliasPath(selectedNode.NodeSiteName, productsStartingPath) > 0); } } return useFallback; } return true; }
private string GetRuleConditionActivityUrlField(TreeNode document) { if (StaticRandom.NextDouble() < 0.5 && document.RelativeURL.Length > 2) { return "<field name=\"ActivityURL\"><value>" + document.RelativeURL.Substring(2) + "</value><params><operator>0</operator></params></field>"; } return String.Empty; }
/// <summary> /// Performs necessary checks and archives document. /// </summary> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PerformArchive(WorkflowManager wm, TreeProvider tree, TreeNode node, string aliasPath) { if (node != null) { if (!UndoPossibleCheckOut(tree, node)) { return true; } try { if (currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(node.DocumentCulture, node.NodeSiteName)) { AddLog(string.Format(GetString("content.notallowedtomodifycultureversion"), node.DocumentCulture, node.NodeAliasPath)); } else { // Add log record AddLog(HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")")); // Archive document wm.ArchiveDocument(node, string.Empty); } } catch (ThreadAbortException te) { AddLog(te.Message); } catch { AddLog(string.Format(ResHelper.GetString("content.archivenowf"), HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"))); } return false; } else { AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath))); return false; } }
/// <summary> /// Return true if any document is in different culture than current. /// </summary> /// <param name="node">Tree node</param> private bool IsAnyDocumentInAnotherCulture(TreeNode node) { return Tree.SelectNodesCount(node.NodeSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, "DocumentCulture NOT LIKE '" + node.DocumentCulture + "'", null, TreeProvider.ALL_LEVELS, false) > 0; }
/// <summary> /// Performs necessary checks and publishes document. /// </summary> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PerformPublish(WorkflowManager wm, TreeProvider tree, TreeNode node, string aliasPath) { if (node != null) { if (currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(node.DocumentCulture, node.NodeSiteName)) { AddLog(string.Format(GetString("content.notallowedtomodifycultureversion"), node.DocumentCulture, HTMLHelper.HTMLEncode(node.NodeAliasPath))); } else { if (!UndoPossibleCheckOut(tree, node)) { return true; } WorkflowStepInfo currentStep = null; try { // Try to get workflow scope currentStep = wm.EnsureStepInfo(node); } catch (ThreadAbortException te) { AddLog(te.Message); } catch { AddLog(string.Format(ResHelper.GetString("content.publishnowf"), HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"))); return false; } if (currentStep != null) { // Publish document return Publish(node, wm, currentStep); } } return false; } else { AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath))); return false; } }
/// <summary> /// Checks whether the user is authorized to delete SKU bound to given node. /// </summary> /// <param name="node">Node to be checked</param> protected bool IsUserAuthorizedToModifySKU(TreeNode node) { bool authorized = false; if ((node != null) && (node.HasSKU)) { var product = BaseAbstractInfoProvider.GetInfoById(PredefinedObjectType.SKU, node.NodeSKUID); if (product != null) { authorized = product.CheckPermissions(PermissionsEnum.Delete, node.NodeSiteName, currentUser); } } return authorized; }
/// <summary> /// Publishes document. /// </summary> /// <param name="node">Node to publish</param> /// <param name="wm">Workflow manager</param> /// <param name="currentStep">Current workflow step</param> /// <returns>TRUE if operation fails</returns> private bool Publish(TreeNode node, WorkflowManager wm, WorkflowStepInfo currentStep) { string pathCulture = HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"); bool alreadyPublished = (currentStep == null) || currentStep.StepIsPublished; if (!alreadyPublished) { // Publish document currentStep = wm.PublishDocument(node, null); } // Document is already published, check if still under workflow if (alreadyPublished && (currentStep != null) && currentStep.StepIsPublished) { WorkflowScopeInfo wsi = wm.GetNodeWorkflowScope(node); if (wsi == null) { DocumentHelper.ClearWorkflowInformation(node); VersionManager vm = VersionManager.GetInstance(node.TreeProvider); vm.RemoveWorkflow(node); } } // Document already published if (alreadyPublished) { AddLog(string.Format(ResHelper.GetString("content.publishedalready"), pathCulture)); } else if (!currentStep.StepIsPublished) { AddError(string.Format(ResHelper.GetString("content.PublishWasApproved"), pathCulture)); return true; } else { // Add log record AddLog(pathCulture); } return false; }
/// <summary> /// Returns true when given node is bound to the same SKU as some other node does. /// </summary> /// <param name="tree">Tree provider to use</param> /// <param name="node">Node to check</param> protected bool NodeSharesSKUWithOtherNode(TreeProvider tree, TreeNode node) { string where = "NodeLinkedNodeID IS NULL AND NodeSKUID = " + node.NodeSKUID + " AND NodeID <> " + node.NodeID; return 0 < tree.SelectNodesCount(TreeProvider.ALL_SITES, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, TreeProvider.ALL_LEVELS, false); }
/// <summary> /// Publishes sub documents of given node. /// </summary> /// <param name="parentNode">Parent node</param> /// <param name="tree">Tree provider</param> /// <param name="wm">Workflow manager</param> /// <param name="cultureCode">Culture code</param> /// <param name="siteName">Site name</param> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PublishSubDocuments(TreeNode parentNode, TreeProvider tree, WorkflowManager wm, string cultureCode, string siteName) { // Get sub documents DataSet subDocuments = GetSubDocuments(parentNode, tree, cultureCode, siteName); if (!DataHelper.DataSourceIsEmpty(subDocuments)) { foreach (DataRow nodeRow in subDocuments.Tables[0].Rows) { if (PerformPublish(wm, tree, siteName, nodeRow)) { return true; } } } return false; }
/// <summary> /// Checks whether the user is authorized to delete document. /// </summary> /// <param name="node">Document node</param> protected bool IsUserAuthorizedToDeleteDocument(TreeNode node) { // Check delete permission for document return (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Delete, NodePermissionsEnum.Read }) == AuthorizationResultEnum.Allowed); }
/// <summary> /// Undoes checkout for given node. /// </summary> /// <param name="tree">Tree provider</param> /// <param name="node">Node to undo checkout</param> /// <returns>FALSE when document is checked out and checkbox for undoing checkout is not checked</returns> private bool UndoPossibleCheckOut(TreeProvider tree, TreeNode node) { if (node.IsCheckedOut) { if (chkUndoCheckOut.Checked && ((CurrentUser.UserID == node.DocumentCheckedOutByUserID) || (CurrentUser.IsAuthorizedPerResource("CMS.Content", "checkinall")))) { TreeProvider.ClearCheckoutInformation(node); node.Update(); } else { string nodeAliasPath = HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"); if (CurrentUser.UserID != node.DocumentCheckedOutByUserID) { // Get checked out message var user = UserInfoProvider.GetUserInfo(node.DocumentCheckedOutByUserID); string userName = (user != null) ? user.GetFormattedUserName(false) : ""; AddError(String.Format(GetString("editcontent.documentnamecheckedoutbyanother"), nodeAliasPath, userName)); } else { AddError(string.Format(ResHelper.GetString("content.checkedoutdocument"), nodeAliasPath)); } return false; } } return true; }
/// <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; }