/// <summary> /// Handles the CreatedUser event of the CreateUserWizard1 control. /// </summary> /// <param name="sender"> /// The source of the event. /// </param> /// <param name="e"> /// The <see cref="EventArgs"/> instance containing the event data. /// </param> protected void CreateUserWizard1_CreatedUser([NotNull] object sender, [NotNull] EventArgs e) { var user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, this.CreateUserWizard1.UserName); var displayName = user.UserName; if (this.Get <YafBoardSettings>().EnableDisplayName) { displayName = this.CreateUserStepContainer.FindControlAs <TextBox>("DisplayName").Text.Trim(); } // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, displayName, YafContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName); // setup their initial profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... YafBuildLink.RedirectInfoPage(InfoMessage.Failure); } if (this.IsPossibleSpamBot) { if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { this.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } } else { // handle e-mail verification if needed if (this.Get <YafBoardSettings>().EmailVerification) { // get the user email var emailTextBox = (TextBox)this.CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Email"); var email = emailTextBox.Text.Trim(); this.Get <ISendNotification>().SendVerificationEmail(user, email, userID); } else { // Send welcome mail/pm to user this.Get <ISendNotification>().SendUserWelcomeNotification(user, userID.Value); } if (this.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... this.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } } }
/// <summary> /// The create user wizard 1_ next button click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void CreateUserWizard1_NextButtonClick(object sender, WizardNavigationEventArgs e) { if (this.CreateUserWizard1.WizardSteps[e.CurrentStepIndex].ID == "profile") { // this is the "Profile Information" step. Save the data to their profile (+ defaults). var timeZones = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("TimeZones"); var locationTextBox = (TextBox)this.CreateUserWizard1.FindWizardControlRecursive("Location"); var homepageTextBox = (TextBox)this.CreateUserWizard1.FindWizardControlRecursive("Homepage"); var dstUser = (CheckBox)this.CreateUserWizard1.FindWizardControlRecursive("DSTUser"); MembershipUser user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName); // setup/save the profile YafUserProfile userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName); // Trying to consume data about user IP whereabouts /* if (_userIpLocator.Status == "OK" && String.IsNullOrEmpty(locationTextBox.Text.Trim())) * { * * if (!String.IsNullOrEmpty(_userIpLocator.CountryName)) * { * userProfile.Location += _userIpLocator.CountryName; * } * if (!String.IsNullOrEmpty(_userIpLocator.RegionName)) * { * userProfile.Location += ", " + _userIpLocator.RegionName; * } * if (!String.IsNullOrEmpty(_userIpLocator.City)) * { * userProfile.Location += ", " + _userIpLocator.City; * } * } * else * { * userProfile.Location = locationTextBox.Text.Trim(); * } */ userProfile.Location = locationTextBox.Text.Trim(); userProfile.Homepage = homepageTextBox.Text.Trim(); userProfile.Save(); // save the time zone... int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); DB.user_save( userId, this.PageContext.PageBoardID, null, null, null, timeZones.SelectedValue.ToType <int>(), null, null, null, null, null, null, null, dstUser.Checked, null, null); bool autoWatchTopicsEnabled = this.PageContext.BoardSettings.DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... DB.user_savenotification( userId, true, autoWatchTopicsEnabled, this.PageContext.BoardSettings.DefaultNotificationSetting, PageContext.BoardSettings.DefaultSendDigestEmail); // Clearing cache with old Active User Lazy Data ... this.PageContext.Cache.Remove(YafCache.GetBoardCacheKey(Constants.Cache.ActiveUserLazyData.FormatWith(userId))); } }
/// <summary> /// The create board. /// </summary> /// <param name="adminName">The admin name.</param> /// <param name="adminPassword">The admin password.</param> /// <param name="adminEmail">The admin email.</param> /// <param name="adminPasswordQuestion">The admin password question.</param> /// <param name="adminPasswordAnswer">The admin password answer.</param> /// <param name="boardName">The board name.</param> /// <param name="boardMembershipAppName">The board membership app name.</param> /// <param name="boardRolesAppName">The board roles app name.</param> /// <param name="createUserAndRoles">The create user and roles.</param> /// <returns>Returns if the board was created or not</returns> protected bool CreateBoard( [NotNull] string adminName, [NotNull] string adminPassword, [NotNull] string adminEmail, [NotNull] string adminPasswordQuestion, [NotNull] string adminPasswordAnswer, [NotNull] string boardName, [NotNull] string boardMembershipAppName, [NotNull] string boardRolesAppName, bool createUserAndRoles) { // Store current App Names var currentMembershipAppName = this.Get <MembershipProvider>().ApplicationName; var currentRolesAppName = this.Get <RoleProvider>().ApplicationName; if (boardMembershipAppName.IsSet() && boardRolesAppName.IsSet()) { // Change App Names for new board this.Get <MembershipProvider>().ApplicationName = boardMembershipAppName; this.Get <MembershipProvider>().ApplicationName = boardRolesAppName; } int newBoardId; var cult = StaticDataHelper.Cultures(); var langFile = "english.xml"; foreach (var drow in cult.Rows.Cast <DataRow>().Where(drow => drow["CultureTag"].ToString() == this.Culture.SelectedValue)) { langFile = (string)drow["CultureFile"]; } if (createUserAndRoles) { // Create new admin users var newAdmin = this.Get <MembershipProvider>() .CreateUser( adminName, adminPassword, adminEmail, adminPasswordQuestion, adminPasswordAnswer, true, null, out var createStatus); if (createStatus != MembershipCreateStatus.Success) { this.PageContext.AddLoadMessage( $"Create User Failed: {this.GetMembershipErrorMessage(createStatus)}", MessageTypes.danger); return(false); } // Create groups required for the new board RoleMembershipHelper.CreateRole("Administrators"); RoleMembershipHelper.CreateRole("Registered"); // Add new admin users to group RoleMembershipHelper.AddUserToRole(newAdmin.UserName, "Administrators"); // Create Board newBoardId = this.DbCreateBoard( boardName, boardMembershipAppName, boardRolesAppName, langFile, newAdmin); } else { // new admin var newAdmin = UserMembershipHelper.GetUser(); // Create Board newBoardId = this.DbCreateBoard( boardName, boardMembershipAppName, boardRolesAppName, langFile, newAdmin); } if (newBoardId > 0 && Config.MultiBoardFolders) { // Successfully created the new board var boardFolder = this.Server.MapPath(Path.Combine(Config.BoardRoot, $"{newBoardId}/")); // Create New Folders. if (!Directory.Exists(Path.Combine(boardFolder, "Images"))) { // Create the Images Folders Directory.CreateDirectory(Path.Combine(boardFolder, "Images")); // Create Sub Folders Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Avatars")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Categories")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Forums")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Emoticons")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Medals")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Ranks")); } if (!Directory.Exists(Path.Combine(boardFolder, "Themes"))) { Directory.CreateDirectory(Path.Combine(boardFolder, "Themes")); // Need to copy default theme to the Themes Folder } if (!Directory.Exists(Path.Combine(boardFolder, "Uploads"))) { Directory.CreateDirectory(Path.Combine(boardFolder, "Uploads")); } } // Return application name to as they were before. this.Get <MembershipProvider>().ApplicationName = currentMembershipAppName; this.Get <RoleProvider>().ApplicationName = currentRolesAppName; return(true); }
/// <summary> /// Sends Notifications to Moderators that a Message was Reported /// </summary> /// <param name="pageForumID"> /// The page Forum ID. /// </param> /// <param name="reportedMessageId"> /// The reported message id. /// </param> /// <param name="reporter"> /// The reporter. /// </param> /// <param name="reportText"> /// The report Text. /// </param> public void ToModeratorsThatMessageWasReported( int pageForumID, int reportedMessageId, int reporter, string reportText) { try { var moderatorsFiltered = this.Get <DataBroker>().GetAllModerators().Where(f => f.ForumID.Equals(pageForumID)); var moderatorUserNames = new List <string>(); moderatorsFiltered.ForEach( moderator => { if (moderator.IsGroup) { moderatorUserNames.AddRange(this.Get <RoleProvider>().GetUsersInRole(moderator.Name)); } else { moderatorUserNames.Add(moderator.Name); } }); var currentContext = HttpContext.Current; // send each message... moderatorUserNames.Distinct().AsParallel().ForAll( userName => { HttpContext.Current = currentContext; try { // add each member of the group var membershipUser = UserMembershipHelper.GetUser(userName); var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(membershipUser.ProviderUserKey); var languageFile = UserHelper.GetUserLanguageFile(userId); var subject = string.Format( this.Get <ILocalization>().GetText( "COMMON", "NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE", languageFile), this.BoardSettings.Name); var notifyModerators = new TemplateEmail("NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE") { // get the user localization... TemplateLanguageFile = languageFile, TemplateParams = { ["{user}"] = userName, ["{reason}"] = reportText, ["{reporter}"] = this.Get <IUserDisplayName>() .GetName(reporter), ["{adminlink}"] = BuildLink.GetLinkNotEscaped( ForumPages.Moderate_ReportedPosts, true, "f={0}", pageForumID) } }; notifyModerators.SendEmail( new MailAddress(membershipUser.Email, membershipUser.UserName), subject); } finally { HttpContext.Current = null; } }); } catch (Exception x) { // report exception to the forum's event log this.Get <ILogger>().Error( x, $"Send Message Report Notification Error for UserID {BoardContext.Current.PageUserID}"); } }
/// <summary> /// Handles click on save button. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e) { var addedRoles = new List <string>(); var removedRoles = new List <string>(); // get user's name var userName = UserMembershipHelper.GetUserNameFromID(this.CurrentUserID); var user = UserMembershipHelper.GetUser(userName); // go through all roles displayed on page for (var i = 0; i < this.UserGroups.Items.Count; i++) { // get current item var item = this.UserGroups.Items[i]; // get role ID from it var roleID = int.Parse(item.FindControlAs <Label>("GroupID").Text); // get role name var roleName = this.GetRepository <Group>().GetById(roleID).Name; // is user supposed to be in that role? var isChecked = item.FindControlAs <CheckBox>("GroupMember").Checked; // save user in role this.GetRepository <UserGroup>().Save(this.CurrentUserID, roleID, isChecked); // empty out access table(s) this.GetRepository <Active>().DeleteAll(); this.GetRepository <ActiveAccess>().DeleteAll(); // update roles if this user isn't the guest if (UserMembershipHelper.IsGuestUser(this.CurrentUserID)) { continue; } // add/remove user from roles in membership provider if (isChecked && !RoleMembershipHelper.IsUserInRole(userName, roleName)) { RoleMembershipHelper.AddUserToRole(userName, roleName); addedRoles.Add(roleName); } else if (!isChecked && RoleMembershipHelper.IsUserInRole(userName, roleName)) { RoleMembershipHelper.RemoveUserFromRole(userName, roleName); removedRoles.Add(roleName); } // Clearing cache with old permissions data... this.Get <IDataCache>().Remove(string.Format(Constants.Cache.ActiveUserLazyData, this.CurrentUserID)); } if (this.SendEmail.Checked) { // send notification to user if (addedRoles.Any()) { this.Get <ISendNotification>().SendRoleAssignmentNotification(user, addedRoles); } if (removedRoles.Any()) { this.Get <ISendNotification>().SendRoleUnAssignmentNotification(user, removedRoles); } } // update forum moderators cache just in case something was changed... this.Get <IDataCache>().Remove(Constants.Cache.ForumModerators); // clear the cache for this user... this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.CurrentUserID)); this.BindData(); }
/// <summary> /// Creates the forum. /// </summary> /// <returns> /// The create forum. /// </returns> private bool CreateForum() { if (this.InstallUpgradeService.IsForumInstalled) { this.ShowErrorMessage("Forum is already installed."); return(false); } if (this.TheForumName.Text.Length == 0) { this.ShowErrorMessage("You must enter a forum name."); return(false); } if (this.ForumEmailAddress.Text.Length == 0) { this.ShowErrorMessage("You must enter a forum email address."); return(false); } MembershipUser user; if (this.UserChoice.SelectedValue == "create") { if (this.UserName.Text.Length == 0) { this.ShowErrorMessage("You must enter the admin user name,"); return(false); } if (this.AdminEmail.Text.Length == 0) { this.ShowErrorMessage("You must enter the administrators email address."); return(false); } if (this.Password1.Text.Length == 0) { this.ShowErrorMessage("You must enter a password."); return(false); } if (this.Password1.Text != this.Password2.Text) { this.ShowErrorMessage("The passwords must match."); return(false); } // create the admin user... MembershipCreateStatus status; user = this.Get <MembershipProvider>() .CreateUser( this.UserName.Text, this.Password1.Text, this.AdminEmail.Text, this.SecurityQuestion.Text, this.SecurityAnswer.Text, true, null, out status); if (status != MembershipCreateStatus.Success) { this.ShowErrorMessage( "Create Admin User Failed: {0}".FormatWith(this.GetMembershipErrorMessage(status))); return(false); } } else { // try to get data for the existing user... user = UserMembershipHelper.GetUser(this.ExistingUserName.Text.Trim()); if (user == null) { this.ShowErrorMessage( "Existing user name is invalid and does not represent a current user in the membership store."); return(false); } } try { var prefix = Config.CreateDistinctRoles && Config.IsAnyPortal ? "YAF " : string.Empty; // add administrators and registered if they don't already exist... if (!RoleMembershipHelper.RoleExists("{0}Administrators".FormatWith(prefix))) { RoleMembershipHelper.CreateRole("{0}Administrators".FormatWith(prefix)); } if (!RoleMembershipHelper.RoleExists("{0}Registered".FormatWith(prefix))) { RoleMembershipHelper.CreateRole("{0}Registered".FormatWith(prefix)); } if (!RoleMembershipHelper.IsUserInRole(user.UserName, "{0}Administrators".FormatWith(prefix))) { RoleMembershipHelper.AddUserToRole(user.UserName, "{0}Administrators".FormatWith(prefix)); } // logout administrator... FormsAuthentication.SignOut(); int timeZone; try { timeZone = int.Parse(this.TimeZones.SelectedValue); } catch (Exception) { timeZone = 0; } // init forum... this.InstallUpgradeService.InitializeForum( this.TheForumName.Text, timeZone, this.Culture.SelectedValue, this.ForumEmailAddress.Text, this.ForumBaseUrlMask.Text, user.UserName, user.Email, user.ProviderUserKey); } catch (Exception x) { this.ShowErrorMessage(x.Message); return(false); } return(true); }
/// <summary> /// Sends Notifications to Moderators that Message Needs Approval /// </summary> /// <param name="forumId">The forum id.</param> /// <param name="newMessageId">The new message id.</param> /// <param name="isSpamMessage">if set to <c>true</c> [is spam message].</param> public void ToModeratorsThatMessageNeedsApproval(int forumId, int newMessageId, bool isSpamMessage) { var moderatorsFiltered = this.Get <DataBroker>().GetAllModerators().Where(f => f.ForumID.Equals(forumId)); var moderatorUserNames = new List <string>(); moderatorsFiltered.ForEach( moderator => { if (moderator.IsGroup) { moderatorUserNames.AddRange(this.Get <RoleProvider>().GetUsersInRole(moderator.Name)); } else { moderatorUserNames.Add(moderator.Name); } }); var themeCss = $"{this.Get<BoardSettings>().BaseUrlMask}{this.Get<ITheme>().BuildThemePath("bootstrap-forum.min.css")}"; var forumLink = BoardInfo.ForumURL; var adminLink = BuildLink.GetLinkNotEscaped(ForumPages.Moderate_UnapprovedPosts, true, "f={0}", forumId); var currentContext = HttpContext.Current; // send each message... moderatorUserNames.Distinct().AsParallel().ForAll( userName => { HttpContext.Current = currentContext; try { // add each member of the group var membershipUser = UserMembershipHelper.GetUser(userName); var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(membershipUser.ProviderUserKey); var languageFile = UserHelper.GetUserLanguageFile(userId); var subject = string.Format( this.Get <ILocalization>().GetText( "COMMON", isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL", languageFile), this.BoardSettings.Name); var notifyModerators = new TemplateEmail( isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL") { TemplateLanguageFile = languageFile, TemplateParams = { ["{user}"] = userName, ["{adminlink}"] = adminLink, ["{themecss}"] = themeCss, ["{forumlink}"] = forumLink } }; notifyModerators.SendEmail( new MailAddress(membershipUser.Email, membershipUser.UserName), subject); } finally { HttpContext.Current = null; } }); }
/// <summary> /// The to watching users. /// </summary> /// <param name="newMessageId"> /// The new message id. /// </param> public void ToWatchingUsers(int newMessageId) { IList <User> usersWithAll = new List <User>(); if (this.BoardSettings.AllowNotificationAllPostsAllTopics) { usersWithAll = this.GetRepository <User>() .FindUserTyped(filter: false, notificationType: UserNotificationSetting.AllTopics.ToInt()); } // TODO : Rewrite Watch Topic code to allow watch mails in the users language, as workaround send all messages in the default board language var languageFile = this.BoardSettings.Language; var boardName = this.BoardSettings.Name; var forumEmail = this.BoardSettings.ForumEmail; var message = this.GetRepository <Message>().MessageList(newMessageId).FirstOrDefault(); var messageAuthorUserID = message.UserID ?? 0; var watchEmail = new YafTemplateEmail("TOPICPOST") { TemplateLanguageFile = languageFile }; // cleaned body as text... var bodyText = this.Get <IBadWordReplace>() .Replace(BBCodeHelper.StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message.Message)))) .RemoveMultipleWhitespace(); // Send track mails var subject = string .Format(this.Get <ILocalization>() .GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile), boardName); watchEmail.TemplateParams["{forumname}"] = boardName; watchEmail.TemplateParams["{topic}"] = HttpUtility.HtmlDecode(this.Get <IBadWordReplace>().Replace(message.Topic)); watchEmail.TemplateParams["{postedby}"] = UserMembershipHelper.GetDisplayNameFromID(messageAuthorUserID); watchEmail.TemplateParams["{body}"] = bodyText; watchEmail.TemplateParams["{bodytruncated}"] = bodyText.Truncate(160); watchEmail.TemplateParams["{link}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.posts, true, "m={0}#post{0}", newMessageId); watchEmail.TemplateParams["{subscriptionlink}"] = YafBuildLink.GetLinkNotEscaped(ForumPages.cp_subscriptions, true); watchEmail.CreateWatch( message.TopicID ?? 0, messageAuthorUserID, new MailAddress(forumEmail, boardName), subject); // create individual watch emails for all users who have All Posts on... foreach (var user in usersWithAll.Where(x => x.ID != messageAuthorUserID && x.ProviderUserKey != null)) { var membershipUser = UserMembershipHelper.GetUser(user.ProviderUserKey.ToType <object>()); if (membershipUser == null || membershipUser.Email.IsNotSet()) { continue; } watchEmail.TemplateLanguageFile = user.LanguageFile.IsSet() ? user.LanguageFile : this.Get <ILocalization>().LanguageFileName; watchEmail.SendEmail( new MailAddress(forumEmail, boardName), new MailAddress(membershipUser.Email, membershipUser.UserName), subject, true); } }
/// <summary> /// Sends Notifications to Moderators that Message Needs Approval /// </summary> /// <param name="forumId">The forum id.</param> /// <param name="newMessageId">The new message id.</param> /// <param name="isSpamMessage">if set to <c>true</c> [is spam message].</param> public void ToModeratorsThatMessageNeedsApproval(int forumId, int newMessageId, bool isSpamMessage) { var moderatorsFiltered = this.Get <YafDbBroker>().GetAllModerators().Where(f => f.ForumID.Equals(forumId)); var moderatorUserNames = new List <string>(); moderatorsFiltered.ForEach( moderator => { if (moderator.IsGroup) { moderatorUserNames.AddRange(this.Get <RoleProvider>().GetUsersInRole(moderator.Name)); } else { moderatorUserNames.Add(moderator.Name); } }); // send each message... moderatorUserNames.Distinct().ForEach( userName => { // add each member of the group var membershipUser = UserMembershipHelper.GetUser(userName); var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(membershipUser.ProviderUserKey); var languageFile = UserHelper.GetUserLanguageFile(userId); var subject = string.Format( this.Get <ILocalization>().GetText( "COMMON", isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL", languageFile), this.BoardSettings.Name); var notifyModerators = new YafTemplateEmail( isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL") { // get the user localization... TemplateLanguageFile = languageFile, TemplateParams = { ["{adminlink}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.moderate_unapprovedposts, true, "f={0}", forumId), ["{forumname}"] = this.BoardSettings.Name } }; notifyModerators.SendEmail( new MailAddress(membershipUser.Email, membershipUser.UserName), subject, true); }); }
/// <summary> /// The render regular. /// </summary> /// <param name="writer"> /// The writer. /// </param> protected void RenderRegular([NotNull] ref HtmlTextWriter writer) { // BEGIN HEADER var buildHeader = new StringBuilder(); buildHeader.AppendFormat( @"<table width=""100%"" cellspacing=""0"" class=""content"" cellpadding=""0"" id=""yafheader""><tr>"); SitecoreMembershipUser user = UserMembershipHelper.GetUser(); if (user != null) { string displayName = this.PageContext.CurrentUserData.DisplayName; buildHeader.AppendFormat( @"<td style=""padding:5px"" class=""post"" align=""left""><strong>{0} <span id=""nick_{1}"" style =""{2}"" >{1}</span></strong></td>", this.GetText("TOOLBAR", "LOGGED_IN_AS").FormatWith(string.Empty), this.Get <HttpServerUtilityBase>().HtmlEncode( this.Get <YafBoardSettings>().EnableDisplayName&& displayName.IsSet() ? displayName : this.PageContext.PageUserName), this.Get <YafBoardSettings>().UseStyledNicks ? this.Get <IStyleTransform>().DecodeStyleByString(this.PageContext.UserStyle, false) : null); buildHeader.AppendFormat(@"<td style=""padding:5px"" align=""right"" valign=""middle"" class=""post"">"); if (!this.PageContext.IsGuest && this.Get <YafBoardSettings>().AllowPrivateMessages) { if (this.PageContext.UnreadPrivate > 0) { string unreadText = this.GetText("TOOLBAR", "NEWPM").FormatWith(this.PageContext.UnreadPrivate); buildHeader.AppendFormat(" <a target='_top' href=\"{0}\">{1}</a> <span class=\"unread\">{2}</span> | ".FormatWith( YafBuildLink.GetLink(ForumPages.cp_pm), this.GetText("CP_PM", "INBOX"), unreadText)); } else { buildHeader.AppendFormat( " <a target='_top' href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.cp_pm), this.GetText("CP_PM", "INBOX"))); } } if (!this.PageContext.IsGuest && this.Get <YafBoardSettings>().EnableBuddyList&& this.PageContext.UserHasBuddies) { if (this.PageContext.PendingBuddies > 0) { string pendingBuddiesText = this.GetText("TOOLBAR", "BUDDYREQUEST").FormatWith(this.PageContext.PendingBuddies); buildHeader.AppendFormat( " <a target='_top' href=\"{0}\">{1}</a> <span class=\"unread\">{2}</span> | ".FormatWith( YafBuildLink.GetLink(ForumPages.cp_editbuddies), this.GetText("TOOLBAR", "BUDDIES"), pendingBuddiesText)); } else { buildHeader.AppendFormat( " <a target='_top' href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.cp_editbuddies), this.GetText("TOOLBAR", "BUDDIES"))); } } if (!this.PageContext.IsGuest && this.Get <YafBoardSettings>().EnableAlbum&& (this.PageContext.UsrAlbums > 0 || this.PageContext.NumAlbums > 0)) { buildHeader.AppendFormat( " <a target='_top' href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.albums, "u={0}", this.PageContext.PageUserID), this.GetText("TOOLBAR", "MYALBUMS"))); } buildHeader.AppendFormat( " <a target='_top' href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.help_index), this.GetText("TOOLBAR", "HELP"))); if (this.PageContext.IsAdmin) { buildHeader.AppendFormat( " <a target='_top' href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.admin_admin), this.GetText("TOOLBAR", "ADMIN"))); } if (this.PageContext.IsModeratorInAnyForum) { buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.moderate_index), this.GetText("TOOLBAR", "MODERATE"))); } if (this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().ExternalSearchPermissions) || this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().SearchPermissions)) { buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.search), this.GetText("TOOLBAR", "SEARCH"))); } if (!this.PageContext.IsGuest) { buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.mytopics), this.GetText("TOOLBAR", "MYTOPICS"))); buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.cp_profile), this.GetText("TOOLBAR", "MYPROFILE"))); } else { buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.mytopics), this.GetText("TOOLBAR", "ACTIVETOPICS"))); } if (this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().MembersListViewPermissions)) { buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.members), this.GetText("TOOLBAR", "MEMBERS"))); } if (!Config.IsAnyPortal && Config.AllowLoginAndLogoff) { buildHeader.AppendFormat( " <a href=\"{0}\" onclick=\"return confirm('{2}');\">{1}</a>".FormatWith( YafBuildLink.GetLink(ForumPages.logout), this.GetText("TOOLBAR", "LOGOUT"), this.GetText("TOOLBAR", "LOGOUT_QUESTION"))); } } else { buildHeader.AppendFormat( @"<td style=""padding:5px"" class=""post"" align=""left""><strong>{0}</strong></td>".FormatWith( this.GetText("TOOLBAR", "WELCOME_GUEST"))); buildHeader.AppendFormat(@"<td style=""padding:5px"" align=""right"" valign=""middle"" class=""post"">"); if (this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().ExternalSearchPermissions) || this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().SearchPermissions)) { buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.search), this.GetText("TOOLBAR", "SEARCH"))); } buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.mytopics), this.GetText("TOOLBAR", "ACTIVETOPICS"))); if (this.Get <IPermissions>().Check(this.Get <YafBoardSettings>().MembersListViewPermissions)) { buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a> | ".FormatWith( YafBuildLink.GetLink(ForumPages.members), this.GetText("TOOLBAR", "MEMBERS"))); } string returnUrl = this.GetReturnUrl(); if (!Config.IsAnyPortal && Config.AllowLoginAndLogoff) { buildHeader.AppendFormat( " <a href=\"{0}\">{1}</a>".FormatWith( (returnUrl == string.Empty) ? (!this.Get <YafBoardSettings>().UseSSLToLogIn ? YafBuildLink.GetLink(ForumPages.login) : YafBuildLink.GetLink(ForumPages.login, true).Replace("http:", "https:")) : (!this.Get <YafBoardSettings>().UseSSLToLogIn ? YafBuildLink.GetLink(ForumPages.login, "ReturnUrl={0}", returnUrl) : YafBuildLink.GetLink(ForumPages.login, true, "ReturnUrl={0}", returnUrl).Replace("http:", "https:")), this.GetText("TOOLBAR", "LOGIN"))); if (!this.Get <YafBoardSettings>().DisableRegistrations) { buildHeader.AppendFormat( " | <a href=\"{0}\">{1}</a>".FormatWith( this.Get <YafBoardSettings>().ShowRulesForRegistration ? YafBuildLink.GetLink(ForumPages.rules) : (!this.Get <YafBoardSettings>().UseSSLToRegister ? YafBuildLink.GetLink(ForumPages.register) : YafBuildLink.GetLink(ForumPages.register, true).Replace("http:", "https:")), this.GetText("TOOLBAR", "REGISTER"))); } } } buildHeader.ToString().TrimEnd(' ', '|'); buildHeader.Append("</td></tr></table>"); buildHeader.Append("<br />"); // END HEADER writer.Write(buildHeader); }
/// <summary> /// Sends the digest to users. /// </summary> /// <param name="usersWithDigest">The users with digest.</param> /// <param name="boardSettings">The board settings.</param> private void SendDigestToUsers(IEnumerable <User> usersWithDigest, BoardSettings boardSettings) { var usersSendCount = 0; var currentContext = HttpContext.Current; usersWithDigest.AsParallel().ForAll( user => { HttpContext.Current = currentContext; try { var digestHtml = this.Get <IDigest>().GetDigestHtml(user.ID, boardSettings); if (digestHtml.IsNotSet()) { return; } if (user.ProviderUserKey == null) { return; } var membershipUser = UserMembershipHelper.GetUser(user.Name); if (membershipUser == null || membershipUser.Email.IsNotSet()) { return; } var subject = Regex.Match(digestHtml, "<title>(.*?)</title>", RegexOptions.Singleline) .Groups[1].Value.Trim(); // send the digest... this.Get <IDigest>().SendDigest( subject.Trim(), digestHtml, boardSettings.Name, boardSettings.ForumEmail, membershipUser.Email, user.DisplayName); usersSendCount++; } catch (Exception e) { this.Get <ILogger>().Error(e, $"Error In Creating Digest for User {user.ID}"); } finally { HttpContext.Current = null; } }); this.Get <ILogger>().Log( $"Digest send to {usersSendCount} user(s)", EventLogTypes.Information, null, "Digest Send Task"); }
/// <summary> /// The to watching users. /// </summary> /// <param name="newMessageId"> /// The new message id. /// </param> public void ToWatchingUsers(int newMessageId) { IEnumerable <TypedUserFind> usersWithAll = new List <TypedUserFind>(); if (this.BoardSettings.AllowNotificationAllPostsAllTopics) { // TODO: validate permissions! usersWithAll = LegacyDb.UserFind( YafContext.Current.PageBoardID, false, null, null, null, UserNotificationSetting.AllTopics.ToInt(), null); } // TODO : Rewrite Watch Topic code to allow watch mails in the users language, as workaround send all messages in the default board language string languageFile = this.BoardSettings.Language; string boardName = this.BoardSettings.Name; string forumEmail = BoardSettings.ForumEmail; foreach (var message in LegacyDb.MessageList(newMessageId)) { int userId = message.UserID ?? 0; var watchEmail = new YafTemplateEmail("TOPICPOST") { TemplateLanguageFile = languageFile }; // cleaned body as text... var bodyText = BBCodeHelper .StripBBCode(HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString(message.Message))) .RemoveMultipleWhitespace(); // Send track mails var subject = this.Get <ILocalization>() .GetText("COMMON", "TOPIC_NOTIFICATION_SUBJECT", languageFile) .FormatWith(boardName); watchEmail.TemplateParams["{forumname}"] = boardName; watchEmail.TemplateParams["{topic}"] = HttpUtility.HtmlDecode(message.Topic); watchEmail.TemplateParams["{postedby}"] = UserMembershipHelper.GetDisplayNameFromID(userId); watchEmail.TemplateParams["{body}"] = bodyText; watchEmail.TemplateParams["{bodytruncated}"] = bodyText.Truncate(160); watchEmail.TemplateParams["{link}"] = YafBuildLink.GetLinkNotEscaped(ForumPages.posts, true, "m={0}#post{0}", newMessageId); watchEmail.CreateWatch( message.TopicID ?? 0, userId, new MailAddress(forumEmail, boardName), subject); // create individual watch emails for all users who have All Posts on... foreach (var user in usersWithAll.Where(x => x.UserID.HasValue && x.UserID.Value != userId)) { // Make sure its not a guest if (user.ProviderUserKey == null) { continue; } var membershipUser = UserMembershipHelper.GetUser(user.ProviderUserKey); if (membershipUser == null || !membershipUser.Email.IsSet()) { continue; } watchEmail.TemplateLanguageFile = !string.IsNullOrEmpty(user.LanguageFile) ? user.LanguageFile : this.Get <ILocalization>().LanguageFileName; watchEmail.SendEmail( new MailAddress(forumEmail, boardName), new MailAddress(membershipUser.Email, membershipUser.UserName), subject, true); } } }
/// <summary> /// Sends Notifications to Moderators that a Message was Reported /// </summary> /// <param name="pageForumID"> /// The page Forum ID. /// </param> /// <param name="reportedMessageId"> /// The reported message id. /// </param> /// <param name="reporter"> /// The reporter. /// </param> /// <param name="reportText"> /// The report Text. /// </param> public void ToModeratorsThatMessageWasReported( int pageForumID, int reportedMessageId, int reporter, string reportText) { try { var moderatorsFiltered = this.Get <YafDbBroker>().GetAllModerators().Where(f => f.ForumID.Equals(pageForumID)); var moderatorUserNames = new List <string>(); foreach (var moderator in moderatorsFiltered) { if (moderator.IsGroup) { moderatorUserNames.AddRange(this.Get <RoleProvider>().GetUsersInRole(moderator.Name)); } else { moderatorUserNames.Add(moderator.Name); } } // send each message... foreach (var userName in moderatorUserNames.Distinct()) { // add each member of the group var membershipUser = UserMembershipHelper.GetUser(userName); var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(membershipUser.ProviderUserKey); var languageFile = UserHelper.GetUserLanguageFile(userId); var subject = this.Get <ILocalization>() .GetText("COMMON", "NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE", languageFile) .FormatWith(this.BoardSettings.Name); var notifyModerators = new YafTemplateEmail("NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE") { // get the user localization... TemplateLanguageFile = languageFile, TemplateParams = { ["{reason}"] = reportText, ["{reporter}"] = this.Get <IUserDisplayName>().GetName(reporter), ["{adminlink}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.moderate_reportedposts, true, "f={0}", pageForumID), ["{forumname}"] = this.BoardSettings.Name } }; notifyModerators.SendEmail( new MailAddress(membershipUser.Email, membershipUser.UserName), subject, true); } } catch (Exception x) { // report exception to the forum's event log this.Get <ILogger>() .Error( x, "Send Message Report Notification Error for UserID {0}".FormatWith( YafContext.Current.PageUserID)); } }
/// <summary> /// The create board. /// </summary> /// <param name="adminName"> /// The admin name. /// </param> /// <param name="adminPassword"> /// The admin password. /// </param> /// <param name="adminEmail"> /// The admin email. /// </param> /// <param name="adminPasswordQuestion"> /// The admin password question. /// </param> /// <param name="adminPasswordAnswer"> /// The admin password answer. /// </param> /// <param name="boardName"> /// The board name. /// </param> /// <param name="boardMembershipAppName"> /// The board membership app name. /// </param> /// <param name="boardRolesAppName"> /// The board roles app name. /// </param> /// <param name="createUserAndRoles"> /// The create user and roles. /// </param> /// <exception cref="ApplicationException"> /// </exception> protected void CreateBoard( string adminName, string adminPassword, string adminEmail, string adminPasswordQuestion, string adminPasswordAnswer, string boardName, string boardMembershipAppName, string boardRolesAppName, bool createUserAndRoles) { // Store current App Names string currentMembershipAppName = PageContext.CurrentMembership.ApplicationName; string currentRolesAppName = PageContext.CurrentRoles.ApplicationName; if (boardMembershipAppName.IsSet() && boardRolesAppName.IsSet()) { // Change App Names for new board PageContext.CurrentMembership.ApplicationName = boardMembershipAppName; PageContext.CurrentMembership.ApplicationName = boardRolesAppName; } int newBoardID = 0; System.Data.DataTable cult = StaticDataHelper.Cultures(); string langFile = "english.xml"; foreach (System.Data.DataRow drow in cult.Rows) { if (drow["CultureTag"].ToString() == this.Culture.SelectedValue) { langFile = (string)drow["CultureFile"]; } } if (createUserAndRoles) { // Create new admin users MembershipCreateStatus createStatus; MembershipUser newAdmin = PageContext.CurrentMembership.CreateUser( adminName, adminPassword, adminEmail, adminPasswordQuestion, adminPasswordAnswer, true, null, out createStatus); if (createStatus != MembershipCreateStatus.Success) { PageContext.AddLoadMessage("Create User Failed: {0}".FormatWith(this.GetMembershipErrorMessage(createStatus))); throw new ApplicationException("Create User Failed: {0}".FormatWith(this.GetMembershipErrorMessage(createStatus))); } // Create groups required for the new board RoleMembershipHelper.CreateRole("Administrators"); RoleMembershipHelper.CreateRole("Registered"); // Add new admin users to group RoleMembershipHelper.AddUserToRole(newAdmin.UserName, "Administrators"); // Create Board newBoardID = DB.board_create(newAdmin.UserName, newAdmin.Email, newAdmin.ProviderUserKey, boardName, this.Culture.SelectedItem.Value, langFile, boardMembershipAppName, boardRolesAppName); } else { // new admin MembershipUser newAdmin = UserMembershipHelper.GetUser(); // Create Board newBoardID = DB.board_create(newAdmin.UserName, newAdmin.Email, newAdmin.ProviderUserKey, boardName, this.Culture.SelectedItem.Value, langFile, boardMembershipAppName, boardRolesAppName); } if (newBoardID > 0 && Config.MultiBoardFolders) { // Successfully created the new board string boardFolder = Server.MapPath(Path.Combine(Config.BoardRoot, newBoardID.ToString() + "/")); // Create New Folders. if (!Directory.Exists(Path.Combine(boardFolder, "Images"))) { // Create the Images Folders Directory.CreateDirectory(Path.Combine(boardFolder, "Images")); // Create Sub Folders Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Avatars")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Categories")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Forums")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Emoticons")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Medals")); Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Ranks")); } if (!Directory.Exists(Path.Combine(boardFolder, "Themes"))) { Directory.CreateDirectory(Path.Combine(boardFolder, "Themes")); // Need to copy default theme to the Themes Folder } if (!Directory.Exists(Path.Combine(boardFolder, "Uploads"))) { Directory.CreateDirectory(Path.Combine(boardFolder, "Uploads")); } } // Return application name to as they were before. YafContext.Current.CurrentMembership.ApplicationName = currentMembershipAppName; YafContext.Current.CurrentRoles.ApplicationName = currentRolesAppName; }
/// <summary> /// The create user wizard 1_ next button click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void CreateUserWizard1_NextButtonClick([NotNull] object sender, [NotNull] WizardNavigationEventArgs e) { if (this.CreateUserWizard1.WizardSteps[e.CurrentStepIndex].ID != "profile") { return; } // this is the "Profile Information" step. Save the data to their profile (+ defaults). var timeZones = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("TimeZones"); var country = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("Country"); var locationTextBox = (TextBox)this.CreateUserWizard1.FindWizardControlRecursive("Location"); var homepageTextBox = (TextBox)this.CreateUserWizard1.FindWizardControlRecursive("Homepage"); var dstUser = (CheckBox)this.CreateUserWizard1.FindWizardControlRecursive("DSTUser"); MembershipUser user = UserMembershipHelper.GetUser(this.CreateUserWizard1.UserName); // setup/save the profile YafUserProfile userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName); if (country.SelectedValue != null) { userProfile.Country = country.SelectedValue; } userProfile.Location = locationTextBox.Text.Trim(); userProfile.Homepage = homepageTextBox.Text.Trim(); userProfile.Save(); // save the time zone... int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); LegacyDb.user_save( userID: userId, boardID: this.PageContext.PageBoardID, userName: null, displayName: null, email: null, timeZone: timeZones.SelectedValue.ToType <int>(), languageFile: null, culture: null, themeFile: null, textEditor: null, useMobileTheme: null, approved: null, pmNotification: null, autoWatchTopics: null, dSTUser: dstUser.Checked, hideUser: null, notificationType: null); bool autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, this.Get <YafBoardSettings>().DefaultNotificationSetting, this.Get <YafBoardSettings>().DefaultSendDigestEmail); // Clearing cache with old Active User Lazy Data ... this.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); }
/// <summary> /// The get is user disabled label. /// </summary> /// <param name="userName"> /// The user name. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> protected string GetIsUserDisabledLabel(string userName) { return(UserMembershipHelper.GetUser(userName).IsApproved ? string.Empty : $@"<span class=""badge badge-warning"">{this.GetText("DISABLED")}</span>"); }