/// <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 = MacroResolver.ResolveCurrentPath(aliasPath); // Prepare site name string siteName = SiteName; if (String.IsNullOrEmpty(siteName)) { siteName = SiteContext.CurrentSiteName; } // Prepare culture code string cultureCode = CultureCode; if (String.IsNullOrEmpty(cultureCode)) { cultureCode = LocalizationContext.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"), ID); 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; } }
private TreeNode GetDocument(UserInfo user) { var tree = new TreeProvider(user); var node = tree.SelectSingleNode(SiteName, MacroResolver.ResolveCurrentPath(Path), CultureCode, false, null, false, CheckPermissions); if ((node != null) && (PortalContext.ViewMode != ViewModeEnum.LiveSite)) { node = DocumentHelper.GetDocument(node, tree); } return(node); }
/// <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) && (DocumentContext.CurrentDocument != null)) { nodeAliasPath = DocumentContext.CurrentDocument.NodeAliasPath; } nodeIdFromPath = TreePathUtils.GetNodeIdByAliasPath(SiteName, MacroResolver.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(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(AdvancedSearchPath))); lnkAdvanceSearch.Visible = true; lnkAdvanceSearch.Text = GetString("ForumSearch.AdvanceSearch"); if (!RequestHelper.IsPostBack()) { txtSearch.Text = QueryHelper.GetString("searchtext", txtSearch.Text); } } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { newBlog.StopProcessing = true; } else { // Set new blog properties newBlog.BlogParentPath = MacroResolver.ResolveCurrentPath(BlogParentPath); newBlog.RedirectToNewBlog = RedirectToNewBlog; newBlog.BlogAllowAnonymousComments = BlogAllowAnonymousComments; newBlog.BlogModerateComments = BlogModerateComments; newBlog.BlogOpenCommentsFor = BlogOpenCommentsFor; newBlog.BlogSendCommentsToEmail = BlogSendCommentsToEmail; newBlog.BlogSideColumnText = BlogSideColumnText; newBlog.BlogTeaser = BlogTeaser; newBlog.BlogUseCAPTCHAForComments = BlogUseCAPTCHAForComments; newBlog.BlogModerators = BlogModerators; newBlog.NewBlogTemplate = NewBlogTemplate; newBlog.CheckPermissions = CheckPermissions; } }
private void SetupControl() { if (StopProcessing) { // Do nothing libraryElem.StopProcessing = true; } else { // Initialize document library control libraryElem.LibraryPath = MacroResolver.ResolveCurrentPath(LibraryPath); libraryElem.CombineWithDefaultCulture = CombineWithDefaultCulture; libraryElem.PageSize = PageSize; libraryElem.OrderBy = OrderBy; libraryElem.DocumentForm = DocumentForm; libraryElem.CacheDependencies = CacheDependencies; libraryElem.CacheItemName = CacheItemName; libraryElem.CacheMinutes = CacheMinutes; libraryElem.ZeroRowsText = ZeroRowsText; libraryElem.CheckPermissions = CheckPermissions; libraryElem.ComponentName = WebPartID; } }
/// <summary> /// Initializes control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { if (string.IsNullOrEmpty(Path)) { Path = DocumentContext.CurrentAliasPath; } srcAttach.Path = TreePathUtils.EnsureSingleNodePath(MacroResolver.ResolveCurrentPath(Path)); srcAttach.OrderBy = OrderBy; srcAttach.TopN = SelectTopN; srcAttach.WhereCondition = WhereCondition; srcAttach.SelectedColumns = Columns; srcAttach.FilterName = ValidationHelper.GetString(GetValue("WebPartControlID"), ID); srcAttach.SourceFilterName = FilterName; srcAttach.GetBinary = false; srcAttach.AttachmentGroupGUID = AttachmentGroupGUID; if (string.IsNullOrEmpty(CultureCode)) { srcAttach.CultureCode = DocumentContext.CurrentDocumentCulture.CultureCode; } else { srcAttach.CultureCode = CultureCode; } srcAttach.CombineWithDefaultCulture = CombineWithDefaultCulture; srcAttach.CheckPermissions = CheckPermissions; srcAttach.CacheItemName = CacheItemName; srcAttach.CacheMinutes = CacheMinutes; srcAttach.CacheDependencies = CacheDependencies; srcAttach.LoadPagesIndividually = LoadPagesIndividually; } }
/// <summary> /// Setups grid where condition to filter out by given restrictions. /// </summary> private void SetupGridFilterWhereCondition() { string where = String.Empty; // Set proper base where condition switch (ListingType) { case ListingTypeEnum.CheckedOut: where = "DocumentCheckedOutByUserID = @UserID"; break; case ListingTypeEnum.MyDocuments: where = "NodeOwner = @UserID"; break; case ListingTypeEnum.RecentDocuments: where = "((DocumentCreatedByUserID = @UserID OR DocumentModifiedByUserID = @UserID OR DocumentCheckedOutByUserID = @UserID))"; break; case ListingTypeEnum.PendingDocuments: where = "DocumentWorkflowStepID IN (SELECT StepID FROM CMS_WorkflowStep WHERE " + WorkflowStepInfoProvider.GetWorkflowPendingStepsWhereCondition(currentUserInfo, new SiteInfoIdentifier(SiteName)).ToString(false) + ")"; break; case ListingTypeEnum.OutdatedDocuments: where = "DocumentCreatedByUserID = @UserID OR DocumentModifiedByUserID = @UserID OR DocumentCheckedOutByUserID = @UserID"; break; case ListingTypeEnum.All: where = String.Format("(UserID1 = {0} OR UserID2 = {0} OR UserID3 = {0})", currentUserInfo.UserID); break; } gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, where); // Selected site filter if (!String.IsNullOrEmpty(SiteName) && (SiteName != UniGrid.ALL)) { selectedSiteInfo = SiteInfoProvider.GetSiteInfo(SiteName); if (selectedSiteInfo != null) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, SOURCE_NODESITEID + " = " + selectedSiteInfo.SiteID); } } // Site running filter if ((SiteName == UniGrid.ALL) && DisplayOnlyRunningSites) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, "NodeSiteID IN (SELECT SiteID FROM CMS_Site WHERE SiteStatus = 'RUNNING')"); } // Path filter if (Path != String.Empty) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, ((ListingType == ListingTypeEnum.All) ? SOURCE_DOCUMENTNAMEPATH : SOURCE_NODEALIASPATH) + " LIKE N'" + SqlHelper.EscapeQuotes(MacroResolver.ResolveCurrentPath(Path)) + "'"); } // Document type filer if (!String.IsNullOrEmpty(DocumentType)) { string classNames = DocumentTypeHelper.GetClassNames(DocumentType); gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, SqlHelper.GetWhereCondition <string>(SOURCE_CLASSNAME, classNames.Split(';'), true)); } // Document name filter if (DocumentName != String.Empty) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, SOURCE_DOCUMENTNAME + " LIKE N'%" + SqlHelper.EscapeLikeText(SqlHelper.EscapeQuotes(DocumentName)) + "%'"); } }
/// <summary> /// Perform search. /// </summary> protected void Search() { if (StopProcessing) { // Do nothing } else { // Check if the search was triggered bool searchAllowed = SearchOnEachPageLoad || QueryHelper.Contains("searchtext"); // Get query strings string searchText = QueryHelper.GetString("searchtext", ""); // Check whether string passes text requirements settings bool searchTextIsNotEmptyOrNotRequired = (!SearchTextRequired || !String.IsNullOrEmpty(searchText)); // Proceed when search was triggered and search text is passing requirements settings. // Requirements setting could be overriden on this level by obsolete web.config key. The reason is backward compatibility. // Search text required web part setting was introduced after this web.config key. Key default value was at the time set to true. // This default value had the same effect as this new web part setting. When somenone changed the web.config key to false and then upgraded the solution, // required wep part setting with default value true would override previous behaviour. That's the reason why this obsolete key can override this setting. if (searchAllowed && (searchTextIsNotEmptyOrNotRequired || !SearchHelper.SearchOnlyWhenContentPresent)) { string searchMode = QueryHelper.GetString("searchMode", ""); SearchModeEnum searchModeEnum = searchMode.ToEnum <SearchModeEnum>(); // Get current culture string culture = CultureCode; if (string.IsNullOrEmpty(culture)) { culture = ValidationHelper.GetString(ViewState["CultureCode"], LocalizationContext.PreferredCultureCode); } // Get default culture string defaultCulture = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName); // Resolve path string path = Path; if (!string.IsNullOrEmpty(path)) { path = MacroResolver.ResolveCurrentPath(Path); } if (PortalContext.ViewMode.IsLiveSite()) { if (AnalyticsHelper.JavascriptLoggingEnabled(SiteContext.CurrentSiteName)) { ScriptHelper.RegisterWebServiceCallFunction(Page); string script = "WebServiceCall('" + URLHelper.GetAbsoluteUrl("~/CMSPages/WebAnalyticsService.asmx") + "','LogSearch', '{\"keyword\":" + // Serialize raw search text to encode '<' and similar characters, then escape '\' new JavaScriptSerializer().Serialize(searchText).Replace(@"\", @"\\") + ", \"pageGUID\":\"" + DocumentContext.CurrentPageInfo.DocumentGUID + "\"}')"; ScriptHelper.RegisterStartupScript(Page, typeof(string), "logSearch", script, true); } else { // Log on site keywords AnalyticsHelper.LogOnSiteSearchKeywords(SiteContext.CurrentSiteName, DocumentContext.CurrentAliasPath, culture, searchText, 0, 1); } } // Prepare search text var docCondition = new DocumentSearchCondition(DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture); var searchCond = SearchCondition; if (!string.IsNullOrEmpty(FilterSearchCondition) && (searchModeEnum == SearchModeEnum.AnyWordOrSynonyms)) { // Make sure the synonyms are expanded before the filter condition is applied (filter condition is Lucene syntax, cannot be expanded) searchCond = SearchSyntaxHelper.ExpandWithSynonyms(searchCond, docCondition.Culture); searchModeEnum = SearchModeEnum.AnyWord; } var condition = new SearchCondition(searchCond + FilterSearchCondition, searchModeEnum, SearchOptions, docCondition, DoFuzzySearch); searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition); // Get positions and ranges for search method int startPosition = 0; int numberOfProceeded = 100; int displayResults = 100; if (pgr.PageSize != 0 && pgr.GroupSize != 0) { // Reset pager if needed if (mResetPager) { pgr.CurrentPage = 1; } startPosition = (pgr.CurrentPage - 1) * pgr.PageSize; // Only results covered by current page group are proccessed (filtered) for performance reasons. This may cause decrease of the number of results while paging. 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 = srt, Path = path, ClassNames = DocumentTypes, CurrentCulture = culture, DefaultCulture = defaultCulture, CombineWithDefaultCulture = CombineWithDefaultCulture, CheckPermissions = CheckPermissions, SearchInAttachments = SearchInAttachments, User = MembershipContext.AuthenticatedUser, 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; 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 = SearchContext.LastError; if (searchError != null) { ShowError(GetString("smartsearch.searcherror") + " " + searchError.Message); } } lblNoResults.Text = NoResultsText; lblNoResults.Visible = true; } } else { if (!String.IsNullOrEmpty(SearchTextValidationFailedText) && searchAllowed) { pnlSearchResults.AddCssClass(SearchTextValidationFailedCssClass); lblNoResults.Text = SearchTextValidationFailedText; lblNoResults.Visible = true; } else { Visible = false; } } // Invoke search completed event if (OnSearchCompleted != null) { OnSearchCompleted(Visible); } } }
/// <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) ? "/%" : MacroResolver.ResolveCurrentPath(Path)); subscriptionElem.EventData2 = DocumentTypes; subscriptionElem.SubscriptionUseHTML = SubscriptionUseHTML; // If "#current#" is set, then get current site ID if (SiteName == "#current#") { subscriptionElem.SubscriptionSiteID = SiteContext.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 = TextHelper.LimitLength(String.Format(GetString("notifications.contentsubscription.name"), (String.IsNullOrEmpty(Path) ? "/%" : Path), (String.IsNullOrEmpty(DocumentTypes) ? GetString("notifications.contentsubscription.alldoctypes") : DocumentTypes), actions[i]), 250, wholeWords: true, cutLocation: CutTextEnum.Middle); } else { nsi.SubscriptionEventDisplayName = currentDisplayName; } subscriptions[i] = nsi; } subscriptionElem.Subscriptions = subscriptions; } } }
/// <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, SiteContext.CurrentSiteName) : GroupsSecurityAccessPath; string url = URLHelper.ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.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 (!AuthenticationHelper.IsAuthenticated()) { URLHelper.Redirect(url); } break; // Only group members can view the content case SecurityAccessEnum.GroupMembers: if (!MembershipContext.AuthenticatedUser.IsGroupMember(group.GroupID)) { URLHelper.Redirect(url); } break; } } } else { Visible = false; } ReleaseContext(); } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { editForm.StopProcessing = true; editForm.Visible = false; } else { pnlEdit.Visible = false; var currentUser = MembershipContext.AuthenticatedUser; // Get the document TreeNode node = TreeHelper.GetDocument(SiteName, MacroResolver.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 = AuthenticationHelper.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 control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing ucDataSource.StopProcessing = true; } else { ucRepeater.DataBindByDefault = false; ucPager.PageControl = ucRepeater.ID; ucDataSource.GetBinary = false; // Basic control properties ucRepeater.HideControlForZeroRows = HideControlForZeroRows; ucRepeater.ZeroRowsText = ZeroRowsText; // Data source properties ucDataSource.WhereCondition = WhereCondition; ucDataSource.OrderBy = OrderBy; ucDataSource.FilterName = FilterName; ucDataSource.CacheItemName = CacheItemName; ucDataSource.CacheDependencies = CacheDependencies; ucDataSource.CacheMinutes = CacheMinutes; ucDataSource.AttachmentGroupGUID = AttachmentGroupGUID; ucDataSource.CheckPermissions = CheckPermissions; ucDataSource.CombineWithDefaultCulture = CombineWithDefaultCulture; if (string.IsNullOrEmpty(CultureCode)) { ucDataSource.CultureCode = DocumentContext.CurrentDocumentCulture.CultureCode; } else { ucDataSource.CultureCode = CultureCode; } ucDataSource.Path = TreePathUtils.EnsureSingleNodePath(MacroResolver.ResolveCurrentPath(Path)); ucDataSource.SiteName = SiteName; ucDataSource.TopN = TopN; // UniPager properties ucPager.PageSize = PageSize; ucPager.GroupSize = GroupSize; ucPager.QueryStringKey = QueryStringKey; ucPager.DisplayFirstLastAutomatically = DisplayFirstLastAutomatically; ucPager.DisplayPreviousNextAutomatically = DisplayPreviousNextAutomatically; ucPager.HidePagerForSinglePage = HidePagerForSinglePage; switch (PagingMode.ToLowerCSafe()) { case "postback": ucPager.PagerMode = UniPagerMode.PostBack; break; default: ucPager.PagerMode = UniPagerMode.Querystring; break; } // Effect properties ucRepeater.ItemHTMLBefore = ItemHTMLBefore; ucRepeater.ItemHTMLAfter = ItemHTMLAfter; ucRepeater.ItemHTMLSeparator = ItemHTMLSeparator; ucRepeater.HideLayoutForZeroRows = HideLayoutForZeroRows; ucRepeater.ScriptFiles = ScriptFiles; ucRepeater.InitScript = InitScript; ucRepeater.CSSFiles = CSSFiles; ucRepeater.InlineCSS = InlineCSS; // Setup repeater and pager templates SetupTemplates(); } }
/// <summary> /// Gets parent node ID. /// </summary> private TreeNode GetParentNode() { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); return(tree.SelectSingleNode(SiteName, MacroResolver.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)) && !AuthenticationHelper.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(MembershipContext.AuthenticatedUser); // Generate additional where condition WhereCondition condition = new WhereCondition(WhereCondition); if (!String.IsNullOrEmpty(ClassNames)) { condition.WhereIn("ClassName", ClassNames.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)); } // Add user condition if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner) { condition.WhereEquals("NodeOwner", MembershipContext.AuthenticatedUser.UserID); } // Get the documents var query = DocumentHelper.GetDocuments() .OnSite(SiteName) .Path(MacroResolver.ResolveCurrentPath(Path)) .Where(condition) .OrderBy(OrderBy) .Published(SelectOnlyPublished) .NestingLevel(MaxRelativeLevel) .CheckPermissions(CheckPermissions); TreeProvider.SetQueryCultures(query, CultureCode, CombineWithDefaultCulture); // Do not apply published from / to columns to make sure the published information is correctly evaluated query.Properties.ExcludedVersionedColumns = new[] { "DocumentPublishFrom", "DocumentPublishTo" }; var ds = query.Result; 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 || MembershipContext.AuthenticatedUser.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 = MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(ParentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed; } if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner) { if (VirtualContext.ReadonlyMode) { isAuthorizedToCreateDoc = false; } else { // Check if user is document owner (or global admin) isAuthorizedToCreateDoc = isAuthorizedToCreateDoc && ((ParentNode.NodeOwner == MembershipContext.AuthenticatedUser.UserID) || MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin)); } } } // 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> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { editForm.StopProcessing = true; editForm.Visible = false; } else { pnlEdit.Visible = false; var currentUser = MembershipContext.AuthenticatedUser; // Get the document TreeNode node = TreeHelper.GetDocument(SiteName, MacroResolver.ResolveCurrentPath(Path), CultureCode, false, null, false, CheckPermissions, currentUser); if (node != null) { bool authorized = false; // Check allowed users switch (AllowUsers) { case UserContributionAllowUserEnum.All: authorized = true; break; case UserContributionAllowUserEnum.Authenticated: authorized = AuthenticationHelper.IsAuthenticated(); break; case UserContributionAllowUserEnum.DocumentOwner: authorized = (node.NodeOwner == currentUser.UserID); break; } bool authorizedDelete = authorized; // Check control access permission if (authorized && 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) { pnlEdit.Visible = true; // Set visibility of edit and delete buttons btnEdit.Visible = btnEdit.Visible && authorized; btnDelete.Visible = btnDelete.Visible && AllowDelete && authorizedDelete; if ((!RequestHelper.IsPostBack()) && ((btnEdit.Text.Trim() == string.Empty) || (btnDelete.Text.Trim() == string.Empty))) { // Initialize labels and css classes btnEdit.ResourceString = EditButtonText; btnEdit.CssClass = "EditContributionEdit"; btnDelete.ResourceString = DeleteButtonText; btnDelete.CssClass = "EditContributionDelete"; } editForm.ComponentName = WebPartID; editForm.LogActivity = LogActivity; if (pnlForm.Visible) { editForm.StopProcessing = false; editForm.AllowDelete = AllowDelete && CheckGroupPermission("deletepages"); editForm.CheckPermissions = CheckPermissions; editForm.NodeID = node.NodeID; editForm.SiteName = SiteName; editForm.CultureCode = CultureCode; editForm.AlternativeFormName = AlternativeFormName; editForm.ValidationErrorMessage = ValidationErrorMessage; editForm.CMSForm.IsLiveSite = true; editForm.OnAfterApprove += editForm_OnAfterChange; editForm.OnAfterReject += editForm_OnAfterChange; editForm.OnAfterDelete += editForm_OnAfterChange; editForm.CMSForm.OnAfterSave += CMSForm_OnAfterSave; // Reload data editForm.ReloadData(false); } } } } }
/// <summary> /// OK click handler (Proceed registration). /// </summary> private void btnRegister_Click(object sender, EventArgs e) { string currentSiteName = SiteContext.CurrentSiteName; string[] siteList = { currentSiteName }; // If AssignToSites field set if (!String.IsNullOrEmpty(AssignToSites)) { siteList = AssignToSites.Split(';'); } if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(currentSiteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } // Check if captcha is required and verify captcha text if (DisplayCaptcha && !captchaElem.IsValid()) { // Display error message if captcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } string userName = String.Empty; string nickName = String.Empty; string firstName = String.Empty; string lastName = String.Empty; string emailValue = String.Empty; string pwd = string.Empty; string confPassword = string.Empty; string educationLevel = String.Empty; string interestArea = String.Empty; string industry = String.Empty; string referralSource = string.Empty; // Check duplicate user // 1. Find appropriate control and get its value (i.e. user name) // 2. Try to find user info //FormEngineUserControl txtUserName = formUser.FieldControls["UserName"]; //if (txtUserName != null) //{ // userName = ValidationHelper.GetString(txtUserName.Value, String.Empty); //} FormEngineUserControl txtEmail = formUser.FieldControls["Email"]; if (txtEmail != null) { emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty); userName = emailValue; } // If user name and e-mail aren't filled stop processing and display error. if (string.IsNullOrEmpty(userName) && String.IsNullOrEmpty(emailValue)) { formUser.StopProcessing = true; lblError.Visible = true; lblError.Text = GetString("customregistrationform.usernameandemail"); return; } else { formUser.Data.SetValue("UserName", userName); } //check if email is valid if (!ValidationHelper.IsEmail(txtEmail.Text.ToLowerCSafe())) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"); return; } FormEngineUserControl txtNickName = formUser.FieldControls["UserNickName"]; if (txtNickName != null) { nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty); } FormEngineUserControl txtFirstName = formUser.FieldControls["FirstName"]; if (txtFirstName != null) { firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty); } FormEngineUserControl txtLastName = formUser.FieldControls["LastName"]; if (txtLastName != null) { lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty); } FormEngineUserControl txtPwd = formUser.FieldControls["UserPassword"]; if (txtPwd != null) { pwd = ValidationHelper.GetString(txtPwd.Value, String.Empty); } FormEngineUserControl txtConfPassword = formUser.FieldControls["ReenterPassword"]; if (txtConfPassword != null) { confPassword = ValidationHelper.GetString(txtConfPassword.Value, String.Empty); } if (string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(confPassword)) { lblError.Visible = true; lblError.Text = "please enter password with confirmation"; return; } if (pwd != confPassword) { lblError.Visible = true; lblError.Text = "Password doesn't match"; return; } if (validateFields(formUser.FieldControls["UserPassword"].Value.ToString())) { // Test if "global" or "site" user exists. SiteInfo si = SiteContext.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(currentSiteName, userName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } if (UserInfoProvider.NameIsReserved(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(RequestContext.CurrentDomain, FeatureEnum.SiteMembers, ObjectActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedSiteMember"); return; } // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(emailValue, siteList, 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(currentSiteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si); } ui.Enabled = EnableUserAfterRegistration; ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer; ui.UserCampaign = AnalyticsHelper.Campaign; ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None); // 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() == String.Empty) { ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true); } ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; ui.UserSettings.UserLogActivities = true; ui.UserSettings.UserShowIntroductionTile = true; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(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 = MacroResolver.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); var customerToken = PersonifyRegistered(emailValue, password, firstName, lastName); if (string.IsNullOrEmpty(customerToken)) { UserInfoProvider.DeleteUser(ui); return; } else { var roles = GetImsroles(customerToken); string groupslist = ""; if (roles.Length > 0) { foreach (string s in roles) { if (s.Length > 0) { groupslist += s + ","; } } } //we need this mispelling. groupslist += "peronifyUser" + ","; new LoginUsertokentico().AddUserToRole(ui, groupslist, true, false); } // 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 MacroResolver resolver = MacroContext.CurrentResolver; resolver.SetAnonymousSourceData(data); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EmailTemplateInfo template = null; // Prepare macro replacements string[,] replacements = new string[6, 2]; replacements[0, 0] = "confirmaddress"; replacements[0, 1] = AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, currentSiteName, NotifyAdministrator); 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.SetNamedSourceData(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", 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", currentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", currentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject"); } } if (template != null) { emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetStringValue(currentSiteName + ".CMSNoreplyEmailAddress")); // Enable macro encoding for body resolver.Settings.EncodeResolvedValues = true; emailMessage.Body = resolver.ResolveMacros(template.TemplateText); // Disable macro encoding for plaintext body and subject resolver.Settings.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 { EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(currentSiteName, emailMessage, true); } catch (Exception ex) { EventLogProvider.LogException("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", currentSiteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName); } if (mEmailTemplate == null) { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { // E-mail template ok 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.SetNamedSourceData(replacements); // Enable macro encoding for body resolver.Settings.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.Settings.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 EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); EmailSender.SendEmail(currentSiteName, message); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } #endregion #region "Web analytics" // Track successful registration conversion if (TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(currentSiteName) && AnalyticsHelper.TrackConversionsEnabled(currentSiteName) && !AnalyticsHelper.IsIPExcluded(currentSiteName, RequestContext.UserHostAddress)) { HitLogProvider.LogConversions(currentSiteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(currentSiteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.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, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables); activityLogin.Log(); } } #endregion #region "Site and roles addition and authentication" string[] roleList = AssignRoles.Split(';'); 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(".") ? String.Empty : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, sn)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn); } } } } if (ui.Enabled) { if (this.AutoLoginAfterRegistration) { Session["UserName"] = userName; Session["Password"] = password; Session["RememberMe"] = true; Session["RetryCount"] = null; if (this.Request.QueryString["ReturnURL"] != null) { var returnURL = this.Request.QueryString["ReturnURL"]; Session["ReturnURL"] = returnURL; } else if (!String.IsNullOrEmpty(this.RedirectToURL)) { var returnURL = this.Request.QueryString["ReturnURL"]; Session["ReturnURL"] = returnURL; } Response.Redirect("~/sso/ssohandler.aspx", true); } else if (!String.IsNullOrEmpty(this.LoginURL)) { Response.Redirect(string.Format(this.LoginURL, userName), true); } else if (!String.IsNullOrEmpty(this.RedirectToURL)) { Response.Redirect(this.RedirectToURL, true); } } #endregion lblError.Visible = false; } } }
private void ReloadData() { if (StopProcessing) { // Do nothing gridDocs.StopProcessing = true; editDoc.StopProcessing = true; } else { if (((AllowUsers == UserContributionAllowUserEnum.Authenticated) || (AllowUsers == UserContributionAllowUserEnum.DocumentOwner)) && !AuthenticationHelper.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(MembershipContext.AuthenticatedUser); // Generate additional where condition string classWhere = null; if (!String.IsNullOrEmpty(ClassNames)) { // Remove ending semicolon classWhere = ClassNames.TrimEnd(';'); // Replace single apostrophs classWhere = SqlHelper.GetSafeQueryString(classWhere, false); // Replace ; with ',' classWhere = classWhere.Replace(";", "','"); if (!String.IsNullOrEmpty(classWhere)) { classWhere = String.Format("ClassName IN ('{0}')", classWhere); } } string where = SqlHelper.AddWhereCondition(WhereCondition, classWhere); // Add user condition if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner) { where = SqlHelper.AddWhereCondition(where, "NodeOwner = " + MembershipContext.AuthenticatedUser.UserID); } // Ensure that required columns are included in "Columns" list string columns = EnsureColumns(); // Get the documents DataSet ds = DocumentHelper.GetDocuments(SiteName, MacroResolver.ResolveCurrentPath(Path), CultureCode, CombineWithDefaultCulture, null, where, OrderBy, MaxRelativeLevel, SelectOnlyPublished, 0, columns, tree); if (CheckPermissions) { ds = TreeSecurityProvider.FilterDataSetByPermissions(ds, NodePermissionsEnum.Read, MembershipContext.AuthenticatedUser); } 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 || MembershipContext.AuthenticatedUser.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 = MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(ParentNode, NodePermissionsEnum.Create) == AuthorizationResultEnum.Allowed; } if (AllowUsers == UserContributionAllowUserEnum.DocumentOwner) { // Do not allow documents creation under virtual user if (MembershipContext.AuthenticatedUser.IsVirtual) { isAuthorizedToCreateDoc = false; } else { // Check if user is document owner (or global admin) isAuthorizedToCreateDoc = isAuthorizedToCreateDoc && ((ParentNode.NodeOwner == MembershipContext.AuthenticatedUser.UserID) || MembershipContext.AuthenticatedUser.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(); } } }
void formUser_OnAfterSave(object sender, EventArgs e) { // Get user info from form UserInfo ui = (UserInfo)formUser.Data; // Add user prefix if settings is on // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(CurrentSiteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(ui.UserName, SiteContext.CurrentSite); } ui.Enabled = EnableUserAfterRegistration; ui.UserURLReferrer = MembershipContext.AuthenticatedUser.URLReferrer; ui.UserCampaign = Service <ICampaignService> .Entry().CampaignCode; ui.SetPrivilegeLevel(UserPrivilegeLevelEnum.None); // 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() == String.Empty) { ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true); } ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; ui.UserSettings.UserLogActivities = true; ui.UserSettings.UserShowIntroductionTile = true; // Check whether confirmation is required if (!ConfirmationRequired) { // If confirmation is not required check whether administration approval is required if (AdminApprovalRequired) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath); } // Get user password and save it in appropriate format after form save string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty); UserInfoProvider.SetPassword(ui, password); if (!ConfirmationRequired) { SendAdminNotification(ui); LogOMActivity(ui); } SendRegistrationEmail(ui, password); LogWebAnalytics(ui); AssignToRoles(ui); if (ui.Enabled) { AuthenticationHelper.AuthenticateUser(ui.UserName, true); } var displayMessage = DisplayMessage.Trim(); if (!String.IsNullOrEmpty(displayMessage)) { ShowInformation(displayMessage); } else { // Redirect after user registration, first try to use RedirectToURL property if (RedirectToURL != String.Empty) { URLHelper.Redirect(RedirectToURL); } // RedirectToURL property is not set, try to use ReturnURL query string string returnUrl = QueryHelper.GetString("ReturnURL", String.Empty); if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWithCSafe("~") || returnUrl.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash", "aliaspath"))) { URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl)); } } pnlRegForm.Visible = false; }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { partPlaceholder.CheckPermissions = CheckPermissions; partPlaceholder.CacheMinutes = CacheMinutes; // Load content only when default page template or path is defined string templateName = PageTemplate; string path = Path; if ((templateName != "") || (path != "")) { ViewModeEnum viewMode = ViewModeEnum.Unknown; // Process template only if the control is on the last hierarchy page PageInfo currentPage = PagePlaceholder.PageInfo; PageInfo usePage; PageTemplateInfo ti = null; if (String.IsNullOrEmpty(path)) { // Use the same page usePage = PagePlaceholder.PageInfo; if (UseDefaultTemplateOnSubPages || (currentPage.ChildPageInfo == null) || (currentPage.ChildPageInfo.UsedPageTemplateInfo == null) || (currentPage.ChildPageInfo.UsedPageTemplateInfo.PageTemplateId == 0)) { ti = PageTemplateInfoProvider.GetPageTemplateInfo(templateName); } } else { // Resolve the path first path = MacroResolver.ResolveCurrentPath(path); // Get specific page usePage = PageInfoProvider.GetPageInfo(SiteContext.CurrentSiteName, path, LocalizationContext.PreferredCultureCode, null, SiteContext.CurrentSite.CombineWithDefaultCulture); if (PortalManager.ViewMode != ViewModeEnum.LiveSite) { viewMode = ViewModeEnum.Preview; // Set design mode for document's placeholder if is currently displayed TreeNode tn = DocumentContext.CurrentDocument; if ((tn != null) && (PortalContext.ViewMode == ViewModeEnum.Design) && tn.NodeAliasPath.EqualsCSafe(path, true)) { viewMode = ViewModeEnum.Design; } // Get latest version data of current document content if (usePage != null) { usePage.LoadVersion(); } } // Get the appropriate page template if (String.IsNullOrEmpty(templateName)) { ti = (usePage != null) ? usePage.UsedPageTemplateInfo : null; } else { ti = PageTemplateInfoProvider.GetPageTemplateInfo(templateName); } } if ((usePage != null) && (ti != null)) { // If same template as current page, avoid cycling if (ti.PageTemplateId == currentPage.UsedPageTemplateInfo.PageTemplateId) { lblError.Text = GetString("WebPart.PagePlaceHolder.CurrentTemplateNotAllowed"); lblError.Visible = true; } else { usePage = usePage.Clone(); // Setup the page template int templateId = ti.PageTemplateId; usePage.SetPageTemplateId(templateId); usePage.UsedPageTemplateInfo = ti; // Load the current page info with the template and document if (viewMode != ViewModeEnum.Unknown) { partPlaceholder.ViewMode = viewMode; } partPlaceholder.UsingDefaultPageTemplate = !string.IsNullOrEmpty(templateName); partPlaceholder.UsingDefaultDocument = !string.IsNullOrEmpty(path); partPlaceholder.PageLevel = PagePlaceholder.PageLevel; partPlaceholder.LoadContent(usePage); } } } } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { rssFeed.StopProcessing = true; srcProducts.StopProcessing = true; } else { string feedCodeName = URLHelper.GetSafeUrlPart(FeedName, SiteName); // RSS feed properties rssFeed.FeedName = feedCodeName; rssFeed.FeedLink = URLHelper.GetAbsoluteUrl(URLHelper.AddParameterToUrl(RequestContext.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; // Datasource properties srcProducts.WhereCondition = WhereCondition; srcProducts.OrderBy = OrderBy; srcProducts.TopN = SelectTopN; srcProducts.SourceFilterName = FilterName; srcProducts.SelectedColumns = Columns; // Prepare alias path string aliasPath = Path; if (String.IsNullOrEmpty(aliasPath)) { aliasPath = "/%"; } aliasPath = MacroResolver.ResolveCurrentPath(aliasPath); // Prepare site name string siteName = SiteName; if (String.IsNullOrEmpty(siteName)) { siteName = SiteContext.CurrentSiteName; } // Prepare culture code string cultureCode = CultureCode; if (String.IsNullOrEmpty(cultureCode)) { cultureCode = LocalizationContext.PreferredCultureCode; } // Document filter properties srcProducts.SiteName = siteName; srcProducts.UseDocumentFilter = UseDocumentFilter; srcProducts.DocumentsWhereCondition = DocumentsWhereCondition; srcProducts.CombineWithDefaultCulture = CombineWithDefaultCulture; srcProducts.CultureCode = cultureCode; srcProducts.SelectOnlyPublished = SelectOnlyPublished; srcProducts.MaxRelativeLevel = MaxRelativeLevel; srcProducts.Path = aliasPath; // Cache properties rssFeed.CacheItemName = CacheItemName; rssFeed.CacheDependencies = CacheDependencies; rssFeed.CacheMinutes = CacheMinutes; srcProducts.CacheItemName = CacheItemName; srcProducts.CacheDependencies = CacheDependencies; srcProducts.CacheMinutes = CacheMinutes; // Transformation properties rssFeed.TransformationName = TransformationName; // Datasource properties rssFeed.DataSourceControl = srcProducts; } }
/// <summary> /// Initializes control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing ucAttachments.StopProcessing = true; } else { ucAttachments.GetBinary = false; // Basic control properties ucAttachments.HideControlForZeroRows = HideControlForZeroRows; ucAttachments.ZeroRowsText = ZeroRowsText; // Data source properties ucAttachments.WhereCondition = WhereCondition; ucAttachments.OrderBy = OrderBy; ucAttachments.FilterName = FilterName; ucAttachments.CacheItemName = CacheItemName; ucAttachments.CacheDependencies = CacheDependencies; ucAttachments.CacheMinutes = CacheMinutes; ucAttachments.AttachmentGroupGUID = AttachmentGroupGUID; ucAttachments.CheckPermissions = CheckPermissions; ucAttachments.CombineWithDefaultCulture = CombineWithDefaultCulture; if (string.IsNullOrEmpty(CultureCode)) { ucAttachments.CultureCode = DocumentContext.CurrentDocumentCulture.CultureCode; } else { ucAttachments.CultureCode = CultureCode; } ucAttachments.Path = TreePathUtils.EnsureSingleNodePath(MacroResolver.ResolveCurrentPath(Path)); ucAttachments.SiteName = SiteName; ucAttachments.TopN = TopN; #region "Repeater template properties" // Apply transformations if they exist ucAttachments.TransformationName = TransformationName; ucAttachments.AlternatingItemTransformationName = AlternatingItemTransformationName; ucAttachments.FooterTransformationName = FooterTransformationName; ucAttachments.HeaderTransformationName = HeaderTransformationName; ucAttachments.SeparatorTransformationName = SeparatorTransformationName; #endregion // UniPager properties ucAttachments.PageSize = PageSize; ucAttachments.GroupSize = GroupSize; ucAttachments.QueryStringKey = QueryStringKey; ucAttachments.DisplayFirstLastAutomatically = DisplayFirstLastAutomatically; ucAttachments.DisplayPreviousNextAutomatically = DisplayPreviousNextAutomatically; ucAttachments.HidePagerForSinglePage = HidePagerForSinglePage; switch (PagingMode.ToLowerCSafe()) { case "postback": ucAttachments.PagingMode = UniPagerMode.PostBack; break; default: ucAttachments.PagingMode = UniPagerMode.Querystring; break; } #region "UniPager template properties" // UniPager template properties ucAttachments.PagesTemplate = PagesTemplate; ucAttachments.CurrentPageTemplate = CurrentPageTemplate; ucAttachments.SeparatorTemplate = SeparatorTemplate; ucAttachments.FirstPageTemplate = FirstPageTemplate; ucAttachments.LastPageTemplate = LastPageTemplate; ucAttachments.PreviousPageTemplate = PreviousPageTemplate; ucAttachments.NextPageTemplate = NextPageTemplate; ucAttachments.PreviousGroupTemplate = PreviousGroupTemplate; ucAttachments.NextGroupTemplate = NextGroupTemplate; ucAttachments.LayoutTemplate = LayoutTemplate; #endregion } }
/// <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 = MacroResolver.ResolveCurrentPath(aliasPath); // Prepare site name siteName = SiteName; if (String.IsNullOrEmpty(siteName)) { siteName = SiteContext.CurrentSiteName; } // Prepare culture code cultureCode = CultureCode; if (String.IsNullOrEmpty(cultureCode)) { cultureCode = LocalizationContext.PreferredCultureCode; } // Base URL of the links string url; if (String.IsNullOrEmpty(DocumentListPath)) { url = RequestContext.CurrentURL; } else { url = DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(DocumentListPath)); } url = UrlResolver.ResolveUrl(url); string renderedTags = null; // Try to get data from cache using (var cs = new CachedSection <string>(ref renderedTags, CacheMinutes, true, CacheItemName, "tagcloud", TagGroupName, OrderBy, SelectTopN, url, 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 (!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); } // 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 behavior 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>"; } } }
/// <summary> /// Perform search. /// </summary> protected void Search() { if (StopProcessing) { // Do nothing } else { // Check if the search was triggered bool searchAllowed = SearchOnEachPageLoad || QueryHelper.Contains("searchtext"); // Get query strings string searchText = QueryHelper.GetString("searchtext", ""); // Check whether string passes text requirements settings bool searchTextIsNotEmptyOrNotRequired = (!SearchTextRequired || !String.IsNullOrEmpty(searchText)); // Proceed when search was triggered and search text is passing requirements settings. // Requirements setting could be overridden on this level by obsolete web.config key. The reason is backward compatibility. // Search text required web part setting was introduced after this web.config key. Key default value was at the time set to true. // This default value had the same effect as this new web part setting. When someone changed the web.config key to false and then upgraded the solution, // required web part setting with default value true would override previous behavior. That's the reason why this obsolete key can override this setting. if (searchAllowed && (searchTextIsNotEmptyOrNotRequired || !SearchHelper.SearchOnlyWhenContentPresent)) { string searchMode = QueryHelper.GetString("searchMode", ""); SearchModeEnum searchModeEnum = EnumStringRepresentationExtensions.ToEnum <SearchModeEnum>(searchMode); // Get current culture string culture = CultureCode; if (string.IsNullOrEmpty(culture)) { culture = ValidationHelper.GetString(ViewState["CultureCode"], LocalizationContext.PreferredCultureCode); } var siteName = SiteContext.CurrentSiteName; // Get default culture string defaultCulture = CultureHelper.GetDefaultCultureCode(siteName); // Resolve path string path = Path; if (!string.IsNullOrEmpty(path)) { path = MacroResolver.ResolveCurrentPath(Path); } // Prepare search text var docCondition = new DocumentSearchCondition(DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture); var searchCond = SearchCondition; if (!string.IsNullOrEmpty(FilterSearchCondition) && (searchModeEnum == SearchModeEnum.AnyWordOrSynonyms)) { // Make sure the synonyms are expanded before the filter condition is applied (filter condition is Lucene syntax, cannot be expanded) searchCond = SearchSyntaxHelper.ExpandWithSynonyms(searchCond, docCondition.Culture); } var condition = new SearchCondition(searchCond + FilterSearchCondition, searchModeEnum, SearchOptions, docCondition, DoFuzzySearch); searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition); // Get positions and ranges for search method int startPosition = 0; int numberOfProceeded = 100; int displayResults = 100; if (pgr.PageSize != 0 && pgr.GroupSize != 0) { // Reset pager if needed if (mResetPager) { pgr.CurrentPage = 1; } startPosition = (pgr.CurrentPage - 1) * pgr.PageSize; // Only results covered by current page group are proccessed (filtered) for performance reasons. This may cause decrease of the number of results while paging. 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 = srt, Path = path, ClassNames = DocumentTypes, CurrentCulture = culture, DefaultCulture = defaultCulture, CombineWithDefaultCulture = CombineWithDefaultCulture, CheckPermissions = CheckPermissions, SearchInAttachments = SearchInAttachments, User = MembershipContext.AuthenticatedUser, SearchIndexes = Indexes, StartingPosition = startPosition, DisplayResults = displayResults, NumberOfProcessedResults = numberOfProceeded, NumberOfResults = 0, AttachmentWhere = AttachmentsWhere, AttachmentOrderBy = AttachmentsOrderBy, BlockFieldOnlySearch = BlockFieldOnlySearch, }; // Search var results = SearchHelper.Search(parameters); int numberOfResults = parameters.NumberOfResults; if ((MaxResults > 0) && (numberOfResults > MaxResults)) { numberOfResults = MaxResults; } // Limit displayed results according to MaxPages property var maxDisplayedResultsOnMaxPages = MaxPages * PageSize; // Apply only if MaxPages and PageSize properties are set if ((maxDisplayedResultsOnMaxPages > 0) && (numberOfResults > maxDisplayedResultsOnMaxPages)) { numberOfResults = maxDisplayedResultsOnMaxPages; } // Fill repeater with results repSearchResults.DataSource = results.Items; repSearchResults.PagerForceNumberOfResults = numberOfResults; PagerForceNumberOfResults = numberOfResults; repSearchResults.DataBind(); // Call page binding event if (OnPageBinding != null) { OnPageBinding(this, null); } // Show no results found ? if (numberOfResults == 0) { if (ShowParsingErrors) { Exception searchError = results.LastError; if (searchError != null) { ShowError(GetString("smartsearch.searcherror") + " " + HTMLHelper.HTMLEncode(searchError.Message)); } } lblNoResults.Text = NoResultsText; lblNoResults.Visible = true; } } else { if (!String.IsNullOrEmpty(SearchTextValidationFailedText) && searchAllowed) { pnlSearchResults.AddCssClass(SearchTextValidationFailedCssClass); lblNoResults.Text = SearchTextValidationFailedText; lblNoResults.Visible = true; } else { Visible = false; } } // Invoke search completed event if (OnSearchCompleted != null) { OnSearchCompleted(Visible); } } }
/// <summary> /// SignOut handler. /// </summary> protected void btnSignOut_Click(object sender, EventArgs e) { if (StopProcessing) { // Do not process } else { if (AuthenticationHelper.IsAuthenticated()) { string redirectUrl = RedirectToUrl; // If the user has registered Windows Live ID if (!String.IsNullOrEmpty(MembershipContext.AuthenticatedUser.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 = SiteContext.CurrentSiteName; // Get LiveID settings string appId = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationID"); string secret = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationSecret"); // Check valid Windows LiveID parameters if ((appId != string.Empty) && (secret != string.Empty)) { WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret); // Redirect to Windows Live and back to "home" page string defaultAliasPath = SettingsKeyInfoProvider.GetValue(siteName + ".CMSDefaultAliasPath"); string url = DocumentURLProvider.GetUrl(defaultAliasPath); redirectUrl = wll.GetLogoutUrl(URLHelper.GetAbsoluteUrl(url)); } } } PortalContext.ViewMode = ViewModeEnum.LiveSite; AuthenticationHelper.SignOut(); Response.Cache.SetNoStore(); URLHelper.Redirect(UrlResolver.ResolveUrl(redirectUrl)); } else { string returnUrl = null; string signInUrl = null; if (SignInUrl != "") { signInUrl = ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(SignInUrl))); } else { signInUrl = AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName); } if (ReturnPath != "") { returnUrl = ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(ReturnPath))); } else { returnUrl = RequestContext.CurrentURL; } if (signInUrl != "") { // Prevent multiple returnUrl parameter returnUrl = URLHelper.RemoveParameterFromUrl(returnUrl, "returnUrl"); URLHelper.Redirect(UrlResolver.ResolveUrl(URLHelper.UpdateParameterInUrl(signInUrl, "returnurl", Server.UrlEncode(returnUrl)))); } } } }
/// <summary> /// Setups control properties. /// </summary> protected void SetupControl() { // Check StopProcessing property if (StopProcessing) { Visible = false; } else { if (!ObjectFactory <ILicenseService> .StaticSingleton().IsFeatureAvailable(FeatureEnum.OnlineUsers)) { ShowLicenseLimitationError(); return; } SetContext(); DataSet users = null; bool transLoaded = false; // Load transformation if (!string.IsNullOrEmpty(TransformationName)) { repUsers.ItemTemplate = TransformationHelper.LoadTransformation(this, TransformationName); transLoaded = true; } if ((transLoaded) || (!String.IsNullOrEmpty(Path))) { // Try to get data from cache using (var cs = new CachedSection <DataSet>(ref users, CacheMinutes, true, CacheItemName, "onlineusers", SiteContext.CurrentSiteName, SelectTopN, Columns, Path)) { if (cs.LoadData) { // Get the data users = SessionManager.GetOnlineUsers(null, null, SelectTopN, Columns, MacroResolver.ResolveCurrentPath(Path), SiteContext.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 = CacheItemName; if (!string.IsNullOrEmpty(cacheItemNameNumbers)) { cacheItemNameNumbers += "Number"; } // Try to get data from cache using (var cs = new CachedSection <string>(ref numbers, CacheMinutes, true, cacheItemNameNumbers, "onlineusersnumber", SiteContext.CurrentSiteName, Path)) { if (cs.LoadData) { // Get the data SessionManager.GetUsersNumber(CurrentSiteName, MacroResolver.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 if (!String.IsNullOrEmpty(numbers)) { // 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> /// Gets URL from given path. /// </summary> /// <param name="path">Node alias path</param> private string GetUrl(string path) { return(ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(path)))); }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { // Initialize properties string script = ""; // Set current user currentUser = MembershipContext.AuthenticatedUser; // Get Enable Friends setting bool friendsEnabled = UIHelper.IsFriendsModuleEnabled(SiteContext.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 = MacroResolver.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(DocumentURLProvider.GetUrl(GroupMemberInfoProvider.GetMemberManagementPath(currentUser.UserName, SiteContext.CurrentSiteName))); pnlEditMyProfile.Visible = true; pnlProfileLinks.Visible = true; } // Display My profile link if set so if (DisplayMyProfileLink) { lnkMyProfile.NavigateUrl = URLHelper.ResolveUrl(DocumentURLProvider.GetUrl(GroupMemberInfoProvider.GetMemberProfilePath(currentUser.UserName, SiteContext.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 var entry = ModuleManager.GetModule(ModuleName.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(MembershipContext.AuthenticatedUser.UserID, currentGroup.GroupID); if (gmi == null) { if (String.IsNullOrEmpty(JoinGroupPath)) { script += "function JoinToGroupRequest() {\n" + "modalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/JoinTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestJoinToGroup', 500, 180); \n" + " } \n"; lnkJoinGroup.Attributes.Add("onclick", "JoinToGroupRequest();return false;"); lnkJoinGroup.NavigateUrl = RequestContext.CurrentURL; } else { lnkJoinGroup.NavigateUrl = GetUrl(JoinGroupPath); } pnlJoinGroup.Visible = true; pnlGroupLinks.Visible = true; } else if ((gmi.MemberStatus == GroupMemberStatus.Approved) || (MembershipContext.AuthenticatedUser.IsGlobalAdministrator)) // Display Leave the group link if user is the group member { if (String.IsNullOrEmpty(LeaveGroupPath)) { script += "function LeaveTheGroupRequest() {\n" + "modalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/LeaveTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestLeaveThGroup', 500, 180); \n" + " } \n"; lnkLeaveGroup.Attributes.Add("onclick", "LeaveTheGroupRequest();return false;"); lnkLeaveGroup.NavigateUrl = RequestContext.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(DocumentURLProvider.GetUrl(GroupInfoProvider.GetGroupManagementPath(currentGroup.GroupName, SiteContext.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 = MembershipContext.CurrentUserProfile; // Display invite to group link for user who is visiting a group page if (currentGroup != null) { // Get group user if (gmi == null) { gmi = GetGroupMember(MembershipContext.AuthenticatedUser.UserID, currentGroup.GroupID); } if (((gmi != null) && (gmi.MemberStatus == GroupMemberStatus.Approved)) || (MembershipContext.AuthenticatedUser.IsGlobalAdministrator)) { pnlInviteToGroup.Visible = true; if (String.IsNullOrEmpty(InviteGroupPath)) { script += "function InviteToGroup() {\n modalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','inviteToGroup', 800, 450); \n } \n"; lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;"); lnkInviteToGroup.NavigateUrl = RequestContext.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, SiteContext.CurrentSite) != 0)) { pnlInviteToGroup.Visible = true; if (String.IsNullOrEmpty(InviteGroupPath)) { script += "function InviteToGroup() {\n modalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?invitedid=" + siteContextUser.UserID + "','inviteToGroup', 700, 400); \n } \n"; lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;"); lnkInviteToGroup.NavigateUrl = RequestContext.CurrentURL; } else { lnkInviteToGroup.NavigateUrl = GetUrl(InviteGroupPath); } } } if (SiteContext.CurrentUser != null) { // Get user info from site context UserInfo siteContextUser = MembershipContext.CurrentUserProfile; // Display Friendship link if set so and user is visiting an user's page if (DisplayFriendshipLinks && (currentUser.UserID != siteContextUser.UserID) && friendsEnabled) { FriendshipStatusEnum status = MembershipContext.AuthenticatedUser.HasFriend(siteContextUser.UserID); switch (status) { case FriendshipStatusEnum.Approved: // Friendship rejection script += "function ShortcutFriendshipReject(id) { \n" + "modalDialog('" + AuthenticationHelper.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 = RequestContext.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('" + AuthenticationHelper.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 = RequestContext.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 = RequestContext.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 = RequestContext.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> /// OK click handler (Proceed registration). /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { String siteName = SiteContext.CurrentSiteName; #region "Banned IPs" // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration)) { ShowError(GetString("banip.ipisbannedregistration")); return; } #endregion #region "Check Email & password" string[] siteList = { siteName }; // If AssignToSites field set if (!String.IsNullOrEmpty(AssignToSites)) { siteList = AssignToSites.Split(';'); } // Check whether another user with this user name (which is effectively email) does not exist UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail.Text); SiteInfo si = SiteContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si)); if ((ui != null) || (siteui != null)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text))); return; } // Check whether password is same if (passStrength.Text != txtConfirmPassword.Text) { ShowError(GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch")); return; } if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength)); return; } if (!passStrength.IsValid()) { ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName)); return; } if ((!txtEmail.IsValid()) || (txtEmail.Text.Length > EMAIL_MAX_LENGTH)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"), EMAIL_MAX_LENGTH)); return; } #endregion #region "Captcha" // Check if captcha is required and verify captcha text if (DisplayCaptcha && !scCaptcha.IsValid()) { // Display error message if catcha text is not valid ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError")); return; } #endregion #region "User properties" var userEmail = txtEmail.Text.Trim(); ui = new UserInfo(); ui.PreferredCultureCode = ""; ui.Email = userEmail; ui.FirstName = txtFirstName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName); ui.MiddleName = ""; ui.UserMFRequired = chkUseMultiFactorAutentization.Checked; // User name as put by user (no site prefix included) var plainUserName = userEmail; ui.UserName = plainUserName; // Check if the given email can be used as user name if (!ValidationHelper.IsUserName(plainUserName)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.UserNameNotValid"), HTMLHelper.HTMLEncode(plainUserName))); return; } // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(siteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(plainUserName, si); } ui.Enabled = EnableUserAfterRegistration; ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer); ui.UserCampaign = Service <ICampaignService> .Entry().CampaignCode; ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None; 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 = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = false; if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is required requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"); if (requiresAdminApprove) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath); } #endregion #region "Reserved names" // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true)))); return; } if (UserInfoProvider.NameIsReserved(siteName, ui.UserNickName)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName))); return; } #endregion #region "License limitations" string errorMessage = String.Empty; UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage); if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } #endregion // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(userEmail, siteList, 0)) { ShowError(GetString("UserInfo.EmailAlreadyExist")); return; } // Set password UserInfoProvider.SetPassword(ui, passStrength.Text); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; 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 (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) { // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required) int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); if (contactId > 0) { ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, MembershipType.CMS_USER, contactId); } // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = ui.Email; email.From = SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress"); email.Subject = emailSubject; try { var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator)); EmailSender.SendEmailWithTemplateText(siteName, email, template, resolver, true); } catch (Exception ex) { EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { ShowError(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 && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate; if (SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName); } if (mEmailTemplate == null) { // Log missing e-mail template EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress); message.Recipients = ToAddress; message.Subject = GetString("RegistrationForm.EmailSubject"); try { MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui); EmailSender.SendEmailWithTemplateText(siteName, message, mEmailTemplate, resolver, false); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } #endregion #region "Web analytics" // Track successful registration conversion if (TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, 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) { MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument); // Log login activity if (ui.Enabled) { MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument); } } #endregion #region "Roles & authentication" string[] roleList = AssignRoles.Split(';'); 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(".", StringComparison.Ordinal) ? "" : sn; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, s)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, s); } } } } if (DisplayMessage.Trim() != String.Empty) { pnlForm.Visible = false; lblText.Visible = true; lblText.Text = DisplayMessage; } else { if (ui.Enabled) { AuthenticationHelper.AuthenticateUser(ui.UserName, true); } if (RedirectToURL != String.Empty) { URLHelper.Redirect(UrlResolver.ResolveUrl(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("~", StringComparison.Ordinal) || url.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath")) { URLHelper.Redirect(UrlResolver.ResolveUrl(url)); } // Absolute path with wrong hash else { URLHelper.Redirect(AdministrationUrlHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext")); } } } #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 = MembershipContext.AuthenticatedUser; // 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; lnkInviteToGroup.Text = InviteGroupText; lnkManageGroup.Text = ManageGroupText; lnkMyInvitations.Text = MyInvitationsText; // 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 = MacroResolver.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 && !AuthenticationMode.IsWindowsAuthentication()) { pnlSignOut.Visible = true; pnlSignInOut.Visible = true; } // Display Edit my profile link if set so if (DisplayEditMyProfileLink) { lnkEditMyProfile.NavigateUrl = UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(GroupMemberInfoProvider.GetMemberManagementPath(currentUser.UserName, SiteContext.CurrentSiteName))); pnlEditMyProfile.Visible = true; pnlProfileLinks.Visible = true; } // Display My profile link if set so if (DisplayMyProfileLink) { lnkMyProfile.NavigateUrl = UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(GroupMemberInfoProvider.GetMemberProfilePath(currentUser.UserName, SiteContext.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 var entry = ModuleManager.GetModule(ModuleName.BLOGS); if (entry != null) { lnkCreateNewBlog.NavigateUrl = GetUrl(CreateNewBlogPath); pnlCreateNewBlog.Visible = true; pnlBlogLinks.Visible = true; } } // Display My invitations link if (DisplayMyInvitations) { lnkMyInvitations.NavigateUrl = GetUrl(MyInvitationsPath); pnlMyInvitations.Visible = true; pnlPersonalLinks.Visible = true; } GroupMemberInfo gmi = null; if (CommunityContext.CurrentGroup != null) { // Get group info from community context GroupInfo currentGroup = CommunityContext.CurrentGroup; if (DisplayGroupLinks) { // Display Join group link if set so and user is visiting a group page gmi = GetGroupMember(MembershipContext.AuthenticatedUser.UserID, currentGroup.GroupID); if (gmi == null) { if (String.IsNullOrEmpty(JoinGroupPath)) { script += "function JoinToGroupRequest() {\n" + "modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/JoinTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestJoinToGroup', 500, 180); \n" + " } \n"; lnkJoinGroup.Attributes.Add("onclick", "JoinToGroupRequest();return false;"); lnkJoinGroup.NavigateUrl = RequestContext.CurrentURL; } else { lnkJoinGroup.NavigateUrl = GetUrl(JoinGroupPath); } pnlJoinGroup.Visible = true; pnlGroupLinks.Visible = true; } else if ((gmi.MemberStatus == GroupMemberStatus.Approved) || (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))) // Display Leave the group link if user is the group member { if (String.IsNullOrEmpty(LeaveGroupPath)) { script += "function LeaveTheGroupRequest() {\n" + "modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/LeaveTheGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','requestLeaveThGroup', 500, 180); \n" + " } \n"; lnkLeaveGroup.Attributes.Add("onclick", "LeaveTheGroupRequest();return false;"); lnkLeaveGroup.NavigateUrl = RequestContext.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.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin)))) { lnkManageGroup.NavigateUrl = ResolveUrl(DocumentURLProvider.GetUrl(GroupInfoProvider.GetGroupManagementPath(currentGroup.GroupName, SiteContext.CurrentSiteName))); pnlManageGroup.Visible = true; pnlGroupLinks.Visible = true; } } // Get user info from site context UserInfo siteContextUser = MembershipContext.CurrentUserProfile; if (DisplayInviteToGroup) { // Get group info from community context GroupInfo currentGroup = CommunityContext.CurrentGroup; // Display invite to group link for user who is visiting a group page if (currentGroup != null) { // Get group user if (gmi == null) { gmi = GetGroupMember(MembershipContext.AuthenticatedUser.UserID, currentGroup.GroupID); } if (((gmi != null) && (gmi.MemberStatus == GroupMemberStatus.Approved)) || (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))) { pnlInviteToGroup.Visible = true; if (String.IsNullOrEmpty(InviteGroupPath)) { script += "function InviteToGroup() {\n modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?groupid=" + currentGroup.GroupID + "','inviteToGroup', 800, 450); \n } \n"; lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;"); lnkInviteToGroup.NavigateUrl = RequestContext.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, SiteContext.CurrentSite) != 0)) { pnlInviteToGroup.Visible = true; if (String.IsNullOrEmpty(InviteGroupPath)) { script += "function InviteToGroup() {\n modalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?invitedid=" + siteContextUser.UserID + "','inviteToGroup', 700, 400); \n } \n"; lnkInviteToGroup.Attributes.Add("onclick", "InviteToGroup();return false;"); lnkInviteToGroup.NavigateUrl = RequestContext.CurrentURL; } else { lnkInviteToGroup.NavigateUrl = GetUrl(InviteGroupPath); } } } } // Register menu management scripts ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "Shortcuts_" + ClientID, ScriptHelper.GetScript(script)); // Register the dialog script ScriptHelper.RegisterDialogScript(Page); } }