/// <summary> /// Removes selected operator from the ACL. /// </summary> protected void btnRemoveOperator_Click(Object sender, EventArgs e) { // Check permission CheckPermissions(true); if (lstOperators.SelectedItem == null) { return; } string operatorName = lstOperators.SelectedItem.Text; string message; string operatorID = lstOperators.SelectedValue; if (operatorID.StartsWithCSafe("U")) { int userId = int.Parse(operatorID.Substring(1)); UserInfo ui = UserInfoProvider.GetUserInfo(userId); AclItemInfoProvider.RemoveUser(Node.NodeID, ui); message = "security.documentuserpermissionremoved"; } else { RoleInfo ri = RoleInfoProvider.GetRoleInfo(int.Parse(operatorID.Substring(1))); AclItemInfoProvider.RemoveRole(Node.NodeID, ri); message = "security.documentrolepermissionremoved"; } // Log synchronization task and flush cache DocumentSynchronizationHelper.LogDocumentChange(TreeHelper.SelectSingleNode(Node.NodeID), TaskTypeEnum.UpdateDocument, Node.TreeProvider); CacheHelper.TouchKeys(TreeProvider.GetDependencyCacheKeys(Node, Node.NodeSiteName)); // Insert information about this event to eventlog. if (Tree.LogEvents) { EventLogProvider.LogEvent(EventType.INFORMATION, "Content", "DOCPERMISSIONSMODIFIED", string.Format(ResHelper.GetAPIString(message, "Operator '{0}' has been removed from the document permissions."), operatorName), eventUrl, Tree.UserInfo.UserID, Tree.UserInfo.UserName, Node.NodeID, DocumentName, ipAddress, Node.NodeSiteID); } dsAclItems = null; LoadOperators(true); CheckButtonsActiveState(); }
private void PerformAttachmentAction(string actionName, Guid attachmentGuid, Action action) { // Ensure automatic check-in/ check-out VersionManager vm = null; bool checkin = false; // Check out the document if (AutoCheck) { vm = VersionManager.GetInstance(TreeProvider); var step = vm.CheckOut(Node, Node.IsPublished, true); // Do not check-in document if not under a workflow anymore checkin = (step != null); } // Perform action if (action != null) { action(); } // Check in the document if (AutoCheck) { if ((vm != null) && checkin && (Node.DocumentWorkflowStepID != 0)) { vm.CheckIn(Node, null, null); } // Ensure full page refresh ScriptHelper.RegisterStartupScript(Page, typeof(Page), actionName + "Refresh", ScriptHelper.GetScript(String.Format("InitRefresh_{0}('', true, false, '{1}');", ClientID, actionName))); // Clear document manager properties DocumentManager.ClearProperties(); } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } }
/// <summary> /// Handles the OnAfterSave event of the EditForm control. /// </summary> private void EditForm_OnAfterSave(object sender, EventArgs e) { if (UIFormControl.EditedObject != null) { // Log widget variant synchronization MVTVariantInfo variantInfo = (MVTVariantInfo)UIFormControl.EditedObject; // Clear cache CacheHelper.TouchKey("om.mvtvariant|bytemplateid|" + variantInfo.MVTVariantPageTemplateID); if (variantInfo.MVTVariantDocumentID > 0) { // Log synchronization TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode node = tree.SelectSingleDocument(variantInfo.MVTVariantDocumentID); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } }
/// <summary> /// Handles the OnAfterSave event of the EditForm control. /// </summary> protected void EditForm_OnAfterSave(object sender, EventArgs e) { if (UIFormControl.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(CMSContext.CurrentUser); TreeNode node = tree.SelectSingleDocument(variantInfo.VariantDocumentID); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } }
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); } } } }
protected void chkMarkDocAsProd_CheckedChanged(object sender, EventArgs e) { if (!IsAuthorizedToModifyDocument()) { RedirectToAccessDenied("CMS.Content", "Modify"); } this.Node.NodeSKUID = 0; this.Node.Update(); // Update search index for node if ((this.Node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, this.Node.GetSearchID()); } // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(this.Node, TaskTypeEnum.UpdateDocument, this.Node.TreeProvider); ScriptHelper.RegisterStartupScript(Page, typeof(string), "FirstTabSelection", ScriptHelper.GetScript(" parent.window.location = '" + URLHelper.ResolveUrl("~/CMSModules/Ecommerce/Pages/Content/Product/Product_Selection.aspx") + "?nodeid=" + this.NodeID + "&productid=" + productId + "' ")); }
protected void lnkBreakWithCopy_Click(Object sender, EventArgs e) { // Check permission CheckModifyPermission(true); // Break permission inheritance and copy parent permissions AclInfoProvider.BreakInheritance(Node, true); // Log staging task TaskParameters taskParam = new TaskParameters(); taskParam.SetParameter("copyPermissions", true); DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.BreakACLInheritance, Node.TreeProvider, SynchronizationInfoProvider.ENABLED_SERVERS, taskParam, Node.TreeProvider.AllowAsyncActions); // Insert information about this event to event log. if (DocumentManager.Tree.LogEvents) { var logData = new EventLogData(EventTypeEnum.Information, "Content", "DOCPERMISSIONSMODIFIED") { EventDescription = ResHelper.GetAPIString("security.documentpermissionsbreakcopy", "Inheritance of the parent page permissions have been broken. Parent page permissions have been copied."), EventUrl = currentUrl, UserID = DocumentManager.Tree.UserInfo.UserID, UserName = DocumentManager.Tree.UserInfo.UserName, NodeID = Node.NodeID, DocumentName = DocumentName, IPAddress = ipAddress, SiteID = Node.NodeSiteID }; Service.Resolve <IEventLogService>().LogEvent(logData); } lblInheritanceInfo.Text = GetString("Security.InheritsInfo.DoesNotInherit"); SwitchBackToPermissionsMode(); // Clear and reload securityElem.InvalidateAcls(); securityElem.LoadOperators(true); }
/// <summary> /// Handles UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of the action which should be performed</param> /// <param name="actionArgument">ID of the item the action should be performed with</param> protected void gridElem_OnAction(string actionName, object actionArgument) { int mvtvariantId = ValidationHelper.GetInteger(actionArgument, 0); if (mvtvariantId > 0) { switch (actionName.ToLower()) { case "delete": if (CheckPermissions("CMS.MVTest", CMSAdminControl.PERMISSION_MODIFY)) { // Get the web part instance Guid in order to clear the webpart's cache Guid webPartInstanceGuid = Guid.Empty; MVTVariantInfo vi = MVTVariantInfoProvider.GetMVTVariantInfo(mvtvariantId); // Delete the object MVTVariantInfoProvider.DeleteMVTVariantInfo(mvtvariantId); this.RaiseOnDelete(); // Log widget variant synchronization if ((vi != null) && (vi.MVTVariantDocumentID > 0)) { // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, tree); } // Clear web part variants from the cache if (vi != null) { CMSContext.CurrentDocument = null; ReloadWebPartCache(vi.MVTVariantZoneID, vi.MVTVariantInstanceGUID); } } break; } } }
protected void btnInherit_Click(object sender, EventArgs e) { int pageTemplateId = 0; if ((node != null) && (node.NodeParentID > 0)) { // Get inherited page template object currentPageTemplateId = node.GetValue("DocumentPageTemplateID"); node.SetValue("DocumentPageTemplateID", DBNull.Value); node.LoadInheritedValues(new string[] { "DocumentPageTemplateID" }, false); pageTemplateId = ValidationHelper.GetInteger(node.GetValue("DocumentPageTemplateID"), 0); node.SetValue("DocumentPageTemplateID", currentPageTemplateId); } if (pageTemplateId > 0) { // Get the page template PageTemplateInfo pt = PageTemplateInfoProvider.GetPageTemplateInfo(pageTemplateId); if (pt != null) { txtTemplate.Text = pt.DisplayName + " (inherited)"; ltlScript.Text += ScriptHelper.GetScript("pressedInherit(" + pageTemplateId + "); ShowButtons(" + pt.IsPortal.ToString().ToLower() + ", " + pt.IsReusable.ToString().ToLower() + ");"); btnSaveOnClickScript = "modalDialog('" + ResolveUrl(PORTALENGINE_UI_LAYOUTPATH + "SaveNewPageTemplate.aspx") + "?templateid=' + document.getElementById('InheritedTemplateId').value + '&siteid=" + siteid + "', 'SaveNewTemplate', 480, 360);return false;"; } } else { txtTemplate.Text = ""; ltlScript.Text += ScriptHelper.GetScript("pressedInherit(" + pageTemplateId + "); ShowButtons(false, false); "); } if (sender != null) { // Log the synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } }
private void SaveData() { if (node != null) { // Update fields node.NodeBodyElementAttributes = txtBodyCss.Text; node.NodeBodyScripts = txtBodyScripts.Value.ToString(); node.NodeDocType = txtDocType.Text; node.NodeHeadTags = txtHeadTags.Value.ToString(); // Update the node node.Update(); // Update search index if (DocumentHelper.IsSearchTaskCreationAllowed(node)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID); } // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); RegisterRefreshScript(); // Empty variable for exitwithoutchanges dialog ScriptHelper.RegisterClientScriptBlock(Page, typeof(String), "SubmitAction", "CMSContentManager.changed(false);", true); // Clear cache PageInfoCacheHelper.ClearCache(); ShowChangesSaved(); // Clear content changed flag DocumentManager.ClearContentChanged(); } }
/// <summary> /// On items selected event handling. /// </summary> private void usRoles_OnItemsSelected(object sender, EventArgs e) { // Remove old items string newValues = ValidationHelper.GetString(usRoles.Value, null); string items = DataHelper.GetNewItemsInList(newValues, CurrentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to site foreach (string item in newItems) { int roleID = ValidationHelper.GetInteger(item, 0); if (PollID > 0) { // Remove role from poll ModuleCommands.PollsRemoveRoleFromPoll(roleID, PollID); } else if (FormID > 0) { // Remove role from form BizFormRoleInfoProvider.DeleteBizFormRoleInfo(roleID, FormID); } else if (BoardID > 0) { // Check permissions if (MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.messageboards", CMSAdminControl.PERMISSION_MODIFY)) { // Remove message board from board ModuleCommands.MessageBoardRemoveRoleFromBoard(roleID, BoardID); } } else if (Node != null) { RoleInfo ri = RoleInfoProvider.GetRoleInfo(roleID); // Remove role from treenode AclItemInfoProvider.RemoveRole(NodeID, ri); } } } } // Add new items items = DataHelper.GetNewItemsInList(CurrentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to site foreach (string item in newItems) { int roleID = ValidationHelper.GetInteger(item, 0); if (PollID > 0) { // Add poll role ModuleCommands.PollsAddRoleToPoll(roleID, PollID); } else if (FormID > 0) { // Add BizForm role BizFormRoleInfoProvider.SetBizFormRoleInfo(roleID, FormID); } else if (BoardID > 0) { // Add role to the message board ModuleCommands.MessageBoardAddRoleToBoard(roleID, BoardID); } else if (Node != null) { RoleInfo ri = RoleInfoProvider.GetRoleInfo(roleID); // Add role to treenode AclItemInfoProvider.SetRolePermissions(Node, 0, 0, ri); } } } } // Log synchronization task if (Node != null) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, Node.TreeProvider); } RaiseOnChanged(); }
protected void btnOK_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(this.ctrlURL.PlainURLPath)) { lblError.Text = GetString("doc.urls.requiresurlpath"); return; } if (!usSelectCampaign.IsValid()) { lblError.Visible = true; lblError.Text = GetString("campaign.validcodename"); return; } // Get the document TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); node = tree.SelectSingleNode(nodeId, CMSContext.PreferredCultureCode); if (node != null) { // Check modify permissions if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { lblInfo.Text = string.Empty; lblError.Text = String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath); return; } DocumentAliasInfo dai = null; // Edit existing alias if (aliasId > 0) { dai = DocumentAliasInfoProvider.GetDocumentAliasInfo(aliasId); } if (dai == null) { dai = new DocumentAliasInfo(); } // Set object properties dai.AliasURLPath = ctrlURL.URLPath; dai.AliasCampaign = ValidationHelper.GetString(usSelectCampaign.Value, String.Empty).Trim(); dai.AliasExtensions = txtURLExtensions.Text.Trim(); dai.AliasCulture = ValidationHelper.GetString(cultureSelector.Value, ""); dai.AliasSiteID = CMSContext.CurrentSite.SiteID; if (nodeId > 0) { dai.AliasNodeID = nodeId; } // Insert into database DocumentAliasInfoProvider.SetDocumentAliasInfo(dai, node.NodeSiteName); // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); nodeId = dai.AliasNodeID; aliasId = dai.AliasID; string url = "Alias_Edit.aspx?saved=1&nodeid=" + nodeId.ToString() + "&aliasid=" + aliasId.ToString(); // Refresh the second frame in split mode if (CMSContext.DisplaySplitMode) { if (string.Compare(CMSContext.PreferredCultureCode, CMSContext.SplitModeCultureCode, StringComparison.InvariantCultureIgnoreCase) == 0) { url += "&refresh=1"; } } URLHelper.Redirect(url); } }
/// <summary> /// Raises event postback event. /// </summary> /// <param name="eventArgument">Event argument</param> /// <param name="uniqueCode">Unique code</param> /// <param name="variantId">Variant ID</param> public void RaisePostBackEvent(string eventArgument, string uniqueCode, int variantId) { // Check permissions if (!CheckPermissions("Manage") || stopProcessing) { return; } // Get the argument string arg = eventArgument.ToLowerCSafe(); if (arg == "remove") { // Remove variant action int documentId = 0; if (VariantMode == VariantModeEnum.MVT) { // Is MVT zone => remove the MVT variant MVTVariantInfo variantObj = MVTVariantInfoProvider.GetMVTVariantInfo(variantId); if (variantObj != null) { // Delete the variant MVTVariantInfoProvider.DeleteMVTVariantInfo(variantObj); documentId = variantObj.MVTVariantDocumentID; } } else if (VariantMode == VariantModeEnum.ContentPersonalization) { // Is Content personalization zone => remove the Content personalization variant ContentPersonalizationVariantInfo variantObj = ContentPersonalizationVariantInfoProvider.GetContentPersonalizationVariant(variantId); if (variantObj != null) { // Delete the variant ContentPersonalizationVariantInfoProvider.DeleteContentPersonalizationVariant(variantObj); documentId = variantObj.VariantDocumentID; } } else { return; } // Log widget variant synchronization if (documentId > 0) { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode node = DocumentHelper.GetDocument(documentId, tree); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } switch (SliderMode) { // Remove zone variant case VariantTypeEnum.Zone: if ((WebPartZoneControl != null) && (WebPartZoneControl.ZoneInstance != null)) { // Remove the variant from WebPartZoneControl.ZoneInstance.ZoneInstanceVariants. // It is necessary to remove the variants from the PartInstanceVariants list manually because the PageLoad method has already run // and the PartInstanceVariants list was populated with the old values. WebPartZoneControl.RemoveVariantFromCache(variantId); } break; // Remove web part or widget variant case VariantTypeEnum.WebPart: case VariantTypeEnum.Widget: if ((WebPartControl != null) && (WebPartControl.PartInstance != null)) { // Remove the variant from WebPartControls.PartInstance.PartInstanceVariants. // It is necessary to remove the variants from the PartInstanceVariants list manually because the PageLoad method has already run // and the PartInstanceVariants list was populated with the old values. WebPartControl.RemoveVariantFromCache(variantId); // If there are no other variants present, set the VariantMode to None to allow refreshing the add variant buttons. if ((WebPartControl.PartInstance.PartInstanceVariants == null) || (WebPartControl.PartInstance.PartInstanceVariants.Count == 0)) { mVariantMode = VariantModeEnum.None; } } break; default: break; } // Refresh the variant slider position => choose the last variant ltrScript.Text = ScriptHelper.GetScript( @"cpVariantSliderPositionElem = GetCPVariantSliderPositionElem(); UpdateVariantPosition('" + uniqueCode + @"', '-1'); SaveSlidersConfiguration();"); } }
/// <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 ((CurrentPageInfo != null) && (mTemplateInstance != null) && SaveForm(formCustom)) { ViewModeEnum viewMode = PortalContext.ViewMode; // Check manage permission for non-livesite version if (!viewMode.IsLiveSite() && viewMode != ViewModeEnum.DashboardWidgets && viewMode != ViewModeEnum.UserWidgets) { if (CurrentUser.IsAuthorizedPerDocument(CurrentPageInfo.NodeID, CurrentPageInfo.ClassName, NodePermissionsEnum.Modify) != AuthorizationResultEnum.Allowed) { DisplayError("general.modifynotallowed"); return(false); } // Check design permissions if (PortalContext.IsDesignMode(viewMode, false) && !PortalContext.CurrentUserIsDesigner) { RedirectToAccessDenied("CMS.Design", "Design"); } } PageTemplateInfo pti = mTemplateInstance.ParentPageTemplate; if (PortalContext.IsDesignMode(viewMode) && 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.TypeInfo.ObjectType, pti.DisplayName, userName)); return(false); } // Get the zone mWebPartZoneInstance = mTemplateInstance.EnsureZone(ZoneId); if (mWebPartZoneInstance != null) { mWebPartZoneInstance.WidgetZoneType = ZoneType; // Add new widget if (IsNewWidget) { bool isLayoutZone = (QueryHelper.GetBoolean("layoutzone", false)); int widgetID = ValidationHelper.GetInteger(WidgetId, 0); // Create new widget instance mWidgetInstance = PortalHelper.AddNewWidget(widgetID, ZoneId, ZoneType, isLayoutZone, mTemplateInstance); } // Ensure handling of the currently edited object (if not exists -> redirect) UIContext.EditedObject = mWidgetInstance; mWidgetInstance.XMLVersion = 1; if (IsNewVariant) { mWidgetInstance = mWidgetInstance.Clone(); // Check whether the editor widgets have been already customized if (CurrentPageInfo.DocumentTemplateInstance.WebPartZones.Count == 0) { // There are no customized editor widgets yet => copy the default editor widgets from the page template under the document (to enable customization) // Save to the document as editor admin changes TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider); // Extract and set the document web parts node.SetValue("DocumentWebParts", mTemplateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); // Save the document DocumentHelper.UpdateDocument(node, mTreeProvider); } } bool isLayoutWidget = ((mWebPartInfo != null) && ((WebPartTypeEnum)mWebPartInfo.WebPartType == WebPartTypeEnum.Layout)); // Get basicform's datarow and update widget SaveFormToWidget(formCustom, mTemplateInstance, isLayoutWidget); // Ensure unique id for new widget variant or layout widget if (IsNewVariant || (isLayoutWidget && IsNewWidget)) { string controlId = GetUniqueWidgetId(mWidgetInfo.WidgetName); if (!string.IsNullOrEmpty(controlId)) { mWidgetInstance.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)) { viewMode = ViewModeEnum.Design; PortalContext.SetViewMode(ViewModeEnum.Design); } bool isWidgetVariant = (VariantID > 0) || IsNewVariant; if (!isWidgetVariant) { // Save the changes if ((viewMode.IsEdit(true) || viewMode.IsEditLive()) && (ZoneType == WidgetZoneTypeEnum.Editor)) { if (DocumentManager.AllowSave) { // Store the editor widgets in the temporary interlayer PortalContext.SaveEditorWidgets(CurrentPageInfo.DocumentID, mTemplateInstance.GetZonesXML(WidgetZoneTypeEnum.Editor)); } } else { // Save the changes CMSPortalManager.SaveTemplateChanges(CurrentPageInfo, mTemplateInstance, ZoneType, viewMode, mTreeProvider); } } else if ((viewMode.IsEdit()) && (ZoneType == WidgetZoneTypeEnum.Editor)) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; VariantHelper.SaveWebPartVariantChanges(mWidgetInstance, VariantID, 0, VariantMode, properties); // Log widget variant synchronization TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, mTreeProvider); } } // Reload the form (because of macro values set only by JS) formCustom.ReloadData(); // Display info message ShowChangesSaved(); // Clear the cached web part CacheHelper.TouchKey("webpartinstance|" + InstanceGUID.ToString().ToLowerCSafe()); return(true); } return(false); }
protected void usUsers_OnItemsSelected(object sender, EventArgs e) { // Remove old items string newValues = ValidationHelper.GetString(usUsers.Value, null); string items = DataHelper.GetNewItemsInList(newValues, CurrentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to site foreach (string item in newItems) { int userID = ValidationHelper.GetInteger(item, 0); if (BoardID > 0) { // Remove message board from board ModuleCommands.MessageBoardRemoveModeratorFromBoard(userID, BoardID); } else if (Node != null) { UserInfo ui = UserInfoProvider.GetUserInfo(userID); if (ui != null) { // Remove user from treenode AclItemInfoProvider.RemoveUser(NodeID, ui); } } else if (ForumID > 0) { // Remove user from forum moderators ModuleCommands.ForumsRemoveForumModerator(userID, ForumID); } } } } // Add new items items = DataHelper.GetNewItemsInList(CurrentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to site foreach (string item in newItems) { int userID = ValidationHelper.GetInteger(item, 0); if (BoardID > 0) { // Add user to the message board ModuleCommands.MessageBoardAddModeratorToBoard(userID, BoardID); } else if (Node != null) { UserInfo ui = UserInfoProvider.GetUserInfo(userID); if (ui != null) { // Remove user from treenode AclItemInfoProvider.SetUserPermissions(Node, 0, 0, ui); } } else if (ForumID > 0) { // Add user to the forum moderators ModuleCommands.ForumsAddForumModerator(userID, ForumID); } } } } // Log synchronization task if (Node != null) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, Node.TreeProvider); } RaiseOnChanged(); }
/// <summary> /// Processes the callback action. /// </summary> void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) { eventArgument = eventArgument.ToLowerCSafe(); string[] parameters = eventArgument.Split(';'); if (parameters.Length < 3) { return; } // Get the arguments string action = parameters[0]; int nodeId = ValidationHelper.GetInteger(parameters[1], 0); int targetId = ValidationHelper.GetInteger(parameters[2], 0); // Get the target node TreeNode targetNode = TreeProvider.SelectSingleNode(targetId, TreeProvider.ALL_CULTURES); if (targetNode == null) { AddError(GetString("ContentRequest.ErrorMissingTarget") + " " + eventArgument); mCallbackResult += GetFallBackToRootScript(true); return; } // Get the node TreeNode node = TreeProvider.SelectSingleNode(nodeId); if (node == null) { AddError(GetString("ContentRequest.ErrorMissingSource")); mCallbackResult += GetFallBackToRootScript(true); return; } // Get new parent ID int newParentId = targetNode.NodeID; if (action.Contains("position")) { if (action.Contains("move") && (nodeId == targetId)) { // There is no need to change position return; } if (!targetNode.IsRoot()) { newParentId = targetNode.NodeParentID; } } else if (node.NodeParentID == newParentId) { // Move/Copy/Link as the first node under the same parent if (action.EndsWithCSafe("position")) { action = action.Substring(0, action.Length - 8); } action += "first"; } bool copy = (action.Contains("copy")); bool link = (action.Contains("link")); // Do not allow to move or copy under itself if ((node.NodeID == newParentId) && !copy && !link) { AddError(GetString("ContentRequest.CannotMoveToItself")); return; } // Local action - Only position change if ((node.NodeParentID == newParentId) && !copy && !link) { // Local action - Only position change int originalPosition = node.NodeOrder; TreeNode newNode = ProcessAction(node, targetNode, action, false, false, true); if ((newNode != null) && (originalPosition != newNode.NodeOrder)) { // Log the synchronization tasks for the entire tree level DocumentSynchronizationHelper.LogDocumentChangeOrder(SiteContext.CurrentSiteName, newNode.NodeAliasPath, TreeProvider); mCallbackResult += "CancelDragOperation(); RefreshTree(" + newNode.NodeParentID + ", currentNodeId);"; } } else { // Different parent mCallbackResult += "DragOperation(" + nodeId + ", " + targetId + ", '" + action + "');"; } }
private void DeleteAttachmentAction(Guid attGuid) { if (!createTempAttachment) { if (attGuid != Guid.Empty) { // Delete attachment if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = VersionManager.GetInstance(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } // If the GUID column is set, use it to process additional actions for field attachments if (!String.IsNullOrEmpty(GUIDColumnName)) { DocumentHelper.DeleteAttachment(Node, GUIDColumnName); } else { DocumentHelper.DeleteAttachment(Node, attGuid); } DocumentHelper.UpdateDocument(Node, TreeProvider); // Ensure full page refresh if (AutoCheck) { ScriptHelper.RegisterStartupScript(Page, typeof(Page), "deleteRefresh", ScriptHelper.GetScript("InitRefresh_" + ClientID + "('', true, true, '" + attGuid + "', 'delete');")); } else { string script = "if (window.RefreshTree) { RefreshTree(" + Node.NodeParentID + ", " + Node.NodeID + "); }"; ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refreshTree", ScriptHelper.GetScript(script)); } // Check in the document if (AutoCheck) { vm?.CheckIn(Node, null); } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentInfoProvider.DeleteTemporaryAttachment(attGuid, SiteContext.CurrentSiteName); } } } LastAction = "delete"; Value = null; }
protected void btnOK_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(ctrlURL.PlainURLPath)) { ShowError(GetString("doc.urls.requiresurlpath")); return; } if (!usSelectCampaign.IsValid()) { ShowError(GetString("campaign.validcodename")); return; } // Validate URL path if (!ctrlURL.IsValid()) { ShowError(ctrlURL.ValidationError); return; } if (Node != null) { // Check modify permissions if (!DocumentUIHelper.CheckDocumentPermissions(Node, PermissionsEnum.Modify)) { ShowError(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), Node.NodeAliasPath)); return; } // Check whether if (!DocumentAliasInfoProvider.IsUnique(ctrlURL.URLPath, DocumentAlias.AliasID, Convert.ToString(cultureSelector.Value), txtURLExtensions.Text.Trim(), SiteContext.CurrentSiteName, true, NodeID)) { ShowError(GetString("doc.urls.doacaliasnotunique")); return; } // Set object properties DocumentAlias.AliasURLPath = ctrlURL.URLPath; DocumentAlias.AliasCampaign = ValidationHelper.GetString(usSelectCampaign.Value, String.Empty).Trim(); DocumentAlias.AliasExtensions = txtURLExtensions.Text.Trim(); DocumentAlias.AliasCulture = ValidationHelper.GetString(cultureSelector.Value, ""); DocumentAlias.AliasSiteID = SiteContext.CurrentSite.SiteID; DocumentAlias.AliasActionMode = drpAction.SelectedValue.ToEnum <AliasActionModeEnum>(); DocumentAlias.AliasNodeID = NodeID; // Insert into database DocumentAliasInfoProvider.SetDocumentAliasInfo(DocumentAlias, Node.NodeSiteName); // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, Tree); aliasId = DocumentAlias.AliasID; string url = "Alias_Edit.aspx?saved=1&nodeid=" + NodeID + "&aliasid=" + aliasId + "&dialog=" + IsDialog; if (IsDialog) { url += "&defaultNodeID=" + defaultNodeID; } // Refresh the second frame in split mode if (UIContext.DisplaySplitMode) { url += "&refresh=1"; } URLHelper.Redirect(url); } }
/// <summary> /// Handles UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of the action which should be performed</param> /// <param name="actionArgument">ID of the item the action should be performed with</param> protected void gridElem_OnAction(string actionName, object actionArgument) { if (!CheckPermissions("CMS.ContentPersonalization", "Manage")) { return; } int variantId = ValidationHelper.GetInteger(actionArgument, 0); if (variantId > 0) { string action = actionName.ToLowerCSafe(); switch (action) { case "delete": { // Get the instance in order to clear the cache ContentPersonalizationVariantInfo vi = ContentPersonalizationVariantInfoProvider.GetContentPersonalizationVariant(variantId); // Delete the object ContentPersonalizationVariantInfoProvider.DeleteContentPersonalizationVariant(variantId); RaiseOnAction(string.Empty, null); // Log widget variant synchronization if ((vi != null) && (vi.VariantDocumentID > 0)) { // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, tree); } } break; case "up": case "down": { // Get the instance in order to clear the cache ContentPersonalizationVariantInfo vi = ContentPersonalizationVariantInfoProvider.GetContentPersonalizationVariant(variantId); // Use try/catch due to license check try { if (action == "up") { // Move up ContentPersonalizationVariantInfoProvider.MoveVariantUp(variantId); } else { // Move down ContentPersonalizationVariantInfoProvider.MoveVariantDown(variantId); } RaiseOnAction(string.Empty, null); // Log widget variant synchronization if (vi.VariantDocumentID > 0) { // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, tree); } } catch (Exception ex) { lblError.Visible = true; lblError.Text = ex.Message; } } break; } } }
/// <summary> /// UniGrid action buttons event handler. /// </summary> protected void gridAttachments_OnAction(string actionName, object actionArgument) { if (Enabled && !HideActions) { #region "Check permissions" if (CheckPermissions) { if (FormGUID != Guid.Empty) { if (!RaiseOnCheckPermissions("Create", this)) { if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(NodeParentNodeID, NodeClassName)) { ShowError(GetString("attach.actiondenied")); return; } } } else { if (!RaiseOnCheckPermissions("Modify", this)) { if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { ShowError(GetString("attach.actiondenied")); return; } } } } #endregion Guid attachmentGuid = Guid.Empty; // Get action argument (Guid or int) if (ValidationHelper.IsGuid(actionArgument)) { attachmentGuid = ValidationHelper.GetGuid(actionArgument, Guid.Empty); } // Process proper action switch (actionName.ToLowerCSafe()) { case "moveup": if (attachmentGuid != Guid.Empty) { // Move attachment up if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = VersionManager.GetInstance(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } DocumentHelper.MoveAttachmentUp(attachmentGuid, Node); // Check in the document if (AutoCheck) { if (vm != null) { vm.CheckIn(Node, null, null); } // Ensure full page refresh ScriptHelper.RegisterStartupScript(Page, typeof(Page), "moveUpRefresh", ScriptHelper.GetScript(String.Format("InitRefresh_{0}('', true, false, 'moveup');", ClientID))); } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentInfoProvider.MoveAttachmentUp(attachmentGuid, 0); } } break; case "movedown": if (attachmentGuid != Guid.Empty) { // Move attachment down if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = VersionManager.GetInstance(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } DocumentHelper.MoveAttachmentDown(attachmentGuid, Node); // Check in the document if (AutoCheck) { if (vm != null) { vm.CheckIn(Node, null, null); } // Ensure full page refresh ScriptHelper.RegisterStartupScript(Page, typeof(Page), "moveDownRefresh", ScriptHelper.GetScript(String.Format("InitRefresh_{0}('', true, false, 'movedown');", ClientID))); } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentInfoProvider.MoveAttachmentDown(attachmentGuid, 0); } } break; case "delete": if (attachmentGuid != Guid.Empty) { // Delete attachment if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = VersionManager.GetInstance(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } DocumentHelper.DeleteAttachment(Node, attachmentGuid, TreeProvider); // Check in the document if (AutoCheck) { if (vm != null) { vm.CheckIn(Node, null, null); } // Ensure full page refresh ScriptHelper.RegisterStartupScript(Page, typeof(Page), "deleteRefresh", ScriptHelper.GetScript(String.Format("InitRefresh_{0}('', true, false, 'delete');", ClientID))); } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentInfoProvider.DeleteTemporaryAttachment(attachmentGuid, CMSContext.CurrentSiteName); } ShowConfirmation(GetString("attach.deleted")); } break; } } }
/// <summary> /// Callback event handler. /// </summary> /// <param name="argument">Callback argument</param> public void RaiseCallbackEvent(string argument) { // Check permissions if ((currentUser == null) || (!currentUser.IsAuthorizedPerResource("CMS.MVTest", "Manage")) || stopProcessing) { return; } // Get arguments if (!string.IsNullOrEmpty(argument)) { string[] args = argument.Split(new[] { ';' }, 3); if (args.Length == 3) { string combinationName = ValidationHelper.GetString(args[0], string.Empty); string action = args[1].ToLowerCSafe(); string newValue = args[2]; // Get the combination info MVTCombinationInfo mvtcInfo = MVTCombinationInfoProvider.GetMVTCombinationInfo(combinationSelector.PageTemplateID, combinationName); if (mvtcInfo != null) { switch (action) { case "cname": // Custom name changed mvtcInfo.MVTCombinationCustomName = newValue; if (string.IsNullOrEmpty(newValue)) { newValue = mvtcInfo.MVTCombinationName; } // return the new value (when newValue=="", then return combination code name) callbackValue = newValue; break; case "enabled": // combination Enabled changed mvtcInfo.MVTCombinationEnabledOriginal = mvtcInfo.MVTCombinationEnabled; mvtcInfo.MVTCombinationEnabled = ValidationHelper.GetBoolean(newValue, true); callbackValue = string.Empty; break; default: return; } MVTCombinationInfoProvider.SetMVTCombinationInfo(mvtcInfo); // Synchronize widget variants if enabling combination if ((mvtcInfo.MVTCombinationDocumentID > 0) || (!mvtcInfo.MVTCombinationEnabledOriginal && mvtcInfo.MVTCombinationEnabled )) { // Log synchronization TreeProvider tree = new TreeProvider(currentUser); TreeNode node = tree.SelectSingleDocument(mvtcInfo.MVTCombinationDocumentID); if (node != null) { DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } } } } }
/// <summary> /// Resets permission inheritance of node and its children. /// </summary> /// <param name="siteName">Name of site</param> /// <param name="nodeAliasPath">Alias path</param> /// <param name="recursive">Indicates whether to recursively reset all nodes below the current node</param> /// <param name="user">Current user</param> /// <param name="tr">Tree provider</param> /// <returns>Whether TRUE if no permission conflict has occurred</returns> private bool ResetNodePermission(string siteName, string nodeAliasPath, bool recursive, UserInfo user, TreeProvider tr) { // Check permissions bool permissionsResult = false; try { if (tr == null) { tr = new TreeProvider(user); } // Get node by alias path TreeNode treeNode = tr.SelectSingleNode(siteName, nodeAliasPath, null, true, null, false); permissionsResult = CanModifyPermission(!recursive, treeNode, user); if (treeNode != null) { // If user has permissions if (permissionsResult) { // Break inheritance of a node if (!AclInfoProvider.DoesNodeInheritPermissions(treeNode)) { // Restore inheritance of a node AclInfoProvider.RestoreInheritance(treeNode); // Log current encoded alias path AddLog(HTMLHelper.HTMLEncode(nodeAliasPath)); // Log staging task and flush cache DocumentSynchronizationHelper.LogDocumentChange(treeNode, TaskTypeEnum.RestoreACLInheritance, treeNode.TreeProvider, SynchronizationInfoProvider.ENABLED_SERVERS, null, treeNode.TreeProvider.AllowAsyncActions); Node.ClearCache(); // Insert information about this event to event log. if (DocumentManager.Tree.LogEvents) { if (recursive) { LogContext.LogEventToCurrent(EventType.INFORMATION, "Content", "DOCPERMISSIONSMODIFIED", string.Format(ResHelper.GetAPIString("security.documentpermissionsrestoredfordoc", "Permissions of the page '{0}' have been restored to the parent page permissions."), nodeAliasPath), null, user.UserID, user.UserName, treeNode.NodeID, treeNode.GetDocumentName(), ipAddress, Node.NodeSiteID, null, null, null, DateTime.Now); } else { EventLogProvider.LogEvent(EventType.INFORMATION, "Content", "DOCPERMISSIONSMODIFIED", ResHelper.GetAPIString("security.documentpermissionsrestored", "Permissions have been restored to the parent page permissions."), eventUrl, user.UserID, user.UserName, treeNode.NodeID, treeNode.GetDocumentName(), ipAddress, Node.NodeSiteID); } } } else { AddLog(string.Format(GetString("cmsdesk.skippingrestoring"), HTMLHelper.HTMLEncode(nodeAliasPath))); } } // Recursively reset node inheritance if (recursive) { // Get child nodes of current node DataSet ds = DocumentManager.Tree.SelectNodes(siteName, treeNode.NodeAliasPath.TrimEnd('/') + "/%", TreeProvider.ALL_CULTURES, true, null, null, null, 1, false, -1, DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",NodeAliasPath"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { string childNodeAliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], string.Empty); if (!string.IsNullOrEmpty(childNodeAliasPath)) { bool tempPermissionsResult = ResetNodePermission(siteName, childNodeAliasPath, true, user, tr); permissionsResult = tempPermissionsResult && permissionsResult; } } } } } } catch (ThreadAbortException ex) { if (CMSThread.Stopped(ex)) { // When canceled CurrentInfo = GetString("cmsdesk.restoringcanceled"); AddLog(CurrentInfo); } else { // Log error CurrentError = GetString("cmsdesk.restoringfailed") + ": " + ex.Message; AddLog(CurrentError); } } catch (Exception ex) { // Log error CurrentError = GetString("cmsdesk.restoringfailed") + ": " + ex.Message; AddLog(CurrentError); } return(permissionsResult); }
/// <summary> /// Saves relationship. /// </summary> public void SaveRelationship() { if (TreeNode == null) { return; } // Check modify permissions if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(TreeNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { return; } bool currentNodeIsOnLeftSide = !DefaultSide; // Selected node Id int selectedNodeId = ValidationHelper.GetInteger(hdnSelectedNodeId.Value, 0); if (BindOnPrimaryNodeOnly) { selectedNodeId = RelHelper.GetPrimaryNodeID(selectedNodeId); } var relationshipName = RelationshipName; var relationshipNameInfo = RelationshipNameInfoProvider.GetRelationshipNameInfo(relationshipName); int relationshipNameId; if (relationshipNameInfo != null) { relationshipNameId = relationshipNameInfo.RelationshipNameId; } else { throw new NullReferenceException("[RelatedDocuments.SaveRelationship]: Missing relationship name to use for relation."); } if ((selectedNodeId <= 0) || (relationshipNameId <= 0)) { return; } try { // Test to make sure the selected page is a Right Side macro-allowed page or left side, and also matches the Page type limiter var SelectedTreeNode = (AllowAllTypes ? new DocumentQuery() : new DocumentQuery(AllowedPageTypes)).WhereEquals("NodeID", selectedNodeId).FirstOrDefault(); // If null probably not an allowed page type, but we will need it to validate below if (SelectedTreeNode == null) { SelectedTreeNode = new DocumentQuery().WhereEquals("NodeID", selectedNodeId).FirstOrDefault(); } var CurrentPageMacroResolver = MacroResolver.GetInstance(); CurrentPageMacroResolver.SetNamedSourceData("CurrentDocument", TreeNode); var PageMacroResolver = MacroResolver.GetInstance(); PageMacroResolver.SetNamedSourceData("CurrentDocument", SelectedTreeNode); // Left side if (currentNodeIsOnLeftSide) { if (!AllowAllTypes && !ClassNames.Contains(SelectedTreeNode.ClassName.ToLower())) { AddError(ResHelper.LocalizeExpression("RelatedPages.BadPageType")); } else if (!ValidationHelper.GetBoolean(CurrentPageMacroResolver.ResolveMacros(IsLeftSideMacro), false) || !ValidationHelper.GetBoolean(PageMacroResolver.ResolveMacros(IsRightSideMacro), false)) { AddError(ResHelper.LocalizeExpression("RelatedPages.LeftSideRightSideInvalid")); } else if (TreeNode.NodeID == SelectedTreeNode.NodeID) { AddError(ResHelper.LocalizeExpression("RelatedPages.CannotSelectSelf")); } else { RelationshipInfoProvider.AddRelationship(TreeNode.NodeID, selectedNodeId, relationshipNameId); if (RelHelper.IsStagingEnabled()) { // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(TreeNode.NodeSiteName, TreeNode.NodeAliasPath, TaskTypeEnum.UpdateDocument, TreeProvider); } ShowConfirmation(GetString("relationship.wasadded")); } } // Right side else { if (!AllowAllTypes && !ClassNames.Contains(SelectedTreeNode.ClassName.ToLower())) { AddError(ResHelper.LocalizeExpression("RelatedPages.BadPageType")); } else if (!ValidationHelper.GetBoolean(CurrentPageMacroResolver.ResolveMacros(IsLeftSideMacro), false) || !ValidationHelper.GetBoolean(PageMacroResolver.ResolveMacros(IsRightSideMacro), false)) { AddError(ResHelper.LocalizeExpression("RelatedPages.LeftSideRightSideInvalid")); } else if (TreeNode.NodeID == SelectedTreeNode.NodeID) { AddError(ResHelper.LocalizeExpression("RelatedPages.CannotSelectSelf")); } else { RelationshipInfoProvider.AddRelationship(selectedNodeId, TreeNode.NodeID, relationshipNameId); if (RelHelper.IsStagingEnabled()) { // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(TreeNode.NodeSiteName, SelectedTreeNode.NodeAliasPath, TaskTypeEnum.UpdateDocument, TreeProvider); } ShowConfirmation(GetString("relationship.wasadded")); } } } catch (Exception ex) { ShowError(ex.Message); } }
private void SubmitForm() { if (ctrlProduct.ProductID > 0) { // Check permissions if (ctrlProduct.ProductSiteID > 0) { if (!ECommerceContext.IsUserAuthorizedForPermission("ModifyProducts")) { RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts"); } } else { if (!ECommerceContext.IsUserAuthorizedForPermission("EcommerceGlobalModify")) { RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify"); } } // Update if (chkMarkDocAsProd.Checked) { ctrlProduct.Save(); } // Delete else { this.Node.NodeSKUID = 0; this.Node.Update(); // Update search index for node if ((this.Node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, this.Node.GetSearchID()); } // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(this.Node, TaskTypeEnum.UpdateDocument, this.Node.TreeProvider); URLHelper.Redirect("Product_Selection.aspx?nodeid=" + this.NodeID); } } else { if (!IsAuthorizedToModifyDocument()) { RedirectToAccessDenied("CMS.Content", "Modify"); } // Use existing product if (radSelect.Checked) { if (skuElem.SKUID > 0) { this.Node.NodeSKUID = this.skuElem.SKUID; this.Node.Update(); // Update search index for node if ((this.Node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, this.Node.GetSearchID()); } // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(this.Node, TaskTypeEnum.UpdateDocument, this.Node.TreeProvider); URLHelper.Redirect(String.Format("Product_Edit_Frameset.aspx?productid={0}&nodeid={1}&saved=1", this.Node.NodeSKUID, this.NodeID)); } else { lblError.Visible = true; lblError.Text = GetString("Products.EmptyList"); } } // Create new product else { ctrlProduct.Save(); } } }
/// <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) { RelationshipInfo.Provider.Add(currentNodeId, selectedNodeId, relationshipNameId); } // Right side else { RelationshipInfo.Provider.Add(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); }
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> /// UniGrid action buttons event handler. /// </summary> protected void GridAttachmentsOnAction(string actionName, object actionArgument) { if (Enabled && !HideActions) { // Check the permissions #region "Check permissions" if (CheckPermissions) { if (FormGUID != Guid.Empty) { if (!RaiseOnCheckPermissions("Create", this)) { if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(NodeParentNodeID, NodeClassName)) { lblError.Text = GetString("attach.actiondenied"); return; } } } else { if (!RaiseOnCheckPermissions("Modify", this)) { if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { lblError.Text = GetString("attach.actiondenied"); return; } } } } #endregion Guid attachmentGuid = Guid.Empty; // Get action argument (Guid or int) if (ValidationHelper.IsGuid(actionArgument)) { attachmentGuid = ValidationHelper.GetGuid(actionArgument, Guid.Empty); } // Process proper action switch (actionName.ToLowerCSafe()) { case "delete": if (!createTempAttachment) { if (attachmentGuid != Guid.Empty) { // Delete attachment if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = VersionManager.GetInstance(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } // If the GUID column is set, use it to process additional actions for field attachments if (GUIDColumnName != null) { DocumentHelper.DeleteAttachment(Node, GUIDColumnName, TreeProvider); } else { DocumentHelper.DeleteAttachment(Node, attachmentGuid, TreeProvider); } DocumentHelper.UpdateDocument(Node, TreeProvider); // Ensure full page refresh if (AutoCheck) { ScriptHelper.RegisterStartupScript(Page, typeof(Page), "deleteRefresh", ScriptHelper.GetScript("InitRefresh_" + ClientID + "('', true, true, '" + attachmentGuid + "', 'delete');")); } else { string script = "if (window.RefreshTree) { RefreshTree(" + Node.NodeParentID + ", " + Node.NodeID + "); }"; ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refreshTree", ScriptHelper.GetScript(script)); } // Check in the document if (AutoCheck) { if (vm != null) { vm.CheckIn(Node, null, null); } } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentInfoProvider.DeleteTemporaryAttachment(attachmentGuid, CMSContext.CurrentSiteName); } } } LastAction = "delete"; Value = Guid.Empty; break; } // Force reload data ReloadData(true); } }
/// <summary> /// After node created, solver role permissions. /// </summary> private void AddRoles(object sender, EventArgs e) { var tree = new TreeProvider(MembershipContext.AuthenticatedUser); string roleIds = ";" + usRoles.Value + ";"; // Check if ACL should inherit from parent if (InheritParentPermissions) { AclInfoProvider.EnsureOwnAcl(EditedNode); } else { // If node has already own ACL don't leave permissions, otherwise break inheritance if (!EditedNode.NodeIsACLOwner) { AclInfoProvider.BreakInheritance(EditedNode, false); var breakInheritanceNode = tree.SelectSingleNode(EditedNode.NodeID); DocumentSynchronizationHelper.LogDocumentChange(breakInheritanceNode, TaskTypeEnum.BreakACLInheritance, tree, SynchronizationInfoProvider.ENABLED_SERVERS, null, tree.AllowAsyncActions); } } // Get original ACLItems DataSet ds = AclItemInfoProvider.GetACLItemsAndOperators(EditedNode.NodeID) .WhereStartsWith("Operator", "R") .WhereEquals("ACLID", EditedNode.NodeACLID) .Columns("Operator", "Allowed", "Denied"); // Change original values if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { string op = DataHelper.GetNotEmpty(dr["Operator"], "R"); int allowed = ValidationHelper.GetInteger(dr["Allowed"], 0); int denied = ValidationHelper.GetInteger(dr["Denied"], 0); int aclRoleId = ValidationHelper.GetInteger(op.Substring(1), 0); if (aclRoleId != 0) { // Check if read permission should be set or removed if (roleIds.Contains(";" + aclRoleId + ";")) { // Remove role from processed role and adjust permissions in database roleIds = roleIds.Replace(";" + aclRoleId + ";", ";"); allowed |= 1; } else { allowed &= 126; } RoleInfo ri = RoleInfoProvider.GetRoleInfo(aclRoleId); AclItemInfoProvider.SetRolePermissions(EditedNode, allowed, denied, ri); } } } if (roleIds.Trim(';') != "") { // Create ACL items for new roles string[] roles = roleIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string role in roles) { RoleInfo ri = RoleInfoProvider.GetRoleInfo(int.Parse(role)); AclItemInfoProvider.SetRolePermissions(EditedNode, 1, 0, ri); } } var node = tree.SelectSingleNode(EditedNode.NodeID); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); }
/// <summary> /// Saves modified image data. /// </summary> /// <param name="name">Image name</param> /// <param name="extension">Image extension</param> /// <param name="mimetype">Image mimetype</param> /// <param name="title">Image title</param> /// <param name="description">Image description</param> /// <param name="binary">Image binary data</param> /// <param name="width">Image width</param> /// <param name="height">Image height</param> private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height) { LoadInfos(); // Save image data depending to image type switch (baseImageEditor.ImageType) { // Process attachment case ImageHelper.ImageTypeEnum.Attachment: if (ai != null) { // Save new data try { // Get the node TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree); // Check Create permission when saving temporary attachment, check Modify permission else NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create; // Check permission if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed) { baseImageEditor.ShowError(GetString("attach.actiondenied")); SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.ShowError(GetString("img.namenotunique")); SavingFailed = true; return; } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(baseImageEditor.Tree); if (node != null) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CurrentSiteName); } // Check out the document if (autoCheck) { VersionManager.CheckOut(node, node.IsPublished, true); VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; } // Workflow has been lost, get published attachment if (useWorkflow && (VersionHistoryID == 0)) { ai = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName); } // If extension changed update CMS.File extension if ((node.NodeClassName.ToLowerCSafe() == "cms.file") && (node.DocumentExtensions != extension)) { // Update document extensions if no custom are used if (!node.DocumentUseCustomExtensions) { node.DocumentExtensions = extension; } node.SetValue("DocumentType", extension); DocumentHelper.UpdateDocument(node, baseImageEditor.Tree); } } if (ai != null) { // Test all parameters to empty values and update new value if available if (name != "") { if (!name.EndsWithCSafe(extension)) { ai.AttachmentName = name + extension; } else { ai.AttachmentName = name; } } if (extension != "") { ai.AttachmentExtension = extension; } if (mimetype != "") { ai.AttachmentMimeType = mimetype; } ai.AttachmentTitle = title; ai.AttachmentDescription = description; if (binary != null) { ai.AttachmentBinary = binary; ai.AttachmentSize = binary.Length; } if (width > 0) { ai.AttachmentImageWidth = width; } if (height > 0) { ai.AttachmentImageHeight = height; } // Ensure object ai.MakeComplete(true); if (VersionHistoryID > 0) { VersionManager.SaveAttachmentVersion(ai, VersionHistoryID); } else { AttachmentInfoProvider.SetAttachmentInfo(ai); // Log the synchronization and search task for the document if (node != null) { // Update search index for given document if (DocumentHelper.IsSearchTaskCreationAllowed(node)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID); } DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree); } } // Check in the document if ((autoCheck) && (VersionManager != null) && (VersionHistoryID > 0) && (node != null)) { VersionManager.CheckIn(node, null); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { var currentUser = MembershipContext.AuthenticatedUser; if ((currentUser != null) && currentUser.IsGlobalAdministrator) { try { string physicalPath = Server.MapPath(filePath); string newPath = physicalPath; // Write binary data to the disk File.WriteAllBytes(physicalPath, binary); // Handle rename of the file if (!String.IsNullOrEmpty(name)) { newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name); } if (!String.IsNullOrEmpty(extension)) { string oldExt = Path.GetExtension(physicalPath); newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension; } // Move the file if (newPath != physicalPath) { File.Move(physicalPath, newPath); } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser)) { try { // Test all parameters to empty values and update new value if available if (name.CompareToCSafe("") != 0) { if (!name.EndsWithCSafe(extension)) { mf.MetaFileName = name + extension; } else { mf.MetaFileName = name; } } if (extension.CompareToCSafe("") != 0) { mf.MetaFileExtension = extension; } if (mimetype.CompareToCSafe("") != 0) { mf.MetaFileMimeType = mimetype; } mf.MetaFileTitle = title; mf.MetaFileDescription = description; if (binary != null) { mf.MetaFileBinary = binary; mf.MetaFileSize = binary.Length; } if (width > 0) { mf.MetaFileImageWidth = width; } if (height > 0) { mf.MetaFileImageHeight = height; } // Save new data MetaFileInfoProvider.SetMetaFileInfo(mf); if (RefreshAfterAction) { if (String.IsNullOrEmpty(externalControlID)) { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();"); } else { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID)); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; } }
protected void btnSave_Click(object sender, EventArgs e) { if ((nodeId > 0) && (node != null)) { LayoutTypeEnum layoutType = LayoutInfoProvider.GetLayoutTypeEnum(drpType.SelectedValue); // Check the permissions if ((layoutType != LayoutTypeEnum.Ascx) || user.IsAuthorizedPerResource("CMS.Design", "EditCode")) { // Update the layout if (node.DocumentPageTemplateID > 0) { PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(node.DocumentPageTemplateID); if (pti != null) { // Get shared layout LayoutInfo li = LayoutInfoProvider.GetLayoutInfo(pti.LayoutID); if (li != null) { // Update shared layout li.LayoutCode = txtLayout.Text; li.LayoutType = layoutType; LayoutInfoProvider.SetLayoutInfo(li); } else if (pti.PageTemplateLayoutCheckedOutByUserID <= 0) { // Update custom layout pti.PageTemplateLayout = txtLayout.Text; pti.PageTemplateLayoutType = layoutType; PageTemplateInfoProvider.SetPageTemplateInfo(pti); } } } } // Update fields node.NodeBodyElementAttributes = txtBodyCss.Text; node.NodeDocType = txtDocType.Text; node.NodeHeadTags = txtHeadTags.Value.ToString(); // Update the node node.Update(); // 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); lblInfo.Visible = true; lblInfo.Text = GetString("General.ChangesSaved"); // Clear cache PageInfoProvider.RemoveAllPageInfosFromCache(); } }