/// <summary> /// Creates tag. Called when the "Create tag" button is pressed. /// </summary> private bool AddTagToDocument() { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Get the root document TreeNode root = tree.SelectSingleNode(CMSContext.CurrentSiteName, "/", null, true); // Get tag group ID TagGroupInfo updateGroup = TagGroupInfoProvider.GetTagGroupInfo("MyNewGroup", CMSContext.CurrentSiteID); if ((root != null) && (updateGroup != null)) { // Add tag to document root.DocumentTags = "\"My New Tag\""; // Add tag to document root.DocumentTagGroupID = updateGroup.TagGroupID; // Update document root.Update(); return true; } return false; }
/// <summary> /// Creates attendee. Called when the "Create attendee" button is pressed. /// Expects the CreateEvent method to be run first. /// </summary> private bool CreateAttendee() { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Get event document TreeNode eventNode = tree.SelectSingleNode(CMSContext.CurrentSiteName, "/MyNewDocument/MyNewEvent", null, true); if (eventNode != null) { // Create new attendee object EventAttendeeInfo newAttendee = new EventAttendeeInfo(); // Set the properties newAttendee.AttendeeEmail = "*****@*****.**"; newAttendee.AttendeeEventNodeID = eventNode.NodeID; newAttendee.AttendeeFirstName = "My firstname"; newAttendee.AttendeeLastName = "My lastname"; // Save the attendee EventAttendeeInfoProvider.SetEventAttendeeInfo(newAttendee); return true; } return false; }
/// <summary> /// Apply control settings. /// </summary> public bool ApplySettings() { if (MasterTemplateId <= 0) { lblError.Text = GetString("TemplateSelection.SelectTemplate"); return false; } else { // Update all culture versions TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); DataSet ds = tree.SelectNodes(SiteName, "/", TreeProvider.ALL_CULTURES, false, "CMS.Root", null, null, -1, false); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { // Update the document TreeNode node = TreeNode.New("CMS.Root", dr, tree); node.SetDefaultPageTemplateID(MasterTemplateId); node.Update(); // Update search index for node if (DocumentHelper.IsSearchTaskCreationAllowed(node)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID); } } } } return true; }
protected void Page_Load(object sender, EventArgs e) { districtParm = DistrictParms.LoadDistrictParms(); treeProvider = KenticoHelper.GetUserTreeProvider(SessionObject.LoggedInUser.ToString()); Master.Search += SearchHandler; base.Page_Init(sender, e); if (!IsPostBack) { InitializeCriteriaControls(); } btnAdd.Visible = UserHasPermission(Thinkgate.Base.Enums.Permission.Add_Reference); string cmsTreePathToReferences = ConfigurationManager.AppSettings["CMSTreePathToReferences"]; if (districtParm.isStateSystem) stateInitial.Value = districtParm.State.ToString(); if (!string.IsNullOrWhiteSpace(cmsTreePathToReferences)) { TreeNode tNode = treeProvider.SelectSingleNode(CMSContext.CurrentSiteName, cmsTreePathToReferences.Substring(0, cmsTreePathToReferences.Length - 2), CMSContext.PreferredCultureCode); if (tNode != null) { int messageCenterClassId = CMS.SettingsProvider.DataClassInfoProvider.GetDataClass("Thinkgate.ReferenceCenter").ClassID; classId.Value = messageCenterClassId.ToString(); parentNodeId.Value = tNode.NodeID.ToString(); clientName.Value = districtParm.ClientID.ToString(); } } }
/// <summary> /// Returns true if contact came to specified landing page. /// </summary> /// <param name="parameters">Contact; Node ID or alias path of the page</param> public static object CameToLandingPage(params object[] parameters) { switch (parameters.Length) { case 2: int nodeId = ValidationHelper.GetInteger(parameters[1], 0); string nodeIds = null; if (nodeId <= 0) { string alias = ValidationHelper.GetString(parameters[1], ""); if (!string.IsNullOrEmpty(alias)) { TreeNodeDataSet ds = new TreeProvider().SelectNodes(TreeProvider.ALL_SITES, alias, TreeProvider.ALL_CULTURES, true); if (!DataHelper.DataSourceIsEmpty(ds)) { nodeIds = TextHelper.Join(",", SystemDataHelper.GetStringValues(ds.Tables[0], "NodeID")); } } } if (nodeId > 0) { return OnlineMarketingFunctions.DidActivity(parameters[0], "landingpage", null, 0, "ActivityNodeID = " + nodeId); } else if (!string.IsNullOrEmpty(nodeIds)) { return OnlineMarketingFunctions.DidActivity(parameters[0], "landingpage", null, 0, "ActivityNodeID IN (" + nodeIds + ")"); } return false; default: throw new NotSupportedException(); } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { string path = (string)this.GetValue("Path"); string formatPath = path.Substring(1); try { litArchive.Text = (string)this.GetValue("Header"); DataSet dataSet = null; TreeProvider tree = new TreeProvider(); dataSet = tree.SelectNodes("Custom.BlogMonth").Path(formatPath, PathTypeEnum.Children) .Where("") .OrderBy("NodeLevel, NodeOrder, NodeName"); if (dataSet != null) { rptblogLister.DataSource = dataSet.Tables[0]; rptblogLister.DataBind(); } } catch (Exception ex1) { Response.Write(ex1.Message.ToString() + ex1.StackTrace.ToString()); } }
/// <summary> /// Copies the document under workflow to a different section. Called when the "Copy document" button is pressd. /// Expects the "CreateExampleObjects" and "CreateDocument" methods to be run first. /// </summary> private bool CopyDocument() { // Create an instance of the Tree provider first TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Prepare parameters string siteName = CMSContext.CurrentSiteName; string aliasPath = "/API-Example/My-new-document"; string culture = "en-us"; bool combineWithDefaultCulture = false; string classNames = TreeProvider.ALL_CLASSNAMES; string where = null; string orderBy = null; int maxRelativeLevel = -1; bool selectOnlyPublished = false; string columns = null; // Get the example folder TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree); aliasPath = "/API-Example/Source"; // Get the new parent document TreeNode parentNode = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree); if ((node != null) && (parentNode != null)) { // Copy the document DocumentHelper.CopyDocument(node, parentNode.NodeID, false, tree); return true; } return false; }
public void ProcessAction() { if (ctrl != null) { // Get the node TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = tree.SelectSingleNode(mNodeId); int groupId = ValidationHelper.GetInteger(ctrl.Value, 0); // Check inherited documents if (chkInherit.Checked) { tree.ChangeCommunityGroup(node.NodeAliasPath, groupId, mSiteId, true); } // Update the document node node.SetIntegerValue("NodeGroupID", groupId, false); node.Update(); // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } ltlScript.Text = ScriptHelper.GetScript("wopener.ReloadOwner(); window.close();"); }
protected void Page_Load(object sender, EventArgs e) { int currentNodeId = QueryHelper.GetInteger("nodeid", 0); // Initializes page breadcrumbs string[,] pageTitleTabs = new string[2, 3]; pageTitleTabs[0, 0] = GetString("Relationship.RelatedDocs"); pageTitleTabs[0, 1] = "~/CMSModules/Content/CMSDesk/Properties/Relateddocs_List.aspx?nodeid=" + currentNodeId; pageTitleTabs[0, 2] = "propedit"; pageTitleTabs[1, 0] = GetString("Relationship.AddRelatedDocs"); pageTitleTabs[1, 1] = string.Empty; pageTitleTabs[1, 2] = string.Empty; titleElem.Breadcrumbs = pageTitleTabs; if (currentNodeId > 0) { TreeProvider treeProvider = new TreeProvider(CMSContext.CurrentUser); TreeNode node = treeProvider.SelectSingleNode(currentNodeId); // Set edited document EditedDocument = node; // Set node addRelatedDocument.TreeNode = node; addRelatedDocument.IsLiveSite = false; } }
/// <summary> /// Apply control settings. /// </summary> public bool ApplySettings() { if (MasterTemplateId <= 0) { lblError.Text = GetString("TemplateSelection.SelectTemplate"); return false; } else { // Update all culture versions TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); DataSet ds = tree.SelectNodes(SiteName, "/", TreeProvider.ALL_CULTURES, false, "CMS.Root", null, null, -1, false); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { // Update the document TreeNode node = TreeNode.New(dr, "CMS.Root", tree); node.DocumentPageTemplateID = MasterTemplateId; node.Update(); // Update search index for node if ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } } } } return true; }
protected void Page_Load(object sender, EventArgs e) { // Redirect to the web site root by default string returnUrl = URLHelper.ResolveUrl("~/"); // Check whether on-site editing is enabled if (PortalHelper.IsOnSiteEditingEnabled(SiteContext.CurrentSiteName)) { var cui = MembershipContext.AuthenticatedUser; // Check the permissions if (cui.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor,SiteContext.CurrentSiteName) && cui.IsAuthorizedPerResource("cms.content", "ExploreTree") && cui.IsAuthorizedPerResource("cms.content", "Read")) { // Set edit-live view mode PortalContext.SetViewMode(ViewModeEnum.EditLive); } else { // Redirect to access denied page when the current user does not have permissions for the OnSite editing CMSPage.RedirectToUINotAvailable(); } // Try get return URL string queryUrl = QueryHelper.GetString("returnurl", String.Empty); if (!String.IsNullOrEmpty(queryUrl) && (queryUrl.StartsWithCSafe("~/") || queryUrl.StartsWithCSafe("/"))) { // Remove return url duplication if exist int commaIndex = queryUrl.IndexOfCSafe(",", 0, false); if (commaIndex > 0) { queryUrl = queryUrl.Substring(0, commaIndex); } returnUrl = URLHelper.ResolveUrl(queryUrl); } // Use default alias path if return url isn't defined else { string aliasPath = PageInfoProvider.GetDefaultAliasPath(RequestContext.CurrentDomain, SiteContext.CurrentSiteName); if (!String.IsNullOrEmpty(aliasPath)) { // Get the document which will be displayed for the default alias path TreeProvider tr = new TreeProvider(); TreeNode node = tr.SelectSingleNode(SiteContext.CurrentSiteName, aliasPath, LocalizationContext.PreferredCultureCode, true); if (node != null) { aliasPath = node.NodeAliasPath; } returnUrl = DocumentURLProvider.GetUrl(aliasPath); returnUrl = URLHelper.ResolveUrl(returnUrl); } } // Remove view mode value from query string returnUrl = URLHelper.RemoveParameterFromUrl(returnUrl, "viewmode"); } // Redirect to the requested page URLHelper.Redirect(returnUrl); }
/// <summary> /// Get url by Guid</summary> public static string GetDocumentLink(Guid nodeGuid, string siteName) { var tp = new TreeProvider(); TreeNode tn = tp.SelectSingleNode(TreePathUtils.GetNodeIdByNodeGUID(nodeGuid, siteName)); if (tn != null) return tn.RelativeURL; return string.Empty; }
protected void Page_Load(object sender, EventArgs e) { // Register script files ScriptHelper.RegisterShortcuts(this); ScriptHelper.RegisterSpellChecker(this); ltlScript.Text = GetSpellCheckDialog(); parentNodeId = QueryHelper.GetInteger("nodeid", 0); txtPageName.MaxLength = TreePathUtils.MaxNameLength; TreeProvider tp = new TreeProvider(CMSContext.CurrentUser); // For new node is not document culture important, preffered culture is used TreeNode node = tp.SelectSingleNode(parentNodeId); if (node != null) { selTemplate.DocumentID = node.DocumentID; selTemplate.ParentNodeID = parentNodeId; } // Register progress script ScriptHelper.RegisterProgress(Page); // Check permission to create page with redirect CheckSecurity(true); if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert)) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.documentslicenselimits"), "")); } // Hide error label lblError.Style.Add("display", "none"); string jsValidation = "function ValidateNewPage(){" + " var value = document.getElementById('" + txtPageName.ClientID + "').value;" + " value = value.replace(/^\\s+|\\s+$/g, '');" + " var errorLabel = document.getElementById('" + lblError.ClientID + "'); " + " if (value == '') {" + " errorLabel.style.display = ''; errorLabel.innerHTML = " + ScriptHelper.GetString(GetString("newpage.nameempty")) + "; resizearea(); return false;}"; jsValidation += selTemplate.GetValidationScript(); jsValidation += " return true;}"; // Register validate script ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ValidateNewPage", ScriptHelper.GetScript(jsValidation)); // Register save document script ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "SaveDocument", ScriptHelper.GetScript("function SaveDocument(nodeId, createAnother) {if (ValidateNewPage()) { " + ControlsHelper.GetPostBackEventReference(this, "#", false).Replace("'#'", "createAnother+''") + "; return false; }}")); // Set default focus on page name field if (!RequestHelper.IsPostBack()) { txtPageName.Focus(); } }
protected void Page_Load(object sender, EventArgs e) { // Register the scripts ScriptHelper.RegisterProgress(this.Page); UIContext.PropertyTab = PropertyTabEnum.Categories; // UI settings lblCategoryInfo.Text = GetString("Categories.DocumentAssignedTo"); categoriesElem.DisplaySavedMessage = false; categoriesElem.OnAfterSave += categoriesElem_OnAfterSave; categoriesElem.UniSelector.OnSelectionChanged += categoriesElem_OnSelectionChanged; int nodeId = QueryHelper.GetInteger("nodeid", 0); if (nodeId > 0) { tree = new TreeProvider(CMSContext.CurrentUser); node = tree.SelectSingleNode(nodeId, CMSContext.PreferredCultureCode, false); // Redirect to page 'New culture version' in split mode. It must be before setting EditedDocument. if ((node == null) && displaySplitMode) { URLHelper.Redirect("~/CMSModules/Content/CMSDesk/New/NewCultureVersion.aspx" + URLHelper.Url.Query); } // Set edited document EditedDocument = node; if (node != null) { // Check read permissions if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } // Check modify permissions else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { hasModifyPermission = false; pnlUserCatgerories.Enabled = false; // Disable selector categoriesElem.Enabled = false; lblCategoryInfo.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), node.NodeAliasPath); lblCategoryInfo.Visible = true; } // Display all global categories in administration UI categoriesElem.UserID = CMSContext.CurrentUser.UserID; categoriesElem.DocumentID = node.DocumentID; // Register js synchronization script for split mode if (displaySplitMode) { RegisterSplitModeSync(true, false); } } } }
protected void Page_Load(object sender, EventArgs e) { UIContext.PropertyTab = PropertyTabEnum.RelatedDocs; nodeId = QueryHelper.GetInteger("nodeid", 0); // Check if any relationship exists DataSet dsRel = RelationshipNameInfoProvider.GetRelationshipNames("RelationshipNameID", "RelationshipAllowedObjects LIKE '%" + CMSObjectHelper.GROUP_DOCUMENTS + "%' AND RelationshipNameID IN (SELECT RelationshipNameID FROM CMS_RelationshipNameSite WHERE SiteID = " + CMSContext.CurrentSiteID + ")", null, 1); if (DataHelper.DataSourceIsEmpty(dsRel)) { pnlNewItem.Visible = false; relatedDocuments.Visible = false; lblInfo.Text = ResHelper.GetString("relationship.norelationship"); lblInfo.Visible = true; } else { if (nodeId > 0) { // Get the node tree = new TreeProvider(CMSContext.CurrentUser); node = tree.SelectSingleNode(nodeId, CMSContext.PreferredCultureCode, tree.CombineWithDefaultCulture); // Set edited document EditedDocument = node; if (node != null) { // Check read permissions if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath)); } // Check modify permissions else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { relatedDocuments.Enabled = false; lnkNewRelationship.Enabled = false; imgNewRelationship.Enabled = false; lblInfo.Visible = true; lblInfo.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), node.NodeAliasPath); } else { lblInfo.Visible = false; } // Set tree node relatedDocuments.TreeNode = node; // Initialize controls lnkNewRelationship.NavigateUrl = "~/CMSModules/Content/CMSDesk/Properties/Relateddocs_Add.aspx?nodeid=" + nodeId; imgNewRelationship.ImageUrl = GetImageUrl("CMSModules/CMS_Content/Properties/addrelationship.png"); imgNewRelationship.DisabledImageUrl = GetImageUrl("CMSModules/CMS_Content/Properties/addrelationshipdisabled.png"); } } } }
protected void Page_Load(object sender, EventArgs e) { // Current Node ID int nodeId = 0; if (Request.QueryString["nodeid"] != null) { nodeId = ValidationHelper.GetInteger(Request.QueryString["nodeid"], 0); } switch (QueryHelper.GetString("action", "edit").ToLower()) { case "delete": // Do not include title upon delete this.titleElem.SetWindowTitle = false; break; } // Get the node string aliasPath = TreePathUtils.GetAliasPathByNodeId(nodeId); if (aliasPath == "/") { // Set path as site name if empty SiteInfo si = CMSContext.CurrentSite; if (si != null) { this.titleElem.CreateStaticBreadCrumbs(HttpUtility.HtmlEncode(si.DisplayName)); } } else { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Get the DataSet of nodes string where = TreeProvider.GetNodesOnPathWhereCondition(aliasPath, true, true); DataSet ds = DocumentHelper.GetDocuments(CMSContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "NodeLevel ASC", -1, false, tree); if (!DataHelper.DataSourceIsEmpty(ds)) { string[,] bc = new string[ds.Tables[0].Rows.Count, 3]; int index = 0; // Build the path foreach (DataRow dr in ds.Tables[0].Rows) { string documentName = ValidationHelper.GetString(dr["DocumentName"], ""); bc[index, 0] = documentName; bc[index, 1] = string.Empty; bc[index, 2] = string.Empty; index++; } this.titleElem.Breadcrumbs = bc; } } }
protected void Page_Load(object sender, EventArgs e) { // Initialization productId = QueryHelper.GetInteger("productId", 0); skuGuid = QueryHelper.GetGuid("skuguid", Guid.Empty); currentSite = SiteContext.CurrentSite; var skuObj = SKUInfoProvider.GetSKUInfo(productId); if ((skuObj != null) && skuObj.IsProductVariant) { // Get parent product of variant var parent = skuObj.Parent as SKUInfo; if (parent != null) { productId = parent.SKUID; skuGuid = parent.SKUGUID; } } string where = null; if (productId > 0) { where = "NodeSKUID = " + productId; } else if (skuGuid != Guid.Empty) { where = "SKUGUID = '" + skuGuid + "'"; } if ((where != null) && (currentSite != null)) { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); DataSet ds = tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, "", where); if (!DataHelper.DataSourceIsEmpty(ds)) { // Ger specified product url url = DocumentURLProvider.GetUrl(Convert.ToString(ds.Tables[0].Rows[0]["NodeAliasPath"])); } } if ((url != "") && (currentSite != null)) { // Redirect to specified product URLHelper.RedirectPermanent(url, currentSite.SiteName); } else { // Display error message lblInfo.Visible = true; lblInfo.Text = GetString("GetProduct.NotFound"); } }
/// <summary> /// Get node by Guid</summary> /// <remarks> /// Return null if nodeGuid is empty or node is not exist </remarks> public static TreeNode GetNode(Guid nodeGuid, string siteName) { if (nodeGuid != Guid.Empty) { var tp = new TreeProvider(); return tp.SelectSingleNode(TreePathUtils.GetNodeIdByNodeGUID(nodeGuid, siteName)); } return null; }
protected void Page_Load(object sender, EventArgs e) { // Register the dialog script ScriptHelper.RegisterDialogScript(this); // Get the document ID int nodeId = ValidationHelper.GetInteger(Request.QueryString["nodeid"], 0); TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES); if (node == null) { this.menuElem.Visible = false; } }
public override void ReloadData(bool forceLoad) { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); DocTreeNode nd = tree.SelectSingleNode(EventID, LocalizationContext.PreferredCultureCode, tree.CombineWithDefaultCulture, false); if (nd == null) { ShowInformation(GetString("editedobject.notexists")); plcSend.Visible = false; lblTitle.Visible = false; return; } //Enable controls txtSenderName.Enabled = true; txtSenderEmail.Enabled = true; txtSubject.Enabled = true; htmlEmail.Enabled = true; btnSend.Enabled = true; if (forceLoad) { string siteName = SiteContext.CurrentSiteName; txtSenderEmail.Text = SettingsKeyInfoProvider.GetValue(siteName + ".CMSEventManagerInvitationFrom"); txtSenderName.Text = SettingsKeyInfoProvider.GetValue(siteName + ".CMSEventManagerSenderName"); txtSubject.Text = SettingsKeyInfoProvider.GetValue(siteName + ".CMSEventManagerInvitationSubject"); } // Disable form if no attendees present or user doesn't have modify permission if (MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.eventmanager", "Modify")) { DataSet ds = EventAttendeeInfoProvider.GetEventAttendees(EventID) .Column("AttendeeID") .TopN(1); if (DataHelper.DataSourceIsEmpty(ds)) { DisableForm(); lblInfo.Text = GetString("Events_List.NoAttendees"); lblInfo.Visible = true; } } else { DisableForm(); ShowWarning(GetString("events_sendemail.modifypermission"), null, null); } }
protected void Page_Load(object sender, EventArgs e) { int nodeId = QueryHelper.GetInteger("nodeid", 0); // Get current node TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = tree.SelectSingleNode(nodeId); // Set edited document EditedDocument = node; frameHeader.Attributes.Add("src", "header.aspx" + URLHelper.Url.Query); if (CultureHelper.IsUICultureRTL()) { ControlsHelper.ReverseFrames(colsFrameset); } }
/// <summary> /// OkClick Handler. /// </summary> protected void btnOk_Click(object sender, EventArgs e) { string culture = ValidationHelper.GetString(cultureSelector.Value, ""); if ((culture != "") && ((currentCulture.ToLower() != culture.ToLower()) || chkDocuments.Checked)) { // Set new culture SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId); if (si != null) { try { // Set default culture and change current culture label ObjectHelper.SetSettingsKeyValue(si.SiteName + ".CMSDefaultCultureCode", culture.Trim()); // Change culture of documents if (chkDocuments.Checked) { // Change culture of the documents TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); tree.ChangeCulture(si.SiteName, currentCulture, culture); } if (!LicenseHelper.CheckFeature(URLHelper.GetCurrentDomain(), FeatureEnum.Multilingual)) { // If not multilingual, remove all cultures from the site and assign new culture CultureInfoProvider.RemoveSiteCultures(si.SiteName); CultureInfoProvider.AddCultureToSite(culture, si.SiteName); } ltlScript.Text = ScriptHelper.GetScript("wopener.ChangeCulture('" + chkDocuments.Checked.ToString() + "'); window.close();"); } catch (Exception ex) { EventLogProvider ev = new EventLogProvider(); ev.LogEvent("SiteManager", "ChangeDefaultCulture", ex); } } } else { ltlScript.Text = ScriptHelper.GetScript("window.close();"); } }
protected void Page_Load(object sender, EventArgs e) { int eventId = QueryHelper.GetInteger("eventId", 0); // Check if requested event exists TreeProvider mTree = new TreeProvider(); TreeNode mEventNode = mTree.SelectSingleNode(eventId); if ((mEventNode == null) || (mEventNode.NodeClassName.ToLower() != "cms.bookingevent")) { CMSPage.EditedObject = null; } emailSender.EventID = eventId; if (!URLHelper.IsPostback()) { emailSender.ReloadData(true); } emailSender.OnCheckPermissions += new CMSAdminControl.CheckPermissionsEventHandler(emailSender_OnCheckPermissions); }
/// <summary> /// OkClick Handler. /// </summary> protected void btnOk_Click(object sender, EventArgs e) { string culture = ValidationHelper.GetString(cultureSelector.Value, ""); if ((culture != "") && ((currentCulture.ToLowerCSafe() != culture.ToLowerCSafe()) || chkDocuments.Checked)) { // Set new culture SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId); if (si != null) { try { // Set default culture and change current culture label SettingsKeyInfoProvider.SetValue("CMSDefaultCultureCode", si.SiteName, culture.Trim()); // Change culture of documents if (chkDocuments.Checked) { // Change culture of the documents TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); tree.ChangeCulture(si.SiteName, currentCulture, culture); } if (!LicenseHelper.CheckFeature(RequestContext.CurrentDomain, FeatureEnum.Multilingual)) { // If not multilingual, remove all cultures from the site and assign new culture CultureSiteInfoProvider.RemoveSiteCultures(si.SiteName); CultureSiteInfoProvider.AddCultureToSite(culture, si.SiteName); } ltlScript.Text = ScriptHelper.GetScript("wopener.ChangeCulture('" + chkDocuments.Checked + "'); CloseDialog();"); } catch (Exception ex) { LogAndShowError("Sites", "ChangeDefaultCulture", ex); } } } else { ltlScript.Text = ScriptHelper.GetScript("CloseDialog();"); } }
/// <summary> /// Handles the OnAfterSave event of the EditForm control. /// </summary> private void EditForm_OnAfterSave(object sender, EventArgs e) { if (UIFormControl.EditedObject != null) { // Log widget variant synchronization MVTVariantInfo variantInfo = (MVTVariantInfo)UIFormControl.EditedObject; // Clear cache CacheHelper.TouchKey("om.mvtvariant|bytemplateid|" + variantInfo.MVTVariantPageTemplateID); if (variantInfo.MVTVariantDocumentID > 0) { // Log synchronization TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode node = tree.SelectSingleDocument(variantInfo.MVTVariantDocumentID); DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } }
protected void Page_Load(object sender, EventArgs e) { lblChoose.Text = GetString("TemplateSelection.chooseTemplate"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "SaveDocument", ScriptHelper.GetScript("function SaveDocument(nodeId, createAnother) { " + ControlsHelper.GetPostBackEventReference(this, "#", false).Replace("'#'", "createAnother+''") + "; return false; }")); ltlScript.Text = GetSpellCheckDialog(); int nodeId = QueryHelper.GetInteger("nodeid", 0); TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // For new node is not document culture important, preffered culture is used TreeNode node = tree.SelectSingleNode(nodeId); if (node != null) { selTemplate.DocumentID = node.DocumentID; } selTemplate.ParentNodeID = nodeId; }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Check UI Permissions if ((CMSContext.CurrentUser == null) || (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Content", "Properties.Variants"))) { RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "Properties.Variants"); } // Set NodeID in order to check the access to the document listElem.NodeID = QueryHelper.GetInteger("nodeid", 0); // Remove MoveUp, MoveDown buttons listElem.Grid.GridActions.Actions.RemoveRange(2, 2); // Display disabled information if (!SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSContentPersonalizationEnabled")) { this.pnlWarning.Visible = true; this.lblWarning.Text = ResHelper.GetString("cp.disabled"); } int nodeid = QueryHelper.GetInteger("nodeid", 0); bool displaySplitMode = false; if (nodeid > 0) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode treeNode = DocumentHelper.GetDocument(nodeid, CMSContext.PreferredCultureCode, tree); displaySplitMode = CMSContext.DisplaySplitMode; if ((treeNode == null) && displaySplitMode) { URLHelper.Redirect("~/CMSModules/Content/CMSDesk/New/NewCultureVersion.aspx" + URLHelper.Url.Query); } } // Register js synchronization script for split mode if (displaySplitMode) { RegisterSplitModeSync(true, false); } }
/// <summary> /// Adds document to category. Called when the button "Add document from category" is pressed. /// </summary> private bool AddDocumentToCategory() { // Get the category CategoryInfo category = CategoryInfoProvider.GetCategoryInfo("MyNewCategory", SiteContext.CurrentSiteName); if (category != null) { // Get the tree structure TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); // Get the root document TreeNode root = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/", null, true); // Add document to category DocumentCategoryInfoProvider.AddDocumentToCategory(root.DocumentID, category.CategoryID); return true; } return false; }
/// <summary> /// Deletes site. Called when the "Delete imported site" button is pressed. /// Expects the ImportSite method to be run first. /// </summary> private bool DeleteImportedSite() { // Get the site SiteInfo deleteSite = SiteInfoProvider.GetSiteInfo("MyNewImportedSite"); if (deleteSite != null) { TreeProvider treeProvider = new TreeProvider(MembershipContext.AuthenticatedUser); // Delete documents belonging under the site DocumentHelper.DeleteSiteTree("MyNewImportedSite", treeProvider); // Delete the site SiteInfoProvider.DeleteSite(deleteSite); return true; } return false; }
/// <summary> /// Moves the document to the Archived step in the workflow process. Called when the "Archive document" button is pressed. /// Expects the "CreateExampleObjects" method to be run first. /// </summary> private bool ArchiveDocument() { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); // Prepare parameters string siteName = SiteContext.CurrentSiteName; string aliasPath = "/API-Example"; string culture = "en-us"; bool combineWithDefaultCulture = false; string classNames = TreeProvider.ALL_CLASSNAMES; string where = null; string orderBy = null; int maxRelativeLevel = -1; bool selectOnlyPublished = false; string columns = null; // Get the document TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree); if (node != null) { WorkflowManager workflowManager = WorkflowManager.GetInstance(tree); WorkflowInfo workflow = workflowManager.GetNodeWorkflow(node); // Check if the document uses workflow if (workflow != null) { // Archive the document workflowManager.ArchiveDocument(node, null); return true; } else { apiArchiveDocument.ErrorMessage = "The page doesn't use workflow."; } } return false; }
/// <summary> /// Checks out the document. If check-in/check-out is disabled for the default workflow, the example can't be used. Called when the "Check out document" button is pressed. /// Expects the "CreateExampleObjects" method to be run first. /// </summary> private bool CheckOut() { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Prepare parameters string siteName = CMSContext.CurrentSiteName; string aliasPath = "/API-Example"; string culture = "en-us"; bool combineWithDefaultCulture = false; string classNames = TreeProvider.ALL_CLASSNAMES; string where = null; string orderBy = null; int maxRelativeLevel = -1; bool selectOnlyPublished = false; string columns = null; // Get the document TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree); if (node != null) { // Create a new Workflow manager instance WorkflowManager workflowmanager = new WorkflowManager(tree); // Make sure the document uses workflow WorkflowInfo workflow = workflowmanager.GetNodeWorkflow(node); if (workflow != null) { // Check if the workflow uses check-in/check-out functionality if (workflow.UseCheckInCheckOut(CMSContext.CurrentSiteName)) { // The document has to be checked in if (!node.IsCheckedOut) { // Create a new version manager instance VersionManager versionmanager = new VersionManager(tree); // Check out the document to create a new document version versionmanager.CheckOut(node); return(true); } else { apiCheckOut.ErrorMessage = "The document has already been checked out."; } } else { apiCheckOut.ErrorMessage = "The workflow does not use check-in/check-out. See the \"Edit document\" example, which checks the document out and in automatically."; } } else { apiCheckOut.ErrorMessage = "The document doesn't use workflow."; } } return(false); }
/// <summary> /// Archives document(s). /// </summary> private void ArchiveAll(object parameter) { if (parameter == null) { return; } TreeProvider tree = new TreeProvider(currentUser); tree.AllowAsyncActions = false; try { // Begin log AddLog(ResHelper.GetString("content.archivingdocuments", currentCulture)); string[] parameters = ((string)parameter).Split(';'); string siteName = parameters[1]; // Get identifiers int[] workNodes = nodeIds.ToArray(); // Prepare the where condition string where = SqlHelper.GetWhereCondition("NodeID", workNodes); string columns = SqlHelper.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture"); // Get cultures string cultureCode = chkAllCultures.Checked ? TreeProvider.ALL_CULTURES : parameters[0]; // Get the documents DataSet documents = tree.SelectNodes(siteName, "/%", cultureCode, false, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns); // Create instance of workflow manager class WorkflowManager wm = WorkflowManager.GetInstance(tree); if (!DataHelper.DataSourceIsEmpty(documents)) { foreach (DataRow nodeRow in documents.Tables[0].Rows) { // Get the current document string aliasPath = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty); TreeNode node = GetDocument(tree, siteName, nodeRow); if (PerformArchive(wm, tree, node, aliasPath)) { return; } // Process underlying documents if (chkUnderlying.Checked && (node.NodeChildNodesCount > 0)) { if (ArchiveSubDocuments(node, tree, wm, cultureCode, siteName)) { return; } } } } else { AddError(ResHelper.GetString("content.nothingtoarchive", currentCulture)); } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state != CMSThread.ABORT_REASON_STOP) { // Log error LogExceptionToEventLog(ResHelper.GetString("content.archivefailed", currentCulture), ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ResHelper.GetString("content.archivefailed", currentCulture), ex); } }
/// <summary> /// Publishes document(s). /// </summary> private void PublishAll(object parameter) { if (parameter == null) { return; } TreeProvider tree = new TreeProvider(currentUser); tree.AllowAsyncActions = false; try { // Begin log AddLog(ResHelper.GetString("content.publishingdocuments", currentCulture)); string[] parameters = ((string)parameter).Split(';'); string siteName = parameters[1]; // Get identifiers int[] workNodes = nodeIds.ToArray(); // Prepare the where condition string where = new WhereCondition().WhereIn("NodeID", workNodes).ToString(true); string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture"); // Get cultures string cultureCode = chkAllCultures.Checked ? TreeProvider.ALL_CULTURES : parameters[0]; // Get the documents DataSet documents = tree.SelectNodes(siteName, "/%", cultureCode, false, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns); // Create instance of workflow manager class WorkflowManager wm = WorkflowManager.GetInstance(tree); if (!DataHelper.DataSourceIsEmpty(documents)) { foreach (DataRow nodeRow in documents.Tables[0].Rows) { // Get the current document TreeNode node = GetDocument(tree, siteName, nodeRow); // Publish document if (PerformPublish(wm, tree, siteName, nodeRow)) { return; } // Process underlying documents if (chkUnderlying.Checked && node.NodeHasChildren && PublishSubDocuments(node, tree, wm, cultureCode, siteName)) { return; } } } else { AddError(ResHelper.GetString("content.nothingtopublish", currentCulture)); } } catch (ThreadAbortException ex) { if (!CMSThread.Stopped(ex)) { // Log error LogExceptionToEventLog(ResHelper.GetString("content.publishfailed", currentCulture), ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ResHelper.GetString("content.publishfailed", currentCulture), ex); } }
protected void Page_Load(object sender, EventArgs e) { // Switch the view mode CMSContext.ViewMode = ViewModeEnum.LiveSite; // Get the document int nodeId = 0; if (Request.QueryString["nodeid"] != null) { nodeId = ValidationHelper.GetInteger(Request.QueryString["nodeid"], 0); } string siteName = CMSContext.CurrentSiteName; TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = null; // Check split mode bool isSplitMode = CMSContext.DisplaySplitMode; bool combineWithDefaultCulture = isSplitMode ? false : SiteInfoProvider.CombineWithDefaultCulture(siteName); // Get the document node = tree.SelectSingleNode(nodeId, CMSContext.PreferredCultureCode, combineWithDefaultCulture); // Redirect to the live URL string url = null; if (node != null) { // Check if the node is published or available if (!node.DocumentCulture.Equals(CMSContext.PreferredCultureCode, StringComparison.InvariantCultureIgnoreCase) && (!SiteInfoProvider.CombineWithDefaultCulture(siteName) || !node.DocumentCulture.Equals(CultureHelper.GetDefaultCulture(siteName), StringComparison.InvariantCultureIgnoreCase))) { url = "~/CMSMessages/PageNotAvailable.aspx?reason=missingculture"; } if ((url == null) && !node.IsPublished && URLRewriter.PageNotFoundForNonPublished(siteName)) { // Try to find published document in default culture if (SiteInfoProvider.CombineWithDefaultCulture(siteName)) { string defaultCulture = CultureHelper.GetDefaultCulture(siteName); node = tree.SelectSingleNode(nodeId, defaultCulture, false); if ((node != null) && node.IsPublished) { // Do not use document URL path - preferred culture could be changed url = CMSContext.GetUrl(node.NodeAliasPath, null); } } if (url == null) { // Document is not published url = "~/CMSMessages/PageNotAvailable.aspx?reason=notpublished"; } } } else { url = isSplitMode ? "~/CMSModules/Content/CMSDesk/New/NewCultureVersion.aspx" + URLHelper.Url.Query : "~/CMSMessages/PageNotAvailable.aspx?reason=missingculture&showlink=false"; } if (url == null) { // Do not use document URL path - preferred culture could be changed url = CMSContext.GetUrl(node.NodeAliasPath, null); } // Split mode if (CMSContext.DisplaySplitMode) { url = URLHelper.AddParameterToUrl(url, "cmssplitmode", "1"); } URLHelper.Redirect(url); }
/// <summary> /// Reloads control. /// </summary> /// <param name="forceReload">Forces nested CMSForm to reload if true</param> public void ReloadData(bool forceReload) { if (StopProcessing) { return; } if (!mFormLoaded || forceReload) { // Check License LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.UserContributions); if (!StopProcessing) { // Set document manager mode if (NewDocument) { DocumentManager.Mode = FormModeEnum.Insert; DocumentManager.ParentNodeID = NodeID; DocumentManager.NewNodeClassID = ClassID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; } else if (NewCulture) { DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion; DocumentManager.NodeID = NodeID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; DocumentManager.SourceDocumentID = CopyDefaultDataFromDocumentID; } else { DocumentManager.Mode = FormModeEnum.Update; DocumentManager.NodeID = NodeID; DocumentManager.SiteName = SiteName; DocumentManager.CultureCode = CultureCode; } ScriptHelper.RegisterDialogScript(Page); titleElem.TitleText = String.Empty; pnlSelectClass.Visible = false; pnlEdit.Visible = false; pnlInfo.Visible = false; pnlNewCulture.Visible = false; pnlDelete.Visible = false; // If node found, init the form if (NewDocument || (Node != null)) { // Delete action if (Delete) { // Delete document pnlDelete.Visible = true; titleElem.TitleText = GetString("Content.DeleteTitle"); chkAllCultures.Text = GetString("ContentDelete.AllCultures"); chkDestroy.Text = GetString("ContentDelete.Destroy"); lblQuestion.Text = GetString("ContentDelete.Question"); btnYes.Text = GetString("general.yes"); // Prevent button double-click btnYes.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled=true;this.disabled=true;{1};", btnNo.ClientID, ControlsHelper.GetPostBackEventReference(btnYes, string.Empty, true, false))); btnNo.Text = GetString("general.no"); DataSet culturesDS = CultureSiteInfoProvider.GetSiteCultures(SiteName); if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1)) { chkAllCultures.Visible = false; chkAllCultures.Checked = true; } if (Node.IsLink) { titleElem.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\""; lblQuestion.Text = GetString("ContentDelete.QuestionLink"); chkAllCultures.Checked = true; plcCheck.Visible = false; } else { titleElem.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\""; } } // New document or edit action else { if (NewDocument) { titleElem.TitleText = GetString("Content.NewTitle"); } // Document type selection if (NewDocument && (ClassID <= 0)) { // Use parent node TreeNode parentNode = DocumentManager.ParentNode; if (parentNode != null) { // Select document type pnlSelectClass.Visible = true; // Apply document type scope var whereCondition = DocumentTypeScopeInfoProvider.GetScopeClassWhereCondition(parentNode); var parentClassId = ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0); var siteId = SiteInfoProvider.GetSiteID(SiteName); // Get the allowed child classes DataSet ds = AllowedChildClassInfoProvider.GetAllowedChildClasses(parentClassId, siteId) .Where(whereCondition) .OrderBy("ClassID") .Columns("ClassName", "ClassDisplayName", "ClassID"); ArrayList deleteRows = new ArrayList(); if (!DataHelper.DataSourceIsEmpty(ds)) { // Get the unwanted classes string allowed = AllowedChildClasses.Trim().ToLowerCSafe(); if (!string.IsNullOrEmpty(allowed)) { allowed = String.Format(";{0};", allowed); } var userInfo = MembershipContext.AuthenticatedUser; string className = null; // Check if the user has 'Create' permission per Content bool isAuthorizedToCreateInContent = userInfo.IsAuthorizedPerResource("CMS.Content", "Create"); bool hasNodeAllowCreate = (userInfo.IsAuthorizedPerTreeNode(parentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed); foreach (DataRow dr in ds.Tables[0].Rows) { className = DataHelper.GetStringValue(dr, "ClassName", String.Empty).ToLowerCSafe(); // Document type is not allowed or user hasn't got permission, remove it from the data set if ((!string.IsNullOrEmpty(allowed) && (!allowed.Contains(";" + className + ";"))) || (CheckPermissions && CheckDocPermissionsForInsert && !(isAuthorizedToCreateInContent || userInfo.IsAuthorizedPerClassName(className, "Create") || (userInfo.IsAuthorizedPerClassName(className, "CreateSpecific") && hasNodeAllowCreate)))) { deleteRows.Add(dr); } } // Remove the rows foreach (DataRow dr in deleteRows) { ds.Tables[0].Rows.Remove(dr); } } // Check if some classes are available if (!DataHelper.DataSourceIsEmpty(ds)) { // If number of classes is more than 1 display them in grid if (ds.Tables[0].Rows.Count > 1) { ds.Tables[0].DefaultView.Sort = "ClassDisplayName"; lblError.Visible = false; lblInfo.Visible = true; lblInfo.Text = GetString("Content.NewInfo"); DataSet sortedResult = new DataSet(); sortedResult.Tables.Add(ds.Tables[0].DefaultView.ToTable()); gridClass.DataSource = sortedResult; gridClass.ReloadData(); } // else show form of the only class else { ClassID = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "ClassID"); ReloadData(true); return; } } else { // Display error message lblError.Visible = true; lblError.Text = GetString("Content.NoAllowedChildDocuments"); lblInfo.Visible = false; gridClass.Visible = false; } } else { pnlInfo.Visible = true; lblFormInfo.Text = GetString("EditForm.DocumentNotFound"); } } // Insert or update of a document else { // Display the form pnlEdit.Visible = true; // Try to get GroupID if group context exists int currentGroupId = ModuleCommands.CommunityGetCurrentGroupID(); btnDelete.Attributes.Add("style", "display: none;"); btnRefresh.Attributes.Add("style", "display: none;"); // CMSForm initialization formElem.NodeID = Node.NodeID; formElem.SiteName = SiteName; formElem.CultureCode = CultureCode; formElem.ValidationErrorMessage = HTMLHelper.HTMLEncode(ValidationErrorMessage); formElem.IsLiveSite = IsLiveSite; // Set group ID if group context exists formElem.GroupID = currentGroupId; // External editing is allowed for live site only if the permissions are checked or user is global administrator or for group context - user is group administrator formElem.AllowExternalEditing = !IsLiveSite || CheckPermissions || MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) || MembershipContext.AuthenticatedUser.IsGroupAdministrator(currentGroupId); // Set the form mode if (NewDocument) { ci = DataClassInfoProvider.GetDataClassInfo(ClassID); if (ci == null) { throw new Exception(String.Format("[CMSAdminControls/EditForm.aspx]: Class ID '{0}' not found.", ClassID)); } string classDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ci.ClassDisplayName)); titleElem.TitleText = GetString("Content.NewTitle") + ": " + classDisplayName; // Set default template ID formElem.DefaultPageTemplateID = TemplateID > 0 ? TemplateID : ci.ClassDefaultPageTemplateID; // Set document owner formElem.OwnerID = OwnerID; formElem.FormMode = FormModeEnum.Insert; string newClassName = ci.ClassName; string newFormName = newClassName + ".default"; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } if (newFormName.ToLowerCSafe() != formElem.FormName.ToLowerCSafe()) { formElem.FormName = newFormName; } } else if (NewCulture) { formElem.FormMode = FormModeEnum.InsertNewCultureVersion; // Default data document ID formElem.CopyDefaultDataFromDocumentId = CopyDefaultDataFromDocumentID; ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName); formElem.FormName = Node.NodeClassName + ".default"; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } } else { formElem.FormMode = FormModeEnum.Update; ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName); formElem.FormName = String.Empty; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } } // Allow the CMSForm formElem.StopProcessing = false; ReloadForm(); formElem.LoadForm(true); } } } // New culture version else { // Switch to new culture version mode DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion; DocumentManager.NodeID = NodeID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; if (Node != null) { // Offer a new culture creation pnlNewCulture.Visible = true; titleElem.TitleText = GetString("Content.NewCultureVersionTitle") + " (" + HTMLHelper.HTMLEncode(LocalizationContext.PreferredCultureCode) + ")"; lblNewCultureInfo.Text = GetString("ContentNewCultureVersion.Info"); radCopy.Text = GetString("ContentNewCultureVersion.Copy"); radEmpty.Text = GetString("ContentNewCultureVersion.Empty"); radCopy.Attributes.Add("onclick", "ShowSelection();"); radEmpty.Attributes.Add("onclick", "ShowSelection()"); AddScript( "function ShowSelection() { \n" + " if (document.getElementById('" + radCopy.ClientID + "').checked) { document.getElementById('divCultures').style.display = 'block'; } \n" + " else { document.getElementById('divCultures').style.display = 'none'; } \n" + "} \n" ); btnOk.Text = GetString("ContentNewCultureVersion.Create"); // Load culture versions SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID); if (si != null) { lstCultures.Items.Clear(); DataSet nodes = TreeProvider.SelectNodes(si.SiteName, Node.NodeAliasPath, TreeProvider.ALL_CULTURES, false, null, null, null, 1, false); foreach (DataRow nodeCulture in nodes.Tables[0].Rows) { ListItem li = new ListItem(); li.Text = CultureInfoProvider.GetCultureInfo(nodeCulture["DocumentCulture"].ToString()).CultureName; li.Value = nodeCulture["DocumentID"].ToString(); lstCultures.Items.Add(li); } if (lstCultures.Items.Count > 0) { lstCultures.SelectedIndex = 0; } } } else { pnlInfo.Visible = true; lblFormInfo.Text = GetString("EditForm.DocumentNotFound"); } } } // Set flag that the form is loaded mFormLoaded = true; } }
/// <summary> /// Copy documents section. /// </summary> /// <param name="source">Source document</param> /// <param name="target">Target document</param> /// <param name="tree">Tree provider</param> private void CopyDocumentSection(TreeNode source, TreeNode target, TreeProvider tree) { DocumentHelper.CopyDocument(source, target, true, tree); }
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")) { // Set current UI culture currentCulture = CultureHelper.PreferredUICulture; // Initialize current user currentUser = CMSContext.CurrentUser; // Initialize current site currentSite = CMSContext.CurrentSite; // Initialize events ctlAsync.OnFinished += ctlAsync_OnFinished; ctlAsync.OnError += ctlAsync_OnError; ctlAsync.OnRequestLog += ctlAsync_OnRequestLog; ctlAsync.OnCancel += ctlAsync_OnCancel; if (!RequestHelper.IsCallback()) { DataSet allDocs = null; TreeProvider tree = new TreeProvider(currentUser); btnCancel.Text = GetString("general.cancel"); // 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 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); } allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new char[] { '/' }) + "/%", TreeProvider.ALL_CULTURES, true, TreeProvider.ALL_CLASSNAMES, where, "DocumentName", TreeProvider.ALL_LEVELS, false, 0, TreeProvider.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID"); 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 CurrentMaster.Title.TitleText = GetString("Content.DeleteTitle"); CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Content/Dialogs/delete.png"); btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;"); // Register the dialog script ScriptHelper.RegisterDialogScript(this); titleElemAsync.TitleText = GetString("ContentDelete.DeletingDocuments"); titleElemAsync.TitleImage = GetImageUrl("CMSModules/CMS_Content/Dialogs/delete.png"); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; // Set all cultures checkbox if (!CultureInfoProvider.IsSiteMultilignual(currentSite.SiteName)) { chkAllCultures.Checked = true; chkAllCultures.Visible = false; } if (nodeIds.Count > 0) { if (nodeIds.Count == 1) { 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, currentUser.PreferredCultureCode) ?? tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES); } else { if (allDocs != null) { DataRow dr = allDocs.Tables[0].Rows[0]; node = TreeNode.New(dr, ValidationHelper.GetString(dr["ClassName"], string.Empty), tree); } } if (node != null) { if (!IsUserAuthorizedToDeleteDocument(node)) { pnlDelete.Visible = false; lblError.Text = String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)); } if (node.IsLink) { CurrentMaster.Title.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(node.DocumentName) + "\""; lblQuestion.Text = GetString("ContentDelete.QuestionLink"); chkAllCultures.Checked = true; plcCheck.Visible = false; } else { string nodeName = HTMLHelper.HTMLEncode(node.DocumentName); // Get name for root document if (node.NodeClassName.ToLower() == "cms.root") { nodeName = HTMLHelper.HTMLEncode(currentSite.DisplayName); } CurrentMaster.Title.TitleText = GetString("Content.DeleteTitle") + " \"" + nodeName + "\""; // If there is SKU if (node.HasSKU) { GeneralizedInfo product = ModuleCommands.ECommerceGetSKUInfo(node.NodeSKUID); if (product != null) { bool authorized = false; // Check if product is global if (product.GetValue("SKUSiteID") == null) { // Check EcommerceGlobalModify permission authorized = currentUser.IsAuthorizedPerResource("CMS.Ecommerce", "EcommerceGlobalModify"); } else { // Check ModifyProducts/EcommerceModify permission authorized = currentUser.IsAuthorizedPerResource("CMS.Ecommerce", "ModifyProducts") || currentUser.IsAuthorizedPerResource("CMS.Ecommerce", "EcommerceModify"); } if (authorized) { pnlDeleteSKU.Visible = true; chkDeleteSKU.Visible = true; } } } } // Show or hide checkbox chkDestroy.Visible = CanDestroy(node); cancelNodeId = IsMultipleAction ? node.NodeParentID : node.NodeID; } lblQuestion.Text = GetString("ContentDelete.Question"); chkAllCultures.Text = GetString("ContentDelete.AllCultures"); chkDestroy.Text = GetString("ContentDelete.Destroy"); chkDeleteSKU.Text = GetString("ContentDelete.SKU"); } else if (nodeIds.Count > 1) { pnlDocList.Visible = true; 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)) { TreeNode node = null; string docList = null; if (string.IsNullOrEmpty(parentAliasPath)) { cancelNodeId = ValidationHelper.GetInteger( DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NodeParentID"), 0); } else { cancelNodeId = TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath); } bool canDestroy = 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 += UIHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link); } docList += "<br />"; lblDocuments.Text = docList; // Set visibility of checkboxes node = TreeNode.New(dr, ValidationHelper.GetString(dr["ClassName"], string.Empty)); if (!IsUserAuthorizedToDeleteDocument(node)) { pnlDelete.Visible = false; lblError.Text = String.Format( GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)); break; } // Can destroy if "can destroy all previous AND current" canDestroy = CanDestroy(node) && canDestroy; if ((currentUser.IsAuthorizedPerResource("CMS.Ecommerce", "ModifyProducts") || currentUser.IsAuthorizedPerResource("CMS.Ecommerce", "EcommerceModify")) && (node.HasSKU)) { pnlDeleteSKU.Visible = true; chkDeleteSKU.Visible = true; } } } chkDestroy.Visible = canDestroy; } lblQuestion.Text = GetString("ContentDelete.QuestionMultiple"); CurrentMaster.Title.TitleText = GetString("Content.DeleteTitleMultiple"); chkAllCultures.Text = GetString("ContentDelete.AllCulturesMultiple"); chkDestroy.Text = GetString("ContentDelete.DestroyMultiple"); chkDeleteSKU.Text = GetString("ContentDelete.SKUMultiple"); } // If user has allowed cultures specified if (currentUser.UserHasAllowedCultures) { // Get all site cultures DataSet siteCultures = CultureInfoProvider.GetSiteCultures(currentSite.SiteName); bool denyAllCulturesDeletion = false; // Check that user can edit all site cultures foreach (DataRow culture in siteCultures.Tables[0].Rows) { string cultureCode = ValidationHelper.GetString(DataHelper.GetDataRowValue(culture, "CultureCode"), string.Empty); if (!currentUser.IsCultureAllowed(cultureCode, currentSite.SiteName)) { denyAllCulturesDeletion = true; } } // If user can't edit all site cultures if (denyAllCulturesDeletion) { // Hide all cultures selector chkAllCultures.Visible = false; chkAllCultures.Checked = false; } } } else { // Hide everything pnlContent.Visible = false; } } } else { pnlDelete.Visible = false; lblError.Text = GetString("dialogs.badhashtext"); } }
/// <summary> /// Copies document(s). /// </summary> private void Copy(object parameter) { int nodeId = 0; int oldSiteId = 0; int newSiteId = 0; TreeNode node = null; // Process Action parameters string[] parameters = ValidationHelper.GetString(parameter, "False;False").Split(';'); if (parameters.Length != 2) { parameters = "False;False".Split(';'); } bool includeChildNodes = ValidationHelper.GetBoolean(parameters[0], false); bool copyPermissions = ValidationHelper.GetBoolean(parameters[1], false); ctlAsync.Parameter = null; string siteName = CurrentSite.SiteName; try { AddLog(GetString("ContentRequest.StartCopy")); if (targetId == 0) { AddError(GetString("ContentRequest.ErrorMissingTarget")); return; } // Get target document TreeNode targetNode = TreeProvider.SelectSingleNode(targetId, TreeProvider.ALL_CULTURES); if (targetNode == null) { AddError(GetString("ContentRequest.ErrorMissingTarget")); return; } PrepareNodeIdsForAllDocuments(siteName); if (DataHelper.DataSourceIsEmpty(documentsToProcess)) { // Create where condition string where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true); string columns = SqlHelper.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture"); documentsToProcess = TreeProvider.SelectNodes(siteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, TreeProvider.ALL_LEVELS, false, 0, columns); } if (!DataHelper.DataSourceIsEmpty(documentsToProcess)) { foreach (DataRow nodeRow in documentsToProcess.Tables[0].Rows) { // Get the current document nodeId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0); string className = nodeRow["ClassName"].ToString(); string aliasPath = nodeRow["NodeAliasPath"].ToString(); string docCulture = nodeRow["DocumentCulture"].ToString(); node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, TreeProvider); if (node == null) { AddLog(string.Format(GetString("ContentRequest.DocumentNoLongerExists"), HTMLHelper.HTMLEncode(aliasPath))); continue; } oldSiteId = node.NodeSiteID; // Copy the document TreeNode copiedNode = CopyNode(node, targetNode, includeChildNodes, TreeProvider, copyPermissions); if (copiedNode != null) { node = copiedNode; } newSiteId = node.NodeSiteID; } } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state != CMSThread.ABORT_REASON_STOP) { // Try to get ID of site int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID; // Log event to event log LogExceptionToEventLog("COPYDOC", "ContentRequest.CopyFailed", nodeId, ex, siteId); } } catch (Exception ex) { // Try to get ID of site int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID; // Log event to event log LogExceptionToEventLog("COPYDOC", "ContentRequest.CopyFailed", nodeId, ex, siteId); HandlePossibleErrors(); } finally { if (multiple) { AddLog(GetString("ContentRequest.CopyOK")); ctlAsync.Parameter = GetRefreshListingScript(); } else { // Set moved document in current site or parent node if copy to other site if (oldSiteId == newSiteId) { if (nodeId == 0) { // If processed node does not exist HandleNonExistentDocument(siteName); } else { // Process result if (node != null) { nodeId = (multiple ? nodeId : node.NodeID); ctlAsync.Parameter = "SelectNode(" + nodeId + ");RefreshTree(" + targetId + ", " + nodeId + ");"; } else { AddError(GetString("ContentRequest.CopyFailed")); } } } else { AddLog(GetString("ContentRequest.CopyOK")); ctlAsync.Parameter = string.Empty; } } } }
/// <summary> /// Links selected document(s). /// </summary> /// <param name="includeChildNodes">Determines whether include child nodes</param> /// <param name="targetNodeId">Target node ID</param> /// <param name="sourceNodes">Nodes</param> /// <param name="performedAction">Action to be performed</param> /// <param name="copyPermissions">Indicates if the document permissions should be copied</param> private void Link(bool includeChildNodes, int targetNodeId, List <int> sourceNodes, Action performedAction, bool copyPermissions) { int nodeId = 0; int oldSiteId = 0; int newSiteId = 0; TreeNode node = null; string siteName = (performedAction == Action.LinkDoc) ? targetSite.SiteName : CurrentSite.SiteName; try { AddLog(GetString("ContentRequest.StartLink")); if (targetNodeId == 0) { AddError(GetString("ContentRequest.ErrorMissingTarget")); return; } // Check if allow child type TreeNode targetNode = TreeProvider.SelectSingleNode(targetNodeId, TreeProvider.ALL_CULTURES); if (targetNode == null) { AddError(GetString("ContentRequest.ErrorMissingTarget")); return; } // Prepare NodeIDs to process if (performedAction == Action.LinkDoc) { PrepareNodeIdsForAllDocuments(targetSite.SiteName); } else if (performedAction == Action.Link) { PrepareNodeIdsForAllDocuments(CurrentSite.SiteName); } if (DataHelper.DataSourceIsEmpty(documentsToProcess)) { // Create where condition string where = new WhereCondition().WhereIn("NodeID", sourceNodes).ToString(true); string columns = SqlHelper.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName, NodeAliasPath, NodeLinkedNodeID"); documentsToProcess = TreeProvider.SelectNodes(siteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, TreeProvider.ALL_LEVELS, false, 0, columns); } if (!DataHelper.DataSourceIsEmpty(documentsToProcess)) { foreach (DataRow nodeRow in documentsToProcess.Tables[0].Rows) { nodeId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0); string className = nodeRow["ClassName"].ToString(); string aliasPath = nodeRow["NodeAliasPath"].ToString(); string docCulture = nodeRow["DocumentCulture"].ToString(); // Get document to link node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, TreeProvider); if (node == null) { AddLog(string.Format(GetString("ContentRequest.DocumentNoLongerExists"), HTMLHelper.HTMLEncode(aliasPath))); continue; } oldSiteId = node.NodeSiteID; // Link the document TreeNode linkedNode = LinkNode(node, targetNode, TreeProvider, copyPermissions, includeChildNodes); if (linkedNode != null) { node = linkedNode; } newSiteId = node.NodeSiteID; } } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state != CMSThread.ABORT_REASON_STOP) { // Try to get ID of site int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID; // Log event to event log LogExceptionToEventLog("LINKDOC", "ContentRequest.LinkFailed", nodeId, ex, siteId); } } catch (Exception ex) { // Try to get ID of site int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID; // Log event to event log LogExceptionToEventLog("LINKDOC", "ContentRequest.LinkFailed", nodeId, ex, siteId); HandlePossibleErrors(); } finally { if (multiple) { AddLog(GetString("ContentRequest.LinkOK")); ctlAsync.Parameter = GetRefreshListingScript(); } else { if (nodeId == 0) { // If processed node does not exist HandleNonExistentDocument(siteName); } else { // Set linked document in current site or parent node if linked to other site if (oldSiteId == newSiteId) { if (node == null) { AddError(GetString("ContentRequest.LinkFailed")); } } else { AddLog(GetString("ContentRequest.LinkOK")); } // Process result if (node != null) { ctlAsync.Parameter = "SelectNode(" + node.NodeID + ");RefreshTree(" + node.NodeID + ", " + node.NodeID + ");"; } } } } }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check if message board is opened if (!IsBoardOpen()) { return; } // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == String.Empty) { // Check flooding when message being inserted through the LiveSite if (CheckFloodProtection && IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(GetString("General.FloodProtection")); return; } var currentUser = MembershipContext.AuthenticatedUser; BoardMessageInfo message; if (MessageID > 0) { // Get message info message = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = message.MessageBoardID; } else { // Create new info message = new BoardMessageInfo(); // User IP address message.MessageUserInfo.IPAddress = RequestContext.UserHostAddress; // User agent message.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info message.MessageEmail = txtEmail.Text.Trim(); message.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if (!String.IsNullOrEmpty(url)) { string protocol = URLHelper.GetProtocol(url); if (String.IsNullOrEmpty(protocol)) { url = "http://" + url; } } message.MessageURL = TextHelper.LimitLength(url, txtURL.MaxLength); message.MessageURL = message.MessageURL.ToLowerCSafe().Replace("javascript", "_javascript"); message.MessageUserName = TextHelper.LimitLength(txtUserName.Text.Trim(), txtUserName.MaxLength); if ((message.MessageID <= 0) && (!currentUser.IsPublic())) { message.MessageUserID = currentUser.UserID; if (!plcUserName.Visible) { message.MessageUserName = GetDefaultUserName(); } } message.MessageIsSpam = ValidationHelper.GetBoolean(chkSpam.Checked, false); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { message.MessageRatingValue = ratingControl.CurrentRating; // Update document rating, remember rating in cookie TreeProvider.RememberRating(DocumentContext.CurrentDocument); } BoardInfo boardInfo; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(MessageBoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(MessageBoardID, BoardProperties.BoardModerators); } if (boardInfo != null) { if (BoardInfoProvider.IsUserAuthorizedToAddMessages(boardInfo)) { // If the very new message is inserted if (MessageID == 0) { // If creating message set inserted to now and assign to board message.MessageInserted = DateTime.Now; message.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { message.MessageApprovedByUserID = currentUser.UserID; message.MessageApproved = true; } else { // Is board moderated ? message.MessageApprovedByUserID = 0; message.MessageApproved = !boardInfo.BoardModerated; } } else { if (chkApproved.Checked) { // Set current user as approver message.MessageApproved = true; message.MessageApprovedByUserID = currentUser.UserID; } else { message.MessageApproved = false; message.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { // Columns to check Dictionary <string, int> collumns = new Dictionary <string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check bool validateUserName = plcUserName.Visible; errorMessage = BadWordsHelper.CheckBadWords(message, collumns, "MessageApproved", "MessageApprovedByUserID", message.MessageText, currentUser.UserID, () => ValidateMessage(message, validateUserName)); // Additionally check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(message, validateUserName)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = message.MessageEmail; // Check for duplicate e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("((SubscriptionApproved = 1) OR (SubscriptionApproved IS NULL)) AND SubscriptionBoardID=" + MessageBoardID + " AND SubscriptionEmail='" + SqlHelper.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); ClearForm(); if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); Service <ICurrentContactMergeService> .Entry().UpdateCurrentContactEmail(bsi.SubscriptionEmail, MembershipContext.AuthenticatedUser); LogSubscribingActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + String.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(message); Service <ICurrentContactMergeService> .Entry().UpdateCurrentContactEmail(message.MessageEmail, MembershipContext.AuthenticatedUser); LogCommentActivity(message, boardInfo); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { LogRatingActivity(ratingControl.CurrentRating); } // If the message is not approved let the user know message is waiting for approval if (message.MessageApproved == false) { ShowInformation(GetString("board.messageedit.waitingapproval")); } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(message); } // Hide message form if user has rated and empty rating is not allowed if (BoardProperties.CheckIfUserRated) { if (!BoardProperties.AllowEmptyRating && TreeProvider.HasRated(DocumentContext.CurrentDocument)) { pnlMessageEdit.Visible = false; lblAlreadyrated.Visible = true; } else { // Hide rating form if user has rated if (BoardProperties.EnableContentRating && (ratingControl != null) && ratingControl.GetCurrentRating() > 0) { plcRating.Visible = false; } } } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } else if (String.IsNullOrEmpty(errorMessage)) { errorMessage = ResHelper.GetString("general.actiondenied"); } } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } }
/// <summary> /// Ensures the given node within the tree. /// </summary> /// <param name="node">Node to ensure</param> /// <param name="nodeId">Ensure by NodeID</param> protected void EnsureNode(TreeNode node, int nodeId) { if (node == null) { // If not already exists, do not add if (allNodes[nodeId] != null) { return; } else { // Get the node node = TreeProvider.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES, true); if (!SelectPublishedData) { node = DocumentHelper.GetDocument(node, TreeProvider); } } } else { nodeId = node.NodeID; } if (node != null) { // Get the correct parent node System.Web.UI.WebControls.TreeNode parentNode = (System.Web.UI.WebControls.TreeNode)allNodes[node.NodeParentID]; if (parentNode != null) { // Expand the parent parentNode.Expanded = true; // If still not present, add the node if (allNodes[nodeId] == null) { TreeSiteMapNode sourceNode = new TreeSiteMapNode(MapProvider, nodeId.ToString()); sourceNode.TreeNode = node; System.Web.UI.WebControls.TreeNode newNode = CreateNode(sourceNode, 0, true); parentNode.ChildNodes.Add(newNode); } } else { // Get the correct node and add it to list of processed nodes TreeSiteMapNode targetNode = MapProvider.GetNodeByAliasPath(node.NodeAliasPath); if (targetNode != null) { List <int> procNodes = new List <int>(); procNodes.Add((int)targetNode.NodeData["NodeID"]); if (targetNode.ParentNode != null) { // Repeat until existing parent node in allNodes is found do { int targetParentNodeId = (int)((TreeSiteMapNode)targetNode.ParentNode).NodeData["NodeID"]; procNodes.Add(targetParentNodeId); targetNode = (TreeSiteMapNode)targetNode.ParentNode; } while ((targetNode.ParentNode != null) && (allNodes[(int)(((TreeSiteMapNode)(targetNode.ParentNode)).NodeData["NodeID"])] == null)); } // Process nodes in reverse order procNodes.Reverse(); if (!procNodes.Any(p => (p <= 0))) { foreach (int nodeID in procNodes) { EnsureNode(null, nodeID); } } } } } }
/// <summary> /// Initializes the controls. /// </summary> private void SetupControls() { lblRating.Text = GetString("board.messageedit.rating"); lblEmail.Text = GetString("board.messageedit.email"); lblMessage.Text = GetString("board.messageedit.message"); lblURL.Text = GetString("board.messageedit.url"); lblUserName.Text = GetString("board.messageedit.username"); lblAlreadyrated.Text = GetString("board.messageedit.alreadyrated"); lblSubscribe.Text = GetString("board.messageedit.subscribe"); rfvMessage.ErrorMessage = GetString("board.messageedit.rfvmessage"); rfvUserName.ErrorMessage = GetString("board.messageedit.rfvusername"); rfvEmail.ErrorMessage = GetString("board.messageedit.rfvemail"); btnOk.Text = GetString("board.messageedit.addmessage"); txtUserName.ValidationGroup = ValidationGroup; rfvUserName.ValidationGroup = ValidationGroup; rfvEmail.ValidationGroup = ValidationGroup; txtMessage.ValidationGroup = ValidationGroup; rfvMessage.ValidationGroup = ValidationGroup; btnOk.ValidationGroup = ValidationGroup; btnOkFooter.ValidationGroup = ValidationGroup; // Fields visibility plcUserName.Visible = BoardProperties.ShowNameField; plcEmail.Visible = BoardProperties.ShowEmailField; plcUrl.Visible = BoardProperties.ShowURLField; // Load message board if (BoardProperties != null) { if (!BoardProperties.BoardRequireEmails) { rfvEmail.Enabled = false; } if ((BoardProperties.BoardUseCaptcha) && (!AdvancedMode)) { // Show captcha text and control pnlCaptcha.Visible = true; } } plcRating.Visible = false; // Show rating form only if user has not rated yet or rating check is disabled if (!AdvancedMode && BoardProperties.EnableContentRating && (!TreeProvider.HasRated(DocumentContext.CurrentDocument) || !BoardProperties.CheckIfUserRated)) { if (DocumentContext.CurrentDocument != null) { plcRating.Visible = true; try { // Insert rating control to page ratingControl = (AbstractRatingControl)(Page.LoadUserControl(AbstractRatingControl.GetRatingControlUrl(BoardProperties.RatingType + ".ascx"))); } catch (Exception ex) { Controls.Add(new LiteralControl(ex.Message)); return; } // Init values ratingControl.ID = ID + "_RatingControl"; ratingControl.MaxRating = BoardProperties.MaxRatingValue; ratingControl.Visible = true; ratingControl.Enabled = true; ratingControl.RatingEvent += ratingControl_RatingEvent; ratingControl.CurrentRating = ValidationHelper.GetDouble(ViewState["ratingvalue"], 0); ratingControl.ExternalManagement = true; pnlRating.Controls.Clear(); pnlRating.Controls.Add(ratingControl); } } if (AdvancedMode) { // Initialize advanced controls plcAdvanced.Visible = true; lblApproved.Text = GetString("board.messageedit.approved"); lblSpam.Text = GetString("board.messageedit.spam"); lblInsertedCaption.Text = GetString("board.messageedit.inserted"); btnOk.ResourceString = "general.saveandclose"; btnOkFooter.ResourceString = "general.saveandclose"; // Show or hide "Inserted" label bool showInserted = (MessageID > 0); lblInsertedCaption.Visible = showInserted; lblInserted.Visible = showInserted; chkSubscribe.Visible = false; } else { // If is not moderated then autocheck approve if (!BoardProperties.BoardModerated) { chkApproved.Checked = true; } } if (ModalMode) { plcFooter.Visible = true; pnlOkButton.Visible = false; } else { plcFooter.Visible = false; pnlOkButton.Visible = true; } // Show/hide subscription option plcChkSubscribe.Visible = BoardProperties.BoardEnableSubscriptions && BoardProperties.ShowEmailField; // For new message hide Is approved chkbox (auto approve) if (MessageID <= 0) { plcApproved.Visible = false; } // Hide message form if empty rating is not allowed and user has rated if (!BoardProperties.AllowEmptyRating && BoardProperties.CheckIfUserRated && TreeProvider.HasRated(DocumentContext.CurrentDocument)) { pnlMessageEdit.Visible = false; lblAlreadyrated.Visible = true; } }
/// <summary> /// UniGrid action buttons event handler. /// </summary> protected void gridDocs_OnAction(string actionName, object actionArgument) { switch (actionName.ToLowerCSafe()) { // Edit document case "edit": // Check group's permission to edit document if allowed if (CheckGroupPermission("editpages")) { editDoc.NodeID = ValidationHelper.GetInteger(actionArgument, 0); editDoc.Action = "edit"; editDoc.CheckPermissions = CheckPermissions; editDoc.AllowDelete = AllowDelete && CheckGroupPermission("deletepages"); pnlEdit.Visible = true; pnlList.Visible = false; } break; // Delete document case "delete": // Check banned IP if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { AddAlert(GetString("general.bannedip")); return; } TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Delete specified node int documentId = ValidationHelper.GetInteger(actionArgument, 0); TreeNode node = DocumentHelper.GetDocument(documentId, tree); if (node != null) { // Check user's permission to delete document if allowed bool hasUserDeletePermission = !CheckPermissions || IsUserAuthorizedToDeleteDocument(node); // Check group's permission to delete document if allowed hasUserDeletePermission &= CheckGroupPermission("deletepages"); if (hasUserDeletePermission) { DocumentHelper.DeleteDocument(node, tree, false, false, true); if (LogActivity) { Activity activity = new ActivityUserContributionDelete(node, node.GetDocumentName(), CMSContext.ActivityEnvironmentVariables); activity.Log(); } // Fire OnAfterDelete RaiseOnAfterDelete(); ReloadData(); } // Access denied - not authorized to delete the document else { AddAlert(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), node.NodeAliasPath)); return; } } break; } }
/// <summary> /// Deletes document(s). /// </summary> private void Delete(object parameter) { if (parameter == null || nodeIds.Count < 1) { return; } if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Blogs, VersionActionEnum.Edit)) { AddError(ResHelper.GetString("cmsdesk.blogdeletelicenselimitations", currentCulture)); return; } if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Edit)) { AddError(ResHelper.GetString("cmsdesk.documentdeletelicenselimitations", currentCulture)); return; } int refreshId = 0; TreeProvider tree = new TreeProvider(currentUser); tree.AllowAsyncActions = false; try { string[] parameters = ((string)parameter).Split(';'); string siteName = parameters[1]; // Prepare the where condition string where = SqlHelperClass.GetWhereCondition("NodeID", (int[])nodeIds.ToArray(typeof(int))); string columns = SqlHelperClass.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture, NodeParentID"); bool combineWithDefaultCulture = chkAllCultures.Checked; string cultureCode = combineWithDefaultCulture ? TreeProvider.ALL_CULTURES : parameters[0]; // Begin log AddLog(ResHelper.GetString("ContentDelete.DeletingDocuments", currentCulture)); // Get the documents DataSet ds = tree.SelectNodes(siteName, "/%", cultureCode, combineWithDefaultCulture, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns); if (!DataHelper.DataSourceIsEmpty(ds)) { // Delete the documents foreach (DataRow nodeRow in ds.Tables[0].Rows) { // Get the current document string className = nodeRow["ClassName"].ToString(); string aliasPath = nodeRow["NodeAliasPath"].ToString(); string docCulture = nodeRow["DocumentCulture"].ToString(); refreshId = ValidationHelper.GetInteger(nodeRow["NodeParentID"], 0); if (refreshId == 0) { refreshId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0); } TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, tree); if (node == null) { AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath))); continue; } // Ensure current parent ID int parentId = node.NodeParentID; // Check delete permissions if (IsUserAuthorizedToDeleteDocument(node) && (CanDestroy(node) || !chkDestroy.Checked)) { // Delete the document if (parentId <= 0) { parentId = node.NodeID; } // Delete document refreshId = DocumentHelper.DeleteDocument(node, tree, chkAllCultures.Checked, chkDestroy.Checked, chkDeleteSKU.Checked) ? parentId : node.NodeID; } // Access denied - not authorized to delete the document else { AddError(string.Format(ResHelper.GetString("cmsdesk.notauthorizedtodeletedocument", currentCulture), HTMLHelper.HTMLEncode(node.NodeAliasPath))); continue; } } } else { AddError(ResHelper.GetString("DeleteDocument.CultureNotExists", currentCulture)); return; } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled AddError(ResHelper.GetString("DeleteDocument.DeletionCanceled", currentCulture)); } else { // Log error LogExceptionToEventLog(ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ex); } finally { if (string.IsNullOrEmpty(CurrentError)) { // Refresh tree ctlAsync.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "DisplayDocument(" + refreshId + ");"; } else { ctlAsync.Parameter = "RefreshTree(null, null);"; } } }
private object gridData_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView row = parameter as DataRowView; if (DocumentListingDisplayed) { switch (sourceName.ToLowerCSafe()) { case "skunumber": case "skuavailableitems": case "publicstatusid": case "allowforsale": case "skusiteid": case "typename": case "skuprice": if (ShowSections && (row["NodeSKUID"] == DBNull.Value)) { return(NO_DATA_CELL_VALUE); } break; case "edititem": row = ((GridViewRow)parameter).DataItem as DataRowView; if ((row != null) && ((row["NodeSKUID"] == DBNull.Value) || showProductsInTree)) { CMSGridActionButton btn = sender as CMSGridActionButton; if (btn != null) { int currentNodeId = ValidationHelper.GetInteger(row["NodeID"], 0); int nodeParentId = ValidationHelper.GetInteger(row["NodeParentID"], 0); if (row["NodeSKUID"] == DBNull.Value) { btn.IconCssClass = "icon-eye"; btn.IconStyle = GridIconStyle.Allow; btn.ToolTip = GetString("com.sku.viewproducts"); } // Go to the selected document btn.OnClientClick = "EditItem(" + currentNodeId + ", " + nodeParentId + "); return false;"; } } break; } } switch (sourceName.ToLowerCSafe()) { case "skunumber": string skuNumber = ValidationHelper.GetString(row["SKUNumber"], null); return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(skuNumber) ?? "")); case "skuavailableitems": var sku = new SKUInfo(row.Row); int availableItems = sku.SKUAvailableItems; // Inventory tracked by variants if (sku.SKUTrackInventory == TrackInventoryTypeEnum.ByVariants) { return(GetString("com.inventory.trackedbyvariants")); } // Inventory tracking disabled if (sku.SKUTrackInventory == TrackInventoryTypeEnum.Disabled) { return(GetString("com.inventory.nottracked")); } // Ensure correct values for unigrid export if (sender == null) { return(availableItems); } // Tracking by products InlineEditingTextBox inlineAvailableItems = new InlineEditingTextBox(); inlineAvailableItems.Text = availableItems.ToString(); inlineAvailableItems.DelayedReload = DocumentListingDisplayed; inlineAvailableItems.EnableEncode = false; inlineAvailableItems.Formatting += (s, e) => { var reorderAt = sku.SKUReorderAt; // Emphasize the number when product needs to be reordered if (availableItems <= reorderAt) { // Format message informing about insufficient stock level string reorderMsg = string.Format(GetString("com.sku.reorderatTooltip"), reorderAt); string message = string.Format("<span class=\"alert-status-error\" onclick=\"UnTip()\" onmouseout=\"UnTip()\" onmouseover=\"Tip('{1}')\">{0}</span>", availableItems, reorderMsg); inlineAvailableItems.FormattedText = message; } }; // Unigrid with delayed reload in combination with inline edit control requires additional postback to sort data. // Update data only if external data bound is called for the first time. if (!forceReloadData) { inlineAvailableItems.Update += (s, e) => { var newNumberOfItems = ValidationHelper.GetInteger(inlineAvailableItems.Text, availableItems); if (ValidationHelper.IsInteger(inlineAvailableItems.Text) && (-1000000000 <= newNumberOfItems) && (newNumberOfItems <= 1000000000)) { CheckModifyPermission(sku); // Ensures that grid will display inserted value sku.SKUAvailableItems = newNumberOfItems; // Document list is used to display products -> document has to be updated to ensure correct sku mapping if (DocumentListingDisplayed) { int documentId = ValidationHelper.GetInteger(row.Row["DocumentID"], 0); // Create an instance of the Tree provider and select edited document with coupled data TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode document = tree.SelectSingleDocument(documentId); if (document == null) { return; } document.SetValue("SKUAvailableItems", newNumberOfItems); document.Update(); forceReloadData = true; } // Stand-alone product -> only product has to be updated else { sku.MakeComplete(true); sku.Update(); gridData.ReloadData(); } } else { inlineAvailableItems.ErrorText = GetString("com.productedit.availableitemsinvalid"); } }; } return(inlineAvailableItems); case "skuprice": SKUInfo product = new SKUInfo(row.Row); // Ensure correct values for unigrid export if (sender == null) { return(product.SKUPrice); } InlineEditingTextBox inlineSkuPrice = new InlineEditingTextBox(); inlineSkuPrice.Text = product.SKUPrice.ToString(); inlineSkuPrice.DelayedReload = DocumentListingDisplayed; inlineSkuPrice.Formatting += (s, e) => { // Format price inlineSkuPrice.FormattedText = CurrencyInfoProvider.GetFormattedPrice(product.SKUPrice, product.SKUSiteID); }; // Unigrid with delayed reload in combination with inline edit control requires additional postback to sort data. // Update data only if external data bound is called for the first time. if (!forceReloadData) { inlineSkuPrice.Update += (s, e) => { CheckModifyPermission(product); // Price must be a double number double price = ValidationHelper.GetDouble(inlineSkuPrice.Text, -1); if (ValidationHelper.IsDouble(inlineSkuPrice.Text) && (price >= 0)) { // Ensures that grid will display inserted price product.SKUPrice = price; // Document list is used to display products -> document has to be updated to ensure correct sku mapping if (DocumentListingDisplayed) { int documentId = ValidationHelper.GetInteger(row.Row["DocumentID"], 0); // Create an instance of the Tree provider and select edited document with coupled data TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode document = tree.SelectSingleDocument(documentId); if (document != null) { document.SetValue("SKUPrice", price); document.Update(); forceReloadData = true; } } // Stand-alone product -> only product has to be updated else { product.MakeComplete(true); product.Update(); gridData.ReloadData(); } } else { inlineSkuPrice.ErrorText = GetString("com.productedit.priceinvalid"); } }; } return(inlineSkuPrice); case "publicstatusid": int id = ValidationHelper.GetInteger(row["SKUPublicStatusID"], 0); PublicStatusInfo publicStatus = PublicStatusInfoProvider.GetPublicStatusInfo(id); if (publicStatus != null) { // Localize and encode return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(publicStatus.PublicStatusDisplayName))); } return(string.Empty); case "allowforsale": // Get "on sale" flag return(UniGridFunctions.ColoredSpanYesNo(ValidationHelper.GetBoolean(row["SKUEnabled"], false))); case "typename": string docTypeName = ValidationHelper.GetString(row["ClassDisplayName"], null); // Localize class display name if (!string.IsNullOrEmpty(docTypeName)) { return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(docTypeName))); } return(string.Empty); } return(parameter); }
protected void Page_Load(object sender, EventArgs e) { if (!QueryHelper.ValidateHash("hash")) { return; } // Check if hashtable containing dialog parameters is not empty if ((Parameters == null) || (Parameters.Count == 0)) { return; } // Register CopyMove.js script file ScriptHelper.RegisterScriptFile(Page, "~/CMSModules/Content/Controls/Dialogs/Properties/CopyMove.js"); IsDialogAction = true; // Setup tree provider TreeProvider.AllowAsyncActions = false; // Initialize events ctlAsync.OnFinished += ctlAsync_OnFinished; ctlAsync.OnError += ctlAsync_OnError; ctlAsync.OnRequestLog += ctlAsync_OnRequestLog; ctlAsync.OnCancel += ctlAsync_OnCancel; if (!RequestHelper.IsCallback()) { ClassID = ValidationHelper.GetInteger(Parameters["classid"], 0); // Get whether action is multiple multiple = ValidationHelper.GetBoolean(Parameters["multiple"], false); // Get the source node string nodeIdsString = ValidationHelper.GetString(Parameters["sourcenodeids"], string.Empty); string[] nodeIdsArr = nodeIdsString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nodeId in nodeIdsArr) { int id = ValidationHelper.GetInteger(nodeId, 0); if (id != 0) { nodeIds.Add(id); } } // Get target node id targetId = ValidationHelper.GetInteger(Parameters["targetid"], 0); using (TreeNode tn = TreeProvider.SelectSingleNode(targetId)) { if ((tn != null) && (tn.NodeSiteID != CurrentSite.SiteID)) { SiteInfo si = SiteInfoProvider.GetSiteInfo(tn.NodeSiteID); if (si != null) { targetSite = si; } } else { targetSite = CurrentSite; } } // Set if operation take place on same site sameSite = (CurrentSite == targetSite); btnCancel.Text = GetString("General.Cancel"); btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;"); // Set introducing text if (targetId == 0) { switch (CurrentAction) { case Action.Move: case Action.Copy: case Action.Link: lblEmpty.Text = GetString("dialogs.copymove.select"); break; case Action.LinkDoc: lblEmpty.Text = GetString("dialogs.linkdoc.select"); break; } } // Check if target of action is another site if (!sameSite) { plcCopyPermissions.Visible = false; plcPreservePermissions.Visible = false; } if (!RequestHelper.IsPostBack()) { object check; // Preset checkbox value switch (CurrentAction) { case Action.Copy: // Ensure underlying items checkbox check = WindowHelper.GetItem(Action.Copy + underlying); if (check == null) { WindowHelper.Add(Action.Copy + underlying, true); } chkUnderlying.Checked = ValidationHelper.GetBoolean(check, true); if (sameSite) { chkCopyPermissions.Checked = CopyPermissions; } break; case Action.Link: case Action.LinkDoc: // Ensure underlying items checkbox check = WindowHelper.GetItem(Action.Link + underlying); if (check == null) { WindowHelper.Add(Action.Link + underlying, false); } chkUnderlying.Checked = ValidationHelper.GetBoolean(check, false); if (sameSite) { chkCopyPermissions.Checked = CopyPermissions; } break; case Action.Move: if (sameSite) { chkPreservePermissions.Checked = CopyPermissions; } break; } } string listInfoString = string.Empty; // Set up layout and strings depending on selected action switch (CurrentAction) { case Action.Move: listInfoString = "dialogs.move.listinfo"; canceledString = "ContentRequest.MoveCanceled"; plcUnderlying.Visible = false; plcCopyPermissions.Visible = false; break; case Action.Copy: listInfoString = "dialogs.copy.listinfo"; canceledString = "ContentRequest.CopyingCanceled"; lblUnderlying.ResourceString = "contentrequest.copyunderlying"; plcUnderlying.Visible = true; plcPreservePermissions.Visible = false; break; case Action.Link: listInfoString = "dialogs.link.listinfo"; canceledString = "ContentRequest.LinkCanceled"; lblUnderlying.ResourceString = "contentrequest.linkunderlying"; plcUnderlying.Visible = true; plcPreservePermissions.Visible = false; break; case Action.LinkDoc: listInfoString = "dialogs.link.listinfo"; canceledString = "ContentRequest.LinkCanceled"; lblUnderlying.ResourceString = "contentrequest.linkunderlying"; plcUnderlying.Visible = true; plcPreservePermissions.Visible = false; break; } // Localize string canceledString = GetString(canceledString); // Get alias path of document selected in tree string selectedAliasPath = TreePathUtils.GetAliasPathByNodeId(targetId); // Set target alias path if ((CurrentAction == Action.Copy) || (CurrentAction == Action.Move) || (CurrentAction == Action.Link)) { lblAliasPath.Text = selectedAliasPath; } if (nodeIds.Count == 1) { TreeNode sourceNode = null; string sourceAliasPath = string.Empty; // Get source node if ((CurrentAction == Action.Copy) || (CurrentAction == Action.Move) || (CurrentAction == Action.Link)) { int nodeId = ValidationHelper.GetInteger(nodeIds[0], 0); sourceNode = TreeProvider.SelectSingleNode(nodeId); } else if (CurrentAction == Action.LinkDoc) { sourceNode = TreeProvider.SelectSingleNode(targetId); if (sourceNode != null) { sourceAliasPath = sourceNode.NodeAliasPath; } // Show document to be linked lblDocToCopyList.Text = sourceAliasPath; } // Hide checkbox if document has no children if ((sourceNode != null) && !sourceNode.NodeHasChildren) { plcUnderlying.Visible = false; } } // Set visibility of panels pnlGeneralTab.Visible = true; pnlLog.Visible = false; // Get where condition for multiple operation whereCondition = ValidationHelper.GetString(Parameters["where"], string.Empty); // Get the alias paths of the documents to copy/move/link parentAlias = ValidationHelper.GetString(Parameters["parentalias"], string.Empty); if (!String.IsNullOrEmpty(parentAlias)) { lblDocToCopy.Text = GetString(listInfoString + "all") + ResHelper.Colon; lblDocToCopyList.Text = HTMLHelper.HTMLEncode(parentAlias); } else { lblDocToCopy.Text = GetString(listInfoString) + ResHelper.Colon; // Get the list of alias paths if (!String.IsNullOrEmpty(nodeIdsString)) { // Get alias paths from session string aliasPaths = SessionHelper.GetValue("CopyMoveDocAliasPaths").ToString(); // Set alias paths if ((CurrentAction == Action.Copy) || (CurrentAction == Action.Move) || (CurrentAction == Action.Link)) { // As source paths lblDocToCopyList.Text = aliasPaths; } else { // As target path lblAliasPath.Text = aliasPaths; } } } if (!RequestHelper.IsPostBack() && DoAction) { // Perform Move / Copy / Link action PerformAction(); } pnlEmpty.Visible = (targetId <= 0); pnlGeneralTab.Visible = (targetId > 0); } }
/// <summary> /// Delete documents section. /// </summary> /// <param name="node">Node to be deleted</param> /// <param name="tree">Tree provider</param> private void DeleteDocumentSection(TreeNode node, TreeProvider tree) { // Delete all document cultures DocumentHelper.DeleteDocument(node, tree, true); }
/// <summary> /// Saves edited SKU and returns it's ID. In case of error 0 is returned. Does not fire product saved event. /// </summary> private int SaveInternal() { // Check permissions this.CheckModifyPermission(); // If form is valid and enabled if (this.Validate() && this.FormEnabled) { bool newItem = false; // Get SKUInfo SKUInfo skuiObj = SKUInfoProvider.GetSKUInfo(mProductId); if (skuiObj == null) { newItem = true; // Create new item -> insert skuiObj = new SKUInfo(); skuiObj.SKUSiteID = editedSiteId; } else { SKUProductTypeEnum oldProductType = skuiObj.SKUProductType; SKUProductTypeEnum newProductType = SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value); // Remove e-product dependencies if required if ((oldProductType == SKUProductTypeEnum.EProduct) && (newProductType != SKUProductTypeEnum.EProduct)) { // Delete meta files MetaFileInfoProvider.DeleteFiles(skuiObj.SKUID, ECommerceObjectType.SKU, MetaFileInfoProvider.OBJECT_CATEGORY_EPRODUCT); // Delete SKU files DataSet skuFiles = SKUFileInfoProvider.GetSKUFiles("FileSKUID = " + skuiObj.SKUID, null); foreach (DataRow skuFile in skuFiles.Tables[0].Rows) { SKUFileInfo skufi = new SKUFileInfo(skuFile); SKUFileInfoProvider.DeleteSKUFileInfo(skufi); } } // Remove bundle dependencies if required if ((oldProductType == SKUProductTypeEnum.Bundle) && (newProductType != SKUProductTypeEnum.Bundle)) { // Delete SKU to bundle mappings DataSet bundles = BundleInfoProvider.GetBundles("BundleID = " + skuiObj.SKUID, null); foreach (DataRow bundle in bundles.Tables[0].Rows) { BundleInfo bi = new BundleInfo(bundle); BundleInfoProvider.DeleteBundleInfo(bi); } } } skuiObj.SKUName = this.txtSKUName.Text.Trim(); skuiObj.SKUNumber = this.txtSKUNumber.Text.Trim(); skuiObj.SKUDescription = this.htmlTemplateBody.ResolvedValue; skuiObj.SKUPrice = this.txtSKUPrice.Value; skuiObj.SKUEnabled = this.chkSKUEnabled.Checked; skuiObj.SKUInternalStatusID = this.internalStatusElem.InternalStatusID; skuiObj.SKUDepartmentID = this.departmentElem.DepartmentID; skuiObj.SKUManufacturerID = this.manufacturerElem.ManufacturerID; skuiObj.SKUPublicStatusID = this.publicStatusElem.PublicStatusID; skuiObj.SKUSupplierID = this.supplierElem.SupplierID; skuiObj.SKUSellOnlyAvailable = this.chkSKUSellOnlyAvailable.Checked; skuiObj.SKUNeedsShipping = this.chkNeedsShipping.Checked; skuiObj.SKUWeight = ValidationHelper.GetDouble(this.txtSKUWeight.Text.Trim(), 0); skuiObj.SKUHeight = ValidationHelper.GetDouble(this.txtSKUHeight.Text.Trim(), 0); skuiObj.SKUWidth = ValidationHelper.GetDouble(this.txtSKUWidth.Text.Trim(), 0); skuiObj.SKUDepth = ValidationHelper.GetDouble(this.txtSKUDepth.Text.Trim(), 0); skuiObj.SKUConversionName = ValidationHelper.GetString(this.ucConversion.Value, String.Empty); skuiObj.SKUConversionValue = this.txtConversionValue.Text.Trim(); if (String.IsNullOrEmpty(this.txtSKUAvailableItems.Text.Trim())) { skuiObj.SetValue("SKUAvailableItems", null); } else { skuiObj.SKUAvailableItems = ValidationHelper.GetInteger(this.txtSKUAvailableItems.Text.Trim(), 0); } if (String.IsNullOrEmpty(this.txtSKUAvailableInDays.Text.Trim())) { skuiObj.SetValue("SKUAvailableInDays", null); } else { skuiObj.SKUAvailableInDays = ValidationHelper.GetInteger(this.txtSKUAvailableInDays.Text.Trim(), 0); } if (String.IsNullOrEmpty(this.txtMaxOrderItems.Text.Trim())) { skuiObj.SetValue("SKUMaxItemsInOrder", null); } else { skuiObj.SKUMaxItemsInOrder = ValidationHelper.GetInteger(this.txtMaxOrderItems.Text.Trim(), 0); } if (!ProductOrdered) { // Set product type skuiObj.SKUProductType = SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value); } // Clear product type specific properties skuiObj.SetValue("SKUMembershipGUID", null); skuiObj.SetValue("SKUValidity", null); skuiObj.SetValue("SKUValidFor", null); skuiObj.SetValue("SKUValidUntil", null); skuiObj.SetValue("SKUMaxDownloads", null); skuiObj.SetValue("SKUBundleInventoryType", null); skuiObj.SetValue("SKUPrivateDonation", null); skuiObj.SetValue("SKUMinPrice", null); skuiObj.SetValue("SKUMaxPrice", null); // Set product type specific properties switch (skuiObj.SKUProductType) { // Set membership specific properties case SKUProductTypeEnum.Membership: skuiObj.SKUMembershipGUID = this.membershipElem.MembershipGUID; skuiObj.SKUValidity = this.membershipElem.MembershipValidity; if (skuiObj.SKUValidity == ValidityEnum.Until) { skuiObj.SKUValidUntil = this.membershipElem.MembershipValidUntil; } else { skuiObj.SKUValidFor = this.membershipElem.MembershipValidFor; } break; // Set e-product specific properties case SKUProductTypeEnum.EProduct: skuiObj.SKUValidity = this.eProductElem.EProductValidity; if (skuiObj.SKUValidity == ValidityEnum.Until) { skuiObj.SKUValidUntil = this.eProductElem.EProductValidUntil; } else { skuiObj.SKUValidFor = this.eProductElem.EProductValidFor; } break; // Set donation specific properties case SKUProductTypeEnum.Donation: skuiObj.SKUPrivateDonation = this.donationElem.DonationIsPrivate; if (this.donationElem.MinimumDonationAmount == 0.0) { skuiObj.SetValue("SKUMinPrice", null); } else { skuiObj.SKUMinPrice = this.donationElem.MinimumDonationAmount; } if (this.donationElem.MaximumDonationAmount == 0.0) { skuiObj.SetValue("SKUMaxPrice", null); } else { skuiObj.SKUMaxPrice = this.donationElem.MaximumDonationAmount; } break; // Set bundle specific properties case SKUProductTypeEnum.Bundle: skuiObj.SKUBundleInventoryType = this.bundleElem.RemoveFromInventory; break; } // When creating new product option if ((this.ProductID == 0) && (this.OptionCategoryID > 0)) { skuiObj.SKUOptionCategoryID = this.OptionCategoryID; } if ((newItem) && (!SKUInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))) { lblError.Visible = true; lblError.Text = GetString("ecommerceproduct.versioncheck"); return(0); } SKUInfoProvider.SetSKUInfo(skuiObj); if (newItem) { if (ECommerceSettings.UseMetaFileForProductImage) { // Get allowed extensions string settingKey = (skuiObj.IsGlobal) ? "CMSUploadExtensions" : (CMSContext.CurrentSiteName + ".CMSUploadExtensions"); string allowedExtensions = SettingsKeyProvider.GetStringValue(settingKey); // Get posted file HttpPostedFile file = this.ucMetaFile.PostedFile; if ((file != null) && (file.ContentLength > 0)) { // Get file extension string extension = Path.GetExtension(file.FileName); // Check if file is an image and its extension is allowed if (ImageHelper.IsImage(extension) && (String.IsNullOrEmpty(allowedExtensions) || FileHelper.CheckExtension(extension, allowedExtensions))) { // Upload SKU image meta file this.ucMetaFile.ObjectID = skuiObj.SKUID; this.ucMetaFile.UploadFile(); // Update SKU image path this.UpdateSKUImagePath(skuiObj); } else { // Set error message string error = ValidationHelper.GetString(SessionHelper.GetValue("NewProductError"), null); error += ";" + String.Format(this.GetString("com.productedit.invalidproductimage"), extension); SessionHelper.SetValue("NewProductError", error); } } } else { skuiObj.SKUImagePath = this.imgSelect.Value; } // Upload initial e-product file if (skuiObj.SKUProductType == SKUProductTypeEnum.EProduct) { this.eProductElem.SKUID = skuiObj.SKUID; this.eProductElem.UploadNewProductFile(); } } else { // Update SKU image path UpdateSKUImagePath(skuiObj); } SKUInfoProvider.SetSKUInfo(skuiObj); if ((mNodeId > 0) && (mProductId == 0)) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = tree.SelectSingleNode(mNodeId, TreeProvider.ALL_CULTURES); node.NodeSKUID = skuiObj.SKUID; node.Update(); // Update search index for node if ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); // Ensure new SKU values SKUInfoProvider.SetSKUInfo(skuiObj); } // If SKU is of bundle product type and bundle does not exist yet if ((skuiObj.SKUProductType == SKUProductTypeEnum.Bundle) && (this.bundleElem.BundleID == 0)) { // Set bundle ID this.bundleElem.BundleID = skuiObj.SKUID; // Save selected products this.bundleElem.SaveProductsSelectionChanges(); } this.ProductID = skuiObj.SKUID; // Reload form this.LoadData(skuiObj); // Set changes saved message this.lblInfo.Text = this.GetString("general.changessaved"); return(ValidationHelper.GetInteger(skuiObj.SKUID, 0)); } else { return(0); } }
/// <summary> /// Translates document(s). /// </summary> private void Translate(object parameter) { var parameters = parameter as AsyncParameters; if ((parameters == null) || nodeIds.Count < 1) { return; } AbstractMachineTranslationService machineService = null; AbstractHumanTranslationService humanService = null; TranslationSubmissionInfo submission = null; string submissionFileName = ""; int charCount = 0; int wordCount = 0; int refreshId = 0; int itemCount = 0; int pageCount = 0; bool oneSubmission = translationElem.CreateSeparateSubmission; bool success = false; bool separateSubmissionCreated = false; TreeProvider tree = new TreeProvider(); tree.AllowAsyncActions = false; try { // Begin log AddLog(GetString("contentrequest.starttranslate", parameters.UICulture)); // Prepare translation settings var settings = PrepareTranslationSettings(); // Check selected service var service = TranslationServiceInfoProvider.GetTranslationServiceInfo(translationElem.SelectedService); if (service == null) { return; } // Set if we need target tag (Translations.com workaround) settings.GenerateTargetTag = service.TranslationServiceGenerateTargetTag; if (service.TranslationServiceIsMachine) { machineService = AbstractMachineTranslationService.GetTranslationService(service, CurrentSiteName); } else { humanService = AbstractHumanTranslationService.GetTranslationService(service, CurrentSiteName); } bool langSupported = (humanService == null) || CheckLanguageSupport(humanService, settings); if (!langSupported) { return; } if ((machineService != null) || (humanService != null)) { var data = tree.SelectNodes() .CombineWithDefaultCulture(false) .Published(false) .Culture(settings.SourceLanguage) .WhereIn("NodeID", nodeIds) .OnSite(CurrentSiteName) .OrderBy("NodeLevel, NodeAliasPath") .Column("NodeID"); if (!DataHelper.DataSourceIsEmpty(data)) { var processedNodes = new List <int>(); // Translate the documents foreach (DataRow dr in data.Tables[0].Rows) { int nodeId = ValidationHelper.GetInteger(dr["NodeID"], 0); // Get document in source language var node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, false, tree); if (node == null) { // Document doesn't exist in source culture, skip it continue; } var targetLanguages = GetTargetLanguages(settings.TargetLanguages, node).ToList(); if (!targetLanguages.Any()) { continue; } if ((submission == null) && (humanService != null)) { // Create new submission if not exists for human translation service submission = TranslationServiceHelper.CreateSubmissionInfo(settings, service, MembershipContext.AuthenticatedUser.UserID, SiteInfoProvider.GetSiteID(CurrentSiteName), node.GetDocumentName()); } // Handle duplicities if (processedNodes.Contains(nodeId)) { continue; } processedNodes.Add(nodeId); bool targetLanguageVersionCreated = false; bool logged = false; string encodedPath = HTMLHelper.HTMLEncode(node.NodeAliasPath); foreach (var targetLanguage in targetLanguages) { // Log only once per document if (!logged) { AddLog(String.Format(GetString("content.translating"), encodedPath, settings.SourceLanguage)); logged = true; } itemCount++; targetLanguageVersionCreated = true; if (humanService != null) { if (String.IsNullOrEmpty(submissionFileName)) { submissionFileName = node.NodeAlias; } var targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, targetLanguage, true, false, !settings.TranslateAttachments); TranslationSubmissionItemInfo submissionItem; using (new CMSActionContext { TouchParent = false }) { // Do not touch parent because all updated information are saved after last item submissionItem = TranslationServiceHelper.CreateSubmissionItemInfo(settings, submission, node, targetNode.DocumentID, targetLanguage); } charCount += submissionItem.SubmissionItemCharCount; wordCount += submissionItem.SubmissionItemWordCount; } else { // Prepare local settings to translate per one target language var localSettings = settings.Clone(); localSettings.TargetLanguages.Clear(); localSettings.TargetLanguages.Add(targetLanguage); // Translate page via machine translator TranslationServiceHelper.Translate(machineService, localSettings, node); } } // Each page has own submission if human service is used if (!oneSubmission && (humanService != null)) { if (itemCount > 0) { SubmitSubmissionToService(itemCount, submission, charCount, wordCount, submissionFileName, humanService, true); // Reset counters itemCount = 0; charCount = 0; wordCount = 0; // Reset submission file name submissionFileName = null; // At least one submission was created separateSubmissionCreated = true; } else { // No documents were submitted to translation delete empty submission TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission); } // Reset submission to create new for next page submission = null; } if (targetLanguageVersionCreated) { // Check if at least one target language version was created pageCount++; } // Store parent ID to refresh UI refreshId = node.NodeParentID; } success = true; } else { AddError(GetString("TranslateDocument.NoSourceDocuments", parameters.UICulture)); } } else { AddError(GetString("TranslateDocument.TranslationServiceNotFound", parameters.UICulture)); } } catch (ThreadAbortException ex) { if (CMSThread.Stopped(ex)) { // When canceled AddError(GetString("TranslateDocument.TranslationCanceled", parameters.UICulture)); } else { // Log error LogExceptionToEventLog(ex, parameters.UICulture); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ex, parameters.UICulture); } finally { var showAllAlreadyTranslatedError = false; if (itemCount > 0) { // All pages are submitted via only one submission or using machine service if ((humanService != null) && (submission != null)) { // Set submission name if more pages are translated if (pageCount > 1) { submission.SubmissionName += " " + String.Format(GetString("translationservices.submissionnamesuffix"), pageCount - 1); // Do not localize the file name submissionFileName += String.Format(" (and {0} more)", pageCount - 1); } SubmitSubmissionToService(itemCount, submission, charCount, wordCount, submissionFileName, humanService, success); } } else if (oneSubmission) { TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission); // Log error only if the translation was successfully processed if (success) { showAllAlreadyTranslatedError = true; } } else if (!separateSubmissionCreated) { // Separate submissions were used and no one was created showAllAlreadyTranslatedError = true; } if (showAllAlreadyTranslatedError) { AddError(GetString("TranslateDocument.DocumentsAlreadyTranslated", parameters.UICulture)); } if (parameters.IsDialog) { ctlAsyncLog.Parameter = "wopener.location.replace(wopener.location); CloseDialog(); if (wopener.RefreshTree) { wopener.RefreshTree(null, null);}"; } else { if (String.IsNullOrEmpty(CurrentError)) { // Overwrite refreshId variable if sub-levels are visible if (parameters.AllLevels && Parameters.ContainsKey("refreshnodeid")) { refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0); } // Refresh tree ctlAsyncLog.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");"; } else { ctlAsyncLog.Parameter = "RefreshTree(null, null);"; } } } }
/// <summary> /// Processes the callback action. /// </summary> void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) { eventArgument = eventArgument.ToLowerCSafe(); string[] parameters = eventArgument.Split(';'); if (parameters.Length < 3) { return; } // Get the arguments string action = parameters[0]; int nodeId = ValidationHelper.GetInteger(parameters[1], 0); int targetId = ValidationHelper.GetInteger(parameters[2], 0); // Get the target node TreeNode targetNode = TreeProvider.SelectSingleNode(targetId, TreeProvider.ALL_CULTURES); if (targetNode == null) { AddError(GetString("ContentRequest.ErrorMissingTarget") + " " + eventArgument); mCallbackResult += GetFallBackToRootScript(true); return; } // Get the node TreeNode node = TreeProvider.SelectSingleNode(nodeId); if (node == null) { AddError(GetString("ContentRequest.ErrorMissingSource")); mCallbackResult += GetFallBackToRootScript(true); return; } // Get new parent ID int newParentId = targetNode.NodeID; if (action.Contains("position")) { if (action.Contains("move") && (nodeId == targetId)) { // There is no need to change position return; } if (!targetNode.IsRoot()) { newParentId = targetNode.NodeParentID; } } else if (node.NodeParentID == newParentId) { // Move/Copy/Link as the first node under the same parent if (action.EndsWithCSafe("position")) { action = action.Substring(0, action.Length - 8); } action += "first"; } bool copy = (action.Contains("copy")); bool link = (action.Contains("link")); // Do not allow to move or copy under itself if ((node.NodeID == newParentId) && !copy && !link) { AddError(GetString("ContentRequest.CannotMoveToItself")); return; } // Local action - Only position change if ((node.NodeParentID == newParentId) && !copy && !link) { // Local action - Only position change int originalPosition = node.NodeOrder; TreeNode newNode = ProcessAction(node, targetNode, action, false, false, true); if ((newNode != null) && (originalPosition != newNode.NodeOrder)) { // Log the synchronization tasks for the entire tree level DocumentSynchronizationHelper.LogDocumentChangeOrder(SiteContext.CurrentSiteName, newNode.NodeAliasPath, TreeProvider); mCallbackResult += "CancelDragOperation(); RefreshTree(" + newNode.NodeParentID + ", currentNodeId);"; } } else { // Different parent mCallbackResult += "DragOperation(" + nodeId + ", " + targetId + ", '" + action + "');"; } }
/// <summary> /// Yes button click event handler. /// </summary> protected void btnYes_Click(object sender, EventArgs e) { if (IsBannedIP()) { return; } // Prepare the where condition string where = "NodeID = " + NodeID; // Get the documents DataSet ds = null; if (chkAllCultures.Checked) { ds = TreeProvider.SelectNodes(SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, -1, false); } else { ds = TreeProvider.SelectNodes(SiteName, "/%", CultureCode, false, null, where, null, -1, false); } if (!DataHelper.DataSourceIsEmpty(ds)) { // Get node alias var nodeAlias = DataHelper.GetStringValue(ds.Tables[0].Rows[0], "NodeAlias", string.Empty); // Get parent alias path var parentAliasPath = TreePathUtils.GetParentPath(DataHelper.GetStringValue(ds.Tables[0].Rows[0], "NodeAliasPath", string.Empty)); // Delete the documents foreach (DataRow dr in ds.Tables[0].Rows) { var aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], string.Empty); var culture = ValidationHelper.GetString(dr["DocumentCulture"], string.Empty); var className = ValidationHelper.GetString(dr["ClassName"], string.Empty); // Get the node var treeNode = TreeProvider.SelectSingleNode(SiteName, aliasPath, culture, false, className, false); if (treeNode != null) { // Check delete permissions var hasUserDeletePermission = !CheckPermissions || IsUserAuthorizedToDeleteDocument(treeNode, chkDestroy.Checked); if (hasUserDeletePermission) { // Delete the document try { DocumentHelper.DeleteDocument(treeNode, TreeProvider, chkAllCultures.Checked, chkDestroy.Checked); } catch (Exception ex) { EventLogProvider.LogEvent(EventType.ERROR, "Content", "DELETEDOC", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, MembershipContext.AuthenticatedUser.UserID, MembershipContext.AuthenticatedUser.UserName, treeNode.NodeID, treeNode.GetDocumentName(), RequestContext.UserHostAddress, SiteContext.CurrentSiteID); AddAlert(GetString("ContentRequest.DeleteFailed") + ": " + ex.Message); return; } } // Access denied - not authorized to delete the document else { AddAlert(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), treeNode.NodeAliasPath)); return; } } else { AddAlert(GetString("ContentRequest.ErrorMissingSource")); return; } } RaiseOnAfterDelete(); string rawUrl = RequestContext.RawURL.TrimEnd(new[] { '/' }); if ((!string.IsNullOrEmpty(nodeAlias)) && (rawUrl.Substring(rawUrl.LastIndexOfCSafe('/')).Contains(nodeAlias))) { // Redirect to the parent url when current url belongs to deleted document URLHelper.Redirect(UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(parentAliasPath))); } else { // Redirect to current url URLHelper.Redirect(rawUrl); } } else { AddAlert(GetString("DeleteDocument.CultureNotExists")); } }
protected void uniSelector_OnSelectionChanged(object sender, EventArgs e) { bool relaodNeeded = false; // Remove old items string newValues = ValidationHelper.GetString(this.uniSelector.Value, null); string items = DataHelper.GetNewItemsInList(newValues, currentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Initialize tree provider TreeProvider tree = new TreeProvider(); // Add all new items to site foreach (string item in newItems) { string cultureCode = ValidationHelper.GetString(item, ""); // Get the documents assigned to the culture being removed DataSet nodes = tree.SelectNodes(siteName, "/%", cultureCode, false, null, null, null, -1, false); if (DataHelper.DataSourceIsEmpty(nodes)) { CultureInfoProvider.RemoveCultureFromSite(cultureCode, siteName); } else { relaodNeeded = true; this.lblError.Visible = true; this.lblError.Text += String.Format(GetString("site_edit_cultures.errorremoveculturefromsite"), cultureCode) + '\n'; } } } } // Catch license limitations Exception try { // Add new items items = DataHelper.GetNewItemsInList(currentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to site foreach (string item in newItems) { string cultureCode = ValidationHelper.GetString(item, ""); CultureInfoProvider.AddCultureToSite(cultureCode, siteName); } } } } catch (Exception ex) { relaodNeeded = true; lblError.Text = ex.Message; lblError.Visible = true; } this.lblInfo.Visible = true; this.lblInfo.Text = GetString("general.changessaved"); if (relaodNeeded) { // Get the active cultures from DB DataSet ds = CultureInfoProvider.GetCultures("CultureID IN (SELECT CultureID FROM CMS_SiteCulture WHERE SiteID = " + si.SiteID + ")", null, 0, "CultureCode"); if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", SqlHelperClass.GetStringValues(ds.Tables[0], "CultureCode")); uniSelector.Value = currentValues; uniSelector.Reload(true); } } }
/// <summary> /// Performs necessary checks and publishes document. /// </summary> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PerformPublish(WorkflowManager wm, TreeProvider tree, string siteName, DataRow nodeRow) { string aliasPath = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty); return(PerformPublish(wm, GetDocument(tree, siteName, nodeRow), aliasPath)); }
/// <summary> ///Creates the document, workflow scope and step needed for this example. Called when the "Create example objects" button is pressed. /// </summary> private bool CreateExampleObjects() { // Create a new tree provider TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Get the root node TreeNode parent = tree.SelectSingleNode(CMSContext.CurrentSiteName, "/", "en-us"); if (parent != null) { // Create the API document TreeNode node = TreeNode.New("CMS.MenuItem", tree); node.DocumentName = "API Example"; node.DocumentCulture = "en-us"; // Insert it to database DocumentHelper.InsertDocument(node, parent, tree); // Get the default workflow WorkflowInfo workflow = WorkflowInfoProvider.GetWorkflowInfo("default"); if (workflow != null) { // Get the document data node = DocumentHelper.GetDocument(node, tree); // Create new workflow scope WorkflowScopeInfo scope = new WorkflowScopeInfo(); // Assign to the default workflow and current site and set starting alias path to the example document scope.ScopeWorkflowID = workflow.WorkflowID; scope.ScopeStartingPath = node.NodeAliasPath; scope.ScopeSiteID = CMSContext.CurrentSiteID; // Save the scope into the database WorkflowScopeInfoProvider.SetWorkflowScopeInfo(scope); // Create a new workflow step WorkflowStepInfo step = new WorkflowStepInfo(); // Set its properties step.StepWorkflowID = workflow.WorkflowID; step.StepName = "MyNewWorkflowStep"; step.StepDisplayName = "My new workflow step"; step.StepOrder = 1; // Save the workflow step WorkflowStepInfoProvider.SetWorkflowStepInfo(step); // Ensure correct step order WorkflowStepInfoProvider.InitStepOrders(step.StepWorkflowID); return(true); } else { apiCreateExampleObjects.ErrorMessage = "The default workflow was not found."; } } return(false); }
protected void Page_Load(object sender, EventArgs e) { // Register main CMS script file ScriptHelper.RegisterCMS(this); if (QueryHelper.ValidateHash("hash") && (Parameters != null)) { // Initialize current user currentUser = MembershipContext.AuthenticatedUser; // Check permissions if (!currentUser.IsGlobalAdministrator && !currentUser.IsAuthorizedPerResource("CMS.Content", "manageworkflow")) { RedirectToAccessDenied("CMS.Content", "manageworkflow"); } // Set current UI culture currentCulture = CultureHelper.PreferredUICultureCode; // Initialize current site currentSiteName = SiteContext.CurrentSiteName; currentSiteId = SiteContext.CurrentSiteID; // 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 = 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[] { '|' }, 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); string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeParentID, DocumentName,DocumentCheckedOutByUserID"); allDocs = tree.SelectNodes(currentSiteName, parentAliasPath.TrimEnd('/') + "/%", TreeProvider.ALL_CULTURES, true, DataClassInfoProvider.GetClassName(ClassID), where.ToString(true), "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 string titleText = null; switch (CurrentAction) { case WorkflowAction.Archive: headQuestion.ResourceString = "content.archivequestion"; chkAllCultures.ResourceString = "content.archiveallcultures"; chkUnderlying.ResourceString = "content.archiveunderlying"; canceledString = GetString("content.archivecanceled"); // Setup title of log ctlAsyncLog.TitleText = GetString("content.archivingdocuments"); // Setup page title text and image titleText = GetString("Content.ArchiveTitle"); break; case WorkflowAction.Publish: headQuestion.ResourceString = "content.publishquestion"; chkAllCultures.ResourceString = "content.publishallcultures"; chkUnderlying.ResourceString = "content.publishunderlying"; canceledString = GetString("content.publishcanceled"); // Setup title of log ctlAsyncLog.TitleText = GetString("content.publishingdocuments"); // Setup page title text and image titleText = GetString("Content.PublishTitle"); break; } PageTitle.TitleText = titleText; EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText); if (nodeIds.Count == 0) { // Hide if no node was specified pnlContent.Visible = false; return; } // Register the dialog script ScriptHelper.RegisterDialogScript(this); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; // Set all cultures checkbox DataSet culturesDS = CultureSiteInfoProvider.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 = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true); string columns = SqlHelper.MergeColumns(DocumentColumnLists.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 = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID"); 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 title = GetString("general.publish"); if (CurrentAction == WorkflowAction.Archive) { title = GetString("general.archive"); } SetTitle(title); } else { pnlPublish.Visible = false; ShowError(GetString("dialogs.badhashtext")); } }
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 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 currentCulture = LocalizationContext.CurrentCulture.CultureCode; 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.AddRangeToSet(targetCultures); var useCurrentAsDefault = QueryHelper.GetBoolean("currentastargetdefault", false); if (!currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(currentCulture, 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 string defaultCulture = CultureHelper.GetDefaultCultureCode(CurrentSiteName); 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(CurrentSiteName, 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(CurrentSiteName, "/%", 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(CurrentSiteName, 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 btnTranslate_Click(object sender, EventArgs e) { // Check if data are correct var error = translationElem.ValidateData(); if (!String.IsNullOrEmpty(error) || !allowTranslate) { plcMessages.AddError(error); return; } if (isSelect) { // If in select mode, prepare node IDs now TreeProvider tree = new TreeProvider(); DataSet ds = tree.SelectNodes(CurrentSiteName, pathElem.Value.ToString(), TreeProvider.ALL_CULTURES, true, TreeProvider.ALL_CLASSNAMES, null, null, TreeProvider.ALL_LEVELS, false, 0, DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataTable table in ds.Tables) { foreach (DataRow dr in table.Rows) { TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr); if (TranslationServiceHelper.IsAuthorizedToTranslateDocument(node, currentUser, translationElem.TargetLanguages)) { nodeIds.Add(ValidationHelper.GetInteger(dr["NodeID"], 0)); } else { HideUI(); plcMessages.AddError(String.Format(GetString("cmsdesk.notauthorizedtotranslatedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath))); return; } } } } else { ShowError(GetString("translationservice.nodocumentstotranslate")); return; } targetCultures = translationElem.TargetLanguages; } pnlLog.Visible = true; pnlContent.Visible = false; CurrentError = string.Empty; var parameters = new AsyncParameters { IsDialog = IsDialog, AllLevels = AllLevels, UICulture = CultureHelper.PreferredUICultureCode }; ctlAsyncLog.RunAsync(p => Translate(parameters), WindowsIdentity.GetCurrent()); }
private void ReloadData() { if (StopProcessing) { // Do nothing gridDocs.StopProcessing = true; editDoc.StopProcessing = true; } else { if (((AllowUsers == UserContributionAllowUserEnum.Authenticated) || (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)) && !CMSContext.CurrentUser.IsAuthenticated()) { // Not authenticated, do not display anything pnlList.Visible = false; pnlEdit.Visible = false; StopProcessing = true; } else { SetContext(); // Hide document list gridDocs.Visible = false; // If the list of documents should be displayed ... if (DisplayList) { // Get all documents of the current user TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Generate additional where condition string classWhere = null; if (!String.IsNullOrEmpty(ClassNames)) { // Remove ending semicolon classWhere = ClassNames.TrimEnd(';'); // Replace single apostrophs classWhere = SqlHelperClass.GetSafeQueryString(classWhere, false); // Replace ; with ',' classWhere = classWhere.Replace(";", "','"); if (!String.IsNullOrEmpty(classWhere)) { classWhere = String.Format("ClassName IN ('{0}')", classWhere); } } string where = SqlHelperClass.AddWhereCondition(WhereCondition, classWhere); // Add user condition if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner) { where = SqlHelperClass.AddWhereCondition(where, "NodeOwner = " + CMSContext.CurrentUser.UserID); } // Ensure that required columns are included in "Columns" list string columns = EnsureColumns(); // Get the documents DataSet ds = DocumentHelper.GetDocuments(SiteName, CMSContext.ResolveCurrentPath(Path), CultureCode, CombineWithDefaultCulture, null, where, OrderBy, MaxRelativeLevel, SelectOnlyPublished, 0, columns, tree); if (CheckPermissions) { ds = TreeSecurityProvider.FilterDataSetByPermissions(ds, NodePermissionsEnum.Read, CMSContext.CurrentUser); } if (!DataHelper.DataSourceIsEmpty(ds)) { // Display and initialize grid if datasource is not empty gridDocs.Visible = true; gridDocs.DataSource = ds; gridDocs.OrderBy = OrderBy; editDoc.AlternativeFormName = AlternativeFormName; } } bool isAuthorizedToCreateDoc = false; if (ParentNode != null) { // Check if single class name is set string className = (!string.IsNullOrEmpty(AllowedChildClasses) && !AllowedChildClasses.Contains(";")) ? AllowedChildClasses : null; // Check user's permission to create new document if allowed isAuthorizedToCreateDoc = !CheckPermissions || CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(ParentNodeID, className); // Check group's permission to create new document if allowed isAuthorizedToCreateDoc &= CheckGroupPermission("createpages"); if (!CheckDocPermissionsForInsert && CheckPermissions) { // If document permissions are not required check create permission on parent document isAuthorizedToCreateDoc = CMSContext.CurrentUser.IsAuthorizedPerDocument(ParentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed; } if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner) { // Do not allow documents creation under virtual user if (CMSContext.CurrentUser.IsVirtual) { isAuthorizedToCreateDoc = false; } else { // Check if user is document owner (or global admin) isAuthorizedToCreateDoc = isAuthorizedToCreateDoc && ((ParentNode.NodeOwner == CMSContext.CurrentUser.UserID) || CMSContext.CurrentUser.IsGlobalAdministrator); } } } // Enable/disable inserting new document pnlNewDoc.Visible = (isAuthorizedToCreateDoc && AllowInsert); if (!gridDocs.Visible && !pnlNewDoc.Visible && pnlList.Visible) { // Not authenticated to create new docs and grid is hidden StopProcessing = true; } ReleaseContext(); } } }
/// <summary> /// Gets parent node ID. /// </summary> private TreeNode GetParentNode() { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); return(tree.SelectSingleNode(SiteName, CMSContext.ResolveCurrentPath(NewDocumentPath), TreeProvider.ALL_CULTURES)); }
/// <summary> /// If the document hasn't been checked out, creates a new modified version of the document. If it has, the example modifies the checked out version. Called when the "Edit document" button is pressed. /// Expects the "CreateExampleObjects" method and optionally the "CheckOut" method to be run first. /// </summary> private bool EditDocument() { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Prepare parameters string siteName = CMSContext.CurrentSiteName; string aliasPath = "/API-Example"; string culture = "en-us"; bool combineWithDefaultCulture = false; string classNames = TreeProvider.ALL_CLASSNAMES; string where = null; string orderBy = null; int maxRelativeLevel = -1; bool selectOnlyPublished = false; string columns = null; // Get the document TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree); if (node != null) { WorkflowManager workflowmanager = new WorkflowManager(tree); // Make sure the document uses workflow WorkflowInfo workflow = workflowmanager.GetNodeWorkflow(node); if (workflow != null) { // Check if the workflow uses check-in/check-out bool autoCheck = !workflow.UseCheckInCheckOut(CMSContext.CurrentSiteName); // Create a new version manager instance VersionManager versionmanager = new VersionManager(tree); // If it does not use check-in/check-out, check out the document automatically if (autoCheck) { versionmanager.CheckOut(node); } if (node.IsCheckedOut) { // Edit the last version of the document string newName = node.DocumentName.ToLower(); node.DocumentName = newName; node.SetValue("MenuItemName", newName); // Save the document version DocumentHelper.UpdateDocument(node, tree); // Automatically check in if (autoCheck) { versionmanager.CheckIn(node, null, null); } return(true); } else { apiEditDocument.ErrorMessage = "The document hasn't been checked out."; } } else { apiEditDocument.ErrorMessage = "The document doesn't use workflow."; } } return(false); }