/// <summary> /// Checks whether the user is authorized to delete document. /// </summary> /// <param name="treeNode">Document node</param> /// <param name="deleteDocHistory">Delete document history?</param> protected bool IsUserAuthorizedToDeleteDocument(TreeNode treeNode, bool deleteDocHistory) { bool isAuthorized = true; CurrentUserInfo currentUser = CMSContext.CurrentUser; // Check delete permission if (currentUser.IsAuthorizedPerDocument(treeNode, new NodePermissionsEnum[] { NodePermissionsEnum.Delete, NodePermissionsEnum.Read }) == AuthorizationResultEnum.Allowed) { if (deleteDocHistory) { // Check destroy permission if (currentUser.IsAuthorizedPerDocument(treeNode, NodePermissionsEnum.Destroy) != AuthorizationResultEnum.Allowed) { isAuthorized = false; } } } else { isAuthorized = false; } return(isAuthorized); }
protected void Page_Load(object sender, EventArgs e) { // UI settings categoriesElem.DisplaySavedMessage = false; categoriesElem.OnAfterSave += categoriesElem_OnAfterSave; categoriesElem.UniSelector.OnSelectionChanged += categoriesElem_OnSelectionChanged; if (Node != null) { // Check read permissions if (currentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), Node.NodeAliasPath)); } // Check modify permissions else if (currentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { hasModifyPermission = false; // Disable selector categoriesElem.Enabled = false; DocumentManager.DocumentInfo = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath); } // Display all global categories in administration UI categoriesElem.UserID = currentUser.UserID; categoriesElem.DocumentID = Node.DocumentID; } }
/// <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) { // Check UI Analytics.Settings CurrentUserInfo ui = CMSContext.CurrentUser; if (!ui.IsAuthorizedPerUIElement("CMS.Content", "Analytics.Settings")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "Analytics.Settings"); } // Display disabled information if (!AnalyticsHelper.AnalyticsEnabled(CMSContext.CurrentSiteName)) { this.pnlWarning.Visible = true; this.lblWarning.Text = ResHelper.GetString("WebAnalytics.Disabled"); } ucConversionSelector.SelectionMode = SelectionModeEnum.SingleTextBox; ucConversionSelector.IsLiveSite = false; nodeID = QueryHelper.GetInteger("nodeid", 0); mSave = GetString("general.save"); UIContext.AnalyticsTab = AnalyticsTabEnum.Settings; tree = new TreeProvider(CMSContext.CurrentUser); node = tree.SelectSingleNode(nodeID, CMSContext.PreferredCultureCode, tree.CombineWithDefaultCulture); if (ui.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } // Check modify permissions else if (ui.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { lblInfo.Visible = true; lblInfo.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), node.NodeAliasPath); // Disable save button btnSave.Enabled = false; usSelectCampaign.Enabled = false; } if (node != null) { if (!URLHelper.IsPostback()) { ReloadData(); } } }
private void ReloadData() { if (node != null) { // Check read permissions if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } // Check modify permissions else if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { DisableFormEditing(); lblInfo.Visible = true; lblInfo.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), node.NodeAliasPath); } if (hasDesign) { // Show template name by template id if (node.GetValue("DocumentPageTemplateID") != null) { PageTemplateInfo pt = PageTemplateInfoProvider.GetPageTemplateInfo(Convert.ToInt32(node.GetValue("DocumentPageTemplateID"))); if (pt != null) { // Prepare the template name string templateName = null; if (pt.IsReusable) { templateName = pt.DisplayName; } else { templateName = "Ad-hoc: " + (!string.IsNullOrEmpty(node.DocumentName) ? node.DocumentName : node.DocumentNamePath); } ltlScript.Text += ScriptHelper.GetScript("SelectTemplate(" + pt.PageTemplateId + ", " + ScriptHelper.GetString(templateName) + ", " + pt.IsPortal.ToString().ToLower() + ", " + pt.IsReusable.ToString().ToLower() + "); RememberTemplate(" + ScriptHelper.GetString(pt.DisplayName) + ");"); } else { ltlScript.Text += ScriptHelper.GetScript("NoTemplateSelected();"); } btnInherit.Visible = true; } else { btnInherit_Click(null, null); } } } }
private void ReloadData() { if (node != null) { if (node.IsRoot()) { // Hide inheritance options for root node pnlInherits.Visible = false; } else { inheritElem.Value = node.NodeWireframeInheritPageLevels; } CurrentUserInfo currentUser = CMSContext.CurrentUser; // Check read permissions if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } // Check modify permissions else if (!currentUser.IsAuthorizedPerResource("CMS.Design", "Wireframing") || (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)) { hasModifyPermission = false; txtComment.Enabled = false; EditMenu.Enabled = false; } txtComment.Text = node.GetStringValue("NodeWireframeComment", ""); } }
/// <summary> /// Checks if current use can modify the permission. /// </summary> /// <param name="redirect">If true and can't modify the user is redirected to denied page</param> /// <param name="currentNode">Current node</param> /// <param name="user">Current user</param> private bool CanModifyPermission(bool redirect, TreeNode currentNode, CurrentUserInfo user) { bool hasPermission = false; if (currentNode != null) { hasPermission = (user.IsAuthorizedPerDocument(currentNode, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed); // If hasn't permission and redirect enabled if (!hasPermission) { if (redirect) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoeditdocumentpermissions"), currentNode.NodeAliasPath)); } else { pnlAccessPart.Enabled = false; btnRadOk.Enabled = false; pnlInheritance.Enabled = false; lnkInheritance.Visible = false; } } } return(hasPermission); }
protected void btnSave_Click(object sender, EventArgs ea) { // Check modify permissions CurrentUserInfo ui = CMSContext.CurrentUser; if (node != null) { // Check permissions if (ui.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } string conversionValue = ValidationHelper.GetString(ucConversionSelector.Value, String.Empty).Trim(); if (!ucConversionSelector.IsValid()) { lblError.Text = ucConversionSelector.ValidationError; lblError.Visible = true; return; } if (!usSelectCampaign.IsValid()) { lblError.Visible = true; lblError.Text = usSelectCampaign.ValidationError; return; } node.DocumentCampaign = ValidationHelper.GetString(usSelectCampaign.Value, String.Empty).Trim(); node.DocumentConversionValue = txtConversionValue.Text; node.DocumentTrackConversionName = conversionValue; node.Update(); lblInfo.Visible = true; lblInfo.Text = GetString("general.changessaved"); // Update search index if ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } }
/// <summary> /// Reloads comment list. /// </summary> public void ReloadComments() { this.SetContext(); this.pnlComment.Visible = this.AreCommentsOpened; if (this.PostNode != null) { CurrentUserInfo currentUser = CMSContext.CurrentUser; // Check permissions for blog if (this.BlogProperties.CheckPermissions) { if (currentUser.IsAuthorizedPerDocument(this.PostNode, NodePermissionsEnum.Read) != AuthorizationResultEnum.Allowed) { this.Visible = false; return; } } ctrlCommentEdit.PostDocumentId = this.PostNode.DocumentID; ctrlCommentEdit.PostNodeId = this.PostNode.NodeID; ctrlCommentEdit.PostCulture = this.PostNode.DocumentCulture; if (!this.BlogProperties.StopProcessing) { // Get parent blog bool selectOnlyPublished = (CMSContext.ViewMode == ViewModeEnum.LiveSite); TreeNode blogNode = BlogHelper.GetParentBlog(this.AliasPath, this.SiteName, selectOnlyPublished); // Determine whether user is authorized to manage comments isUserAuthorized = BlogHelper.IsUserAuthorizedToManageComments(blogNode); // Get all post comments rptComments.DataSource = BlogCommentInfoProvider.GetPostComments(this.PostNode.DocumentID, !isUserAuthorized, isUserAuthorized, DisplayTrackbacks); rptComments.DataBind(); } } this.ReleaseContext(); }
/// <summary> /// Checks whether the user is authorized to translate document. /// </summary> /// <param name="node">Document node</param> /// <param name="siteName">Site name</param> protected bool IsUserAuthorizedToTranslateDocument(TreeNode node, string siteName) { // Check create permission for document return((currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Create, NodePermissionsEnum.Read }) == AuthorizationResultEnum.Allowed) && (currentUser.IsAuthorizedPerResource("CMS.Content", "SubmitForTranslation"))); }
/// <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> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (this.StopProcessing) { this.editForm.StopProcessing = true; this.editForm.Visible = false; } else { this.pnlEdit.Visible = false; CurrentUserInfo currentUser = CMSContext.CurrentUser; // Get the document TreeNode node = TreeHelper.GetDocument(this.SiteName, CMSContext.ResolveCurrentPath(this.Path), this.CultureCode, false, null, false, this.CheckPermissions, currentUser); if (node != null) { bool authorized = false; // Check allowed users switch (this.AllowUsers) { case UserContributionAllowUserEnum.All: authorized = true; break; case UserContributionAllowUserEnum.Authenticated: authorized = currentUser.IsAuthenticated(); break; case UserContributionAllowUserEnum.DocumentOwner: authorized = (node.NodeOwner == currentUser.UserID); break; } bool authorizedDelete = authorized; // Check control access permission if (authorized && this.CheckPermissions) { // Node owner has always permission if (node.NodeOwner != currentUser.UserID) { authorized &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Modify }) == AuthorizationResultEnum.Allowed); authorizedDelete &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Delete }) == AuthorizationResultEnum.Allowed); } } // Check group permissions authorized &= CheckGroupPermission("editpages"); authorizedDelete &= CheckGroupPermission("deletepages"); // Global admin has always permission authorized |= currentUser.IsGlobalAdministrator; authorizedDelete |= currentUser.IsGlobalAdministrator; // Do not allow edit for virtual user if (currentUser.IsVirtual) { authorized = false; authorizedDelete = false; } // Display form if authorized if (authorized || authorizedDelete) { this.pnlEdit.Visible = true; // Set visibility of edit and delete buttons this.btnEdit.Visible = this.btnEdit.Visible && authorized; this.btnDelete.Visible = this.btnDelete.Visible && this.AllowDelete && authorizedDelete; if ((!RequestHelper.IsPostBack()) && ((this.btnEdit.Text.Trim() == string.Empty) || (this.btnDelete.Text.Trim() == string.Empty))) { // Initialize labels and css classes this.btnEdit.ResourceString = this.EditButtonText; this.btnEdit.CssClass = "EditContributionEdit"; this.btnDelete.ResourceString = this.DeleteButtonText; this.btnDelete.CssClass = "EditContributionDelete"; } if (this.pnlForm.Visible) { this.editForm.StopProcessing = false; this.editForm.FunctionsPrefix = this.ID + "_"; this.editForm.AllowDelete = this.AllowDelete && CheckGroupPermission("deletepages"); this.editForm.CheckPermissions = this.CheckPermissions; this.editForm.NodeID = node.NodeID; this.editForm.SiteName = this.SiteName; this.editForm.CultureCode = this.CultureCode; this.editForm.AlternativeFormName = this.AlternativeFormName; this.editForm.ValidationErrorMessage = this.ValidationErrorMessage; this.editForm.CMSForm.IsLiveSite = true; this.editForm.OnAfterApprove += editForm_OnAfterChange; this.editForm.OnAfterReject += editForm_OnAfterChange; this.editForm.OnAfterDelete += editForm_OnAfterChange; this.editForm.CMSForm.OnAfterSave += CMSForm_OnAfterSave; this.editForm.LogActivity = this.LogActivity; // Reload data this.editForm.ReloadData(false); } } } } }
protected override void OnPreRender(EventArgs e) { CurrentUserInfo ui = CMSContext.CurrentUser; if (!ui.IsAuthorizedPerUIElement("CMS.Content", "Reports")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "Reports"); } // Check read for web analytics if (!ui.IsAuthorizedPerResource("cms.webanalytics", "Read")) { RedirectToAccessDenied(String.Format(GetString("general.permissionresource"), "Read", "Web analytics")); } // Display disabled information if (!AnalyticsHelper.AnalyticsEnabled(CMSContext.CurrentSiteName)) { this.pnlWarning.Visible = true; this.lblWarning.Text = ResHelper.GetString("WebAnalytics.Disabled"); } ucDisplayReport = LoadControl("~/CMSModules/Reporting/Controls/DisplayReport.ascx") as IDisplayReport; pnlContent.Controls.Add((Control)ucDisplayReport); // Check read permission for node int nodeID = QueryHelper.GetInteger("nodeid", 0); TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = tree.SelectSingleNode(nodeID, CMSContext.PreferredCultureCode, tree.CombineWithDefaultCulture); if (ui.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } ucGraphType.ProcessChartSelectors(false); CurrentMaster.PanelContent.CssClass = String.Empty; UIHelper.AllowUpdateProgress = false; // General report data ucDisplayReport.ReportName = rbContent.Checked ? "pagereports.content" : "pagereports.Traffic"; ucDisplayReport.LoadFormParameters = false; ucDisplayReport.DisplayFilter = false; ucDisplayReport.GraphImageWidth = 100; ucDisplayReport.IgnoreWasInit = true; ucDisplayReport.TableFirstColumnWidth = Unit.Percentage(30); ucDisplayReport.UseExternalReload = true; ucDisplayReport.UseProgressIndicator = true; ucDisplayReport.SetDefaultDynamicMacros((int)ucGraphType.SelectedInterval); // Resolve report macros DataTable dtp = new DataTable(); dtp.Columns.Add("FromDate", typeof(DateTime)); dtp.Columns.Add("ToDate", typeof(DateTime)); dtp.Columns.Add("CodeName", typeof(string)); dtp.Columns.Add("NodeID", typeof(int)); dtp.Columns.Add("CultureCode", typeof(string)); object[] parameters = new object[5]; parameters[0] = ucGraphType.From; parameters[1] = ucGraphType.To; parameters[2] = "pageviews"; parameters[3] = nodeID; parameters[4] = CMSContext.PreferredCultureCode; dtp.Rows.Add(parameters); dtp.AcceptChanges(); ucDisplayReport.ReportParameters = dtp.Rows[0]; ucDisplayReport.ReloadData(true); base.OnPreRender(e); }
/// <summary> /// Page load. /// </summary> protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterScriptFile(this, @"~/CMSModules/Content/CMSDesk/View/Listing.js"); currentSiteName = CMSContext.CurrentSiteName; currentUserInfo = CMSContext.CurrentUser; // Current Node ID nodeId = QueryHelper.GetInteger("nodeid", 0); // Setup page title text and image CurrentMaster.Title.TitleText = GetString("Content.ListingTitle"); CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Content/Menu/Listing.png"); CurrentMaster.Title.HelpName = "helpTopic"; CurrentMaster.Title.HelpTopicName = "list_tab"; string[,] actions = new string[1, 6]; actions[0, 0] = HeaderActions.TYPE_HYPERLINK; actions[0, 1] = GetString("Listing.ParentDirectory"); actions[0, 5] = GetImageUrl("CMSModules/CMS_Content/Listing/parent.png"); CurrentMaster.HeaderActions.Actions = actions; if (nodeId > 0) { tree = new TreeProvider(currentUserInfo); checkPermissions = tree.CheckDocumentUIPermissions(currentSiteName); node = tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES); // Set edited document EditedDocument = node; if (node != null) { if (currentUserInfo.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) != AuthorizationResultEnum.Allowed) { RedirectToCMSDeskAccessDenied("CMS.Content", "exploretree"); } aliasPath = node.NodeAliasPath; // Setup the link to the parent document if ((node.NodeClassName.ToLower() != "cms.root") && (currentUserInfo.UserStartingAliasPath.ToLower() != node.NodeAliasPath.ToLower())) { CurrentMaster.HeaderActions.Actions[0, 3] = "javascript:SelectItem(" + node.NodeParentID + ");"; } else { CurrentMaster.HeaderActions.Visible = false; CurrentMaster.PanelBody.FindControl("pnlActions").Visible = false; } } ScriptHelper.RegisterProgress(this); ScriptHelper.RegisterDialogScript(this); ScriptHelper.RegisterJQuery(this); InitDropdowLists(); cultureElem.DropDownCultures.Width = 222; // Prepare JavaScript for actions StringBuilder actionScript = new StringBuilder(); actionScript.Append( @"function PerformAction(selectionFunction, selectionField, dropId){ var label = document.getElementById('" + lblInfo.ClientID + @"'); var whatDrp = document.getElementById('" + drpWhat.ClientID + @"'); var action = document.getElementById(dropId).value; var selectionFieldElem = document.getElementById(selectionField); var allSelected = " + (int)What.SelectedDocuments + @"; if (action == '" + (int)Action.SelectAction + @"'){ label.innerHTML = '" + GetString("massaction.selectsomeaction") + @"'; return false; } if(whatDrp.value == '" + (int)What.AllDocuments + @"'){ allSelected = " + (int)What.AllDocuments + @"; } var items = selectionFieldElem.value; if(!eval(selectionFunction) || whatDrp.value == '" + (int)What.AllDocuments + @"'){ var argument = '|' + allSelected + '|' + items; switch(action){ case '" + (int)Action.Move + @"': argument = '" + Action.Move + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty) + @"; break; case '" + (int)Action.Copy + @"': argument = '" + Action.Copy + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty) + @"; break; case '" + (int)Action.Link + @"': argument = '" + Action.Link + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty) + @"; break; case '" + (int)Action.Delete + @"': argument = '" + Action.Delete + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty) + @"; break; case '" + (int)Action.Publish + @"': argument = '" + Action.Publish + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty) + @"; break; case '" + (int)Action.Archive + @"': argument = '" + Action.Archive + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty) + @"; break; default: return false; } } else{ label.innerHTML = '" + GetString("documents.selectdocuments") + @"'; } return false; } function OpenModal(arg, context){ modalDialog(arg,'actionDialog','90%', '85%'); } function Redirect(arg, context){ document.location.replace(arg); }"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "actionScript", ScriptHelper.GetScript(actionScript.ToString())); // Add action to button btnOk.OnClientClick = "return PerformAction('" + gridDocuments.GetCheckSelectionScript() + "','" + gridDocuments.GetSelectionFieldClientID() + "','" + drpAction.ClientID + "');"; // Initialize dropdown lists if (!RequestHelper.IsPostBack()) { drpAction.Items.Add(new ListItem(GetString("general." + Action.SelectAction), Convert.ToInt32(Action.SelectAction).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Move), Convert.ToInt32(Action.Move).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Copy), Convert.ToInt32(Action.Copy).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Link), Convert.ToInt32(Action.Link).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Delete), Convert.ToInt32(Action.Delete).ToString())); if (currentUserInfo.IsGlobalAdministrator || currentUserInfo.IsAuthorizedPerResource("CMS.Content", "ManageWorkflow")) { drpAction.Items.Add(new ListItem(GetString("general." + Action.Publish), Convert.ToInt32(Action.Publish).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Archive), Convert.ToInt32(Action.Archive).ToString())); } drpWhat.Items.Add(new ListItem(GetString("contentlisting." + What.SelectedDocuments), Convert.ToInt32(What.SelectedDocuments).ToString())); drpWhat.Items.Add(new ListItem(GetString("contentlisting." + What.AllDocuments), Convert.ToInt32(What.AllDocuments).ToString())); } // Setup the grid gridDocuments.OnExternalDataBound += gridDocuments_OnExternalDataBound; gridDocuments.OnBeforeDataReload += gridDocuments_OnBeforeDataReload; gridDocuments.OnDataReload += gridDocuments_OnDataReload; gridDocuments.ZeroRowsText = GetString("content.nochilddocumentsfound"); gridDocuments.ShowActionsMenu = true; if (node != null) { gridDocuments.WhereCondition = "NodeParentID = " + node.NodeID + " AND NodeLevel = " + (node.NodeLevel + 1); } // Initialize columns string columns = @"DocumentLastVersionName, DocumentName, NodeParentID, ClassDisplayName, DocumentModifiedWhen, Published, DocumentLastVersionNumber, DocumentMenuRedirectURL, DocumentLastVersionMenuRedirectUrl, DocumentIsArchived, DocumentCheckedOutByUserID, DocumentPublishedVersionHistoryID, DocumentWorkflowStepID, DocumentCheckedOutVersionHistoryID, DocumentNamePath, DocumentPublishFrom, DocumentType, DocumentLastVersionType, NodeAliasPath"; if (checkPermissions) { columns = SqlHelperClass.MergeColumns(columns, TreeProvider.SECURITYCHECK_REQUIRED_COLUMNS); } gridDocuments.Columns = columns; StringBuilder refreshScripts = new StringBuilder(); refreshScripts.Append( @"function RefreshTree() { if((parent != null) && (parent.parent != null) && (parent.parent.frames['contenttree'] != null) && (parent.parent.frames['contenttree'].RefreshNode != null)) { parent.parent.frames['contenttree'].RefreshNode(", nodeId, @",", nodeId, @"); } } function ClearSelection() { ", gridDocuments.GetClearSelectionScript(), @" } function RefreshGrid() { ClearSelection(); RefreshTree();", ClientScript.GetPostBackEventReference(btnShow, "null"), @" }"); // Register refresh scripts string refreshScript = ScriptHelper.GetScript(refreshScripts.ToString()); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "refreshListing", refreshScript); // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); gridDocuments.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(di.ColumnNames.ToArray()), SqlHelperClass.MergeColumns(nodeClass.ColumnNames.ToArray())); } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (this.StopProcessing) { // Do not process } else { CurrentUserInfo uinfo = CMSContext.CurrentUser; if (uinfo.IsGlobalAdministrator || !DisplayOnlyToGlobalAdministrator) { // Create new string builder for links StringBuilder sb = new StringBuilder(); // Store current site name string curSiteName = CMSContext.CurrentSiteName; // Get default user name string queryStringKey = (string.IsNullOrEmpty(DefaultUserName)) ? null : "?username="******"~/cmsdesk/default.aspx"); if (!string.IsNullOrEmpty(DefaultUserName)) { url = URLHelper.AddParameterToUrl(url, "username", DefaultUserName); } if (CMSContext.CurrentPageInfo != null) { url = URLHelper.AddParameterToUrl(url, "nodeid", CMSContext.CurrentPageInfo.NodeId.ToString()); } sb.AppendFormat(CMSDeskText, string.Concat("<a href=\"", URLHelper.EncodeQueryString(url), "\">", CMSDeskLinkText, "</a>")); separatorNeeded = true; } // If site manager link is shown if (ShowCMSSiteManagerLink && (!CheckPermissions || uinfo.UserSiteManagerAdmin)) { // Check if separator needed if (separatorNeeded) { sb.Append(Separator); } string url = ResolveUrl("~/cmssitemanager/default.aspx"); if (!string.IsNullOrEmpty(DefaultUserName)) { url = URLHelper.AddParameterToUrl(url, "username", DefaultUserName); } sb.AppendFormat(CMSSiteManagerText, string.Concat("<a href=\"", url, "\">", CMSSiteManagerLinkText, "</a>")); separatorNeeded = true; } // If edit document link is shown if (ShowEditDocumentLink && (!CheckPermissions || (uinfo.CheckEditor(curSiteName) && CMSPage.IsUserAuthorizedPerContent() && (uinfo.IsAuthorizedPerDocument(CMSContext.CurrentDocument, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)))) { // Check if separator needed if (separatorNeeded) { sb.Append(" " + Separator + " "); } sb.AppendFormat(EditDocumentText, string.Concat("<a href=\"", URLHelper.EncodeQueryString(UIHelper.GetDocumentEditUrl(CMSContext.CurrentDocument.NodeID, CMSContext.CurrentDocumentCulture.CultureCode)), "\">", EditDocumentLinkText, "</a>")); } ltlAdminActions.Text = sb.ToString(); } } }
/// <summary> /// Checks if current use can moddify the perrmission. /// </summary> /// <param name="redirect">If true and can't moddify the user is redirected to denied page</param> /// <param name="currentNode">Node to examine</param> /// <param name="currentUser">Current user</param> private bool CanModifyPermission(bool redirect, TreeNode currentNode, CurrentUserInfo currentUser) { bool hasPermission = false; if (currentNode != null) { hasPermission = (currentUser.IsAuthorizedPerDocument(currentNode, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed); // If hasn't permission and resirect enabled if (!hasPermission) { if (redirect) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), currentNode.NodeAliasPath)); } else { pnlAccessPart.Enabled = false; btnRadOk.Enabled = false; pnlInheritance.Enabled = false; lnkInheritance.Visible = false; // Display message lblPermission.Visible = true; lblPermission.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath); } } } return hasPermission; }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do not process } else { CurrentUserInfo uinfo = CMSContext.CurrentUser; if (uinfo.IsGlobalAdministrator || !DisplayOnlyToGlobalAdministrator) { // Create new string builder for links StringBuilder sb = new StringBuilder(); // Store current site name string curSiteName = CMSContext.CurrentSiteName; // Get default user name string queryStringKey = (string.IsNullOrEmpty(DefaultUserName)) ? null : "?username="******"~/cmsdesk/default.aspx"); if (!string.IsNullOrEmpty(DefaultUserName)) { url = URLHelper.AddParameterToUrl(url, "username", DefaultUserName); } if (CMSContext.CurrentPageInfo != null) { url = URLHelper.AddParameterToUrl(url, "nodeid", CMSContext.CurrentPageInfo.NodeID.ToString()); } sb.AppendFormat(CMSDeskText, string.Concat("<a href=\"", URLHelper.EncodeQueryString(url), "\">", CMSDeskLinkText, "</a>")); separatorNeeded = true; } // If site manager link is shown if (ShowCMSSiteManagerLink && (!CheckPermissions || uinfo.UserSiteManagerAdmin)) { // Check if separator needed if (separatorNeeded) { sb.Append(Separator); } string url = ResolveUrl("~/cmssitemanager/default.aspx"); if (!string.IsNullOrEmpty(DefaultUserName)) { url = URLHelper.AddParameterToUrl(url, "username", DefaultUserName); } sb.AppendFormat(CMSSiteManagerText, string.Concat("<a href=\"", url, "\">", CMSSiteManagerLinkText, "</a>")); separatorNeeded = true; } // If edit document link is shown if (ShowEditDocumentLink && (!CheckPermissions || (uinfo.CheckEditor(curSiteName) && CMSPage.IsUserAuthorizedPerContent() && (uinfo.IsAuthorizedPerDocument(CMSContext.CurrentDocument, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)))) { // Check if separator needed if (separatorNeeded) { sb.Append(" " + Separator + " "); } string url = URLHelper.EncodeQueryString(UIHelper.GetDocumentEditUrl(CMSContext.CurrentDocument.NodeID, CMSContext.CurrentDocumentCulture.CultureCode)); if (PreferOnSiteEdit && PortalHelper.IsOnSiteEditingEnabled(CurrentSiteName)) { url = URLHelper.ResolveUrl(PortalHelper.OnSiteEditRelativeURL); string retUrl = URLHelper.CurrentURL; // handle default alias path if ((ViewMode == CMS.PortalEngine.ViewModeEnum.LiveSite) && (URLRewriter.CurrentPageInfoSource == PageInfoSource.DefaultAliasPath)) { string aliasPath = PageInfoProvider.GetDefaultAliasPath(URLHelper.GetCurrentDomain(), CMSContext.CurrentSiteName); if (!String.IsNullOrEmpty(aliasPath)) { string query = URLHelper.GetQuery(retUrl); retUrl = URLHelper.ResolveUrl(DocumentURLProvider.GetUrl(aliasPath)); retUrl = URLHelper.AppendQuery(retUrl, query); } } url = URLHelper.UpdateParameterInUrl(url, "returnurl", HTMLHelper.HTMLEncode(HttpUtility.UrlEncode(retUrl))); } sb.AppendFormat(EditDocumentText, string.Concat("<a href=\"", url, "\">", EditDocumentLinkText, "</a>")); } ltlAdminActions.Text = sb.ToString(); } } }
public void RaisePostBackEvent(string eventArgument) { CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser; // Current Node ID int nodeId = ValidationHelper.GetInteger(Param1, 0); TreeProvider tree = new TreeProvider(currentUser); EventLogProvider log = new EventLogProvider(); string documentName = string.Empty; string action = Action.ToLowerCSafe(); string siteName = SiteContext.CurrentSiteName; // Process the request switch (action) { case "refresh": treeElem.SelectedNodeID = nodeId; AddScript("currentNodeId = " + nodeId + ";"); break; case "moveup": case "movedown": case "movetop": case "movebottom": // Move the document up (document order) try { if (nodeId == 0) { AddAlert(GetString("ContentRequest.ErrorMissingSource")); return; } // Get document to move TreeNode node = tree.SelectSingleNode(nodeId); // Check the permissions for document if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed) { // Root of products tree can not be moved if (!IsProductTree || (node.NodeAliasPath.CompareToCSafe(StartingAliasPath, true) != 0)) { switch (action) { case "moveup": node = tree.MoveNodeUp(nodeId); break; case "movedown": node = tree.MoveNodeDown(nodeId); break; case "movetop": node = tree.SelectSingleNode(nodeId); tree.SetNodeOrder(nodeId, DocumentOrderEnum.First); break; case "movebottom": node = tree.SelectSingleNode(nodeId); tree.SetNodeOrder(nodeId, DocumentOrderEnum.Last); break; } if (node != null) { // Log the synchronization tasks for the entire tree level DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, node.NodeAliasPath, tree); // Select the document in the tree documentName = node.GetDocumentName(); treeElem.ExpandNodeID = node.NodeParentID; treeElem.SelectedNodeID = node.NodeID; AddScript("currentNodeId = " + node.NodeID + ";"); } else { AddAlert(GetString("ContentRequest.MoveFailed")); } } } else { // Select the document in the tree treeElem.SelectedNodeID = nodeId; AddAlert(GetString("ContentRequest.MoveDenied")); } } catch (Exception ex) { log.LogEvent(EventLogProvider.ERROR, DateTime.Now, "Content", "MOVE", currentUser.UserID, currentUser.UserName, nodeId, documentName, RequestContext.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), SiteContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri()); AddAlert(GetString("ContentRequest.MoveFailed") + " : " + ex.Message); } break; case "setculture": // Set the preferred culture code try { // Set the culture code string language = ValidationHelper.GetString(Param2, string.Empty); if (!string.IsNullOrEmpty(language)) { LocalizationContext.PreferredCultureCode = language; treeElem.Culture = language; } // Refresh the document if (nodeId > 0) { treeElem.SelectedNodeID = nodeId; AddScript("SelectNode(" + nodeId + ");"); } } catch (Exception ex) { log.LogEvent(EventLogProvider.ERROR, DateTime.Now, "Content", "SETCULTURE", currentUser.UserID, currentUser.UserName, nodeId, documentName, RequestContext.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), SiteContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri()); AddAlert(GetString("ContentRequest.ErrorChangeLanguage")); } break; case "setdevice": // Set the device profile try { // Set the device name string deviceName = ValidationHelper.GetString(Param2, string.Empty); DeviceContext.CurrentDeviceProfileName = deviceName; // Refresh the document if (nodeId > 0) { treeElem.SelectedNodeID = nodeId; AddScript("SelectNode(" + nodeId + ");"); } } catch (Exception ex) { log.LogEvent(EventLogProvider.ERROR, DateTime.Now, "Content", "SETDEVICE", currentUser.UserID, currentUser.UserName, nodeId, documentName, RequestContext.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), SiteContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri()); AddAlert(GetString("ContentRequest.ErrorChangeLanguage")); } break; // Sorting case "sortalphaasc": case "sortalphadesc": case "sortdateasc": case "sortdatedesc": // Set the preferred culture code try { // Get document to sort TreeNode node = tree.SelectSingleNode(nodeId); // Check the permissions for document if ((currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed) && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) == AuthorizationResultEnum.Allowed)) { switch (action) { case "sortalphaasc": tree.OrderNodesAlphabetically(nodeId, true); break; case "sortalphadesc": tree.OrderNodesAlphabetically(nodeId, false); break; case "sortdateasc": tree.OrderNodesByDate(nodeId, true); break; case "sortdatedesc": tree.OrderNodesByDate(nodeId, false); break; } // Log the synchronization tasks for the entire tree level string fakeAlias = node.NodeAliasPath.TrimEnd('/') + "/child"; DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, fakeAlias, tree); } else { AddAlert(GetString("ContentRequest.SortDenied")); } // Refresh the tree if (nodeId > 0) { treeElem.ExpandNodeID = nodeId; treeElem.SelectedNodeID = nodeId; if (IsProductTree) { AddScript("window.frames['contentview'].location.replace(window.frames['contentview'].location);"); } else { AddScript("SelectNode(" + nodeId + ");"); } } } catch (Exception ex) { log.LogEvent(EventLogProvider.ERROR, DateTime.Now, "Content", "SORT", currentUser.UserID, currentUser.UserName, nodeId, documentName, RequestContext.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), SiteContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri()); AddAlert(GetString("ContentRequest.ErrorSort")); } break; } // Maintain scrollbar position string script = @" SetSelectedNodeId(currentNodeId); MaintainScroll('" + nodeId + @"','" + pnlTreeArea.ClientID + @"', " + ScrollPosition + @"); HideAllContextMenus(); "; ScriptHelper.RegisterStartupScript(Page, typeof(string), "MaintainScrollbar", script, true); }
public void RaisePostBackEvent(string eventArgument) { CurrentUserInfo currentUser = CMSContext.CurrentUser; // Current Node ID int nodeId = ValidationHelper.GetInteger(Param1, 0); TreeProvider tree = new TreeProvider(currentUser); EventLogProvider log = new EventLogProvider(); string documentName = string.Empty; string action = Action.ToLower(); string siteName = CMSContext.CurrentSiteName; // Process the request switch (action) { case "refresh": treeContent.NodeID = nodeId; AddScript("currentNodeId = " + nodeId + ";\n"); break; case "moveup": case "movedown": case "movetop": case "movebottom": // Move the document up (document order) try { if (nodeId == 0) { AddAlert(GetString("ContentRequest.ErrorMissingSource")); return; } // Get document to move TreeNode node = tree.SelectSingleNode(nodeId); // Check the permissions for document if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed) { switch (action) { case "moveup": node = tree.MoveNodeUp(nodeId); break; case "movedown": node = tree.MoveNodeDown(nodeId); break; case "movetop": node = tree.SelectSingleNode(nodeId); tree.SetNodeOrder(nodeId, DocumentOrderEnum.First); break; case "movebottom": node = tree.SelectSingleNode(nodeId); tree.SetNodeOrder(nodeId, DocumentOrderEnum.Last); break; } if (node != null) { // Log the synchronization tasks for the entire tree level if (SettingsKeyProvider.GetBoolValue(siteName + ".CMSStagingLogChanges")) { // Log the synchronization tasks for the entire tree level DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, node.NodeAliasPath, tree); } // Select the document in the tree documentName = node.DocumentName; treeContent.ExpandNodeID = node.NodeParentID; treeContent.NodeID = node.NodeID; AddScript("currentNodeId = " + node.NodeID + ";\n"); } else { AddAlert(GetString("ContentRequest.MoveFailed")); } } else { // Select the document in the tree treeContent.NodeID = nodeId; AddAlert(GetString("ContentRequest.MoveDenied")); } } catch (Exception ex) { log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "MOVE", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri()); AddAlert(GetString("ContentRequest.MoveFailed") + " : " + ex.Message); } break; case "setculture": // Set the preferred culture code try { // Set the culture code string language = ValidationHelper.GetString(Param2, ""); if (!string.IsNullOrEmpty(language)) { CMSContext.PreferredCultureCode = language; } // Refresh the document if (nodeId > 0) { treeContent.NodeID = nodeId; AddScript("SelectNode(" + nodeId + "); \n"); } } catch (Exception ex) { log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "SETCULTURE", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri()); AddAlert(GetString("ContentRequest.ErrorChangeLanguage")); } break; // Sorting case "sortalphaasc": case "sortalphadesc": case "sortdateasc": case "sortdatedesc": // Set the preferred culture code try { // Get document to sort TreeNode node = tree.SelectSingleNode(nodeId); // Check the permissions for document if ((currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed) && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) == AuthorizationResultEnum.Allowed)) { switch (action) { case "sortalphaasc": tree.OrderNodesAlphabetically(nodeId, true); break; case "sortalphadesc": tree.OrderNodesAlphabetically(nodeId, false); break; case "sortdateasc": tree.OrderNodesByDate(nodeId, true); break; case "sortdatedesc": tree.OrderNodesByDate(nodeId, false); break; } // Log the synchronization tasks for the entire tree level if (SettingsKeyProvider.GetBoolValue(siteName + ".CMSStagingLogChanges")) { // Log the synchronization tasks for the entire tree level string fakeAlias = node.NodeAliasPath.TrimEnd('/') + "/child"; DocumentSynchronizationHelper.LogDocumentChangeOrder(siteName, fakeAlias, tree); } } else { AddAlert(GetString("ContentRequest.SortDenied")); } // Refresh the tree if (nodeId > 0) { treeContent.ExpandNodeID = nodeId; treeContent.NodeID = nodeId; AddScript("SelectNode(" + nodeId + "); \n"); } } catch (Exception ex) { log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "SORT", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri()); AddAlert(GetString("ContentRequest.ErrorSort")); } break; } // Maintain scrollbar position string script = @"var elm = jQuery('#handle_" + nodeId + @"'); var pnl = jQuery('#" + pnlTreeArea.ClientID + @"'); var origScroll = " + ScrollPosition + @"; var elmOff = elm.offset(); var elmPos = (elmOff == null) ? 0 : elmOff.top; var scroll = ((elmPos < origScroll) || (elmPos > (origScroll + pnl.height()))); pnl.scrollTop(origScroll); if(scroll){pnl.animate({ scrollTop: elmPos - 20 }, 300);};"; ScriptHelper.RegisterStartupScript(Page, typeof(string), "MaintainScrollbar", script, true); }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { gridDocuments.StopProcessing = ctrlMassActions.StopProcessing = StopProcessing; if (StopProcessing) { return; } InitializeFilterForm(); InitializeMassActionsControl(); if (NodeID <= 0) { return; } checkPermissions = Tree.CheckDocumentUIPermissions(currentSiteName); if (Node != null) { if (currentUserInfo.IsAuthorizedPerDocument(Node, NodePermissionsEnum.ExploreTree) != AuthorizationResultEnum.Allowed) { CMSPage.RedirectToAccessDenied("CMS.Content", "exploretree"); } aliasPath = Node.NodeAliasPath; } ScriptHelper.RegisterLoader(Page); ScriptHelper.RegisterDialogScript(Page); ScriptHelper.RegisterJQuery(Page); // Prepare JavaScript for actions StringBuilder actionScript = new StringBuilder(); actionScript.Append( @" function MoveNode(action, nodeId){ document.getElementById('", hdnMoveId.ClientID, @"').value = action + ';' + nodeId ; ", Page.ClientScript.GetPostBackEventReference(this, "move"), @" }"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "actionScript", ScriptHelper.GetScript(actionScript.ToString())); // Setup the grid gridDocuments.OrderBy = OrderBy; gridDocuments.OnExternalDataBound += gridDocuments_OnExternalDataBound; gridDocuments.OnDataReload += gridDocuments_OnDataReload; gridDocuments.GridView.RowDataBound += GridView_RowDataBound; gridDocuments.GridView.RowCreated += GridView_RowCreated; gridDocuments.ShowActionsMenu = true; // Initialize columns string columns = @"DocumentGUID, DocumentName, NodeParentID, NodeLevel, NodeOrder, NodeName, NodeAlias, NodeHasChildren, ClassDisplayName, DocumentModifiedWhen, DocumentLastVersionNumber, DocumentIsArchived, DocumentCheckedOutByUserID, DocumentPublishedVersionHistoryID, DocumentWorkflowStepID, DocumentCheckedOutVersionHistoryID, DocumentPublishFrom, NodeAliasPath, DocumentIsWaitingForTranslation"; if (checkPermissions) { columns = SqlHelper.MergeColumns(columns, DocumentColumnLists.SECURITYCHECK_REQUIRED_COLUMNS); } columns = SqlHelper.MergeColumns(columns, DocumentColumnLists.GETPUBLISHED_REQUIRED_COLUMNS); gridDocuments.Columns = SqlHelper.MergeColumns(columns, AdditionalColumns); // Store the refresh node id. It will be used for refreshing the dialog after dialog actions are performed (move, delete...) StringBuilder refreshScripts = new StringBuilder(); refreshScripts.Append(@" function RefreshTree() { if((parent != null) && (parent.RefreshTree != null)) { ", (!RequiresDialog) ? ("parent.RefreshTree(" + NodeID + @"," + NodeID + ");") : ControlsHelper.GetPostBackEventReference(this, "refresh", false, false), @" } } function ClearSelection() { ", gridDocuments.GetClearSelectionScript(), @" } function RefreshGrid() { ClearSelection(); RefreshTree(); ", gridDocuments.GetReloadScript(), @" }"); // Register refresh scripts string refreshScript = ScriptHelper.GetScript(refreshScripts.ToString()); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "refreshListing", refreshScript); // Get all possible columns to retrieve gridDocuments.AllColumns = SqlHelper.JoinColumnList(ObjectTypeManager.GetColumnNames(PredefinedObjectType.NODE, PredefinedObjectType.DOCUMENTLOCALIZATION)); }
/// <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) { return(currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Destroy) == AuthorizationResultEnum.Allowed); }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { editForm.StopProcessing = true; editForm.Visible = false; } else { pnlEdit.Visible = false; CurrentUserInfo currentUser = CMSContext.CurrentUser; // Get the document TreeNode node = TreeHelper.GetDocument(SiteName, CMSContext.ResolveCurrentPath(Path), CultureCode, false, null, false, CheckPermissions, currentUser); if (node != null) { bool authorized = false; // Check user group switch (AllowUsers) { case UserContributionAllowUserEnum.All: authorized = true; break; case UserContributionAllowUserEnum.Authenticated: authorized = currentUser.IsAuthenticated(); break; case UserContributionAllowUserEnum.DocumentOwner: authorized = (node.NodeOwner == currentUser.UserID); break; } bool authorizedDelete = authorized; // Check control access permissions if (authorized && CheckPermissions) { // Node owner has always permissions if (node.NodeOwner != currentUser.UserID) { authorized &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Modify }) == AuthorizationResultEnum.Allowed); authorizedDelete &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Delete }) == AuthorizationResultEnum.Allowed); } } else { authorized |= currentUser.IsGlobalAdministrator; authorizedDelete |= currentUser.IsGlobalAdministrator; } // Do not allow edit for virtual user if (currentUser.IsVirtual) { authorized = false; authorizedDelete = false; } // Display form if authorized if (authorized || authorizedDelete) { // Set visibility of the edit and delete buttons pnlEdit.Visible = true; btnEdit.Visible = btnEdit.Visible && authorized; btnDelete.Visible = btnDelete.Visible && AllowDelete && authorizedDelete; editForm.LogActivity = LogActivity; editForm.ComponentName = WebPartID; if (pnlForm.Visible) { editForm.StopProcessing = false; editForm.AllowDelete = AllowDelete; editForm.CheckPermissions = CheckPermissions; editForm.NodeID = node.NodeID; editForm.SiteName = SiteName; editForm.CultureCode = CultureCode; editForm.AlternativeFormName = AlternativeFormName; editForm.ValidationErrorMessage = ValidationErrorMessage; editForm.CMSForm.IsLiveSite = true; // Reload data editForm.ReloadData(false); } editForm.OnAfterApprove += editForm_OnAfterChange; editForm.OnAfterReject += editForm_OnAfterChange; editForm.OnAfterDelete += editForm_OnAfterChange; editForm.CMSForm.OnAfterSave += CMSForm_OnAfterSave; } } } }
/// <summary> /// Saves widget properties. /// </summary> public bool Save() { if (VariantID > 0) { // Check MVT/CP security if (!CheckPermissions("Manage")) { DisplayError("general.modifynotallowed"); return(false); } } // Save the data if ((pi != null) && (templateInstance != null) && SaveForm(formCustom)) { // Check manage permission for non-livesite version if ((PortalContext.ViewMode != ViewModeEnum.LiveSite) && (PortalContext.ViewMode != ViewModeEnum.DashboardWidgets)) { CurrentUserInfo cui = MembershipContext.AuthenticatedUser; // Check document permissions if (cui.IsAuthorizedPerDocument(pi.NodeID, pi.ClassName, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Allowed) { return(false); } // Check design permissions if ((PortalContext.ViewMode == ViewModeEnum.Design) && !(cui.IsGlobalAdministrator || (cui.IsAuthorizedPerResource("cms.design", "Design") && cui.IsAuthorizedPerUIElement("CMS.Content", "Design.WebPartProperties")))) { RedirectToAccessDenied("CMS.Design", "Design"); } } PageTemplateInfo pti = templateInstance.ParentPageTemplate; if ((PortalContext.ViewMode == ViewModeEnum.Design) && SynchronizationHelper.IsCheckedOutByOtherUser(pti)) { string userName = null; UserInfo ui = UserInfoProvider.GetUserInfo(pti.Generalized.IsCheckedOutByUserID); if (ui != null) { userName = HTMLHelper.HTMLEncode(ui.GetFormattedUserName(IsLiveSite)); } DisplayError(string.Format(GetString("ObjectEditMenu.CheckedOutByAnotherUser"), pti.ObjectType, pti.DisplayName, userName)); return(false); } // Get the zone zone = templateInstance.EnsureZone(ZoneId); if (zone != null) { zone.WidgetZoneType = zoneType; // Add new widget if (IsNewWidget) { bool isLayoutZone = (QueryHelper.GetBoolean("layoutzone", false)); int widgetID = ValidationHelper.GetInteger(WidgetId, 0); // Create new widget instance widgetInstance = PortalHelper.AddNewWidget(widgetID, ZoneId, ZoneType, isLayoutZone, templateInstance, null); } widgetInstance.XMLVersion = 1; if (IsNewVariant) { widgetInstance = widgetInstance.Clone(); if (pi.DocumentTemplateInstance.WebPartZones.Count == 0) { // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree); // Extract and set the document web parts node.SetValue("DocumentWebParts", templateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, tree); } } bool isLayoutWidget = ((wpi != null) && ((WebPartTypeEnum)wpi.WebPartType == WebPartTypeEnum.Layout)); // Get basicform's datarow and update widget SaveFormToWidget(formCustom, templateInstance, isLayoutWidget); // Ensure unique id for new widget variant or layout widget if (IsNewVariant || (isLayoutWidget && IsNewWidget)) { string controlId = GetUniqueWidgetId(wi.WidgetName); if (!string.IsNullOrEmpty(controlId)) { widgetInstance.ControlID = controlId; } else { DisplayError("Unable to generate unique widget id."); return(false); } } // Allow set dashboard in design mode if ((zoneType == WidgetZoneTypeEnum.Dashboard) && String.IsNullOrEmpty(PortalContext.DashboardName)) { PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes CMSPortalManager.SaveTemplateChanges(pi, templateInstance, zoneType, PortalContext.ViewMode, tree); } else if ((PortalContext.ViewMode == ViewModeEnum.Edit) && (zoneType == WidgetZoneTypeEnum.Editor)) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; PortalHelper.SaveWebPartVariantChanges(widgetInstance, VariantID, 0, VariantMode, properties); // Clear the document template templateInstance.ParentPageTemplate.ParentPageInfo.DocumentTemplateInstance = null; // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Clear the cached web part if (InstanceGUID != null) { CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe()); } return(true); } return(false); }
public void RaisePostBackEvent(string eventArgument) { CurrentUserInfo currentUser = CMSContext.CurrentUser; // Current Node ID int nodeId = ValidationHelper.GetInteger(Param1, 0); TreeProvider tree = new TreeProvider(currentUser); EventLogProvider log = new EventLogProvider(); string documentName = ""; string action = Action.ToLower(); // Process the request switch (action) { case "moveup": case "movedown": // Move the document up (document order) try { if (nodeId == 0) { AddAlert(GetString("ContentRequest.ErrorMissingSource")); return; } // Get document to move TreeNode node = tree.SelectSingleNode(nodeId); // Check the permissions for document if (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed) { switch (action) { case "moveup": node = tree.MoveNodeUp(nodeId); break; case "movedown": node = tree.MoveNodeDown(nodeId); break; } string siteName = CMSContext.CurrentSiteName; if (SettingsKeyProvider.GetBoolValue(siteName + ".CMSStagingLogChanges")) { // Load all nodes under parent node if (node != null) { string parentPath = TreePathUtils.GetParentPath(node.NodeAliasPath); DataSet ds = tree.SelectNodes(siteName, parentPath.TrimEnd('/') + "/%", TreeProvider.ALL_CULTURES, true, null, null, null, 1); // Check if data source is not empty if (!DataHelper.DataSourceIsEmpty(ds)) { // Go through all nodes foreach (DataRow dr in ds.Tables[0].Rows) { // Update child nodes int logNodeId = ValidationHelper.GetInteger(dr["NodeID"], 0); string culture = ValidationHelper.GetString(dr["DocumentCulture"], ""); string className = ValidationHelper.GetString(dr["ClassName"], ""); TreeNode tn = tree.SelectSingleNode(logNodeId, culture, className); DocumentSynchronizationHelper.LogDocumentChange(tn, TaskTypeEnum.UpdateDocument, tree); } } } } // Move the node if (node != null) { documentName = node.DocumentName; treeContent.ExpandNodeID = node.NodeParentID; treeContent.NodeID = node.NodeID; } else { AddAlert(GetString("ContentRequest.MoveFailed")); } } else { AddAlert(GetString("ContentRequest.MoveDenied")); } } catch (Exception ex) { log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "MOVE", currentUser.UserID, currentUser.UserName, nodeId, documentName, HTTPHelper.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri()); AddAlert(GetString("ContentRequest.MoveFailed") + " : " + ex.Message); } break; case "delete": // Delete the document try { if (nodeId == 0) { AddAlert(GetString("DefineSiteStructure.ErrorMissingSource")); return; } // Get the node TreeNode node = tree.SelectSingleNode(nodeId); // Delete the node if (node != null) { treeContent.NodeID = node.NodeParentID; node.Delete(); // Delete search index for given node if (SearchIndexInfoProvider.SearchEnabled) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Delete, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } if (node.NodeAliasPath == "/") { // Refresh root document treeContent.NodeID = node.NodeID; AddScript("SelectNode(" + node.NodeID + "); \n"); } else { AddScript("SelectNode(" + node.NodeParentID + "); \n"); } } } catch (Exception ex) { AddAlert(GetString("DefineSiteStructure.DeleteFailed") + " : " + ex.Message); } break; } }
/// <summary> /// Initializes common properties used for processing image. /// </summary> void baseImageEditor_InitializeProperties() { CurrentUserInfo currentUser = CMSContext.CurrentUser; // Process attachment switch (baseImageEditor.ImageType) { default: case ImageHelper.ImageTypeEnum.Attachment: { baseImageEditor.Tree = new TreeProvider(currentUser); // If using workflow then get versioned attachment if (VersionHistoryID != 0) { // Get the versioned attachment AttachmentHistoryInfo attachmentVersion = VersionManager.GetAttachmentVersion(VersionHistoryID, attachmentGuid); if (attachmentVersion == null) { ai = null; } else { // Create new attachment object ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass); ai.AttachmentID = attachmentVersion.AttachmentHistoryID; } } // else get file without binary data else { ai = AttachmentManager.GetAttachmentInfoWithoutBinary(attachmentGuid, CurrentSiteName); } // If file is not null and current user is set if (ai != null) { TreeNode node = null; if (ai.AttachmentDocumentID > 0) { node = baseImageEditor.Tree.SelectSingleDocument(ai.AttachmentDocumentID); } else { // Get parent node ID in case attachment is edited for document not created yet int parentNodeId = QueryHelper.GetInteger("parentId", 0); node = baseImageEditor.Tree.SelectSingleNode(parentNodeId); } // If current user has appropriate permissions then set image - check hash fro live site otherwise check node permissions if ((currentUser != null) && (node != null) && ((IsLiveSite && QueryHelper.ValidateHash("hash")) || (!IsLiveSite && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)))) { // Ensure attachment binary data if (VersionHistoryID == 0) { ai.AttachmentBinary = AttachmentManager.GetFile(ai, CurrentSiteName); } if (ai.AttachmentBinary != null) { baseImageEditor.ImgHelper = new ImageHelper(ai.AttachmentBinary); } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.filemodify"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } break; // Process physical file case ImageHelper.ImageTypeEnum.PhysicalFile: { if (!String.IsNullOrEmpty(filePath)) { if ((currentUser != null) && currentUser.IsGlobalAdministrator) { try { // Load the file from disk string physicalPath = Server.MapPath(filePath); byte[] data = File.ReadAllBytes(physicalPath); baseImageEditor.ImgHelper = new ImageHelper(data); } catch { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: { // Get metafile mf = MetaFileInfoProvider.GetMetaFileInfoWithoutBinary(metafileGuid, CurrentSiteName, true); // If file is not null and current user is global administrator then set image if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, this.CurrentSiteName, CMSContext.CurrentUser)) { // Ensure metafile binary data mf.MetaFileBinary = MetaFileInfoProvider.GetFile(mf, CurrentSiteName); if (mf.MetaFileBinary != null) { baseImageEditor.ImgHelper = new ImageHelper(mf.MetaFileBinary); } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } break; } // Check that image is in supported formats if ((!baseImageEditor.LoadingFailed) && (baseImageEditor.ImgHelper.ImageFormatToString() == null)) { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.format"; } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { pi = CMSContext.CurrentPageInfo; if (pi != null) { CMSPagePlaceholder parentPlaceHolder = PortalHelper.FindParentPlaceholder(this); // Nothing to render, nothing to do if ((!DisplayAddButton && !DisplayResetButton) || ((parentPlaceHolder != null) && (parentPlaceHolder.UsingDefaultPage))) { Visible = false; return; } CurrentUserInfo currentUser = CMSContext.CurrentUser; zoneType = WidgetZoneTypeCode.ToEnum(WidgetZoneType); // Check security if (((zoneType == WidgetZoneTypeEnum.Group) && !currentUser.IsGroupAdministrator(pi.NodeGroupID)) || ((zoneType == WidgetZoneTypeEnum.User || zoneType == WidgetZoneTypeEnum.Dashboard) && !currentUser.IsAuthenticated())) { Visible = false; resetAllowed = false; return; } // Displaying - Editor zone only in edit mode, User/Group zone only in Live site/Preview mode if (((zoneType == WidgetZoneTypeEnum.Editor) && ((CMSContext.ViewMode != ViewModeEnum.Edit) && (CMSContext.ViewMode != ViewModeEnum.EditLive))) || (((zoneType == WidgetZoneTypeEnum.User) || (zoneType == WidgetZoneTypeEnum.Group)) && ((CMSContext.ViewMode != ViewModeEnum.LiveSite) && (CMSContext.ViewMode != ViewModeEnum.Preview))) || ((zoneType == WidgetZoneTypeEnum.Dashboard) && ((CMSContext.ViewMode != ViewModeEnum.DashboardWidgets) || (String.IsNullOrEmpty(PortalContext.DashboardName))))) { Visible = false; resetAllowed = false; return; } // Get current document TreeNode currentNode = DocumentHelper.GetDocument(pi.DocumentID, TreeProvider); if (((zoneType == WidgetZoneTypeEnum.Editor) && (!currentUser.IsEditor || (currentUser.IsAuthorizedPerDocument(currentNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)))) { Visible = false; resetAllowed = false; return; } // If use checkin checkout enabled, check if document is checkout by current user if (zoneType == WidgetZoneTypeEnum.Editor) { if (currentNode != null) { WorkflowManager wm = WorkflowManager.GetInstance(TreeProvider); // Get workflow info WorkflowInfo wi = wm.GetNodeWorkflow(currentNode); // Check if node is under workflow and if use checkin checkout enabled if ((wi != null) && (wi.UseCheckInCheckOut(CMSContext.CurrentSiteName))) { int checkedOutBy = currentNode.DocumentCheckedOutByUserID; // Check if document is checkout by current user if (checkedOutBy != CMSContext.CurrentUser.UserID) { Visible = false; resetAllowed = false; return; } } } } // Find widget zone PageTemplateInfo pti = pi.UsedPageTemplateInfo; // ZodeID specified directly if (!String.IsNullOrEmpty(WidgetZoneID)) { zoneInstance = pti.GetZone(WidgetZoneID); } // Zone not find or specified zone is not of correct type if ((zoneInstance != null) && (zoneInstance.WidgetZoneType != zoneType)) { zoneInstance = null; } // For delete all variants all zones are necessary if (parentPlaceHolder != null) { var zones = parentPlaceHolder.WebPartZones; if (zones != null) { foreach (CMSWebPartZone zone in zones) { if ((zone.ZoneInstance != null) && (zone.ZoneInstance.WidgetZoneType == zoneType)) { zoneInstances.Add(zone.ZoneInstance); if (zoneInstance == null) { zoneInstance = zone.ZoneInstance; } } } } } // No suitable zones on the page, nothing to do if (zoneInstance == null) { Visible = false; resetAllowed = false; return; } // Adding is enabled if (DisplayAddButton) { pnlAdd.Visible = true; lnkAddWidget.Visible = true; lnkAddWidget.Text = HTMLHelper.HTMLEncode(DataHelper.GetNotEmpty(AddButtonText, GetString("widgets.addwidget"))); int templateId = 0; if (pi.UsedPageTemplateInfo != null) { templateId = pi.UsedPageTemplateInfo.PageTemplateId; } addScript = "NewWidget('" + HttpUtility.UrlEncode(zoneInstance.ZoneID) + "', '" + HttpUtility.UrlEncode(pi.NodeAliasPath) + "', '" + templateId + "'); return false;"; lnkAddWidget.Attributes.Add("onclick", addScript); } // Reset is enabled if (DisplayResetButton) { pnlReset.Visible = true; btnReset.Text = HTMLHelper.HTMLEncode(DataHelper.GetNotEmpty(ResetButtonText, GetString("widgets.resettodefault"))); btnReset.Click += new EventHandler(btnReset_Click); // Add confirmation if required if (ResetConfirmationRequired) { btnReset.Attributes.Add("onclick", "if (!confirm('" + GetString("widgets.resetzoneconfirmtext") + "')) return false;"); } } // Set the panel css clas with dependence on actions zone type switch (zoneType) { // Editor case WidgetZoneTypeEnum.Editor: pnlWidgetActions.CssClass = "EditorWidgetActions"; break; // User case WidgetZoneTypeEnum.User: pnlWidgetActions.CssClass = "UserWidgetActions"; break; // Group case WidgetZoneTypeEnum.Group: pnlWidgetActions.CssClass = "GroupWidgetActions"; break; // Dashboard case WidgetZoneTypeEnum.Dashboard: { if (pnlContextHelp.Controls.Count == 0) { // Load help control dynamically (due to faster start compilation) var help = this.LoadUserControl("~/CMSAdminControls/UI/PageElements/Help.ascx") as HelpControl; help.TopicName = "dashboard"; } } break; } } } }
/// <summary> /// Deletes document(s). /// </summary> private void Delete(object parameter) { if (parameter == null || nodeIds.Count < 1) { return; } if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Blogs, ObjectActionEnum.Edit)) { AddError(ResHelper.GetString("cmsdesk.blogdeletelicenselimitations", currentCulture)); return; } if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Edit)) { AddError(ResHelper.GetString("cmsdesk.documentdeletelicenselimitations", currentCulture)); return; } int refreshId = 0; TreeProvider tree = new TreeProvider(currentUser); tree.AllowAsyncActions = false; string[] parameters = ((string)parameter).Split(';'); bool allLevelsSelected = ValidationHelper.GetBoolean(parameters[3], false); try { string siteName = parameters[1]; bool isMultipleDelete = ValidationHelper.GetBoolean(parameters[2], false); // Prepare the where condition string where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true); string columns = SqlHelper.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture, NodeParentID"); bool combineWithDefaultCulture = false; string cultureCode = parameters[0]; switch (parameters[4]) { // Normalne page deletion case "documentoptions": combineWithDefaultCulture = chkAllCultures.Checked; cultureCode = combineWithDefaultCulture ? TreeProvider.ALL_CULTURES : parameters[0]; break; // Root page deletion case "rootoptions": cultureCode = rblRoot.SelectedValue == "allpages" ? TreeProvider.ALL_CULTURES : parameters[0]; tree.DeleteChildNodes = rblRoot.SelectedValue != "current"; where = rblRoot.SelectedValue == "allculturepages" ? String.Empty : where; break; } // Begin log AddLog(ResHelper.GetString("ContentDelete.DeletingDocuments", currentCulture)); string orderBy = "NodeAliasPath DESC"; if (cultureCode == TreeProvider.ALL_CULTURES) { // Default culture has to be selected on last position string defaultCulture = CultureHelper.GetDefaultCultureCode(siteName); orderBy += ", CASE WHEN DocumentCulture = '" + SqlHelper.EscapeQuotes(defaultCulture) + "' THEN 1 ELSE 0 END"; } // Get the documents DataSet ds = tree.SelectNodes(siteName, "/%", cultureCode, combineWithDefaultCulture, null, where, orderBy, TreeProvider.ALL_LEVELS, false, 0, columns); if (!DataHelper.DataSourceIsEmpty(ds)) { string altPath = Convert.ToString(selAltPath.Value); TreeNode altNode = null; if (chkUseDeletedPath.Checked && !String.IsNullOrEmpty(altPath)) { NodeSelectionParameters nsp = new NodeSelectionParameters(); nsp.AliasPath = altPath; nsp.CultureCode = TreeProvider.ALL_CULTURES; nsp.ClassNames = TreeProvider.ALL_CLASSNAMES; nsp.CombineWithDefaultCulture = true; nsp.SiteName = siteName; nsp.MaxRelativeLevel = TreeProvider.ALL_LEVELS; nsp.TopN = 1; altNode = DocumentHelper.GetDocument(nsp, tree); // Check whether user is authorized to use alternating document if (altNode != null) { if (currentUser.IsAuthorizedPerDocument(altNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { throw new Exception(GetString("contentdelete.notallowedalternating")); } } } // Delete the documents foreach (DataRow nodeRow in ds.Tables[0].Rows) { // Get the current document string className = nodeRow["ClassName"].ToString(); string aliasPath = nodeRow["NodeAliasPath"].ToString(); string docCulture = nodeRow["DocumentCulture"].ToString(); refreshId = ValidationHelper.GetInteger(nodeRow["NodeParentID"], 0); if (refreshId == 0) { refreshId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0); } TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, tree); if (node == null) { AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath))); continue; } // Ensure current parent ID int parentId = node.NodeParentID; // Check if bound SKU can be deleted (if any) bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node); // Check delete permissions if (IsUserAuthorizedToDeleteDocument(node) && (CanDestroy(node) || !chkDestroy.Checked) && authorizedToDeleteSKU) { // Delete the document if (parentId <= 0) { parentId = node.NodeID; } // Prepare action for affected products DeleteProductActionEnum deleteSKUsAction = DeleteProductActionEnum.NoAction; switch (rblSKUAction.SelectedValue) { case "delete": deleteSKUsAction = DeleteProductActionEnum.DeleteSKU; break; case "disable": deleteSKUsAction = DeleteProductActionEnum.DisableSKU; break; case "deleteordisable": deleteSKUsAction = DeleteProductActionEnum.DeleteOrDisableSKU; break; } // Prepare settings for delete DeleteDocumentSettings settings = new DeleteDocumentSettings(node, chkAllCultures.Checked, chkDestroy.Checked, tree) { DeleteProductAction = deleteSKUsAction }; // Add additional settings if alternating document is specified if (altNode != null) { settings.AlternatingDocument = altNode; settings.AlternatingDocumentCopyAllPaths = chkAltAliases.Checked; settings.AlternatingDocumentMaxLevel = chkAltSubNodes.Checked ? -1 : node.NodeLevel; } // Delete document refreshId = DocumentHelper.DeleteDocument(settings) || isMultipleDelete ? parentId : node.NodeID; } // Access denied - not authorized to delete the document else { AddError(string.Format(ResHelper.GetString("cmsdesk.notauthorizedtodeletedocument", currentCulture), HTMLHelper.HTMLEncode(node.NodeAliasPath))); } } } else { AddError(ResHelper.GetString("DeleteDocument.CultureNotExists", currentCulture)); } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled ShowError(ResHelper.GetString("DeleteDocument.DeletionCanceled", currentCulture)); } else { // Log error LogExceptionToEventLog(ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ex); } finally { if (string.IsNullOrEmpty(CurrentError)) { // Overwrite refreshId variable if sub-levels are visible if (allLevelsSelected && Parameters.ContainsKey("refreshnodeid")) { refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0); } // Refresh tree or page (on-site editing) if (!RequiresDialog) { ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");"; } else { // Go to the root by default string url = URLHelper.ResolveUrl("~/"); // Update the refresh node id when set in the parent dialog if (Parameters != null) { int refreshNodeId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0); if (refreshNodeId > 0) { refreshId = refreshNodeId; } } // Try go to the parent document if (refreshId > 0) { TreeProvider tp = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode tn = DocumentHelper.GetDocument(refreshId, TreeProvider.ALL_CULTURES, tp); if (tn != null) { url = URLHelper.ResolveUrl(DocumentURLProvider.GetUrl(tn.NodeAliasPath)); } } ctlAsync.Parameter = "window.refreshPageOnClose = true; window.reloadPageUrl = " + ScriptHelper.GetString(url) + "; CloseDialog();"; } } else { ctlAsync.Parameter = "RefreshTree(null, null);"; } } }
/// <summary> /// Page load. /// </summary> protected void Page_Load(object sender, EventArgs e) { CurrentUserInfo currentUserInfo = CMSContext.CurrentUser; string[,] actions = new string[1, 6]; if (!RequiresDialog) { ScriptHelper.RegisterScriptFile(this, @"~/CMSModules/Content/CMSDesk/View/Listing.js"); } if (docList.NodeID > 0) { TreeNode node = docList.Node; // Set edited document EditedDocument = node; if (node != null) { if (currentUserInfo.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) != AuthorizationResultEnum.Allowed) { RedirectToCMSDeskAccessDenied("CMS.Content", "exploretree"); } if (RequiresDialog) { ScriptHelper.RegisterScriptFile(this, @"~/CMSModules/Content/CMSDesk/View/ListingDialog.js"); // Set JavaScript for new button actions[0, 3] = "javascript:AddItem(" + node.NodeID + ");"; actions[0, 0] = HeaderActions.TYPE_HYPERLINK; actions[0, 1] = GetString("content.newtitle"); actions[0, 5] = GetImageUrl("CMSModules/CMS_Content/Listing/16/New.png"); CurrentMaster.Title.HelpTopicName = "ose_documents"; // Ensure breadcrumbs EnsureBreadcrumbs(node); } else { // Setup the link to the parent document if ((node.NodeClassName.ToLowerCSafe() != "cms.root") && (currentUserInfo.UserStartingAliasPath.ToLowerCSafe() != node.NodeAliasPath.ToLowerCSafe())) { actions[0, 0] = HeaderActions.TYPE_HYPERLINK; actions[0, 1] = GetString("Listing.ParentDirectory"); actions[0, 5] = GetImageUrl("CMSModules/CMS_Content/Listing/parent.png"); actions[0, 3] = "javascript:SelectItem(" + node.NodeParentID + ");"; } else { CurrentMaster.HeaderActions.Visible = false; CurrentMaster.PanelBody.FindControl("pnlActions").Visible = false; } } // Define target window for modal dialogs (used for mobile Android browser which cannot open more than one modal dialog window at a time). // If set: The target window will be used for opening the new dialog in the following way: targetWindow.location.href = '...new dialog url...'; // If not set: New modal dialog window will be opened string actionTargetWindow = "var targetWindow = " + (CMSContext.CurrentDevice.IsMobile ? "this" : "null"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "listingScript", actionTargetWindow, true); } } CurrentMaster.HeaderActions.Actions = actions; }