Advertisement
Guest User

Untitled

a guest
Jun 17th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 18.14 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Session.php
  4.  *
  5.  * The Session class is meant to simplify the task of keeping
  6.  * track of logged in users and also guests.
  7.  *
  8.  * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
  9.  * Last Updated: August 2, 2009 by Ivan Novak
  10.  */
  11. include("database.php");
  12. include("mailer.php");
  13. include("form.php");
  14.  
  15. class Session
  16. {
  17.    var $username;     //Username given on sign-up
  18.    var $userid;       //Random value generated on current login
  19.    var $userlevel;    //The level to which the user pertains
  20.    var $time;         //Time user was last active (page loaded)
  21.    var $logged_in;    //True if user is logged in, false otherwise
  22.    var $userinfo = array();  //The array holding all user info
  23.    var $url;          //The page url current being viewed
  24.    var $referrer;     //Last recorded site page viewed
  25.    /**
  26.     * Note: referrer should really only be considered the actual
  27.     * page referrer in process.php, any other time it may be
  28.     * inaccurate.
  29.     */
  30.  
  31.    /* Class constructor */
  32.    function Session(){
  33.       $this->time = time();
  34.       $this->startSession();
  35.    }
  36.  
  37.    /**
  38.     * startSession - Performs all the actions necessary to
  39.     * initialize this session object. Tries to determine if the
  40.     * the user has logged in already, and sets the variables
  41.     * accordingly. Also takes advantage of this page load to
  42.     * update the active visitors tables.
  43.     */
  44.    function startSession(){
  45.       global $database;  //The database connection
  46.       session_start();   //Tell PHP to start the session
  47.  
  48.       /* Determine if user is logged in */
  49.       $this->logged_in = $this->checkLogin();
  50.  
  51.       /**
  52.        * Set guest value to users not logged in, and update
  53.        * active guests table accordingly.
  54.        */
  55.       if(!$this->logged_in){
  56.          $this->username = $_SESSION['username'] = GUEST_NAME;
  57.          $this->userlevel = GUEST_LEVEL;
  58.          $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
  59.       }
  60.       /* Update users last active timestamp */
  61.       else{
  62.          $database->addActiveUser($this->username, $this->time);
  63.       }
  64.      
  65.       /* Remove inactive visitors from database */
  66.       $database->removeInactiveUsers();
  67.       $database->removeInactiveGuests();
  68.      
  69.       /* Set referrer page */
  70.       if(isset($_SESSION['url'])){
  71.          $this->referrer = $_SESSION['url'];
  72.       }else{
  73.          $this->referrer = "/";
  74.       }
  75.  
  76.       /* Set current url */
  77.       $this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];
  78.    }
  79.  
  80.    /**
  81.     * checkLogin - Checks if the user has already previously
  82.     * logged in, and a session with the user has already been
  83.     * established. Also checks to see if user has been remembered.
  84.     * If so, the database is queried to make sure of the user's
  85.     * authenticity. Returns true if the user has logged in.
  86.     */
  87.    function checkLogin(){
  88.       global $database;  //The database connection
  89.       /* Check if user has been remembered */
  90.       if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
  91.          $this->username = $_SESSION['username'] = $_COOKIE['cookname'];
  92.          $this->userid   = $_SESSION['userid']   = $_COOKIE['cookid'];
  93.       }
  94.  
  95.       /* Username and userid have been set and not guest */
  96.       if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&
  97.          $_SESSION['username'] != GUEST_NAME){
  98.          /* Confirm that username and userid are valid */
  99.          if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){
  100.             /* Variables are incorrect, user not logged in */
  101.             unset($_SESSION['username']);
  102.             unset($_SESSION['userid']);
  103.             return false;
  104.          }
  105.  
  106.          /* User is logged in, set class variables */
  107.          $this->userinfo  = $database->getUserInfo($_SESSION['username']);
  108.          $this->username  = $this->userinfo['username'];
  109.          $this->userid    = $this->userinfo['userid'];
  110.          $this->userlevel = $this->userinfo['userlevel'];
  111.          return true;
  112.       }
  113.       /* User not logged in */
  114.       else{
  115.          return false;
  116.       }
  117.    }
  118.  
  119.    /**
  120.     * login - The user has submitted his username and password
  121.     * through the login form, this function checks the authenticity
  122.     * of that information in the database and creates the session.
  123.     * Effectively logging in the user if all goes well.
  124.     */
  125.    function login($subuser, $subpass, $subremember){
  126.       global $database, $form;  //The database and form object
  127.  
  128.       /* Username error checking */
  129.       $field = "user";  //Use field name for username
  130.       $q = "SELECT valid FROM ".TBL_USERS." WHERE username='$subuser'";
  131.       $valid = $database->query($q);
  132.       $valid = mysql_fetch_array($valid);
  133.              
  134.       if(!$subuser || strlen($subuser = trim($subuser)) == 0){
  135.          $form->setError($field, "* Username not entered");
  136.       }
  137.       else{
  138.          /* Check if username is not alphanumeric */
  139.          if(!eregi("^([0-9a-z])*$", $subuser)){
  140.             $form->setError($field, "* Username not alphanumeric");
  141.          }
  142.       }  
  143.  
  144.       /* Password error checking */
  145.       $field = "pass";  //Use field name for password
  146.       if(!$subpass){
  147.          $form->setError($field, "* Password not entered");
  148.       }
  149.      
  150.       /* Return if form errors exist */
  151.       if($form->num_errors > 0){
  152.          return false;
  153.       }
  154.  
  155.       /* Checks that username is in database and password is correct */
  156.       $subuser = stripslashes($subuser);
  157.       $result = $database->confirmUserPass($subuser, md5($subpass));
  158.  
  159.       /* Check error codes */
  160.       if($result == 1){
  161.          $field = "user";
  162.          $form->setError($field, "* Username not found");
  163.       }
  164.       else if($result == 2){
  165.          $field = "pass";
  166.          $form->setError($field, "* Invalid password");
  167.       }
  168.      
  169.       /* Return if form errors exist */
  170.       if($form->num_errors > 0){
  171.          return false;
  172.       }
  173.  
  174.      
  175.       if(EMAIL_WELCOME){
  176.         if($valid['valid'] == 0){
  177.             $form->setError($field, "* User's account has not yet been confirmed.");
  178.         }
  179.       }
  180.                  
  181.       /* Return if form errors exist */
  182.       if($form->num_errors > 0){
  183.          return false;
  184.       }
  185.      
  186.  
  187.  
  188.       /* Username and password correct, register session variables */
  189.       $this->userinfo  = $database->getUserInfo($subuser);
  190.       $this->username  = $_SESSION['username'] = $this->userinfo['username'];
  191.       $this->userid    = $_SESSION['userid']   = $this->generateRandID();
  192.       $this->userlevel = $this->userinfo['userlevel'];
  193.      
  194.       /* Insert userid into database and update active users table */
  195.       $database->updateUserField($this->username, "userid", $this->userid);
  196.       $database->addActiveUser($this->username, $this->time);
  197.       $database->removeActiveGuest($_SERVER['REMOTE_ADDR']);
  198.  
  199.       /**
  200.        * This is the cool part: the user has requested that we remember that
  201.        * he's logged in, so we set two cookies. One to hold his username,
  202.        * and one to hold his random value userid. It expires by the time
  203.        * specified in constants.php. Now, next time he comes to our site, we will
  204.        * log him in automatically, but only if he didn't log out before he left.
  205.        */
  206.       if($subremember){
  207.          setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
  208.          setcookie("cookid",   $this->userid,   time()+COOKIE_EXPIRE, COOKIE_PATH);
  209.       }
  210.  
  211.       /* Login completed successfully */
  212.       return true;
  213.    }
  214.  
  215.    /**
  216.     * logout - Gets called when the user wants to be logged out of the
  217.     * website. It deletes any cookies that were stored on the users
  218.     * computer as a result of him wanting to be remembered, and also
  219.     * unsets session variables and demotes his user level to guest.
  220.     */
  221.    function logout(){
  222.       global $database;  //The database connection
  223.       /**
  224.        * Delete cookies - the time must be in the past,
  225.        * so just negate what you added when creating the
  226.        * cookie.
  227.        */
  228.       if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
  229.          setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
  230.          setcookie("cookid",   "", time()-COOKIE_EXPIRE, COOKIE_PATH);
  231.       }
  232.  
  233.       /* Unset PHP session variables */
  234.       unset($_SESSION['username']);
  235.       unset($_SESSION['userid']);
  236.  
  237.       /* Reflect fact that user has logged out */
  238.       $this->logged_in = false;
  239.      
  240.       /**
  241.        * Remove from active users table and add to
  242.        * active guests tables.
  243.        */
  244.       $database->removeActiveUser($this->username);
  245.       $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
  246.      
  247.       /* Set user level to guest */
  248.       $this->username  = GUEST_NAME;
  249.       $this->userlevel = GUEST_LEVEL;
  250.    }
  251.  
  252.    /**
  253.     * register - Gets called when the user has just submitted the
  254.     * registration form. Determines if there were any errors with
  255.     * the entry fields, if so, it records the errors and returns
  256.     * 1. If no errors were found, it registers the new user and
  257.     * returns 0. Returns 2 if registration failed.
  258.     */
  259.    function register($subuser, $subpass, $subemail, $subname){
  260.       global $database, $form, $mailer;  //The database, form and mailer object
  261.      
  262.       /* Username error checking */
  263.       $field = "user";  //Use field name for username
  264.       if(!$subuser || strlen($subuser = trim($subuser)) == 0){
  265.          $form->setError($field, "* Username not entered");
  266.       }
  267.       else{
  268.          /* Spruce up username, check length */
  269.          $subuser = stripslashes($subuser);
  270.          if(strlen($subuser) < 5){
  271.             $form->setError($field, "* Username below 5 characters");
  272.          }
  273.          else if(strlen($subuser) > 30){
  274.             $form->setError($field, "* Username above 30 characters");
  275.          }
  276.          /* Check if username is not alphanumeric */
  277.          else if(!eregi("^([0-9a-z])+$", $subuser)){
  278.             $form->setError($field, "* Username not alphanumeric");
  279.          }
  280.          /* Check if username is reserved */
  281.          else if(strcasecmp($subuser, GUEST_NAME) == 0){
  282.             $form->setError($field, "* Username reserved word");
  283.          }
  284.          /* Check if username is already in use */
  285.          else if($database->usernameTaken($subuser)){
  286.             $form->setError($field, "* Username already in use");
  287.          }
  288.          /* Check if username is banned */
  289.          else if($database->usernameBanned($subuser)){
  290.             $form->setError($field, "* Username banned");
  291.          }
  292.       }
  293.  
  294.       /* Password error checking */
  295.       $field = "pass";  //Use field name for password
  296.       if(!$subpass){
  297.          $form->setError($field, "* Password not entered");
  298.       }
  299.       else{
  300.          /* Spruce up password and check length*/
  301.          $subpass = stripslashes($subpass);
  302.          if(strlen($subpass) < 4){
  303.             $form->setError($field, "* Password too short");
  304.          }
  305.          /* Check if password is not alphanumeric */
  306.          else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){
  307.             $form->setError($field, "* Password not alphanumeric");
  308.          }
  309.          /**
  310.           * Note: I trimmed the password only after I checked the length
  311.           * because if you fill the password field up with spaces
  312.           * it looks like a lot more characters than 4, so it looks
  313.           * kind of stupid to report "password too short".
  314.           */
  315.       }
  316.      
  317.       /* Email error checking */
  318.       $field = "email";  //Use field name for email
  319.       if(!$subemail || strlen($subemail = trim($subemail)) == 0){
  320.          $form->setError($field, "* Email not entered");
  321.       }
  322.       else{
  323.          /* Check if valid email address */
  324.          $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
  325.                  ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
  326.                  ."\.([a-z]{2,}){1}$";
  327.          if(!eregi($regex,$subemail)){
  328.             $form->setError($field, "* Email invalid");
  329.          }
  330.          /* Check if email is already in use */
  331.          if($database->emailTaken($subemail)){
  332.             $form->setError($field, "* Email already in use");
  333.          }
  334.  
  335.          $subemail = stripslashes($subemail);
  336.       }
  337.      
  338.       /* Name error checking */
  339.       $field = "name";
  340.       if(!$subname || strlen($subname = trim($subname)) == 0){
  341.          $form->setError($field, "* Name not entered");
  342.       } else {
  343.          $subname = stripslashes($subname);
  344.       }
  345.      
  346.       $randid = $this->generateRandID();
  347.      
  348.       /* Errors exist, have user correct them */
  349.       if($form->num_errors > 0){
  350.          return 1;  //Errors with form
  351.       }
  352.       /* No errors, add the new account to the */
  353.       else{
  354.          if($database->addNewUser($subuser, md5($subpass), $subemail, $randid, $subname)){
  355.             if(EMAIL_WELCOME){              
  356.                $mailer->sendWelcome($subuser,$subemail,$subpass,$randid);
  357.             }
  358.             return 0;  //New user added succesfully
  359.          }else{
  360.             return 2;  //Registration attempt failed
  361.          }
  362.       }
  363.    }
  364.    
  365.    /**
  366.     * editAccount - Attempts to edit the user's account information
  367.     * including the password, which it first makes sure is correct
  368.     * if entered, if so and the new password is in the right
  369.     * format, the change is made. All other fields are changed
  370.     * automatically.
  371.     */
  372.    function editAccount($subcurpass, $subnewpass, $subemail, $subname){
  373.       global $database, $form;  //The database and form object
  374.       /* New password entered */
  375.       if($subnewpass){
  376.          /* Current Password error checking */
  377.          $field = "curpass";  //Use field name for current password
  378.          if(!$subcurpass){
  379.             $form->setError($field, "* Current Password not entered");
  380.          }
  381.          else{
  382.             /* Check if password too short or is not alphanumeric */
  383.             $subcurpass = stripslashes($subcurpass);
  384.             if(strlen($subcurpass) < 4 ||
  385.                !eregi("^([0-9a-z])+$", ($subcurpass = trim($subcurpass)))){
  386.                $form->setError($field, "* Current Password incorrect");
  387.             }
  388.             /* Password entered is incorrect */
  389.             if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){
  390.                $form->setError($field, "* Current Password incorrect");
  391.             }
  392.          }
  393.          
  394.          /* New Password error checking */
  395.          $field = "newpass";  //Use field name for new password
  396.          /* Spruce up password and check length*/
  397.          $subpass = stripslashes($subnewpass);
  398.          if(strlen($subnewpass) < 4){
  399.             $form->setError($field, "* New Password too short");
  400.          }
  401.          /* Check if password is not alphanumeric */
  402.          else if(!eregi("^([0-9a-z])+$", ($subnewpass = trim($subnewpass)))){
  403.             $form->setError($field, "* New Password not alphanumeric");
  404.          }
  405.       }
  406.       /* Change password attempted */
  407.       else if($subcurpass){
  408.          /* New Password error reporting */
  409.          $field = "newpass";  //Use field name for new password
  410.          $form->setError($field, "* New Password not entered");
  411.       }
  412.      
  413.       /* Email error checking */
  414.       $field = "email";  //Use field name for email
  415.       if($subemail && strlen($subemail = trim($subemail)) > 0){
  416.          /* Check if valid email address */
  417.          $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
  418.                  ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
  419.                  ."\.([a-z]{2,}){1}$";
  420.          if(!eregi($regex,$subemail)){
  421.             $form->setError($field, "* Email invalid");
  422.          }
  423.          $subemail = stripslashes($subemail);
  424.       }
  425.      
  426.       /* Name error checking */
  427.       $field = "name";
  428.       if(!$subname || strlen($subname = trim($subname)) == 0){
  429.          $form->setError($field, "* Name not entered");
  430.       } else {
  431.          $subname = stripslashes($subname);
  432.       }
  433.      
  434.       /* Errors exist, have user correct them */
  435.       if($form->num_errors > 0){
  436.          return false;  //Errors with form
  437.       }
  438.      
  439.       /* Update password since there were no errors */
  440.       if($subcurpass && $subnewpass){
  441.          $database->updateUserField($this->username,"password",md5($subnewpass));
  442.       }
  443.      
  444.       /* Change Email */
  445.       if($subemail){
  446.          $database->updateUserField($this->username,"email",$subemail);
  447.       }
  448.      
  449.       /* Change Name */
  450.       if($subname){
  451.          $database->updateUserField($this->username,"name",$subname);
  452.       }
  453.      
  454.       /* Success! */
  455.       return true;
  456.    }
  457.    
  458.    /**
  459.     * isAdmin - Returns true if currently logged in user is
  460.     * an administrator, false otherwise.
  461.     */
  462.    function isAdmin(){
  463.       return ($this->userlevel == ADMIN_LEVEL ||
  464.               $this->username  == ADMIN_NAME);
  465.    }
  466.    
  467.    /**
  468.     * isAuthor - Returns true if currently logged in user is
  469.     * an author or an administrator, false otherwise.
  470.     */
  471.    function isAuthor(){
  472.       return ($this->userlevel == AUTHOR_LEVEL ||
  473.               $this->userlevel == ADMIN_LEVEL);
  474.    }
  475.    
  476.    /**
  477.     * generateRandID - Generates a string made up of randomized
  478.     * letters (lower and upper case) and digits and returns
  479.     * the md5 hash of it to be used as a userid.
  480.     */
  481.    function generateRandID(){
  482.       return md5($this->generateRandStr(16));
  483.    }
  484.    
  485.    /**
  486.     * generateRandStr - Generates a string made up of randomized
  487.     * letters (lower and upper case) and digits, the length
  488.     * is a specified parameter.
  489.     */
  490.    function generateRandStr($length){
  491.       $randstr = "";
  492.       for($i=0; $i<$length; $i++){
  493.          $randnum = mt_rand(0,61);
  494.          if($randnum < 10){
  495.             $randstr .= chr($randnum+48);
  496.          }else if($randnum < 36){
  497.             $randstr .= chr($randnum+55);
  498.          }else{
  499.             $randstr .= chr($randnum+61);
  500.          }
  501.       }
  502.       return $randstr;
  503.    }
  504. };
  505.  
  506.  
  507. /**
  508.  * Initialize session object - This must be initialized before
  509.  * the form object because the form uses session variables,
  510.  * which cannot be accessed unless the session has started.
  511.  */
  512. $session = new Session;
  513.  
  514. /* Initialize form object */
  515. $form = new Form;
  516.  
  517. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement