/// <summary> /// Initializes control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { // Prepare alias path string aliasPath = Path; if (String.IsNullOrEmpty(aliasPath)) { aliasPath = "/%"; } aliasPath = CMSContext.ResolveCurrentPath(aliasPath); // Prepare site name string siteName = SiteName; if (String.IsNullOrEmpty(siteName)) { siteName = CMSContext.CurrentSiteName; } // Prepare culture code string cultureCode = CultureCode; if (String.IsNullOrEmpty(cultureCode)) { cultureCode = CMSContext.PreferredCultureCode; } // Comments filter properties srcComments.SelectOnlyApproved = SelectOnlyApproved; srcComments.SiteName = siteName; srcComments.WhereCondition = WhereCondition; srcComments.OrderBy = OrderBy; srcComments.TopN = SelectTopN; srcComments.SelectedColumns = Columns; srcComments.FilterName = ValidationHelper.GetString(GetValue("WebPartControlID"), ClientID); srcComments.SourceFilterName = FilterName; // Caching properties srcComments.CacheItemName = CacheItemName; srcComments.CacheDependencies = CacheDependencies; srcComments.CacheMinutes = CacheMinutes; // Document filter properties srcComments.UseDocumentFilter = UseDocumentFilter; srcComments.DocumentsWhereCondition = DocumentsWhereCondition; srcComments.CombineWithDefaultCulture = CombineWithDefaultCulture; srcComments.CultureCode = cultureCode; srcComments.SelectOnlyPublished = SelectOnlyPublished; srcComments.MaxRelativeLevel = MaxRelativeLevel; srcComments.Path = aliasPath; } }
/// <summary> /// Initializes control properties. /// </summary> protected void SetupControl() { if (this.StopProcessing) { // Do nothing } else { // Prepare alias path string aliasPath = Path; if (String.IsNullOrEmpty(aliasPath)) { aliasPath = "/%"; } aliasPath = CMSContext.ResolveCurrentPath(aliasPath); // Prepare site name string siteName = SiteName; if (String.IsNullOrEmpty(siteName)) { siteName = CMSContext.CurrentSiteName; } // Prepare culture code string cultureCode = CultureCode; if (String.IsNullOrEmpty(cultureCode)) { cultureCode = CMSContext.PreferredCultureCode; } this.srcMessages.BoardName = this.BoardName; this.srcMessages.SiteName = siteName; this.srcMessages.WhereCondition = this.WhereCondition; this.srcMessages.OrderBy = this.OrderBy; this.srcMessages.TopN = this.SelectTopN; this.srcMessages.FilterName = ValidationHelper.GetString(this.GetValue("WebPartControlID"), this.ClientID); this.srcMessages.SourceFilterName = this.FilterName; this.srcMessages.CacheItemName = this.CacheItemName; this.srcMessages.CacheDependencies = this.CacheDependencies; this.srcMessages.CacheMinutes = this.CacheMinutes; this.srcMessages.SelectOnlyApproved = this.SelectOnlyApproved; this.srcMessages.SelectedColumns = this.Columns; this.srcMessages.ShowGroupMessages = this.ShowGroupMessages; // Documents properties this.srcMessages.Path = aliasPath; this.srcMessages.UseDocumentFilter = this.UseDocumentFilter; this.srcMessages.CultureCode = cultureCode; this.srcMessages.DocumentsWhereCondition = this.DocumentsWhereCondition; this.srcMessages.CombineWithDefaultCulture = this.CombineWithDefaultCulture; this.srcMessages.SelectOnlyPublished = this.SelectOnlyPublished; this.srcMessages.MaxRelativeLevel = this.MaxRelativeLevel; } }
/// <summary> /// Returns Correct URL of the 'Set permissions' dialog. /// </summary> private string GetPermissionsDialogUrl(string nodeAliasPath) { string url = ResolveUrl("~/CMSModules/Content/FormControls/Documents/ChangePermissions/ChangePermissions.aspx"); // Use current document path if not set if (string.IsNullOrEmpty(nodeAliasPath) && (CMSContext.CurrentDocument != null)) { nodeAliasPath = CMSContext.CurrentDocument.NodeAliasPath; } nodeIdFromPath = TreePathUtils.GetNodeIdByAliasPath(SiteName, CMSContext.ResolveCurrentPath(nodeAliasPath)); url = URLHelper.AddParameterToUrl(url, "nodeid", nodeIdFromPath.ToString()); url = URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash(url)); return(url); }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { // WAI validation lblSearch.ResourceString = "ForumSearch.SearchWord"; lblSearch.Attributes.Add("style", "display: none;"); btnGo.Text = GetString("ForumSearch.Go"); if (!String.IsNullOrEmpty(AdvancedSearchPath)) { lnkAdvanceSearch.NavigateUrl = ResolveUrl(TreePathUtils.GetUrl(CMSContext.ResolveCurrentPath(AdvancedSearchPath))); lnkAdvanceSearch.Visible = true; lnkAdvanceSearch.Text = GetString("ForumSearch.AdvanceSearch"); if (!RequestHelper.IsPostBack()) { txtSearch.Text = QueryHelper.GetString("searchtext", txtSearch.Text); } } }
private void SetupControl() { if (StopProcessing) { // Do nothing libraryElem.StopProcessing = true; } else { // Initialize document library control libraryElem.LibraryPath = CMSContext.ResolveCurrentPath(LibraryPath); libraryElem.CombineWithDefaultCulture = CombineWithDefaultCulture; libraryElem.PageSize = PageSize; libraryElem.DocumentForm = DocumentForm; libraryElem.CacheDependencies = CacheDependencies; libraryElem.CacheItemName = CacheItemName; libraryElem.CacheMinutes = CacheMinutes; libraryElem.ZeroRowsText = ZeroRowsText; libraryElem.CheckPermissions = CheckPermissions; libraryElem.PermissionsIconImageUrl = PermissionsIconImageUrl; libraryElem.NewFileIconImageUrl = NewFileIconImageUrl; } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { rssFeed.StopProcessing = true; srcComments.StopProcessing = true; } else { string feedCodeName = URLHelper.GetSafeUrlPart(FeedName, SiteName); // RSS feed properties rssFeed.FeedName = feedCodeName; rssFeed.FeedLink = URLHelper.GetAbsoluteUrl(URLHelper.AddParameterToUrl(URLHelper.CurrentURL, QueryStringKey, feedCodeName)); rssFeed.LinkText = LinkText; rssFeed.LinkIcon = LinkIcon; rssFeed.FeedTitle = FeedTitle; rssFeed.FeedDescription = FeedDescription; rssFeed.FeedLanguage = FeedLanguage; rssFeed.EnableAutodiscovery = EnableRSSAutodiscovery; rssFeed.QueryStringKey = QueryStringKey; rssFeed.HeaderXML = HeaderXML; rssFeed.FooterXML = FooterXML; rssFeed.CacheDependencies = CacheDependencies; rssFeed.CacheItemName = CacheItemName; rssFeed.CacheMinutes = CacheMinutes; // Prepare alias path string aliasPath = Path; if (String.IsNullOrEmpty(aliasPath)) { aliasPath = "/%"; } aliasPath = CMSContext.ResolveCurrentPath(aliasPath); // Prepare site name string siteName = SiteName; if (String.IsNullOrEmpty(siteName)) { siteName = CMSContext.CurrentSiteName; } // Prepare culture code string cultureCode = CultureCode; if (String.IsNullOrEmpty(cultureCode)) { cultureCode = CMSContext.PreferredCultureCode; } // Document properties srcComments.UseDocumentFilter = UseDocumentFilter; srcComments.FilterName = ValidationHelper.GetString(GetValue("WebPartControlID"), ClientID); srcComments.CacheItemName = CacheItemName; srcComments.CacheDependencies = CacheDependencies; srcComments.CacheMinutes = CacheMinutes; srcComments.CombineWithDefaultCulture = CombineWithDefaultCulture; srcComments.CultureCode = cultureCode; srcComments.MaxRelativeLevel = MaxRelativeLevel; srcComments.OrderBy = OrderBy; srcComments.Path = aliasPath; srcComments.SelectOnlyPublished = SelectOnlyPublished; srcComments.SiteName = siteName; srcComments.WhereCondition = WhereCondition; srcComments.TopN = SelectTopN; srcComments.SelectedColumns = Columns; srcComments.SourceFilterName = FilterName; srcComments.SelectOnlyApproved = SelectOnlyApproved; // Binding rssFeed.DataBindByDefault = DataBindByDefault; // Transformations rssFeed.TransformationName = TransformationName; // Connects RSS feed with data source rssFeed.DataSourceControl = srcComments; } }
/// <summary> /// SignOut handler. /// </summary> protected void btnSignOut_Click(object sender, EventArgs e) { if (StopProcessing) { // Do not process } else { if (CMSContext.CurrentUser.IsAuthenticated()) { CMSContext.LogoutUser(); string redirectUrl = RedirectToUrl; // If the user has registered Windows Live ID if (!String.IsNullOrEmpty(CMSContext.CurrentUser.UserSettings.WindowsLiveID)) { // Get data from auth cookie string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie(); // If user has logged in using Windows Live ID, then sign him out from Live too if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0)) { string siteName = CMSContext.CurrentSiteName; // Get LiveID settings string appId = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationID"); string secret = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationSecret"); // Check valid Windows LiveID parameters if ((appId != string.Empty) && (secret != string.Empty)) { WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret); // Store info about logout request, for validation logout request SessionHelper.SetValue("liveidlogout", DateTime.Now); // Redirect to Windows Live redirectUrl = wll.GetLogoutUrl(); } } } CMSContext.ViewMode = ViewModeEnum.LiveSite; CMSContext.CurrentUser = null; Response.Cache.SetNoStore(); URLHelper.Redirect(redirectUrl); } else { string returnUrl = null; string signInUrl = null; if (SignInUrl != "") { signInUrl = ResolveUrl(CMSContext.GetUrl(CMSContext.ResolveCurrentPath(SignInUrl))); } else { signInUrl = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSecuredAreasLogonPage"); } if (ReturnPath != "") { returnUrl = ResolveUrl(CMSContext.GetUrl(CMSContext.ResolveCurrentPath(ReturnPath))); } else { returnUrl = URLHelper.CurrentURL; } if (signInUrl != "") { // Prevent multiple returnUrl parameter returnUrl = URLHelper.RemoveParameterFromUrl(returnUrl, "returnUrl"); URLHelper.Redirect(URLHelper.UpdateParameterInUrl(signInUrl, "returnurl", returnUrl)); } } } }
/// <summary> /// Perform search. /// </summary> protected void Search() { if (StopProcessing) { // Do nothing } else { // Get query strings string searchText = QueryHelper.GetString("searchtext", ""); if (!string.IsNullOrEmpty(searchText)) { string searchMode = QueryHelper.GetString("searchMode", ""); CMS.ISearchEngine.SearchModeEnum searchModeEnum = CMS.ISearchEngine.SearchHelper.GetSearchModeEnum(searchMode); int numberOfResults = 0; // Get current culture string culture = CultureCode; if (string.IsNullOrEmpty(culture)) { culture = ValidationHelper.GetString(ViewState["CultureCode"], CMSContext.PreferredCultureCode); } // Get default culture string defaultCulture = CultureHelper.GetDefaultCulture(CMSContext.CurrentSiteName); // Resolve path string path = Path; if (!string.IsNullOrEmpty(path)) { path = CMSContext.ResolveCurrentPath(Path); } if (CMSContext.ViewMode == ViewModeEnum.LiveSite) { // Log on site keywords AnalyticsHelper.LogOnSiteSearchKeywords(CMSContext.CurrentSiteName, CMSContext.CurrentAliasPath, culture, searchText, 0, 1); } // Prepare search text searchText = SearchHelper.CombineSearchCondition(searchText, SearchCondition + FilterSearchCondition, searchModeEnum, SearchOptions, DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture); // Get positions and ranges for search method int startPosition = 0; int numberOfProceeded = 100; int displayResults = 100; if (pgrSearch.PageSize != 0 && pgrSearch.GroupSize != 0) { startPosition = (pgrSearch.CurrentPage - 1) * pgrSearch.PageSize; numberOfProceeded = (((pgrSearch.CurrentPage / pgrSearch.GroupSize) + 1) * pgrSearch.PageSize * pgrSearch.GroupSize) + pgrSearch.PageSize; displayResults = pgrSearch.PageSize; } if ((this.MaxResults > 0) && (numberOfProceeded > this.MaxResults)) { numberOfProceeded = this.MaxResults; } // Combine regular search sort with filter sort string srt = ValidationHelper.GetString(SearchSort, String.Empty).Trim(); string filterSrt = ValidationHelper.GetString(FilterSearchSort, String.Empty).Trim(); if (!String.IsNullOrEmpty(filterSrt)) { if (!String.IsNullOrEmpty(srt)) { srt += ", "; } srt += filterSrt; } // Search DataSet results = SearchHelper.Search(searchText, SearchHelper.GetSort(srt), path, DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture, CheckPermissions, SearchInAttachments, Indexes, displayResults, startPosition, numberOfProceeded, (UserInfo)CMSContext.CurrentUser, out numberOfResults, AttachmentsWhere, AttachmentsOrderBy); if ((this.MaxResults > 0) && (numberOfResults > MaxResults)) { numberOfResults = MaxResults; } // Fill repeater with results repSearchResults.DataSource = results; repSearchResults.PagerForceNumberOfResults = numberOfResults; repSearchResults.DataBind(); // Show now results found ? if (numberOfResults == 0) { lblNoResults.Text = NoResultsText; lblNoResults.Visible = true; } } else { Visible = false; } // Invoke search completed event if (OnSearchCompleted != null) { OnSearchCompleted(Visible); } } }
/// <summary> /// Setups control properties. /// </summary> protected void SetupControl() { // Check StopProcessing property if (StopProcessing) { Visible = false; } else { SetContext(); DataSet users = null; bool transLoaded = false; // Load transformation if (!string.IsNullOrEmpty(TransformationName)) { repUsers.ItemTemplate = CMSDataProperties.LoadTransformation(this, TransformationName, false); transLoaded = true; } if ((transLoaded) || (!String.IsNullOrEmpty(Path))) { // Try to get data from cache using (CachedSection <DataSet> cs = new CachedSection <DataSet>(ref users, this.CacheMinutes, true, this.CacheItemName, "onlineusers", CMSContext.CurrentSiteName, SelectTopN, Columns, Path)) { if (cs.LoadData) { // Get the data users = SessionManager.GetOnlineUsers(null, null, SelectTopN, Columns, CMSContext.ResolveCurrentPath(Path), CMSContext.CurrentSiteName, false, false); // Prepare the cache dependency if (cs.Cached) { cs.CacheDependency = GetCacheDependency(); cs.Data = users; } } } // Data bind if (!DataHelper.DataSourceIsEmpty(users)) { // Set to repeater repUsers.DataSource = users; repUsers.DataBind(); } } int authenticated = 0; int publicUsers = 0; string numbers = string.Empty; // Get or generate cache item name string cacheItemNameNumbers = this.CacheItemName; if (!string.IsNullOrEmpty(cacheItemNameNumbers)) { cacheItemNameNumbers += "Number"; } // Try to get data from cache using (CachedSection <string> cs = new CachedSection <string>(ref numbers, this.CacheMinutes, true, cacheItemNameNumbers, "onlineusersnumber", CMSContext.CurrentSiteName, Path)) { if (cs.LoadData) { // Get the data SessionManager.GetUsersNumber(CurrentSiteName, CMSContext.ResolveCurrentPath(Path), false, false, out publicUsers, out authenticated); // Save to the cache if (cs.Cached) { cs.CacheDependency = GetCacheDependency(); cs.Data = publicUsers.ToString() + ";" + authenticated.ToString(); } } else { // Retrieved from cache string[] nums = numbers.Split(';'); publicUsers = ValidationHelper.GetInteger(nums[0], 0); authenticated = ValidationHelper.GetInteger(nums[1], 0); } } // Check if at least one user is online if ((publicUsers + authenticated) == 0) { ltrAdditionaInfos.Text = NoUsersOnlineText; } else { ltrAdditionaInfos.Text = string.Format(AdditionalInfoText, publicUsers + authenticated, publicUsers, authenticated); } } ReleaseContext(); }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (this.StopProcessing) { this.editForm.StopProcessing = true; this.editForm.Visible = false; } else { this.pnlEdit.Visible = false; CurrentUserInfo currentUser = CMSContext.CurrentUser; // Get the document TreeNode node = TreeHelper.GetDocument(this.SiteName, CMSContext.ResolveCurrentPath(this.Path), this.CultureCode, false, null, false, this.CheckPermissions, currentUser); if (node != null) { bool authorized = false; // Check allowed users switch (this.AllowUsers) { case UserContributionAllowUserEnum.All: authorized = true; break; case UserContributionAllowUserEnum.Authenticated: authorized = currentUser.IsAuthenticated(); break; case UserContributionAllowUserEnum.DocumentOwner: authorized = (node.NodeOwner == currentUser.UserID); break; } bool authorizedDelete = authorized; // Check control access permission if (authorized && this.CheckPermissions) { // Node owner has always permission if (node.NodeOwner != currentUser.UserID) { authorized &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Modify }) == AuthorizationResultEnum.Allowed); authorizedDelete &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Delete }) == AuthorizationResultEnum.Allowed); } } // Check group permissions authorized &= CheckGroupPermission("editpages"); authorizedDelete &= CheckGroupPermission("deletepages"); // Global admin has always permission authorized |= currentUser.IsGlobalAdministrator; authorizedDelete |= currentUser.IsGlobalAdministrator; // Do not allow edit for virtual user if (currentUser.IsVirtual) { authorized = false; authorizedDelete = false; } // Display form if authorized if (authorized || authorizedDelete) { this.pnlEdit.Visible = true; // Set visibility of edit and delete buttons this.btnEdit.Visible = this.btnEdit.Visible && authorized; this.btnDelete.Visible = this.btnDelete.Visible && this.AllowDelete && authorizedDelete; if ((!RequestHelper.IsPostBack()) && ((this.btnEdit.Text.Trim() == string.Empty) || (this.btnDelete.Text.Trim() == string.Empty))) { // Initialize labels and css classes this.btnEdit.ResourceString = this.EditButtonText; this.btnEdit.CssClass = "EditContributionEdit"; this.btnDelete.ResourceString = this.DeleteButtonText; this.btnDelete.CssClass = "EditContributionDelete"; } if (this.pnlForm.Visible) { this.editForm.StopProcessing = false; this.editForm.FunctionsPrefix = this.ID + "_"; this.editForm.AllowDelete = this.AllowDelete && CheckGroupPermission("deletepages"); this.editForm.CheckPermissions = this.CheckPermissions; this.editForm.NodeID = node.NodeID; this.editForm.SiteName = this.SiteName; this.editForm.CultureCode = this.CultureCode; this.editForm.AlternativeFormName = this.AlternativeFormName; this.editForm.ValidationErrorMessage = this.ValidationErrorMessage; this.editForm.CMSForm.IsLiveSite = true; this.editForm.OnAfterApprove += editForm_OnAfterChange; this.editForm.OnAfterReject += editForm_OnAfterChange; this.editForm.OnAfterDelete += editForm_OnAfterChange; this.editForm.CMSForm.OnAfterSave += CMSForm_OnAfterSave; this.editForm.LogActivity = this.LogActivity; // Reload data this.editForm.ReloadData(false); } } } } }
/// <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)); }
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> /// OK click handler (Proceed registration). /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible)) { // Do not process } else { String siteName = CMSContext.CurrentSiteName; #region "Banned IPs" // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } #endregion #region "Check Email & password" // Check whether user with same email does not exist UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail.Text); SiteInfo si = CMSContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si)); if ((ui != null) || (siteui != null)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text)); return; } // Check whether password is same if (passStrength.Text != txtConfirmPassword.Text) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch"); return; } if ((this.PasswordMinLength > 0) && (passStrength.Text.Length < this.PasswordMinLength)) { lblError.Visible = true; lblError.Text = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), this.PasswordMinLength.ToString()); return; } if (!passStrength.IsValid()) { lblError.Visible = true; lblError.Text = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName); return; } if (!ValidationHelper.IsEmail(txtEmail.Text.ToLower())) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"); return; } #endregion #region "Captcha" // Check if captcha is required if (this.DisplayCaptcha) { // Verifiy captcha text if (!scCaptcha.IsValid()) { // Display error message if catcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } else { // Generate new captcha scCaptcha.GenerateNew(); } } #endregion #region "User properties" ui = new UserInfo(); ui.PreferredCultureCode = ""; ui.Email = txtEmail.Text.Trim(); ui.FirstName = txtFirstName.Text.Trim(); ui.FullName = txtFirstName.Text.Trim() + " " + txtLastName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.MiddleName = ""; // User name as put by user (no site prefix included) String plainUserName = txtEmail.Text.Trim(); ui.UserName = plainUserName; // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(siteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text.Trim(), si); } ui.Enabled = this.EnableUserAfterRegistration; ui.IsEditor = false; ui.IsGlobalAdministrator = false; ui.UserURLReferrer = CMSContext.CurrentUser.URLReferrer; ui.UserCampaign = CMSContext.Campaign; ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = false; if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is reqiures if ((requiresAdminApprove = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"))) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(this.StartingAliasPath)) { ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(this.StartingAliasPath); } #endregion #region "Reserved names" // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true))); return; } if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName)); return; } #endregion #region "License limitations" // Check limitations for Global administrator if (ui.IsGlobalAdministrator) { if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedGlobal"); return; } } // Check limitations for editors if (ui.IsEditor) { if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Editors, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedEditor"); return; } } // Check limitations for site members if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedSiteMember"); return; } #endregion // Check whether email is unique if it is required string checkSites = (String.IsNullOrEmpty(this.AssignToSites)) ? siteName : this.AssignToSites; if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), checkSites, 0)) { lblError.Visible = true; lblError.Text = GetString("UserInfo.EmailAlreadyExist"); return; } // Set password UserInfoProvider.SetPassword(ui, passStrength.Text); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EventLogProvider ev = new EventLogProvider(); EmailTemplateInfo template = null; string emailSubject = null; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject")); } // Send welcome message with username and password, with information that user must be approved by administrator else if (this.SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject")); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject")); } } if (template != null) { // Rretrieve contact ID for confirmation e-mail int contactId = 0; if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { // Check if loggin registration activity is enabled if (ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); } } } // Prepare macro replacements string[,] replacements = new string[6, 2]; replacements[0, 0] = "confirmaddress"; replacements[0, 1] = (this.ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(this.ApprovalPage) : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx"); replacements[0, 1] += "?userguid=" + ui.UserGUID + (contactId > 0?"&contactid=" + contactId.ToString():String.Empty); replacements[1, 0] = "username"; replacements[1, 1] = plainUserName; replacements[2, 0] = "password"; replacements[2, 1] = passStrength.Text; replacements[3, 0] = "Email"; replacements[3, 1] = txtEmail.Text; replacements[4, 0] = "FirstName"; replacements[4, 1] = txtFirstName.Text; replacements[5, 0] = "LastName"; replacements[5, 1] = txtLastName.Text; // Set resolver ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; resolver.EncodeResolvedValues = true; // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = ui.Email; email.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(siteName + ".CMSNoreplyEmailAddress")); email.Body = resolver.ResolveMacros(template.TemplateText); resolver.EncodeResolvedValues = false; email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); email.Subject = resolver.ResolveMacros(emailSubject); email.CcRecipients = template.TemplateCc; email.BccRecipients = template.TemplateBcc; try { MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(siteName, email, true); } catch (Exception ex) { ev.LogEvent("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { lblError.Visible = true; lblError.Text = GetString("RegistrationForm.UserWasNotCreated"); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and e-mail confirmation is not required if (!requiresConfirmation && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate = null; if (requiresAdminApprove) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName); } if (mEmailTemplate == null) { // Log missing e-mail template ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri()); } else { string[,] replacements = new string[4, 2]; replacements[0, 0] = "firstname"; replacements[0, 1] = ui.FirstName; replacements[1, 0] = "lastname"; replacements[1, 1] = ui.LastName; replacements[2, 0] = "email"; replacements[2, 1] = ui.Email; replacements[3, 0] = "username"; replacements[3, 1] = plainUserName; ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceParameters = replacements; resolver.EncodeResolvedValues = true; EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, this.FromAddress); message.Recipients = this.ToAddress; message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText); resolver.EncodeResolvedValues = false; message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText); message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject"))); message.CcRecipients = mEmailTemplate.TemplateCc; message.BccRecipients = mEmailTemplate.TemplateBcc; try { // Attach template meta-files to e-mail MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); EmailSender.SendEmail(siteName, message); } catch { ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID); } } } #endregion #region "Web analytics" // Track successful registration conversion if (this.TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, this.TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(siteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName)) { int contactId = 0; // Log registration activity if (ActivitySettingsHelper.UserRegistrationEnabled(siteName)) { if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); ActivityLogProvider.LogRegistrationActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } // Log login activity if (ui.Enabled && ActivitySettingsHelper.UserLoginEnabled(siteName)) { if (contactId <= 0) { contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); } ActivityLogHelper.UpdateContactLastLogon(contactId); // Update last logon time if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui)) { ActivityLogProvider.LogLoginActivity(contactId, ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture); } } } } #endregion #region "Roles & authentication" string[] roleList = this.AssignRoles.Split(';'); string[] siteList; // If AssignToSites field set if (!String.IsNullOrEmpty(this.AssignToSites)) { siteList = this.AssignToSites.Split(';'); } else // If not set user current site { siteList = new string[] { siteName }; } foreach (string sn in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, sn); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String s = roleName.StartsWith(".") ? "" : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, s)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, s); } } } } if (this.DisplayMessage.Trim() != String.Empty) { pnlForm.Visible = false; lblText.Visible = true; lblText.Text = this.DisplayMessage; } else { if (ui.Enabled) { CMSContext.AuthenticateUser(ui.UserName, true); } if (this.RedirectToURL != String.Empty) { URLHelper.Redirect(this.RedirectToURL); } else if (QueryHelper.GetString("ReturnURL", "") != String.Empty) { string url = QueryHelper.GetString("ReturnURL", ""); // Do url decode url = Server.UrlDecode(url); // Check that url is relative path or hash is ok if (url.StartsWith("~") || url.StartsWith("/") || QueryHelper.ValidateHash("hash")) { URLHelper.Redirect(url); } // Absolute path with wrong hash else { URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext"))); } } } #endregion lblError.Visible = false; } }
/// <summary> /// Updates the current Group or creates new if no GroupID is present. /// </summary> public void SaveData() { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Validate form entries string errorMessage = ValidateForm(); if (errorMessage == "") { try { codeName = GetSafeCodeName(); codeName = GetUniqueCodeName(codeName); GroupInfo group = new GroupInfo(); group.GroupDisplayName = this.txtDisplayName.Text; group.GroupName = codeName; group.GroupDescription = this.txtDescription.Text; group.GroupAccess = GetGroupAccess(); group.GroupSiteID = this.mSiteId; group.GroupApproveMembers = GetGroupApproveMembers(); // Set columns GroupCreatedByUserID and GroupApprovedByUserID to current user CurrentUserInfo user = CMSContext.CurrentUser; if (user != null) { group.GroupCreatedByUserID = user.UserID; if ((!this.RequireApproval) || (CurrentUserIsAdmin())) { group.GroupApprovedByUserID = user.UserID; group.GroupApproved = true; } } // Save Group in the database GroupInfoProvider.SetGroupInfo(group); // Create group admin role RoleInfo roleInfo = new RoleInfo(); roleInfo.DisplayName = "Group admin"; roleInfo.RoleName = group.GroupName + "_groupadmin"; roleInfo.RoleGroupID = group.GroupID; roleInfo.RoleIsGroupAdministrator = true; roleInfo.SiteID = this.mSiteId; // Save group admin role RoleInfoProvider.SetRoleInfo(roleInfo); if (user != null) { // Set user as member of group GroupMemberInfo gmi = new GroupMemberInfo(); gmi.MemberUserID = user.UserID; gmi.MemberGroupID = group.GroupID; gmi.MemberJoined = DateTime.Now; gmi.MemberStatus = GroupMemberStatus.Approved; gmi.MemberApprovedWhen = DateTime.Now; gmi.MemberApprovedByUserID = user.UserID; // Save user as member of group GroupMemberInfoProvider.SetGroupMemberInfo(gmi); // Set user as member of admin group role UserRoleInfo userRole = new UserRoleInfo(); userRole.UserID = user.UserID; userRole.RoleID = roleInfo.RoleID; // Save user as member of admin group role UserRoleInfoProvider.SetUserRoleInfo(userRole); } // Clear user session a request CMSContext.CurrentUser.Invalidate(); CMSContext.CurrentUser = null; string culture = CultureHelper.EnglishCulture.ToString(); if (CMSContext.CurrentDocument != null) { culture = CMSContext.CurrentDocument.DocumentCulture; } // Copy document errorMessage = GroupInfoProvider.CopyGroupDocument(group, CMSContext.ResolveCurrentPath(GroupTemplateSourceAliasPath), CMSContext.ResolveCurrentPath(GroupTemplateTargetAliasPath), GroupProfileURLPath, culture, this.CombineWithDefaultCulture, CMSContext.CurrentUser, roleInfo); if (errorMessage != "") { // Display error message this.lblError.Text = errorMessage; this.lblError.Visible = true; return; } // Create group forum if (CreateForum) { CreateGroupForum(group); // Create group forum search index if (CreateSearchIndexes) { CreateGroupForumSearchIndex(group); } } // Create group media library if (CreateMediaLibrary) { CreateGroupMediaLibrary(group); } // Create search index for group documents if (CreateSearchIndexes) { CreateGroupContentSearchIndex(group); } // Display information on success this.lblInfo.Text = GetString("group.group.createdinfo"); this.lblInfo.Visible = true; // If URL is set, redirect user to specified page if (!String.IsNullOrEmpty(this.RedirectToURL)) { URLHelper.Redirect(ResolveUrl(CMSContext.GetUrl(this.RedirectToURL))); } // After registration message if ((this.RequireApproval) && (!CurrentUserIsAdmin())) { this.lblInfo.Text = this.SuccessfullRegistrationWaitingForApprovalText; // Send approval email to admin if (!String.IsNullOrEmpty(SendWaitingForApprovalEmailTo)) { // Create the message EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate("Groups.WaitingForApproval", CMSContext.CurrentSiteName); if (eti != null) { EmailMessage message = new EmailMessage(); if (String.IsNullOrEmpty(eti.TemplateFrom)) { message.From = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSSendEmailNotificationsFrom"); } else { message.From = eti.TemplateFrom; } MacroResolver resolver = CMSContext.CurrentResolver; resolver.SourceData = new object[] { group }; resolver.SetNamedSourceData("Group", group); message.Recipients = SendWaitingForApprovalEmailTo; message.Subject = resolver.ResolveMacros(eti.TemplateSubject); message.Body = resolver.ResolveMacros(eti.TemplateText); resolver.EncodeResolvedValues = false; message.PlainTextBody = resolver.ResolveMacros(eti.TemplatePlainText); // Send the message using email engine EmailSender.SendEmail(message); } } } else { string groupPath = SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSGroupProfilePath"); string url = String.Empty; if (!String.IsNullOrEmpty(groupPath)) { url = TreePathUtils.GetUrl(groupPath.Replace("{GroupName}", group.GroupName)); } this.lblInfo.Text = String.Format(this.SuccessfullRegistrationText, url); } // Hide form if (this.HideFormAfterRegistration) { this.plcForm.Visible = false; } else { ClearForm(); } } catch (Exception ex) { // Display error message this.lblError.Text = GetString("general.erroroccurred") + ex.Message; this.lblError.Visible = true; } } else { // Display error message this.lblError.Text = errorMessage; this.lblError.Visible = true; } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing subscriptionElem.StopProcessing = true; } else { // Build the actions string string actionsString = (CreateEventEnabled ? "|CREATEDOC" : "") + (DeleteEventEnabled ? "|DELETEDOC" : "") + (UpdateEventEnabled ? "|UPDATEDOC" : ""); actionsString = actionsString.TrimStart('|'); // Get the actions string[] actions = actionsString.Split(new char[] { '|' }); if (actions.Length > 0) { // Inititalize subscriptionElem control subscriptionElem.GatewayNames = GatewayNames; subscriptionElem.EventSource = "Content"; subscriptionElem.EventDescription = EventDescription; subscriptionElem.EventObjectID = 0; subscriptionElem.EventData1 = (String.IsNullOrEmpty(Path) ? "/%" : CMSContext.ResolveCurrentPath(Path)); subscriptionElem.EventData2 = DocumentTypes; subscriptionElem.SubscriptionUseHTML = SubscriptionUseHTML; // If "#current#" is set, then get current site ID if (SiteName == "#current#") { subscriptionElem.SubscriptionSiteID = CMSContext.CurrentSiteID; } // If "-" as global is not set, then try to find the site else if (SiteName != "-") { // Try to find given site SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteName); if (si != null) { subscriptionElem.SubscriptionSiteID = si.SiteID; } } // Initialize SubscriptionInfo objects NotificationSubscriptionInfo[] subscriptions = new NotificationSubscriptionInfo[actions.Length]; for (int i = 0; i < actions.Length; i++) { NotificationSubscriptionInfo nsi = new NotificationSubscriptionInfo(); nsi.SubscriptionEventCode = actions[i]; // Get correct template name and event display name string currentDisplayName = string.Empty; string currentTemplateName = string.Empty; switch (actions[i].ToLowerCSafe()) { case "createdoc": currentDisplayName = CreateEventDisplayName; currentTemplateName = CreateEventTemplateName; break; case "deletedoc": currentDisplayName = DeleteEventDisplayName; currentTemplateName = DeleteEventTemplateName; break; case "updatedoc": currentDisplayName = UpdateEventDisplayName; currentTemplateName = UpdateEventTemplateName; break; } // Get correct template NotificationTemplateInfo nti = GetTemplateInfo(currentTemplateName); if (nti != null) { nsi.SubscriptionTemplateID = nti.TemplateID; } if (String.IsNullOrEmpty(currentDisplayName)) { nsi.SubscriptionEventDisplayName = String.Format(GetString("notifications.contentsubscription.name"), (String.IsNullOrEmpty(Path) ? "/%" : Path), (String.IsNullOrEmpty(DocumentTypes) ? GetString("notifications.contentsubscription.alldoctypes") : DocumentTypes), actions[i]); } else { nsi.SubscriptionEventDisplayName = currentDisplayName; } subscriptions[i] = nsi; } subscriptionElem.Subscriptions = subscriptions; } } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { editForm.StopProcessing = true; editForm.Visible = false; } else { pnlEdit.Visible = false; CurrentUserInfo currentUser = CMSContext.CurrentUser; // Get the document TreeNode node = TreeHelper.GetDocument(SiteName, CMSContext.ResolveCurrentPath(Path), CultureCode, false, null, false, CheckPermissions, currentUser); if (node != null) { bool authorized = false; // Check user group switch (AllowUsers) { case UserContributionAllowUserEnum.All: authorized = true; break; case UserContributionAllowUserEnum.Authenticated: authorized = currentUser.IsAuthenticated(); break; case UserContributionAllowUserEnum.DocumentOwner: authorized = (node.NodeOwner == currentUser.UserID); break; } bool authorizedDelete = authorized; // Check control access permissions if (authorized && CheckPermissions) { // Node owner has always permissions if (node.NodeOwner != currentUser.UserID) { authorized &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Modify }) == AuthorizationResultEnum.Allowed); authorizedDelete &= (currentUser.IsAuthorizedPerDocument(node, new NodePermissionsEnum[] { NodePermissionsEnum.Read, NodePermissionsEnum.Delete }) == AuthorizationResultEnum.Allowed); } } else { authorized |= currentUser.IsGlobalAdministrator; authorizedDelete |= currentUser.IsGlobalAdministrator; } // Do not allow edit for virtual user if (currentUser.IsVirtual) { authorized = false; authorizedDelete = false; } // Display form if authorized if (authorized || authorizedDelete) { // Set visibility of the edit and delete buttons pnlEdit.Visible = true; btnEdit.Visible = btnEdit.Visible && authorized; btnDelete.Visible = btnDelete.Visible && AllowDelete && authorizedDelete; editForm.LogActivity = LogActivity; editForm.ComponentName = WebPartID; if (pnlForm.Visible) { editForm.StopProcessing = false; editForm.AllowDelete = AllowDelete; editForm.CheckPermissions = CheckPermissions; editForm.NodeID = node.NodeID; editForm.SiteName = SiteName; editForm.CultureCode = CultureCode; editForm.AlternativeFormName = AlternativeFormName; editForm.ValidationErrorMessage = ValidationErrorMessage; editForm.CMSForm.IsLiveSite = true; // Reload data editForm.ReloadData(false); } editForm.OnAfterApprove += editForm_OnAfterChange; editForm.OnAfterReject += editForm_OnAfterChange; editForm.OnAfterDelete += editForm_OnAfterChange; editForm.CMSForm.OnAfterSave += CMSForm_OnAfterSave; } } } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (this.StopProcessing) { // Do nothing } else { this.partPlaceholder.CheckPermissions = this.CheckPermissions; this.partPlaceholder.CacheMinutes = this.CacheMinutes; // Load content only when default page template or path is defined string templateName = this.PageTemplate; string path = this.Path; if ((templateName != "") || (path != "")) { ViewModeEnum viewMode = ViewModeEnum.Unknown; // Process template only if the control is on the last hierarchy page PageInfo currentPage = this.PagePlaceholder.PageInfo; PageInfo usePage = null; PageTemplateInfo ti = null; if (String.IsNullOrEmpty(path)) { // Use the same page usePage = this.PagePlaceholder.PageInfo; if (this.UseDefaultTemplateOnSubPages || (currentPage.ChildPageInfo == null) || (currentPage.ChildPageInfo.PageTemplateInfo == null) || (currentPage.ChildPageInfo.PageTemplateInfo.PageTemplateId == 0)) { ti = PageTemplateInfoProvider.GetPageTemplateInfo(templateName); } } else { // Resolve the path first path = CMSContext.ResolveCurrentPath(path); // Get specific page usePage = PageInfoProvider.GetPageInfo(CMSContext.CurrentSiteName, path, CMSContext.PreferredCultureCode, null, false); if (this.PortalManager.ViewMode != ViewModeEnum.LiveSite) { viewMode = ViewModeEnum.Preview; // Get current document content if (usePage != null) { TreeNode node = DocumentHelper.GetDocument(usePage.DocumentId, null); if (node != null) { usePage.LoadVersion(node); } } } // Get the appropriate page template if (String.IsNullOrEmpty(templateName)) { ti = usePage.PageTemplateInfo; } else { ti = PageTemplateInfoProvider.GetPageTemplateInfo(templateName); } } if ((usePage != null) && (ti != null)) { // If same template as current page, avoid cycling if (ti.PageTemplateId == currentPage.PageTemplateInfo.PageTemplateId) { this.lblError.Text = GetString("WebPart.PagePlaceHolder.CurrentTemplateNotAllowed"); this.lblError.Visible = true; } else { usePage = usePage.Clone(); usePage.DocumentPageTemplateID = ti.PageTemplateId; usePage.PageTemplateInfo = ti; // Load the current page info with the template and document if (viewMode != ViewModeEnum.Unknown) { this.partPlaceholder.ViewMode = viewMode; } this.partPlaceholder.UsingDefaultPageTemplate = true; this.partPlaceholder.PageLevel = this.PagePlaceholder.PageLevel; this.partPlaceholder.LoadContent(usePage, true); } } } } }
/// <summary> /// Gets URL from given path. /// </summary> /// <param name="path">Node alias path</param> private string GetUrl(string path) { return(ResolveUrl(TreePathUtils.GetUrl(CMSContext.ResolveCurrentPath(path)))); }
/// <summary> /// OK click handler (Proceed registration). /// </summary> private void btnRegister_Click(object sender, EventArgs e) { if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } // Check if captcha is required if (DisplayCaptcha) { // Verify captcha text if (!captchaElem.IsValid()) { // Display error message if captcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } else { // Generate new code and clear captcha textbox if cpatcha code is valid captchaElem.GenerateNew(); } } string userName = String.Empty; string nickName = String.Empty; string firstName = String.Empty; string lastName = String.Empty; string emailValue = String.Empty; // Check duplicate user // 1. Find appropriate control and get its value (i.e. user name) // 2. Try to find user info EditingFormControl txtUserName = formUser.BasicForm.FieldEditingControls["UserName"] as EditingFormControl; if (txtUserName != null) { userName = ValidationHelper.GetString(txtUserName.Value, String.Empty); } EditingFormControl txtEmail = formUser.BasicForm.FieldEditingControls["Email"] as EditingFormControl; if (txtEmail != null) { emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty); } // If user name and e-mail aren't filled stop processing and display error. if (string.IsNullOrEmpty(userName)) { userName = emailValue; if (String.IsNullOrEmpty(emailValue)) { formUser.StopProcessing = true; lblError.Visible = true; lblError.Text = GetString("customregistrationform.usernameandemail"); return; } else { formUser.BasicForm.Data.SetValue("UserName", userName); } } EditingFormControl txtNickName = formUser.BasicForm.FieldEditingControls["UserNickName"] as EditingFormControl; if (txtNickName != null) { nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty); } EditingFormControl txtFirstName = formUser.BasicForm.FieldEditingControls["FirstName"] as EditingFormControl; if (txtFirstName != null) { firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty); } EditingFormControl txtLastName = formUser.BasicForm.FieldEditingControls["LastName"] as EditingFormControl; if (txtLastName != null) { lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty); } // Test if "global" or "site" user exists. SiteInfo si = CMSContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si)); if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, userName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, nickName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName)); return; } // Check limitations for site members if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedSiteMember"); return; } // Check whether email is unique if it is required string checkSites = (String.IsNullOrEmpty(AssignToSites)) ? CMSContext.CurrentSiteName : AssignToSites; if (!UserInfoProvider.IsEmailUnique(emailValue, checkSites, 0)) { lblError.Visible = true; lblError.Text = GetString("UserInfo.EmailAlreadyExist"); return; } // Validate and save form with new user data if (!formUser.Save()) { // Return if saving failed return; } // Get user info from form UserInfo ui = (UserInfo)formUser.Info; // Add user prefix if settings is on // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(CMSContext.CurrentSiteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si); } ui.PreferredCultureCode = ""; ui.Enabled = EnableUserAfterRegistration; ui.IsEditor = false; ui.IsGlobalAdministrator = false; ui.UserURLReferrer = CMSContext.CurrentUser.URLReferrer; ui.UserCampaign = CMSContext.Campaign; // Fill optionally full user name if (String.IsNullOrEmpty(ui.FullName)) { ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName); } // Ensure nick name if (ui.UserNickName.Trim() == "") { ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true); } ui.UserSettings.UserRegistrationInfo.IPAddress = HTTPHelper.UserHostAddress; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; ui.UserSettings.UserLogActivities = true; ui.UserSettings.UserShowSplashScreen = true; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationAdministratorApproval"); if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is reqiures if (requiresAdminApprove) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(StartingAliasPath); } // Get user password and save it in apropriate format after form save string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty); UserInfoProvider.SetPassword(ui, password); // Prepare macro data source for email resolver UserInfo userForMail = ui.Clone(); userForMail.SetValue("UserPassword", string.Empty); object[] data = new object[1]; data[0] = userForMail; // Prepare resolver for notification and welcome emails ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceData = data; #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EventLogProvider ev = new EventLogProvider(); EmailTemplateInfo template = null; // Prepare macro replacements string[,] replacements = new string[6, 2]; replacements[0, 0] = "confirmaddress"; replacements[0, 1] = (ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(ApprovalPage) + "?userguid=" + ui.UserGUID : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx") + "?userguid=" + ui.UserGUID; replacements[1, 0] = "username"; replacements[1, 1] = userName; replacements[2, 0] = "password"; replacements[2, 1] = password; replacements[3, 0] = "Email"; replacements[3, 1] = emailValue; replacements[4, 0] = "FirstName"; replacements[4, 1] = firstName; replacements[5, 0] = "LastName"; replacements[5, 1] = lastName; // Set resolver resolver.SourceParameters = replacements; // Email message EmailMessage emailMessage = new EmailMessage(); emailMessage.EmailFormat = EmailFormatEnum.Default; emailMessage.Recipients = ui.Email; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject"); } // Send welcome message with username and password, with information that user must be approved by administrator else if (SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject"); } } if (template != null) { emailMessage.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress")); // Enable macro encoding for body resolver.EncodeResolvedValues = true; emailMessage.Body = resolver.ResolveMacros(template.TemplateText); // Disable macro encoding for plaintext body and subject resolver.EncodeResolvedValues = false; emailMessage.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject)); emailMessage.CcRecipients = template.TemplateCc; emailMessage.BccRecipients = template.TemplateBcc; try { MetaFileInfoProvider.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(CMSContext.CurrentSiteName, emailMessage, true); } catch (Exception ex) { ev.LogEvent("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { lblError.Visible = true; lblError.Text = GetString("RegistrationForm.UserWasNotCreated"); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and email confirmation is not required if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate = null; if (requiresAdminApprove) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", CMSContext.CurrentSiteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", CMSContext.CurrentSiteName); } if (mEmailTemplate == null) { ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri()); } //email template ok else { replacements = new string[4, 2]; replacements[0, 0] = "firstname"; replacements[0, 1] = ui.FirstName; replacements[1, 0] = "lastname"; replacements[1, 1] = ui.LastName; replacements[2, 0] = "email"; replacements[2, 1] = ui.Email; replacements[3, 0] = "username"; replacements[3, 1] = userName; // Set resolver resolver.SourceParameters = replacements; // Enable macro encoding for body resolver.EncodeResolvedValues = true; EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress); message.Recipients = ToAddress; message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText); // Disable macro encoding for plaintext body and subject resolver.EncodeResolvedValues = false; message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject"))); message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText); message.CcRecipients = mEmailTemplate.TemplateCc; message.BccRecipients = mEmailTemplate.TemplateBcc; try { // Attach template meta-files to e-mail MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); EmailSender.SendEmail(CMSContext.CurrentSiteName, message); } catch { ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID); } } } #endregion #region "Web analytics" // Track successful registration conversion if (TrackConversionName != String.Empty) { string siteName = CMSContext.CurrentSiteName; if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress)) { HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(CMSContext.CurrentSiteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables); if (activity.Data != null) { activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); activity.Log(); } // Log login activity if (ui.Enabled) { // Log activity int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); Activity activityLogin = new ActivityUserLogin(contactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables); activityLogin.Log(); } } #endregion #region "Site and roles addition and authentication" string[] roleList = AssignRoles.Split(';'); string[] siteList; // If AssignToSites field set if (!String.IsNullOrEmpty(AssignToSites)) { siteList = AssignToSites.Split(';'); } else // If not set user current site { siteList = new string[] { CMSContext.CurrentSiteName }; } foreach (string siteName in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, siteName); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String sn = roleName.StartsWithCSafe(".") ? "" : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, sn)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn); } } } } if (DisplayMessage.Trim() != String.Empty) { pnlRegForm.Visible = false; lblInfo.Visible = true; lblInfo.Text = DisplayMessage; } else { if (ui.Enabled) { CMSContext.AuthenticateUser(ui.UserName, true); } string returnUrl = QueryHelper.GetString("ReturnURL", ""); if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWithCSafe("~") || returnUrl.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash"))) { URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl)); } else if (RedirectToURL != String.Empty) { URLHelper.Redirect(RedirectToURL); } } #endregion lblError.Visible = false; } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { // Initialize properties string script = ""; // Set current user currentUser = CMSContext.CurrentUser; // Get Enable Friends setting bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(CMSContext.CurrentSiteName); // Initialize strings lnkSignIn.Text = SignInText; lnkJoinCommunity.Text = JoinCommunityText; lnkMyProfile.Text = MyProfileText; lnkEditMyProfile.Text = EditMyProfileText; btnSignOut.Text = SignOutText; lnkCreateNewGroup.Text = CreateNewGroupText; lnkCreateNewBlog.Text = CreateNewBlogText; lnkJoinGroup.Text = JoinGroupText; lnkLeaveGroup.Text = LeaveGroupText; lnkRejectFriendship.Text = RejectFriendshipText; requestFriendshipElem.LinkText = RequestFriendshipText; lnkSendMessage.Text = SendMessageText; lnkAddToContactList.Text = AddToContactListText; lnkAddToIgnoreList.Text = AddToIgnoreListText; lnkInviteToGroup.Text = InviteGroupText; lnkManageGroup.Text = ManageGroupText; lnkMyMessages.Text = MyMessagesText; lnkMyFriends.Text = MyFriendsText; lnkMyInvitations.Text = MyInvitationsText; lnkMyTasks.Text = MyTasksText; // If current user is public... if (currentUser.IsPublic()) { // Display Sign In link if set so if (DisplaySignIn) { // SignInPath returns URL - because of settings value lnkSignIn.NavigateUrl = CMSContext.ResolveCurrentPath(SignInPath); pnlSignIn.Visible = true; pnlSignInOut.Visible = true; } // Display Join the community link if set so if (DisplayJoinCommunity) { lnkJoinCommunity.NavigateUrl = GetUrl(JoinCommunityPath); pnlJoinCommunity.Visible = true; pnlPersonalLinks.Visible = true; } } // If user is logged in else { // Display Sign out link if set so if (DisplaySignOut && !RequestHelper.IsWindowsAuthentication()) { pnlSignOut.Visible = true; pnlSignInOut.Visible = true; } // Display Edit my profile link if set so if (DisplayEditMyProfileLink) { lnkEditMyProfile.NavigateUrl = URLHelper.ResolveUrl(TreePathUtils.GetUrl(GroupMemberInfoProvider.GetMemberManagementPath(currentUser.UserName, CMSContext.CurrentSiteName))); pnlEditMyProfile.Visible = true; pnlProfileLinks.Visible = true; } // Display My profile link if set so if (DisplayMyProfileLink) { lnkMyProfile.NavigateUrl = URLHelper.ResolveUrl(TreePathUtils.GetUrl(GroupMemberInfoProvider.GetMemberProfilePath(currentUser.UserName, CMSContext.CurrentSiteName))); pnlMyProfile.Visible = true; pnlProfileLinks.Visible = true; } // Display Create new group link if set so if (DisplayCreateNewGroup) { lnkCreateNewGroup.NavigateUrl = GetUrl(CreateNewGroupPath); pnlCreateNewGroup.Visible = true; pnlGroupLinks.Visible = true; } // Display Create new blog link if set so if (DisplayCreateNewBlog) { // Check that Community Module is present ModuleEntry entry = ModuleEntry.GetModuleEntry(ModuleEntry.BLOGS); if (entry != null) { lnkCreateNewBlog.NavigateUrl = GetUrl(CreateNewBlogPath); pnlCreateNewBlog.Visible = true; pnlBlogLinks.Visible = true; } } // Display My messages link if (DisplayMyMessages) { lnkMyMessages.NavigateUrl = GetUrl(MyMessagesPath); pnlMyMessages.Visible = true; pnlPersonalLinks.Visible = true; } // Display My friends link if (DisplayMyFriends && friendsEnabled) { lnkMyFriends.NavigateUrl = GetUrl(MyFriendsPath); pnlMyFriends.Visible = true; pnlPersonalLinks.Visible = true; } // Display My invitations link if (DisplayMyInvitations) { lnkMyInvitations.NavigateUrl = GetUrl(MyInvitationsPath); pnlMyInvitations.Visible = true; pnlPersonalLinks.Visible = true; } // Display My tasks link if (DisplayMyTasks) { lnkMyTasks.NavigateUrl = GetUrl(MyTasksPath); pnlMyTasks.Visible = true; pnlPersonalLinks.Visible = true; } GroupMemberInfo gmi = null; if (CommunityContext.CurrentGroup != null) { // Get group info from community context GroupInfo currentGroup = CommunityContext.CurrentGroup; if (DisplayGroupLinks) { script += "function ReloadPage(){" + ControlsHelper.GetPostBackEventReference(this, "") + "}"; // Display Join group link if set so and user is visiting a group page gmi = GetGroupMember(CMSContext.CurrentUser.UserID, currentGroup.GroupID); if (gmi == null) { if (String.IsNullOrEmpty(JoinGroupPath)) { script += "function JoinToGroupRequest() {\n" + "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/JoinTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestJoinToGroup', 500, 180); \n" + " } \n"; lnkJoinGroup.Attributes.Add("onclick", "JoinToGroupRequest();return false;"); lnkJoinGroup.NavigateUrl = URLHelper.CurrentURL; } else { lnkJoinGroup.NavigateUrl = GetUrl(JoinGroupPath); } pnlJoinGroup.Visible = true; pnlGroupLinks.Visible = true; } else if ((gmi.MemberStatus == GroupMemberStatus.Approved) || (CMSContext.CurrentUser.IsGlobalAdministrator)) // Display Leave the group link if user is the group member { if (String.IsNullOrEmpty(LeaveGroupPath)) { script += "function LeaveTheGroupRequest() {\n" + "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/LeaveTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestLeaveThGroup', 500, 180); \n" + " } \n"; lnkLeaveGroup.Attributes.Add("onclick", "LeaveTheGroupRequest();return false;"); lnkLeaveGroup.NavigateUrl = URLHelper.CurrentURL; } else { lnkLeaveGroup.NavigateUrl = GetUrl(LeaveGroupPath); } pnlLeaveGroup.Visible = true; pnlGroupLinks.Visible = true; } } // Display Manage the group link if set so and user is logged as group administrator and user is visiting a group page if (DisplayManageGroup && (currentUser.IsGroupAdministrator(currentGroup.GroupID) || (currentUser.IsGlobalAdministrator))) { lnkManageGroup.NavigateUrl = ResolveUrl(TreePathUtils.GetUrl(GroupInfoProvider.GetGroupManagementPath(currentGroup.GroupName, CMSContext.CurrentSiteName))); pnlManageGroup.Visible = true; pnlGroupLinks.Visible = true; } } if (DisplayInviteToGroup) { // Get group info from community context GroupInfo currentGroup = CommunityContext.CurrentGroup; // Get user info from site context UserInfo siteContextUser = SiteContext.CurrentUser; // Display invite to group link for user who is visiting a group page if (currentGroup != null) { // Get group user if (gmi == null) { gmi = GetGroupMember(CMSContext.CurrentUser.UserID, currentGroup.GroupID); } if (((gmi != null) && (gmi.MemberStatus == GroupMemberStatus.Approved)) || (CMSContext.CurrentUser.IsGlobalAdministrator)) { pnlInviteToGroup.Visible = true; if (String.IsNullOrEmpty(InviteGroupPath)) { script += "function InviteToGroup() {\n modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','inviteToGroup', 500, 345); \n } \n"; lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;"); lnkInviteToGroup.NavigateUrl = URLHelper.CurrentURL; } else { lnkInviteToGroup.NavigateUrl = GetUrl(InviteGroupPath); } } } // Display invite to group link for user who is visiting another user's page else if ((siteContextUser != null) && (siteContextUser.UserName != currentUser.UserName) && (GroupInfoProvider.GetUserGroupsCount(currentUser, CMSContext.CurrentSite) != 0)) { pnlInviteToGroup.Visible = true; if (String.IsNullOrEmpty(InviteGroupPath)) { script += "function InviteToGroup() {\n modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?invitedid=" + siteContextUser.UserID + "','inviteToGroup', 500, 310); \n } \n"; lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;"); lnkInviteToGroup.NavigateUrl = URLHelper.CurrentURL; } else { lnkInviteToGroup.NavigateUrl = GetUrl(InviteGroupPath); } } } if (SiteContext.CurrentUser != null) { // Get user info from site context UserInfo siteContextUser = SiteContext.CurrentUser; // Display Friendship link if set so and user is visiting an user's page if (DisplayFriendshipLinks && (currentUser.UserID != siteContextUser.UserID) && friendsEnabled) { FriendshipStatusEnum status = CMSContext.CurrentUser.HasFriend(siteContextUser.UserID); switch (status) { case FriendshipStatusEnum.Approved: // Friendship rejection script += "function ShortcutFriendshipReject(id) { \n" + "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Friends/CMSPages/Friends_Reject.aspx") + "?userid=" + currentUser.UserID + "&requestid=' + id , 'rejectFriend', 410, 270); \n" + " } \n"; lnkRejectFriendship.Attributes.Add("onclick", "ShortcutFriendshipReject('" + siteContextUser.UserID + "');return false;"); lnkRejectFriendship.NavigateUrl = URLHelper.CurrentURL; pnlRejectFriendship.Visible = true; pnlFriendshipLinks.Visible = true; break; case FriendshipStatusEnum.None: requestFriendshipElem.UserID = currentUser.UserID; requestFriendshipElem.RequestedUserID = siteContextUser.UserID; pnlFriendshipLink.Visible = true; pnlFriendshipLinks.Visible = true; break; } } // Show messaging links if enabled if (MessagingPresent && (currentUser.UserID != siteContextUser.UserID)) { // Display Send message link if user is visiting an user's page if (DisplaySendMessage) { // Send private message script += "function ShortcutPrivateMessage(id) { \n" + "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Messaging/CMSPages/SendMessage.aspx") + "?userid=" + currentUser.UserID + "&requestid=' + id , 'sendMessage', 390, 390); \n" + " } \n"; lnkSendMessage.Attributes.Add("onclick", "ShortcutPrivateMessage('" + siteContextUser.UserID + "');return false;"); lnkSendMessage.NavigateUrl = URLHelper.CurrentURL; pnlSendMessage.Visible = true; pnlMessageLinks.Visible = true; } // Display Add to contact list link if user is visiting an user's page if (DisplayAddToContactList) { // Check if user is in contact list bool isInContactList = ModuleCommands.MessagingIsInContactList(currentUser.UserID, siteContextUser.UserID); // Add to actions if (!isInContactList) { lnkAddToContactList.Attributes.Add("onclick", "return ShortcutAddToContactList('" + siteContextUser.UserID + "')"); lnkAddToContactList.NavigateUrl = URLHelper.CurrentURL; pnlAddToContactList.Visible = true; pnlMessageLinks.Visible = true; // Add to contact list script += "function ShortcutAddToContactList(usertoadd) { \n" + "var confirmation = confirm(" + ScriptHelper.GetString(GetString("messaging.contactlist.addconfirmation")) + ");" + "if(confirmation)" + "{" + "selectedIdElem = document.getElementById('" + hdnSelectedId.ClientID + "'); \n" + "if (selectedIdElem != null) { selectedIdElem.value = usertoadd;}" + ControlsHelper.GetPostBackEventReference(this, "addtocontactlist", false) + "} return false;}\n"; } } // Display Add to ignore list link if user is visiting an user's page if (DisplayAddToIgnoreList) { // Check if user is in ignore list bool isInIgnoreList = ModuleCommands.MessagingIsInIgnoreList(currentUser.UserID, siteContextUser.UserID); // Add to ignore list if (!isInIgnoreList) { lnkAddToIgnoreList.Attributes.Add("onclick", "return ShortcutAddToIgnoretList('" + siteContextUser.UserID + "')"); lnkAddToIgnoreList.NavigateUrl = URLHelper.CurrentURL; pnlAddToIgnoreList.Visible = true; pnlMessageLinks.Visible = true; // Add to ignore list script += "function ShortcutAddToIgnoretList(usertoadd) { \n" + "var confirmation = confirm(" + ScriptHelper.GetString(GetString("messaging.ignorelist.addconfirmation")) + ");" + "if(confirmation)" + "{" + "selectedIdElem = document.getElementById('" + hdnSelectedId.ClientID + "'); \n" + "if (selectedIdElem != null) { selectedIdElem.value = usertoadd;}" + ControlsHelper.GetPostBackEventReference(this, "addtoignorelist", false) + "} return false; } \n"; } } } } } // Register menu management scripts ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "Shortcuts_" + ClientID, ScriptHelper.GetScript(script)); // Register the dialog script ScriptHelper.RegisterDialogScript(Page); } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { SetContext(); GroupInfo group = CommunityContext.CurrentGroup; if (group != null) { string path = (GroupsSecurityAccessPath == "") ? GroupInfoProvider.GetGroupSecurityAccessPath(group.GroupName, CMSContext.CurrentSiteName) : GroupsSecurityAccessPath; string url = URLHelper.ResolveUrl(TreePathUtils.GetUrl(CMSContext.ResolveCurrentPath(path))); if (UseQueryString) { url = URLHelper.UpdateParameterInUrl(url, "groupid", group.GroupID.ToString()); } // Check whether group is approved if (!group.GroupApproved) { URLHelper.Redirect(url); } else { // Check permissions for current user switch (group.GroupAccess) { // Anybody can view the content default: case SecurityAccessEnum.AllUsers: break; // Site members can view the content case SecurityAccessEnum.AuthenticatedUsers: if (!CMSContext.CurrentUser.IsAuthenticated()) { URLHelper.Redirect(url); } break; // Only group members can view the content case SecurityAccessEnum.GroupMembers: if (!CMSContext.CurrentUser.IsGroupMember(group.GroupID)) { URLHelper.Redirect(url); } break; } } } else { Visible = false; } ReleaseContext(); } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { try { // Prepare alias path aliasPath = AliasPath; if (String.IsNullOrEmpty(aliasPath)) { aliasPath = "/%"; } aliasPath = CMSContext.ResolveCurrentPath(aliasPath); // Prepare site name siteName = SiteName; if (String.IsNullOrEmpty(siteName)) { siteName = CMSContext.CurrentSiteName; } // Prepare culture code cultureCode = CultureCode; if (String.IsNullOrEmpty(cultureCode)) { cultureCode = CMSContext.PreferredCultureCode; } string renderedTags = null; // Try to get data from cache using (CachedSection <string> cs = new CachedSection <string>(ref renderedTags, this.CacheMinutes, true, this.CacheItemName, "tagcloud", TagGroupName, OrderBy, SelectTopN, DocumentListPath, TagSeparator, QueryStringName, MaxTagSize, MinTagSize, "documents", siteName, aliasPath, CacheHelper.GetCultureCacheKey(cultureCode), CombineWithDefaultCulture, WhereCondition, SelectOnlyPublished, MaxRelativeLevel)) { if (cs.LoadData) { // Get the correct range int maxSize = Math.Max(MaxTagSize, MinTagSize); int minSize = Math.Min(MaxTagSize, MinTagSize); // Get the tags SiteInfo si = SiteInfoProvider.GetSiteInfo(siteName); int siteId = 0; if (si != null) { siteId = si.SiteID; } // Get tag group info tgi = TagGroupInfoProvider.GetTagGroupInfo(TagGroupName, siteId); // Get the data DataSet ds = null; if (!this.UseDocumentFilter) { // Get the tag group if (tgi != null) { // Get the tags for group ds = TagInfoProvider.GetTags("TagGroupID = " + tgi.TagGroupID, OrderBy, SelectTopN); } } else { // Get the tags for documents string comleteWhere = TreeProvider.GetCompleteWhereCondition(siteName, aliasPath, cultureCode, CombineWithDefaultCulture, WhereCondition, SelectOnlyPublished, MaxRelativeLevel); ds = TagInfoProvider.GetTags(TagGroupName, siteId, comleteWhere, OrderBy, SelectTopN); } // DS must have at least three columns (fist for IDs, second for names, third for counts) if (!DataHelper.DataSourceIsEmpty(ds)) { // First we need to find the maximum and minimum int max = Int32.MinValue; int min = Int32.MaxValue; foreach (DataRow dr in ds.Tables[0].Rows) { int tagCount = ValidationHelper.GetInteger(dr["TagCount"], 0); max = Math.Max(tagCount, max); min = Math.Min(tagCount, min); } // Base URL of the links string url; if (String.IsNullOrEmpty(DocumentListPath)) { url = URLHelper.CurrentURL; } else { url = CMSContext.GetUrl(CMSContext.ResolveCurrentPath(DocumentListPath)); } url = URLHelper.ResolveUrl(url); // Now generate the tags int count = ds.Tables[0].Rows.Count; StringBuilder sb = new StringBuilder(count * 100); int index = 0; // Process the tags foreach (DataRow dr in ds.Tables[0].Rows) { if (index > 0) { sb.Append(TagSeparator + "\n"); } // Count the percentage and get the final size of the tag int tagCount = ValidationHelper.GetInteger(dr["TagCount"], 0); int val = (min == max ? 100 : (((tagCount - min) * 100) / (max - min))); int pixelSize = minSize + ((val * (maxSize - minSize)) / 100); // Create the link with query string parameter string paramUrl = URLHelper.AddParameterToUrl(url, QueryStringName, ValidationHelper.GetString(dr["TagID"], "")); sb.Append("<span><a href=\"" + HTMLHelper.HTMLEncode(paramUrl) + "\" style=\"font-size:" + pixelSize.ToString() + "px;\" >" + HTMLHelper.HTMLEncode(dr["TagName"].ToString()) + "</a></span>"); index++; } renderedTags = sb.ToString(); } // Save to cache if (cs.Cached) { cs.CacheDependency = GetCacheDependency(); cs.Data = renderedTags; } } } if (String.IsNullOrEmpty(renderedTags)) { // Ensure no data behaviour if (HideControlForZeroRows) { Visible = false; } else { renderedTags = ZeroRowsText; } } // Display the tags ltlTags.Text = renderedTags; } catch (Exception ex) { // Display the error ltlTags.Text = "<div style=\"color: red\">" + ex.Message + "</div>"; } } }
protected void Page_Load(object sender, EventArgs e) { if (StopProcessing) { // Do nothing return; } gridElem.IsLiveSite = IsLiveSite; gridElem.OnExternalDataBound += gridElem_OnExternalDataBound; gridElem.HideControlForZeroRows = false; currentUserInfo = CMSContext.CurrentUser; // Initialize strings string strDays = GetString("MyDesk.OutdatedDocuments.Days"); string strWeeks = GetString("MyDesk.OutdatedDocuments.Weeks"); string strMonths = GetString("MyDesk.OutdatedDocuments.Months"); string strYears = GetString("MyDesk.OutdatedDocuments.Years"); // Set proper XML for control type switch (ListingType) { case ListingTypeEnum.CheckedOut: gridElem.ZeroRowsText = GetString("mydesk.ui.nochecked"); gridElem.WhereCondition = "View_CMS_Tree_Joined.DocumentCheckedOutByUserID = @UserID"; break; case ListingTypeEnum.MyDocuments: gridElem.ZeroRowsText = GetString("general.nodatafound"); gridElem.WhereCondition = "View_CMS_Tree_Joined.NodeOwner = @UserID"; break; case ListingTypeEnum.RecentDocuments: gridElem.ZeroRowsText = GetString("general.nodatafound"); gridElem.WhereCondition = "((View_CMS_Tree_Joined.DocumentCreatedByUserID = @UserID OR View_CMS_Tree_Joined.DocumentModifiedByUserID = @UserID OR View_CMS_Tree_Joined.DocumentCheckedOutByUserID = @UserID))"; break; case ListingTypeEnum.PendingDocuments: gridElem.ZeroRowsText = GetString("mydesk.ui.nowaitingdocs"); gridElem.WhereCondition = WorkflowStepInfoProvider.GetWorkflowPendingStepsWhereCondition(currentUserInfo, SiteName); break; case ListingTypeEnum.OutdatedDocuments: // Initialize controls if (!RequestHelper.IsPostBack()) { // Fill the dropdown list drpFilter.Items.Add(strDays); drpFilter.Items.Add(strWeeks); drpFilter.Items.Add(strMonths); drpFilter.Items.Add(strYears); // Load default value txtFilter.Text = "1"; drpFilter.SelectedValue = strYears; // Bind dropdown lists BindDropDowns(); } gridElem.WhereCondition = "((DocumentCreatedByUserID = @UserID OR DocumentModifiedByUserID = @UserID OR DocumentCheckedOutByUserID = @UserID) AND " + SOURCE_MODIFIEDWHEN + "<=@OlderThan AND " + SOURCE_NODESITEID + "=@SiteID)"; // Add where condition if (!string.IsNullOrEmpty(txtDocumentName.Text)) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, GetOutdatedWhereCondition(SOURCE_DOCUMENTNAME, drpDocumentName, txtDocumentName)); } if (!string.IsNullOrEmpty(txtDocumentType.Text)) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, GetOutdatedWhereCondition(SOURCE_CLASSDISPLAYNAME, drpDocumentType, txtDocumentType)); } gridElem.ZeroRowsText = GetString("mydesk.ui.nooutdated"); // Show custom filter plcOutdatedFilter.Visible = true; break; case ListingTypeEnum.WorkflowDocuments: break; case ListingTypeEnum.PageTemplateDocuments: gridElem.ZeroRowsText = GetString("Administration-PageTemplate_Header.Documents.nodata"); break; case ListingTypeEnum.CategoryDocuments: gridElem.ZeroRowsText = GetString("Category_Edit.Documents.nodata"); break; case ListingTypeEnum.ProductDocuments: break; case ListingTypeEnum.TagDocuments: gridElem.ZeroRowsText = GetString("taggroup_edit.documents.nodata"); break; case ListingTypeEnum.DocTypeDocuments: gridElem.ZeroRowsText = GetString("DocumentType_Edit_General.Documents.nodata"); break; case ListingTypeEnum.All: gridElem.ZeroRowsText = GetString("mydesk.ui.nodata"); break; } // Page Size if (!RequestHelper.IsPostBack() && !String.IsNullOrEmpty(ItemsPerPage)) { gridElem.Pager.DefaultPageSize = ValidationHelper.GetInteger(ItemsPerPage, -1); } // Order switch (ListingType) { case ListingTypeEnum.WorkflowDocuments: case ListingTypeEnum.OutdatedDocuments: case ListingTypeEnum.PageTemplateDocuments: case ListingTypeEnum.CategoryDocuments: case ListingTypeEnum.TagDocuments: case ListingTypeEnum.ProductDocuments: case ListingTypeEnum.DocTypeDocuments: gridElem.OrderBy = SOURCE_DOCUMENTNAME; break; default: gridElem.OrderBy = OrderBy; break; } if (ListingType == ListingTypeEnum.All) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, String.Format("(UserID1 = {0} OR UserID2 = {0} OR UserID3 = {0})", currentUserInfo.UserID)); } // Create query parameters QueryDataParameters parameters = new QueryDataParameters(); if (ListingType == ListingTypeEnum.OutdatedDocuments) { parameters.Add("@SiteID", CMSContext.CurrentSite.SiteID); DateTime olderThan = DateTime.Now; int dateTimeValue = ValidationHelper.GetInteger(txtFilter.Text, 0); if (drpFilter.SelectedValue == strDays) { olderThan = olderThan.AddDays(-dateTimeValue); } else if (drpFilter.SelectedValue == strWeeks) { olderThan = olderThan.AddDays(-dateTimeValue * 7); } else if (drpFilter.SelectedValue == strMonths) { olderThan = olderThan.AddMonths(-dateTimeValue); } else if (drpFilter.SelectedValue == strYears) { olderThan = olderThan.AddYears(-dateTimeValue); } parameters.Add("@OlderThan", olderThan); } // Initialize UserID query parameter int userID = currentUserInfo.UserID; if (ListingType == ListingTypeEnum.PendingDocuments) { parameters.Add("@SiteID", SiteInfoProvider.GetSiteID(SiteName)); if ((currentUserInfo.IsGlobalAdministrator) || (currentUserInfo.IsAuthorizedPerResource("CMS.Content", "manageworkflow"))) { userID = -1; } } parameters.Add("@UserID", userID); // Document Age if (DocumentAge != String.Empty) { string[] ages = DocumentAge.Split(';'); if (ages.Length == 2) { // Add from a to values to temp parameters int from = ValidationHelper.GetInteger(ages[1], 0); int to = ValidationHelper.GetInteger(ages[0], 0); if (from > 0) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_MODIFIEDWHEN + " >= @FROM"); parameters.Add("@FROM", DateTime.Now.AddDays((-1) * from)); } if (to > 0) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_MODIFIEDWHEN + " <= @TO"); parameters.Add("@TO", DateTime.Now.AddDays((-1) * to)); } } } // Site name if (!String.IsNullOrEmpty(SiteName) && (SiteName != UniGrid.ALL)) { SiteInfo site = SiteInfoProvider.GetSiteInfo(SiteName); if (site != null) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_NODESITEID + " = " + site.SiteID); UniGrid.GridColumns.Columns.RemoveAll(c => (c.Source == SOURCE_SITENAME || c.Source == SOURCE_NODESITEID)); } } // Path filter if (Path != String.Empty) { if (ListingType == ListingTypeEnum.All) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_DOCUMENTNAMEPATH + " LIKE N'" + CMSContext.ResolveCurrentPath(Path).Replace("'", "''") + "'"); } else { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_NODEALIASPATH + " LIKE N'" + CMSContext.ResolveCurrentPath(Path).Replace("'", "''") + "'"); } } // Document type filer if (!String.IsNullOrEmpty(DocumentType)) { string[] types = DocumentType.Split(';'); gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SqlHelperClass.GetWhereCondition <string>(SOURCE_CLASSNAME, types, true)); } // Document name filter if (DocumentName != String.Empty) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_DOCUMENTNAME + " LIKE N'%" + SqlHelperClass.GetSafeQueryString(DocumentName, false) + "%'"); } // Site running filter if ((SiteName == UniGrid.ALL) && DisplayOnlyRunningSites) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, "SiteName IN (SELECT SiteName FROM CMS_Site WHERE SiteStatus = 'RUNNING')"); } // Set parameters gridElem.QueryParameters = parameters; }
/// <summary> /// Perform search. /// </summary> protected void Search() { if (StopProcessing) { // Do nothing } else { // Get query strings string searchText = QueryHelper.GetString("searchtext", ""); bool searchTextIsNotEmptyOrRequired = (!SearchTextRequired || !String.IsNullOrEmpty(searchText)); bool searchAllowed = SearchOnEachPageLoad || QueryHelper.Contains("searchtext"); if ((searchTextIsNotEmptyOrRequired || !SearchHelper.SearchOnlyWhenContentPresent) && searchAllowed) { string searchMode = QueryHelper.GetString("searchMode", ""); SearchModeEnum searchModeEnum = CMS.ISearchEngine.SearchHelper.GetSearchModeEnum(searchMode); // Get current culture string culture = CultureCode; if (string.IsNullOrEmpty(culture)) { culture = ValidationHelper.GetString(ViewState["CultureCode"], CMSContext.PreferredCultureCode); } // Get default culture string defaultCulture = CultureHelper.GetDefaultCulture(CMSContext.CurrentSiteName); // Resolve path string path = Path; if (!string.IsNullOrEmpty(path)) { path = CMSContext.ResolveCurrentPath(Path); } if (CMSContext.ViewMode == ViewModeEnum.LiveSite) { // Log on site keywords if (AnalyticsHelper.JavascriptLoggingEnabled(CMSContext.CurrentSiteName)) { ScriptHelper.RegisterWebServiceCallFunction(Page); string script = "WebServiceCall('" + URLHelper.GetAbsoluteUrl("~/CMSPages/WebAnalyticsService.asmx") + "','LogSearch', '{\"keyword\":\"" + ScriptHelper.GetString(ScriptHelper.GetString(searchText, false), false) + "\"}')"; ScriptHelper.RegisterStartupScript(Page, typeof(string), "logSearch", script, true); } else { AnalyticsHelper.LogOnSiteSearchKeywords(CMSContext.CurrentSiteName, CMSContext.CurrentAliasPath, culture, searchText, 0, 1); } } // Prepare search text searchText = SearchHelper.CombineSearchCondition(searchText, SearchCondition + FilterSearchCondition, searchModeEnum, SearchOptions, DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture); // Get positions and ranges for search method int startPosition = 0; int numberOfProceeded = 100; int displayResults = 100; if (pgr.PageSize != 0 && pgr.GroupSize != 0) { startPosition = (pgr.CurrentPage - 1) * pgr.PageSize; numberOfProceeded = (((pgr.CurrentPage / pgr.GroupSize) + 1) * pgr.PageSize * pgr.GroupSize) + pgr.PageSize; displayResults = pgr.PageSize; } if ((MaxResults > 0) && (numberOfProceeded > MaxResults)) { numberOfProceeded = MaxResults; } // Combine regular search sort with filter sort string srt = ValidationHelper.GetString(SearchSort, String.Empty).Trim(); string filterSrt = ValidationHelper.GetString(FilterSearchSort, String.Empty).Trim(); if (!String.IsNullOrEmpty(filterSrt)) { if (!String.IsNullOrEmpty(srt)) { srt += ", "; } srt += filterSrt; } // Prepare parameters SearchParameters parameters = new SearchParameters() { SearchFor = searchText, SearchSort = SearchHelper.GetSort(srt), Path = path, ClassNames = DocumentTypes, CurrentCulture = culture, DefaultCulture = defaultCulture, CombineWithDefaultCulture = CombineWithDefaultCulture, CheckPermissions = CheckPermissions, SearchInAttachments = SearchInAttachments, User = (UserInfo)CMSContext.CurrentUser, SearchIndexes = Indexes, StartingPosition = startPosition, DisplayResults = displayResults, NumberOfProcessedResults = numberOfProceeded, NumberOfResults = 0, AttachmentWhere = AttachmentsWhere, AttachmentOrderBy = AttachmentsOrderBy, BlockFieldOnlySearch = BlockFieldOnlySearch, }; // Search DataSet results = SearchHelper.Search(parameters); int numberOfResults = parameters.NumberOfResults; if ((MaxResults > 0) && (numberOfResults > MaxResults)) { numberOfResults = MaxResults; } // Fill repeater with results repSearchResults.DataSource = results; repSearchResults.PagerForceNumberOfResults = numberOfResults; this.PagerForceNumberOfResults = numberOfResults; repSearchResults.DataBind(); // Call page binding event if (OnPageBinding != null) { OnPageBinding(this, null); } // Show now results found ? if (numberOfResults == 0) { if (ShowParsingErrors) { Exception searchError = SearchHelper.LastSmartSearchError; if (searchError != null) { ShowError(GetString("smartsearch.searcherror") + " " + searchError.Message); } } lblNoResults.Text = NoResultsText; lblNoResults.Visible = true; } } else { Visible = false; } // Invoke search completed event if (OnSearchCompleted != null) { OnSearchCompleted(Visible); } } }