Example #1
0
        /// <summary>
        /// Creates the YAF user.
        /// </summary>
        /// <param name="dnnUserInfo">The DNN user info.</param>
        /// <param name="dnnUser">The DNN user.</param>
        /// <param name="boardId">The board ID.</param>
        /// <param name="portalId">The portal identifier.</param>
        /// <param name="boardSettings">The board settings.</param>
        /// <returns>
        /// Returns the User ID of the new User
        /// </returns>
        public static int CreateYafUser(
            UserInfo dnnUserInfo,
            MembershipUser dnnUser,
            int boardId,
            int portalId,
            BoardSettings boardSettings)
        {
            // setup roles
            RoleMembershipHelper.SetupUserRoles(boardId, dnnUser.UserName);

            // create the user in the YAF DB so profile can gets created...
            var yafUserId = RoleMembershipHelper.CreateForumUser(dnnUser, dnnUserInfo.DisplayName, boardId);

            if (yafUserId == null)
            {
                return(0);
            }

            // create profile
            var userProfile = YAF.Utils.UserProfile.GetProfile(dnnUser.UserName);

            // setup their initial profile information
            userProfile.Initialize(dnnUser.UserName, true);

            if (dnnUserInfo.Profile.FullName.IsSet())
            {
                userProfile.RealName = dnnUserInfo.Profile.FullName;
            }

            if (dnnUserInfo.Profile.Country.IsSet() && !dnnUserInfo.Profile.Country.Equals("N/A"))
            {
                var regionInfo = ProfileSyncronizer.GetRegionInfoFromCountryName(dnnUserInfo.Profile.Country);

                if (regionInfo != null)
                {
                    userProfile.Country = regionInfo.TwoLetterISORegionName;
                }
            }

            if (dnnUserInfo.Profile.City.IsSet())
            {
                userProfile.City = dnnUserInfo.Profile.City;
            }

            if (dnnUserInfo.Profile.Website.IsSet())
            {
                userProfile.Homepage = dnnUserInfo.Profile.Website;
            }

            userProfile.Save();

            var autoWatchTopicsEnabled =
                boardSettings.DefaultNotificationSetting.Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo);

            // Save User
            BoardContext.Current.GetRepository <User>().Save(
                yafUserId,
                boardId,
                dnnUserInfo.Username,
                dnnUserInfo.DisplayName,
                dnnUserInfo.Email,
                dnnUserInfo.Profile.PreferredTimeZone.Id,
                null,
                null,
                null,
                null,
                boardSettings.DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                dnnUserInfo.Profile.PreferredTimeZone.SupportsDaylightSavingTime,
                null,
                null);

            // save notification Settings
            BoardContext.Current.GetRepository <User>().SaveNotification(
                yafUserId.Value,
                true,
                autoWatchTopicsEnabled,
                boardSettings.DefaultNotificationSetting.ToInt(),
                boardSettings.DefaultSendDigestEmail);

            RoleSyncronizer.SynchronizeUserRoles(boardId, portalId, yafUserId.ToType <int>(), dnnUserInfo);

            return(yafUserId.ToType <int>());
        }
Example #2
0
        /// <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)
        {
            if (!ValidationHelper.IsValidInt(this.PMLimit.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_VALID_NUMBER"));
                return;
            }

            if (!ValidationHelper.IsValidInt(this.Priority.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_INTEGER"));
                return;
            }

            if (!ValidationHelper.IsValidInt(this.UsrAlbums.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_ALBUM_NUMBER"));
                return;
            }

            if (!ValidationHelper.IsValidInt(this.UsrSigChars.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_SIG_NUMBER"));
                return;
            }

            if (!ValidationHelper.IsValidInt(this.UsrAlbumImages.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_TOTAL_NUMBER"));
                return;
            }

            // Role
            long roleID = 0;

            // get role ID from page's parameter
            if (this.Request.QueryString.GetFirstOrDefault("i") != null)
            {
                roleID = long.Parse(this.Request.QueryString.GetFirstOrDefault("i"));
            }

            // get new and old name
            var roleName    = this.Name.Text.Trim();
            var oldRoleName = string.Empty;

            // if we are editing exising role, get it's original name
            if (roleID != 0)
            {
                // get the current role name in the DB
                using (var dt = this.GetRepository <Group>().List(boardId: this.PageContext.PageBoardID))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        oldRoleName = row["Name"].ToString();
                    }
                }
            }

            // save role and get its ID if it's new (if it's old role, we get it anyway)
            roleID = LegacyDb.group_save(
                roleID,
                this.PageContext.PageBoardID,
                roleName,
                this.IsAdminX.Checked,
                this.IsGuestX.Checked,
                this.IsStartX.Checked,
                this.IsModeratorX.Checked,
                this.AccessMaskID.SelectedValue,
                this.PMLimit.Text.Trim(),
                this.StyleTextBox.Text.Trim(),
                this.Priority.Text.Trim(),
                this.Description.Text,
                this.UsrSigChars.Text,
                this.UsrSigBBCodes.Text,
                this.UsrSigHTMLTags.Text,
                this.UsrAlbums.Text.Trim(),
                this.UsrAlbumImages.Text.Trim());

            // empty out access table(s)
            this.GetRepository <Active>().DeleteAll();
            this.GetRepository <ActiveAccess>().DeleteAll();

            // see if need to rename an existing role...
            if (oldRoleName.IsSet() && roleName != oldRoleName && RoleMembershipHelper.RoleExists(oldRoleName) && !RoleMembershipHelper.RoleExists(roleName) && !this.IsGuestX.Checked)
            {
                // transfer users in addition to changing the name of the role...
                var users = this.Get <RoleProvider>().GetUsersInRole(oldRoleName);

                // delete the old role...
                RoleMembershipHelper.DeleteRole(oldRoleName, false);

                // create new role...
                RoleMembershipHelper.CreateRole(roleName);

                if (users.Any())
                {
                    // put users into new role...
                    this.Get <RoleProvider>().AddUsersToRoles(users, new[] { roleName });
                }
            }
            else if (!RoleMembershipHelper.RoleExists(roleName) && !this.IsGuestX.Checked)
            {
                // if role doesn't exist in provider's data source, create it

                // simply create it
                RoleMembershipHelper.CreateRole(roleName);
            }

            // Access masks for a newly created or an existing role
            if (this.Request.QueryString.GetFirstOrDefault("i") != null)
            {
                // go trhough all forums
                for (var i = 0; i < this.AccessList.Items.Count; i++)
                {
                    // get current repeater item
                    var item = this.AccessList.Items[i];

                    // get forum ID
                    var forumID = int.Parse(((Label)item.FindControl("ForumID")).Text);

                    // save forum access maks for this role
                    LegacyDb.forumaccess_save(
                        forumID,
                        roleID,
                        ((DropDownList)item.FindControl("AccessmaskID")).SelectedValue);
                }

                YafBuildLink.Redirect(ForumPages.admin_groups);
            }

            // remove caching in case something got updated...
            this.Get <IDataCache>().Remove(Constants.Cache.ForumModerators);

            // Clearing cache with old permissions data...
            this.Get <IDataCache>().Remove(k => k.StartsWith(Constants.Cache.ActiveUserLazyData.FormatWith(string.Empty)));

            // Done, redirect to role editing page
            YafBuildLink.Redirect(ForumPages.admin_editgroup, "i={0}", roleID);
        }
Example #3
0
        /// <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);
                }
            }
        }
Example #4
0
        /// <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); ");
        }
Example #5
0
        /// <summary>
        ///     Creates the forum.
        /// </summary>
        /// <returns>
        ///     The create forum.
        /// </returns>
        private bool CreateForum()
        {
            if (this.InstallUpgradeService.IsForumInstalled)
            {
                this.ShowErrorMessage("Forum is already installed.");
                return(false);
            }

            if (this.TheForumName.Text.Length == 0)
            {
                this.ShowErrorMessage("You must enter a forum name.");
                return(false);
            }

            if (this.ForumEmailAddress.Text.Length == 0)
            {
                this.ShowErrorMessage("You must enter a forum email address.");
                return(false);
            }

            MembershipUser user;

            if (this.UserChoice.SelectedValue == "create")
            {
                if (this.UserName.Text.Length == 0)
                {
                    this.ShowErrorMessage("You must enter the admin user name,");
                    return(false);
                }

                if (this.AdminEmail.Text.Length == 0)
                {
                    this.ShowErrorMessage("You must enter the administrators email address.");
                    return(false);
                }

                if (this.Password1.Text.Length == 0)
                {
                    this.ShowErrorMessage("You must enter a password.");
                    return(false);
                }

                if (this.Password1.Text != this.Password2.Text)
                {
                    this.ShowErrorMessage("The passwords must match.");
                    return(false);
                }

                // create the admin user...
                MembershipCreateStatus status;
                user = this.Get <MembershipProvider>()
                       .CreateUser(
                    this.UserName.Text,
                    this.Password1.Text,
                    this.AdminEmail.Text,
                    this.SecurityQuestion.Text,
                    this.SecurityAnswer.Text,
                    true,
                    null,
                    out status);
                if (status != MembershipCreateStatus.Success)
                {
                    this.ShowErrorMessage(
                        "Create Admin User Failed: {0}".FormatWith(this.GetMembershipErrorMessage(status)));
                    return(false);
                }
            }
            else
            {
                // try to get data for the existing user...
                user = UserMembershipHelper.GetUser(this.ExistingUserName.Text.Trim());

                if (user == null)
                {
                    this.ShowErrorMessage(
                        "Existing user name is invalid and does not represent a current user in the membership store.");
                    return(false);
                }
            }

            try
            {
                var prefix = Config.CreateDistinctRoles && Config.IsAnyPortal ? "YAF " : string.Empty;

                // add administrators and registered if they don't already exist...
                if (!RoleMembershipHelper.RoleExists("{0}Administrators".FormatWith(prefix)))
                {
                    RoleMembershipHelper.CreateRole("{0}Administrators".FormatWith(prefix));
                }

                if (!RoleMembershipHelper.RoleExists("{0}Registered".FormatWith(prefix)))
                {
                    RoleMembershipHelper.CreateRole("{0}Registered".FormatWith(prefix));
                }

                if (!RoleMembershipHelper.IsUserInRole(user.UserName, "{0}Administrators".FormatWith(prefix)))
                {
                    RoleMembershipHelper.AddUserToRole(user.UserName, "{0}Administrators".FormatWith(prefix));
                }

                // logout administrator...
                FormsAuthentication.SignOut();


                int timeZone;

                try
                {
                    timeZone = int.Parse(this.TimeZones.SelectedValue);
                }
                catch (Exception)
                {
                    timeZone = 0;
                }

                // init forum...
                this.InstallUpgradeService.InitializeForum(
                    this.TheForumName.Text,
                    timeZone,
                    this.Culture.SelectedValue,
                    this.ForumEmailAddress.Text,
                    this.ForumBaseUrlMask.Text,
                    user.UserName,
                    user.Email,
                    user.ProviderUserKey);
            }
            catch (Exception x)
            {
                this.ShowErrorMessage(x.Message);
                return(false);
            }

            return(true);
        }
Example #6
0
        /// <summary>
        /// Get the User Groups
        /// </summary>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        protected string GetUserRoles()
        {
            var filler = string.Empty;

            if (!this.Get <YafBoardSettings>().ShowGroups)
            {
                return(filler);
            }

            const string StyledNick = @"<span class=""YafGroup_{0}"" style=""{1}"">{0}</span>";

            var groupsText = new StringBuilder(500);

            var    first     = true;
            var    hasRole   = false;
            string roleStyle = null;

            var userName = this.DataRow["IsGuest"].ToType <bool>()
                               ? UserMembershipHelper.GuestUserName
                               : this.DataRow["UserName"].ToString();

            RoleMembershipHelper.GetRolesForUser(userName).ForEach(
                role =>
            {
                var role1 = role;

                foreach (var dataRow in this.roleRankStyleTable.Rows.Cast <DataRow>().Where(
                             row => row["LegendID"].ToType <int>() == 1 && row["Style"] != null &&
                             row["Name"].ToString() == role1))
                {
                    roleStyle = this.TransformStyle.DecodeStyleByString(dataRow["Style"].ToString(), true);
                    break;
                }

                if (first)
                {
                    groupsText.AppendLine(
                        this.Get <YafBoardSettings>().UseStyledNicks
                                    ? string.Format(StyledNick, role, roleStyle)
                                    : role);

                    first = false;
                }
                else
                {
                    if (this.Get <YafBoardSettings>().UseStyledNicks)
                    {
                        groupsText.AppendFormat(", " + StyledNick, role, roleStyle);
                    }
                    else
                    {
                        groupsText.AppendFormat(", {0}", role);
                    }
                }

                roleStyle = null;
                hasRole   = true;
            });

            // vzrus: Only a guest normally has no role
            if (!hasRole)
            {
                var dt = this.Get <IDataCache>().GetOrSet(
                    Constants.Cache.GuestGroupsCache,
                    () => this.GetRepository <Group>().MemberAsDataTable(
                        this.PageContext.PageBoardID,
                        this.DataRow["UserID"]),
                    TimeSpan.FromMinutes(60));

                foreach (var guestRole in dt.Rows.Cast <DataRow>().Where(role => role["Member"].ToType <int>() > 0)
                         .Select(role => role["Name"].ToString()))
                {
                    foreach (var dataRow in this.roleRankStyleTable.Rows.Cast <DataRow>().Where(
                                 row => row["LegendID"].ToType <int>() == 1 && row["Style"] != null &&
                                 row["Name"].ToString() == guestRole))
                    {
                        roleStyle = this.TransformStyle.DecodeStyleByString(dataRow["Style"].ToString(), true);
                        break;
                    }

                    groupsText.AppendLine(
                        this.Get <YafBoardSettings>().UseStyledNicks
                            ? string.Format(StyledNick, guestRole, roleStyle)
                            : guestRole);
                    break;
                }
            }

            filler = $"<strong>{this.GetText("GROUPS")}:</strong> {groupsText}";

            // Remove the space before the first comma when multiple groups exist.
            filler = filler.Replace("\r\n,", ",");

            return(filler);
        }
        /// <summary>
        /// Import the User From the Current Table Row
        /// </summary>
        /// <param name="row">
        /// The row with the User Information.
        /// </param>
        /// <param name="importCount">
        /// The import Count.
        /// </param>
        /// <returns>
        /// Returns the Imported User Count.
        /// </returns>
        private int ImportUser(DataRow row, int importCount)
        {
            // Also Check if the Email is unique and exists
            if (this.Get <MembershipProvider>().RequiresUniqueEmail)
            {
                if (this.Get <MembershipProvider>().GetUserNameByEmail((string)row["Email"]) != null)
                {
                    return(importCount);
                }
            }

            MembershipCreateStatus status;

            var pass             = Membership.GeneratePassword(32, 16);
            var securityAnswer   = Membership.GeneratePassword(64, 30);
            var securityQuestion = "Answer is a generated Pass";

            if (row.Table.Columns.Contains("Password") && !string.IsNullOrEmpty((string)row["Password"]) &&
                row.Table.Columns.Contains("SecurityQuestion") &&
                !string.IsNullOrEmpty((string)row["SecurityQuestion"]) &&
                row.Table.Columns.Contains("SecurityAnswer") && !string.IsNullOrEmpty((string)row["SecurityAnswer"]))
            {
                pass = (string)row["Password"];

                securityAnswer   = (string)row["SecurityAnswer"];
                securityQuestion = (string)row["SecurityQuestion"];
            }

            var user = YafContext.Current.Get <MembershipProvider>().CreateUser(
                (string)row["Name"],
                pass,
                (string)row["Email"],
                this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityQuestion : null,
                this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityAnswer : null,
                true,
                null,
                out status);

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, (string)row["Name"]);

            // 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((string)row["Name"]);

            // Add Profile Fields to User List Table.
            if (row.Table.Columns.Contains("RealName") && !string.IsNullOrEmpty((string)row["RealName"]))
            {
                userProfile.RealName = (string)row["RealName"];
            }

            if (row.Table.Columns.Contains("Blog") && !string.IsNullOrEmpty((string)row["Blog"]))
            {
                userProfile.Blog = (string)row["Blog"];
            }

            if (row.Table.Columns.Contains("Gender") && !string.IsNullOrEmpty((string)row["Gender"]))
            {
                int gender;

                int.TryParse((string)row["Gender"], out gender);

                userProfile.Gender = gender;
            }

            if (row.Table.Columns.Contains("Birthday") && !string.IsNullOrEmpty((string)row["Birthday"]))
            {
                DateTime userBirthdate;

                DateTime.TryParse((string)row["Birthday"], out userBirthdate);

                if (userBirthdate > DateTimeHelper.SqlDbMinTime())
                {
                    userProfile.Birthday = userBirthdate;
                }
            }

            if (row.Table.Columns.Contains("MSN") && !string.IsNullOrEmpty((string)row["MSN"]))
            {
                userProfile.MSN = (string)row["MSN"];
            }

            if (row.Table.Columns.Contains("BlogServiceUsername") &&
                !string.IsNullOrEmpty((string)row["BlogServiceUsername"]))
            {
                userProfile.BlogServiceUsername = (string)row["BlogServiceUsername"];
            }

            if (row.Table.Columns.Contains("BlogServicePassword") &&
                !string.IsNullOrEmpty((string)row["BlogServicePassword"]))
            {
                userProfile.BlogServicePassword = (string)row["BlogServicePassword"];
            }

            if (row.Table.Columns.Contains("AIM") && !string.IsNullOrEmpty((string)row["AIM"]))
            {
                userProfile.AIM = (string)row["AIM"];
            }

            if (row.Table.Columns.Contains("Google") && !string.IsNullOrEmpty((string)row["Google"]))
            {
                userProfile.Google = (string)row["Google"];
            }

            if (row.Table.Columns.Contains("GoogleId") && !string.IsNullOrEmpty((string)row["GoogleId"]))
            {
                userProfile.GoogleId = (string)row["GoogleId"];
            }

            if (row.Table.Columns.Contains("Location") && !string.IsNullOrEmpty((string)row["Location"]))
            {
                userProfile.Location = (string)row["Location"];
            }

            if (row.Table.Columns.Contains("Country") && !string.IsNullOrEmpty((string)row["Country"]))
            {
                userProfile.Country = (string)row["Country"];
            }

            if (row.Table.Columns.Contains("Region") && !string.IsNullOrEmpty((string)row["Region"]))
            {
                userProfile.Region = (string)row["Region"];
            }

            if (row.Table.Columns.Contains("City") && !string.IsNullOrEmpty((string)row["City"]))
            {
                userProfile.City = (string)row["City"];
            }

            if (row.Table.Columns.Contains("Interests") && !string.IsNullOrEmpty((string)row["Interests"]))
            {
                userProfile.Interests = (string)row["Interests"];
            }

            if (row.Table.Columns.Contains("Homepage") && !string.IsNullOrEmpty((string)row["Homepage"]))
            {
                userProfile.Homepage = (string)row["Homepage"];
            }

            if (row.Table.Columns.Contains("Skype") && !string.IsNullOrEmpty((string)row["Skype"]))
            {
                userProfile.Skype = (string)row["Skype"];
            }

            if (row.Table.Columns.Contains("ICQe") && !string.IsNullOrEmpty((string)row["ICQ"]))
            {
                userProfile.ICQ = (string)row["ICQ"];
            }

            if (row.Table.Columns.Contains("XMPP") && !string.IsNullOrEmpty((string)row["XMPP"]))
            {
                userProfile.XMPP = (string)row["XMPP"];
            }

            if (row.Table.Columns.Contains("YIM") && !string.IsNullOrEmpty((string)row["YIM"]))
            {
                userProfile.YIM = (string)row["YIM"];
            }

            if (row.Table.Columns.Contains("Occupation") && !string.IsNullOrEmpty((string)row["Occupation"]))
            {
                userProfile.Occupation = (string)row["Occupation"];
            }

            if (row.Table.Columns.Contains("Twitter") && !string.IsNullOrEmpty((string)row["Twitter"]))
            {
                userProfile.Twitter = (string)row["Twitter"];
            }

            if (row.Table.Columns.Contains("TwitterId") && !string.IsNullOrEmpty((string)row["TwitterId"]))
            {
                userProfile.TwitterId = (string)row["TwitterId"];
            }

            if (row.Table.Columns.Contains("Facebook") && !string.IsNullOrEmpty((string)row["Facebook"]))
            {
                userProfile.Facebook = (string)row["Facebook"];
            }

            if (row.Table.Columns.Contains("FacebookId") && !string.IsNullOrEmpty((string)row["FacebookId"]))
            {
                userProfile.FacebookId = (string)row["FacebookId"];
            }

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                return(importCount);
            }

            // send user register notification to the new users
            this.Get <ISendNotification>().SendRegistrationNotificationToUser(
                user, pass, securityAnswer, "NOTIFICATION_ON_REGISTER");

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            var isDST = false;

            if (row.Table.Columns.Contains("IsDST") && !string.IsNullOrEmpty((string)row["IsDST"]))
            {
                bool.TryParse((string)row["IsDST"], out isDST);
            }

            var timeZone = 0;

            if (row.Table.Columns.Contains("Timezone") && !string.IsNullOrEmpty((string)row["Timezone"]))
            {
                int.TryParse((string)row["Timezone"], out timeZone);
            }

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                row["Name"],
                row.Table.Columns.Contains("DisplayName") ? row["DisplayName"] : null,
                row["Email"],
                timeZone,
                row.Table.Columns.Contains("LanguageFile") ? row["LanguageFile"] : null,
                row.Table.Columns.Contains("Culture") ? row["Culture"] : null,
                row.Table.Columns.Contains("ThemeFile") ? row["ThemeFile"] : null,
                row.Table.Columns.Contains("TextEditor") ? row["TextEditor"] : null,
                null,
                null,
                null,
                null,
                isDST,
                null,
                null);

            var autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            // save the settings...
            LegacyDb.user_savenotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                this.Get <YafBoardSettings>().DefaultNotificationSetting,
                this.Get <YafBoardSettings>().DefaultSendDigestEmail);

            importCount++;

            return(importCount);
        }
Example #8
0
        protected void ForumRegister_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                string newEmail    = Email.Text.Trim();
                string newUsername = UserName.Text.Trim();

                if (!General.IsValidEmail(newEmail))
                {
                    PageContext.AddLoadMessage("You have entered an illegal e-mail address.");
                    return;
                }

                if (UserMembershipHelper.UserExists(UserName.Text.Trim(), newEmail))
                {
                    PageContext.AddLoadMessage("Username or email are already registered.");
                    return;
                }

                string hashinput = DateTime.Now.ToString() + newEmail + Security.CreatePassword(20);
                string hash      = FormsAuthentication.HashPasswordForStoringInConfigFile(hashinput, "md5");

                MembershipCreateStatus status;
                MembershipUser         user = Membership.CreateUser(newUsername, Password.Text.Trim(), newEmail, Question.Text.Trim(), Answer.Text.Trim(), !PageContext.BoardSettings.EmailVerification, out status);

                if (status != MembershipCreateStatus.Success)
                {
                    // error of some kind
                    PageContext.AddLoadMessage("Membership Error Creating User: "******"VERIFYEMAIL");

                    verifyEmail.TemplateParams ["{link}"]      = String.Format("{1}{0}", YAF.Classes.Utils.YafBuildLink.GetLink(YAF.Classes.Utils.ForumPages.approve, "k={0}", hash), YAF.Classes.Utils.YafForumInfo.ServerURL);
                    verifyEmail.TemplateParams ["{key}"]       = hash;
                    verifyEmail.TemplateParams ["{forumname}"] = PageContext.BoardSettings.Name;
                    verifyEmail.TemplateParams ["{forumlink}"] = String.Format("{0}", ForumURL);

                    string subject = String.Format(PageContext.Localization.GetText("COMMON", "EMAILVERIFICATION_SUBJECT"), PageContext.BoardSettings.Name);

                    verifyEmail.SendEmail(new System.Net.Mail.MailAddress(newEmail, newUsername), subject, true);
                }

                // success
                PageContext.AddLoadMessage(string.Format("User {0} Created Successfully.", UserName.Text.Trim()));
                YAF.Classes.Utils.YafBuildLink.Redirect(YAF.Classes.Utils.ForumPages.admin_reguser);
            }
        }
Example #9
0
        /// <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);
            }

            MembershipCreateStatus status;

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            MembershipUser user = YafContext.Current.Get <MembershipProvider>()
                                  .CreateUser(
                facebookUser.UserName,
                pass,
                facebookUser.Email,
                "Answer is a generated Pass",
                securityAnswer,
                true,
                null,
                out status);

            // setup inital 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...
            int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            YafUserProfile userProfile = YafUserProfile.GetProfile(facebookUser.UserName);

            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;
            }

            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, 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...
            int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                facebookUser.UserName,
                facebookUser.UserName,
                facebookUser.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,
                "https://graph.facebook.com/{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);
        }
Example #10
0
        /// <summary>
        /// The create board.
        /// </summary>
        /// <param name="adminName">
        /// The admin name.
        /// </param>
        /// <param name="adminPassword">
        /// The admin password.
        /// </param>
        /// <param name="adminEmail">
        /// The admin email.
        /// </param>
        /// <param name="adminPasswordQuestion">
        /// The admin password question.
        /// </param>
        /// <param name="adminPasswordAnswer">
        /// The admin password answer.
        /// </param>
        /// <param name="boardName">
        /// The board name.
        /// </param>
        /// <param name="boardMembershipAppName">
        /// The board membership app name.
        /// </param>
        /// <param name="boardRolesAppName">
        /// The board roles app name.
        /// </param>
        /// <param name="createUserAndRoles">
        /// The create user and roles.
        /// </param>
        /// <exception cref="ApplicationException">
        /// </exception>
        protected void CreateBoard(
            string adminName,
            string adminPassword,
            string adminEmail,
            string adminPasswordQuestion,
            string adminPasswordAnswer,
            string boardName,
            string boardMembershipAppName,
            string boardRolesAppName,
            bool createUserAndRoles)
        {
            // Store current App Names
            string currentMembershipAppName = PageContext.CurrentMembership.ApplicationName;
            string currentRolesAppName      = PageContext.CurrentRoles.ApplicationName;

            if (boardMembershipAppName.IsSet() && boardRolesAppName.IsSet())
            {
                // Change App Names for new board
                PageContext.CurrentMembership.ApplicationName = boardMembershipAppName;
                PageContext.CurrentMembership.ApplicationName = boardRolesAppName;
            }

            int newBoardID = 0;

            System.Data.DataTable cult = StaticDataHelper.Cultures();
            string langFile            = "english.xml";

            foreach (System.Data.DataRow drow in cult.Rows)
            {
                if (drow["CultureTag"].ToString() == this.Culture.SelectedValue)
                {
                    langFile = (string)drow["CultureFile"];
                }
            }
            if (createUserAndRoles)
            {
                // Create new admin users
                MembershipCreateStatus createStatus;
                MembershipUser         newAdmin = PageContext.CurrentMembership.CreateUser(
                    adminName, adminPassword, adminEmail, adminPasswordQuestion, adminPasswordAnswer, true, null, out createStatus);
                if (createStatus != MembershipCreateStatus.Success)
                {
                    PageContext.AddLoadMessage("Create User Failed: {0}".FormatWith(this.GetMembershipErrorMessage(createStatus)));
                    throw new ApplicationException("Create User Failed: {0}".FormatWith(this.GetMembershipErrorMessage(createStatus)));
                }

                // Create groups required for the new board
                RoleMembershipHelper.CreateRole("Administrators");
                RoleMembershipHelper.CreateRole("Registered");

                // Add new admin users to group
                RoleMembershipHelper.AddUserToRole(newAdmin.UserName, "Administrators");

                // Create Board
                newBoardID = DB.board_create(newAdmin.UserName, newAdmin.Email, newAdmin.ProviderUserKey, boardName, this.Culture.SelectedItem.Value, langFile, boardMembershipAppName, boardRolesAppName);
            }
            else
            {
                // new admin
                MembershipUser newAdmin = UserMembershipHelper.GetUser();

                // Create Board
                newBoardID = DB.board_create(newAdmin.UserName, newAdmin.Email, newAdmin.ProviderUserKey, boardName, this.Culture.SelectedItem.Value, langFile, boardMembershipAppName, boardRolesAppName);
            }


            if (newBoardID > 0 && Config.MultiBoardFolders)
            {
                // Successfully created the new board
                string boardFolder = Server.MapPath(Path.Combine(Config.BoardRoot, newBoardID.ToString() + "/"));

                // Create New Folders.
                if (!Directory.Exists(Path.Combine(boardFolder, "Images")))
                {
                    // Create the Images Folders
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images"));

                    // Create Sub Folders
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Avatars"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Categories"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Forums"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Emoticons"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Medals"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Ranks"));
                }

                if (!Directory.Exists(Path.Combine(boardFolder, "Themes")))
                {
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Themes"));

                    // Need to copy default theme to the Themes Folder
                }

                if (!Directory.Exists(Path.Combine(boardFolder, "Uploads")))
                {
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Uploads"));
                }
            }


            // Return application name to as they were before.
            YafContext.Current.CurrentMembership.ApplicationName = currentMembershipAppName;
            YafContext.Current.CurrentRoles.ApplicationName      = currentRolesAppName;
        }
Example #11
0
        /// <summary>
        /// The create board.
        /// </summary>
        /// <param name="adminName">The admin name.</param>
        /// <param name="adminPassword">The admin password.</param>
        /// <param name="adminEmail">The admin email.</param>
        /// <param name="adminPasswordQuestion">The admin password question.</param>
        /// <param name="adminPasswordAnswer">The admin password answer.</param>
        /// <param name="boardName">The board name.</param>
        /// <param name="boardMembershipAppName">The board membership app name.</param>
        /// <param name="boardRolesAppName">The board roles app name.</param>
        /// <param name="createUserAndRoles">The create user and roles.</param>
        /// <returns>Returns if the board was created or not</returns>
        protected bool CreateBoard(
            [NotNull] string adminName,
            [NotNull] string adminPassword,
            [NotNull] string adminEmail,
            [NotNull] string adminPasswordQuestion,
            [NotNull] string adminPasswordAnswer,
            [NotNull] string boardName,
            [NotNull] string boardMembershipAppName,
            [NotNull] string boardRolesAppName,
            bool createUserAndRoles)
        {
            // Store current App Names
            var currentMembershipAppName = this.Get <MembershipProvider>().ApplicationName;
            var currentRolesAppName      = this.Get <RoleProvider>().ApplicationName;

            if (boardMembershipAppName.IsSet() && boardRolesAppName.IsSet())
            {
                // Change App Names for new board
                this.Get <MembershipProvider>().ApplicationName = boardMembershipAppName;
                this.Get <MembershipProvider>().ApplicationName = boardRolesAppName;
            }

            int newBoardId;
            var cult     = StaticDataHelper.Cultures();
            var langFile = "english.xml";

            cult.Where(dataRow => dataRow.CultureTag == this.Culture.SelectedValue)
            .ForEach(row => langFile = row.CultureFile);

            if (createUserAndRoles)
            {
                // Create new admin users
                var newAdmin = this.Get <MembershipProvider>()
                               .CreateUser(
                    adminName,
                    adminPassword,
                    adminEmail,
                    adminPasswordQuestion,
                    adminPasswordAnswer,
                    true,
                    null,
                    out var createStatus);

                if (createStatus != MembershipCreateStatus.Success)
                {
                    this.PageContext.AddLoadMessage(
                        $"Create User Failed: {this.GetMembershipErrorMessage(createStatus)}",
                        MessageTypes.danger);

                    return(false);
                }

                // Create groups required for the new board
                RoleMembershipHelper.CreateRole("Administrators");
                RoleMembershipHelper.CreateRole("Registered");

                // Add new admin users to group
                RoleMembershipHelper.AddUserToRole(newAdmin.UserName, "Administrators");

                // Create Board
                newBoardId = this.DbCreateBoard(
                    boardName,
                    boardMembershipAppName,
                    boardRolesAppName,
                    langFile,
                    newAdmin);
            }
            else
            {
                // new admin
                var newAdmin = UserMembershipHelper.GetUser();

                // Create Board
                newBoardId = this.DbCreateBoard(
                    boardName,
                    boardMembershipAppName,
                    boardRolesAppName,
                    langFile,
                    newAdmin);
            }

            if (newBoardId > 0 && Config.MultiBoardFolders)
            {
                // Successfully created the new board
                var boardFolder = this.Server.MapPath(Path.Combine(Config.BoardRoot, $"{newBoardId}/"));

                // Create New Folders.
                if (!Directory.Exists(Path.Combine(boardFolder, "Images")))
                {
                    // Create the Images Folders
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images"));

                    // Create Sub Folders
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Avatars"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Categories"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Forums"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Medals"));
                }

                if (!Directory.Exists(Path.Combine(boardFolder, "Uploads")))
                {
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Uploads"));
                }
            }

            // Return application name to as they were before.
            this.Get <MembershipProvider>().ApplicationName = currentMembershipAppName;
            this.Get <RoleProvider>().ApplicationName       = currentRolesAppName;

            return(true);
        }
Example #12
0
        /// <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)
        {
            // go through all roles displayed on page
            for (int i = 0; i < this.UserGroups.Items.Count; i++)
            {
                // get current item
                RepeaterItem item = this.UserGroups.Items[i];

                // get role ID from it
                int roleID = int.Parse(((Label)item.FindControl("GroupID")).Text);

                // get role name
                string roleName = string.Empty;
                using (DataTable dt = this.Get <IDbFunction>().GetAsDataTable(cdb => cdb.group_list(this.PageContext.PageBoardID, roleID)))
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        roleName = (string)row["Name"];
                    }
                }

                // is user supposed to be in that role?
                bool isChecked = ((CheckBox)item.FindControl("GroupMember")).Checked;

                // save user in role
                this.Get <IDbFunction>().Query.usergroup_save(this.CurrentUserID, roleID, isChecked);

                // empty out access table
                this.Get <IDbFunction>().Query.activeaccess_reset();

                // update roles if this user isn't the guest
                if (UserMembershipHelper.IsGuestUser(this.CurrentUserID))
                {
                    continue;
                }

                // get user's name
                string userName = UserMembershipHelper.GetUserNameFromID(this.CurrentUserID);

                // add/remove user from roles in membership provider
                if (isChecked && !RoleMembershipHelper.IsUserInRole(userName, roleName))
                {
                    RoleMembershipHelper.AddUserToRole(userName, roleName);
                }
                else if (!isChecked && RoleMembershipHelper.IsUserInRole(userName, roleName))
                {
                    RoleMembershipHelper.RemoveUserFromRole(userName, roleName);
                }

                // Clearing cache with old permisssions data...
                this.Get <IDataCache>().Remove(Constants.Cache.ActiveUserLazyData.FormatWith(this.CurrentUserID));
            }

            // 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();
        }
Example #13
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </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)
        {
            // we're in the admin section...
            this.ProfileEditControl.InAdminPages   = true;
            this.SignatureEditControl.InAdminPages = true;
            this.AvatarEditControl.InAdminPages    = true;

            this.PageContext.QueryIDs = new QueryStringIDHelper("u", true);

            DataTable dt = LegacyDb.user_list(this.PageContext.PageBoardID, this.CurrentUserID, null);

            if (dt.Rows.Count != 1)
            {
                return;
            }

            DataRow userRow = dt.Rows[0];

            // do admin permission check...
            if (!this.PageContext.IsHostAdmin && this.IsUserHostAdmin(userRow))
            {
                // user is not host admin and is attempted to edit host admin account...
                YafBuildLink.AccessDenied();
            }

            if (this.IsPostBack)
            {
                return;
            }

            this.PageLinks.AddRoot();
            this.PageLinks.AddLink(
                this.GetText("ADMIN_ADMIN", "Administration"), YafBuildLink.GetLink(ForumPages.admin_admin));

            this.PageLinks.AddLink(this.GetText("ADMIN_USERS", "TITLE"), YafBuildLink.GetLink(ForumPages.admin_users));

            var userName = this.Get <YafBoardSettings>().EnableDisplayName
                               ? userRow["DisplayName"].ToString()
                               : userRow["Name"].ToString();

            // current page label (no link)
            this.PageLinks.AddLink(
                this.GetText("ADMIN_EDITUSER", "TITLE").FormatWith(userName),
                string.Empty);

            this.Page.Header.Title = "{0} - {1} - {2}".FormatWith(
                this.GetText("ADMIN_ADMIN", "Administration"),
                this.GetText("ADMIN_USERS", "TITLE"),
                this.GetText("ADMIN_EDITUSER", "TITLE").FormatWith(userName));

            // do a quick user membership sync...
            MembershipUser user = UserMembershipHelper.GetMembershipUserById(this.CurrentUserID);

            // update if the user is not Guest
            if (!this.IsGuestUser)
            {
                RoleMembershipHelper.UpdateForumUser(user, this.PageContext.PageBoardID);
            }

            this.EditUserTabs.DataBind();
        }
Example #14
0
        private static bool CreateTwitterUser(TwitterUser twitterUser, OAuthTwitter oAuth, out string message)
        {
            if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Create User if not exists?! Doesnt work because there is no Email
            var email = "{0}@twitter.com".FormatWith(twitterUser.UserName);

            // 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(twitterUser.UserName, twitterUser.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(twitterUser.UserName, twitterUser.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;
             *  }
             * }*/

            // Create User if not exists?!
            MembershipCreateStatus status;

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            SitecoreMembershipUser user = YafContext.Current.Get <MembershipProvider>()
                                          .CreateUser(
                twitterUser.UserName,
                pass,
                email,
                "Answer is a generated Pass",
                securityAnswer,
                true,
                null,
                out status).ToType <SitecoreMembershipUser>();

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, twitterUser.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(twitterUser.UserName);

            userProfile.TwitterId = twitterUser.UserId.ToString();
            userProfile.Twitter   = twitterUser.UserName;
            userProfile.Homepage  = twitterUser.Url.IsSet()
                                       ? twitterUser.Url
                                       : "http://twitter.com/{0}".FormatWith(twitterUser.UserName);
            userProfile.RealName  = twitterUser.Name;
            userProfile.Interests = twitterUser.Description;
            userProfile.Location  = twitterUser.Location;

            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_TWITTER_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);
            }

            // save the time zone...
            int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            // send user register notification to the following admin users...
            SendRegistrationMessageToTwitterUser(user, pass, securityAnswer, userId, oAuth);

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                twitterUser.UserName,
                null,
                email,
                0,
                null,
                null,
                null,
                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
            if (twitterUser.ProfileImageUrl.IsSet())
            {
                LegacyDb.user_saveavatar(userId, twitterUser.ProfileImageUrl, null, null);
            }

            LoginTwitterSuccess(true, oAuth, userId, user);

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "UPDATE_EMAIL");

            return(true);
        }
Example #15
0
        /// <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;
            }

            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"));
                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();

            var autoWatchTopicsEnabled =
                this.Get <YafBoardSettings>()
                .DefaultNotificationSetting.Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo);

            // 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,
                this.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                null,
                null,
                null);

            if (this.Get <YafBoardSettings>().EmailVerification)
            {
                this.Get <ISendNotification>().SendVerificationEmail(user, newEmail, userID, newUsername);
            }

            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);
        }
Example #16
0
        /// <summary>
        /// Creates the or assign twitter user.
        /// </summary>
        /// <param name="twitterUser">The twitter user.</param>
        /// <param name="oAuth">The oAUTH.</param>
        /// <param name="message">The message.</param>
        /// <returns>
        /// Returns if the login was successfully or not
        /// </returns>
        private static bool CreateTwitterUser(TwitterUser twitterUser, OAuthTwitter oAuth, out string message)
        {
            if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Create User if not exists?! Doesnt work because there is no Email
            var email = "{0}@twitter.com".FormatWith(twitterUser.UserName);

            // Create User if not exists?!
            MembershipCreateStatus status;

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            MembershipUser user = YafContext.Current.Get <MembershipProvider>()
                                  .CreateUser(
                twitterUser.UserName,
                pass,
                email,
                "Answer is a generated Pass",
                securityAnswer,
                true,
                null,
                out status);

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, twitterUser.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(twitterUser.UserName);

            userProfile.TwitterId = twitterUser.UserId.ToString();
            userProfile.Twitter   = twitterUser.UserName;
            userProfile.Homepage  = twitterUser.Url.IsSet()
                                       ? twitterUser.Url
                                       : "http://twitter.com/{0}".FormatWith(twitterUser.UserName);
            userProfile.RealName  = twitterUser.Name;
            userProfile.Interests = twitterUser.Description;
            userProfile.Location  = twitterUser.Location;

            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_TWITTER_FAILED");

                return(false);
            }

            if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafSingleSignOnUser.SendRegistrationNotificationEmail(user);
            }

            // save the time zone...
            int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            // send user register notification to the following admin users...
            SendRegistrationMessageToTwitterUser(user, pass, securityAnswer, userId, oAuth);

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                twitterUser.UserName,
                null,
                email,
                0,
                null,
                null,
                null,
                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
            if (twitterUser.ProfileImageUrl.IsSet())
            {
                LegacyDb.user_saveavatar(userId, twitterUser.ProfileImageUrl, null, null);
            }

            LoginTwitterSuccess(true, oAuth, userId, user);

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "UPDATE_EMAIL");

            return(true);
        }
Example #17
0
        /// <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 (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Check user for bot
            var isPossibleSpamBot = false;

            var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress();

            // Check content for spam
            if (YafContext.Current.Get <ISpamCheck>().CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out var result))
            {
                YafContext.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 (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 {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 {userIpAddress}",
                            EventLogTypes.IpBanSet);
                    }

                    return(false);
                }
            }

            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 var 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);

            // setup their initial profile information
            userProfile.Save();

            userProfile.GoogleId = googleUser.UserID;
            userProfile.Homepage = googleUser.ProfileURL;

            userProfile.Gender = userGender;

            if (YafContext.Current.Get <YafBoardSettings>().EnableIPInfoService)
            {
                var userIpLocator = YafContext.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 = 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);

            var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            YafContext.Current.GetRepository <User>().Save(
                userId,
                YafContext.Current.PageBoardID,
                googleUser.UserName,
                googleUser.UserName,
                googleUser.Email,
                TimeZoneInfo.Local.Id,
                null,
                null,
                null,
                null,
                null,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                TimeZoneInfo.Local.SupportsDaylightSavingTime,
                null,
                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, 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);
        }
Example #18
0
        /// <summary>
        /// Handles page load event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // if user isn't authenticated, redirect him to login page
            if (User == null || YafContext.Current.IsGuest)
            {
                RedirectNoAccess();
            }

            // set attributes of editor
            this._editor.BaseDir    = YafForumInfo.ForumClientFileRoot + "editors";
            this._editor.StyleSheet = YafContext.Current.Theme.BuildThemePath("theme.css");

            // this needs to be done just once, not during postbacks
            if (!IsPostBack)
            {
                // create page links
                this.CreatePageLinks();

                // localize button labels
                this.FindUsers.Text = GetText("FINDUSERS");
                this.AllUsers.Text  = GetText("ALLUSERS");
                this.Clear.Text     = GetText("CLEAR");

                // only administrators can send messages to all users
                this.AllUsers.Visible = YafContext.Current.IsAdmin;

                if (this.Request.QueryString.GetFirstOrDefault("p").IsSet())
                {
                    // PM is a reply or quoted reply (isQuoting)
                    // to the given message id "p"
                    bool isQuoting = Request.QueryString.GetFirstOrDefault("q") == "1";

                    // get quoted message
                    DataRow row = DB.pmessage_list(Security.StringToLongOrRedirect(Request.QueryString.GetFirstOrDefault("p"))).GetFirstRow();

                    // there is such a message
                    if (row != null)
                    {
                        // get message sender/recipient
                        var toUserId   = (int)row["ToUserID"];
                        var fromUserId = (int)row["FromUserID"];

                        // verify access to this PM
                        if (toUserId != YafContext.Current.PageUserID && fromUserId != YafContext.Current.PageUserID)
                        {
                            YafBuildLink.AccessDenied();
                        }

                        // handle subject
                        var subject = (string)row["Subject"];
                        if (!subject.StartsWith("Re: "))
                        {
                            subject = string.Format("Re: {0}", subject);
                        }

                        this.PmSubjectTextBox.Text = subject;

                        string displayName = PageContext.UserDisplayName.GetName(fromUserId);

                        // set "To" user and disable changing...
                        this.To.Text           = displayName;
                        this.To.Enabled        = false;
                        this.FindUsers.Enabled = false;
                        this.AllUsers.Enabled  = false;

                        if (isQuoting)
                        {
                            // PM is a quoted reply
                            string body = row["Body"].ToString();

                            if (YafContext.Current.BoardSettings.RemoveNestedQuotes)
                            {
                                body = YafFormatMessage.RemoveNestedQuotes(body);
                            }

                            // Ensure quoted replies have bad words removed from them
                            body = this.Get <YafBadWordReplace>().Replace(body);

                            // Quote the original message
                            body = "[QUOTE={0}]{1}[/QUOTE]".FormatWith(displayName, body);

                            // we don't want any whitespaces at the beginning of message
                            this._editor.Text = body.TrimStart();
                        }
                    }
                }
                else if (this.Request.QueryString.GetFirstOrDefault("u").IsSet() && this.Request.QueryString.GetFirstOrDefault("r").IsSet())
                {
                    // We check here if the user have access to the option
                    if (PageContext.IsModerator || PageContext.IsForumModerator)
                    {
                        // PM is being sent to a predefined user
                        int toUser;
                        int reportMessage;

                        if (Int32.TryParse(this.Request.QueryString.GetFirstOrDefault("u"), out toUser) &&
                            Int32.TryParse(this.Request.QueryString.GetFirstOrDefault("r"), out reportMessage))
                        {
                            // get quoted message
                            DataRow messagesRow =
                                DB.message_listreporters(
                                    Security.StringToLongOrRedirect(this.Request.QueryString.GetFirstOrDefault("r")).ToType <int>(),
                                    Security.StringToLongOrRedirect(this.Request.QueryString.GetFirstOrDefault("u")).ToType <int>()).GetFirstRow();

                            // there is such a message
                            // message info should be always returned as 1 row
                            if (messagesRow != null)
                            {
                                // handle subject
                                this.PmSubjectTextBox.Text = this.GetText("REPORTED_SUBJECT");

                                string displayName = PageContext.UserDisplayName.GetName(messagesRow.Field <int>("UserID"));

                                // set "To" user and disable changing...
                                this.To.Text           = displayName;
                                this.To.Enabled        = false;
                                this.FindUsers.Enabled = false;
                                this.AllUsers.Enabled  = false;

                                // Parse content with delimiter '|'
                                string[] quoteList = messagesRow.Field <string>("ReportText").Split('|');

                                // Quoted replies should have bad words in them
                                // Reply to report PM is always a quoted reply
                                // Quote the original message in a cycle
                                for (int i = 0; i < quoteList.Length; i++)
                                {
                                    // Add quote codes
                                    quoteList[i] = "[QUOTE={0}]{1}[/QUOTE]".FormatWith(displayName, quoteList[i]);

                                    // Replace DateTime delimiter '??' by ': '
                                    // we don't want any whitespaces at the beginning of message
                                    this._editor.Text = quoteList[i].Replace("??", ": ") + this._editor.Text.TrimStart();
                                }
                            }
                        }
                    }
                }
                else if (this.Request.QueryString.GetFirstOrDefault("u").IsSet())
                {
                    // PM is being send as a reply to a reported post

                    // find user
                    int toUserId;

                    if (Int32.TryParse(Request.QueryString.GetFirstOrDefault("u"), out toUserId))
                    {
                        DataRow currentRow = DB.user_list(YafContext.Current.PageBoardID, toUserId, true).GetFirstRow();

                        if (currentRow != null)
                        {
                            this.To.Text    = PageContext.UserDisplayName.GetName(currentRow.Field <int>("UserID"));
                            this.To.Enabled = false;

                            // Simon: Disable for admins
                            DisablePMs = RoleMembershipHelper.IsUserInRole(this.To.Text, "Administrators");

                            // hide find user/all users buttons
                            this.FindUsers.Enabled = false;
                            this.AllUsers.Enabled  = false;
                        }
                    }
                }
                else
                {
                    // Blank PM

                    // multi-receiver info is relevant only when sending blank PM
                    if (YafContext.Current.BoardSettings.PrivateMessageMaxRecipients > 1)
                    {
                        // format localized string
                        this.MultiReceiverInfo.Text = "<br />{0}<br />{1}".FormatWith(YafContext.Current.Localization.GetText("MAX_RECIPIENT_INFO").FormatWith(YafContext.Current.BoardSettings.PrivateMessageMaxRecipients), YafContext.Current.Localization.GetText("MULTI_RECEIVER_INFO"));

                        // display info
                        this.MultiReceiverInfo.Visible = true;
                    }
                }
            }
        }
Example #19
0
        /// <summary>
        /// Creates the or assign twitter user.
        /// </summary>
        /// <param name="twitterUser">
        /// The twitter user.
        /// </param>
        /// <param name="oAuth">
        /// The oAUTH.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if the login was successfully or not
        /// </returns>
        private static bool CreateTwitterUser(TwitterUser twitterUser, OAuthTwitter oAuth, out string message)
        {
            if (BoardContext.Current.Get <BoardSettings>().DisableRegistrations)
            {
                message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Create User if not exists?! Doesn't work because there is no Email
            var email = $"{twitterUser.UserName}@twitter.com";

            // Check user for bot

            /*var spamChecker = new YafSpamCheck();
             * string result;
             * var isPossibleSpamBot = false;
             *
             * var userIpAddress = BoardContext.Current.Get<HttpRequestBase>().GetUserRealIPAddress();
             *
             * // Check content for spam
             * if (spamChecker.CheckUserForSpamBot(twitterUser.UserName, twitterUser.Email, userIpAddress, out result))
             * {
             *  BoardContext.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(twitterUser.UserName, twitterUser.Email, userIpAddress, result),
             *      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 {0}".FormatWith(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 {0}".FormatWith(
             *                      userIpAddress),
             *                  EventLogTypes.IpBanSet);
             *      }
             *
             *      return false;
             *  }
             * }*/

            // Create User if not exists?!
            var memberShipProvider = BoardContext.Current.Get <MembershipProvider>();

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            var user = memberShipProvider.CreateUser(
                twitterUser.UserName,
                pass,
                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, twitterUser.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 = Utils.UserProfile.GetProfile(twitterUser.UserName);

            // setup their initial profile information
            userProfile.Save();

            userProfile.TwitterId = twitterUser.UserId.ToString();
            userProfile.Twitter   = twitterUser.UserName;
            userProfile.Homepage  = twitterUser.Url.IsSet()
                                       ? twitterUser.Url
                                       : $"http://twitter.com/{twitterUser.UserName}";
            userProfile.RealName  = twitterUser.Name;
            userProfile.Interests = twitterUser.Description;
            userProfile.Location  = twitterUser.Location;

            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_TWITTER_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);
            }

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            // send user register notification to the following admin users...
            SendRegistrationMessageToTwitterUser(user, pass, securityAnswer, userId, oAuth);

            var autoWatchTopicsEnabled = BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            BoardContext.Current.GetRepository <User>().Save(
                userId,
                BoardContext.Current.PageBoardID,
                twitterUser.UserName,
                twitterUser.UserName,
                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
            if (twitterUser.ProfileImageUrl.IsSet())
            {
                BoardContext.Current.GetRepository <User>().SaveAvatar(userId, twitterUser.ProfileImageUrl, null, null);
            }

            LoginTwitterSuccess(true, oAuth, userId, user);

            message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "UPDATE_EMAIL");

            return(true);
        }
Example #20
0
        /// <summary>
        /// Handles save button click event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Save_Click(object sender, EventArgs e)
        {
            // recipient was set in dropdown
            if (this.ToList.Visible)
            {
                this.To.Text = this.ToList.SelectedItem.Text;
            }

            // Simon: Disable for admins
            DisablePMs = RoleMembershipHelper.IsUserInRole(this.To.Text, "Administrators");
            if (DisablePMs)
            {
                return;
            }


            if (this.To.Text.Length <= 0)
            {
                // recipient is required field
                YafContext.Current.AddLoadMessage(GetText("need_to"));
                return;
            }

            // subject is required
            if (this.PmSubjectTextBox.Text.Trim().Length <= 0)
            {
                YafContext.Current.AddLoadMessage(GetText("need_subject"));
                return;
            }

            // message is required
            if (this._editor.Text.Trim().Length <= 0)
            {
                YafContext.Current.AddLoadMessage(GetText("need_message"));
                return;
            }

            if (this.ToList.SelectedItem != null && this.ToList.SelectedItem.Value == "0")
            {
                // administrator is sending PMs tp all users
                string body         = this._editor.Text;
                var    messageFlags = new MessageFlags();

                messageFlags.IsHtml   = this._editor.UsesHTML;
                messageFlags.IsBBCode = this._editor.UsesBBCode;

                DB.pmessage_save(YafContext.Current.PageUserID, 0, this.PmSubjectTextBox.Text, body, messageFlags.BitValue);

                // redirect to outbox (sent items), not control panel
                YafBuildLink.Redirect(ForumPages.cp_pm, "v={0}", "out");
            }
            else
            {
                // remove all abundant whitespaces and separators
                this.To.Text.Trim();
                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 > YafContext.Current.BoardSettings.PrivateMessageMaxRecipients && !YafContext.Current.IsAdmin &&
                    YafContext.Current.BoardSettings.PrivateMessageMaxRecipients != 0)
                {
                    // to many recipients
                    YafContext.Current.AddLoadMessage(GetTextFormatted("TOO_MANY_RECIPIENTS", YafContext.Current.BoardSettings.PrivateMessageMaxRecipients));
                    return;
                }


                // test sending user's PM count
                // get user's name
                DataRow drPMInfo = DB.user_pmcount(YafContext.Current.PageUserID).Rows[0];

                if ((Convert.ToInt32(drPMInfo["NumberTotal"]) > Convert.ToInt32(drPMInfo["NumberAllowed"]) + recipients.Count) && !YafContext.Current.IsAdmin)
                {
                    // user has full PM box
                    YafContext.Current.AddLoadMessage(GetTextFormatted("OWN_PMBOX_FULL", drPMInfo["NumberAllowed"]));
                    return;
                }

                // list of recipient's ids
                var recipientIds = new List <int>();

                // get recipients' IDs
                foreach (string recipient in recipients)
                {
                    int?userId = PageContext.UserDisplayName.GetId(recipient);

                    if (!userId.HasValue)
                    {
                        YafContext.Current.AddLoadMessage(GetTextFormatted("NO_SUCH_USER", recipient));
                        return;
                    }
                    else if (UserMembershipHelper.IsGuestUser(userId.Value))
                    {
                        YafContext.Current.AddLoadMessage(GetText("NOT_GUEST"));
                        return;
                    }

                    // get recipient's ID from the database
                    if (!recipientIds.Contains(userId.Value))
                    {
                        recipientIds.Add(userId.Value);
                    }

                    // test receiving user's PM count
                    if ((DB.user_pmcount(userId.Value).Rows[0]["NumberTotal"].ToType <int>() >=
                         DB.user_pmcount(userId.Value).Rows[0]["NumberAllowed"].ToType <int>()) &&
                        !YafContext.Current.IsAdmin && !(bool)Convert.ChangeType(UserMembershipHelper.GetUserRowForID(userId.Value, true)["IsAdmin"], typeof(bool)))
                    {
                        // recipient has full PM box
                        YafContext.Current.AddLoadMessage(GetTextFormatted("RECIPIENTS_PMBOX_FULL", recipient));
                        return;
                    }
                }

                // send PM to all recipients
                foreach (var userId in recipientIds)
                {
                    string body = this._editor.Text;

                    var messageFlags = new MessageFlags();

                    messageFlags.IsHtml   = this._editor.UsesHTML;
                    messageFlags.IsBBCode = this._editor.UsesBBCode;

                    DB.pmessage_save(YafContext.Current.PageUserID, userId, this.PmSubjectTextBox.Text, body, messageFlags.BitValue);

                    // reset reciever's lazy data as he should be informed at once
                    PageContext.Cache.Remove(YafCache.GetBoardCacheKey(Constants.Cache.ActiveUserLazyData.FormatWith(userId)));

                    if (YafContext.Current.BoardSettings.AllowPMEmailNotification)
                    {
                        this.Get <YafSendNotification>().ToPrivateMessageRecipient(userId, this.PmSubjectTextBox.Text.Trim());
                    }
                }

                // redirect to outbox (sent items), not control panel
                YafBuildLink.Redirect(ForumPages.cp_pm, "v={0}", "out");
            }
        }
Example #21
0
        /// <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);

            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;
            }

            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);

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                facebookUser.UserName,
                facebookUser.UserName,
                facebookUser.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,
                "https://graph.facebook.com/{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);
        }
Example #22
0
        /// <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();
        }
Example #23
0
        /// <summary>
        /// The wizard_ next button click.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.Web.UI.WebControls.WizardNavigationEventArgs"/> instance containing the event data.
        /// </param>
        protected void Wizard_NextButtonClick([NotNull] object sender, [NotNull] WizardNavigationEventArgs e)
        {
            e.Cancel = true;

            switch (this.CurrentWizardStepID)
            {
            case "WizValidatePermission":
                e.Cancel = false;
                break;

            case "WizDatabaseConnection":

                // save the database settings...
                var type = this.UpdateDatabaseConnection();
                e.Cancel = false;

                switch (type)
                {
                case UpdateDBFailureType.None:
                    this.CurrentWizardStepID = "WizTestSettings";
                    break;

                case UpdateDBFailureType.AppSettingsWrite:
                    this.NoWriteAppSettingsHolder.Visible = true;
                    break;

                case UpdateDBFailureType.ConnectionStringWrite:
                    this.NoWriteDBSettingsHolder.Visible = true;
                    this.lblDBConnStringName.Text        = Config.ConnectionStringName;
                    this.lblDBConnStringValue.Text       = this.CurrentConnString;
                    break;
                }

                break;

            case "WizManualDatabaseConnection":
                e.Cancel = false;
                break;

            case "WizCreatePassword":
                if (this.txtCreatePassword1.Text.Trim() == string.Empty)
                {
                    this.ShowErrorMessage("Please enter a configuration password.");
                    break;
                }

                if (this.txtCreatePassword2.Text != this.txtCreatePassword1.Text)
                {
                    this.ShowErrorMessage("Verification is not the same as your password.");
                    break;
                }

                e.Cancel = false;

                this.CurrentWizardStepID =
                    this._config.WriteAppSetting(_AppPasswordKey, this.txtCreatePassword1.Text)
                            ? "WizDatabaseConnection"
                            : "WizManuallySetPassword";

                break;

            case "WizManuallySetPassword":
                if (this.IsConfigPasswordSet)
                {
                    e.Cancel = false;
                }
                else
                {
                    this.ShowErrorMessage(
                        "You must update your appSettings with the YAF.ConfigPassword Key to continue. NOTE: The key name is case sensitive.");
                }

                break;

            case "WizTestSettings":
                e.Cancel = false;
                break;

            case "WizEnterPassword":
                if (this._config.GetConfigValueAsString(_AppPasswordKey)
                    == FormsAuthentication.HashPasswordForStoringInConfigFile(this.txtEnteredPassword.Text, "md5") ||
                    this._config.GetConfigValueAsString(_AppPasswordKey) == this.txtEnteredPassword.Text.Trim())
                {
                    e.Cancel = false;

                    // move to upgrade..
                    this.CurrentWizardStepID = this.IsForumInstalled ? "WizWelcomeUpgrade" : "WizDatabaseConnection";

                    var dbVersionName = LegacyDb.GetDBVersionName();
                    var dbVersion     = LegacyDb.GetDBVersion();

                    this.CurrentVersionName.Text = dbVersion < 0
                                                           ? "New"
                                                           : "{0} ({1})".FormatWith(dbVersionName, dbVersion);
                    this.UpgradeVersionName.Text = "{0} ({1})".FormatWith(YafForumInfo.AppVersionName, YafForumInfo.AppVersion);
                }
                else
                {
                    this.ShowErrorMessage("You entered the <strong>wrong password</strong>!");
                }

                break;

            case "WizCreateForum":
                if (this.CreateForum())
                {
                    e.Cancel = false;
                }

                break;

            case "WizInitDatabase":
                if (this.InstallUpgradeService.UpgradeDatabase(
                        this.FullTextSupport.Checked,
                        this.UpgradeExtensions.Checked))
                {
                    e.Cancel = false;
                }

                var messages = this.InstallUpgradeService.Messages;

                if (messages.Any())
                {
                    this._loadMessage += messages.ToDelimitedString("\r\n");
                }

                this.ShowErrorMessage(this._loadMessage);

                break;

            case "WizMigrateUsers":

                // migrate users/roles only if user does not want to skip
                if (!this.skipMigration.Checked)
                {
                    RoleMembershipHelper.SyncRoles(this.PageBoardID);

                    // start the background migration task...
                    this.Get <ITaskModuleManager>().Start <MigrateUsersTask>(this.PageBoardID);
                }

                e.Cancel = false;
                break;

            case "WizWelcomeUpgrade":

                e.Cancel = false;

                // move to upgrade..
                this.CurrentWizardStepID = "WizInitDatabase";
                break;

            case "WizWelcome":

                e.Cancel = false;

                // move to upgrade..
                this.CurrentWizardStepID = "WizValidatePermission";
                break;

            case "WizFinished":
                break;

            default:
                throw new ApplicationException(
                          "Installation Wizard step not handled: {0}".FormatWith(
                              this.InstallWizard.WizardSteps[e.CurrentStepIndex].ID));
            }
        }
Example #24
0
        /// <summary>
        /// The bind data.
        /// </summary>
        private void BindData()
        {
            MembershipUser user = UserMembershipHelper.GetMembershipUserById(this.UserId);

            if (user == null || user.ProviderUserKey.ToString() == "0")
            {
                // No such user exists or this is an nntp user ("0")
                YafBuildLink.AccessDenied();
            }

            var userData = new CombinedUserDataHelper(user, this.UserId);

            // populate user information controls...
            // Is BuddyList feature enabled?
            if (this.Get <YafBoardSettings>().EnableBuddyList)
            {
                this.SetupBuddyList(this.UserId, userData);
            }
            else
            {
                // BuddyList feature is disabled. don't show any link.
                this.BuddyLi.Visible      = false;
                this.BuddyListTab.Visible = false;
                this.lnkBuddy.Visible     = false;
                this.ltrApproval.Visible  = false;
            }

            // Is album feature enabled?
            if (this.Get <YafBoardSettings>().EnableAlbum)
            {
                this.AlbumList1.UserID = this.UserId;
            }
            else
            {
                this.AlbumList1.Dispose();
            }

            var userNameOrDisplayName = this.Get <YafBoardSettings>().EnableDisplayName
                                            ? userData.DisplayName
                                            : userData.UserName;

            this.SetupUserProfileInfo(this.UserId, user, userData, userNameOrDisplayName);

            this.AddPageLinks(userNameOrDisplayName);

            this.SetupUserStatistics(userData);

            this.SetupUserLinks(userData, userNameOrDisplayName);

            this.SetupAvatar(this.UserId, userData);

            this.Groups.DataSource = RoleMembershipHelper.GetRolesForUser(userData.UserName);

            // EmailRow.Visible = PageContext.IsAdmin;
            this.ModerateTab.Visible = this.PageContext.IsAdmin || this.PageContext.IsForumModerator;
            this.ModerateLi.Visible  = this.PageContext.IsAdmin || this.PageContext.IsForumModerator;

            this.AdminUserButton.Visible = this.PageContext.IsAdmin;

            if (this.LastPosts.Visible)
            {
                this.LastPosts.DataSource =
                    LegacyDb.post_alluser(this.PageContext.PageBoardID, this.UserId, this.PageContext.PageUserID, 10)
                    .AsEnumerable();

                this.SearchUser.NavigateUrl = YafBuildLink.GetLinkNotEscaped(
                    ForumPages.search,
                    "postedby={0}",
                    this.Get <YafBoardSettings>().EnableDisplayName ? userData.DisplayName : userData.UserName);
            }

            this.DataBind();
        }
Example #25
0
        /// <summary>
        /// The create board.
        /// </summary>
        /// <param name="adminName">The admin name.</param>
        /// <param name="adminPassword">The admin password.</param>
        /// <param name="adminEmail">The admin email.</param>
        /// <param name="adminPasswordQuestion">The admin password question.</param>
        /// <param name="adminPasswordAnswer">The admin password answer.</param>
        /// <param name="boardName">The board name.</param>
        /// <param name="boardMembershipAppName">The board membership app name.</param>
        /// <param name="boardRolesAppName">The board roles app name.</param>
        /// <param name="createUserAndRoles">The create user and roles.</param>
        /// <returns></returns>
        protected bool CreateBoard(
            [NotNull] string adminName,
            [NotNull] string adminPassword,
            [NotNull] string adminEmail,
            [NotNull] string adminPasswordQuestion,
            [NotNull] string adminPasswordAnswer,
            [NotNull] string boardName,
            [NotNull] string boardMembershipAppName,
            [NotNull] string boardRolesAppName,
            bool createUserAndRoles)
        {
            // Store current App Names
            string currentMembershipAppName = this.Get <MembershipProvider>().ApplicationName;
            string currentRolesAppName      = this.Get <RoleProvider>().ApplicationName;

            if (boardMembershipAppName.IsSet() && boardRolesAppName.IsSet())
            {
                // Change App Names for new board
                this.Get <MembershipProvider>().ApplicationName = boardMembershipAppName;
                this.Get <MembershipProvider>().ApplicationName = boardRolesAppName;
            }

            int       newBoardID;
            DataTable cult     = StaticDataHelper.Cultures();
            string    langFile = "english.xml";

            foreach (DataRow drow in
                     cult.Rows.Cast <DataRow>().Where(drow => drow["CultureTag"].ToString() == this.Culture.SelectedValue))
            {
                langFile = (string)drow["CultureFile"];
            }

            if (createUserAndRoles)
            {
                // Create new admin users
                MembershipCreateStatus createStatus;
                MembershipUser         newAdmin = this.Get <MembershipProvider>()
                                                  .CreateUser(
                    adminName,
                    adminPassword,
                    adminEmail,
                    adminPasswordQuestion,
                    adminPasswordAnswer,
                    true,
                    null,
                    out createStatus);

                if (createStatus != MembershipCreateStatus.Success)
                {
                    this.PageContext.AddLoadMessage(
                        "Create User Failed: {0}".FormatWith(this.GetMembershipErrorMessage(createStatus)),
                        MessageTypes.danger);

                    return(false);
                }

                // Create groups required for the new board
                RoleMembershipHelper.CreateRole("Administrators");
                RoleMembershipHelper.CreateRole("Registered");

                // Add new admin users to group
                RoleMembershipHelper.AddUserToRole(newAdmin.UserName, "Administrators");

                // Create Board
                newBoardID = this.DbCreateBoard(
                    boardName,
                    boardMembershipAppName,
                    boardRolesAppName,
                    langFile,
                    newAdmin);
            }
            else
            {
                // new admin
                MembershipUser newAdmin = UserMembershipHelper.GetUser();

                // Create Board
                newBoardID = this.DbCreateBoard(
                    boardName,
                    boardMembershipAppName,
                    boardRolesAppName,
                    langFile,
                    newAdmin);
            }

            if (newBoardID > 0 && Config.MultiBoardFolders)
            {
                // Successfully created the new board
                string boardFolder = this.Server.MapPath(Path.Combine(Config.BoardRoot, "{0}/".FormatWith(newBoardID)));

                // Create New Folders.
                if (!Directory.Exists(Path.Combine(boardFolder, "Images")))
                {
                    // Create the Images Folders
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images"));

                    // Create Sub Folders
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Avatars"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Categories"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Forums"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Emoticons"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Medals"));
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Images\\Ranks"));
                }

                if (!Directory.Exists(Path.Combine(boardFolder, "Themes")))
                {
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Themes"));

                    // Need to copy default theme to the Themes Folder
                }

                if (!Directory.Exists(Path.Combine(boardFolder, "Uploads")))
                {
                    Directory.CreateDirectory(Path.Combine(boardFolder, "Uploads"));
                }
            }

            // Return application name to as they were before.
            this.Get <MembershipProvider>().ApplicationName = currentMembershipAppName;
            this.Get <RoleProvider>().ApplicationName       = currentRolesAppName;

            return(true);
        }
Example #26
0
        /// <summary>
        /// The wizard_ next button click.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.Web.UI.WebControls.WizardNavigationEventArgs"/> instance containing the event data.
        /// </param>
        protected void Wizard_NextButtonClick([NotNull] object sender, [NotNull] WizardNavigationEventArgs e)
        {
            e.Cancel = true;

            switch (this.CurrentWizardStepID)
            {
            case "WizValidatePermission":
                e.Cancel = false;
                break;

            case "WizDatabaseConnection":

                // save the database settings...
                UpdateDBFailureType type = this.UpdateDatabaseConnection();
                e.Cancel = false;

                switch (type)
                {
                case UpdateDBFailureType.None:
                    this.CurrentWizardStepID = "WizTestSettings";
                    break;

                case UpdateDBFailureType.AppSettingsWrite:
                    this.NoWriteAppSettingsHolder.Visible = true;
                    break;

                case UpdateDBFailureType.ConnectionStringWrite:
                    this.NoWriteDBSettingsHolder.Visible = true;
                    this.lblDBConnStringName.Text        = Config.ConnectionStringName;
                    this.lblDBConnStringValue.Text       = this.CurrentConnString;
                    break;
                }

                break;

            case "WizManualDatabaseConnection":
                e.Cancel = false;
                break;

            case "WizCreatePassword":
                if (this.txtCreatePassword1.Text.Trim() == string.Empty)
                {
                    this.AddLoadMessage("Please enter a configuration password.");
                    break;
                }

                if (this.txtCreatePassword2.Text != this.txtCreatePassword1.Text)
                {
                    this.AddLoadMessage("Verification is not the same as your password.");
                    break;
                }

                e.Cancel = false;

                if (this._config.TrustLevel >= AspNetHostingPermissionLevel.High &&
                    this._config.WriteAppSetting(_AppPasswordKey, this.txtCreatePassword1.Text))
                {
                    // advance to the testing section since the password is now set...
                    this.CurrentWizardStepID = "WizDatabaseConnection";
                }
                else
                {
                    this.CurrentWizardStepID = "WizManuallySetPassword";
                }

                break;

            case "WizManuallySetPassword":
                if (this.IsInstalled)
                {
                    e.Cancel = false;
                }
                else
                {
                    this.AddLoadMessage(
                        "You must update your appSettings with the YAF.ConfigPassword Key to continue. NOTE: The key name is case sensitive.");
                }

                break;

            case "WizTestSettings":
                e.Cancel = false;
                break;

            case "WizEnterPassword":
                if (this._config.GetConfigValueAsString(_AppPasswordKey)
                    == FormsAuthentication.HashPasswordForStoringInConfigFile(this.txtEnteredPassword.Text, "md5") ||
                    this._config.GetConfigValueAsString(_AppPasswordKey) == this.txtEnteredPassword.Text.Trim())
                {
                    e.Cancel = false;

                    // move to test settings...
                    this.CurrentWizardStepID = "WizTestSettings";
                }
                else
                {
                    this.AddLoadMessage("Wrong password!");
                }

                break;

            case "WizCreateForum":
                if (this.CreateForum())
                {
                    e.Cancel = false;
                }

                break;

            case "WizInitDatabase":
                if (this.InstallUpgradeService.UpgradeDatabase(this.FullTextSupport.Checked, this.UpgradeExtensions.Checked))
                {
                    e.Cancel = false;
                }

                // Check if BaskeUrlMask is set and if not automatically write it
                if (this._config.GetConfigValueAsString(_AppBaseUrlMaskKey).IsNotSet() && this._config.TrustLevel >= AspNetHostingPermissionLevel.High)
                {
#if DEBUG
                    var urlKey =
                        "http://{0}{1}/".FormatWith(
                            HttpContext.Current.Request.ServerVariables["SERVER_NAME"],
                            HttpContext.Current.Request.ServerVariables["SERVER_PORT"].Equals("80")
                                    ? string.Empty
                                    : ":{0}".FormatWith(HttpContext.Current.Request.ServerVariables["SERVER_PORT"]));
#else
                    var urlKey =
                        "http://{0}/".FormatWith(
                            HttpContext.Current.Request.ServerVariables["SERVER_NAME"]);
#endif

                    this._config.WriteAppSetting(_AppBaseUrlMaskKey, urlKey);
                }

                var messages = this.InstallUpgradeService.Messages;

                if (messages.Any())
                {
                    this._loadMessage += messages.ToDelimitedString("\r\n");
                }

                break;

            case "WizMigrateUsers":

                // migrate users/roles only if user does not want to skip
                if (!this.skipMigration.Checked)
                {
                    RoleMembershipHelper.SyncRoles(this.PageBoardID);

                    // start the background migration task...
                    this.Get <ITaskModuleManager>().Start <MigrateUsersTask>(this.PageBoardID);
                }

                e.Cancel = false;
                break;

            case "WizFinished":
                break;

            default:
                throw new ApplicationException(
                          "Installation Wizard step not handled: {0}".FormatWith(
                              this.InstallWizard.WizardSteps[e.CurrentStepIndex].ID));
            }
        }
Example #27
0
        /// <summary>
        /// The render.
        /// </summary>
        /// <param name="writer">
        /// The writer.
        /// </param>
        protected override void Render(HtmlTextWriter writer)
        {
            var hiddenContent = this.Parameters["inner"];

            var groupString = this.Parameters["group"];

            if (hiddenContent.IsNotSet())
            {
                return;
            }

            var descriptionGuest = this.LocalizedString(
                "HIDDENMOD_GUEST",
                "This board requires you to be registered and logged-in before you can view hidden messages.");

            var shownContentGuest = $"<div class=\"alert alert-danger\" role=\"alert\">{descriptionGuest}</div>";

            if (groupString.IsNotSet())
            {
                // Hide from Guests only
                if (BoardContext.Current.IsGuest)
                {
                    writer.Write(shownContentGuest);
                    return;
                }
            }
            else
            {
                if (BoardContext.Current.IsGuest)
                {
                    writer.Write(shownContentGuest);
                    return;
                }

                descriptionGuest = this.LocalizedString(
                    "HIDDENMOD_GROUP",
                    "You dont´t have the right to see the Hidden Content.");

                shownContentGuest = $"<div class=\"alert alert-danger\" role=\"alert\">{descriptionGuest}</div>";

                var groups = groupString.Split(';');

                /*List<string> groups = new List<string>();
                 * List<string> ranks = new List<string>();
                 *
                 * foreach (string group in groupsAndRanks)
                 * {
                 *  if (group.StartsWith("group."))
                 *  {
                 *      groups.Add(group.Substring(group.IndexOf(".") + 1));
                 *  }
                 *  else if (group.StartsWith("rank."))
                 *  {
                 *      ranks.Add(group.Substring(group.IndexOf(".") + 1));
                 *  }
                 *  else
                 *  {
                 *      groups.Add(group);
                 *  }
                 * }*/

                // Check For Role Hiding
                if (RoleMembershipHelper.GetRolesForUser(
                        BoardContext.Current.User.UserName).Any(role => !groups.Any(role.Equals)))
                {
                    shownContentGuest = hiddenContent;
                }

                // TODO : Check for Rank Hiding

                /*if (ranks.Any())
                 * {
                 *  var yafUserData = new CombinedUserDataHelper(BoardContext.Current.CurrentUserData.PageUserID);
                 *
                 *  if (!ranks.Where(rank => yafUserData.RankName.Equals(rank)).Any())
                 *  {
                 *      shownContentGuest = hiddenContent;
                 *  }
                 * }*/
            }

            // Override Admin, or User is Post Author
            if (BoardContext.Current.IsAdmin || this.DisplayUserID == BoardContext.Current.CurrentUserData.UserID)
            {
                shownContentGuest = hiddenContent;
            }

            writer.Write(shownContentGuest);
        }
Example #28
0
        /// <summary>
        /// Creates the YAF user.
        /// </summary>
        /// <param name="dnnUserInfo">The DNN user info.</param>
        /// <param name="dnnUser">The DNN user.</param>
        /// <param name="boardID">The board ID.</param>
        /// <param name="portalID">The portal identifier.</param>
        /// <param name="boardSettings">The board settings.</param>
        /// <returns>
        /// Returns the User ID of the new User
        /// </returns>
        public static int CreateYafUser(
            UserInfo dnnUserInfo,
            MembershipUser dnnUser,
            int boardID,
            int portalID,
            YafBoardSettings boardSettings)
        {
            // setup roles
            RoleMembershipHelper.SetupUserRoles(boardID, dnnUser.UserName);

            // create the user in the YAF DB so profile can gets created...
            var yafUserId = RoleMembershipHelper.CreateForumUser(dnnUser, dnnUserInfo.DisplayName, boardID);

            if (yafUserId == null)
            {
                return(0);
            }

            // create profile
            var userProfile = YafUserProfile.GetProfile(dnnUser.UserName);

            // setup their initial profile information
            userProfile.Initialize(dnnUser.UserName, true);

            if (dnnUserInfo.Profile.FullName.IsSet())
            {
                userProfile.RealName = dnnUserInfo.Profile.FullName;
            }

            if (dnnUserInfo.Profile.Country.IsSet() && !dnnUserInfo.Profile.Country.Equals("N/A"))
            {
                var regionInfo = ProfileSyncronizer.GetRegionInfoFromCountryName(dnnUserInfo.Profile.Country);

                if (regionInfo != null)
                {
                    userProfile.Country = regionInfo.TwoLetterISORegionName;
                }
            }

            if (dnnUserInfo.Profile.City.IsSet())
            {
                userProfile.City = dnnUserInfo.Profile.City;
            }

            if (dnnUserInfo.Profile.Website.IsSet())
            {
                userProfile.Homepage = dnnUserInfo.Profile.Website;
            }

            userProfile.Save();

            // Save User
            LegacyDb.user_save(
                yafUserId,
                boardID,
                dnnUserInfo.Username,
                dnnUserInfo.DisplayName,
                dnnUserInfo.Email,
                0,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                dnnUserInfo.Membership.LastLoginDate.ToUniversalTime());

            var autoWatchTopicsEnabled =
                boardSettings.DefaultNotificationSetting.Equals(UserNotificationSetting.TopicsIPostToOrSubscribeTo);

            // save notification Settings
            LegacyDb.user_savenotification(
                yafUserId,
                true,
                autoWatchTopicsEnabled,
                boardSettings.DefaultNotificationSetting,
                boardSettings.DefaultSendDigestEmail);

            RoleSyncronizer.SynchronizeUserRoles(boardID, portalID, yafUserId.ToType <int>(), dnnUserInfo);

            return(yafUserId.ToType <int>());
        }
Example #29
0
        private string MatchUserBoxGroups([NotNull] string userBox, [NotNull] DataTable roleStyleTable)
        {
            const string StyledNick = @"<span class=""YafGroup_{0}"" style=""{1}"">{0}</span>";

            string filler = string.Empty;

            Regex rx = this.GetRegex(Constants.UserBox.Groups);

            if (this.Get <YafBoardSettings>().ShowGroups)
            {
                var groupsText = new StringBuilder(500);

                bool   bFirst    = true;
                bool   hasRole   = false;
                string roleStyle = null;

                var userName = this.DataRow["IsGuest"].ToType <bool>()
                                   ? UserMembershipHelper.GuestUserName
                                   : this.DataRow["UserName"].ToString();

                foreach (string role in RoleMembershipHelper.GetRolesForUser(userName))
                {
                    string role1 = role;

                    foreach (DataRow drow in
                             roleStyleTable.Rows.Cast <DataRow>().Where(
                                 drow =>
                                 drow["LegendID"].ToType <int>() == 1 && drow["Style"] != null &&
                                 drow["Name"].ToString() == role1))
                    {
                        roleStyle = this.TransformStyle.DecodeStyleByString(drow["Style"].ToString(), true);
                        break;
                    }

                    if (bFirst)
                    {
                        groupsText.AppendLine(
                            this.Get <YafBoardSettings>().UseStyledNicks ? StyledNick.FormatWith(role, roleStyle) : role);

                        bFirst = false;
                    }
                    else
                    {
                        if (this.Get <YafBoardSettings>().UseStyledNicks)
                        {
                            groupsText.AppendLine((@", " + StyledNick).FormatWith(role, roleStyle));
                        }
                        else
                        {
                            groupsText.AppendFormat(", {0}", role);
                        }
                    }

                    roleStyle = null;
                    hasRole   = true;
                }

                // vzrus: Only a guest normally has no role
                if (!hasRole)
                {
                    DataTable dt = this.Get <IDataCache>().GetOrSet(
                        Constants.Cache.GuestGroupsCache,
                        () => LegacyDb.group_member(PageContext.PageBoardID, this.DataRow["UserID"]),
                        TimeSpan.FromMinutes(60));

                    foreach (string guestRole in
                             dt.Rows.Cast <DataRow>().Where(role => role["Member"].ToType <int>() > 0).Select(
                                 role => role["Name"].ToString()))
                    {
                        foreach (DataRow drow in
                                 roleStyleTable.Rows.Cast <DataRow>().Where(
                                     drow =>
                                     drow["LegendID"].ToType <int>() == 1 && drow["Style"] != null &&
                                     drow["Name"].ToString() == guestRole))
                        {
                            roleStyle = this.TransformStyle.DecodeStyleByString(drow["Style"].ToString(), true);
                            break;
                        }

                        groupsText.AppendLine(
                            this.Get <YafBoardSettings>().UseStyledNicks
                                ? StyledNick.FormatWith(guestRole, roleStyle)
                                : guestRole);
                        break;
                    }
                }

                filler = this.Get <YafBoardSettings>().UserBoxGroups.FormatWith(this.GetText("groups"), groupsText);

                // mddubs : 02/21/2009
                // Remove the space before the first comma when multiple groups exist.
                filler = filler.Replace("\r\n,", ",");
            }

            // replaces template placeholder with actual groups
            userBox = rx.Replace(userBox, filler);
            return(userBox);
        }
Example #30
0
        /// <summary>
        /// Import the User From the Current Table Row
        /// </summary>
        /// <param name="row">
        /// The row with the User Information.
        /// </param>
        /// <param name="importCount">
        /// The import Count.
        /// </param>
        /// <returns>
        /// Returns the Imported User Count.
        /// </returns>
        private int ImportUser(DataRow row, int importCount)
        {
            // Also Check if the Email is unique and exists
            if (this.Get <MembershipProvider>().RequiresUniqueEmail)
            {
                if (this.Get <MembershipProvider>().GetUserNameByEmail(email: (string)row[columnName: "Email"]) != null)
                {
                    return(importCount);
                }
            }

            MembershipCreateStatus status;

            var pass             = Membership.GeneratePassword(length: 32, numberOfNonAlphanumericCharacters: 16);
            var securityAnswer   = Membership.GeneratePassword(length: 64, numberOfNonAlphanumericCharacters: 30);
            var securityQuestion = "Answer is a generated Pass";

            if (row.Table.Columns.Contains(name: "Password") && ((string)row[columnName : "Password"]).IsSet() &&
                row.Table.Columns.Contains(name : "SecurityQuestion") &&
                ((string)row[columnName : "SecurityQuestion"]).IsSet() &&
                row.Table.Columns.Contains(name : "SecurityAnswer") && ((string)row[columnName : "SecurityAnswer"]).IsSet())
            {
                pass = (string)row[columnName : "Password"];

                securityAnswer   = (string)row[columnName : "SecurityAnswer"];
                securityQuestion = (string)row[columnName : "SecurityQuestion"];
            }

            var user = YafContext.Current.Get <MembershipProvider>().CreateUser(
                username: (string)row[columnName: "Name"],
                password: pass,
                email: (string)row[columnName: "Email"],
                passwordQuestion: this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityQuestion : null,
                passwordAnswer: this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityAnswer : null,
                isApproved: true,
                providerUserKey: null,
                status: out status);

            // setup initial roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(pageBoardID: YafContext.Current.PageBoardID, userName: (string)row[columnName: "Name"]);

            // create the user in the YAF DB as well as sync roles...
            var userID = RoleMembershipHelper.CreateForumUser(user: user, pageBoardID: YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            var userProfile = YafUserProfile.GetProfile(userName: (string)row[columnName: "Name"]);

            // Add Profile Fields to User List Table.
            if (row.Table.Columns.Contains(name: "RealName") && ((string)row[columnName : "RealName"]).IsSet())
            {
                userProfile.RealName = (string)row[columnName : "RealName"];
            }

            if (row.Table.Columns.Contains(name: "Blog") && ((string)row[columnName : "Blog"]).IsSet())
            {
                userProfile.Blog = (string)row[columnName : "Blog"];
            }

            if (row.Table.Columns.Contains(name: "Gender") && ((string)row[columnName : "Gender"]).IsSet())
            {
                int gender;

                int.TryParse(s: (string)row[columnName: "Gender"], result: out gender);

                userProfile.Gender = gender;
            }

            if (row.Table.Columns.Contains(name: "Birthday") && ((string)row[columnName : "Birthday"]).IsSet())
            {
                DateTime userBirthdate;

                DateTime.TryParse(s: (string)row[columnName: "Birthday"], result: out userBirthdate);

                if (userBirthdate > DateTimeHelper.SqlDbMinTime())
                {
                    userProfile.Birthday = userBirthdate;
                }
            }

            if (row.Table.Columns.Contains(name: "BlogServiceUsername") &&
                ((string)row[columnName : "BlogServiceUsername"]).IsSet())
            {
                userProfile.BlogServiceUsername = (string)row[columnName : "BlogServiceUsername"];
            }

            if (row.Table.Columns.Contains(name: "BlogServicePassword") &&
                ((string)row[columnName : "BlogServicePassword"]).IsSet())
            {
                userProfile.BlogServicePassword = (string)row[columnName : "BlogServicePassword"];
            }

            if (row.Table.Columns.Contains(name: "GoogleId") && ((string)row[columnName : "GoogleId"]).IsSet())
            {
                userProfile.GoogleId = (string)row[columnName : "GoogleId"];
            }

            if (row.Table.Columns.Contains(name: "Location") && ((string)row[columnName : "Location"]).IsSet())
            {
                userProfile.Location = (string)row[columnName : "Location"];
            }

            if (row.Table.Columns.Contains(name: "Country") && ((string)row[columnName : "Country"]).IsSet())
            {
                userProfile.Country = (string)row[columnName : "Country"];
            }

            if (row.Table.Columns.Contains(name: "Region") && ((string)row[columnName : "Region"]).IsSet())
            {
                userProfile.Region = (string)row[columnName : "Region"];
            }

            if (row.Table.Columns.Contains(name: "City") && ((string)row[columnName : "City"]).IsSet())
            {
                userProfile.City = (string)row[columnName : "City"];
            }

            if (row.Table.Columns.Contains(name: "Interests") && ((string)row[columnName : "Interests"]).IsSet())
            {
                userProfile.Interests = (string)row[columnName : "Interests"];
            }

            if (row.Table.Columns.Contains(name: "Homepage") && ((string)row[columnName : "Homepage"]).IsSet())
            {
                userProfile.Homepage = (string)row[columnName : "Homepage"];
            }

            if (row.Table.Columns.Contains(name: "Skype") && ((string)row[columnName : "Skype"]).IsSet())
            {
                userProfile.Skype = (string)row[columnName : "Skype"];
            }

            if (row.Table.Columns.Contains(name: "ICQe") && ((string)row[columnName : "ICQ"]).IsSet())
            {
                userProfile.ICQ = (string)row[columnName : "ICQ"];
            }

            if (row.Table.Columns.Contains(name: "XMPP") && ((string)row[columnName : "XMPP"]).IsSet())
            {
                userProfile.XMPP = (string)row[columnName : "XMPP"];
            }

            if (row.Table.Columns.Contains(name: "Occupation") && ((string)row[columnName : "Occupation"]).IsSet())
            {
                userProfile.Occupation = (string)row[columnName : "Occupation"];
            }

            if (row.Table.Columns.Contains(name: "Twitter") && ((string)row[columnName : "Twitter"]).IsSet())
            {
                userProfile.Twitter = (string)row[columnName : "Twitter"];
            }

            if (row.Table.Columns.Contains(name: "TwitterId") && ((string)row[columnName : "TwitterId"]).IsSet())
            {
                userProfile.TwitterId = (string)row[columnName : "TwitterId"];
            }

            if (row.Table.Columns.Contains(name: "Facebook") && ((string)row[columnName : "Facebook"]).IsSet())
            {
                userProfile.Facebook = (string)row[columnName : "Facebook"];
            }

            if (row.Table.Columns.Contains(name: "FacebookId") && ((string)row[columnName : "FacebookId"]).IsSet())
            {
                userProfile.FacebookId = (string)row[columnName : "FacebookId"];
            }

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                return(importCount);
            }

            // send user register notification to the new users
            this.Get <ISendNotification>().SendRegistrationNotificationToUser(
                user: user, pass: pass, securityAnswer: securityAnswer, templateName: "NOTIFICATION_ON_REGISTER");

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(providerUserKey: user.ProviderUserKey);

            var isDst = false;

            if (row.Table.Columns.Contains(name: "IsDST") && ((string)row[columnName : "IsDST"]).IsSet())
            {
                bool.TryParse(value : (string)row[columnName : "IsDST"], result : out isDst);
            }

            var timeZone = 0;

            if (row.Table.Columns.Contains(name: "Timezone") && ((string)row[columnName : "Timezone"]).IsSet())
            {
                int.TryParse(s : (string)row[columnName : "Timezone"], result : out timeZone);
            }

            var autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            this.GetRepository <User>().Save(
                userID: userId,
                boardID: YafContext.Current.PageBoardID,
                userName: row[columnName: "Name"],
                displayName: row.Table.Columns.Contains(name: "DisplayName") ? row[columnName: "DisplayName"] : null,
                email: row[columnName: "Email"],
                timeZone: timeZone,
                languageFile: row.Table.Columns.Contains(name: "LanguageFile") ? row[columnName: "LanguageFile"] : null,
                culture: row.Table.Columns.Contains(name: "Culture") ? row[columnName: "Culture"] : null,
                themeFile: row.Table.Columns.Contains(name: "ThemeFile") ? row[columnName: "ThemeFile"] : null,
                textEditor: row.Table.Columns.Contains(name: "TextEditor") ? row[columnName: "TextEditor"] : null,
                approved: null,
                pmNotification: null,
                autoWatchTopics: this.Get <YafBoardSettings>().DefaultNotificationSetting,
                dSTUser: autoWatchTopicsEnabled,
                hideUser: isDst,
                notificationType: null,
                null);

            // save the settings...
            this.GetRepository <User>().SaveNotification(
                userID: userId,
                pmNotification: true,
                autoWatchTopics: autoWatchTopicsEnabled,
                notificationType: this.Get <YafBoardSettings>().DefaultNotificationSetting,
                dailyDigest: this.Get <YafBoardSettings>().DefaultSendDigestEmail);

            importCount++;

            return(importCount);
        }