protected void Page_Load(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(Convert.ToString(Context.Items["SessionID"])))
        {
            qPtl_Sessions session = new qPtl_Sessions(Convert.ToInt32(Context.Items["SessionID"]));
            if (session.SessionID > 0)
            {
                session.StopTime = DateTime.Now;
                session.Update();
            }

            qPtl_User user = new qPtl_User(Convert.ToInt32(Context.Items["UserID"]));
            if (user.UserID > 0)
            {
                DateTime last_time = new DateTime();
                last_time = Convert.ToDateTime(user.LastTimeSeen);
                if (!String.IsNullOrEmpty(Convert.ToString(user.LastTimeSeen)))
                    user.LastTimeSeen = last_time.AddMinutes(-16);
                user.Update();
            }
        }

        Session.Abandon();
        FormsAuthentication.SignOut();
        Response.Redirect("~/default.aspx", true);
    }
        public static void UpdateMobileSession(int user_id)
        {
            int curr_session_id = 0;

            curr_session_id = GetCurrentSessionID(user_id);

            if (curr_session_id > 0)
            {
                qPtl_Sessions session = new qPtl_Sessions(curr_session_id);
                session.LastTimeSeen = DateTime.Now;
                session.StopTime     = null;
                session.Update();
            }
        }
        public static bool ValidateMobileSession(int session_id, int user_id)
        {
            bool is_valid = false;

            qPtl_Sessions session = new qPtl_Sessions(session_id);

            if (session.SessionID > 0)
            {
                if (session.UserID == user_id && String.IsNullOrEmpty(Convert.ToString(session.StopTime)))
                {
                    is_valid = true;
                }
            }

            return(is_valid);
        }
        public static int UserLogoff(int user_id, int session_id)
        {
            qPtl_Sessions session = new qPtl_Sessions(session_id);

            session.StopTime = DateTime.Now;
            session.Update();

            qPtl_User user      = new qPtl_User(Convert.ToInt32(user_id));
            DateTime  last_time = new DateTime();

            last_time         = Convert.ToDateTime(user.LastTimeSeen);
            user.LastTimeSeen = last_time.AddMinutes(-16);
            user.Update();

            return(user_id);
        }
        public static qPtl_Sessions AddSession(qPtl_User user, int temp_session_id, string host_address, string browser, string platform)
        {
            qPtl_Sessions session = new qPtl_Sessions();

            session.Created       = DateTime.Now;
            session.StartTime     = DateTime.Now;
            session.LastTimeSeen  = DateTime.Now;
            session.TempSessionID = temp_session_id;
            session.ScopeID       = user.ScopeID;
            session.UserID        = user.UserID;
            session.IPAddress     = host_address;
            session.BrowserType   = browser;
            session.ComputerType  = platform;
            session.Insert();

            return(session);
        }
    private void cmdLogin_ServerClick(object sender, System.EventArgs e)
    {
        if (ValidateUser(txtUserName.Value, txtUserPass.Value))
        {
            qPtl_User user = new qPtl_User(txtUserName.Value);

            qPtl_Sessions session = new qPtl_Sessions();
            session.Created = DateTime.Now;
            session.StartTime = DateTime.Now;
            session.LastTimeSeen = DateTime.Now;
            session.ScopeID = user.ScopeID;
            session.UserID = user.UserID;
            session.BrowserType = Request.Browser.Browser;
            session.ComputerType = Request.Browser.Platform;
            session.Insert();
            int sessionID = session.SessionID;
            int scopeID = user.ScopeID;

            var u_roles = qPtl_UserRole_View.GetUserRoles(user.UserID);
            string role_list = string.Empty;

            if (u_roles != null)
            {
                foreach (var u in u_roles)
                {
                    role_list += string.Format("{0},", u.RoleName, ",");
                }
            }

            role_list.TrimEnd(',');

            // see if there is a campaign code
            string reg_code = string.Empty;
            string custom_redirect = string.Empty;
            if (!String.IsNullOrEmpty(txtSpaceCode.Text))
            {
                reg_code = txtSpaceCode.Text;

                qSoc_Campaign campaign = new qSoc_Campaign(reg_code);

                if (campaign.CampaignID > 0)
                {
                    // see if already enrolled
                    var exist_campaign = qSoc_UserCampaign.GetUserCampaign(user.UserID, campaign.CampaignID);

                    if (exist_campaign != null)
                    {
                        if (exist_campaign.UserCampaignID > 0)
                        {
                            exist_campaign.DeleteUserCampaign(campaign.CampaignID, user.UserID);
                            exist_campaign.DeleteUserCampaignActions(campaign.CampaignID, user.UserID);
                        }
                    }

                    AddUserCampaign(campaign.CampaignID, user.ScopeID, user);
                    custom_redirect = "~/social/learning/campaigns/campaign-details.aspx?campaignID=" + campaign.CampaignID;
                }
            }

            string userData = string.Format("{0};{1};{2}", sessionID, role_list, scopeID);

            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;
            int timeout_minutes = 480;                  // default shorter timeout (8 hours)
            int timeout_extended_minutes = 1440;        // default extended timeout (1 day)
            int logout_minutes = 0;
            if (!String.IsNullOrEmpty(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Site_LoginTimeOut"])))
                timeout_minutes = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Site_LoginTimeOut"]);
            else if (!String.IsNullOrEmpty(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Site_ExtendedLoginTimeOut"])))
                timeout_extended_minutes = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Site_ExtendedLoginTimeOut"]);

            if (chkLeaveLoggedIn.Checked)
                logout_minutes = timeout_extended_minutes;
            else
                logout_minutes = timeout_minutes;

            tkt = new FormsAuthenticationTicket(1, user.UserID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(logout_minutes), true, userData);
            cookiestr = FormsAuthentication.Encrypt(tkt);
            ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
            //if (chkPersistCookie.Checked)
            //ck.Expires = tkt.Expiration;
            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(ck);

            HttpCookie cookie2 = new HttpCookie("UserID", Convert.ToString(user.UserID));
            if (tkt.IsPersistent) { cookie2.Expires = tkt.Expiration.AddMinutes(logout_minutes+5); }
            Response.Cookies.Add(cookie2);

            string strRedirect;
            strRedirect = Request["ReturnUrl"];
            if (strRedirect == null)
                strRedirect = "~/utilities/manage-user-access.aspx";
            if (!String.IsNullOrEmpty(custom_redirect))
                strRedirect = custom_redirect;
            Response.Redirect(strRedirect, true);
        }
        else
            lblMsg.Text = "<br><br>Your username or password is not correct. Please try again.";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(Request.QueryString["key"]) != System.Configuration.ConfigurationManager.AppSettings["Site_AutomationKey"])
        {
            Response.Redirect("access-restricted.aspx");
        }
        else
        {
            qPtl_User user = new qPtl_User(Convert.ToInt32(Request.QueryString["userID"]));

            if (user.UserID > 0)
            {
                qPtl_Sessions sess = new qPtl_Sessions();
                sess.UserID = user.UserID;
                qPtl_Sessions session = new qPtl_Sessions();
                session.Created = DateTime.Now;
                session.StartTime = DateTime.Now;
                session.LastTimeSeen = DateTime.Now;
                session.ScopeID = user.ScopeID;
                session.UserID = user.UserID;
                session.BrowserType = Request.Browser.Browser;
                session.ComputerType = Request.Browser.Platform;
                session.Insert();

                int session_id = session.SessionID;

                var u_roles = qPtl_UserRole_View.GetUserRoles(user.UserID);
                string role_list = string.Empty;

                if (u_roles != null)
                {
                    foreach (var u in u_roles)
                    {
                        role_list += string.Format("{0},", u.RoleName, ",");
                    }
                }

                role_list.TrimEnd(',');

                string userData = string.Format("{0};{1};{2}", session.SessionID, role_list, user.ScopeID);

                FormsAuthenticationTicket tkt;
                string cookiestr;
                HttpCookie ck;
                int timeout_minutes = 480;                  // default shorter timeout (8 hours)
                int timeout_extended_minutes = 1440;        // default extended timeout (1 day)
                int logout_minutes = 0;
                if (!String.IsNullOrEmpty(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Site_LoginTimeOut"])))
                    timeout_minutes = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Site_LoginTimeOut"]);
                else if (!String.IsNullOrEmpty(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Site_ExtendedLoginTimeOut"])))
                    timeout_extended_minutes = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Site_ExtendedLoginTimeOut"]);

                logout_minutes = timeout_extended_minutes;

                tkt = new FormsAuthenticationTicket(1, user.UserID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(logout_minutes), true, userData);
                cookiestr = FormsAuthentication.Encrypt(tkt);
                ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

                ck.Path = FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(ck);

                HttpCookie cookie2 = new HttpCookie("UserID", Convert.ToString(user.UserID));
                if (tkt.IsPersistent) { cookie2.Expires = tkt.Expiration.AddMinutes(logout_minutes + 5); }
                Response.Cookies.Add(cookie2);

                if (!string.IsNullOrEmpty(Request.QueryString["redirectURL"]))
                {
                    string redirect = Request.QueryString["redirectURL"];
                    Response.Redirect(redirect);
                }
                else
                    Response.Redirect("~/default.aspx");
            }
            else
                Response.Redirect("access-restricted.aspx");
        }
    }
    protected void btnSignUp_Click(object sender, EventArgs e)
    {
        Page.Validate("register");

        if (Page.IsValid)
        {
            string sqlCode = string.Empty;
            string returnMessage = string.Empty;
            qDbs_SQLcode sql = new qDbs_SQLcode();
            string register_mode = "new";
            int existing_user_id = 0;
            int scope_id = 1;   // would have to be changed to support multiple organizations on a single platform
            int role_id = 0;
            int moderator_role_id = 0;
            if (!String.IsNullOrEmpty(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Register_ModeratorRoleID"])))
                moderator_role_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_ModeratorRoleID"]);

            // ****************************************************
            // STEP 1: DETERMINE IF USER IS ALREADY A LIMITED MOBILE USER
            if (plhMobileNumber.Visible == true)
            {
                //Determine if upgrade of mobile account or new registration
                qPtl_UserProfile mobile_test = qPtl_UserProfile.GetProfileByMobileNumber(txtMobileNumber.Text);

                if (mobile_test != null)
                {
                    if (mobile_test.UserID > 0)
                    {
                        // make sure that the user is eligible for upgrade from mobile only status
                        qPtl_User eval_user = new qPtl_User(mobile_test.UserID);

                        if (eval_user.HighestRole == "Mobile")
                        {
                            register_mode = "update";
                            existing_user_id = mobile_test.UserID;
                        }
                    }
                    else
                    {
                        register_mode = "new";
                    }
                }
                else
                {
                    register_mode = "new";
                }
            }

            // ****************************************************
            // STEP 2a: Mode == new; then add new user
            string currAvailableStatus = string.Empty;
            currAvailableStatus = "Yes";

            if (register_mode == "new")
            {
                qPtl_User new_user = new qPtl_User();
                new_user.Available = "Yes";
                new_user.ScopeID = scope_id;
                new_user.Created = DateTime.Now;
                new_user.CreatedBy = 0;
                new_user.LastModified = DateTime.Now;
                new_user.LastModifiedBy = 0;
                new_user.MarkAsDelete = 0;
                new_user.Status = "";       // used to include a default message for their status, now leave blank
                new_user.FirstName = txtFirstName.Text;
                new_user.LastName = txtLastName.Text;
                new_user.Email = txtEmail.Text;
                new_user.UserName = txtUserName.Text;
                string password_for_storing = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "sha1");
                new_user.Password = password_for_storing;
                new_user.AccountStatus = "Active";
                new_user.Insert();
                existing_user_id = new_user.UserID;

                DateTime DOB;
                try
                {
                    DOB = new DateTime(int.Parse(ddlYear.SelectedValue), int.Parse(ddlMonth.SelectedValue), int.Parse(ddlDay.SelectedValue)); ;//Convert.ToDateTime(ddlMonth.SelectedValue + "/" + ddlDay.SelectedValue + "/" + ddlYear.SelectedValue);
                }
                catch
                {
                    // no valid date so use default value
                    DOB = new DateTime(1900, 1, 1); ////Convert.ToDateTime("1/1/1900");
                }
                qPtl_UserProfile new_profile = new qPtl_UserProfile();
                new_profile.UserID = existing_user_id;
                new_profile.ScopeID = scope_id;
                new_profile.Available = "Yes";
                new_profile.Created = DateTime.Now;
                new_profile.CreatedBy = existing_user_id;
                new_profile.LastModified = DateTime.Now;
                new_profile.LastModifiedBy = existing_user_id;
                new_profile.MarkAsDelete = 0;
                new_profile.Style = "default";
                new_profile.Visibility = "all";
                new_profile.Gender = ddlGender.SelectedValue;
                new_profile.DOB = DOB;

                if (plhRace.Visible == true)
                {
                    string race = string.Empty;
                    int n = 0;
                    foreach (ListItem item in cblRace.Items)
                    {
                        if (item.Selected)
                        {
                            if (n > 0)
                            {
                                race += "," + item.Value;
                            }
                            else
                            {
                                race += item.Value;
                            }
                            n++;
                        }
                    }
                    n = 0;
                    new_profile.Race = race;
                }
                new_profile.Insert();
            }
            qPtl_User user = new qPtl_User(existing_user_id);

            // STEP 2b: Mode == update; then update mobile info
            //mode mobile = update existing account
            if (register_mode == "update")
            {
                user.FirstName = txtFirstName.Text;
                user.LastName = txtLastName.Text;
                user.UserName = txtEmail.Text;
                user.Email = txtEmail.Text;
                string password_for_storing = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "sha1");
                user.Password = password_for_storing;
                user.AccountStatus = "Mobile Verification Pending";
                user.Update();
            }

            // ****************************************************
            // STEP 3: Process invitation & perform invitation-specific work
            // OPTION #1 -- an invitation is required as part of the registration process and a collection of additional actions are related to that
            string code = string.Empty;
            string process_code_mode = string.Empty;
            if (plhInvitation.Visible == true)
            {
                code = txtInvitationCode.Text;
                if (String.IsNullOrEmpty(process_code_mode))
                    process_code_mode = "invitation";                // deal with default/null values
            }
            else if (plhSpaceCode.Visible == true)
            {
                code = txtSpaceCode.Text;
                if (String.IsNullOrEmpty(process_code_mode))
                {
                    qSoc_Space space = new qSoc_Space(code);

                    if (space.SpaceID > 0)
                    {
                        process_code_mode = "space";
                    }
                    else
                    {
                        qSoc_Campaign campaign = new qSoc_Campaign(code);

                        if (campaign.CampaignID > 0)
                        {
                            process_code_mode = "campaign";
                        }
                    }
                }
            }

            if (!String.IsNullOrEmpty(code) && process_code_mode == "invitation")
            {
                //Process invitation
                int invitationID = 0;
                qPtl_Invitation invite = null;
                invite = new qPtl_Invitation(code);
                invitationID = invite.InvitationID;
                role_id = invite.RoleID;

                // update invitation records as necessary
                if (invite.InvitationAudience == "family")
                {
                    invite.UserID = user.UserID;
                    invite.InvitationStatus = "Redeemed";
                    invite.LastModified = DateTime.Now;
                    invite.LastModifiedBy = user.UserID;
                    invite.CurrRedemptions = invite.CurrRedemptions + 1;
                }
                else if (invite.InvitationAudience == "individual")
                {
                    invite.UserID = user.UserID;
                    invite.InvitationStatus = "Redeemed";
                    invite.LastModified = DateTime.Now;
                    invite.LastModifiedBy = user.UserID;
                    invite.CurrRedemptions = invite.CurrRedemptions + 1;
                }
                else if (invite.InvitationAudience == "group")
                {
                    invite.UserID = user.UserID;
                    invite.LastModified = DateTime.Now;
                    invite.LastModifiedBy = user.UserID;
                    invite.CurrRedemptions = invite.CurrRedemptions + 1;

                    if (invite.MaxRedemptions > 0 && invite.CurrRedemptions >= invite.MaxRedemptions)
                        invite.InvitationStatus = "Redeemed";
                }
                else if (invite.InvitationAudience == "moderated group")
                {
                    invite.UserID = user.UserID;
                    invite.LastModified = DateTime.Now;
                    invite.LastModifiedBy = user.UserID;
                    invite.CurrRedemptions = invite.CurrRedemptions + 1;

                    if (invite.MaxRedemptions > 0 && invite.CurrRedemptions >= invite.MaxRedemptions)
                        invite.InvitationStatus = "Redeemed";
                }
                invite.Update();

                // add possible space associated with invitation & space-specific elements

                if (invite.SpaceID > 0)
                {
                    qSoc_Space space = new qSoc_Space(invite.SpaceID);
                    if (space != null)
                    {
                        if (space.SpaceID > 0)
                        {
                            qSoc_UserSpace u_space = new qSoc_UserSpace();
                            u_space.ScopeID = scope_id;
                            u_space.Available = "Yes";
                            u_space.Created = DateTime.Now;
                            u_space.CreatedBy = user.UserID;
                            u_space.LastModified = DateTime.Now;
                            u_space.LastModifiedBy = user.UserID;
                            u_space.MarkAsDelete = 0;
                            u_space.UserID = user.UserID;
                            u_space.SpaceID = space.SpaceID;
                            u_space.PrimarySpace = true;
                            if (role_id == moderator_role_id)
                                u_space.SpaceRole = "Moderator";
                            u_space.Insert();
                        }

                        if (space.SchoolID > 0)
                        {
                            qOrg_UserSchool school = new qOrg_UserSchool();
                            school.UserID = user.UserID;
                            school.SchoolID = space.SchoolID;
                            school.Insert();
                        }

                        // set space to visibile in directory it not already visible
                        if (space.VisibleInDirectory == "No")
                        {
                            space.VisibleInDirectory = "Yes";
                            space.Update();
                        }

                        // add campaign -- includes check to insure that campaigns aren't added twice
                        AddSpaceCampaigns(space, user, scope_id);
                    }
                }

                // add possible campaign associated with invitation -- includes check to insure that campaigns aren't added twice
                if (invite.CampaignID > 0)
                {
                    qSoc_UserCampaign checkc = new qSoc_UserCampaign(user.UserID, invite.CampaignID);
                    if (checkc.UserCampaignID == 0)
                    {
                        AddUserCampaign(invite.CampaignID, scope_id, user);
                    }
                }

                if (invite.FunctionalRoleID > 0)
                {
                    sqlCode = "INSERT INTO qLrn_UserFunctionalRoles ([UserID],[FunctionalRoleID]) VALUES(" + user.UserID + "," + invite.FunctionalRoleID + ")";
                    sql.ExecuteSQL(sqlCode);

                    UserFunctions.AddUserTrainingsByFunctionalRole(user.UserID, invite.FunctionalRoleID);
                }
            }
            else
            {
                // else use default role types
                int teen_max_age = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenMaxAge"]);

                qPtl_UserProfile profile = new qPtl_UserProfile(user.UserID);
                if (profile.Age <= teen_max_age)
                    role_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenRoleID"]);
                else
                    role_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_ParentRoleID"]);
            }

            // OPTION #2 -- User might have entered a registration code; this will assign them to a space which might have one or more associated campaigns
            if (!String.IsNullOrEmpty(code) && process_code_mode == "space")
            {
                if (!string.IsNullOrEmpty(code))
                {
                    qSoc_Space space = new qSoc_Space(code);

                    if (space != null)
                    {
                        if (space.SpaceID > 0)
                        {
                            qSoc_UserSpace u_space = new qSoc_UserSpace();
                            u_space.ScopeID = scope_id;
                            u_space.Available = "Yes";
                            u_space.Created = DateTime.Now;
                            u_space.CreatedBy = user.UserID;
                            u_space.LastModified = DateTime.Now;
                            u_space.LastModifiedBy = user.UserID;
                            u_space.MarkAsDelete = 0;
                            u_space.UserID = user.UserID;
                            u_space.SpaceID = space.SpaceID;
                            u_space.PrimarySpace = true;
                            if (role_id == moderator_role_id)
                                u_space.SpaceRole = "Moderator";
                            u_space.Insert();
                        }

                        space_redirect = true;
                        new_space_id = space.SpaceID;

                        AddSpaceCampaigns(space, user, scope_id);
                    }
                }
            }
            else if (!String.IsNullOrEmpty(code) && process_code_mode == "campaign")
            {
                qSoc_Campaign campaign = new qSoc_Campaign(code);

                AddUserCampaign(campaign.CampaignID, scope_id, user);
            }

            // ****************************************************
            // STEP 4: Add School Information
            if (plhSchool.Visible == true)
            {
                string school_name = string.Empty;
                string school_other_name = string.Empty;

                if (radCBSearch.Visible == true)
                    school_name = radCBSearch.SelectedValue;
                else
                {
                    school_other_name = txtSchoolOther.Text;
                    school_name = "Other";
                }

                var school = qOrg_School.GetSchoolFromAutoPopulateDropdown(school_name);

                if (school != null)
                {
                    if (school.SchoolID > 0)
                    {
                        qOrg_UserSchool user_school = new qOrg_UserSchool();
                        user_school.Available = "Yes";
                        user_school.ScopeID = scope_id;
                        user_school.Created = DateTime.Now;
                        user_school.CreatedBy = user.UserID;
                        user_school.LastModified = DateTime.Now;
                        user_school.LastModifiedBy = user.UserID;
                        user_school.MarkAsDelete = 0;
                        user_school.UserID = user.UserID;
                        user_school.SchoolID = school.SchoolID;
                        user_school.OtherName = school_other_name;
                        user_school.Insert();

                        // see if this school is already a space
                        var school_space = qSoc_Space.GetSpacesBySchool(school.SchoolID);

                        qSoc_Space curr_space = new qSoc_Space();
                        if (school_space == null)
                        {
                            qSoc_Space new_space = new qSoc_Space();
                            new_space.ScopeID = scope_id;
                            new_space.Available = "Yes";
                            new_space.Created = DateTime.Now;
                            new_space.CreatedBy = 0;
                            new_space.LastModified = DateTime.Now;
                            new_space.LastModifiedBy = 0;
                            new_space.MarkAsDelete = 0;
                            new_space.SpaceName = school.School;
                            new_space.SpaceShortName = school.School;
                            new_space.SpaceType = "school";
                            new_space.AccessMode = "open";
                            new_space.VisibleInDirectory = "Yes";
                            new_space.SpaceCategoryID = 1;
                            new_space.SchoolID = school.SchoolID;
                            new_space.Insert();

                            school_space = new_space;
                        }

                        if (school_space != null)
                        {
                            qSoc_UserSpace s_space = new qSoc_UserSpace();
                            s_space.ScopeID = scope_id;
                            s_space.Available = "Yes";
                            s_space.Created = DateTime.Now;
                            s_space.CreatedBy = user.UserID;
                            s_space.LastModified = DateTime.Now;
                            s_space.LastModifiedBy = user.UserID;
                            s_space.MarkAsDelete = 0;
                            s_space.UserID = user.UserID;
                            s_space.SpaceID = school_space.SpaceID;
                            s_space.PrimarySpace = true;
                            if (role_id == moderator_role_id)
                                s_space.SpaceRole = "Moderator";
                            s_space.Insert();
                        }
                    }
                }
            }

            // ****************************************************
            // STEP 5: Add User Role & Supporting Role Structures
            // Add role
            /*
            qPtl_UserRole role = new qPtl_UserRole();
            role.UserID = user.UserID;
            role.RoleID = role_id;
            role.Insert();
             */
            sqlCode = "INSERT INTO qPtl_UserRoles ([UserID],[RoleID]) VALUES(" + user.UserID + "," + role_id + ")";
            sql.ExecuteSQL(sqlCode);

            // Add possible role actions for the new user role
            AddRoleAction(role_id, scope_id, user);

            // Add possible role campaigns
            AddRoleCampaigns(role_id, scope_id, user);

            // Redundancy check -- write Highest Level into qPtl_User table in case DB trigger not working
            qPtl_Role role = new qPtl_Role(role_id);
            user.HighestRank = role.RoleRank;
            user.HighestRole = role.RoleName;
            user.Update();

            // ****************************************************
            // STEP 6: User Utilties to finalize/prep account
            // Add username folder for images
            string rootLocation = Server.MapPath("~/") + "user_data\\";

            if (!Directory.Exists(rootLocation + user.UserName))
                Directory.CreateDirectory(rootLocation + user.UserName);

            // Create default album
            qSoc_Album album = new qSoc_Album();
            album.ScopeID = scope_id;
            album.Available = "Yes";
            album.Created = DateTime.Now;
            album.CreatedBy = user.UserID;
            album.LastModified = DateTime.Now;
            album.LastModifiedBy = user.UserID;
            album.MarkAsDelete = 0;
            album.UserID = user.UserID;
            album.Name = "My Pics";
            album.Insert();

            // Add communications preferences
            if (register_mode == "new")
            {
                qCom_UserPreference connect = new qCom_UserPreference();
                connect.UserID = user.UserID;
                connect.Created = DateTime.Now;
                connect.CreatedBy = user.UserID;
                connect.LastModified = DateTime.Now;
                connect.LastModifiedBy = user.UserID;
                connect.Available = "Yes";
                connect.ScopeID = 1;
                connect.MarkAsDelete = 0;
                connect.OkBulkEmail = "Yes";
                connect.OkEmail = "Yes";
                connect.OkSms = "Yes";
                connect.LanguageID = 1;
                connect.Insert();
            }

            qCom_UserPreference user_connect = qCom_UserPreference.GetUserPreference(user.UserID);
            user_connect.OkBulkEmail = "Yes";
            user_connect.OkEmail = "Yes";
            user_connect.Update();

            // ****************************************************
            // STEP 7: Log user in and redirect to account setup page/
            // initial session created -- will last for 24 hours before timing out
            qPtl_Sessions session = new qPtl_Sessions();
            session.Created = DateTime.Now;
            session.StartTime = DateTime.Now;
            session.LastTimeSeen = DateTime.Now;
            session.ScopeID = user.ScopeID;
            session.UserID = user.UserID;
            session.BrowserType = Request.Browser.Browser;
            session.ComputerType = Request.Browser.Platform;
            session.Insert();
            int sessionID = session.SessionID;
            int scopeID = user.ScopeID;

            var u_roles = qPtl_UserRole_View.GetUserRoles(user.UserID);
            string role_list = string.Empty;

            if (u_roles != null)
            {
                foreach (var u in u_roles)
                {
                    role_list += string.Format("{0},", u.RoleName, ",");
                }
            }

            role_list.TrimEnd(',');

            string userData = string.Format("{0};{1};{2}", sessionID, role_list, scopeID);

            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;
            tkt = new FormsAuthenticationTicket(1, user.UserID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(3600), false, userData);
            cookiestr = FormsAuthentication.Encrypt(tkt);
            ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(ck);

            HttpCookie cookie2 = new HttpCookie("UserID", Convert.ToString(user.UserID));
            if (tkt.IsPersistent) { cookie2.Expires = tkt.Expiration.AddMinutes(3605); }
            Response.Cookies.Add(cookie2);

            if (space_redirect == true && new_space_id > 0)
                Response.Redirect("~/utilities/manage-user-access.aspx?mode=registration&spaceID=" + new_space_id);
            else
                Response.Redirect("~/utilities/manage-user-access.aspx?mode=registration");
        }
    }
        public static bool ValidateMobileSession(int session_id, int user_id)
        {
            bool is_valid = false;

            qPtl_Sessions session = new qPtl_Sessions(session_id);

            if (session.SessionID > 0)
            {
                if (session.UserID == user_id && String.IsNullOrEmpty(Convert.ToString(session.StopTime)))
                {
                    is_valid = true;
                }
            }

            return is_valid;
        }
        public static void UpdateMobileSession(int user_id)
        {
            int curr_session_id = 0;

            curr_session_id = GetCurrentSessionID(user_id);

            if (curr_session_id > 0)
            {
                qPtl_Sessions session = new qPtl_Sessions(curr_session_id);
                session.LastTimeSeen = DateTime.Now;
                session.StopTime = null;
                session.Update();
            }
        }
        public static qPtl_Sessions AddSession(qPtl_User user, int temp_session_id, string host_address, string browser, string platform)
        {
            qPtl_Sessions session = new qPtl_Sessions();
            session.Created = DateTime.Now;
            session.StartTime = DateTime.Now;
            session.LastTimeSeen = DateTime.Now;
            session.TempSessionID = temp_session_id;
            session.ScopeID = user.ScopeID;
            session.UserID = user.UserID;
            session.IPAddress = host_address;
            session.BrowserType = browser;
            session.ComputerType = platform;
            session.Insert();

            return session;
        }
        public static int UserLogoff(int user_id, int session_id)
        {
            qPtl_Sessions session = new qPtl_Sessions(session_id);
            session.StopTime = DateTime.Now;
            session.Update();

            qPtl_User user = new qPtl_User(Convert.ToInt32(user_id));
            DateTime last_time = new DateTime();
            last_time = Convert.ToDateTime(user.LastTimeSeen);
            user.LastTimeSeen = last_time.AddMinutes(-16);
            user.Update();

            return user_id;
        }