/// <summary> /// Creates the facebook user /// </summary> /// <param name="facebookUser"> /// The facebook user. /// </param> /// <param name="userGender"> /// The user gender. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private bool CreateFacebookUser(FacebookUser facebookUser, int userGender, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check user for bot var spamChecker = new YafSpamCheck(); string result; var isPossibleSpamBot = false; var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(); // Check content for spam if (spamChecker.CheckUserForSpamBot(facebookUser.UserName, facebookUser.Email, userIpAddress, out result)) { YafContext.Current.Get <ILogger>().Log( null, "Bot Detected", "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected." .FormatWith(facebookUser.UserName, facebookUser.Email, userIpAddress, result), EventLogTypes.SpamBotDetected); if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot isPossibleSpamBot = true; } else if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2)) { message = YafContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE"); if (!YafContext.Current.Get <YafBoardSettings>().BanBotIpOnDetection) { return(false); } YafContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress), YafContext.Current.PageUserID); // Clear cache YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (YafContext.Current.Get <YafBoardSettings>().LogBannedIP) { YafContext.Current.Get <ILogger>() .Log( null, "IP BAN of Bot During Registration", "A spam Bot who was trying to register was banned by IP {0}".FormatWith( userIpAddress), EventLogTypes.IpBanSet); } return(false); } } MembershipCreateStatus status; var memberShipProvider = YafContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( facebookUser.UserName, pass, facebookUser.Email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out status); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, facebookUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = YafUserProfile.GetProfile(facebookUser.UserName); // setup their initial profile information userProfile.Save(); userProfile.Facebook = facebookUser.ProfileURL; userProfile.FacebookId = facebookUser.UserID; userProfile.Homepage = facebookUser.ProfileURL; if (facebookUser.Birthday.IsSet()) { DateTime userBirthdate; var ci = CultureInfo.CreateSpecificCulture("en-US"); DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out userBirthdate); if (userBirthdate > DateTimeHelper.SqlDbMinTime().Date) { userProfile.Birthday = userBirthdate; } } userProfile.RealName = facebookUser.Name; userProfile.Gender = userGender; if (facebookUser.Location != null && facebookUser.Location.Name.IsSet()) { userProfile.Location = facebookUser.Location.Name; } if (YafContext.Current.Get <YafBoardSettings>().EnableIPInfoService&& this.UserIpLocator == null) { this.UserIpLocator = new IPDetails().GetData( YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(), "text", false, YafContext.Current.CurrentForumPage.Localization.Culture.Name, string.Empty, string.Empty); if (this.UserIpLocator != null && this.UserIpLocator["StatusCode"] == "OK" && this.UserIpLocator.Count > 0) { userProfile.Country = this.UserIpLocator["CountryCode"]; } } userProfile.Save(); // setup their initial profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } if (isPossibleSpamBot) { YafContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } // send user register notification to the user... YafContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_FACEBOOK_REGISTER"); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; YafContext.Current.GetRepository <User>().Save( userID: userId, boardID: YafContext.Current.PageBoardID, userName: facebookUser.UserName, displayName: facebookUser.UserName, email: facebookUser.Email, timeZone: TimeZoneInfo.Local.Id, languageFile: null, culture: null, themeFile: null, textEditor: null, approved: null, pmNotification: YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, autoWatchTopics: autoWatchTopicsEnabled, dSTUser: TimeZoneInfo.Local.SupportsDaylightSavingTime, hideUser: null, notificationType: null); // save the settings... YafContext.Current.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar YafContext.Current.GetRepository <User>().SaveAvatar( userId, "https://graph.facebook.com/v3.3/{0}/picture".FormatWith(facebookUser.UserID), null, null); YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); YafSingleSignOnUser.LoginSuccess(AuthService.facebook, user.UserName, userId, true); message = string.Empty; return(true); }
/// <summary> /// The create users. /// </summary> /// <param name="boardID"> /// The board id. /// </param> /// <param name="_users_Number"> /// The _users_ number. /// </param> /// <param name="_outCounter"> /// The _out counter. /// </param> /// <param name="_countLimit"> /// The _count limit. /// </param> /// <param name="_excludeCurrentBoard"> /// The _exclude current board. /// </param> /// <returns> /// The string with number of created users. /// </returns> private string CreateUsers( int boardID, int _users_Number, int _outCounter, int _countLimit, bool _excludeCurrentBoard) { int iboards; // if ( _users_Number > createCommonLimit ) _users_Number = createCommonLimit; for (iboards = 0; iboards < _countLimit; iboards++) { boardID = this.UsersBoardsList.Items[iboards].Value.ToType <int>(); int i; for (i = 0; i < this.UsersNumber.Text.Trim().ToType <int>(); i++) { this.randomGuid = Guid.NewGuid().ToString(); string newEmail = this.UserPrefixTB.Text.Trim() + this.randomGuid + "@test.info"; string newUsername = this.UserPrefixTB.Text.Trim() + this.randomGuid; if (UserMembershipHelper.UserExists(newUsername, newEmail)) { continue; } string hashinput = DateTime.UtcNow + newEmail + Security.CreatePassword(20); string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5"); MembershipCreateStatus status; MembershipUser user = this.Get <MembershipProvider>().CreateUser( newUsername, this.Password.Text.Trim(), newEmail, this.Question.Text.Trim(), this.Answer.Text.Trim(), !this.Get <YafBoardSettings>().EmailVerification, null, out status); if (status != MembershipCreateStatus.Success) { continue; } // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(boardID, newUsername); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, boardID); // create profile YafUserProfile userProfile = YafUserProfile.GetProfile(newUsername); // setup their inital profile information userProfile.Location = this.Location.Text.Trim(); userProfile.Homepage = this.HomePage.Text.Trim(); userProfile.Save(); // save the time zone... if ( !(this.UsersBoardsList.Items[iboards].Value.ToType <int>() == YafContext.Current.PageBoardID && _excludeCurrentBoard)) { LegacyDb.user_save( LegacyDb.user_get(boardID, user.ProviderUserKey), boardID, null, null, null, this.TimeZones.SelectedValue.ToType <int>(), null, null, null, null, null, null, null, null, null, null, null); _outCounter++; } } } return(_outCounter + " Users in " + iboards + " Board(s); "); }
/// <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 bind data. /// </summary> private void BindData() { MembershipUser user = UserMembershipHelper.GetMembershipUserById(this.UserId); if (user == null || user.ProviderUserKey.ToString() == "0") { YafBuildLink.AccessDenied(/*No such user exists or this is an nntp user ("0") */); } var userData = new CombinedUserDataHelper(user, this.UserId); // populate user information controls... // Is BuddyList feature enabled? if (YafContext.Current.BoardSettings.EnableBuddyList) { this.SetupBuddyList(this.UserId, userData); } else { // BuddyList feature is disabled. don't show any link. this.lnkBuddy.Visible = false; this.ltrApproval.Visible = false; } // Is album feature enabled? if (YafContext.Current.BoardSettings.EnableAlbum) { this.AlbumList1.UserID = this.UserId; } else { this.AlbumList1.Dispose(); } string userDisplayName = this.PageContext.UserDisplayName.GetName(this.UserId); this.SetupUserProfileInfo(this.UserId, user, userData, userDisplayName); this.AddPageLinks(userDisplayName); this.SetupUserStatistics(userData); // private messages this.SetupUserLinks(userData); // localize tab titles... this.LocalizeTabTitles(this.UserId); this.SetupAvatar(this.UserId, userData); this.Groups.DataSource = RoleMembershipHelper.GetRolesForUser(UserMembershipHelper.GetUserNameFromID(this.UserId)); // EmailRow.Visible = PageContext.IsAdmin; this.ProfileTabs.Views["ModerateTab"].Visible = this.PageContext.IsAdmin || this.PageContext.IsForumModerator; this.ProfileTabs.Views["ModerateTab"].Text = this.GetText("MODERATION"); this.AdminUserButton.Visible = this.PageContext.IsAdmin; if (this.LastPosts.Visible) { this.LastPosts.DataSource = DB.post_alluser(this.PageContext.PageBoardID, this.UserId, this.PageContext.PageUserID, 10).AsEnumerable(); this.SearchUser.NavigateUrl = YafBuildLink.GetLinkNotEscaped(ForumPages.search, "postedby={0}", userDisplayName); } this.DataBind(); }
/// <summary> /// The update user profile. /// </summary> /// <param name="userName"> /// The user name. /// </param> private void UpdateUserProfile([NotNull] string userName) { YafUserProfile userProfile = YafUserProfile.GetProfile(userName); userProfile.Country = this.Country.SelectedItem != null ? this.Country.SelectedItem.Value.Trim() : string.Empty; userProfile.Region = this.Region.SelectedItem != null && this.Country.SelectedItem != null && this.Country.SelectedItem.Value.Trim().IsSet() ? this.Region.SelectedItem.Value.Trim() : string.Empty; userProfile.City = this.City.Text.Trim(); userProfile.Location = this.Location.Text.Trim(); userProfile.Homepage = this.HomePage.Text.Trim(); userProfile.MSN = this.MSN.Text.Trim(); userProfile.YIM = this.YIM.Text.Trim(); userProfile.AIM = this.AIM.Text.Trim(); userProfile.ICQ = this.ICQ.Text.Trim(); userProfile.Facebook = this.Facebook.Text.Trim(); userProfile.Twitter = this.Twitter.Text.Trim(); userProfile.Google = this.Google.Text.Trim(); userProfile.XMPP = this.Xmpp.Text.Trim(); userProfile.Skype = this.Skype.Text.Trim(); userProfile.RealName = this.Realname.Text.Trim(); userProfile.Occupation = this.Occupation.Text.Trim(); userProfile.Interests = this.Interests.Text.Trim(); userProfile.Gender = this.Gender.SelectedIndex; userProfile.Blog = this.Weblog.Text.Trim(); DateTime userBirthdate; if (this.Get <YafBoardSettings>().UseFarsiCalender&& this.CurrentCultureInfo.IsFarsiCulture()) { var persianDate = new PersianDate(this.Birthday.Text); userBirthdate = PersianDateConverter.ToGregorianDateTime(persianDate); if (userBirthdate > DateTime.MinValue.Date) { userProfile.Birthday = userBirthdate.Date; } } else { DateTime.TryParse(this.Birthday.Text, this.CurrentCultureInfo, DateTimeStyles.None, out userBirthdate); if (userBirthdate > DateTime.MinValue.Date) { // Attention! This is stored in profile in the user timezone date userProfile.Birthday = userBirthdate.Date; } } userProfile.BlogServiceUrl = this.WeblogUrl.Text.Trim(); userProfile.BlogServiceUsername = this.WeblogUsername.Text.Trim(); userProfile.BlogServicePassword = this.WeblogID.Text.Trim(); try { // Sync to User Profile Mirror table while it's dirty SettingsPropertyValueCollection settingsPropertyValueCollection = userProfile.PropertyValues; LegacyDb.SetPropertyValues( PageContext.PageBoardID, UserMembershipHelper.ApplicationName(), this.currentUserID, settingsPropertyValueCollection); } catch (Exception ex) { this.Logger.Log( "Error while syncinng the User Profile", EventLogTypes.Error, this.PageContext.PageUserName, "Edit User Profile page", ex); } userProfile.Save(); }
/// <summary> /// Do thanks row formatting. /// </summary> private void FormatThanksRow() { if (!this.Get <YafBoardSettings>().EnableThanksMod) { return; } // Register Javascript const string AddThankBoxHTML = "'<a class=\"yaflittlebutton\" href=\"javascript:addThanks(' + res.d.MessageID + ');\" onclick=\"jQuery(this).blur();\" title=' + res.d.Title + '><span>' + res.d.Text + '</span></a>'"; const string RemoveThankBoxHTML = "'<a class=\"yaflittlebutton\" href=\"javascript:removeThanks(' + res.d.MessageID + ');\" onclick=\"jQuery(this).blur();\" title=' + res.d.Title + '><span>' + res.d.Text + '</span></a>'"; var thanksJs = JavaScriptBlocks.AddThanksJs(RemoveThankBoxHTML) + Environment.NewLine + JavaScriptBlocks.RemoveThanksJs(AddThankBoxHTML); YafContext.Current.PageElements.RegisterJsBlockStartup("ThanksJs", thanksJs); this.Thank.Visible = this.PostData.CanThankPost && !this.PageContext.IsGuest && this.Get <YafBoardSettings>().EnableThanksMod; if (Convert.ToBoolean(this.DataRow["IsThankedByUser"])) { this.Thank.NavigateUrl = "javascript:removeThanks({0});".FormatWith(this.DataRow["MessageID"]); this.Thank.TextLocalizedTag = "BUTTON_THANKSDELETE"; this.Thank.TitleLocalizedTag = "BUTTON_THANKSDELETE_TT"; } else { this.Thank.NavigateUrl = "javascript:addThanks({0});".FormatWith(this.DataRow["MessageID"]); this.Thank.TextLocalizedTag = "BUTTON_THANKS"; this.Thank.TitleLocalizedTag = "BUTTON_THANKS_TT"; } var thanksNumber = this.DataRow["MessageThanksNumber"].ToType <int>(); if (thanksNumber == 0) { return; } var username = this.HtmlEncode( this.Get <YafBoardSettings>().EnableDisplayName ? UserMembershipHelper.GetDisplayNameFromID(this.PostData.UserId) : UserMembershipHelper.GetUserNameFromID(this.PostData.UserId)); var thanksLabelText = thanksNumber == 1 ? this.Get <ILocalization>().GetText("THANKSINFOSINGLE").FormatWith(username) : this.Get <ILocalization>().GetText("THANKSINFO").FormatWith(thanksNumber, username); this.ThanksDataLiteral.Text = "<img id=\"ThanksInfoImage{0}\" src=\"{1}\" alt=\"thanks\" runat=\"server\" /> {2}".FormatWith( this.DataRow["MessageID"], this.Get <ITheme>().GetItem("ICONS", "THANKSINFOLIST_IMAGE"), thanksLabelText); this.ThanksDataLiteral.Visible = true; this.thanksDataExtendedLiteral.Text = this.FormatThanksInfo(this.DataRow["ThanksInfo"].ToString()); this.thanksDataExtendedLiteral.Visible = true; }
/// <summary> /// Do thanks row formatting. /// </summary> private void FormatThanksRow() { if (!this.Get <BoardSettings>().EnableThanksMod) { return; } if (this.PostData.PostDeleted || this.PostData.IsLocked) { return; } // Register Javascript var addThankBoxHTML = this.PageContext.IsMobileDevice ? "'<a class=\"btn btn-link\" href=\"javascript:addThanks(' + response.MessageID + ');\" onclick=\"jQuery(this).blur();\" title=' + response.Title + '><span><i class=\"fas fa-heart text-danger fa-fw\"></i></span></a>'" : "'<a class=\"btn btn-link\" href=\"javascript:addThanks(' + response.MessageID + ');\" onclick=\"jQuery(this).blur();\" title=' + response.Title + '><span><i class=\"fas fa-heart text-danger fa-fw\"></i> ' + response.Text + '</span></a>'"; var removeThankBoxHTML = this.PageContext.IsMobileDevice ? "'<a class=\"btn btn-link\" href=\"javascript:removeThanks(' + response.MessageID + ');\" onclick=\"jQuery(this).blur();\" title=' + response.Title + '><span><i class=\"far fa-heart fa-fw\"></i></a>'" : "'<a class=\"btn btn-link\" href=\"javascript:removeThanks(' + response.MessageID + ');\" onclick=\"jQuery(this).blur();\" title=' + response.Title + '><span><i class=\"far fa-heart fa-fw\"></i> ' + response.Text + '</span></a>'"; var thanksJs = "{0}{1}{2}".Fmt( JavaScriptBlocks.AddThanksJs(removeThankBoxHTML), Environment.NewLine, JavaScriptBlocks.RemoveThanksJs(addThankBoxHTML)); this.PageContext.PageElements.RegisterJsBlockStartup("ThanksJs", thanksJs); this.Thank.Visible = this.PostData.CanThankPost && !this.PageContext.IsGuest && this.Get <BoardSettings>().EnableThanksMod; if (this.DataRow.Field <bool>("IsThankedByUser")) { this.Thank.NavigateUrl = $"javascript:removeThanks({this.DataRow["MessageID"]});"; if (!this.PageContext.IsMobileDevice) { this.Thank.Text = this.GetText("BUTTON_THANKSDELETE"); } this.Thank.TitleLocalizedTag = "BUTTON_THANKSDELETE_TT"; this.Thank.Icon = "heart"; this.Thank.IconCssClass = "far"; } else { this.Thank.NavigateUrl = $"javascript:addThanks({this.DataRow["MessageID"]});"; if (!this.PageContext.IsMobileDevice) { this.Thank.Text = this.GetText("BUTTON_THANKS"); } this.Thank.TitleLocalizedTag = "BUTTON_THANKS_TT"; this.Thank.Icon = "heart"; this.Thank.IconCssClass = "fas"; this.Thank.IconColor = "text-danger"; } var thanksNumber = this.DataRow["MessageThanksNumber"].ToType <int>(); if (thanksNumber == 0) { return; } var username = this.HtmlEncode( this.Get <BoardSettings>().EnableDisplayName ? UserMembershipHelper.GetDisplayNameFromID(this.PostData.UserId) : UserMembershipHelper.GetUserNameFromID(this.PostData.UserId)); var thanksLabelText = thanksNumber == 1 ? this.Get <ILocalization>().GetTextFormatted("THANKSINFOSINGLE", username) : this.Get <ILocalization>().GetTextFormatted( "THANKSINFO", thanksNumber, username); this.ThanksDataLiteral.Text = $@"<a class=""btn btn-sm btn-link thanks-popover"" data-toggle=""popover"" data-trigger=""click hover"" data-html=""true"" title=""{thanksLabelText}"" data-content=""{this.FormatThanksInfo(this.DataRow["ThanksInfo"].ToString()).ToJsString()}""> <i class=""fa fa-heart"" style=""color:#e74c3c""></i> +{thanksNumber} </a>"; this.ThanksDataLiteral.Visible = true; }
/// <summary> /// the page load event. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (!this.Get <YafBoardSettings>().EnableAlbum) { YafBuildLink.AccessDenied(); } if (this.IsPostBack) { return; } DataTable sigData = LegacyDb.user_getalbumsdata(this.PageContext.PageUserID, YafContext.Current.PageBoardID); var usrAlbumsAllowed = sigData.GetFirstRowColumnAsValue <int?>("UsrAlbums", null); int[] albumSize = LegacyDb.album_getstats(this.PageContext.PageUserID, null); int userID; switch (this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("a")) { // A new album is being created. check the permissions. case "new": // Is album feature enabled? if (!this.Get <YafBoardSettings>().EnableAlbum) { YafBuildLink.AccessDenied(); } // Has the user created maximum number of albums? if (usrAlbumsAllowed.HasValue && usrAlbumsAllowed > 0) { // Albums count. If we reached limit then we go to info page. if (usrAlbumsAllowed > 0 && (albumSize[0] >= usrAlbumsAllowed)) { YafBuildLink.RedirectInfoPage(InfoMessage.AccessDenied); } } /* if (this.Get<YafBoardSettings>().AlbumsMax > 0 && * albumSize[0] > this.Get<YafBoardSettings>().AlbumsMax - 1) * { * YafBuildLink.RedirectInfoPage(InfoMessage.AccessDenied); * }*/ userID = this.PageContext.PageUserID; break; default: userID = LegacyDb.album_list( null, Security.StringToLongOrRedirect(this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("a"))) .Rows[0]["UserID"].ToType <int>(); if (userID != this.PageContext.PageUserID) { YafBuildLink.AccessDenied(); } break; } var displayName = YafContext.Current.Get <YafBoardSettings>().EnableDisplayName ? UserMembershipHelper.GetDisplayNameFromID(userID) : UserMembershipHelper.GetUserNameFromID(userID); // Add the page links. this.PageLinks.AddRoot(); this.PageLinks.AddLink( displayName, YafBuildLink.GetLink(ForumPages.profile, "u={0}&name={1}", userID.ToString(), displayName)); this.PageLinks.AddLink( this.GetText("ALBUMS"), YafBuildLink.GetLink(ForumPages.albums, "u={0}", userID.ToString())); this.PageLinks.AddLink(this.GetText("TITLE"), string.Empty); this.Back.Text = this.GetText("BACK"); this.Upload.Text = this.GetText("UPLOAD"); this.BindData(); var usrAlbumImagesAllowed = sigData.GetFirstRowColumnAsValue <int?>("UsrAlbumImages", null); // Has the user uploaded maximum number of images? // vzrus: changed for DB check The default number of album images is 0. In the case albums are disabled. if (usrAlbumImagesAllowed.HasValue && usrAlbumImagesAllowed > 0) { if (this.List.Items.Count >= usrAlbumImagesAllowed) { this.uploadtitletr.Visible = false; this.selectfiletr.Visible = false; } else { this.uploadtitletr.Visible = true; this.selectfiletr.Visible = true; } this.imagesInfo.Text = this.GetTextFormatted( "IMAGES_INFO", this.List.Items.Count, usrAlbumImagesAllowed, this.Get <YafBoardSettings>().AlbumImagesSizeMax / 1024); } else { this.uploadtitletr.Visible = false; this.selectfiletr.Visible = false; } }
/// <summary> /// The forum register_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void ForumRegister_Click([NotNull] object sender, [NotNull] EventArgs e) { if (!this.Page.IsValid) { return; } string newEmail = this.Email.Text.Trim(); string newUsername = this.UserName.Text.Trim(); if (!ValidationHelper.IsValidEmail(newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_INVALID_MAIL")); return; } if (UserMembershipHelper.UserExists(this.UserName.Text.Trim(), newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_NAME_EXISTS")); return; } MembershipCreateStatus status; MembershipUser user = this.Get <MembershipProvider>().CreateUser( newUsername, this.Password.Text.Trim(), newEmail, this.Question.Text.Trim(), this.Answer.Text.Trim(), !this.Get <YafBoardSettings>().EmailVerification, null, out status); if (status != MembershipCreateStatus.Success) { // error of some kind this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_ERROR_CREATE").FormatWith(status)); return; } // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, newUsername); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create profile YafUserProfile userProfile = YafUserProfile.GetProfile(newUsername); // setup their inital profile information userProfile.Location = this.Location.Text.Trim(); userProfile.Homepage = this.HomePage.Text.Trim(); userProfile.Save(); // save the time zone... LegacyDb.user_save( UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey), this.PageContext.PageBoardID, null, null, null, this.TimeZones.SelectedValue.ToType <int>(), null, null, null, null, null, null, null, null, null, null, null); if (this.Get <YafBoardSettings>().EmailVerification) { this.SendVerificationEmail(user, newEmail, userID, newUsername); } bool autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting.Equals( UserNotificationSetting.TopicsIPostToOrSubscribeTo); LegacyDb.user_savenotification( UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey), true, autoWatchTopicsEnabled, this.Get <YafBoardSettings>().DefaultNotificationSetting, this.Get <YafBoardSettings>().DefaultSendDigestEmail); // success this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_CREATED").FormatWith(this.UserName.Text.Trim())); YafBuildLink.Redirect(ForumPages.admin_reguser); }
/// <summary> /// Handles the Click event of the ForumRegister 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 ForumRegisterClick([NotNull] object sender, [NotNull] EventArgs e) { this.Page.Validate(); if (!this.Page.IsValid) { return; } var newEmail = this.Email.Text.Trim(); var newUsername = this.UserName.Text.Trim(); if (!ValidationHelper.IsValidEmail(newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_INVALID_MAIL"), MessageTypes.danger); return; } if (UserMembershipHelper.UserExists(this.UserName.Text.Trim(), newEmail)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_REGUSER", "MSG_NAME_EXISTS"), MessageTypes.danger); return; } var user = this.Get <MembershipProvider>().CreateUser( newUsername, this.Password.Text.Trim(), newEmail, this.Question.Text.Trim(), this.Answer.Text.Trim(), !this.Get <BoardSettings>().EmailVerification, null, out var status); if (status != MembershipCreateStatus.Success) { // error of some kind this.PageContext.AddLoadMessage( this.GetTextFormatted("MSG_ERROR_CREATE", status), MessageTypes.danger); return; } // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, newUsername); // create the user in the YAF DB as well as sync roles... var userId = RoleMembershipHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); // create profile var userProfile = Utils.UserProfile.GetProfile(newUsername); // setup their initial profile information userProfile.Location = this.Location.Text.Trim(); userProfile.Homepage = this.HomePage.Text.Trim(); userProfile.Save(); var autoWatchTopicsEnabled = this.Get <BoardSettings>().DefaultNotificationSetting .Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo); // save the time zone... this.GetRepository <User>().Save( UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey), this.PageContext.PageBoardID, null, null, null, this.TimeZones.SelectedValue, null, null, null, null, this.Get <BoardSettings>().DefaultNotificationSetting, autoWatchTopicsEnabled, null, null, null); if (this.Get <BoardSettings>().EmailVerification) { this.Get <ISendNotification>().SendVerificationEmail(user, newEmail, userId, newUsername); } this.GetRepository <User>().SaveNotification( UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey), true, autoWatchTopicsEnabled, this.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), this.Get <BoardSettings>().DefaultSendDigestEmail); // success this.PageContext.AddLoadMessage( this.GetTextFormatted("MSG_CREATED", this.UserName.Text.Trim()), MessageTypes.success); BuildLink.Redirect(ForumPages.Admin_RegisterUser); }
/// <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(((Label)item.FindControl("GroupID")).Text); // get role name var roleName = this.GetRepository <Group>().List(boardId: this.PageContext.PageBoardID, groupId: roleID) .FirstOrDefault().Name; // is user supposed to be in that role? var isChecked = ((CheckBox)item.FindControl("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 permisssions 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> /// Kills the User /// </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 Kill_OnClick([NotNull] object sender, [NotNull] EventArgs e) { var user = UserMembershipHelper.GetMembershipUserById(this.CurrentUserId); // Ban User Email? if (this.BanEmail.Checked) { this.GetRepository <BannedEmail>().Save( null, user.Email, $"Email was reported by: {(this.Get<BoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.CurrentUserData.UserName)}"); } // Ban User IP? if (this.BanIps.Checked && this.IPAddresses.Any()) { this.BanUserIps(); } // Ban User IP? if (this.BanName.Checked) { this.GetRepository <BannedName>().Save( null, user.UserName, $"Name was reported by: {(this.Get<BoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.CurrentUserData.UserName)}"); } this.DeleteAllUserMessages(); if (this.ReportUser.Checked && this.Get <BoardSettings>().StopForumSpamApiKey.IsSet() && this.IPAddresses.Any()) { try { var stopForumSpam = new StopForumSpam(); if (stopForumSpam.ReportUserAsBot(this.IPAddresses.FirstOrDefault(), user.Email, user.UserName)) { this.GetRepository <Registry>().IncrementReportedSpammers(); this.Logger.Log( this.PageContext.PageUserID, "User Reported to StopForumSpam.com", $"User (Name:{user.UserName}/ID:{this.CurrentUserId}/IP:{this.IPAddresses.FirstOrDefault()}/Email:{user.Email}) Reported to StopForumSpam.com by {(this.Get<BoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.CurrentUserData.UserName)}", EventLogTypes.SpamBotReported); } } catch (Exception exception) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITUSER", "BOT_REPORTED_FAILED"), MessageTypes.danger); this.Logger.Log( this.PageContext.PageUserID, $"User (Name{user.UserName}/ID:{this.CurrentUserId}) Report to StopForumSpam.com Failed", exception); } } switch (this.SuspendOrDelete.SelectedValue) { case "delete": if (this.CurrentUserId > 0) { // we are deleting user if (this.PageContext.PageUserID == this.CurrentUserId) { // deleting yourself isn't an option this.PageContext.AddLoadMessage( this.GetText("ADMIN_USERS", "MSG_SELF_DELETE"), MessageTypes.danger); return; } // get user(s) we are about to delete using (var dt = this.GetRepository <User>().ListAsDataTable( this.PageContext.PageBoardID, this.CurrentUserId, DBNull.Value)) { // examine each if he's possible to delete dt.Rows.Cast <DataRow>().ForEach(row => { if (row["IsGuest"].ToType <int>() > 0) { // we cannot delete guest this.PageContext.AddLoadMessage( this.GetText("ADMIN_USERS", "MSG_DELETE_GUEST"), MessageTypes.danger); return; } if ((row["IsAdmin"] == DBNull.Value || row["IsAdmin"].ToType <int>() <= 0) && (row["IsHostAdmin"] == DBNull.Value || row["IsHostAdmin"].ToType <int>() <= 0)) { return; } // admin are not deletable either this.PageContext.AddLoadMessage( this.GetText("ADMIN_USERS", "MSG_DELETE_ADMIN"), MessageTypes.danger); }); } // all is good, user can be deleted UserMembershipHelper.DeleteUser(this.CurrentUserId.ToType <int>()); BuildLink.Redirect(ForumPages.Admin_Users); } break; case "suspend": if (this.CurrentUserId > 0) { this.GetRepository <User>().Suspend( this.CurrentUserId.ToType <int>(), DateTime.UtcNow.AddYears(5)); } break; } this.PageContext.AddLoadMessage( this.GetTextFormatted("MSG_USER_KILLED", user.UserName), MessageTypes.success); // update the displayed data... this.BindData(); }
/// <summary> /// Handles the ItemCommand event of the UserList control. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param> public void UserList_ItemCommand([NotNull] object source, [NotNull] RepeaterCommandEventArgs e) { switch (e.CommandName) { case "edit": YafBuildLink.Redirect(ForumPages.admin_edituser, "u={0}", e.CommandArgument); break; case "delete": string daysValue = this.PageContext.CurrentForumPage.FindControlRecursiveAs <TextBox>("DaysOld").Text.Trim(); if (!ValidationHelper.IsValidInt(daysValue)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_ADMIN", "MSG_VALID_DAYS")); return; } if (!Config.IsAnyPortal) { UserMembershipHelper.DeleteUser(e.CommandArgument.ToType <int>()); } LegacyDb.user_delete(e.CommandArgument); this.Get <ILogger>() .Log( this.PageContext.PageUserID, "YAF.Pages.Admin.admin", "User {0} was deleted by {1}.".FormatWith(e.CommandArgument.ToType <int>(), this.PageContext.PageUserID), EventLogTypes.UserDeleted); this.BindData(); break; case "approve": UserMembershipHelper.ApproveUser(e.CommandArgument.ToType <int>()); this.BindData(); break; case "deleteall": // vzrus: Should not delete the whole providers portal data? Under investigation. string daysValueAll = this.PageContext.CurrentForumPage.FindControlRecursiveAs <TextBox>("DaysOld").Text.Trim(); if (!ValidationHelper.IsValidInt(daysValueAll)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_ADMIN", "MSG_VALID_DAYS")); return; } if (!Config.IsAnyPortal) { UserMembershipHelper.DeleteAllUnapproved(DateTime.UtcNow.AddDays(-daysValueAll.ToType <int>())); } LegacyDb.user_deleteold(this.PageContext.PageBoardID, daysValueAll.ToType <int>()); this.BindData(); break; case "approveall": UserMembershipHelper.ApproveAll(); // vzrus: Should delete users from send email list LegacyDb.user_approveall(this.PageContext.PageBoardID); this.BindData(); break; } }
/// <summary> /// Gets the forum user info as JSON string for the hover cards /// </summary> /// <param name="context">The context.</param> public void GetUserInfo([NotNull] HttpContext context) { try { var userId = context.Request.QueryString.GetFirstOrDefaultAs <int>("userinfo"); var boardId = context.Request.QueryString.GetFirstOrDefaultAs <int>("boardId"); var user = UserMembershipHelper.GetMembershipUserById(userId, boardId); if (user == null || user.ProviderUserKey.ToString() == "0") { context.Response.Write( "Error: Resource has been moved or is unavailable. Please contact the forum admin."); return; } // Check if user has access if (!this.Get <IPermissions>().Check(this.Get <BoardSettings>().ProfileViewPermissions)) { context.Response.Write(string.Empty); return; } var userData = new CombinedUserDataHelper(user, userId); context.Response.Clear(); context.Response.ContentType = "application/json"; context.Response.ContentEncoding = Encoding.UTF8; context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetExpires( System.DateTime.UtcNow.AddMilliseconds(BoardContext.Current.Get <BoardSettings>().OnlineStatusCacheTimeout)); context.Response.Cache.SetLastModified(System.DateTime.UtcNow); var avatarUrl = this.Get <IAvatars>().GetAvatarUrlForUser(userId); avatarUrl = avatarUrl.IsNotSet() ? $"{BoardInfo.ForumClientFileRoot}images/noavatar.svg" : avatarUrl; var activeUsers = this.Get <IDataCache>().GetOrSet( Constants.Cache.UsersOnlineStatus, () => this.Get <DataBroker>().GetActiveList( false, BoardContext.Current.Get <BoardSettings>().ShowCrawlersInActiveList), TimeSpan.FromMilliseconds(BoardContext.Current.Get <BoardSettings>().OnlineStatusCacheTimeout)); var userIsOnline = activeUsers.AsEnumerable().Any( x => x.Field <int>("UserId").Equals(userId) && !x.Field <bool>("IsHidden")); var userName = this.Get <BoardSettings>().EnableDisplayName ? userData.DisplayName : userData.UserName; userName = HttpUtility.HtmlEncode(userName); var location = userData.Profile.Country.IsSet() ? BoardContext.Current.Get <IHaveLocalization>().GetText( "COUNTRY", userData.Profile.Country.Trim()) : userData.Profile.Location; if (userData.Profile.Region.IsSet() && userData.Profile.Country.IsSet()) { var tag = $"RGN_{userData.Profile.Country.Trim()}_{userData.Profile.Region}"; location += $", {this.Get<IHaveLocalization>().GetText("REGION", tag)}"; } var userInfo = new ForumUserInfo { Name = userName, RealName = HttpUtility.HtmlEncode(userData.Profile.RealName), Avatar = avatarUrl, Interests = HttpUtility.HtmlEncode(userData.Profile.Interests), HomePage = userData.Profile.Homepage, Posts = $"{userData.NumPosts:N0}", Rank = userData.RankName, Location = location, Joined = $"{this.Get<IHaveLocalization>().GetText("PROFILE", "JOINED")} {this.Get<IDateTime>().FormatDateLong(userData.Joined)}", Online = userIsOnline/*, * ProfileLink = BuildLink.GetLink(ForumPages.Profile, true, "u={0}&name={1}", userId, userName)*/ }; if (BoardContext.Current.Get <BoardSettings>().EnableUserReputation) { userInfo.Points = (userData.Points.ToType <int>() > 0 ? "+" : string.Empty) + userData.Points; } context.Response.Write(userInfo.ToJson()); HttpContext.Current.ApplicationInstance.CompleteRequest(); } catch (Exception x) { this.Get <ILogger>().Log(BoardContext.Current.PageUserID, this, x, EventLogTypes.Information); context.Response.Write( "Error: Resource has been moved or is unavailable. Please contact the forum admin."); } }
/// <summary> /// Verifies the message allowed. /// </summary> /// <param name="count">The recipients count.</param> /// <param name="message">The message.</param> /// <returns> /// Returns if the user is allowed to send a message or not /// </returns> private bool VerifyMessageAllowed(int count, string message) { // Check if SPAM Message first... if (!this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess && !this.Get <YafBoardSettings>().SpamServiceType.Equals(0)) { string spamResult; // Check content for spam if (this.Get <ISpamCheck>().CheckPostForSpam( this.PageContext.IsGuest ? "Guest" : this.PageContext.PageUserName, YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(), message, this.PageContext.User.Email, out spamResult)) { switch (this.Get <YafBoardSettings>().SpamMessageHandling) { case 0: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", string .Format( "Spam Check detected possible SPAM ({1}) posted by User: {0}", this.PageContext.PageUserName, spamResult), EventLogTypes.SpamMessageDetected); break; case 1: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", string .Format( "Spam Check detected possible SPAM ({1}) posted by User: {0}, it was flagged as unapproved post", this.PageContext.PageUserName, spamResult), EventLogTypes.SpamMessageDetected); break; case 2: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", string .Format( "Spam Check detected possible SPAM ({1}) posted by User: {0}, post was rejected", this.PageContext.PageUserName, spamResult), EventLogTypes.SpamMessageDetected); this.PageContext.AddLoadMessage(this.GetText("SPAM_MESSAGE"), MessageTypes.danger); break; case 3: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", string .Format( "Spam Check detected possible SPAM ({1}) posted by User: {0}, user was deleted and bannded", this.PageContext.PageUserName, spamResult), EventLogTypes.SpamMessageDetected); var userIp = new CombinedUserDataHelper( this.PageContext.CurrentUserData.Membership, this.PageContext.PageUserID).LastIP; UserMembershipHelper.DeleteAndBanUser( this.PageContext.PageUserID, this.PageContext.CurrentUserData.Membership, userIp); break; } return(false); } // Check posts for urls if the user has only x posts if (YafContext.Current.CurrentUserData.NumPosts <= YafContext.Current.Get <YafBoardSettings>().IgnoreSpamWordCheckPostCount&& !this.PageContext.IsAdmin && !this.PageContext.ForumModeratorAccess) { var urlCount = UrlHelper.CountUrls(message); if (urlCount > this.PageContext.BoardSettings.AllowedNumberOfUrls) { spamResult = $"The user posted {urlCount} urls but allowed only {this.PageContext.BoardSettings.AllowedNumberOfUrls}"; switch (this.Get <YafBoardSettings>().SpamMessageHandling) { case 0: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", string.Format( "Spam Check detected possible SPAM ({1}) posted by User: {0}", this.PageContext.PageUserName, spamResult), EventLogTypes.SpamMessageDetected); break; case 1: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", string .Format( "Spam Check detected possible SPAM ({1}) posted by User: {0}, it was flagged as unapproved post", this.PageContext.IsGuest ? "Guest" : this.PageContext.PageUserName, spamResult), EventLogTypes.SpamMessageDetected); break; case 2: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", string .Format( "Spam Check detected possible SPAM ({1}) posted by User: {0}, post was rejected", this.PageContext.PageUserName, spamResult), EventLogTypes.SpamMessageDetected); this.PageContext.AddLoadMessage(this.GetText("SPAM_MESSAGE"), MessageTypes.danger); break; case 3: this.Logger.Log( this.PageContext.PageUserID, "Spam Message Detected", string .Format( "Spam Check detected possible SPAM ({1}) posted by User: {0}, user was deleted and bannded", this.PageContext.PageUserName, spamResult), EventLogTypes.SpamMessageDetected); var userIp = new CombinedUserDataHelper( this.PageContext.CurrentUserData.Membership, this.PageContext.PageUserID).LastIP; UserMembershipHelper.DeleteAndBanUser( this.PageContext.PageUserID, this.PageContext.CurrentUserData.Membership, userIp); break; } return(false); } } return(true); } /////////////////////////////// // test sending user's PM count // get user's name var drPMInfo = this.GetRepository <PMessage>().UserMessageCount(YafContext.Current.PageUserID).Rows[0]; if (drPMInfo["NumberTotal"].ToType <int>() + count <= drPMInfo["NumberAllowed"].ToType <int>() || YafContext.Current.IsAdmin) { return(true); } // user has full PM box YafContext.Current.AddLoadMessage( this.GetTextFormatted("OWN_PMBOX_FULL", drPMInfo["NumberAllowed"]), MessageTypes.danger); return(false); }
/// <summary> /// Kills the User /// </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 Kill_OnClick([NotNull] object sender, [NotNull] EventArgs e) { var user = UserMembershipHelper.GetMembershipUserById(this.CurrentUserID); // Ban User Email? if (this.BanEmail.Checked) { this.GetRepository <BannedEmail>() .Save( null, user.Email, "Email was reported by: {0}".FormatWith( this.Get <YafBoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.CurrentUserData.UserName)); } // Ban User IP? if (this.BanIps.Checked && this.IPAddresses.Any()) { this.BanUserIps(); } // Ban User IP? if (this.BanName.Checked) { this.GetRepository <BannedName>() .Save( null, user.UserName, "Name was reported by: {0}".FormatWith( this.Get <YafBoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.CurrentUserData.UserName)); } this.DeleteAllUserMessages(); if (this.ReportUser.Checked && this.Get <YafBoardSettings>().StopForumSpamApiKey.IsSet() && this.IPAddresses.Any()) { try { var stopForumSpam = new StopForumSpam(); if (!stopForumSpam.ReportUserAsBot(this.IPAddresses.FirstOrDefault(), user.Email, user.UserName)) { this.Logger.Log( this.PageContext.PageUserID, "User Reported to StopForumSpam.com", "User (Name:{0}/ID:{1}/IP:{2}/Email:{3}) Reported to StopForumSpam.com by {4}".FormatWith( user.UserName, this.CurrentUserID, this.IPAddresses.FirstOrDefault(), user.Email, this.Get <YafBoardSettings>().EnableDisplayName ? this.PageContext.CurrentUserData.DisplayName : this.PageContext.CurrentUserData.UserName), EventLogTypes.SpamBotReported); } } catch (Exception exception) { this.PageContext.AddLoadMessage( this.GetText("ADMIN_EDITUSER", "BOT_REPORTED_FAILED"), MessageTypes.Error); this.Logger.Log( this.PageContext.PageUserID, "User (Name{0}/ID:{1}) Report to StopForumSpam.com Failed".FormatWith( user.UserName, this.CurrentUserID), exception); } } switch (this.SuspendOrDelete.SelectedValue) { case "delete": if (this.CurrentUserID > 0) { // we are deleting user if (this.PageContext.PageUserID == this.CurrentUserID) { // deleting yourself isn't an option this.PageContext.AddLoadMessage( this.GetText("ADMIN_USERS", "MSG_SELF_DELETE"), MessageTypes.Error); return; } // get user(s) we are about to delete using ( DataTable dt = LegacyDb.user_list( this.PageContext.PageBoardID, this.CurrentUserID, DBNull.Value)) { // examine each if he's possible to delete foreach (DataRow row in dt.Rows) { if (row["IsGuest"].ToType <int>() > 0) { // we cannot detele guest this.PageContext.AddLoadMessage( this.GetText("ADMIN_USERS", "MSG_DELETE_GUEST"), MessageTypes.Error); return; } if ((row["IsAdmin"] == DBNull.Value || row["IsAdmin"].ToType <int>() <= 0) && (row["IsHostAdmin"] == DBNull.Value || row["IsHostAdmin"].ToType <int>() <= 0)) { continue; } // admin are not deletable either this.PageContext.AddLoadMessage( this.GetText("ADMIN_USERS", "MSG_DELETE_ADMIN"), MessageTypes.Error); return; } } // all is good, user can be deleted UserMembershipHelper.DeleteUser(this.CurrentUserID.ToType <int>()); YafBuildLink.Redirect(ForumPages.admin_users); } break; case "suspend": if (this.CurrentUserID > 0) { LegacyDb.user_suspend(this.CurrentUserID, DateTime.UtcNow.AddYears(5)); } break; } this.PageContext.AddLoadMessage( this.Get <ILocalization>().GetText("ADMIN_EDITUSER", "MSG_USER_KILLED").FormatWith(user.UserName)); // update the displayed data... this.BindData(); }
/// <summary> /// The render. /// </summary> /// <param name="output"> /// The output. /// </param> protected override void Render([NotNull] HtmlTextWriter output) { var displayName = this.ReplaceName.IsNotSet() ? this.Get <IUserDisplayName>().GetName(this.UserID) : this.ReplaceName; if (this.UserID == -1 || !displayName.IsSet()) { return; } // is this the guest user? If so, guest's don't have a profile. var isGuest = this.IsGuest ? this.IsGuest : UserMembershipHelper.IsGuestUser(this.UserID); output.BeginRender(); if (!isGuest) { output.WriteBeginTag("a"); output.WriteAttribute("href", YafBuildLink.GetLink(ForumPages.profile, "u={0}", this.UserID)); if (this.CanViewProfile && this.IsHoverCardEnabled) { if (this.CssClass.IsSet()) { this.CssClass += " userHoverCard"; } else { this.CssClass = "userHoverCard"; } output.WriteAttribute( "data-hovercard", "{0}resource.ashx?userinfo={1}&type=json&forumUrl={2}".FormatWith( YafForumInfo.ForumClientFileRoot, this.UserID, HttpUtility.UrlEncode(YafBuildLink.GetBasePath()))); } else { output.WriteAttribute("title", this.GetText("COMMON", "VIEW_USRPROFILE")); } if (this.Get <YafBoardSettings>().UseNoFollowLinks) { output.WriteAttribute("rel", "nofollow"); } if (this.BlankTarget) { output.WriteAttribute("target", "_blank"); } } else { output.WriteBeginTag("span"); } this.RenderMainTagAttributes(output); output.Write(HtmlTextWriter.TagRightChar); // Replace Name with Crawler Name if Set, otherwise use regular display name or Replace Name if set if (this.CrawlerName.IsSet()) { output.WriteEncodedText(this.CrawlerName); } else if (!this.CrawlerName.IsSet() && this.ReplaceName.IsSet() && isGuest) { output.WriteEncodedText(this.ReplaceName); } else { output.WriteEncodedText(displayName); } output.WriteEndTag(!isGuest ? "a" : "span"); if (this.PostfixText.IsSet()) { output.Write(this.PostfixText); } output.EndRender(); }
/// <summary> /// A method to get album path string. /// </summary> /// <param name="forumPageAttributes"> /// A page query string cleared from page name. /// </param> /// <returns> /// The string /// </returns> private string Album([NotNull] string forumPageAttributes) { string outstring = string.Empty; string userID = forumPageAttributes.Substring(forumPageAttributes.IndexOf("u=") + 2).Trim(); if (userID.Contains("&")) { userID = userID.Substring(0, userID.IndexOf("&")).Trim(); } string albumID = forumPageAttributes.Substring(forumPageAttributes.IndexOf("a=") + 2); albumID = albumID.Contains("&") ? albumID.Substring(0, albumID.IndexOf("&")).Trim() : albumID.Substring(0).Trim(); if (ValidationHelper.IsValidInt(userID) && ValidationHelper.IsValidInt(albumID)) { // The DataRow should not be missing in the case DataRow dr = LegacyDb.album_list(null, albumID.Trim().ToType <int>()).Rows[0]; // If album doesn't have a Title, use his ID. string albumName = !string.IsNullOrEmpty(dr["Title"].ToString()) ? dr["Title"].ToString() : dr["AlbumID"].ToString(); // Render if (userID.ToType <int>() != this.UserID) { var displayName = HttpUtility.HtmlEncode(UserMembershipHelper.GetDisplayNameFromID(userID.ToType <long>())); if (displayName.IsNotSet()) { displayName = HttpUtility.HtmlEncode(UserMembershipHelper.GetUserNameFromID(userID.ToType <long>())); } outstring += this.GetText("ACTIVELOCATION", "ALBUM").FormatWith(); outstring += @"<a href=""{0}"" id=""uiseralbumid_{1}"" runat=""server""> {2} </a>".FormatWith( YafBuildLink.GetLink(ForumPages.album, "a={0}", albumID), userID + this.PageContext.PageUserID, HttpUtility.HtmlEncode(albumName)); outstring += this.GetText("ACTIVELOCATION", "ALBUM_OFUSER").FormatWith(); outstring += @"<a href=""{0}"" id=""albumuserid_{1}"" runat=""server""> {2} </a>".FormatWith( YafBuildLink.GetLink(ForumPages.profile, "u={0}&name={1}", userID, displayName), userID, HttpUtility.HtmlEncode(displayName)); } else { outstring += this.GetText("ACTIVELOCATION", "ALBUM_OWN").FormatWith(); outstring += @"<a href=""{0}"" id=""uiseralbumid_{1}"" runat=""server""> {2} </a>".FormatWith( YafBuildLink.GetLink(ForumPages.album, "a={0}", albumID), userID + this.PageContext.PageUserID, HttpUtility.HtmlEncode(albumName)); } } else { outstring += this.GetText("ACTIVELOCATION", "ALBUM").FormatWith(); } return(outstring); }
/// <summary> /// The on pre render. /// </summary> /// <param name="e"> /// The e. /// </param> protected override void OnPreRender(EventArgs e) { if (this.PageContext.IsGuest) { this.ShowHideIgnoredUserPost.Visible = false; this.MessageRow.CssClass = "collapse show"; } else if (this.Get <IUserIgnored>().IsIgnored(this.PostData.UserId)) { this.MessageRow.CssClass = "collapse"; this.ShowHideIgnoredUserPost.Visible = true; } else if (!this.Get <IUserIgnored>().IsIgnored(this.PostData.UserId)) { this.MessageRow.CssClass = "collapse show"; } this.Edit.Visible = this.Edit2.Visible = !this.PostData.PostDeleted && this.PostData.CanEditPost && !this.PostData.IsLocked; this.Edit.NavigateUrl = this.Edit2.NavigateUrl = BuildLink.GetLinkNotEscaped( ForumPages.PostMessage, "m={0}", this.PostData.MessageId); this.MovePost.Visible = this.Move.Visible = this.PageContext.ForumModeratorAccess && !this.PostData.IsLocked; this.MovePost.NavigateUrl = this.Move.NavigateUrl = BuildLink.GetLinkNotEscaped( ForumPages.MoveMessage, "m={0}", this.PostData.MessageId); this.Delete.Visible = this.Delete2.Visible = !this.PostData.PostDeleted && this.PostData.CanDeletePost && !this.PostData.IsLocked; this.Delete.NavigateUrl = this.Delete2.NavigateUrl = BuildLink.GetLinkNotEscaped( ForumPages.DeleteMessage, "m={0}&action=delete", this.PostData.MessageId); this.UnDelete.Visible = this.UnDelete2.Visible = this.PostData.CanUnDeletePost && !this.PostData.IsLocked; this.UnDelete.NavigateUrl = this.UnDelete2.NavigateUrl = BuildLink.GetLinkNotEscaped( ForumPages.DeleteMessage, "m={0}&action=undelete", this.PostData.MessageId); this.Quote.Visible = this.Quote2.Visible = this.Reply.Visible = this.ReplyFooter.Visible = this.QuickReplyLink.Visible = !this.PostData.PostDeleted && this.PostData.CanReply && !this.PostData.IsLocked; if (!this.PostData.PostDeleted && this.PostData.CanReply && !this.PostData.IsLocked) { this.ContextMenu.Attributes.Add( "data-url", BuildLink.GetLinkNotEscaped( ForumPages.PostMessage, "t={0}&f={1}", this.PageContext.PageTopicID, this.PageContext.PageForumID)); this.ContextMenu.Attributes.Add( "data-quote", this.GetText("COMMON", "SELECTED_QUOTE")); } this.ContextMenu.Attributes.Add( "data-search", this.GetText("COMMON", "SELECTED_SEARCH")); if (!this.PageContext.IsMobileDevice) { this.Quote.Text = this.GetText("BUTTON_QUOTE_TT"); this.ReplyFooter.Text = this.GetText("REPLY"); } this.MultiQuote.Visible = !this.PostData.PostDeleted && this.PostData.CanReply && !this.PostData.IsLocked; this.Quote.NavigateUrl = this.Quote2.NavigateUrl = BuildLink.GetLinkNotEscaped( ForumPages.PostMessage, "t={0}&f={1}&q={2}", this.PageContext.PageTopicID, this.PageContext.PageForumID, this.PostData.MessageId); this.Reply.NavigateUrl = this.ReplyFooter.NavigateUrl = BuildLink.GetLinkNotEscaped( ForumPages.PostMessage, "t={0}&f={1}", this.PageContext.PageTopicID, this.PageContext.PageForumID); if (this.MultiQuote.Visible) { this.MultiQuote.Attributes.Add( "onclick", $"handleMultiQuoteButton(this, '{this.PostData.MessageId}', '{this.PostData.TopicId}')"); BoardContext.Current.PageElements.RegisterJsBlockStartup( "MultiQuoteButtonJs", JavaScriptBlocks.MultiQuoteButtonJs); BoardContext.Current.PageElements.RegisterJsBlockStartup( "MultiQuoteCallbackSuccessJS", JavaScriptBlocks.MultiQuoteCallbackSuccessJs); var icon = new Icon { IconName = "quote-left", IconNameBadge = "plus" }; this.MultiQuote.Text = this.PageContext.IsMobileDevice ? icon.RenderToString() : $"{icon.RenderToString()} {this.GetText("BUTTON_MULTI_QUOTE")}"; this.MultiQuote.ToolTip = this.GetText("BUTTON_MULTI_QUOTE_TT"); } if (this.Get <BoardSettings>().EnableUserReputation) { this.AddReputationControls(); } if (this.Edit.Visible || this.Delete.Visible || this.MovePost.Visible) { this.ManageDropPlaceHolder.Visible = true; } else { this.ManageDropPlaceHolder.Visible = false; } BoardContext.Current.PageElements.RegisterJsBlockStartup( "asynchCallFailedJs", "function CallFailed(res){console.log(res); }"); this.FormatThanksRow(); this.ShowIpInfo(); this.panMessage.CssClass = "col"; var userId = this.PostData.UserId; var avatarUrl = this.Get <IAvatars>().GetAvatarUrlForUser(userId); var displayName = this.Get <BoardSettings>().EnableDisplayName ? UserMembershipHelper.GetDisplayNameFromID(userId) : UserMembershipHelper.GetUserNameFromID(userId); if (avatarUrl.IsSet()) { this.Avatar.Visible = true; this.Avatar.AlternateText = displayName; this.Avatar.ToolTip = displayName; this.Avatar.ImageUrl = avatarUrl; } else { this.Avatar.Visible = false; } // report post if (this.Get <IPermissions>().Check(this.Get <BoardSettings>().ReportPostPermissions) && !this.PostData.PostDeleted) { if (!this.PageContext.IsGuest && this.PageContext.User != null) { this.ReportPost.Visible = this.ReportPost2.Visible = true; this.ReportPost.NavigateUrl = this.ReportPost2.NavigateUrl = BuildLink.GetLinkNotEscaped( ForumPages.ReportPost, "m={0}", this.PostData.MessageId); } } // mark post as answer if (!this.PostData.PostDeleted && !this.PageContext.IsGuest && this.PageContext.User != null && this.PageContext.PageUserID.Equals(this.DataRow["TopicOwnerID"].ToType <int>()) && !this.PostData.UserId.Equals(this.PageContext.PageUserID)) { this.MarkAsAnswer.Visible = true; if (this.PostData.PostIsAnswer) { this.MarkAsAnswer.TextLocalizedTag = "MARK_ANSWER_REMOVE"; this.MarkAsAnswer.TitleLocalizedTag = "MARK_ANSWER_REMOVE_TITLE"; this.MarkAsAnswer.Icon = "minus-square"; this.MarkAsAnswer.IconColor = "text-danger"; } else { this.MarkAsAnswer.TextLocalizedTag = "MARK_ANSWER"; this.MarkAsAnswer.TitleLocalizedTag = "MARK_ANSWER_TITLE"; this.MarkAsAnswer.Icon = "check-square"; this.MarkAsAnswer.IconColor = "text-success"; } } if (this.ReportPost.Visible == false && this.MarkAsAnswer.Visible == false && this.ReportPost.Visible == false && this.ManageDropPlaceHolder.Visible == false) { this.ToolsHolder.Visible = false; } if (this.ThanksDataLiteral.Visible == false && this.Thank.Visible == false && this.Quote.Visible == false && this.MultiQuote.Visible == false) { this.Footer.Visible = false; } base.OnPreRender(e); }
/// <summary> /// Creates the Google user /// </summary> /// <param name="googleUser">The Google user.</param> /// <param name="userGender">The user gender.</param> /// <param name="message">The message.</param> /// <returns> /// Returns if the login was successfully or not /// </returns> private bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } MembershipCreateStatus status; var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); MembershipUser user = YafContext.Current.Get <MembershipProvider>() .CreateUser( googleUser.UserName, pass, googleUser.Email, "Answer is a generated Pass", securityAnswer, true, null, out status); // setup inital roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, googleUser.UserName); // create the user in the YAF DB as well as sync roles... int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one YafUserProfile userProfile = YafUserProfile.GetProfile(googleUser.UserName); userProfile.Google = googleUser.ProfileURL; userProfile.GoogleId = googleUser.UserID; userProfile.Homepage = googleUser.ProfileURL; userProfile.Gender = userGender; userProfile.Save(); // setup their inital profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafSingleSignOnUser.SendRegistrationNotificationEmail(user); } // send user register notification to the user... YafContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER"); // TODO : LOCALIZE // save the time zone... int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); LegacyDb.user_save( userId, YafContext.Current.PageBoardID, googleUser.UserName, googleUser.UserName, googleUser.Email, 0, null, null, true, null, null, null, null, null, null, null, null); bool autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar LegacyDb.user_saveavatar(userId, googleUser.ProfileImage, null, null); YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); YafSingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true); message = string.Empty; return(true); }
/// <summary> /// Creates the Google user /// </summary> /// <param name="googleUser"> /// The Google user. /// </param> /// <param name="userGender"> /// The user gender. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private static bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message) { if (BoardContext.Current.Get <BoardSettings>().DisableRegistrations) { message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check user for bot var isPossibleSpamBot = false; var userIpAddress = BoardContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(); // Check content for spam if (BoardContext.Current.Get <ISpamCheck>().CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out var result)) { BoardContext.Current.Get <ILogger>().Log( null, "Bot Detected", $"Bot Check detected a possible SPAM BOT: (user name : '{googleUser.UserName}', email : '{googleUser.Email}', ip: '{userIpAddress}', reason : {result}), user was rejected.", EventLogTypes.SpamBotDetected); if (BoardContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot isPossibleSpamBot = true; } else if (BoardContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(2)) { message = BoardContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE"); if (!BoardContext.Current.Get <BoardSettings>().BanBotIpOnDetection) { return(false); } BoardContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, $"A spam Bot who was trying to register was banned by IP {userIpAddress}", BoardContext.Current.PageUserID); // Clear cache BoardContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (BoardContext.Current.Get <BoardSettings>().LogBannedIP) { BoardContext.Current.Get <ILogger>() .Log( null, "IP BAN of Bot During Registration", $"A spam Bot who was trying to register was banned by IP {userIpAddress}", EventLogTypes.IpBanSet); } return(false); } } var memberShipProvider = BoardContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( googleUser.UserName, pass, googleUser.Email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out var status); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, googleUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, BoardContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = YafUserProfile.GetProfile(googleUser.UserName); // setup their initial profile information userProfile.Save(); userProfile.GoogleId = googleUser.UserID; userProfile.Homepage = googleUser.ProfileURL; userProfile.Gender = userGender; if (BoardContext.Current.Get <BoardSettings>().EnableIPInfoService) { var userIpLocator = BoardContext.Current.Get <IIpInfoService>().GetUserIpLocator(); if (userIpLocator != null) { userProfile.Country = userIpLocator["CountryCode"]; var location = new StringBuilder(); if (userIpLocator["RegionName"] != null && userIpLocator["RegionName"].IsSet() && !userIpLocator["RegionName"].Equals("-")) { location.Append(userIpLocator["RegionName"]); } if (userIpLocator["CityName"] != null && userIpLocator["CityName"].IsSet() && !userIpLocator["CityName"].Equals("-")) { location.AppendFormat(", {0}", userIpLocator["CityName"]); } userProfile.Location = location.ToString(); } } userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (BoardContext.Current.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... BoardContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } if (isPossibleSpamBot) { BoardContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } // send user register notification to the user... BoardContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER"); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); var autoWatchTopicsEnabled = BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; BoardContext.Current.GetRepository <User>().Save( userId, BoardContext.Current.PageBoardID, googleUser.UserName, googleUser.UserName, googleUser.Email, TimeZoneInfo.Local.Id, null, null, null, null, BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting, autoWatchTopicsEnabled, TimeZoneInfo.Local.SupportsDaylightSavingTime, null, null); // save the settings... BoardContext.Current.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting.ToInt(), BoardContext.Current.Get <BoardSettings>().DefaultSendDigestEmail); // save avatar BoardContext.Current.GetRepository <User>().SaveAvatar(userId, googleUser.ProfileImage, null, null); BoardContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); SingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true); message = string.Empty; return(true); }
/// <summary> /// Called when the page loads /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.IsPostBack) { return; } string umhdn = UserMembershipHelper.GetDisplayNameFromID(this.UserID); this.AlbumHeaderLabel.Param0 = this.Get <YafBoardSettings>().EnableDisplayName ? this.HtmlEncode(umhdn) : this.HtmlEncode(UserMembershipHelper.GetUserNameFromID(this.UserID)); this.BindData(); HttpContext.Current.Session["imagePreviewWidth"] = this.Get <YafBoardSettings>().ImageAttachmentResizeWidth; HttpContext.Current.Session["imagePreviewHeight"] = this.Get <YafBoardSettings>().ImageAttachmentResizeHeight; HttpContext.Current.Session["imagePreviewCropped"] = this.Get <YafBoardSettings>().ImageAttachmentResizeCropped; HttpContext.Current.Session["localizationFile"] = this.Get <ILocalization>().LanguageFileName; // Show Albums Max Info if (this.UserID == this.PageContext.PageUserID) { this.albumsInfo.Text = this.Get <ILocalization>().GetTextFormatted( "ALBUMS_INFO", this.PageContext.NumAlbums, this.PageContext.UsrAlbums); if (this.PageContext.UsrAlbums > this.PageContext.NumAlbums) { this.AddAlbum.Visible = true; } this.albumsInfo.Text = this.PageContext.UsrAlbums > 0 ? this.Get <ILocalization>().GetTextFormatted( "ALBUMS_INFO", this.PageContext.NumAlbums, this.PageContext.UsrAlbums) : this.Get <ILocalization>().GetText("ALBUMS_NOTALLOWED"); this.albumsInfo.Visible = true; } // vzrus: used if someone moderates usuful if a moderation is implemented /* else * { * DataTable sigData = LegacyDb.user_getalbumsdata(this.PageContext.PageUserID, YafContext.Current.PageBoardID); * DataTable usrAlbumsData = LegacyDb.user_getalbumsdata(this.PageContext.PageUserID, YafContext.Current.PageBoardID); * var allowedAlbums = usrAlbumsData.GetFirstRowColumnAsValue<int?>("UsrAlbums", null); * var numAlbums = usrAlbumsData.GetFirstRowColumnAsValue<int?>("NumAlbums", null); * * if (allowedAlbums.HasValue && allowedAlbums > 0 && numAlbums < allowedAlbums) * { * this.AddAlbum.Visible = true; * } * * this.albumsInfo.Visible = false; * } */ if (this.AddAlbum.Visible) { this.AddAlbum.Text = this.Get <ILocalization>().GetText("BUTTON", "BUTTON_ADDALBUM"); } }
/// <summary> /// Saves the Updated Profile /// </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 UpdateProfile_Click([NotNull] object sender, [NotNull] EventArgs e) { var userName = UserMembershipHelper.GetUserNameFromID(this.currentUserID); if (this.HomePage.Text.IsSet()) { // add http:// by default if (!Regex.IsMatch(this.HomePage.Text.Trim(), @"^(http|https|ftp|ftps|git|svn|news)\://.*")) { this.HomePage.Text = "http://{0}".FormatWith(this.HomePage.Text.Trim()); } if (!ValidationHelper.IsValidURL(this.HomePage.Text)) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_HOME"), MessageTypes.Warning); return; } // Check for spam string result; if (this.Get <ISpamWordCheck>().CheckForSpamWord(this.HomePage.Text, out result)) { // Log and Send Message to Admins if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { this.Logger.Log( null, "Bot Detected", "Internal Spam Word Check detected a SPAM BOT: (user name : '{0}', user id : '{1}') after the user changed the profile Homepage url to: {2}" .FormatWith(userName, this.currentUserID, this.HomePage.Text), EventLogTypes.SpamBotDetected); } else if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2)) { this.Logger.Log( null, "Bot Detected", "Internal Spam Word Check detected a SPAM BOT: (user name : '{0}', user id : '{1}') after the user changed the profile Homepage url to: {2}, user was deleted and the name, email and IP Address are banned." .FormatWith(userName, this.currentUserID, this.HomePage.Text), EventLogTypes.SpamBotDetected); // Kill user if (!this.adminEditMode) { var user = UserMembershipHelper.GetMembershipUserById(this.currentUserID); var userId = this.currentUserID; var userIp = new CombinedUserDataHelper(user, userId).LastIP; UserMembershipHelper.DeleteAndBanUser(this.currentUserID, user, userIp); } } } } if (this.Weblog.Text.IsSet() && !ValidationHelper.IsValidURL(this.Weblog.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_WEBLOG"), MessageTypes.Warning); return; } if (this.MSN.Text.IsSet() && !ValidationHelper.IsValidEmail(this.MSN.Text)) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_MSN"), MessageTypes.Warning); return; } if (this.Xmpp.Text.IsSet() && !ValidationHelper.IsValidXmpp(this.Xmpp.Text)) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_XMPP"), MessageTypes.Warning); return; } if (this.ICQ.Text.IsSet() && !(ValidationHelper.IsValidEmail(this.ICQ.Text) || ValidationHelper.IsNumeric(this.ICQ.Text))) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_ICQ"), MessageTypes.Warning); return; } if (this.Facebook.Text.IsSet() && !ValidationHelper.IsValidURL(this.Facebook.Text)) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_FACEBOOK"), MessageTypes.Warning); return; } if (this.Google.Text.IsSet() && !ValidationHelper.IsValidURL(this.Google.Text)) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_GOOGLE"), MessageTypes.Warning); return; } string displayName = null; if (this.Get <YafBoardSettings>().EnableDisplayName && this.Get <YafBoardSettings>().AllowDisplayNameModification) { // Check if name matches the required minimum length if (this.DisplayName.Text.Trim().Length < this.Get <YafBoardSettings>().DisplayNameMinLength) { this.PageContext.AddLoadMessage( this.GetTextFormatted("USERNAME_TOOLONG", this.Get <YafBoardSettings>().DisplayNameMinLength), MessageTypes.Warning); return; } // Check if name matches the required minimum length if (this.DisplayName.Text.Length > this.Get <YafBoardSettings>().UserNameMaxLength) { this.PageContext.AddLoadMessage( this.GetTextFormatted("USERNAME_TOOLONG", this.Get <YafBoardSettings>().UserNameMaxLength), MessageTypes.Warning); return; } if (this.DisplayName.Text.Trim() != this.UserData.DisplayName) { if (this.Get <IUserDisplayName>().GetId(this.DisplayName.Text.Trim()).HasValue) { this.PageContext.AddLoadMessage( this.GetText("REGISTER", "ALREADY_REGISTERED_DISPLAYNAME"), MessageTypes.Warning); return; } displayName = this.DisplayName.Text.Trim(); } } if (this.UpdateEmailFlag) { string newEmail = this.Email.Text.Trim(); if (!ValidationHelper.IsValidEmail(newEmail)) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_EMAIL"), MessageTypes.Warning); return; } string userNameFromEmail = this.Get <MembershipProvider>().GetUserNameByEmail(this.Email.Text.Trim()); if (userNameFromEmail.IsSet() && userNameFromEmail != userName) { this.PageContext.AddLoadMessage(this.GetText("PROFILE", "BAD_EMAIL"), MessageTypes.Warning); return; } if (this.Get <YafBoardSettings>().EmailVerification) { this.SendEmailVerification(newEmail); } else { // just update the e-mail... try { UserMembershipHelper.UpdateEmail(this.currentUserID, this.Email.Text.Trim()); } catch (ApplicationException) { this.PageContext.AddLoadMessage( this.GetText("PROFILE", "DUPLICATED_EMAIL"), MessageTypes.Warning); return; } } } if (this.Interests.Text.Trim().Length > 400) { this.PageContext.AddLoadMessage( this.GetTextFormatted("FIELD_TOOLONG", this.GetText("CP_EDITPROFILE", "INTERESTS"), 400), MessageTypes.Warning); return; } if (this.Occupation.Text.Trim().Length > 400) { this.PageContext.AddLoadMessage( this.GetTextFormatted("FIELD_TOOLONG", this.GetText("CP_EDITPROFILE", "OCCUPATION"), 400), MessageTypes.Warning); return; } this.UpdateUserProfile(userName); // vzrus: We should do it as we need to write null value to db, else it will be empty. // Localizer currently treats only nulls. object language = null; object culture = this.Culture.SelectedValue; object theme = this.Theme.SelectedValue; object editor = this.ForumEditor.SelectedValue; if (this.Theme.SelectedValue.IsNotSet()) { theme = null; } if (this.ForumEditor.SelectedValue.IsNotSet()) { editor = null; } if (this.Culture.SelectedValue.IsNotSet()) { culture = null; } else { foreach (DataRow row in StaticDataHelper.Cultures() .Rows.Cast <DataRow>() .Where(row => culture.ToString() == row["CultureTag"].ToString())) { language = row["CultureFile"].ToString(); } } // save remaining settings to the DB LegacyDb.user_save( this.currentUserID, this.PageContext.PageBoardID, null, displayName, null, this.TimeZones.SelectedValue.ToType <int>(), language, culture, theme, editor, this.UseMobileTheme.Checked, null, null, null, this.DSTUser.Checked, this.HideMe.Checked, null); // vzrus: If it's a guest edited by an admin registry value should be changed DataTable dt = LegacyDb.user_list(this.PageContext.PageBoardID, this.currentUserID, true, null, null, false); if (dt.Rows.Count > 0 && dt.Rows[0]["IsGuest"].ToType <bool>()) { LegacyDb.registry_save("timezone", this.TimeZones.SelectedValue, this.PageContext.PageBoardID); } // clear the cache for this user...) this.Get <IRaiseEvent>().Raise(new UpdateUserEvent(this.currentUserID)); YafContext.Current.Get <IDataCache>().Clear(); if (!this.adminEditMode) { YafBuildLink.Redirect(ForumPages.cp_profile); } else { this._userData = null; this.BindData(); } }
/// <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 inital 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 inital 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> /// Handles the ItemCommand event of the UserList control. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param> public void UserListItemCommand([NotNull] object source, [NotNull] RepeaterCommandEventArgs e) { switch (e.CommandName) { case "edit": YafBuildLink.Redirect(ForumPages.admin_edituser, "u={0}", e.CommandArgument); break; case "resendEmail": var commandArgument = e.CommandArgument.ToString().Split(';'); var checkMail = this.GetRepository <CheckEmail>().ListTyped(commandArgument[0]).FirstOrDefault(); if (checkMail != null) { var verifyEmail = new YafTemplateEmail("VERIFYEMAIL"); var subject = this.Get <ILocalization>() .GetTextFormatted("VERIFICATION_EMAIL_SUBJECT", this.Get <YafBoardSettings>().Name); verifyEmail.TemplateParams["{link}"] = YafBuildLink.GetLinkNotEscaped( ForumPages.approve, true, "k={0}", checkMail.Hash); verifyEmail.TemplateParams["{key}"] = checkMail.Hash; verifyEmail.TemplateParams["{forumname}"] = this.Get <YafBoardSettings>().Name; verifyEmail.TemplateParams["{forumlink}"] = YafForumInfo.ForumURL; verifyEmail.SendEmail(new MailAddress(checkMail.Email, commandArgument[1]), subject, true); this.PageContext.AddLoadMessage(this.GetText("ADMIN_ADMIN", "MSG_MESSAGE_SEND")); } else { var userFound = this.Get <IUserDisplayName>().Find(commandArgument[1]).FirstOrDefault(); var user = this.Get <MembershipProvider>().GetUser(userFound.Value, false); this.Get <ISendNotification>().SendVerificationEmail(user, commandArgument[0], userFound.Key); } break; case "delete": var daysValue = this.PageContext.CurrentForumPage.FindControlRecursiveAs <TextBox>("DaysOld").Text.Trim(); if (!ValidationHelper.IsValidInt(daysValue)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_ADMIN", "MSG_VALID_DAYS")); return; } if (!Config.IsAnyPortal) { UserMembershipHelper.DeleteUser(e.CommandArgument.ToType <int>()); } LegacyDb.user_delete(e.CommandArgument); this.BindData(); break; case "approve": UserMembershipHelper.ApproveUser(e.CommandArgument.ToType <int>()); this.BindData(); break; case "deleteall": // vzrus: Should not delete the whole providers portal data? Under investigation. var daysValueAll = this.PageContext.CurrentForumPage.FindControlRecursiveAs <TextBox>("DaysOld").Text.Trim(); if (!ValidationHelper.IsValidInt(daysValueAll)) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_ADMIN", "MSG_VALID_DAYS")); return; } if (!Config.IsAnyPortal) { UserMembershipHelper.DeleteAllUnapproved(DateTime.UtcNow.AddDays(-daysValueAll.ToType <int>())); } LegacyDb.user_deleteold(this.PageContext.PageBoardID, daysValueAll.ToType <int>()); this.BindData(); break; case "approveall": UserMembershipHelper.ApproveAll(); // vzrus: Should delete users from send email list LegacyDb.user_approveall(this.PageContext.PageBoardID); this.BindData(); break; } }
/// <summary> /// Setups the user profile. /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="userId"> /// The user identifier. /// </param> private void SetupUserProfile(MembershipUser user, int userId) { // this is the "Profile Information" step. Save the data to their profile (+ defaults). var timeZones = (DropDownList)this.CreateUserWizard1.FindWizardControlRecursive("TimeZones"); var country = (ImageListBox)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"); // setup/save the profile var userProfile = YafUserProfile.GetProfile(this.CreateUserWizard1.UserName); if (country.SelectedValue != null) { userProfile.Country = country.SelectedValue; } string result; if (this.Get <ISpamWordCheck>().CheckForSpamWord(homepageTextBox.Text.Trim(), out result)) { this.IsPossibleSpamBotInternalCheck = true; // Flag user as spam bot this.IsPossibleSpamBot = true; var userIpAddress = this.Get <HttpRequestBase>().GetUserRealIPAddress(); if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { this.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userId); } else if (this.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2)) { // Kill user UserMembershipHelper.DeleteAndBanUser(userId, user, userIpAddress); this.PageContext.AddLoadMessage(this.GetText("BOT_MESSAGE"), MessageTypes.danger); } this.GetRepository <Registry>().IncrementDeniedRegistrations(); this.Logger.Log( null, "Bot Detected", $"Internal Spam Word Check detected a SPAM BOT: (user name : '{user.UserName}', email : '{this.CreateUserWizard1.Email}', ip: '{userIpAddress}') reason word: {homepageTextBox.Text.Trim()}", EventLogTypes.SpamBotDetected); } if (!this.IsPossibleSpamBotInternalCheck) { userProfile.Location = locationTextBox.Text.Trim(); // add http:// by default if (!Regex.IsMatch(homepageTextBox.Text.Trim(), @"^(http|https|ftp|ftps|git|svn|news)\://.*")) { homepageTextBox.Text = $"http://{homepageTextBox.Text.Trim()}"; } if (ValidationHelper.IsValidURL(homepageTextBox.Text)) { userProfile.Homepage = homepageTextBox.Text.Trim(); } userProfile.Save(); var autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the time zone... this.GetRepository <User>().Save( userID: userId, boardID: this.PageContext.PageBoardID, userName: null, displayName: null, email: null, timeZone: timeZones.SelectedValue, languageFile: null, culture: null, themeFile: null, textEditor: null, approved: null, pmNotification: this.Get <YafBoardSettings>().DefaultNotificationSetting, autoWatchTopics: autoWatchTopicsEnabled, dSTUser: dstUser.Checked, hideUser: null, notificationType: null); // save the settings... this.GetRepository <User>().SaveNotification( userId, true, autoWatchTopicsEnabled, this.Get <YafBoardSettings>().DefaultNotificationSetting, this.Get <YafBoardSettings>().DefaultSendDigestEmail); } }
/// <summary> /// The password recovery 1_ verifying user. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void PasswordRecovery1_VerifyingUser([NotNull] object sender, [NotNull] LoginCancelEventArgs e) { MembershipUser user = null; if (this.PasswordRecovery1.UserName.Contains("@") && this.Get <MembershipProvider>().RequiresUniqueEmail) { // Email Login var username = this.Get <MembershipProvider>().GetUserNameByEmail(this.PasswordRecovery1.UserName); if (username != null) { user = this.Get <MembershipProvider>().GetUser(username, false); // update the username this.PasswordRecovery1.UserName = username; } } else { // Standard user name login if (this.Get <BoardSettings>().EnableDisplayName) { // Display name login var id = this.Get <IUserDisplayName>().GetId(this.PasswordRecovery1.UserName); if (id.HasValue) { // get the username associated with this id... var username = UserMembershipHelper.GetUserNameFromID(id.Value); // update the username this.PasswordRecovery1.UserName = username; } user = this.Get <MembershipProvider>().GetUser(this.PasswordRecovery1.UserName, false); } } if (user == null) { return; } // verify the user is approved, etc... if (user.IsApproved) { return; } if (this.Get <BoardSettings>().EmailVerification) { // get the hash from the db associated with this user... var checkTyped = this.GetRepository <CheckEmail>().ListTyped(user.Email).FirstOrDefault(); if (checkTyped != null) { // re-send verification email instead of lost password... var verifyEmail = new TemplateEmail("VERIFYEMAIL"); var subject = this.GetTextFormatted( "VERIFICATION_EMAIL_SUBJECT", this.Get <BoardSettings>().Name); verifyEmail.TemplateParams["{link}"] = BuildLink.GetLinkNotEscaped( ForumPages.Approve, true, "k={0}", checkTyped.Hash); verifyEmail.TemplateParams["{key}"] = checkTyped.Hash; verifyEmail.TemplateParams["{forumname}"] = this.Get <BoardSettings>().Name; verifyEmail.TemplateParams["{forumlink}"] = $"{BoardInfo.ForumURL}"; verifyEmail.SendEmail(new MailAddress(user.Email, user.UserName), subject); this.PageContext.LoadMessage.AddSession( this.GetTextFormatted("ACCOUNT_NOT_APPROVED_VERIFICATION", user.Email), MessageTypes.warning); } } else { // explain they are not approved yet... this.PageContext.LoadMessage.AddSession(this.GetText("ACCOUNT_NOT_APPROVED"), MessageTypes.warning); } // just in case cancel the verification... e.Cancel = true; // nothing they can do here... redirect to login... BuildLink.Redirect(ForumPages.Login); }
/// <summary> /// Send Private Message /// </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 Save_Click([NotNull] object sender, [NotNull] EventArgs e) { var replyTo = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("p").IsSet() ? this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("p").ToType <int>() : -1; // recipient was set in dropdown if (this.ToList.Visible) { this.To.Text = this.ToList.SelectedItem.Text; } if (this.To.Text.Length <= 0) { // recipient is required field YafContext.Current.AddLoadMessage(this.GetText("need_to"), MessageTypes.warning); return; } // subject is required if (this.PmSubjectTextBox.Text.Trim().Length <= 0) { YafContext.Current.AddLoadMessage(this.GetText("need_subject"), MessageTypes.warning); return; } // message is required if (this._editor.Text.Trim().Length <= 0) { YafContext.Current.AddLoadMessage(this.GetText("need_message"), MessageTypes.warning); return; } if (this.ToList.SelectedItem != null && this.ToList.SelectedItem.Value == "0") { // administrator is sending PMs to all users var body = this._editor.Text; var messageFlags = new MessageFlags { IsHtml = this._editor.UsesHTML, IsBBCode = this._editor.UsesBBCode }; // test user's PM count if (!this.VerifyMessageAllowed(1, body)) { return; } this.GetRepository <PMessage>().SendMessage( YafContext.Current.PageUserID, 0, this.PmSubjectTextBox.Text, body, messageFlags.BitValue, replyTo); // redirect to outbox (sent items), not control panel YafBuildLink.Redirect(ForumPages.cp_pm, "v={0}", "out"); } else { // remove all abundant whitespaces and separators var rx = new Regex(@";(\s|;)*;"); this.To.Text = rx.Replace(this.To.Text, ";"); if (this.To.Text.StartsWith(";")) { this.To.Text = this.To.Text.Substring(1); } if (this.To.Text.EndsWith(";")) { this.To.Text = this.To.Text.Substring(0, this.To.Text.Length - 1); } rx = new Regex(@"\s*;\s*"); this.To.Text = rx.Replace(this.To.Text, ";"); // list of recipients var recipients = new List <string>(this.To.Text.Trim().Split(';')); if (recipients.Count > this.Get <YafBoardSettings>().PrivateMessageMaxRecipients && !YafContext.Current.IsAdmin && this.Get <YafBoardSettings>().PrivateMessageMaxRecipients != 0) { // to many recipients YafContext.Current.AddLoadMessage( this.GetTextFormatted( "TOO_MANY_RECIPIENTS", this.Get <YafBoardSettings>().PrivateMessageMaxRecipients), MessageTypes.warning); return; } if (!this.VerifyMessageAllowed(recipients.Count, this._editor.Text)) { return; } // list of recipient's ids var recipientIds = new List <int>(); // get recipients' IDs foreach (var recipient in recipients) { var userId = this.Get <IUserDisplayName>().GetId(recipient); if (!userId.HasValue) { YafContext.Current.AddLoadMessage( this.GetTextFormatted("NO_SUCH_USER", recipient), MessageTypes.warning); return; } if (UserMembershipHelper.IsGuestUser(userId.Value)) { YafContext.Current.AddLoadMessage(this.GetText("NOT_GUEST"), MessageTypes.danger); return; } // get recipient's ID from the database if (!recipientIds.Contains(userId.Value)) { recipientIds.Add(userId.Value); } var receivingPMInfo = this.GetRepository <PMessage>().UserMessageCount(userId.Value).Rows[0]; // test receiving user's PM count if (receivingPMInfo["NumberTotal"].ToType <int>() + 1 < receivingPMInfo["NumberAllowed"].ToType <int>() || YafContext.Current.IsAdmin || (bool) Convert.ChangeType( UserMembershipHelper.GetUserRowForID(userId.Value, true)["IsAdmin"], typeof(bool))) { continue; } // recipient has full PM box YafContext.Current.AddLoadMessage( this.GetTextFormatted("RECIPIENTS_PMBOX_FULL", recipient), MessageTypes.danger); return; } // send PM to all recipients foreach (var userId in recipientIds) { var body = this._editor.Text; var messageFlags = new MessageFlags { IsHtml = this._editor.UsesHTML, IsBBCode = this._editor.UsesBBCode }; this.GetRepository <PMessage>().SendMessage( YafContext.Current.PageUserID, userId, this.PmSubjectTextBox.Text, body, messageFlags.BitValue, replyTo); // reset lazy data as he should be informed at once this.Get <IDataCache>().Remove(string.Format(Constants.Cache.ActiveUserLazyData, userId)); if (this.Get <YafBoardSettings>().AllowPMEmailNotification) { this.Get <ISendNotification>() .ToPrivateMessageRecipient(userId, this.PmSubjectTextBox.Text.Trim()); } } // redirect to outbox (sent items), not control panel YafBuildLink.Redirect(ForumPages.cp_pm, "v={0}", "out"); } }
/// <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>(); 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", isSpamMessage ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL" : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL", languageFile) .FormatWith(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> /// Creates the Google user /// </summary> /// <param name="googleUser"> /// The Google user. /// </param> /// <param name="userGender"> /// The user gender. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// Returns if the login was successfully or not /// </returns> private bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message) { if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations) { message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } // Check user for bot var spamChecker = new YafSpamCheck(); string result; var isPossibleSpamBot = false; var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress(); // Check content for spam if (spamChecker.CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out result)) { YafContext.Current.Get <ILogger>().Log( null, "Bot Detected", "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected." .FormatWith(googleUser.UserName, googleUser.Email, userIpAddress, result), EventLogTypes.SpamBotDetected); if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1)) { // Flag user as spam bot isPossibleSpamBot = true; } else if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2)) { message = YafContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE"); if (!YafContext.Current.Get <YafBoardSettings>().BanBotIpOnDetection) { return(false); } YafContext.Current.GetRepository <BannedIP>() .Save( null, userIpAddress, "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress), YafContext.Current.PageUserID); // Clear cache YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP); if (YafContext.Current.Get <YafBoardSettings>().LogBannedIP) { YafContext.Current.Get <ILogger>() .Log( null, "IP BAN of Bot During Registration", "A spam Bot who was trying to register was banned by IP {0}".FormatWith( userIpAddress), EventLogTypes.IpBanSet); } return(false); } } MembershipCreateStatus status; var memberShipProvider = YafContext.Current.Get <MembershipProvider>(); var pass = Membership.GeneratePassword(32, 16); var securityAnswer = Membership.GeneratePassword(64, 30); var user = memberShipProvider.CreateUser( googleUser.UserName, pass, googleUser.Email, memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null, memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null, true, null, out status); // setup initial roles (if any) for this user RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, googleUser.UserName); // create the user in the YAF DB as well as sync roles... var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID); // create empty profile just so they have one var userProfile = YafUserProfile.GetProfile(googleUser.UserName); userProfile.Google = googleUser.ProfileURL; userProfile.GoogleId = googleUser.UserID; userProfile.Homepage = googleUser.ProfileURL; userProfile.Gender = userGender; userProfile.Save(); // setup their initial profile information userProfile.Save(); if (userID == null) { // something is seriously wrong here -- redirect to failure... message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED"); return(false); } if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet()) { // send user register notification to the following admin users... YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value); } if (isPossibleSpamBot) { YafContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value); } // send user register notification to the user... YafContext.Current.Get <ISendNotification>() .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER"); // save the time zone... var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey); LegacyDb.user_save( userId, YafContext.Current.PageBoardID, googleUser.UserName, googleUser.UserName, googleUser.Email, 0, null, null, true, null, null, null, null, null, null, null, null); var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting == UserNotificationSetting.TopicsIPostToOrSubscribeTo; // save the settings... LegacyDb.user_savenotification( userId, true, autoWatchTopicsEnabled, YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting, YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail); // save avatar LegacyDb.user_saveavatar(userId, googleUser.ProfileImage, null, null); YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId)); YafSingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true); message = string.Empty; return(true); }