Esempio n. 1
0
        public NetworkMember Join(Core core, User member, string networkEmail)
        {
            string activateKey = User.GenerateActivationSecurityToken();

            if (!IsValidNetworkEmail(networkEmail) && networkInfo.RequireConfirmation)
            {
                return null;
            }

            if (IsNetworkMember(member.ItemKey))
            {
                return null;
            }

            int isActive = (networkInfo.RequireConfirmation) ? 0 : 1;

            // delete any existing unactivated e-mails for this user in this network, re-send the invitation
            db.BeginTransaction();

            try
            {
                NetworkMember nm = new NetworkMember(core, this, member);

                if (!nm.IsMemberActive)
                {
                    try
                    {
                        UserEmail uMail = new UserEmail(core, nm.MemberEmail);
                        uMail.Delete();
                    }
                    catch (InvalidUserEmailException)
                    {
                        // Do Nothing
                    }
                    nm.Delete();
                }
            }
            catch (InvalidUserException)
            {
                // Do Nothing
            }

            if (!networkInfo.RequireConfirmation)
            {
                UpdateQuery uQuery = new UpdateQuery(GetTable(typeof(Network)));
                uQuery.AddField("network_members", new QueryOperation("network_members", QueryOperations.Addition, 1));
                uQuery.AddCondition("network_id", networkId);

                db.Query(uQuery);
            }

            InsertQuery iQuery = new InsertQuery(GetTable(typeof(NetworkMember)));
            iQuery.AddField("network_id", this.Id);
            iQuery.AddField("user_id", member.UserId);
            iQuery.AddField("member_join_date_ut", UnixTime.UnixTimeStamp());
            iQuery.AddField("member_join_ip", core.Session.IPAddress.ToString());
            iQuery.AddField("member_email", networkEmail);
            iQuery.AddField("member_active", isActive);
            iQuery.AddField("member_activate_code", activateKey);

            db.Query(iQuery);

            NetworkMember newMember = new NetworkMember(core, this, member);
            string activateUri = string.Format("http://zinzam.com/network/{0}?mode=activate&id={1}&key={2}",
                networkNetwork, member.UserId, activateKey);

            if (networkInfo.RequireConfirmation)
            {
                EmailAddressTypes emailType = EmailAddressTypes.Other;

                switch (networkInfo.NetworkType)
                {
                    case NetworkTypes.School:
                    case NetworkTypes.University:
                        emailType = EmailAddressTypes.Student;
                        break;
                    case NetworkTypes.Workplace:
                        emailType = EmailAddressTypes.Business;
                        break;
                }

                UserEmail registrationEmail = UserEmail.Create(core, newMember, networkEmail, emailType, true);

                Template emailTemplate = new Template(core.Http.TemplateEmailPath, "join_network.html");

                emailTemplate.Parse("SITE_TITLE", core.Settings.SiteTitle);
                emailTemplate.Parse("U_SITE", core.Hyperlink.StripSid(core.Hyperlink.AppendAbsoluteSid(core.Hyperlink.BuildHomeUri())));
                emailTemplate.Parse("TO_NAME", member.DisplayName);
                emailTemplate.Parse("U_ACTIVATE", activateUri);
                emailTemplate.Parse("S_EMAIL", networkEmail);

                core.Email.SendEmail(networkEmail, core.Settings.SiteTitle + " Network Registration Confirmation", emailTemplate);
            }

            return newMember;
        }
        void AccountContactManage_AddEmail(object sender, ModuleModeEventArgs e)
        {
            SetTemplate("account_email_edit");

            /**/
            TextBox emailTextBox = new TextBox("email-address");

            /**/
            SelectBox emailTypeSelectBox = new SelectBox("phone-type");
            emailTypeSelectBox.Add(new SelectBoxItem(((byte)EmailAddressTypes.Personal).ToString(), "Personal"));
            emailTypeSelectBox.Add(new SelectBoxItem(((byte)EmailAddressTypes.Business).ToString(), "Business"));
            emailTypeSelectBox.Add(new SelectBoxItem(((byte)EmailAddressTypes.Student).ToString(), "Student"));
            emailTypeSelectBox.Add(new SelectBoxItem(((byte)EmailAddressTypes.Other).ToString(), "Other"));

            switch (e.Mode)
            {
                case "add-email":
                    break;
                case "edit-email":
                    long emailId = core.Functions.FormLong("id", core.Functions.RequestLong("id", 0));
                    UserEmail email = null;

                    if (emailId > 0)
                    {
                        try
                        {
                            email = new UserEmail(core, emailId);

                            emailTextBox.IsDisabled = true;
                            emailTextBox.Value = email.Email;

                            if (emailTypeSelectBox.ContainsKey(((byte)email.EmailType).ToString()))
                            {
                                emailTypeSelectBox.SelectedKey = ((byte)email.EmailType).ToString();
                            }

                            template.Parse("S_ID", email.Id.ToString());
                        }
                        catch (InvalidUserEmailException)
                        {
                            return;
                        }
                    }
                    else
                    {
                        return;
                    }

                    template.Parse("EDIT", "TRUE");
                    break;
            }

            template.Parse("S_EMAIL", emailTextBox);
            template.Parse("S_EMAIL_TYPE", emailTypeSelectBox);
        }
Esempio n. 3
0
        public static UserEmail Create(Core core, User owner, string email, EmailAddressTypes type, bool isRegistration)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            if (!User.CheckEmailValid(email))
            {
                throw new EmailInvalidException();
            }

            if (!User.CheckEmailUnique(core, email))
            {
                throw new EmailAlreadyRegisteredException();
            }

            string activateKey = User.GenerateActivationSecurityToken();

            InsertQuery iquery = new InsertQuery(UserEmail.GetTable(typeof(UserEmail)));
            iquery.AddField("email_user_id", owner.Id);
            iquery.AddField("email_email", email);
            iquery.AddField("email_type", (byte)type);
            if (!isRegistration)
            {
                iquery.AddField("email_verified", false);
            }
            else
            {
                iquery.AddField("email_verified", true);
            }
            iquery.AddField("email_time_ut", UnixTime.UnixTimeStamp());
            iquery.AddField("email_activate_code", activateKey);
            iquery.AddField("email_simple_permissions", true);

            long emailId = core.Db.Query(iquery);

            if (!isRegistration)
            {
                string activateUri = string.Format(core.Hyperlink.Uri + "register/?mode=activate-email&id={0}&key={1}",
                    emailId, activateKey);

                Template emailTemplate = new Template(core.Http.TemplateEmailPath, "email_activation.html");

                emailTemplate.Parse("TO_NAME", owner.DisplayName);
                emailTemplate.Parse("U_ACTIVATE", activateUri);
                emailTemplate.Parse("USERNAME", owner.UserName);

                core.Email.SendEmail(email, core.Settings.SiteTitle + " email activation", emailTemplate);
            }

            UserEmail newEmail = new UserEmail(core, emailId);

            Access.CreateGrantForPrimitive(core, newEmail, User.GetCreatorKey(core), "VIEW");
            if (!isRegistration)
            {
                Access.CreateGrantForPrimitive(core, newEmail, Friend.GetFriendsGroupKey(core), "VIEW");
            }
            Access.CreateGrantForPrimitive(core, newEmail, User.GetEveryoneGroupKey(core), "RECIEVE_FROM");

            return newEmail;
        }
        void AccountContactManage_VerifyEmail(object sender, ModuleModeEventArgs e)
        {
            AuthoriseRequestSid();

            UserEmail email = new UserEmail(core, core.Functions.RequestLong("id", 0));

            if (email.UserId == LoggedInMember.Id)
            {
                if (!email.IsActivated)
                {
                    string activateKey = User.GenerateActivationSecurityToken();

                    string activateUri = string.Format("http://" + Hyperlink.Domain + "/register/?mode=activate-email&id={0}&key={1}",
                        email.Id, activateKey);

                    UpdateQuery query = new UpdateQuery(typeof(UserEmail));
                    query.AddField("email_activate_code", activateKey);
                    query.AddCondition("email_id", email.Id);

                    core.Db.Query(query);

                    Template emailTemplate = new Template(core.Http.TemplateEmailPath, "email_activation.html");

                    emailTemplate.Parse("TO_NAME", Owner.DisplayName);
                    emailTemplate.Parse("U_ACTIVATE", activateUri);
                    emailTemplate.Parse("USERNAME", ((User)Owner).UserName);

                    core.Email.SendEmail(email.Email, core.Settings.SiteTitle + " email activation", emailTemplate);

                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("Verification e-mail send", "A verification code has been sent to the e-mail address along with verification instructions.");
                }
                else
                {
                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("Already verified", "You have already verified your email address.");
                }
            }
            else
            {
                SetRedirectUri(BuildUri());
                core.Display.ShowMessage("Error", "An error has occured.");
            }
        }
        void AccountContactManage_AddEmail_save(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            switch (core.Http.Form["mode"])
            {
                case "add-email":
                    string emailAddress = core.Http.Form["email-address"];
                    EmailAddressTypes emailType = (EmailAddressTypes)core.Functions.FormByte("email-type", (byte)EmailAddressTypes.Personal);

                    try
                    {
                        UserEmail.Create(core, emailAddress, emailType);

                        SetRedirectUri(BuildUri());
                        core.Display.ShowMessage("E-mail address Saved", "Your e-mail address has been saved in the database. Before your e-mail can be used it will need to be verification. A verification code has been sent to the e-mail address along with verification instructions.");
                        return;
                    }
                    catch (InvalidUserEmailException)
                    {
                    }
                    catch (EmailInvalidException)
                    {
                        this.SetError("E-mail address is not valid");
                        return;
                    }
                    catch (EmailAlreadyRegisteredException)
                    {
                        this.SetError("E-mail address has been registered with " + core.Settings.SiteTitle + " before, please add another address");
                        return;
                    }
                    return;
                case "edit-email":
                    long emailId = core.Functions.FormLong("id", 0);

                    UserEmail email = null;

                    try
                    {
                        email = new UserEmail(core, emailId);
                    }
                    catch (InvalidUserEmailException)
                    {
                        return;
                    }

                    email.EmailType = (EmailAddressTypes)core.Functions.FormByte("email-type", (byte)EmailAddressTypes.Other);
                    email.Update();

                    SetRedirectUri(BuildUri());
                    core.Display.ShowMessage("E-mail address Saved", "Your e-mail address settings has been saved in the database.");
                    return;
                default:
                    DisplayError("Error - no mode selected");
                    return;
            }
        }
Esempio n. 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string redirect = (Request.Form["redirect"] != null) ? Request.Form["redirect"] : Request.QueryString["redirect"];
            string domain = (Request.Form["domain"] != null) ? Request.Form["domain"] : Request.QueryString["domain"];
            DnsRecord record = null;

            template.Parse("IS_CONTENT", "FALSE");
            template.Parse("S_POST", core.Hyperlink.AppendSid("/sign-in/", true));

            if (!string.IsNullOrEmpty(domain))
            {
                try
                {
                    if (domain != Hyperlink.Domain)
                    {
                        record = new DnsRecord(core, domain);
                    }
                    if (core.Http["mode"] == "sign-out")
                    {
                        if (record != null)
                        {
                            session.SessionEnd(Request.QueryString["sid"], loggedInMember.UserId, record);
                        }
                        else
                        {
                            session.SessionEnd(Request.QueryString["sid"], loggedInMember.UserId);
                        }

                        if (!string.IsNullOrEmpty(redirect))
                        {
                            Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + redirect.TrimStart(new char[] { '/' }), true));
                        }
                        else
                        {
                            Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/", true));
                        }
                    }
                    else if (core.LoggedInMemberId > 0)
                    {
                        string sessionId = Request.QueryString["sid"];

                        if (!string.IsNullOrEmpty(sessionId))
                        {
                            core.Session.SessionEnd(sessionId, 0, record);
                        }

                        sessionId = core.Session.SessionBegin(core.LoggedInMemberId, false, false, false, record, null);

                        Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + redirect.TrimStart(new char[] { '/' }), true));
                    }
                }
                catch (InvalidDnsRecordException)
                {
                    core.Display.ShowMessage("Error", "Error starting remote session");
                    return;
                }
            }

            if (core.Http["mode"] == "sign-out")
            {
                string sessionId = Request.QueryString["sid"];

                if (!string.IsNullOrEmpty(sessionId))
                {
                    core.Session.SessionEnd(sessionId, loggedInMember.UserId);
                }

                if (!string.IsNullOrEmpty(redirect))
                {
                    Response.Redirect(redirect, true);
                }
                else
                {
                    Response.Redirect("/", true);
                }
                return;
            }
            if (Request.Form["submit"] != null)
            {
                if (core.Http["mode"] == "reset-password")
                {
                    string email = Request.Form["email"];

                    if (string.IsNullOrEmpty(email))
                    {
                        core.Display.ShowMessage("Error", "An error occured");
                        return;
                    }
                    else
                    {
                        try
                        {
                            UserEmail userEmail = new UserEmail(core, email);

                            if (userEmail.IsActivated)
                            {
                                string newPassword = BoxSocial.Internals.User.GenerateRandomPassword();
                                string activateCode = BoxSocial.Internals.User.GenerateActivationSecurityToken();

                                db.UpdateQuery(string.Format("UPDATE user_info SET user_new_password = '******', user_activate_code = '{1}' WHERE user_id = {2}",
                                    Mysql.Escape(newPassword), Mysql.Escape(activateCode), userEmail.Owner.Id));

                                string activateUri = string.Format(core.Hyperlink.Uri + "register/?mode=activate-password&id={0}&key={1}",
                                    userEmail.Owner.Id, activateCode);

                                // send the e-mail

                                Template emailTemplate = new Template(core.Http.TemplateEmailPath, "new_password.html");

                                emailTemplate.Parse("SITE_TITLE", core.Settings.SiteTitle);
                                emailTemplate.Parse("U_SITE", core.Hyperlink.StripSid(core.Hyperlink.AppendAbsoluteSid(core.Hyperlink.BuildHomeUri())));
                                emailTemplate.Parse("TO_NAME", userEmail.Owner.DisplayName);
                                emailTemplate.Parse("U_ACTIVATE", activateUri);
                                emailTemplate.Parse("USERNAME", userEmail.Owner.UserName);
                                // TODO: do not send a new password in plain text
                                emailTemplate.Parse("PASSWORD", newPassword);

                                core.Email.SendEmail(userEmail.Email, core.Settings.SiteTitle + " Password Reset", emailTemplate);

                                core.Display.ShowMessage("Password reset", "You have been sent an e-mail to the address you entered with your new password. You will need to click the confirmation link before you can sign in");
                                return;
                            }
                            else
                            {
                                core.Display.ShowMessage("E-mail not verified", "The e-mail you have entered has not been verified, you need to enter an e-mail address you have verified to reset your password.");
                                return;
                            }
                        }
                        catch (InvalidUserEmailException)
                        {
                            core.Display.ShowMessage("No e-mail registered", "The e-mail you have entered is not associated with a user account.");
                            return;
                        }
                    }
                }
                else if (core.Http.Form["mode"] == "verify")
                {
                    Authenticator authenticator = new Authenticator();
                    if (authenticator.CheckCode(core.Session.CandidateMember.UserInfo.TwoFactorAuthKey, core.Http.Form["verify"]))
                    {
                        if (Request.Form["remember"] == "true")
                        {
                            session.SessionBegin(core.Session.CandidateMember.UserId, false, true, true);
                        }
                        else
                        {
                            session.SessionBegin(core.Session.CandidateMember.UserId, false, false, true);
                        }
                        if ((!string.IsNullOrEmpty(domain)) && (record != null))
                        {
                            string sessionId = core.Session.SessionBegin(core.Session.CandidateMember.UserId, false, false, true, record, null);

                            core.Hyperlink.Sid = sessionId;
                            if (!string.IsNullOrEmpty(redirect))
                            {
                                Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + redirect.TrimStart(new char[] { '/' }), true));
                            }
                            else
                            {
                                Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/", true));
                            }
                            return;
                        }
                        if (!string.IsNullOrEmpty(redirect))
                        {
                            if (redirect.StartsWith("/account", StringComparison.Ordinal))
                            {
                                redirect = core.Hyperlink.AppendSid(core.Hyperlink.StripSid(redirect), true);
                            }
                            else
                            {
                                redirect = core.Hyperlink.AppendSid(redirect);
                            }
                            Response.Redirect(redirect, true);
                        }
                        else
                        {
                            Response.Redirect(core.Hyperlink.AppendSid("/"), true);
                        }
                        return; /* stop processing the display of this page */
                    }
                    else
                    {
                        core.Session.SessionEnd(core.Session.SessionId, core.Session.CandidateMember.UserId);

                        template.Parse("ERROR", "Bad log in credentials were given, you could not be logged in. Try again.");
                    }
                }
                else
                {
                    string userName = Request.Form["username"];
                    string password = BoxSocial.Internals.User.HashPassword(Request.Form["password"]);

                    DataTable userTable = db.Query(string.Format("SELECT uk.user_name, uk.user_id, ui.user_password, ui.user_two_factor_auth_key, ui.user_two_factor_auth_verified FROM user_keys uk INNER JOIN user_info ui ON uk.user_id = ui.user_id WHERE uk.user_name = '{0}';",
                       userName));

                    if (userTable.Rows.Count == 1)
                    {
                        DataRow userRow = userTable.Rows[0];
                        bool authenticated = false;
                        string dbPassword = (string)userRow["user_password"];

                        // old phpBB passwords
                        if (dbPassword.Length == 32)
                        {
                            // phpBB2 passwords
                            if (SessionState.SessionMd5(Request.Form["password"]) == dbPassword.ToLower())
                            {
                                authenticated = true;
                            }
                        }
                        else if (dbPassword.Length == 34)
                        {
                            // phpBB3 passwords
                            string itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

                            if (SessionState.phpBB3Hash(Request.Form["password"], dbPassword, ref itoa64) == dbPassword)
                            {
                                authenticated = true;
                            }
                        }
                        else
                        {
                            if (dbPassword == password)
                            {
                                authenticated = true;
                            }
                        }

                        if (authenticated)
                        {
                            if ((byte)userRow["user_two_factor_auth_verified"] > 0)
                            {
                                template.SetTemplate("login_two_factor_verify.html");

                                HiddenField rememberHiddenField = new HiddenField("remember");
                                rememberHiddenField.Value = core.Http.Form["remember"];

                                TextBox verifyTextBox = new Forms.TextBox("verify");

                                template.Parse("S_REMEMBER", rememberHiddenField);
                                template.Parse("S_VERIFY", verifyTextBox);

                                if (Request.Form["remember"] == "true")
                                {
                                    session.SessionBegin((long)userRow["user_id"], false, true, false);
                                }
                                else
                                {
                                    session.SessionBegin((long)userRow["user_id"], false, false, false);
                                }
                            }
                            else
                            {

                                if (Request.Form["remember"] == "true")
                                {
                                    session.SessionBegin((long)userRow["user_id"], false, true);
                                }
                                else
                                {
                                    session.SessionBegin((long)userRow["user_id"], false, false);
                                }
                                if ((!string.IsNullOrEmpty(domain)) && (record != null))
                                {
                                    string sessionId = core.Session.SessionBegin((long)userRow["user_id"], false, false, false, record, null);

                                    core.Hyperlink.Sid = sessionId;
                                    if (!string.IsNullOrEmpty(redirect))
                                    {
                                        Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/" + redirect.TrimStart(new char[] { '/' }), true));
                                    }
                                    else
                                    {
                                        Response.Redirect(core.Hyperlink.AppendSid("http://" + record.Domain + "/", true));
                                    }
                                    return;
                                }
                                if (!string.IsNullOrEmpty(redirect))
                                {
                                    if (redirect.StartsWith("/account", StringComparison.Ordinal))
                                    {
                                        redirect = core.Hyperlink.AppendSid(core.Hyperlink.StripSid(redirect), true);
                                    }
                                    else
                                    {
                                        redirect = core.Hyperlink.AppendSid(redirect);
                                    }
                                    Response.Redirect(redirect, true);
                                }
                                else
                                {
                                    Response.Redirect(core.Hyperlink.AppendSid("/"), true);
                                }
                                return; /* stop processing the display of this page */
                            }
                        }
                        else
                        {
                            template.Parse("ERROR", "Bad log in credentials were given, you could not be logged in. Try again.");
                        }

                    }
                    else
                    {
                        template.Parse("ERROR", "Bad log in credentials were given, you could not be logged in. Try again.");
                    }
                }
            }

            if (core.Http["mode"] == "reset-password")
            {
                template.Parse("S_POST", core.Hyperlink.AppendSid("/sign-in/?mode=reset-password", true));

                template.SetTemplate("password_reset.html");

                EndResponse();
                return;
            }
            else
            {
                template.Parse("U_FORGOT_PASSWORD", core.Hyperlink.AppendSid("/sign-in/?mode=reset-password"));
            }

            template.Parse("DOMAIN", domain);
            template.Parse("REDIRECT", redirect);

            EndResponse();
        }
Esempio n. 7
0
        public static bool CheckEmailUnique(Core core, string eMail)
        {
            try
            {
                UserEmail uMail = new UserEmail(core, eMail);
                return false; // not unique
            }
            catch (InvalidUserEmailException)
            {
                return true; // unique
            }

            // TODO: register all e-mail addresses into a new table, along with privacy controls
            /*DataTable userTable = db.Query(string.Format("SELECT user_id, user_alternate_email FROM user_info WHERE LCASE(user_alternate_email) = '{0}';",
                Mysql.Escape(eMail.ToLower())));
            if (userTable.Rows.Count > 0)
            {
                lastEmailId = (int)userTable.Rows[0]["user_id"];
                return false;
            }

            DataTable networkMemberTable = db.Query(string.Format("SELECT user_id, member_email FROM network_members WHERE LCASE(member_email) = '{0}';",
                Mysql.Escape(eMail.ToLower())));
            if (networkMemberTable.Rows.Count > 0)
            {
                lastEmailId = (int)networkMemberTable.Rows[0]["user_id"];
                return false;
            }

            SelectQuery query = new SelectQuery(UserEmail.GetTable(typeof(UserEmail)));
            query.AddCondition(new QueryFunction("email_email", QueryFunctions.ToLowerCase).ToString(), eMail.ToLower());

            DataTable emailsTable = db.Query(query);

            return true;*/
        }
Esempio n. 8
0
        void AccountFriendInvite_Send(object sender, EventArgs e)
        {
            AuthoriseRequestSid();

            if (core.Http.Files["contacts"] != null)
            {
                StreamReader sr = new StreamReader(core.Http.Files["contacts"].InputStream);
                string contactsString = sr.ReadToEnd();

                MatchCollection mc = Regex.Matches(contactsString, @"[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*?[a-z]+", RegexOptions.IgnoreCase);
                string[] friendEmails = new string[mc.Count];
                int i = 0;
                foreach (Match m in mc)
                {
                    friendEmails[i] = m.Value;
                    i++;
                }
                InviteFriendsSend(friendEmails);
                return;
            }

            string friendEmail = ((string)core.Http.Form["email"]).Trim(new char[] { ' ', '\t' });
            string friendName = core.Http.Form["name"];

            friendEmail = (string.IsNullOrEmpty(friendEmail)) ? core.Http.Query["email"] : friendEmail;
            friendName = (string.IsNullOrEmpty(friendName)) ? core.Http.Query["name"] : friendName;

            if (string.IsNullOrEmpty(friendEmail))
            {
                core.Display.ShowMessage("Cannot Invite Friend", "You must enter a valid e-mail address to invite.");
                return;
            }

            if (User.CheckEmailValid(friendEmail))
            {
                if (User.CheckEmailUnique(core, friendEmail))
                {
                    DataTable inviteKeysTable = db.Query(string.Format("SELECT email_key FROM invite_keys WHERE email_hash = '{0}' AND invite_allow = 0",
                        Mysql.Escape(User.HashPassword(friendEmail))));

                    if (inviteKeysTable.Rows.Count > 0)
                    {
                        core.Display.ShowMessage("Cannot Invite Friend", "The person you have invited has opted-out of mailings from " + core.Settings.SiteTitle + ".");
                        return;
                    }
                    else
                    {
                        Random rand = new Random();
                        string emailKey = User.HashPassword(friendEmail + rand.NextDouble().ToString());
                        emailKey = emailKey.Substring((int)(rand.NextDouble() * 10), 32);

                        Template emailTemplate = new Template(core.Http.TemplateEmailPath, "friend_invitation.html");

                        if (!string.IsNullOrEmpty(friendName))
                        {
                            emailTemplate.Parse("TO_NAME", " " + friendName);
                        }

                        emailTemplate.Parse("SITE_TITLE", core.Settings.SiteTitle);
                        emailTemplate.Parse("U_SITE", core.Hyperlink.StripSid(core.Hyperlink.AppendAbsoluteSid(core.Hyperlink.BuildHomeUri())));
                        emailTemplate.Parse("FROM_NAME", LoggedInMember.DisplayName);
                        emailTemplate.Parse("FROM_EMAIL", LoggedInMember.UserInfo.PrimaryEmail);
                        emailTemplate.Parse("FROM_NAMES", LoggedInMember.DisplayNameOwnership);
                        emailTemplate.Parse("U_REGISTER", core.Hyperlink.StripSid(core.Hyperlink.AppendAbsoluteSid(core.Hyperlink.BuildRegisterUri(emailKey))));
                        emailTemplate.Parse("U_PROFILE", core.Hyperlink.StripSid(core.Hyperlink.AppendAbsoluteSid(core.Session.LoggedInMember.ProfileUri)));
                        emailTemplate.Parse("U_OPTOUT", core.Hyperlink.StripSid(core.Hyperlink.AppendAbsoluteSid(core.Hyperlink.BuildOptOutUri(emailKey))));

                        core.Email.SendEmail(friendEmail, string.Format("{0} has invited you to " + core.Settings.SiteTitle, LoggedInMember.DisplayName), emailTemplate);

                        db.UpdateQuery(string.Format("INSERT INTO invite_keys (email_key, invite_allow, email_hash, invite_user_id, invite_time_ut) VALUES ('{0}', 1, '{1}', {2}, {3});",
                            Mysql.Escape(emailKey), Mysql.Escape(User.HashPassword(friendEmail)), Mysql.Escape(core.LoggedInMemberId.ToString()), Mysql.Escape(UnixTime.UnixTimeStamp().ToString())));
                    }
                }
                else
                {
                    try
                    {
                        UserEmail email = new UserEmail(core, friendEmail);
                        core.Display.ShowMessage("Already Member", string.Format("This person is already a member of " + core.Settings.SiteTitle + ". To add them to your friends list <a href=\"{0}\">click here</a>.",
                            core.Hyperlink.BuildAddFriendUri(email.UserId)));
                        return;
                    }
                    catch (InvalidUserEmailException)
                    {
                        core.Display.ShowMessage("ERROR", "An exception has occured");
                        return;
                    }
                }
            }
            else
            {
                core.Display.ShowMessage("Cannot Invite Friend", "You must enter a valid e-mail address to invite.");
                return;
            }

            core.Session.LoggedInMember.UserInfo.Invites++;
            core.Session.LoggedInMember.UserInfo.Update();

            SetRedirectUri(BuildUri());
            core.Display.ShowMessage("Invited Friend", "You have invited a friend to " + core.Settings.SiteTitle + ".");
        }