protected void Page_Load(object sender, EventArgs e) { currentUser = CMSContext.CurrentUser; if (currentUser == null) { return; } // Check 'ReadForm' permission if (!currentUser.IsAuthorizedPerResource("cms.form", "ReadForm")) { RedirectToCMSDeskAccessDenied("cms.form", "ReadForm"); } UniGridBizForms.OnAction += new OnActionEventHandler(UniGridBizForms_OnAction); UniGridBizForms.OnAfterRetrieveData += new OnAfterRetrieveData(uniGrid_OnAfterRetrieveData); UniGridBizForms.HideControlForZeroRows = false; UniGridBizForms.ZeroRowsText = GetString("general.nodatafound"); UniGridBizForms.WhereCondition = "FormSiteID = " + CMSContext.CurrentSiteID; // New item link string[,] actions = new string[1,6]; actions[0, 0] = HeaderActions.TYPE_HYPERLINK; actions[0, 1] = GetString("BizFormList.lnkNewBizForm"); actions[0, 2] = null; actions[0, 3] = ResolveUrl("BizForm_New.aspx"); actions[0, 4] = null; actions[0, 5] = GetImageUrl("Objects/CMS_Form/add.png"); CurrentMaster.HeaderActions.Actions = actions; CurrentMaster.Title.TitleText = GetString("BizFormList.TitleText"); CurrentMaster.Title.TitleImage = GetImageUrl("Objects/CMS_Form/object.png"); CurrentMaster.Title.HelpTopicName = "bizforms"; }
protected void Page_Load(object sender, EventArgs e) { currentUser = MembershipContext.AuthenticatedUser; currentObject = (ContactRoleInfo)EditedObject; // Check read permission currentObjectSiteId = currentObject.ContactRoleID != 0 ? currentObject.ContactRoleSiteID : siteID; CheckReadPermission(currentObjectSiteId); // Preserve site info passed in query PageBreadcrumbs.Items[0].RedirectUrl = AddSiteQuery(PageBreadcrumbs.Items[0].RedirectUrl, siteID); EditForm.RedirectUrlAfterSave = AddSiteQuery(EditForm.RedirectUrlAfterSave, siteID); ContactRoleInfo contactRole = EditForm.EditedObject as ContactRoleInfo; // Set new site ID for new object if ((contactRole == null) || (contactRole.ContactRoleID < 1)) { if ((siteID == UniSelector.US_GLOBAL_RECORD) && ModifyGlobalConfiguration) { EditForm.Data["ContactRoleSiteID"] = null; } else if (IsSiteManager && currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)) { EditForm.Data["ContactRoleSiteID"] = siteID; } else { EditForm.Data["ContactRoleSiteID"] = SiteContext.CurrentSiteID; } } }
protected void Page_Load(object sender, EventArgs e) { currentUser = MembershipContext.AuthenticatedUser; if (currentUser == null) { return; } // Check 'ReadForm' permission if (!currentUser.IsAuthorizedPerResource("cms.form", "ReadForm")) { RedirectToAccessDenied("cms.form", "ReadForm"); } UniGridBizForms.OnAction += UniGridBizForms_OnAction; UniGridBizForms.OnAfterRetrieveData += uniGrid_OnAfterRetrieveData; UniGridBizForms.HideControlForZeroRows = false; UniGridBizForms.ZeroRowsText = GetString("general.nodatafound"); UniGridBizForms.WhereCondition = "FormSiteID = " + SiteContext.CurrentSiteID; PageTitle.TitleText = GetString("BizFormList.TitleText"); InitHeaderActions(); }
protected void Page_Load(object sender, EventArgs e) { currentUser = CMSContext.CurrentUser; string imagePath = URLHelper.ResolveUrl(GetImageUrl("Objects/CMS_Friend/")); ScriptHelper.RegisterDialogScript(this); FriendsList.UserID = currentUser.UserID; FriendsList.OnCheckPermissions += CheckPermissions; FriendsList.ZeroRowsText = GetString("friends.nofriends"); // Request friend link string script = "function displayRequest(){ \n" + "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Friends/Dialogs/Friends_Request.aspx") + "?userid=" + currentUser.UserID + "', 'rejectDialog', 480, 350);}"; ScriptHelper.RegisterStartupScript(this, GetType(), "displayModalRequest", ScriptHelper.GetScript(script)); string[,] actions = new string[1, 6]; actions[0, 0] = HeaderActions.TYPE_HYPERLINK; actions[0, 1] = GetString("Friends_List.NewItemCaption"); actions[0, 2] = null; actions[0, 3] = "javascript:displayRequest();"; actions[0, 4] = null; actions[0, 5] = imagePath + "add.png"; CurrentMaster.HeaderActions.Actions = actions; }
protected void Page_Load(object sender, EventArgs e) { userId = QueryHelper.GetInteger("userId", 0); currentUser = CMSContext.CurrentUser; // Check 'read' permissions if (!currentUser.IsAuthorizedPerResource("CMS.Friends", "Read") && (currentUser.UserID != userId)) { RedirectToAccessDenied("CMS.Friends", "Read"); } // Check license if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.Friends); } // initializes breadcrumbs string[,] pageTitleTabs = new string[1, 3]; pageTitleTabs[0, 0] = GetString("friends.friends"); pageTitleTabs[0, 1] = ""; pageTitleTabs[0, 2] = ""; CurrentMaster.Title.Breadcrumbs = pageTitleTabs; CurrentMaster.Title.HelpTopicName = "friends_myfriends"; CurrentMaster.Title.HelpName = "helpTopic"; if (!RequestHelper.IsPostBack()) { InitalizeMenu(); } }
protected void Page_Load(object sender, EventArgs e) { currentUser = CMSContext.CurrentUser; if (currentUser == null) { return; } // Page title CurrentMaster.Title.TitleText = GetString("avat.title"); CurrentMaster.Title.TitleImage = GetImageUrl("Objects/CMS_Avatar/object.png"); CurrentMaster.Title.HelpTopicName = "avatars_list"; CurrentMaster.Title.HelpName = "helpTopic"; // New item link string[,] actions = new string[1,6]; actions[0, 0] = HeaderActions.TYPE_HYPERLINK; actions[0, 1] = GetString("avat.newavatar"); actions[0, 2] = null; actions[0, 3] = ResolveUrl("Avatar_Edit.aspx"); actions[0, 4] = null; actions[0, 5] = GetImageUrl("Objects/CMS_Avatar/add.png"); CurrentMaster.HeaderActions.Actions = actions; // Set up unigrid options unigridAvatarList.OrderBy = "AvatarName"; unigridAvatarList.OnExternalDataBound += unigridAvatarList_OnExternalDataBound; unigridAvatarList.OnAction += unigridAvatarList_OnAction; unigridAvatarList.GridView.PageSize = 10; unigridAvatarList.ZeroRowsText = GetString("general.nodatafound"); unigridAvatarList.HideFilterButton = true; }
protected void Page_Load(object sender, EventArgs e) { // Check license if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.Friends); } userId = QueryHelper.GetInteger("userid", 0); currentUser = CMSContext.CurrentUser; int requestedUserId = QueryHelper.GetInteger("requestid", 0); CurrentMaster.Title.TitleText = GetString("friends.addnewfriend"); CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Friends/request.png"); FriendsRequest.UserID = userId; FriendsRequest.RequestedUserID = requestedUserId; FriendsRequest.OnCheckPermissions += FriendsRequest_OnCheckPermissions; FriendsRequest.IsLiveSite = true; if (requestedUserId != 0) { string fullUserName = String.Empty; UserInfo requestedUser = UserInfoProvider.GetFullUserInfo(requestedUserId); if (requestedUser != null) { fullUserName = Functions.GetFormattedUserName(requestedUser.UserName, requestedUser.FullName, requestedUser.UserNickName, true); } Page.Title = string.Format(GetString("friends.requestfriendshipwith"), HTMLHelper.HTMLEncode(fullUserName)); CurrentMaster.Title.TitleText = Page.Title; } }
protected void Page_Load(object sender, EventArgs e) { // Check 'Read' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.groups", CMSAdminControl.PERMISSION_READ)) { RedirectToCMSDeskAccessDenied("cms.groups", CMSAdminControl.PERMISSION_READ); } cu = CMSContext.CurrentUser; this.messageEditElem.IsLiveSite = false; this.messageEditElem.AdvancedMode = true; this.messageEditElem.MessageID = mMessageId; this.messageEditElem.MessageBoardID = mBoardId; this.messageEditElem.OnCheckPermissions += new CMSAdminControl.CheckPermissionsEventHandler(messageEditElem_OnCheckPermissions); this.messageEditElem.OnBeforeMessageSaved += new OnBeforeMessageSavedEventHandler(messageEditElem_OnBeforeMessageSaved); this.messageEditElem.OnAfterMessageSaved += new OnAfterMessageSavedEventHandler(messageEditElem_OnAfterMessageSaved); // initializes page title control if (this.mMessageId > 0) { this.CurrentMaster.Title.TitleText = GetString("Board.MessageEdit.title"); this.CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Board_Message/object.png"); } else { this.CurrentMaster.Title.TitleText = GetString("Board.MessageNew.title"); this.CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Board_Message/new.png"); } this.CurrentMaster.Title.HelpTopicName = "messages_edit"; this.CurrentMaster.Title.HelpName = "helpTopic"; }
protected void Page_Load(object sender, EventArgs e) { currentUser = CMSContext.CurrentUser; currentObject = (ContactRoleInfo)EditedObject; // Check read permission currentObjectSiteId = currentObject != null ? currentObject.ContactRoleSiteID : siteID; this.CheckReadPermission(currentObjectSiteId); // Preserve site info passed in query CurrentMaster.Title.Breadcrumbs[0, 1] = AddSiteQuery(CurrentMaster.Title.Breadcrumbs[0, 1], siteID); EditForm.RedirectUrlAfterSave = AddSiteQuery(EditForm.RedirectUrlAfterSave, siteID); // Set new site ID for new object if (EditedObject == null) { if ((siteID == UniSelector.US_GLOBAL_RECORD) && ModifyGlobalConfiguration) { EditForm.Data["ContactRoleSiteID"] = DBNull.Value; } else if (this.IsSiteManager && currentUser.UserSiteManagerAdmin) { EditForm.Data["ContactRoleSiteID"] = siteID; } else { EditForm.Data["ContactRoleSiteID"] = CMSContext.CurrentSiteID; } } }
protected void Page_Load(object sender, EventArgs e) { userId = QueryHelper.GetInteger("userid", 0); currentUser = MembershipContext.AuthenticatedUser; // Check license if (DataHelper.GetNotEmpty(RequestContext.CurrentDomain, string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.Friends); } int requestedUserId = QueryHelper.GetInteger("requestid", 0); Page.Title = GetString("friends.addnewfriend"); PageTitle.TitleText = Page.Title; FriendsRequest.UserID = userId; FriendsRequest.RequestedUserID = requestedUserId; FriendsRequest.OnCheckPermissions += FriendsRequest_OnCheckPermissions; if (requestedUserId != 0) { UserInfo requestedUser = UserInfoProvider.GetUserInfo(requestedUserId); string fullUserName = Functions.GetFormattedUserName(requestedUser.UserName, requestedUser.FullName, requestedUser.UserNickName, false); Page.Title = string.Format(GetString("friends.requestfriendshipwith"), HTMLHelper.HTMLEncode(fullUserName)); PageTitle.TitleText = Page.Title; } }
protected void Page_Load(object sender, EventArgs e) { // Check hash if (!QueryHelper.ValidateHash("hash")) { RedirectToAccessDenied(ResHelper.GetString("dialogs.badhashtitle")); } userId = QueryHelper.GetInteger("userId", 0); currentUser = CMSContext.CurrentUser; // Check 'read' permissions if (!currentUser.IsAuthorizedPerResource("CMS.Friends", "Read") && (currentUser.UserID != userId)) { RedirectToAccessDenied("CMS.Friends", "Read"); } // Check license if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.Friends); } if (userId > 0) { // Check that only global administrator can edit global administrator's accounts UserInfo ui = UserInfoProvider.GetUserInfo(userId); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; lblError.Text = GetString("Administration-User_List.ErrorGlobalAdmin"); lblError.Visible = true; } else { string imagePath = GetImageUrl("Objects/CMS_Friend/"); ScriptHelper.RegisterDialogScript(this); FriendsListRequested.UserID = userId; FriendsListRequested.OnCheckPermissions += CheckPermissions; FriendsListRequested.ZeroRowsText = GetString("friends.nouserrequestedfriends"); // Request friend link string script = "function displayRequest(){ \n" + "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Friends/Dialogs/Friends_Request.aspx") + "?userid=" + userId + "&siteid=" + SiteID + "', 'rejectDialog', 480, 350);}"; ScriptHelper.RegisterStartupScript(this, GetType(), "displayModalRequest", ScriptHelper.GetScript(script)); string[,] actions = new string[1, 6]; actions[0, 0] = HeaderActions.TYPE_HYPERLINK; actions[0, 1] = GetString("Friends_List.NewItemCaption"); actions[0, 2] = null; actions[0, 3] = "javascript:displayRequest();"; actions[0, 4] = null; actions[0, 5] = imagePath + "add.png"; CurrentMaster.HeaderActions.Actions = actions; } } }
protected void Page_Load(object sender, EventArgs e) { cu = MembershipContext.AuthenticatedUser; // Check 'Manage' permission if (!cu.IsGroupAdministrator(mGroupId) && !MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.groups", CMSAdminControl.PERMISSION_MANAGE)) { RedirectToAccessDenied("cms.groups", CMSAdminControl.PERMISSION_MANAGE); } messageEditElem.AdvancedMode = true; messageEditElem.MessageID = mMessageId; messageEditElem.MessageBoardID = mBoardId; messageEditElem.OnCheckPermissions += new CMSAdminControl.CheckPermissionsEventHandler(messageEditElem_OnCheckPermissions); messageEditElem.OnBeforeMessageSaved += new OnBeforeMessageSavedEventHandler(messageEditElem_OnBeforeMessageSaved); messageEditElem.OnAfterMessageSaved += new OnAfterMessageSavedEventHandler(messageEditElem_OnAfterMessageSaved); // initializes page title control if (mMessageId > 0) { PageTitle.TitleText = GetString("Board.MessageEdit.title"); } else { PageTitle.TitleText = GetString("Board.MessageNew.title"); } if (!URLHelper.IsPostback()) { messageEditElem.ReloadData(); } }
protected void Page_Load(object sender, EventArgs e) { // Check 'Read' permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.groups", CMSAdminControl.PERMISSION_READ)) { RedirectToAccessDenied("cms.groups", CMSAdminControl.PERMISSION_READ); } cu = MembershipContext.AuthenticatedUser; messageEditElem.IsLiveSite = false; messageEditElem.AdvancedMode = true; messageEditElem.MessageID = mMessageId; messageEditElem.MessageBoardID = mBoardId; messageEditElem.OnCheckPermissions += new CMSAdminControl.CheckPermissionsEventHandler(messageEditElem_OnCheckPermissions); messageEditElem.OnBeforeMessageSaved += new OnBeforeMessageSavedEventHandler(messageEditElem_OnBeforeMessageSaved); messageEditElem.OnAfterMessageSaved += new OnAfterMessageSavedEventHandler(messageEditElem_OnAfterMessageSaved); // initializes page title control if (mMessageId > 0) { PageTitle.TitleText = GetString("Board.MessageEdit.title"); } else { PageTitle.TitleText = GetString("Board.MessageNew.title"); } }
protected void Page_Load(object sender, EventArgs e) { userId = QueryHelper.GetInteger("userId", 0); currentUser = MembershipContext.AuthenticatedUser; if (userId <= 0 && currentUser != null) { userId = currentUser.UserID; } // Check 'read' permissions if (!currentUser.IsAuthorizedPerResource("CMS.Friends", "Read") && (currentUser.UserID != userId)) { RedirectToAccessDenied("CMS.Friends", "Read"); } // Check 'manage' permission bool friendsManagePermission = currentUser.IsAuthorizedPerResource("CMS.Friends", "Manage") || (currentUser.UserID == userId); // Check license if (DataHelper.GetNotEmpty(RequestContext.CurrentDomain, string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.Friends); } // Check that only global administrator can edit global administrator's accounts if (userId > 0) { UserInfo ui = UserInfoProvider.GetUserInfo(userId); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; lblError.Text = GetString("Administration-User_List.ErrorGlobalAdmin"); lblError.Visible = true; } else { ScriptHelper.RegisterDialogScript(this); FriendsList.UserID = userId; FriendsList.OnCheckPermissions += CheckPermissions; FriendsList.ZeroRowsText = GetString("friends.nouserfriends"); // Request friend link string script = "function displayRequest(){ \n" + "modalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Friends/Dialogs/Friends_Request.aspx") + "?userid=" + userId + "&siteid=" + SiteID + "', 'rejectDialog', 810, 460);}"; ScriptHelper.RegisterStartupScript(this, GetType(), "displayModalRequest", ScriptHelper.GetScript(script)); HeaderAction action = new HeaderAction(); action.Text = GetString("Friends_List.NewItemCaption"); action.OnClientClick = "displayRequest();"; action.RedirectUrl = null; action.Enabled = friendsManagePermission; CurrentMaster.HeaderActions.AddAction(action); } } }
protected void Page_Load(object sender, EventArgs e) { currentUser = MembershipContext.AuthenticatedUser; ScriptHelper.RegisterDialogScript(this); FriendsListToApprove.UserID = currentUser.UserID; FriendsListToApprove.OnCheckPermissions += CheckPermissions; FriendsListToApprove.ZeroRowsText = GetString("friends.nowaitingfriends"); }
protected void Page_Load(object sender, EventArgs e) { // Check the current user currentUser = CMSContext.CurrentUser; if (currentUser == null) { return; } // Check 'Read' permission if (currentUser.IsAuthorizedPerResource("cms.blog", "Read")) { readBlogs = true; } if (!RequestHelper.IsPostBack()) { this.drpBlogs.Items.Add(new ListItem(GetString("general.selectall"), "##ALL##")); this.drpBlogs.Items.Add(new ListItem(GetString("blog.selectmyblogs"), "##MYBLOGS##")); } // No cms.blog doc. type if (DataClassInfoProvider.GetDataClass("cms.blog") == null) { RedirectToInformation(GetString("blog.noblogdoctype")); } this.CurrentMaster.DisplaySiteSelectorPanel = true; gridBlogs.OnDataReload += gridBlogs_OnDataReload; gridBlogs.ZeroRowsText = GetString("general.nodatafound"); gridBlogs.ShowActionsMenu = true; gridBlogs.Columns = "BlogID, BlogName, NodeID, DocumentCulture"; // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); BlogInfo bi = new BlogInfo(); gridBlogs.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(bi.ColumnNames.ToArray()), SqlHelperClass.MergeColumns(di.ColumnNames.ToArray())), SqlHelperClass.MergeColumns(nodeClass.ColumnNames.ToArray())); DataClassInfo dci = DataClassInfoProvider.GetDataClass("cms.blogpost"); string classId = ""; StringBuilder script = new StringBuilder(); if (dci != null) { classId = dci.ClassID.ToString(); } // Get script to redirect to new blog post page script.Append("function NewPost(parentId, culture) {", " if (parentId != 0) {", " parent.parent.parent.location.href = \"", ResolveUrl("~/CMSDesk/default.aspx"), "?section=content&action=new&nodeid=\" + parentId + \"&classid=", classId, " &culture=\" + culture;", "}}"); // Generate javascript code ltlScript.Text = ScriptHelper.GetScript(script.ToString()); }
protected void Page_Load(object sender, EventArgs e) { currentUser = MembershipContext.AuthenticatedUser; ScriptHelper.RegisterDialogScript(this); FriendsListRejected.UserID = currentUser.UserID; FriendsListRejected.UseEncapsulation = false; FriendsListRejected.OnCheckPermissions += CheckPermissions; FriendsListRejected.ZeroRowsText = GetString("friends.norejectedfriends"); }
protected override void OnInit(EventArgs e) { base.OnInit(e); // Get current user currentUser = MembershipContext.AuthenticatedUser; // Enable split mode EnableSplitMode = true; }
protected override void OnInit(EventArgs e) { base.OnInit(e); currentUser = MembershipContext.AuthenticatedUser; categoryId = QueryHelper.GetInteger("categoryId", 0); parentCategoryId = QueryHelper.GetInteger("parentId", -1); createPersonal = QueryHelper.GetBoolean("personal", true); }
protected void Page_Load(object sender, EventArgs e) { editedContact = (ContactInfo)CMSPage.EditedObject; currentUser = CMSContext.CurrentUser; siteID = ContactHelper.ObjectSiteID(EditedObject); LoadPermissions(); CheckReadPermissions(); LoadGroupSelector(); LoadContactGroups(); }
protected override void OnInit(EventArgs e) { base.OnInit(e); currentUser = CMSContext.CurrentUser; categoryId = QueryHelper.GetInteger("categoryId", 0); parentCategoryId = QueryHelper.GetInteger("parentId", -1); createPersonal = QueryHelper.GetBoolean("personal", true); catEdit.OnSaved += new EventHandler(catEdit_OnSaved); }
protected override void OnInit(EventArgs e) { base.OnInit(e); // Get current user currentUser = CMSContext.CurrentUser; // Enable split mode EnableSplitMode = true; // Mark selected tab UIContext.ProductTab = ProductTabEnum.Categories; }
protected void Page_Load(object sender, EventArgs e) { // Check the current user currentUser = CMSContext.CurrentUser; if (currentUser == null) { return; } // Check 'Read' permission if (currentUser.IsAuthorizedPerResource("cms.blog", "Read")) { readBlogs = true; } if (!RequestHelper.IsPostBack()) { this.drpBlogs.Items.Add(new ListItem(GetString("general.selectall"), "##ALL##")); this.drpBlogs.Items.Add(new ListItem(GetString("blog.selectmyblogs"), "##MYBLOGS##")); } // No cms.blog doc. type if (DataClassInfoProvider.GetDataClass("cms.blog") == null) { RedirectToInformation(GetString("blog.noblogdoctype")); } this.CurrentMaster.DisplaySiteSelectorPanel = true; this.gridBlogs.OnDataReload += new OnDataReloadEventHandler(gridBlogs_OnDataReload); this.gridBlogs.ZeroRowsText = GetString("general.nodatafound"); DataClassInfo dci = DataClassInfoProvider.GetDataClass("cms.blogpost"); string classId = ""; string script = ""; if (dci != null) { classId = dci.ClassID.ToString(); } // Get script to redirect to new blog post page script += "function NewPost(parentId, culture) { \n"; script += " if (parentId != 0) { \n"; script += " parent.parent.parent.location.href = \"" + ResolveUrl("~/CMSDesk/default.aspx") + "?section=content&action=new&nodeid=\" + parentId + \"&classid=" + classId + "&culture=\" + culture;"; script += "}} \n"; // Generate javascript code ltlScript.Text = ScriptHelper.GetScript(script); }
protected void Page_Load(object sender, EventArgs e) { currentUser = CMSContext.CurrentUser; if (currentUser == null) { return; } // No cms.blog doc. type if (DataClassInfoProvider.GetDataClass("cms.blog") == null) { RedirectToInformation(GetString("blog.noblogdoctype")); } // Check if user is authorized to manage isAuthorized = currentUser.IsAuthorizedPerResource("CMS.Blog", "Manage") || (currentUser.IsAuthorizedPerClassName("cms.blog", "Manage", CMSContext.CurrentSiteName) && currentUser.IsAuthorizedPerClassName("cms.blogpost", "Manage", CMSContext.CurrentSiteName)); // Register grid events gridBlogs.OnExternalDataBound += gridBlogs_OnExternalDataBound; gridBlogs.OnDataReload += gridBlogs_OnDataReload; gridBlogs.ShowActionsMenu = true; gridBlogs.Columns = "BlogID, ClassName, BlogName, NodeID, DocumentCulture, NodeOwner, BlogModerators"; // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); BlogInfo bi = new BlogInfo(); gridBlogs.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(bi.ColumnNames), SqlHelperClass.MergeColumns(di.ColumnNames)), SqlHelperClass.MergeColumns(nodeClass.ColumnNames)); // Get ClassID of the 'cms.blogpost' class DataClassInfo dci = DataClassInfoProvider.GetDataClass("cms.blogpost"); string classId = ""; string script = ""; if (dci != null) { classId = dci.ClassID.ToString(); } // Get script to redirect to new blog post page script += "function NewPost(parentId, culture) { \n"; script += " if (parentId != 0) { \n"; script += " parent.parent.parent.location.href = \"" + ResolveUrl("~/CMSDesk/default.aspx") + "?section=content&action=new&nodeid=\" + parentId + \"&classid=" + classId + "&culture=\" + culture;"; script += "}} \n"; // Generate javascript code ltlScript.Text = ScriptHelper.GetScript(script); }
protected override void CreateChildControls() { // Enable split mode EnableSplitMode = true; user = CMSContext.CurrentUser; if (Node != null) { CMSContext.EditedObject = Node; ucHierarchy.PreviewObjectName = Node.NodeAliasPath; ucHierarchy.AddContentParameter(new UILayoutValue("PreviewObject", Node)); ucHierarchy.DefaultAliasPath = Node.NodeAliasPath; ucHierarchy.IgnoreSessionValues = true; } base.CreateChildControls(); }
protected void Page_Load(object sender, EventArgs e) { userId = QueryHelper.GetInteger("userId", 0); currentUser = CMSContext.CurrentUser; // Check 'read' permissions if (!currentUser.IsAuthorizedPerResource("CMS.Friends", "Read") && (currentUser.UserID != userId)) { RedirectToAccessDenied("CMS.Friends", "Read"); } // Check license if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.Friends); } }
protected void Page_Load(object sender, EventArgs e) { // Check hash if (!QueryHelper.ValidateHash("hash")) { RedirectToAccessDenied(ResHelper.GetString("dialogs.badhashtitle")); } userId = QueryHelper.GetInteger("userId", 0); currentUser = CMSContext.CurrentUser; // Check 'read' permissions if (!currentUser.IsAuthorizedPerResource("CMS.Friends", "Read") && (currentUser.UserID != userId)) { RedirectToAccessDenied("CMS.Friends", "Read"); } // Check license if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.Friends); } if (userId > 0) { // Check that only global administrator can edit global administrator's accounts UserInfo ui = UserInfoProvider.GetUserInfo(userId); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; lblError.Text = GetString("Administration-User_List.ErrorGlobalAdmin"); lblError.Visible = true; } else { ScriptHelper.RegisterDialogScript(this); FriendsListRejected.UserID = userId; FriendsListRejected.UseEncapsulation = false; FriendsListRejected.OnCheckPermissions += CheckPermissions; FriendsListRejected.ZeroRowsText = GetString("friends.nouserrejectedfriends"); } } }
protected void Page_Load(object sender, EventArgs e) { // Check UI personalization CheckUIElementAccessHierarchical(ModuleName.ONLINEMARKETING, "ContactContactGroups"); editedContact = (ContactInfo)EditedObject; if (editedContact == null) { RedirectToAccessDenied(GetString("general.invalidparameters")); } currentUser = MembershipContext.AuthenticatedUser; siteID = ContactHelper.ObjectSiteID(EditedObject); LoadPermissions(); CheckReadPermission(); LoadGroupSelector(); LoadContactGroups(); }
protected void Page_Load(object sender, EventArgs e) { // Check the current user currentUser = MembershipContext.AuthenticatedUser; if (currentUser == null) { return; } // Check 'Read' permission if (currentUser.IsAuthorizedPerResource("cms.blog", "Read")) { readBlogs = true; } // Prepare permissions for external data bound contentExploreTreePermission = currentUser.IsAuthorizedPerResource("cms.content", "exploretree"); contentReadPermission = currentUser.IsAuthorizedPerResource("cms.content", "read"); contentCreatePermission = currentUser.IsAuthorizedPerResource("cms.content", "create"); if (!RequestHelper.IsPostBack()) { drpBlogs.Items.Add(new ListItem(GetString("general.selectall"), "##ALL##")); drpBlogs.Items.Add(new ListItem(GetString("blog.selectmyblogs"), "##MYBLOGS##")); } // No cms.blog doc. type if (DataClassInfoProvider.GetDataClassInfo("cms.blog") == null) { RedirectToInformation(GetString("blog.noblogdoctype")); } CurrentMaster.DisplaySiteSelectorPanel = true; gridBlogs.OnDataReload += gridBlogs_OnDataReload; gridBlogs.ZeroRowsText = GetString("general.nodatafound"); gridBlogs.ShowActionsMenu = true; gridBlogs.Columns = "BlogID, BlogName, NodeID, DocumentCulture"; gridBlogs.OnExternalDataBound += gridBlogs_OnExternalDataBound; // Get all possible columns to retrieve gridBlogs.AllColumns = SqlHelper.JoinColumnList(ObjectTypeManager.GetColumnNames(BlogInfo.OBJECT_TYPE, PredefinedObjectType.NODE, PredefinedObjectType.DOCUMENTLOCALIZATION)); }
protected void Page_Load(object sender, EventArgs e) { userId = QueryHelper.GetInteger("userId", 0); currentUser = MembershipContext.AuthenticatedUser; if (userId <= 0 && currentUser != null) { userId = currentUser.UserID; } // Check 'read' permissions if (!currentUser.IsAuthorizedPerResource("CMS.Friends", "Read") && (currentUser.UserID != userId)) { RedirectToAccessDenied("CMS.Friends", "Read"); } // Check license if (DataHelper.GetNotEmpty(RequestContext.CurrentDomain, string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.Friends); } if (userId > 0) { // Check that only global administrator can edit global administrator's accounts UserInfo ui = UserInfoProvider.GetUserInfo(userId); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; lblError.Text = GetString("Administration-User_List.ErrorGlobalAdmin"); lblError.Visible = true; } else { ScriptHelper.RegisterDialogScript(this); FriendsListToApprove.UserID = userId; FriendsListToApprove.OnCheckPermissions += CheckPermissions; FriendsListToApprove.ZeroRowsText = GetString("friends.nouserwaitingfriends"); } } }
/// <summary> /// Init event handler. /// </summary> protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Setup basic form on live site formCustom.AllowMacroEditing = false; formCustom.IsLiveSite = IsLiveSite; // Load settings if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Try to find the widget variant in the database and set its VariantID if (IsNewVariant) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(properties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = 0; if (VariantMode == VariantModeEnum.MVT) { variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName); } else if (VariantMode == VariantModeEnum.ContentPersonalization) { variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName); } // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } EnsureDashboard(); if (!String.IsNullOrEmpty(WidgetId) && !IsInline) { // Get page info try { pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId, CultureCode); } catch (PageNotFoundException) { // Do not throw exception if page info not found (e.g. bad alias path) } if (pi == null) { lblInfo.Text = GetString("Widgets.Properties.aliasnotfound"); lblInfo.Visible = true; pnlFormArea.Visible = false; return; } // Get template instance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi); if (!IsNewWidget) { // Get the instance of widget widgetInstance = templateInstance.GetWebPart(InstanceGUID, WidgetId); if (widgetInstance == null) { lblInfo.Text = GetString("Widgets.Properties.WidgetNotFound"); lblInfo.Visible = true; pnlFormArea.Visible = false; return; } if ((VariantID > 0) && (widgetInstance != null) && (widgetInstance.PartInstanceVariants != null)) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { widgetInstance = pi.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId); widgetInstance = widgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID)); // Set the widget variant mode if (widgetInstance != null) { VariantMode = widgetInstance.VariantMode; } } else { // Not authorized for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } // Get widget info by widget name(widget type) wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType); } // Widget instance hasn't created yet else { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } // Keep xml version if (widgetInstance != null) { xmlVersion = widgetInstance.XMLVersion; } CMSPage.EditedObject = wi; zoneType = ZoneType; // Get the zone to which it inserts WebPartZoneInstance zone = templateInstance.GetZone(ZoneId); if ((zoneType == WidgetZoneTypeEnum.None) && (zone != null)) { zoneType = zone.WidgetZoneType; } // Check security CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser; switch (zoneType) { // Group zone => Only group widgets and group admin case WidgetZoneTypeEnum.Group: // Should always be, only group widget are allowed in group zone if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(pi.NodeGroupID) && ((PortalContext.ViewMode != ViewModeEnum.Design) || ((PortalContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design")))))) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for editor zones case WidgetZoneTypeEnum.Editor: if (!wi.WidgetForEditor) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for user zones case WidgetZoneTypeEnum.User: if (!wi.WidgetForUser) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for dashboard zones case WidgetZoneTypeEnum.Dashboard: if (!wi.WidgetForDashboard) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; } // Check security if ((zoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated())) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } // Get form schemas wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true); if (fi != null) { // Check if there are some editable properties var ffi = fi.GetFields(true, false).ToList <FormFieldInfo>(); if ((ffi == null) || (ffi.Count == 0)) { lblInfo.Visible = true; lblInfo.Text = GetString("widgets.emptyproperties"); } // Get datarows with required columns DataRow dr = fi.GetDataRow(); // Load default values for new widget if (IsNewWidget || (xmlVersion > 0)) { fi.LoadDefaultValues(dr); fi.LoadDefaultValues(dr, wi.WidgetDefaultValues, true); } if (IsNewWidget) { // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(wi.WidgetDisplayName)); } // Load values from existing widget LoadDataRowFromWidget(dr, fi); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES; } } if (IsInline) { // Load text definition from session string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), string.Empty); if (String.IsNullOrEmpty(definition)) { definition = Request.Form[hdnWidgetDefinition.UniqueID]; } else { hdnWidgetDefinition.Value = definition; } Hashtable parameters = null; if (IsNewWidget) { // New widget - load widget info by id if (!String.IsNullOrEmpty(WidgetId)) { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } else { // Try to get widget from codename mName = QueryHelper.GetString("WidgetName", String.Empty); wi = WidgetInfoProvider.GetWidgetInfo(mName); } } else { if (definition == null) { DisplayError("widget.failedtoload"); return; } // Parse definition parameters = CMSDialogHelper.GetHashTableFromString(definition); // Trim control name if (parameters["name"] != null) { mName = parameters["name"].ToString(); } wi = WidgetInfoProvider.GetWidgetInfo(mName); } if (wi == null) { DisplayError("widget.failedtoload"); return; } // If widget cant be used as inline if (!wi.WidgetForInline) { DisplayError("widget.cantbeusedasinline"); return; } // Test permission for user CurrentUserInfo currentUser = MembershipContext.AuthenticatedUser; if (!WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated())) { mIsValidWidget = false; OnNotAllowed(this, null); } // If user is editor, more properties are shown WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User; if (currentUser.IsEditor) { zoneType = WidgetZoneTypeEnum.Editor; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); FormInfo zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType); FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true); if (fi != null) { // Check if there are some editable properties mFields = fi.GetFields(true, true); if ((mFields == null) || !mFields.Any()) { lblInfo.Visible = true; lblInfo.Text = GetString("widgets.emptyproperties"); } // Get datarows with required columns DataRow dr = PortalHelper.CombineWithDefaultValues(fi, wi); if (IsNewWidget) { // Load default values for new widget fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible); } else { foreach (string key in parameters.Keys) { object value = parameters[key]; // Test if given property exists if (dr.Table.Columns.Contains(key) && (value != null)) { try { dr[key] = DataHelper.ConvertValue(value, dr.Table.Columns[key].DataType); } catch { } } } } // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES; } } }
public BinSettingsContainer(CurrentUserInfo user, What what) : this() { User = user; CurrentWhat = what; }
protected void Page_Load(object sender, EventArgs e) { // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Get site info currentSiteId = CMSContext.CurrentSiteID; currentSiteName = CMSContext.CurrentSiteName; // Initialize current user for the async actions currentUser = CMSContext.CurrentUser; serverId = QueryHelper.GetInteger("serverid", 0); if (RequestHelper.CausedPostback(btnSyncComplete)) { SyncComplete(); } else { if (!RequestHelper.IsCallback()) { int nodeId = QueryHelper.GetInteger("nodeid", 0); aliasPath = "/"; // Get the document node if (nodeId > 0) { TreeProvider tree = new TreeProvider(currentUser); TreeNode node = tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES); if (node != null) { aliasPath = node.NodeAliasPath; } } // Setup title titleElem.TitleText = GetString("Synchronization.Title"); titleElem.TitleImage = GetImageUrl("CMSModules/CMS_Staging/synchronization.png"); if (!RequestHelper.CausedPostback(btnCurrent, btnSubtree, btnSyncSelected, btnSyncAll)) { // Check 'Manage servers' permission if (!currentUser.IsAuthorizedPerResource("cms.staging", "ManageDocumentsTasks")) { RedirectToAccessDenied("cms.staging", "ManageDocumentsTasks"); } // Register the dialog script ScriptHelper.RegisterDialogScript(this); ltlScript.Text += ScriptHelper.GetScript("function ConfirmDeleteTask(taskId) { return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDelete")) + "); }"); ltlScript.Text += ScriptHelper.GetScript("function CompleteSync(){" + Page.ClientScript.GetPostBackEventReference(btnSyncComplete, null) + "}"); // Initialize grid tasksUniGrid.OnExternalDataBound += tasksUniGrid_OnExternalDataBound; tasksUniGrid.OnAction += tasksUniGrid_OnAction; tasksUniGrid.OnDataReload += tasksUniGrid_OnDataReload; tasksUniGrid.ShowActionsMenu = true; tasksUniGrid.Columns = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount"; TaskInfo ti = new TaskInfo(); tasksUniGrid.AllColumns = SqlHelperClass.MergeColumns(ti.ColumnNames.ToArray()); // Initialize images viewImage = GetImageUrl("Design/Controls/UniGrid/Actions/View.png"); deleteImage = GetImageUrl("Design/Controls/UniGrid/Actions/Delete.png"); syncImage = GetImageUrl("Design/Controls/UniGrid/Actions/Synchronize.png"); imgCurrent.ImageUrl = GetImageUrl("CMSModules/CMS_Staging/synccurrent.png"); imgSubtree.ImageUrl = GetImageUrl("CMSModules/CMS_Staging/syncsubtree.png"); // Initialize tooltips syncTooltip = GetString("general.synchronize"); deleteTooltip = GetString("general.delete"); viewTooltip = GetString("general.view"); syncCurrent = GetString("Tasks.SyncCurrent"); syncSubtree = GetString("Tasks.SyncSubtree"); plcContent.Visible = true; // Initialize buttons btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;"); btnCancel.Text = GetString("General.Cancel"); btnDeleteAll.Text = GetString("Tasks.DeleteAll"); btnDeleteSelected.Text = GetString("Tasks.DeleteSelected"); btnSyncAll.Text = GetString("Tasks.SyncAll"); btnSyncSelected.Text = GetString("Tasks.SyncSelected"); btnSyncSelected.OnClientClick = "return !" + tasksUniGrid.GetCheckSelectionScript(); btnDeleteAll.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");"; btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");"; pnlLog.Visible = false; } } } ctlAsync.OnFinished += ctlAsync_OnFinished; ctlAsync.OnError += ctlAsync_OnError; ctlAsync.OnRequestLog += ctlAsync_OnRequestLog; ctlAsync.OnCancel += ctlAsync_OnCancel; }
/// <summary> /// Updates the current Group or creates new if no GroupID is present. /// </summary> public void SaveData() { if (!CheckPermissions("cms.groups", PERMISSION_MANAGE, GroupID)) { return; } // Trim display name and code name string displayName = txtDisplayName.Text.Trim(); string codeName = txtCodeName.Text.Trim(); // Validate form entries string errorMessage = ValidateForm(displayName, codeName); if (errorMessage == "") { GroupInfo group = null; try { bool newGroup = false; // Update existing item if ((GroupID > 0) && (gi != null)) { group = gi; } else { group = new GroupInfo(); newGroup = true; } if (group != null) { if (displayName != group.GroupDisplayName) { // Refresh a breadcrumb if used in the tabs layout ScriptHelper.RefreshTabHeader(Page, string.Empty); } if (DisplayAdvanceOptions) { // Update Group fields group.GroupDisplayName = displayName; group.GroupName = codeName; group.GroupNodeGUID = ValidationHelper.GetGuid(groupPageURLElem.Value, Guid.Empty); } if (AllowChangeGroupDisplayName && IsLiveSite) { group.GroupDisplayName = displayName; } group.GroupDescription = txtDescription.Text; group.GroupAccess = GetGroupAccess(); group.GroupSiteID = SiteID; group.GroupApproveMembers = GetGroupApproveMembers(); group.GroupSendJoinLeaveNotification = chkJoinLeave.Checked; group.GroupSendWaitingForApprovalNotification = chkWaitingForApproval.Checked; groupPictureEdit.UpdateGroupPicture(group); // If new group was created if (newGroup) { // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user CurrentUserInfo user = CMSContext.CurrentUser; if (user != null) { group.GroupCreatedByUserID = user.UserID; group.GroupApprovedByUserID = user.UserID; group.GroupApproved = true; } } if (!IsLiveSite && (group.GroupNodeGUID == Guid.Empty)) { plcStyleSheetSelector.Visible = false; } // Save theme int selectedSheetID = ValidationHelper.GetInteger(ctrlSiteSelectStyleSheet.Value, 0); if (plcStyleSheetSelector.Visible) { if (group.GroupNodeGUID != Guid.Empty) { // Save theme for every site culture var cultures = CultureInfoProvider.GetSiteCultureCodes(CMSContext.CurrentSiteName); if (cultures != null) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Return class name of selected tree node TreeNode treeNode = tree.SelectSingleNode(group.GroupNodeGUID, TreeProvider.ALL_CULTURES, CMSContext.CurrentSiteName); if (treeNode != null) { // Return all culture version of node DataSet ds = tree.SelectNodes(CMSContext.CurrentSiteName, null, TreeProvider.ALL_CULTURES, false, treeNode.NodeClassName, "NodeGUID ='" + group.GroupNodeGUID + "'", String.Empty, -1, false); if (!DataHelper.DataSourceIsEmpty(ds)) { // Loop through all nodes foreach (DataRow dr in ds.Tables[0].Rows) { // Create node and set tree provider for user validation TreeNode node = TreeNode.New(dr, ValidationHelper.GetString(dr["className"], String.Empty)); node.TreeProvider = tree; // Update stylesheet id if set if (selectedSheetID == 0) { node.SetValue("DocumentStylesheetID", -1); } else { node.DocumentStylesheetID = selectedSheetID; } node.Update(); } } } } } } if (!IsLiveSite && (group.GroupNodeGUID != Guid.Empty)) { plcStyleSheetSelector.Visible = true; } if (plcOnline.Visible) { // On-line marketing setting is visible => set flag according to checkbox group.GroupLogActivity = chkLogActivity.Checked; } else { // On-line marketing setting is not visible => set flag to TRUE as default value group.GroupLogActivity = true; } // Save Group in the database GroupInfoProvider.SetGroupInfo(group); groupPictureEdit.GroupInfo = group; txtDisplayName.Text = group.GroupDisplayName; txtCodeName.Text = group.GroupName; // Flush cached information CMSContext.CurrentDocument = null; CMSContext.CurrentPageInfo = null; CMSContext.CurrentDocumentStylesheet = null; // Display information on success ShowChangesSaved(); // If new group was created if (newGroup) { GroupID = group.GroupID; RaiseOnSaved(); } } } catch (Exception ex) { // Display error message ShowError(GetString("general.saveerror"), ex.Message, null); } } else { // Display error message ShowError(errorMessage); } }
protected void Page_Load(object sender, EventArgs e) { // Check whether user is global admin CurrentUserInfo currentUser = CMSContext.CurrentUser; if (!currentUser.UserSiteManagerAdmin) { RedirectToAccessDenied(GetString("general.notauthorizedtopage")); } // Set dialog body class CurrentMaster.PanelBody.CssClass = "DialogPageBody"; selectElem.ShowInheritedWebparts = false; selectElem.ShowWidgetOnlyWebparts = true; // Proceeds the current item selection string javascript = @" function SelectCurrentWebPart() { SelectWebPart(selectedValue) ; } function SelectWebPart(value) { if( value != null ) { window.close(); if ( wopener.OnSelectWebPart ) { wopener.OnSelectWebPart(value); } } else { alert(document.getElementById('" + hdnMessage.ClientID + @"').value); } } // Cancel action function Cancel() { window.close(); } "; ScriptHelper.RegisterStartupScript(this, typeof(string), "WebPartSelector", ScriptHelper.GetScript(javascript)); // Set name of selection function selectElem.SelectFunction = "SelectWebPart"; // Set the title and icon string title = GetString("portalengine-webpartselection.title"); this.Page.Title = title; this.CurrentMaster.Title.TitleText = title; this.CurrentMaster.Title.TitleImage = GetImageUrl("Objects/CMS_WebPart/object.png"); // Remove default css class if (this.CurrentMaster.PanelBody != null) { Panel pnl = this.CurrentMaster.PanelBody.FindControl("pnlContent") as Panel; if (pnl != null) { pnl.CssClass = String.Empty; } } }
protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); // Check site availability if (!ResourceSiteInfoProvider.IsResourceOnSite("CMS.Reporting", CMSContext.CurrentSiteName)) { RedirectToResourceNotAvailableOnSite("CMS.Reporting"); } CurrentUserInfo user = CMSContext.CurrentUser; // Check 'Read' permission if (!user.IsAuthorizedPerResource("CMS.Reporting", "Read")) { RedirectToAccessDenied("CMS.Reporting", "Read"); } IFormatProvider culture = DateTimeHelper.DefaultIFormatProvider; IFormatProvider currentCulture = new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentUICulture.IetfLanguageTag); // Get report name from querystring reportName = QueryHelper.GetString("reportname", String.Empty); // Get ReportInfo object ReportInfo ri = ReportInfoProvider.GetReportInfo(reportName); if (ri != null) { // Get parameters from querystring string[] httpParameters = QueryHelper.GetString("parameters", String.Empty).Split(";".ToCharArray()); if (httpParameters.Length > 1) { string[] parameters = new string[httpParameters.Length / 2]; DataTable dtp = new DataTable(); // Create correct columns and put values in it for (int i = 0; i < httpParameters.Length; i = i + 2) { if (ValidationHelper.GetDateTime(httpParameters[i + 1], DataHelper.DATETIME_NOT_SELECTED, culture) == DataHelper.DATETIME_NOT_SELECTED) { dtp.Columns.Add(httpParameters[i]); parameters[i / 2] = httpParameters[i + 1].Replace(AnalyticsHelper.PARAM_SEMICOLON, ";"); } else { dtp.Columns.Add(httpParameters[i], typeof(DateTime)); parameters[i / 2] = Convert.ToDateTime(httpParameters[i + 1], culture).ToString(currentCulture); } } dtp.Rows.Add(parameters); dtp.AcceptChanges(); DisplayReport1.LoadFormParameters = false; DisplayReport1.ReportName = ri.ReportName; DisplayReport1.DisplayFilter = false; DisplayReport1.ReportParameters = dtp.Rows[0]; } else { DisplayReport1.ReportName = ri.ReportName; DisplayReport1.DisplayFilter = false; } Page.Title = GetString("Report_Print.lblPrintReport") + " " + HTMLHelper.HTMLEncode(ri.ReportDisplayName); } }
protected void Page_Load(object sender, EventArgs e) { currentUser = MembershipContext.AuthenticatedUser; // Hide the add MVT/CP variant when Manage permission is not allowed if (!currentUser.IsAuthorizedPerResource("cms.mvtest", "Manage")) { plcAddMVTVariant.Visible = false; } if (!currentUser.IsAuthorizedPerResource("cms.contentpersonalization", "Manage")) { plcAddCPVariant.Visible = false; } string click = null; // Main menu iProperties.Text = ResHelper.GetString("WebPartMenu.IconProperties", UICulture); iProperties.Attributes.Add("onclick", "ContextConfigureWebPart();"); // Up menu - Bottom iTop.Text = ResHelper.GetString("UpMenu.IconTop", UICulture); iForwardAll.Text = ResHelper.GetString("WebPartMenu.IconForward", UICulture); click = "ContextMoveWebPartTop();"; iForwardAll.Attributes.Add("onclick", click); iTop.Attributes.Add("onclick", click); // Up iUp.Text = ResHelper.GetString("WebPartMenu.IconUp", UICulture); click = "ContextMoveWebPartUp();"; iUp.Attributes.Add("onclick", click); // Down iDown.Text = ResHelper.GetString("WebPartMenu.IconDown", UICulture); click = "ContextMoveWebPartDown();"; iDown.Attributes.Add("onclick", click); // Down menu - Bottom iBottom.Text = ResHelper.GetString("DownMenu.IconBottom", UICulture); iBackwardAll.Text = ResHelper.GetString("WebPartMenu.IconBackward", UICulture); click = "ContextMoveWebPartBottom();"; iBackwardAll.Attributes.Add("onclick", click); iBottom.Attributes.Add("onclick", click); // Move to iMoveTo.Text = ResHelper.GetString("WebPartMenu.IconMoveTo", UICulture); // Copy iCopy.Text = ResHelper.GetString("WebPartMenu.copy", UICulture); iCopy.Attributes.Add("onclick", "ContextCopyWebPart(this);"); // Paste iPaste.Text = ResHelper.GetString("WebPartMenu.paste", UICulture); iPaste.Attributes.Add("onclick", "ContextPasteWebPart(this);"); iPaste.ToolTip = ResHelper.GetString("WebPartMenu.pasteTooltip", UICulture); // Delete iDelete.Text = ResHelper.GetString("general.remove", UICulture); iDelete.Attributes.Add("onclick", "ContextRemoveWebPart();"); // Add new MVT variant lblAddMVTVariant.Text = ResHelper.GetString("WebPartMenu.AddWebPartVariant", UICulture); pnlAddMVTVariant.Attributes.Add("onclick", "ContextAddWebPartMVTVariant();"); // Add new Content personalization variant lblAddCPVariant.Text = ResHelper.GetString("WebPartMenu.AddWebPartVariant", UICulture); pnlAddCPVariant.Attributes.Add("onclick", "ContextAddWebPartCPVariant();"); // List all variants lblMVTVariants.Text = ResHelper.GetString("WebPartMenu.WebPartMVTVariants", UICulture); lblCPVariants.Text = ResHelper.GetString("WebPartMenu.WebPartPersonalizationVariants", UICulture); // No MVT variants lblNoWebPartMVTVariants.Text = ResHelper.GetString("ZoneMenu.NoVariants", UICulture); // No CP variants lblNoWebPartCPVariants.Text = ResHelper.GetString("ZoneMenu.NoVariants", UICulture); if (PortalManager.CurrentPlaceholder != null) { // Build the list of web part zones var webPartZones = new List <CMSWebPartZone>(); if (PortalManager.CurrentPlaceholder.WebPartZones != null) { foreach (CMSWebPartZone zone in PortalManager.CurrentPlaceholder.WebPartZones) { // Add only standard zones to the list if ((zone.ZoneInstance.WidgetZoneType == WidgetZoneTypeEnum.None) && zone.AllowModifyWebPartCollection) { webPartZones.Add(zone); } } } repZones.DataSource = webPartZones; repZones.DataBind(); } if (PortalContext.MVTVariantsEnabled || PortalContext.ContentPersonalizationEnabled) { var loadingMenu = new ContextMenuItem { ResourceString = "ContextMenu.Loading" }.GetRenderedHTML(); menuMoveToZoneVariants.LoadingContent = loadingMenu; menuMoveToZoneVariants.OnReloadData += menuMoveToZoneVariants_OnReloadData; repMoveToZoneVariants.ItemDataBound += repMoveToZoneVariants_ItemDataBound; // Display the MVT menu part in the Pages->Design only. Hide the context menu in the PageTemplates->Design if (PortalContext.MVTVariantsEnabled && (DocumentContext.CurrentPageInfo != null) && (DocumentContext.CurrentPageInfo.DocumentID > 0)) { // Set Display='none' for the MVT panel. Show dynamically only if required. pnlContextMenuMVTVariants.Visible = true; pnlContextMenuMVTVariants.Style.Add("display", "none"); menuWebPartMVTVariants.LoadingContent = loadingMenu; menuWebPartMVTVariants.OnReloadData += menuWebPartMVTVariants_OnReloadData; repWebPartMVTVariants.ItemDataBound += repWebPartVariants_ItemDataBound; string script = "webPartMVTVariantContextMenuId = '" + pnlContextMenuMVTVariants.ClientID + "';"; ScriptHelper.RegisterStartupScript(this, typeof(string), "webPartMVTVariantContextMenuId", ScriptHelper.GetScript(script)); } // Display the Content personalization menu part in the Pages->Design only. Hide the context menu in the PageTemplates->Design if ((PortalContext.ContentPersonalizationEnabled) && (DocumentContext.CurrentPageInfo != null) && (DocumentContext.CurrentPageInfo.DocumentID > 0)) { // Set Display='none' for the MVT panel. Show dynamically only if required. pnlContextMenuCPVariants.Visible = true; pnlContextMenuCPVariants.Style.Add("display", "none"); menuWebPartCPVariants.LoadingContent = loadingMenu; menuWebPartCPVariants.OnReloadData += menuWebPartCPVariants_OnReloadData; repWebPartCPVariants.ItemDataBound += repWebPartVariants_ItemDataBound; string script = "webPartCPVariantContextMenuId = '" + pnlContextMenuCPVariants.ClientID + "';"; ScriptHelper.RegisterStartupScript(this, typeof(string), "webPartCPVariantContextMenuId", ScriptHelper.GetScript(script)); } } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { plcOther.Controls.Clear(); if (CMSContext.CurrentUser.IsAuthenticated()) { // Set the layout of tab menu tabMenu.TabControlLayout = BasicTabControl.GetTabMenuLayout(TabControlLayout); // Remove 'saved' parameter from querystring string absoluteUri = URLHelper.RemoveParameterFromUrl(URLRewriter.CurrentURL, "saved"); CurrentUserInfo currentUser = CMSContext.CurrentUser; // Get customer info GeneralizedInfo customer = ModuleCommands.ECommerceGetCustomerInfoByUserId(currentUser.UserID); bool userIsCustomer = (customer != null); // Get friends enabled setting bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(CMSContext.CurrentSiteName); // Get customer ID int customerId = 0; if (userIsCustomer) { customerId = ValidationHelper.GetInteger(customer.ObjectID, 0); } // Selected page url string selectedPage = string.Empty; // Menu initialization tabMenu.UrlTarget = "_self"; ArrayList activeTabs = new ArrayList(); string tabName = string.Empty; int arraySize = 0; if (DisplayMyPersonalSettings) { arraySize++; } if (DisplayMyMessages) { arraySize++; } // Handle 'Notifications' tab displaying bool hideUnavailableUI = SettingsKeyProvider.GetBoolValue("CMSHideUnavailableUserInterface"); bool showNotificationsTab = (DisplayMyNotifications && ModuleEntry.IsModuleLoaded(ModuleEntry.NOTIFICATIONS) && (!hideUnavailableUI || LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.Notifications))); bool isWindowsAuthentication = RequestHelper.IsWindowsAuthentication(); if (showNotificationsTab) { arraySize++; } if (DisplayMyFriends && friendsEnabled) { arraySize++; } if (DisplayMyDetails && userIsCustomer) { arraySize++; } if (DisplayMyCredits && userIsCustomer) { arraySize++; } if (DisplayMyAddresses && userIsCustomer) { arraySize++; } if (DisplayMyOrders && userIsCustomer) { arraySize++; } if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication) { arraySize++; } if (DisplayMySubscriptions) { arraySize++; } if (this.DisplayMyMemberships) { arraySize++; } if (DisplayMyCategories) { arraySize++; } tabMenu.Tabs = new string[arraySize, 5]; if (DisplayMyPersonalSettings) { tabName = personalTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyPersonalSettings"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, personalTab)); if (currentUser != null) { selectedPage = tabName; } } // These items can be displayed only for customer if (userIsCustomer && ModuleEntry.IsModuleLoaded(ModuleEntry.ECOMMERCE)) { if (DisplayMyDetails) { // Try to load the control dynamically (if available) ucMyDetails = Page.LoadControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyDetails.ascx") as CMSAdminControl; if (ucMyDetails != null) { ucMyDetails.ID = "ucMyDetails"; plcOther.Controls.Add(ucMyDetails); tabName = detailsTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyDetails"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, detailsTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if (DisplayMyAddresses) { // Try to load the control dynamically (if available) ucMyAddresses = Page.LoadControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyAddresses.ascx") as CMSAdminControl; if (ucMyAddresses != null) { ucMyAddresses.ID = "ucMyAddresses"; plcOther.Controls.Add(ucMyAddresses); tabName = addressesTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyAddresses"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, addressesTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if (DisplayMyOrders) { // Try to load the control dynamically (if available) ucMyOrders = Page.LoadControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyOrders.ascx") as CMSAdminControl; if (ucMyOrders != null) { ucMyOrders.ID = "ucMyOrders"; plcOther.Controls.Add(ucMyOrders); tabName = ordersTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyOrders"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, ordersTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if (DisplayMyCredits) { // Try to load the control dynamically (if available) ucMyCredit = Page.LoadControl("~/CMSModules/Ecommerce/Controls/MyDetails/MyCredit.ascx") as CMSAdminControl; if (ucMyCredit != null) { ucMyCredit.ID = "ucMyCredit"; plcOther.Controls.Add(ucMyCredit); tabName = creditTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyCredit"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, creditTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } } if (DisplayChangePassword && !currentUser.IsExternal && !isWindowsAuthentication) { tabName = passwordTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.ChangePassword"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, passwordTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } if ((ucMyNotifications == null) && showNotificationsTab) { // Try to load the control dynamically (if available) ucMyNotifications = Page.LoadControl("~/CMSModules/Notifications/Controls/UserNotifications.ascx") as CMSAdminControl; if (ucMyNotifications != null) { ucMyNotifications.ID = "ucMyNotifications"; plcOther.Controls.Add(ucMyNotifications); tabName = notificationsTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyNotifications"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, notificationsTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if ((ucMyMessages == null) && DisplayMyMessages && ModuleEntry.IsModuleLoaded(ModuleEntry.MESSAGING)) { // Try to load the control dynamically (if available) ucMyMessages = Page.LoadControl("~/CMSModules/Messaging/Controls/MyMessages.ascx") as CMSAdminControl; if (ucMyMessages != null) { ucMyMessages.ID = "ucMyMessages"; plcOther.Controls.Add(ucMyMessages); tabName = messagesTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyMessages"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, messagesTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if ((ucMyFriends == null) && DisplayMyFriends && ModuleEntry.IsModuleLoaded(ModuleEntry.COMMUNITY) && friendsEnabled) { // Try to load the control dynamically (if available) ucMyFriends = Page.LoadControl("~/CMSModules/Friends/Controls/MyFriends.ascx") as CMSAdminControl; if (ucMyFriends != null) { ucMyFriends.ID = "ucMyFriends"; plcOther.Controls.Add(ucMyFriends); tabName = friendsTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyFriends"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, friendsTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } if ((ucMyAllSubscriptions == null) && DisplayMySubscriptions) { // Try to load the control dynamically (if available) ucMyAllSubscriptions = Page.LoadControl("~/CMSModules/Membership/Controls/Subscriptions.ascx") as CMSAdminControl; if (ucMyAllSubscriptions != null) { ucMyAllSubscriptions.Visible = false; ucMyAllSubscriptions.SetValue("ShowBlogs", DisplayBlogs); ucMyAllSubscriptions.SetValue("ShowMessageBoards", DisplayMessageBoards); ucMyAllSubscriptions.SetValue("ShowNewsletters", DisplayNewsletters); ucMyAllSubscriptions.SetValue("sendconfirmationemail", SendConfirmationEmails); ucMyAllSubscriptions.ID = "ucMyAllSubscriptions"; plcOther.Controls.Add(ucMyAllSubscriptions); tabName = subscriptionsTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyAllSubscriptions"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, subscriptionsTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } // My memberships if ((this.ucMyMemberships == null) && this.DisplayMyMemberships) { // Try to load the control dynamically this.ucMyMemberships = this.Page.LoadControl("~/CMSModules/Membership/Controls/MyMemberships.ascx") as CMSAdminControl; if (this.ucMyMemberships != null) { this.ucMyMemberships.SetValue("UserID", currentUser.UserID); if (!String.IsNullOrEmpty(this.MembershipsPagePath)) { this.ucMyMemberships.SetValue("BuyMembershipURL", CMSContext.GetUrl(this.MembershipsPagePath)); } this.plcOther.Controls.Add(this.ucMyMemberships); tabName = membershipsTab; activeTabs.Add(tabName); this.tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = this.GetString("myaccount.mymemberships"); this.tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, this.ParameterName, membershipsTab)); if (selectedPage == String.Empty) { selectedPage = tabName; } } } if ((ucMyCategories == null) && DisplayMyCategories) { // Try to load the control dynamically (if available) ucMyCategories = Page.LoadControl("~/CMSModules/Categories/Controls/Categories.ascx") as CMSAdminControl; if (ucMyCategories != null) { ucMyCategories.Visible = false; ucMyCategories.SetValue("DisplaySiteCategories", false); ucMyCategories.SetValue("DisplaySiteSelector", false); ucMyCategories.ID = "ucMyCategories"; plcOther.Controls.Add(ucMyCategories); tabName = categoriesTab; activeTabs.Add(tabName); tabMenu.Tabs[activeTabs.IndexOf(tabName), 0] = GetString("MyAccount.MyCategories"); tabMenu.Tabs[activeTabs.IndexOf(tabName), 2] = HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(absoluteUri, ParameterName, categoriesTab)); if (selectedPage == string.Empty) { selectedPage = tabName; } } } // Set css class pnlBody.CssClass = CssClass; // Get page url page = QueryHelper.GetString(ParameterName, selectedPage); // Set controls visibility ucChangePassword.Visible = false; ucChangePassword.StopProcessing = true; if (ucMyAddresses != null) { ucMyAddresses.Visible = false; ucMyAddresses.StopProcessing = true; } if (ucMyOrders != null) { ucMyOrders.Visible = false; ucMyOrders.StopProcessing = true; } if (ucMyDetails != null) { ucMyDetails.Visible = false; ucMyDetails.StopProcessing = true; } if (ucMyCredit != null) { ucMyCredit.Visible = false; ucMyCredit.StopProcessing = true; } if (ucMyAllSubscriptions != null) { ucMyAllSubscriptions.Visible = false; ucMyAllSubscriptions.StopProcessing = true; ucMyAllSubscriptions.SetValue("CacheMinutes", CacheMinutes); } if (ucMyNotifications != null) { ucMyNotifications.Visible = false; ucMyNotifications.StopProcessing = true; } if (ucMyMessages != null) { ucMyMessages.Visible = false; ucMyMessages.StopProcessing = true; } if (ucMyFriends != null) { ucMyFriends.Visible = false; ucMyFriends.StopProcessing = true; } if (this.ucMyMemberships != null) { this.ucMyMemberships.Visible = false; this.ucMyMemberships.StopProcessing = true; } if (this.ucMyCategories != null) { this.ucMyCategories.Visible = false; this.ucMyCategories.StopProcessing = true; } tabMenu.SelectedTab = activeTabs.IndexOf(page); // Select current page switch (page) { case personalTab: if (myProfile != null) { // Get alternative form info AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(AlternativeFormName); if (afi != null) { myProfile.StopProcessing = false; myProfile.Visible = true; myProfile.AllowEditVisibility = AllowEditVisibility; myProfile.AlternativeFormName = AlternativeFormName; } else { lblError.Text = String.Format(GetString("altform.formdoesntexists"), AlternativeFormName); lblError.Visible = true; myProfile.Visible = false; } } break; case detailsTab: if (ucMyDetails != null) { ucMyDetails.Visible = true; ucMyDetails.StopProcessing = false; ucMyDetails.SetValue("Customer", customer); } break; case addressesTab: if (ucMyAddresses != null) { ucMyAddresses.Visible = true; ucMyAddresses.StopProcessing = false; ucMyAddresses.SetValue("CustomerId", customerId); } break; case ordersTab: if (ucMyOrders != null) { ucMyOrders.Visible = true; ucMyOrders.StopProcessing = false; ucMyOrders.SetValue("CustomerId", customerId); ucMyOrders.SetValue("ShowOrderTrackingNumber", ShowOrderTrackingNumber); } break; case creditTab: if (ucMyCredit != null) { ucMyCredit.Visible = true; ucMyCredit.StopProcessing = false; ucMyCredit.SetValue("CustomerId", customerId); } break; case passwordTab: ucChangePassword.Visible = true; ucChangePassword.StopProcessing = false; ucChangePassword.AllowEmptyPassword = AllowEmptyPassword; break; case notificationsTab: if (ucMyNotifications != null) { ucMyNotifications.Visible = true; ucMyNotifications.StopProcessing = false; ucMyNotifications.SetValue("UserId", currentUser.UserID); ucMyNotifications.SetValue("UnigridImageDirectory", UnigridImageDirectory); } break; case messagesTab: if (ucMyMessages != null) { ucMyMessages.Visible = true; ucMyMessages.StopProcessing = false; } break; case friendsTab: if (ucMyFriends != null) { ucMyFriends.Visible = true; ucMyFriends.StopProcessing = false; ucMyFriends.SetValue("UserID", currentUser.UserID); } break; case subscriptionsTab: if (ucMyAllSubscriptions != null) { ucMyAllSubscriptions.Visible = true; ucMyAllSubscriptions.StopProcessing = false; ucMyAllSubscriptions.SetValue("userid", currentUser.UserID); ucMyAllSubscriptions.SetValue("siteid", CMSContext.CurrentSiteID); } break; case membershipsTab: if (this.ucMyMemberships != null) { this.ucMyMemberships.Visible = true; this.ucMyMemberships.StopProcessing = false; } break; case categoriesTab: if (this.ucMyCategories != null) { this.ucMyCategories.Visible = true; this.ucMyCategories.StopProcessing = false; } break; } } else { // Hide control if current user is not authenticated Visible = false; } } }
protected void Page_Load(object sender, EventArgs e) { // Register main CMS script file ScriptHelper.RegisterCMS(this); // Fix messages position MessagesPlaceHolder.WrapperControlClientID = pnlContent.ClientID; if (QueryHelper.ValidateHash("hash") && (Parameters != null)) { // Initialize current user currentUser = CMSContext.CurrentUser; // Check permissions if (!currentUser.IsGlobalAdministrator && !currentUser.IsAuthorizedPerResource("CMS.Content", "manageworkflow")) { RedirectToAccessDenied("CMS.Content", "manageworkflow"); } // Set current UI culture currentCulture = CultureHelper.PreferredUICulture; // Initialize current site currentSiteName = CMSContext.CurrentSiteName; currentSiteId = CMSContext.CurrentSiteID; // Initialize events ctlAsync.OnFinished += ctlAsync_OnFinished; ctlAsync.OnError += ctlAsync_OnError; ctlAsync.OnRequestLog += ctlAsync_OnRequestLog; ctlAsync.OnCancel += ctlAsync_OnCancel; if (!IsCallback) { DataSet allDocs = null; TreeProvider tree = new TreeProvider(currentUser); // Current Node ID to delete string parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty); if (string.IsNullOrEmpty(parentAliasPath)) { // Get IDs of nodes string nodeIdsString = ValidationHelper.GetString(Parameters["nodeids"], string.Empty); string[] nodeIdsArr = nodeIdsString.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nodeId in nodeIdsArr) { int id = ValidationHelper.GetInteger(nodeId, 0); if (id != 0) { nodeIds.Add(id); } } } else { string where = "ClassName <> 'CMS.Root'"; if (!string.IsNullOrEmpty(WhereCondition)) { where = SqlHelperClass.AddWhereCondition(where, WhereCondition); } string columns = SqlHelperClass.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName,DocumentCheckedOutByUserID"); allDocs = tree.SelectNodes(currentSiteName, parentAliasPath.TrimEnd('/') + "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", 1, false, 0, columns); if (!DataHelper.DataSourceIsEmpty(allDocs)) { foreach (DataRow row in allDocs.Tables[0].Rows) { nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0)); } } } // Initialize strings based on current action switch (CurrentAction) { case WorkflowAction.Archive: lblQuestion.ResourceString = "content.archivequestion"; chkAllCultures.ResourceString = "content.archiveallcultures"; chkUnderlying.ResourceString = "content.archiveunderlying"; canceledString = GetString("content.archivecanceled"); // Setup title of log titleElemAsync.TitleText = GetString("content.archivingdocuments"); titleElemAsync.TitleImage = GetImageUrl("CMSModules/CMS_Content/Dialogs/archive.png"); // Setup page title text and image CurrentMaster.Title.TitleText = GetString("Content.ArchiveTitle"); CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Content/Dialogs/archive.png"); break; case WorkflowAction.Publish: lblQuestion.ResourceString = "content.publishquestion"; chkAllCultures.ResourceString = "content.publishallcultures"; chkUnderlying.ResourceString = "content.publishunderlying"; canceledString = GetString("content.publishcanceled"); // Setup title of log titleElemAsync.TitleText = GetString("content.publishingdocuments"); titleElemAsync.TitleImage = GetImageUrl("CMSModules/CMS_Content/Dialogs/publish.png"); // Setup page title text and image CurrentMaster.Title.TitleText = GetString("Content.PublishTitle"); CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Content/Dialogs/publish.png"); break; } if (nodeIds.Count == 0) { // Hide if no node was specified pnlContent.Visible = false; return; } btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;"); // Register the dialog script ScriptHelper.RegisterDialogScript(this); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; // Set all cultures checkbox DataSet culturesDS = CultureInfoProvider.GetSiteCultures(currentSiteName); if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1)) { chkAllCultures.Checked = true; plcAllCultures.Visible = false; } if (nodeIds.Count > 0) { pnlDocList.Visible = true; // Create where condition string where = SqlHelperClass.GetWhereCondition("NodeID", nodeIds.ToArray()); string columns = SqlHelperClass.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName,DocumentCheckedOutByUserID"); // Select nodes DataSet ds = allDocs ?? tree.SelectNodes(currentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", TreeProvider.ALL_LEVELS, false, 0, columns); // Enumerate selected documents if (!DataHelper.DataSourceIsEmpty(ds)) { cancelNodeId = ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NodeParentID"), 0); foreach (DataRow dr in ds.Tables[0].Rows) { AddToList(dr); } // Display enumeration of documents foreach (KeyValuePair <int, string> line in list) { lblDocuments.Text += line.Value; } } } } // Set title for dialog mode string imgUrl = "CMSModules/CMS_Content/Dialogs/publish.png"; string title = GetString("general.publish"); if (CurrentAction == WorkflowAction.Archive) { imgUrl = "CMSModules/CMS_Content/Dialogs/archive.png"; title = GetString("general.archive"); } SetTitle(imgUrl, title, null, null); } else { pnlPublish.Visible = false; ShowError(GetString("dialogs.badhashtext")); } }
protected void Page_Load(object sender, EventArgs e) { // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Initialize current user for the async actions currentUser = CMSContext.CurrentUser; currentSiteId = CMSContext.CurrentSiteID; serverId = QueryHelper.GetInteger("serverid", 0); HeaderActions.ActionPerformed += HeaderActions_ActionPerformed; if (RequestHelper.CausedPostback(btnSyncComplete)) { SyncComplete(); } else { if (!RequestHelper.IsCallback()) { // Check 'Manage object tasks' permission if (!currentUser.IsAuthorizedPerResource("cms.staging", "ManageDataTasks")) { RedirectToAccessDenied("cms.staging", "ManageDataTasks"); } ucDisabledModule.SettingsKeys = "CMSStagingLogDataChanges;CMSStagingLogStagingChanges"; ucDisabledModule.InfoTexts.Add(GetString("DataStaging.TaskSeparator") + "<br />"); ucDisabledModule.InfoTexts.Add(GetString("stagingchanges.notlogged")); ucDisabledModule.ParentPanel = pnlNotLogged; // Check logging if (!ucDisabledModule.Check()) { pnlFooter.Visible = false; plcContent.Visible = false; return; } // Register the dialog script ScriptHelper.RegisterDialogScript(this); // Get object type objectType = QueryHelper.GetString("objecttype", string.Empty); if (!String.IsNullOrEmpty(objectType)) { // Create header action HeaderActions.AddAction(new HeaderAction() { Text = GetString("ObjectTasks.SyncCurrent"), ImageUrl = GetImageUrl("CMSModules/CMS_Staging/syncsubtree.png"), EventName = SYNCHRONIZE_CURRENT }); } // Setup title titleElem.TitleText = GetString("Synchronization.Title"); titleElem.TitleImage = GetImageUrl("/CMSModules/CMS_Staging/synchronization.png"); if (!RequestHelper.CausedPostback(HeaderActions, btnSyncSelected, btnSyncAll)) { // Initialize images viewImage = GetImageUrl("Design/Controls/UniGrid/Actions/View.png"); deleteImage = GetImageUrl("Design/Controls/UniGrid/Actions/Delete.png"); syncImage = GetImageUrl("Design/Controls/UniGrid/Actions/Synchronize.png"); // Initialize tooltips syncTooltip = GetString("general.synchronize"); deleteTooltip = GetString("general.delete"); viewTooltip = GetString("general.view"); plcContent.Visible = true; // Initialize buttons btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;"); btnCancel.Text = GetString("General.Cancel"); btnDeleteAll.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");"; btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");"; btnSyncSelected.OnClientClick = "return !" + gridTasks.GetCheckSelectionScript(); ltlScript.Text += ScriptHelper.GetScript("function CompleteSync(){" + Page.ClientScript.GetPostBackEventReference(btnSyncComplete, null) + "}"); // Initialize grid gridTasks.OrderBy = "TaskTime"; gridTasks.ZeroRowsText = GetString("Tasks.NoTasks"); gridTasks.OnAction += gridTasks_OnAction; gridTasks.OnDataReload += gridTasks_OnDataReload; gridTasks.OnExternalDataBound += gridTasks_OnExternalDataBound; gridTasks.ShowActionsMenu = true; gridTasks.Columns = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount"; TaskInfo ti = new TaskInfo(); gridTasks.AllColumns = SqlHelperClass.MergeColumns(ti.ColumnNames); pnlLog.Visible = false; } } } ctlAsync.OnFinished += ctlAsync_OnFinished; ctlAsync.OnError += ctlAsync_OnError; ctlAsync.OnRequestLog += ctlAsync_OnRequestLog; ctlAsync.OnCancel += ctlAsync_OnCancel; }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Do not process control by default StopProcessing = true; // Keep frequent objects CurrentUserInfo cui = MembershipContext.AuthenticatedUser; PageInfo pi = DocumentContext.CurrentPageInfo; if (pi == null) { IsPageNotFound = true; pi = DocumentContext.CurrentCultureInvariantPageInfo ?? new PageInfo(); checkChanges = string.Empty; } ucUIToolbar.StopProcessing = true; // Get main UI element var element = UIElementInfoProvider.GetUIElementInfo(MODULE_NAME, ELEMENT_NAME); if (element == null) { return; } // Check whether user is authorized to edit page if ((pi != null) && AuthenticationHelper.IsAuthenticated() && cui.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName) && ((IsPageNotFound && pi.NodeID == 0) || cui.IsAuthorizedPerTreeNode(pi.NodeID, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed) && CMSPage.CheckUIElementAccessHierarchical(element, redirectToAccessDenied: false)) { // Enable processing StopProcessing = false; // Check whether the preferred culture is RTL isRTL = CultureHelper.IsUICultureRTL(); // Add link to CSS file CssRegistration.RegisterCssLink(Page, "Design", "OnSiteEdit.css"); CssRegistration.RegisterBootstrap(Page); // Filter UI element buttons ucUIToolbar.OnButtonFiltered += ucUIToolbar_OnButtonFiltered; ucUIToolbar.OnButtonCreated += ucUIToolbar_OnButtonCreated; ucUIToolbar.OnGroupsCreated += ucUIToolbar_OnGroupsCreated; ucUIToolbar.IsRTL = isRTL; // Register edit script file RegisterEditScripts(pi); if (ViewMode.IsEditLive()) { popupHandler.Visible = true; IsLiveSite = false; MessagesPlaceHolder.IsLiveSite = false; MessagesPlaceHolder.Opacity = 100; // Keep content of editable web parts when saving the document changes if (!IsPageNotFound) { PortalManager.PreserveContent = true; } // Display warning in the Safe mode if (PortalHelper.SafeMode) { string safeModeText = GetString("onsiteedit.safemode") + "<br/><a href=\"" + RequestContext.RawURL.Replace("safemode=1", "safemode=0") + "\">" + GetString("general.close") + "</a> " + GetString("contentedit.safemode2"); string safeModeDescription = GetString("onsiteedit.safemode") + "<br/>" + GetString("general.seeeventlog"); // Display the warning message ShowWarning(safeModeText, safeModeDescription, ""); } ucUIToolbar.StopProcessing = false; // Ensure document redirection var redirectUrl = TreePathUtils.GetRedirectionUrl(pi); if (!String.IsNullOrEmpty(redirectUrl)) { redirectUrl = UrlResolver.ResolveUrl(redirectUrl); ShowInformation(GetString("onsiteedit.redirectinfo") + " <a href=\"" + redirectUrl + "\">" + redirectUrl + "</a>"); } pnlUpdateProgress.Visible = true; } // Mode menu on live site else if (ViewMode.IsLiveSite()) { // Hide the edit panel, show only slider button pnlToolbarSpace.Visible = false; pnlToolbar.Visible = false; pnlSlider.Visible = true; icon.CssClass = "cms-icon-80 icon-edit"; icon.ToolTip = GetString("onsitedit.editmode"); lblSliderText.Text = GetString("onsiteedit.editmode"); pnlButton.Attributes.Add("onclick", "OnSiteEdit_ChangeEditMode();"); // Hide the OnSite edit button when displayed in administration pnlSlider.Style.Add("display", "none"); } } // Hide control actions for unauthorized users else { plcEdit.Visible = false; } }
/// <summary> /// External data binding handler. /// </summary> protected object gridDocuments_OnExternalDataBound(object sender, string sourceName, object parameter) { int currentNodeId; sourceName = sourceName.ToLowerCSafe(); switch (sourceName) { case "view": { // Dialog view item DataRowView data = ((DataRowView)((GridViewRow)parameter).DataItem); CMSGridActionButton btn = ((CMSGridActionButton)sender); // Current row is the Root document isRootDocument = (ValidationHelper.GetInteger(data["NodeParentID"], 0) == 0); currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0); isCurrentDocument = (currentNodeId == WOpenerNodeID); string culture = ValidationHelper.GetString(data["DocumentCulture"], string.Empty); // Existing document culture if (culture.ToLowerCSafe() == CultureCode.ToLowerCSafe()) { // Force redirection to the root document in case of on-site editing (to ensure that user is not redirected to default alias path document) string url = ResolveUrl(!isRootDocument ? DocumentURLProvider.GetPresentationUrlHandlerPath(culture, currentNodeId) : "~/"); btn.OnClientClick = "ViewItem(" + ScriptHelper.GetString(url) + "); return false;"; } // New culture version else { btn.OnClientClick = "wopener.NewDocumentCulture(" + currentNodeId + ", '" + CultureCode + "'); CloseDialog(); return false;"; } } break; case "edit": { CMSGridActionButton btn = ((CMSGridActionButton)sender); if (IsEditVisible) { DataRowView data = ((DataRowView)((GridViewRow)parameter).DataItem); string culture = ValidationHelper.GetString(data["DocumentCulture"], string.Empty); currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0); int nodeParentId = ValidationHelper.GetInteger(data["NodeParentID"], 0); if (!RequiresDialog || (culture.ToLowerCSafe() == CultureCode.ToLowerCSafe())) { // Go to the selected document or create a new culture version when not used in a dialog btn.OnClientClick = "EditItem(" + currentNodeId + ", " + nodeParentId + "); return false;"; } else { // New culture version in a dialog btn.OnClientClick = "wopener.NewDocumentCulture(" + currentNodeId + ", '" + CultureCode + "'); CloseDialog(); return false;"; } } else { btn.Visible = false; } } break; case "delete": { // Delete button CMSGridActionButton btn = ((CMSGridActionButton)sender); // Hide the delete button for the root document btn.Visible = !isRootDocument; } break; case "contextmenu": { // Dialog context menu item CMSGridActionButton btn = ((CMSGridActionButton)sender); // Hide the context menu for the root document btn.Visible = !isRootDocument && !ShowAllLevels; } break; case "versionnumber": { // Version number if (parameter == DBNull.Value) { parameter = "-"; } parameter = HTMLHelper.HTMLEncode(parameter.ToString()); return(parameter); } case "documentname": { // Document name DataRowView data = (DataRowView)parameter; string className = ValidationHelper.GetString(data["ClassName"], string.Empty); string classDisplayName = ValidationHelper.GetString(data["classdisplayname"], null); string name = ValidationHelper.GetString(data["DocumentName"], string.Empty); string culture = ValidationHelper.GetString(data["DocumentCulture"], string.Empty); string cultureString = null; currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0); int nodeParentId = ValidationHelper.GetInteger(data["NodeParentID"], 0); if (isRootDocument) { // User site name for the root document name = SiteContext.CurrentSiteName; } // Default culture if (culture.ToLowerCSafe() != CultureCode.ToLowerCSafe()) { cultureString = " (" + culture + ")"; } StringBuilder sb = new StringBuilder(); var isFile = className.EqualsCSafe(SystemDocumentTypes.File, true); string extension = isFile ? ValidationHelper.GetString(data["DocumentType"], String.Empty) : String.Empty; if (ShowDocumentTypeIcon) { // Prepare tooltip for document type icon string iconTooltip = ""; if (ShowDocumentTypeIconTooltip && (classDisplayName != null)) { string safeClassName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(classDisplayName)); iconTooltip = string.Format("onmouseout=\"UnTip()\" onmouseover=\"Tip('{0}')\"", HTMLHelper.EncodeForHtmlAttribute(safeClassName)); } if (isFile) { sb.Append(UIHelper.GetFileIcon(Page, extension, additionalAttributes: iconTooltip)); } // Use class icons else { var dataClass = DataClassInfoProvider.GetDataClassInfo(className); if (dataClass != null) { var iconClass = (string)dataClass.GetValue("ClassIconClass"); sb.Append(UIHelper.GetDocumentTypeIcon(Page, className, iconClass, additionalAttributes: iconTooltip)); } } } string safeName = HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50)); if (DocumentNameAsLink && !isRootDocument) { string tooltip = UniGridFunctions.DocumentNameTooltip(data); string selectFunction = SelectItemJSFunction + "(" + currentNodeId + ", " + nodeParentId + ");"; sb.Append("<a href=\"javascript: ", selectFunction, "\""); // Ensure onclick action on mobile devices. This is necessary due to Tip/UnTip functions. They block default click behavior on mobile devices. if (DeviceContext.CurrentDevice.IsMobile()) { sb.Append(" ontouchend=\"", selectFunction, "\""); } sb.Append(" onmouseout=\"UnTip()\" onmouseover=\"Tip('", HTMLHelper.EncodeForHtmlAttribute(tooltip), "')\">", safeName, cultureString, "</a>"); } else { sb.Append(safeName, cultureString); } // Show document marks only if method is not called from grid export and document marks are allowed if ((sender != null) && ShowDocumentMarks) { // Prepare parameters int workflowStepId = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(data, "DocumentWorkflowStepID"), 0); WorkflowStepTypeEnum stepType = WorkflowStepTypeEnum.Undefined; if (workflowStepId > 0) { WorkflowStepInfo stepInfo = WorkflowStepInfoProvider.GetWorkflowStepInfo(workflowStepId); if (stepInfo != null) { stepType = stepInfo.StepType; } } // Create data container IDataContainer container = new DataRowContainer(data); // Add icons and use current culture of processed node because of 'Not translated document' icon sb.Append(" ", DocumentUIHelper.GetDocumentMarks(Page, currentSiteName, ValidationHelper.GetString(container.GetValue("DocumentCulture"), string.Empty), stepType, container)); } return(sb.ToString()); } case "documentculture": { DocumentFlagsControl ucDocFlags = null; if (OnDocumentFlagsCreating != null) { // Raise event for obtaining custom DocumentFlagControl object result = OnDocumentFlagsCreating(this, sourceName, parameter); ucDocFlags = result as DocumentFlagsControl; // Check if something other than DocumentFlagControl was returned if ((ucDocFlags == null) && (result != null)) { return(result); } } // Dynamically load document flags control when not created if (ucDocFlags == null) { ucDocFlags = LoadUserControl("~/CMSAdminControls/UI/DocumentFlags.ascx") as DocumentFlagsControl; } // Set document flags properties if (ucDocFlags != null) { DataRowView data = (DataRowView)parameter; // Get node ID currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0); if (!string.IsNullOrEmpty(SelectLanguageJSFunction)) { ucDocFlags.SelectJSFunction = SelectLanguageJSFunction; } ucDocFlags.ID = "docFlags" + currentNodeId; ucDocFlags.SiteCultures = SiteCultures; ucDocFlags.NodeID = currentNodeId; ucDocFlags.StopProcessing = true; // Keep the control for later usage FlagsControls.Add(ucDocFlags); return(ucDocFlags); } } break; case "modifiedwhen": case "modifiedwhentooltip": // Modified when if (string.IsNullOrEmpty(parameter.ToString())) { return(string.Empty); } DateTime modifiedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME); currentUserInfo = currentUserInfo ?? MembershipContext.AuthenticatedUser; currentSiteInfo = currentSiteInfo ?? SiteContext.CurrentSite; return(sourceName.EqualsCSafe("modifiedwhen", StringComparison.InvariantCultureIgnoreCase) ? TimeZoneHelper.ConvertToUserTimeZone(modifiedWhen, true, currentUserInfo, currentSiteInfo) : TimeZoneHelper.GetUTCLongStringOffset(currentUserInfo, currentSiteInfo)); default: if (OnExternalAdditionalDataBound != null) { return(OnExternalAdditionalDataBound(sender, sourceName, parameter)); } break; } return(parameter); }
/// <summary> /// 获取登录用户信息 /// </summary> /// <param name="menuCode"></param> /// <returns></returns> public static CurrentUserInfo FindUserInfo(string userCode) { // string sql = @"select // tu.UserCode, // tu.UserName, // ur.RoleCode, // tu.CompanyCode as CompanyId, // tc.OrgType, // tpu.PositionCode // from TbUser tu // left join TbUserRole ur on tu.UserCode=ur.UserCode // left join TbPositionUser tpu on tu.UserCode=tpu.UserCode // left join TbCompany tc on tc.CompanyCode=tu.CompanyCode // where tu.UserCode=@userCode"; // var model = Db.Context.FromSql(sql) // .AddInParameter("@userCode", DbType.String, userCode) // .ToFirst<CurrentUserInfo>(); // return model; CurrentUserInfo cui = new CurrentUserInfo(); string sql = @"select top 1 ur.ProjectId,pro.ProjectName,ur.OrgId,cm.CompanyFullName,cm.ParentCompanyCode,ur.OrgType,ur.UserCode as UserId,u.UserCode,u.UserName from TbUserRole ur left join TbCompany cm on ur.OrgId=cm.CompanyCode left join TbProjectInfo pro on ur.ProjectId=pro.ProjectId left join TbUser u on ur.UserCode=u.UserId where u.UserCode=@UserCode and ur.Flag=0 group by ur.ProjectId,pro.ProjectName,ur.OrgId,cm.CompanyFullName,cm.ParentCompanyCode,ur.OrgType,ur.UserCode,u.UserCode,u.UserName order by OrgId asc"; DataTable dt = Db.Context.FromSql(sql).AddInParameter("@UserCode", DbType.String, userCode).ToDataTable(); if (dt != null && dt.Rows.Count > 0) { string sqlRole = @"select distinct ur.RoleCode as RoleId,r.RoleCode,r.RoleName from TbUserRole ur left join TbUser u on ur.UserCode=u.UserId left join TbRole r on ur.RoleCode=r.RoleId where u.UserCode=@UserCode and ProjectId=@ProjectId and OrgId=@OrgId and ur.Flag=0"; string strRole = ""; DataTable dtRole = Db.Context.FromSql(sqlRole).AddInParameter("@UserCode", DbType.String, userCode).AddInParameter("@ProjectId", DbType.String, dt.Rows[0]["ProjectId"]).AddInParameter("@OrgId", DbType.String, dt.Rows[0]["OrgId"]).ToDataTable(); if (dtRole != null && dt.Rows.Count > 0) { for (int i = 0; i < dtRole.Rows.Count; i++) { if (i == dtRole.Rows.Count - 1) { strRole += "'" + dtRole.Rows[i]["RoleId"] + "'"; } else { strRole += "'" + dtRole.Rows[i]["RoleId"] + "',"; } } } cui.ProjectId = Convert.ToString(dt.Rows[0]["ProjectId"]); cui.CompanyId = Convert.ToString(dt.Rows[0]["OrgId"]); cui.OrgType = Convert.ToString(dt.Rows[0]["OrgType"]); cui.ComPanyName = Convert.ToString(dt.Rows[0]["CompanyFullName"]); if (cui.OrgType == "3" || cui.OrgType == "4" || cui.OrgType == "5") { string ProjectOrgAllId = ""; string ProjectOrgAllName = ""; string sql1 = @"with tab as ( select CompanyCode,ParentCompanyCode,CompanyFullName,OrgType from TbCompany where CompanyCode=@CompanyCode union all select b.CompanyCode,b.ParentCompanyCode,b.CompanyFullName,b.OrgType from tab a, TbCompany b where a.ParentCompanyCode=b.CompanyCode ) select * from tab order by OrgType asc;"; var ret1 = Db.Context.FromSql(sql1).AddInParameter("@CompanyCode", DbType.String, dt.Rows[0]["OrgId"]).ToDataTable(); if (ret1 != null && ret1.Rows.Count > 0) { for (int j = 0; j < ret1.Rows.Count; j++) { if (ret1.Rows.Count > 1 && ret1.Rows.Count != j + 1) { ProjectOrgAllId += ret1.Rows[j]["CompanyCode"] + "/"; ProjectOrgAllName += ret1.Rows[j]["CompanyFullName"] + "/"; } else { ProjectOrgAllId += ret1.Rows[j]["CompanyCode"]; ProjectOrgAllName += ret1.Rows[j]["CompanyFullName"]; } } } cui.ProjectOrgAllId = ProjectOrgAllId; cui.ProjectOrgAllName = ProjectOrgAllName; //cui.ProcessFactoryCode = ""; //cui.ProcessFactoryName = "所有加工厂"; cui.ProcessFactoryCode = "6386683729561128960"; cui.ProcessFactoryName = "二号加工厂"; } else { cui.ProjectOrgAllId = Convert.ToString(dt.Rows[0]["OrgId"]); cui.ProjectOrgAllName = Convert.ToString(dt.Rows[0]["CompanyFullName"]); if (cui.OrgType == "1")//当前登录人是加工厂 { cui.ProcessFactoryCode = Convert.ToString(dt.Rows[0]["OrgId"]); cui.ProcessFactoryName = Convert.ToString(dt.Rows[0]["CompanyFullName"]); cui.ProjectId = ""; } else//经理部默认所有 { //cui.ProcessFactoryCode = ""; //cui.ProcessFactoryName = "所有加工厂"; cui.ProcessFactoryCode = "6386683729561128960"; cui.ProcessFactoryName = "二号加工厂"; } } cui.RoleCode = strRole; cui.UserId = Convert.ToString(dt.Rows[0]["UserId"]); cui.UserCode = Convert.ToString(dt.Rows[0]["UserCode"]); cui.UserName = Convert.ToString(dt.Rows[0]["UserName"]); } return(cui); }
protected override void OnInit(EventArgs e) { // Do not check changes DocumentManager.RegisterSaveChangesScript = false; EditForm.OnBeforeSave += EditForm_OnBeforeSave; etaCode.Editor.Language = LanguageEnum.HTML; etaCSS.Editor.Language = LanguageEnum.CSS; wpli = CMSContext.EditedObject as WebPartLayoutInfo; layoutID = QueryHelper.GetInteger("layoutid", 0); isSiteManager = ((CMSContext.CurrentUser.IsGlobalAdministrator && layoutID != 0) || QueryHelper.GetBoolean("sitemanager", false)); isNew = (LayoutCodeName == "|new|"); isDefault = (LayoutCodeName == "|default|") || (!isSiteManager && string.IsNullOrEmpty(LayoutCodeName)); if ((wpli == null) && isSiteManager) { isNew = true; } if (wpli == null) { editMenuElem.ObjectManager.ObjectType = PredefinedObjectType.WEBPARTLAYOUT; } ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "PreviewHierarchyPerformAction", ScriptHelper.GetScript("function actionPerformed(action) { if (action == 'saveandclose') { document.getElementById('" + hdnClose.ClientID + "').value = '1'; } " + editMenuElem.ObjectManager.GetJSFunction(ComponentEvents.SAVE, null, null) + "; }")); RegisterResizeHeaders(); currentUser = CMSContext.CurrentUser; // Get webpart instance (if edited in CMSDesk) if ((webpartId != "") && !isSiteManager) { // Get pageinfo pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); if (pi == null) { ShowInformation(GetString("WebPartProperties.WebPartNotFound"), null, false); } // Get page template pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.GetWebPart(webpartId); } } // If the web part is not found, try webpart ID if (webPart == null) { // Site manager wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(webpartId, 0)); if (wpi == null) { ShowError(GetString("WebPartProperties.WebPartNotFound"), null, null); startWithFullScreen = false; return; } } else { // CMS desk wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (string.IsNullOrEmpty(LayoutCodeName)) { // Get the current layout name LayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } } if (wpi != null) { if (CMSObjectHelper.UseCheckinCheckout && (!isNew || isSiteManager)) { pnlFormArea.CssClass = "PreviewDefaultContentLarge"; } else { pnlFormArea.CssClass = "PreviewDefaultContent"; } // Load the web part information webPartInfo = wpi; bool loaded = false; if (!RequestHelper.IsPostBack()) { if (wpli != null) { editMenuElem.MenuPanel.Visible = true; // Read-only code text area etaCode.Editor.ReadOnly = false; loaded = true; } if (!loaded) { string fileName = webPartInfo.WebPartFileName; if (webPartInfo.WebPartParentID > 0) { WebPartInfo pwpi = WebPartInfoProvider.GetWebPartInfo(webPartInfo.WebPartParentID); if (pwpi != null) { fileName = pwpi.WebPartFileName; } } if (!fileName.StartsWithCSafe("~")) { fileName = "~/CMSWebparts/" + fileName; } // Check if filename exist if (!FileHelper.FileExists(fileName)) { ShowError(GetString("WebPartProperties.FileNotExist"), null, null); plcContent.Visible = false; } else { // Load default web part layout code etaCode.Text = File.ReadAllText(Server.MapPath(fileName)); // Load default web part CSS etaCSS.Text = wpi.WebPartCSS; startWithFullScreen = false; } } } } if ((wpli == null) && isSiteManager) { pnlFormArea.CssClass += " NewPreviewContent"; var breadcrumbs = new string[2, 3]; breadcrumbs[0, 0] = GetString("WebParts.Layout"); breadcrumbs[0, 1] = ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/Development/WebPart_Edit_Layout.aspx?webpartid=" + QueryHelper.GetInteger("webpartid", 0)); breadcrumbs[1, 0] = GetString("webparts_layout_newlayout"); editMenuElem.PageTitleBreadcrumbs = breadcrumbs; } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ApplyButton", ScriptHelper.GetScript( "function SetRefresh(refreshpage) { document.getElementById('" + hidRefresh.ClientID + @"').value = refreshpage; } function OnApplyButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('save');refreshPreview(); } function OnOKButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('saveandclose'); } ")); InitLayoutForm(); plcCssLink.Visible = string.IsNullOrEmpty(etaCSS.Text.Trim()); base.OnInit(e); }
public RegistrationStateFault(string msg, string path, CurrentUserInfo userInfo) : base(msg, path, userInfo) { }
/// <summary> /// Restores set of given version histories. /// </summary> /// <param name="currentUserInfo">Current user info</param> /// <param name="recycleBin">DataSet with nodes to restore</param> private void RestoreDataSet(CurrentUserInfo currentUserInfo, DataSet recycleBin) { // Result flags bool resultOK = true; bool permissionsOK = true; if (!DataHelper.DataSourceIsEmpty(recycleBin)) { TreeProvider tree = new TreeProvider(currentUserInfo); tree.AllowAsyncActions = false; VersionManager versionManager = VersionManager.GetInstance(tree); // Restore all documents foreach (DataRow dataRow in recycleBin.Tables[0].Rows) { // Log actual event string taskTitle = HTMLHelper.HTMLEncode(ValidationHelper.GetString(dataRow["DocumentNamePath"], string.Empty)); // Restore document int versionHistoryId = ValidationHelper.GetInteger(dataRow["VersionHistoryID"], 0); if (versionHistoryId > 0) { var versionHistoryInfo = GetVersionHistoryInfo(versionHistoryId); // Check permissions if (!IsAuthorizedPerDocument(versionHistoryInfo, "Create", mCurrentUser)) { CurrentError = String.Format(ResHelper.GetString("Recyclebin.RestorationFailedPermissions", mCurrentCulture), taskTitle); AddLog(CurrentError); permissionsOK = false; } else { var treeNode = versionManager.RestoreDocument(versionHistoryId); if (treeNode != null) { AddLog(ResHelper.GetString("general.document", mCurrentCulture) + "'" + taskTitle + "'"); } else { // Set result flag if (resultOK) { resultOK = false; } } } } } } if (resultOK && permissionsOK) { CurrentInfo = ResHelper.GetString("Recyclebin.RestorationOK", mCurrentCulture); AddLog(CurrentInfo); } else { CurrentError = ResHelper.GetString("Recyclebin.RestorationFailed", mCurrentCulture); if (!permissionsOK) { CurrentError += "<br />" + ResHelper.GetString("recyclebin.errorsomenotrestored", mCurrentCulture); } AddLog(CurrentError); } }
/// <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 (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "attach.actiondenied"; SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "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 ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree); } } // Check in the document if (autoCheck) { if (VersionManager != null) { if (VersionHistoryID > 0 && node != null) { VersionManager.CheckIn(node, null, null); } } } } } catch (Exception ex) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { CurrentUserInfo currentUser = CMSContext.CurrentUser; 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.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "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, CMSContext.CurrentUser)) { 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.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; SavingFailed = true; } } break; } }
protected void Page_Load(object sender, EventArgs e) { if (StopProcessing) { ugRecycleBin.StopProcessing = true; return; } // Register the main CMS script ScriptHelper.RegisterCMS(Page); // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Set current UI culture mCurrentCulture = CultureHelper.PreferredUICultureCode; // Get current user info mCurrentUser = MembershipContext.AuthenticatedUser; // Set current site ID to filter filter.SiteID = (mSelectedSite != null) ? mSelectedSite.SiteID : UniSelector.US_ALL_RECORDS; PrepareGrid(); if (!RequestHelper.IsCallback()) { ControlsHelper.RegisterPostbackControl(btnOk); // Create action script StringBuilder actionScript = new StringBuilder(); actionScript.AppendLine("function PerformAction(selectionFunction, selectionField, dropId, validationLabel, whatId)"); actionScript.AppendLine("{"); actionScript.AppendLine(" var selectionFieldElem = document.getElementById(selectionField);"); actionScript.AppendLine(" var label = document.getElementById(validationLabel);"); actionScript.AppendLine(" var items = selectionFieldElem.value;"); actionScript.AppendLine(" var whatDrp = document.getElementById(whatId);"); actionScript.AppendLine(" var allDocs = whatDrp.value == '" + (int)What.AllDocuments + "';"); actionScript.AppendLine(" var action = document.getElementById(dropId).value;"); actionScript.AppendLine(" if (action == '" + (int)Action.SelectAction + "')"); actionScript.AppendLine(" {"); actionScript.AppendLine(" label.innerHTML = " + ScriptHelper.GetLocalizedString("massaction.selectsomeaction") + ";"); actionScript.AppendLine(" label.style.display = 'block';"); actionScript.AppendLine(" return false;"); actionScript.AppendLine(" }"); actionScript.AppendLine(" if(!eval(selectionFunction) || allDocs)"); actionScript.AppendLine(" {"); actionScript.AppendLine(" var confirmed = false;"); actionScript.AppendLine(" var confMessage = '';"); actionScript.AppendLine(" switch(action)"); actionScript.AppendLine(" {"); actionScript.AppendLine(" case '" + (int)Action.Restore + "':"); actionScript.AppendLine(" confMessage = " + ScriptHelper.GetLocalizedString("recyclebin.confirmrestores") + ";"); actionScript.AppendLine(" break;"); actionScript.AppendLine(" case '" + (int)Action.Delete + "':"); actionScript.AppendLine(" confMessage = allDocs ? " + ScriptHelper.GetLocalizedString("recyclebin.confirmemptyrecbin") + " : " + ScriptHelper.GetLocalizedString("recyclebin.confirmdeleteselected") + ";"); actionScript.AppendLine(" break;"); actionScript.AppendLine(" }"); actionScript.AppendLine(" return confirm(confMessage);"); actionScript.AppendLine(" }"); actionScript.AppendLine(" else"); actionScript.AppendLine(" {"); actionScript.AppendLine(" label.innerHTML = " + ScriptHelper.GetLocalizedString("documents.selectdocuments") + ";"); actionScript.AppendLine(" label.style.display = 'block';"); actionScript.AppendLine(" return false;"); actionScript.AppendLine(" }"); actionScript.AppendLine("}"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "recycleBinScript", ScriptHelper.GetScript(actionScript.ToString())); // Set page size int itemsPerPage = ValidationHelper.GetInteger(ItemsPerPage, 0); if ((itemsPerPage > 0) && !RequestHelper.IsPostBack()) { ugRecycleBin.Pager.DefaultPageSize = itemsPerPage; } // Add action to button btnOk.OnClientClick = "return PerformAction('" + ugRecycleBin.GetCheckSelectionScript() + "','" + ugRecycleBin.GetSelectionFieldClientID() + "','" + drpAction.ClientID + "','" + lblValidation.ClientID + "', '" + drpWhat.ClientID + "');"; // Initialize dropdown lists if (!RequestHelper.IsPostBack()) { drpAction.Items.Add(new ListItem(GetString("general." + Action.Restore), Convert.ToInt32(Action.Restore).ToString())); drpAction.Items.Add(new ListItem(GetString("recyclebin.destroyhint"), Convert.ToInt32(Action.Delete).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())); } // Register the dialog script ScriptHelper.RegisterDialogScript(Page); // Register script for viewing versions string viewVersionScript = "function ViewVersion(versionHistoryId) {modalDialog('" + ResolveUrl("~/CMSModules/RecycleBin/Pages/ViewVersion.aspx") + "?noCompare=1&versionHistoryId=' + versionHistoryId, 'contentversion', 900, 600);}"; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "viewVersionScript", ScriptHelper.GetScript(viewVersionScript)); string error = QueryHelper.GetString("displayerror", String.Empty); if (error != String.Empty) { ShowError(GetString("recyclebin.errorsomenotdestroyed")); } // Set visibility of panels pnlLog.Visible = false; } else { ugRecycleBin.StopProcessing = true; } // Initialize events ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished; ctlAsyncLog.OnError += ctlAsyncLog_OnError; ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel; }
/// <summary> /// Initializes common properties used for processing image. /// </summary> private 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 = AttachmentInfoProvider.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 = AttachmentInfoProvider.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, 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"; } }
protected void Page_Load(object sender, EventArgs e) { // Register script files ScriptHelper.RegisterCMS(this); ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js"); if (!QueryHelper.ValidateHash("hash")) { pnlContent.Visible = false; ShowError(GetString("dialogs.badhashtext")); return; } // Setup page title text and image PageTitle.TitleText = GetString("Content.TranslateTitle"); EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText); if (IsDialog) { RegisterModalPageScripts(); RegisterEscScript(); plcInfo.Visible = false; pnlButtons.Visible = false; } if (!TranslationServiceHelper.IsTranslationAllowed(CurrentSiteName)) { pnlContent.Visible = false; ShowError(GetString("translations.translationnotallowed")); return; } // Initialize current user currentUser = MembershipContext.AuthenticatedUser; // Initialize current site currentSite = SiteContext.CurrentSite; // Initialize events ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished; ctlAsyncLog.OnError += ctlAsyncLog_OnError; ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel; isSelect = QueryHelper.GetBoolean("select", false); if (isSelect) { pnlDocList.Visible = false; pnlDocSelector.Visible = true; translationElem.DisplayMachineServices = false; } var displayTargetLanguage = !IsDialog || isSelect; translationElem.DisplayTargetlanguage = displayTargetLanguage; // Get target culture(s) targetCultures = displayTargetLanguage ? translationElem.TargetLanguages : new HashSet <string>(new[] { QueryHelper.GetString("targetculture", currentCulture) }); // Set the target settings var settings = new TranslationSettings(); settings.TargetLanguages.AddRange(targetCultures); var useCurrentAsDefault = QueryHelper.GetBoolean("currentastargetdefault", false); if (!currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(currentCulture, SiteContext.CurrentSiteName)) { // Do not use current culture as default if user has no permissions to edit it useCurrentAsDefault = false; } translationElem.UseCurrentCultureAsDefaultTarget = useCurrentAsDefault; // Do not include default culture if it is current one if (useCurrentAsDefault && !string.Equals(currentCulture, defaultCulture, StringComparison.InvariantCultureIgnoreCase) && !RequestHelper.IsPostBack()) { settings.TargetLanguages.Add(currentCulture); } translationElem.TranslationSettings = settings; allowTranslate = true; if (RequestHelper.IsCallback()) { return; } // If not in select mode, load all the document IDs and check permissions // In select mode, documents are checked when the button is clicked if (!isSelect) { DataSet allDocs = null; TreeProvider tree = new TreeProvider(); // Current Node ID to translate string parentAliasPath = string.Empty; if (Parameters != null) { parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty); nodeIdsArr = ValidationHelper.GetString(Parameters["nodeids"], string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); } if (string.IsNullOrEmpty(parentAliasPath)) { if (nodeIdsArr == null) { // One document translation is requested string nodeIdQuery = QueryHelper.GetString("nodeid", ""); if (nodeIdQuery != "") { // Mode of single node translation pnlList.Visible = false; chkSkipTranslated.Checked = false; translationElem.NodeID = ValidationHelper.GetInteger(nodeIdQuery, 0); nodeIdsArr = new[] { nodeIdQuery }; } else { nodeIdsArr = new string[] { }; } } foreach (string nodeId in nodeIdsArr) { int id = ValidationHelper.GetInteger(nodeId, 0); if (id != 0) { nodeIds.Add(id); } } } else { // Exclude root of the website from multiple translation requested by document listing bulk action var where = new WhereCondition(WhereCondition) .WhereNotEquals("ClassName", SystemDocumentTypes.Root); allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%", TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where.ToString(true), "DocumentName", AllLevels ? TreeProvider.ALL_LEVELS : 1, false, 0, DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath"); if (!DataHelper.DataSourceIsEmpty(allDocs)) { foreach (DataTable table in allDocs.Tables) { foreach (DataRow row in table.Rows) { nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0)); } } } } if (nodeIds.Count > 0) { var where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true); DataSet ds = allDocs ?? tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", TreeProvider.ALL_LEVELS, false); if (!DataHelper.DataSourceIsEmpty(ds)) { string docList = null; cancelNodeId = string.IsNullOrEmpty(parentAliasPath) ? DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID") : TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath); foreach (DataTable table in ds.Tables) { foreach (DataRow dr in table.Rows) { bool isLink = (dr["NodeLinkedNodeID"] != DBNull.Value); string name = (string)dr["DocumentName"]; docList += HTMLHelper.HTMLEncode(name); if (isLink) { docList += DocumentUIHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link); } docList += "<br />"; lblDocuments.Text = docList; // Set visibility of checkboxes TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr); if (!TranslationServiceHelper.IsAuthorizedToTranslateDocument(node, currentUser, targetCultures)) { allowTranslate = false; plcMessages.AddError(String.Format(GetString("cmsdesk.notauthorizedtotranslatedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath))); } } } if (!allowTranslate && !RequestHelper.IsPostBack()) { // Hide UI only when security check is performed within first load, if postback used user may loose some setting HideUI(); } } // Display check box for separate submissions for each document if there is more than one document translationElem.DisplaySeparateSubmissionOption = (nodeIds.Count > 1); } else { // Hide everything pnlContent.Visible = false; } } // Register the dialog script ScriptHelper.RegisterDialogScript(this); ctlAsyncLog.TitleText = GetString("contentrequest.starttranslate"); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; }
protected void Page_Load(object sender, EventArgs e) { // Register script for unimenu button selection CMSDeskPage.AddMenuButtonSelectScript(this, "Contacts", null, "menu"); // Get current user info CurrentUserInfo user = CMSContext.CurrentUser; // Get contact info object ContactInfo ci = (ContactInfo)EditedObject; if (ci == null) { return; } // Check permission read ContactHelper.AuthorizedReadContact(ci.ContactSiteID, true); // Check if running under site manager (and distribute "site manager" flag to other tabs) string siteManagerParam = string.Empty; if (this.IsSiteManager) { siteManagerParam = "&issitemanager=1"; // Hide title CurrentMaster.Title.TitleText = CurrentMaster.Title.TitleImage = string.Empty; } else { // Set title CurrentMaster.Title.TitleImage = GetImageUrl("Objects/OM_Contact/object.png"); CurrentMaster.Title.TitleText = GetString("om.contact.edit"); } // Set default help topic SetHelp("onlinemarketing_contact_general", "helpTopic"); string append = null; if (ci.ContactMergedWithContactID != 0) { // Append '(merged)' behind contact name in breadcrumbs append = " " + GetString("om.contact.mergedsuffix"); } else if (ci.ContactSiteID == 0) { // Append '(global)' behind contact name in breadcrumbs append = " " + GetString("om.contact.globalsuffix"); } // Modify header appearance in modal dialog (display title instead of breadcrumbs) if (QueryHelper.GetBoolean("dialogmode", false)) { CurrentMaster.Title.TitleText = GetString("om.contact.edit") + " - " + HTMLHelper.HTMLEncode(ContactInfoProvider.GetContactFullName(ci)) + append; CurrentMaster.Title.TitleImage = GetImageUrl("Objects/OM_Contact/object.png"); } else { // Get url for breadcrumbs string url = ResolveUrl("~/CMSModules/ContactManagement/Pages/Tools/Contact/List.aspx"); url = URLHelper.AddParameterToUrl(url, "siteid", this.SiteID.ToString()); if (this.IsSiteManager) { url = URLHelper.AddParameterToUrl(url, "issitemanager", "1"); } CurrentPage.InitBreadcrumbs(2); CurrentPage.SetBreadcrumb(0, GetString("om.contact.list"), url, "_parent", null); CurrentPage.SetBreadcrumb(1, ContactInfoProvider.GetContactFullName(ci) + append, null, null, null); } // Check if contact has any custom fields int i = 0; FormInfo formInfo = FormHelper.GetFormInfo(ci.Generalized.DataClass.ClassName, false); if (formInfo.GetFormElements(true, false, true).Count > 0) { i = 1; } int contactId = ci.ContactID; bool ipTabAvailable = ActivitySettingsHelper.IPLoggingEnabled(CMSContext.CurrentSiteName) || ContactHelper.IsSiteManager; int counter = 0; // Initialize tabs this.InitTabs(7 + (ipTabAvailable ? 1 : 0) + i, "content"); this.SetTab(counter++, GetString("general.general"), "Tab_General.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_general');"); if (i > 0) { // Add tab for custom fields this.SetTab(counter++, GetString("general.customfields"), "Tab_CustomFields.aspx?contactid=" + ci.ContactID + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_customfields');"); } if (AccountHelper.AuthorizedReadAccount(ci.ContactSiteID, false) || ContactHelper.AuthorizedReadContact(ci.ContactSiteID, false)) { this.SetTab(counter++, GetString("om.account.list"), "Tab_Accounts.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_accounts');"); } this.SetTab(counter++, GetString("om.membership.list"), "Membership/Tab_Membership.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_membership');"); this.SetTab(counter++, GetString("om.activity.list"), "Tab_Activities.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_activities');"); if (ipTabAvailable) { this.SetTab(counter++, GetString("om.activity.iplist"), "Tab_IPs.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_ips');"); } // Show contact groups this.SetTab(counter++, GetString("om.contactgroup.list"), "Tab_ContactGroups.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_contactgroups');"); // Show scoring tab for site contacts if (ci.ContactSiteID > 0) { this.SetTab(counter++, GetString("om.score.list"), "Tab_Scoring.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_scoring');"); } // Hide last 3 tabs if the contact is merged if (ci.ContactMergedWithContactID == 0) { this.SetTab(counter++, GetString("om.contact.merge"), "Tab_Merge.aspx?contactid=" + contactId + siteManagerParam, "SetHelpTopic('helpTopic', 'onlinemarketing_contact_merge');"); } }
/// <summary> /// Check user permissions for document. /// </summary> /// <param name="versionHistoryInfo">Document version history info</param> /// <param name="permission">Permissions</param> /// <param name="user">User</param> /// <returns>TreeNode if authorized, null otherwise</returns> private bool IsAuthorizedPerDocument(VersionHistoryInfo versionHistoryInfo, string permission, CurrentUserInfo user) { // Check global permission var userHasGlobalPerm = user.IsAuthorizedPerResource("CMS.Content", permission); // Get the values form deleted node var className = new DocumentClassNameRetriever(versionHistoryInfo.Data, true).Retrieve(); var additionalPermission = false; if (permission.Equals("create", StringComparison.InvariantCultureIgnoreCase)) { additionalPermission = user.IsAuthorizedPerClassName(className, "CreateSpecific"); } // Check permissions if (userHasGlobalPerm || user.IsAuthorizedPerClassName(className, permission) || additionalPermission) { return(true); } return(false); }
protected void Page_Load(object sender, EventArgs e) { // Register script files ScriptHelper.RegisterCMS(this); ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js"); // Set current UI culture currentCulture = CultureHelper.PreferredUICultureCode; // Initialize current user currentUser = MembershipContext.AuthenticatedUser; // Initialize current site currentSite = SiteContext.CurrentSite; // Initialize events ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished; ctlAsyncLog.OnError += ctlAsyncLog_OnError; ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel; if (!RequestHelper.IsCallback()) { DataSet allDocs = null; TreeProvider tree = new TreeProvider(currentUser); // Current Node ID to delete string parentAliasPath = string.Empty; if (Parameters != null) { parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty); } if (string.IsNullOrEmpty(parentAliasPath)) { nodeIdsArr = QueryHelper.GetString("nodeid", string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nodeId in nodeIdsArr) { int id = ValidationHelper.GetInteger(nodeId, 0); if (id != 0) { nodeIds.Add(id); } } } else { var where = new WhereCondition(WhereCondition) .WhereNotEquals("ClassName", SystemDocumentTypes.Root); allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%", TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where.ToString(true), "DocumentName", TreeProvider.ALL_LEVELS, false, 0, DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath,NodeSKUID"); if (!DataHelper.DataSourceIsEmpty(allDocs)) { foreach (DataTable table in allDocs.Tables) { foreach (DataRow row in table.Rows) { nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0)); } } } } // Setup page title text and image PageTitle.TitleText = GetString("Content.DeleteTitle"); EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText); // Register the dialog script ScriptHelper.RegisterDialogScript(this); ctlAsyncLog.TitleText = GetString("ContentDelete.DeletingDocuments"); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; bool isMultilingual = CultureSiteInfoProvider.IsSiteMultilingual(currentSite.SiteName); if (!isMultilingual) { // Set all cultures checkbox chkAllCultures.Checked = true; pnlAllCultures.Visible = false; } if (nodeIds.Count > 0) { if (nodeIds.Count == 1) { // Single document deletion int nodeId = ValidationHelper.GetInteger(nodeIds[0], 0); TreeNode node = null; if (string.IsNullOrEmpty(parentAliasPath)) { // Get any culture if current not found node = tree.SelectSingleNode(nodeId, CultureCode) ?? tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES); } else { if (allDocs != null) { DataRow dr = allDocs.Tables[0].Rows[0]; node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr, tree); } } if (node != null) { bool rootDeleteDisabled = false; if (IsProductsMode) { string startingPath = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSStoreProductsStartingPath"); if (node.NodeAliasPath.CompareToCSafe(startingPath) == 0) { string closeLink = "<a href=\"#\"><span style=\"cursor: pointer;\" " + "onclick=\"SelectNode(" + node.NodeID + "); return false;\">" + GetString("general.back") + "</span></a>"; ShowError(string.Format(GetString("com.productsection.deleteroot"), closeLink, "")); pnlDelete.Visible = false; rootDeleteDisabled = true; } } if (node.IsRoot() && isMultilingual) { // Hide 'Delete all cultures' checkbox pnlAllCultures.Visible = false; if (!URLHelper.IsPostback()) { // Check if there are any documents in another culture or current culture has some documents pnlDeleteRoot.Visible = IsAnyDocumentInAnotherCulture(node) && (tree.SelectNodesCount(SiteContext.CurrentSiteName, "/%", LocalizationContext.PreferredCultureCode, false, null, null, null, TreeProvider.ALL_LEVELS, false) > 0); if (pnlDeleteRoot.Visible) { // Insert 'Delete current root' option if current root node is translated to current culture if (node.DocumentCulture == LocalizationContext.PreferredCultureCode) { rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentroot"), "current")); } rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentculture"), "allculturepages")); rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages")); } else { rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages")); } if (rblRoot.SelectedIndex < 0) { rblRoot.SelectedIndex = 0; } } } // Display warning for root node if (!rootDeleteDisabled && node.IsRoot()) { if (!currentUser.IsGlobalAdministrator) { pnlDelete.Visible = false; ShowInformation(GetString("delete.rootonlyglobaladmin")); } else { if ((rblRoot.SelectedValue == "allpages") || !isMultilingual || ((rblRoot.SelectedValue == "allculturepages") && !IsAnyDocumentInAnotherCulture(node))) { messagesPlaceholder.ShowWarning(GetString("Delete.RootWarning")); plcDeleteRoot.Visible = true; } else { plcDeleteRoot.Visible = false; } } } hasChildren = node.NodeHasChildren; bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node); if (!RequestHelper.IsPostBack()) { bool authorizedToDeleteDocument = IsUserAuthorizedToDeleteDocument(node); if (!authorizedToDeleteDocument || !authorizedToDeleteSKU) { pnlDelete.Visible = false; RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath))); } } if (node.IsLink) { PageTitle.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(node.GetDocumentName())) + "\""; headQuestion.Text = GetString("ContentDelete.QuestionLink"); chkAllCultures.Checked = true; plcCheck.Visible = false; } else { string nodeName = HTMLHelper.HTMLEncode(node.GetDocumentName()); // Get name for root document if (node.IsRoot()) { nodeName = HTMLHelper.HTMLEncode(currentSite.DisplayName); } PageTitle.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(nodeName)) + "\""; } // Show or hide checkbox pnlDestroy.Visible = CanDestroy(node); cancelNodeId = IsMultipleAction ? node.NodeParentID : node.NodeID; lblDocuments.Text = HTMLHelper.HTMLEncode(node.GetDocumentName()); if (node.IsRoot()) { // Change SEO panel if root is selected pnlSeo.Visible = false; } } else { if (!RequestHelper.IsPostBack()) { URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists")); } else { // Hide everything pnlContent.Visible = false; } } headQuestion.Text = GetString("ContentDelete.Question"); lblAllCultures.Text = GetString("ContentDelete.AllCultures"); lblDestroy.Text = GetString("ContentDelete.Destroy"); headDeleteDocument.Text = GetString("ContentDelete.Document"); } else if (nodeIds.Count > 1) { string where = "NodeID IN ("; foreach (int nodeID in nodeIds) { where += nodeID + ","; } where = where.TrimEnd(',') + ")"; DataSet ds = allDocs ?? tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", -1, false); if (!DataHelper.DataSourceIsEmpty(ds)) { string docList = null; if (string.IsNullOrEmpty(parentAliasPath)) { cancelNodeId = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID"); } else { cancelNodeId = TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath); } bool canDestroy = true; bool permissions = true; foreach (DataTable table in ds.Tables) { foreach (DataRow dr in table.Rows) { bool isLink = (dr["NodeLinkedNodeID"] != DBNull.Value); string name = (string)dr["DocumentName"]; docList += HTMLHelper.HTMLEncode(name); if (isLink) { docList += DocumentUIHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link); } docList += "<br />"; lblDocuments.Text = docList; // Set visibility of checkboxes TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr); if (!IsUserAuthorizedToDeleteDocument(node)) { permissions = false; AddError(String.Format( GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)), null); } // Can destroy if "can destroy all previous AND current" canDestroy = CanDestroy(node) && canDestroy; if (!hasChildren) { hasChildren = node.NodeHasChildren; } } } pnlDelete.Visible = permissions; pnlDestroy.Visible = canDestroy; } else { if (!RequestHelper.IsPostBack()) { URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists")); } else { // Hide everything pnlContent.Visible = false; } } headQuestion.Text = GetString("ContentDelete.QuestionMultiple"); PageTitle.TitleText = GetString("Content.DeleteTitleMultiple"); lblAllCultures.Text = GetString("ContentDelete.AllCulturesMultiple"); lblDestroy.Text = GetString("ContentDelete.DestroyMultiple"); headDeleteDocument.Text = GetString("global.pages"); } lblAltPath.AssociatedControlClientID = selAltPath.PathTextBox.ClientID; selAltPath.SiteID = currentSite.SiteID; chkUseDeletedPath.CheckedChanged += chkUseDeletedPath_CheckedChanged; if (!RequestHelper.IsPostBack()) { selAltPath.Enabled = false; chkAltSubNodes.Enabled = false; chkAltAliases.Enabled = false; // Set default path if is defined selAltPath.Value = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSDefaultDeletedNodePath"); if (!hasChildren) { chkAltSubNodes.Checked = false; chkAltSubNodes.Enabled = false; } } // If user has allowed cultures specified if (currentUser.UserHasAllowedCultures) { // Get all site cultures DataSet siteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSite.SiteName); bool denyAllCulturesDeletion = false; // Check that user can edit all site cultures foreach (DataRow culture in siteCultures.Tables[0].Rows) { string cultureCode = DataHelper.GetStringValue(culture, "CultureCode"); if (!currentUser.IsCultureAllowed(cultureCode, currentSite.SiteName)) { denyAllCulturesDeletion = true; } } // If user can't edit all site cultures if (denyAllCulturesDeletion) { // Hide all cultures selector pnlAllCultures.Visible = false; chkAllCultures.Checked = false; } } pnlDeleteDocument.Visible = pnlAllCultures.Visible || pnlDestroy.Visible; } else { // Hide everything pnlContent.Visible = false; } } // Initialize header action InitializeActionMenu(); }
protected void Page_Load(object sender, EventArgs e) { RegisterResizeHeaders(); CMSContext.ViewMode = ViewModeEnum.MasterPage; previewState = GetPreviewStateFromCookies(MASTERPAGE); // Keep current user user = CMSContext.CurrentUser; // Get document node tree = new TreeProvider(user); node = CMSContext.EditedObject as TreeNode; // Register the dialog script ScriptHelper.RegisterDialogScript(Page); // Register save changes ScriptHelper.RegisterSaveChanges(Page); // Save changes support bool confirmChanges = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSConfirmChanges"); string script = string.Empty; if (confirmChanges) { script = "var confirmLeave='" + ResHelper.GetString("Content.ConfirmLeave", user.PreferredUICultureCode) + "'; \n"; } else { script += "confirmChanges = false;"; } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "saveChangesScript", ScriptHelper.GetScript(script)); try { if (node != null) { CMSContext.CurrentPageInfo = PageInfoProvider.GetPageInfo(CMSContext.CurrentSiteName, node.NodeAliasPath, node.DocumentCulture, null, false); // Title string title = CMSContext.CurrentTitle; if (!string.IsNullOrEmpty(title)) { title = "<title>" + title + "</title>"; } // Body class string bodyCss = CMSContext.CurrentBodyClass; if (bodyCss != null && bodyCss.Trim() != "") { bodyCss = "class=\"" + bodyCss + "\""; } else { bodyCss = ""; } // Metadata string meta = "<meta http-equiv=\"pragma\" content=\"no-cache\" />"; string description = CMSContext.CurrentDescription; if (description != "") { meta += "<meta name=\"description\" content=\"" + description + "\" />"; } string keywords = CMSContext.CurrentKeyWords; if (keywords != "") { meta += "<meta name=\"keywords\" content=\"" + keywords + "\" />"; } // Site style sheet string cssSiteSheet = ""; int stylesheetId = CMSContext.CurrentPageInfo.DocumentStylesheetID; CssStylesheetInfo cssInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo((stylesheetId > 0) ? stylesheetId : CMSContext.CurrentSite.SiteDefaultStylesheetID); if (cssInfo != null) { cssSiteSheet = CSSHelper.GetCSSFileLink(CSSHelper.GetStylesheetUrl(cssInfo.StylesheetName)); } // Theme CSS files string themeCssFiles = ""; if (cssInfo != null) { try { string directory = URLHelper.GetPhysicalPath(string.Format("~/App_Themes/{0}/", cssInfo.StylesheetName)); if (Directory.Exists(directory)) { foreach (string file in Directory.GetFiles(directory, "*.css")) { themeCssFiles += CSSHelper.GetCSSFileLink(CSSHelper.GetPhysicalCSSUrl(cssInfo.StylesheetName, Path.GetFileName(file))); } } } catch { } } // Add values to page mHead = FormatHTML(HighlightHTML(title + meta + cssSiteSheet + themeCssFiles), 2); mBody = bodyCss; } } catch { ShowError(GetString("MasterPage.PageEditErr")); } LoadData(); // Add save action SaveAction save = new SaveAction(Page); save.CommandArgument = ComponentEvents.SAVE_DATA; save.CommandName = ComponentEvents.SAVE_DATA; headerActions.ActionsList.Add(save); if (pti != null) { // Edit layout HeaderAction action = new HeaderAction { Text = GetString("content.ui.pagelayout"), Tooltip = GetString("pageplaceholder.editlayouttooltip"), OnClientClick = "EditLayout();return false;", ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/Edit.png") }; headerActions.ActionsList.Add(action); // Edit page properties action action = new HeaderAction { Text = GetString("PageProperties.EditTemplateProperties"), Tooltip = GetString("PageProperties.EditTemplateProperties"), OnClientClick = "modalDialog('" + ResolveUrl("~/CMSModules/PortalEngine/UI/PageTemplates/PageTemplate_Edit.aspx") + "?templateid=" + pti.PageTemplateId + "&nobreadcrumbs=1&dialog=1', 'TemplateSelection', 850, 680, false);return false;", ImageUrl = GetImageUrl("CMSModules/CMS_Content/Template/edit.png") }; CMSPagePlaceholder.RegisterEditLayoutScript(this, pti.PageTemplateId, node.NodeAliasPath, null); headerActions.ActionsList.Add(action); // Preview HeaderAction preview = new HeaderAction { ControlType = HeaderActionTypeEnum.LinkButton, Text = GetString("general.preview"), OnClientClick = "performToolbarAction('split');return false;", ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/Preview.png"), SmallImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/16/Preview.png"), Visible = ((previewState == 0) && !CMSContext.DisplaySplitMode), Tooltip = GetString("preview.tooltip") }; headerActions.ActionsList.Add(preview); headerActions.ActionPerformed += new CommandEventHandler(headerActions_ActionPerformed); } RegisterInitScripts(pnlBody.ClientID, pnlMenu.ClientID, false); }
protected void Page_Load(object sender, EventArgs e) { userId = QueryHelper.GetInteger("userid", 0); currentUser = CMSContext.CurrentUser; // Check license if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), string.Empty) != string.Empty) { LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.Friends); } FriendsApprove.SelectedFriends = null; FriendsApprove.OnCheckPermissions += FriendsApprove_OnCheckPermissions; int requestedId = QueryHelper.GetInteger("requestid", 0); int friendshipId = 0; Page.Title = GetString("friends.approvefriendship"); CurrentMaster.Title.TitleText = Page.Title; CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Friends/Waitingforapproval.png"); // Multiple selection if (Request["ids"] != null) { string[] items = Request["ids"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (items.Length > 0) { ArrayList friends = new ArrayList(); foreach (string item in items) { friends.Add(ValidationHelper.GetInteger(item, 0)); } FriendsApprove.SelectedFriends = friends; if (friends.Count == 1) { friendshipId = Convert.ToInt32(friends[0]); } } } // For one user else { FriendsApprove.RequestedUserID = requestedId; } FriendInfo fi = null; if (friendshipId != 0) { fi = FriendInfoProvider.GetFriendInfo(friendshipId); // Set edited object EditedObject = fi; } else if (requestedId != 0) { fi = FriendInfoProvider.GetFriendInfo(userId, requestedId); // Set edited object EditedObject = fi; } if (fi != null) { UserInfo requestedUser = (userId == fi.FriendRequestedUserID) ? UserInfoProvider.GetFullUserInfo(fi.FriendUserID) : UserInfoProvider.GetFullUserInfo(fi.FriendRequestedUserID); string fullUserName = Functions.GetFormattedUserName(requestedUser.UserName, requestedUser.FullName, requestedUser.UserNickName, false); Page.Title = GetString("friends.approvefriendshipwith") + " " + HTMLHelper.HTMLEncode(fullUserName); CurrentMaster.Title.TitleText = Page.Title; } // Set current user FriendsApprove.UserID = userId; }
/// <summary> /// Empties recycle bin. /// </summary> private void EmptyBin(object parameter) { // Begin log AddLog(ResHelper.GetString("Recyclebin.EmptyingBin", mCurrentCulture)); BinSettingsContainer settings = (BinSettingsContainer)parameter; CurrentUserInfo currentUserInfo = settings.User; string where = null; DateTime modifiedFrom = DateTimeHelper.ZERO_TIME; DateTime modifiedTo = DateTimeHelper.ZERO_TIME; switch (settings.CurrentWhat) { case What.AllDocuments: SetDocumentAge(ref modifiedFrom, ref modifiedTo); where = GetWhereCondition(filter.WhereCondition); break; case What.SelectedDocuments: // Restore selected documents var toRestore = settings.SelectedItems; if ((toRestore != null) && (toRestore.Count > 0)) { where = new WhereCondition().WhereIn("VersionHistoryID", toRestore).ToString(true); } break; } DataSet recycleBin = VersionHistoryInfoProvider.GetRecycleBin((mSelectedSite != null) ? mSelectedSite.SiteID : 0, 0, @where, "DocumentNamePath ASC", -1, null, modifiedFrom, modifiedTo); try { if (!DataHelper.DataSourceIsEmpty(recycleBin)) { TreeProvider tree = new TreeProvider(currentUserInfo); tree.AllowAsyncActions = false; VersionManager versionManager = VersionManager.GetInstance(tree); foreach (DataRow dr in recycleBin.Tables[0].Rows) { int versionHistoryId = Convert.ToInt32(dr["VersionHistoryID"]); var versionHistoryInfo = GetVersionHistoryInfo(versionHistoryId); string documentNamePath = ValidationHelper.GetString(dr["DocumentNamePath"], string.Empty); // Check permissions if (!IsAuthorizedPerDocument(versionHistoryInfo, "Destroy", mCurrentUser)) { CurrentError = String.Format(ResHelper.GetString("Recyclebin.DestructionFailedPermissions", mCurrentCulture), documentNamePath); AddLog(CurrentError); } else { AddLog(ResHelper.GetString("general.document", mCurrentCulture) + "'" + HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["DocumentNamePath"], string.Empty)) + "'"); // Destroy the version versionManager.DestroyDocumentHistory(ValidationHelper.GetInteger(dr["DocumentID"], 0)); LogContext.LogEventToCurrent(EventType.INFORMATION, "Content", "DESTROYDOC", string.Format(ResHelper.GetString("Recyclebin.documentdestroyed"), documentNamePath), RequestContext.RawURL, mCurrentUser.UserID, mCurrentUser.UserName, 0, null, RequestContext.UserHostAddress, SiteContext.CurrentSiteID, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now); } } if (!String.IsNullOrEmpty(CurrentError)) { CurrentError = ResHelper.GetString("recyclebin.errorsomenotdestroyed", mCurrentCulture); AddLog(CurrentError); } else { CurrentInfo = ResHelper.GetString("recyclebin.destroyok", mCurrentCulture); AddLog(CurrentInfo); } } } catch (ThreadAbortException ex) { if (!CMSThread.Stopped(ex)) { // Log error LogException("DESTROYDOC", ex); } } catch (Exception ex) { // Log error LogException("DESTROYDOC", ex); } }
protected void Page_Load(object sender, EventArgs e) { currentUser = CMSContext.CurrentUser; // Use UI culture for strings string culture = currentUser.PreferredUICultureCode; // Hide the add MVT/CP variant when Manage permission is not allowed if (!currentUser.IsAuthorizedPerResource("cms.contentpersonalization", "Manage")) { plcAddCPVariant.Visible = false; } if (!currentUser.IsAuthorizedPerResource("cms.mvtest", "Manage")) { plcAddMVTVariant.Visible = false; } // Main menu imgNewWebPart.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Add.png"); lblNewWebPart.Text = ResHelper.GetString("ZoneMenu.IconNewWebPart", culture); imgNewWebPart.AlternateText = lblNewWebPart.Text; pnlNewWebPart.Attributes.Add("onclick", "ContextNewWebPart(GetContextMenuParameter('webPartZoneMenu'));"); // Configure imgConfigureZone.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Properties.png"); lblConfigureZone.Text = ResHelper.GetString("ZoneMenu.IconConfigureWebpartZone", culture); imgConfigureZone.AlternateText = lblConfigureZone.Text; pnlConfigureZone.Attributes.Add("onclick", "ContextConfigureWebPartZone(GetContextMenuParameter('webPartZoneMenu'));"); // Move to imgMoveTo.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/MoveTo.png"); lblMoveTo.Text = ResHelper.GetString("ZoneMenu.IconMoveTo", culture); // Delete all web parts imgDelete.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Delete.png"); lblDelete.Text = ResHelper.GetString("ZoneMenu.RemoveAll", culture); imgDelete.AlternateText = lblDelete.Text; pnlDelete.Attributes.Add("onclick", "ContextRemoveAllWebParts(GetContextMenuParameter('webPartZoneMenu'));"); // Add new MVT variants lblAddMVTVariant.Text = ResHelper.GetString("ZoneMenu.AddZoneVariant", culture); imgAddMVTVariant.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Variants/addZone.png"); imgAddMVTVariant.AlternateText = lblAddMVTVariant.Text; // Add new Content personalization variant lblAddCPVariant.Text = ResHelper.GetString("ZoneMenu.AddZoneVariant", culture); imgAddCPVariant.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Variants/addZone.png"); imgAddCPVariant.AlternateText = lblAddCPVariant.Text; // Add new variant pnlAddMVTVariant.Attributes.Add("onclick", "ContextAddWebPartZoneMVTVariant(GetContextMenuParameter('webPartZoneMenu'));"); pnlAddCPVariant.Attributes.Add("onclick", "ContextAddWebPartZoneCPVariant(GetContextMenuParameter('webPartZoneMenu'));"); // List all variants lblMVTVariants.Text = ResHelper.GetString("ZoneMenu.ZoneMVTVariants", culture); lblCPVariants.Text = ResHelper.GetString("ZoneMenu.ZonePersonalizationVariants", culture); // No MVT variants lblNoZoneMVTVariants.Text = ResHelper.GetString("ZoneMenu.NoVariants"); imgNoZoneMVTVariants.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Variants/novariant.png"); // No CP variants lblNoZoneCPVariants.Text = ResHelper.GetString("ZoneMenu.NoVariants"); imgNoZoneCPVariants.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Variants/novariant.png"); // List all variants imgMVTVariants.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Variants/zoneList.png"); imgMVTVariants.AlternateText = lblMVTVariants.Text; imgCPVariants.ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/ContextMenu/Variants/zoneList.png"); imgCPVariants.AlternateText = lblCPVariants.Text; if (PortalManager.CurrentPlaceholder != null) { // Build the list of web part zones ArrayList webPartZones = new ArrayList(); if (PortalManager.CurrentPlaceholder.WebPartZones != null) { foreach (CMSWebPartZone zone in PortalManager.CurrentPlaceholder.WebPartZones) { // Add only standard zones to the list if (zone.ZoneInstance.WidgetZoneType == WidgetZoneTypeEnum.None) { webPartZones.Add(zone); } } } repZones.DataSource = webPartZones; repZones.DataBind(); } if (PortalContext.MVTVariantsEnabled || PortalContext.ContentPersonalizationEnabled) { menuMoveToZoneVariants.LoadingContent = "<div class=\"PortalContextMenu ZoneContextMenu\"><div class=\"ItemPadding\">" + ResHelper.GetString("ContextMenu.Loading", CultureHelper.GetPreferredUICulture()) + "</div></div>"; menuMoveToZoneVariants.OnReloadData += menuMoveToZoneVariants_OnReloadData; repMoveToZoneVariants.ItemDataBound += repZoneVariants_ItemDataBound; // Display the MVT menu part in the CMSDesk->Design only. Hide the context menu in the SM->PageTemplates->Design if (PortalContext.MVTVariantsEnabled && (CMSContext.CurrentPageInfo != null) && (CMSContext.CurrentPageInfo.DocumentID > 0) && currentUser.IsAuthorizedPerResource("cms.mvtest", "read")) { // Set Display='none' for the MVT panel. Show dynamically only if required. pnlContextMenuMVTVariants.Visible = true; pnlContextMenuMVTVariants.Style.Add("display", "none"); menuZoneMVTVariants.LoadingContent = "<div class=\"PortalContextMenu ZoneContextMenu\"><div class=\"ItemPadding\">" + ResHelper.GetString("ContextMenu.Loading", CultureHelper.GetPreferredUICulture()) + "</div></div>"; menuZoneMVTVariants.OnReloadData += menuZoneMVTVariants_OnReloadData; repZoneMVTVariants.ItemDataBound += repVariants_ItemDataBound; string script = "zoneMVTVariantContextMenuId = '" + pnlContextMenuMVTVariants.ClientID + "';"; ScriptHelper.RegisterStartupScript(this, typeof(string), "zoneMVTVariantContextMenuId", ScriptHelper.GetScript(script)); } else { // Hide the MVT variant context menu items when MVT is not enabled for the current document pnlUIMVTVariants.Visible = false; } // Display the Content personalization menu part in the CMSDesk->Design only. Hide the context menu in the SM->PageTemplates->Design if ((PortalContext.ContentPersonalizationEnabled) && (CMSContext.CurrentPageInfo != null) && (CMSContext.CurrentPageInfo.DocumentID > 0) && currentUser.IsAuthorizedPerResource("cms.contentpersonalization", "read")) { // Set Display='none' for the MVT panel. Show dynamically only if required. pnlContextMenuCPVariants.Visible = true; pnlContextMenuCPVariants.Style.Add("display", "none"); menuZoneCPVariants.LoadingContent = "<div class=\"PortalContextMenu ZoneContextMenu\"><div class=\"ItemPadding\">" + ResHelper.GetString("ContextMenu.Loading", CultureHelper.GetPreferredUICulture()) + "</div></div>"; menuZoneCPVariants.OnReloadData += menuZoneCPVariants_OnReloadData; repZoneCPVariants.ItemDataBound += repVariants_ItemDataBound; string script = "zoneCPVariantContextMenuId = '" + pnlContextMenuCPVariants.ClientID + "';"; ScriptHelper.RegisterStartupScript(this, typeof(string), "zoneCPVariantContextMenuId", ScriptHelper.GetScript(script)); } else { // Hide the Content personalization variant context menu items when the Content Personalization is not enabled. pnlUICPVariants.Visible = false; } } }
/// <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); }
protected void Page_Load(object sender, EventArgs e) { ucDisplayReport = this.LoadUserControl("~/CMSModules/Reporting/Controls/DisplayReport.ascx") as IDisplayReport; reportHeader.ActionPerformed += HeaderActions_ActionPerformed; pnlContent.Controls.Add((Control)ucDisplayReport); // Set disabled module info ucDisabledModule.SettingsKeys = "CMSAnalyticsEnabled;CMSABTestingEnabled"; ucDisabledModule.InfoTexts.Add(GetString("WebAnalytics.Disabled") + "</br>"); ucDisabledModule.InfoTexts.Add(GetString("abtesting.disabled")); ucDisabledModule.ParentPanel = pnlWarning; CurrentMaster.PanelContent.CssClass = ""; UIHelper.AllowUpdateProgress = false; // ABTest Info int abTestID = QueryHelper.GetInteger("abtestid", 0); ABTestInfo abInfo = ABTestInfoProvider.GetABTestInfo(abTestID); if (abInfo == null) { return; } siteName = CMSContext.CurrentSiteName; testName = abInfo.ABTestName; // Variants condition ucSelectVariation.WhereCondition = "ABVariantTestID IN ( SELECT ABTestID FROM OM_ABTest WHERE ABTestName = N'" + testName + "')"; ucGraphType.ProcessChartSelectors(false); // Enables/disables radio buttons (based on UI elements) CurrentUserInfo ui = CMSContext.CurrentUser; if (!RequestHelper.IsPostBack()) { if (!ui.IsGlobalAdministrator) { rbCount.Enabled = ui.IsAuthorizedPerUIElement("cms.WebAnalytics", "ABTest.ConversionsCount"); rbRate.Enabled = ui.IsAuthorizedPerUIElement("cms.WebAnalytics", "ABTest.ConversionsRate"); rbValue.Enabled = ui.IsAuthorizedPerUIElement("cms.WebAnalytics", "ABTest.ConversionsValue"); rbSourcePages.Enabled = ui.IsAuthorizedPerUIElement("cms.WebAnalytics", "ABTest.ConversionsSourcePages"); rbVariants.Enabled = ui.IsAuthorizedPerUIElement("cms.WebAnalytics", "ABTest.ConversionsByVariations"); bool checkedButton = false; // Check first enabled button foreach (Control ctrl in pnlRadios.Controls) { RadioButton rb = ctrl as RadioButton; if (rb != null) { if (rb.Enabled) { rb.Checked = true; checkedButton = true; break; } } } // No report avaible -> redirect to access denied if (!checkedButton) { RedirectToAccessDenied(GetString("abtest.noreportavaible")); } } else { // Admin check first radio button rbCount.Checked = true; } } }
protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterProgress(this); if (!RequestHelper.IsPostBack()) { chkWebParts.Checked = PortalHelper.DisplayContentInDesignMode; } chkWebParts.Attributes.Add("onclick", "SaveSettings()"); chkWebParts.Text = GetString("EditTabs.DisplayContent"); string scripts = @" function SetTabsContext(mode) { if ((mode == 'design') || (mode == 'wireframe')) { document.getElementById('divDesign').style.display = 'block'; } else { document.getElementById('divDesign').style.display = 'none'; } parent.SetSelectedMode(mode); } function RefreshContent() { parent.frames['contenteditview'].document.location.replace(parent.frames['contenteditview'].document.location); } function SaveSettings() { __theFormPostData = ''; WebForm_InitCallback(); " + ClientScript.GetCallbackEventReference(this, "'save'", "RefreshContent", null) + @"; }"; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "editTabsScripts", scripts, true); // Initialize tabs tabsModes.OnTabCreated += tabModes_OnTabCreated; tabsModes.OnCheckTabSecurity += tabsModes_OnCheckTabSecurity; tabsModes.SelectedTab = 0; tabsModes.UrlTarget = "contenteditview"; // Process the page mode currentUser = CMSContext.CurrentUser; if (Node != null) { // Product tab showProductTab = Node.HasSKU; // Initialize required variables authorizedPerDesign = currentUser.IsAuthorizedPerResource("CMS.Design", "Design"); isWireframe = Node.IsWireframe(); hasWireframe = isWireframe || (Node.NodeWireframeTemplateID > 0); // Get page template information try { PageInfo pi = PageInfoProvider.GetPageInfo(CMSContext.CurrentSiteName, Node.NodeAliasPath, Node.DocumentCulture, Node.DocumentUrlPath, false); if ((pi != null) && (pi.DesignPageTemplateInfo != null)) { PageTemplateInfo pti = pi.DesignPageTemplateInfo; isPortalPage = pti.IsPortal; isMasterPage = isPortalPage && ((Node.NodeAliasPath == "/") || pti.ShowAsMasterTemplate); designEnabled = ((pti.PageTemplateType == PageTemplateTypeEnum.Portal) || (pti.PageTemplateType == PageTemplateTypeEnum.AspxPortal)); } } catch { // Page info not found - probably tried to display document from different site } // Do not show design tab for CMS.File if (Node.NodeClassName.EqualsCSafe("CMS.File", true)) { designEnabled = false; } } }