Guest User

Member Login/Registration

a guest
Oct 8th, 2014
385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 38.01 KB | None | 0 0
  1. <?PHP
  2.  
  3. /*
  4.  *
  5.  *      Members Registration/Login from AssembledBits
  6.  *      2014-10-08 - 5:55AM
  7.  *
  8.  */
  9.  
  10. require_once("class.phpmailer.php");
  11. require_once("formvalidator.php");
  12.  
  13. class Members
  14. {
  15.     var $admin_email;
  16.     var $sitename;
  17.     var $from_address;
  18.    
  19.     var $db_username;
  20.     var $db_password;
  21.     var $db_name;
  22.     var $db_table;
  23.     var $db_connection;
  24.  
  25.     var $rand_key;
  26.    
  27.     var $error_message;
  28.  
  29. /*  ==========================================================================
  30.     Initialize database variables
  31.     ========================================================================== */
  32.     function InitDB($host,$username,$password,$database,$table)
  33.     {
  34.         $this->db_host      = $host;
  35.         $this->db_username  = $username;
  36.         $this->db_password  = $password;
  37.         $this->db_name      = $database;
  38.         $this->db_table     = $table;
  39.     }
  40.  
  41. /*  ==========================================================================
  42.     Set the admin contact e-mail address
  43.     ========================================================================== */
  44.     function SetAdminEmail($email)
  45.     {
  46.         $this->admin_email = $email;
  47.     }
  48.  
  49. /*  ==========================================================================
  50.     Set Website Name
  51.     ========================================================================== */
  52.     function SetWebsiteName($sitename)
  53.     {
  54.         $this->sitename = $sitename;
  55.     }
  56.  
  57. /*  ==========================================================================
  58.     Set Random Key Generation
  59.     ========================================================================== */
  60.     function SetRandomKey($key)
  61.     {
  62.         $this->rand_key = $key;
  63.     }
  64.  
  65.     /*
  66.      *     _______ _______ _______ ______ _______ _______ _______ _______ _______
  67.      *    |    ___|   |   |    |  |      |_     _|_     _|       |    |  |     __|
  68.      *    |    ___|   |   |       |   ---| |   |  _|   |_|   -   |       |__     |
  69.      *    |___|   |_______|__|____|______| |___| |_______|_______|__|____|_______|
  70.      *
  71.      */
  72.  
  73. /*  ==========================================================================
  74.     Register User
  75.  
  76.     <?php
  77.         if(isset($_POST['submitted']))
  78.         {
  79.            if($members->RegisterUser())
  80.            {
  81.                 $members->RedirectToURL("thank-you.html");
  82.            }
  83.         }
  84.     ?>
  85.  
  86.     <form>
  87.         <input type='hidden' name='submitted' id='submitted' value='1'/>
  88.         <input type='text'  class='spmhidip' name='<?php echo $members->GetSpamTrapInputName(); ?>' />
  89.  
  90.         <input type='text' name='user_name' id='user_name' value='<?php echo $members->SafeDisplay('user_name') ?>' maxlength="50" />
  91.         <input type='text' name='user_email' id='user_email' value='<?php echo $members->SafeDisplay('user_email') ?>' maxlength="50" />
  92.         <input type='password' name='user_password' id='password' maxlength="50" />
  93.     </form>
  94.  
  95.     ========================================================================== */
  96.     function RegisterUser()
  97.     {
  98.         if(!isset($_POST['submitted']))
  99.         {
  100.            return false;
  101.         }
  102.        
  103.         $formvars = array();
  104.        
  105.         if(!$this->ValidateRegistrationSubmission())
  106.         {
  107.             return false;
  108.         }
  109.  
  110.         $this->CollectRegistrationSubmission($formvars);
  111.  
  112.         if(!$this->SaveToDatabase($formvars))
  113.         {
  114.             return false;
  115.         }
  116.  
  117.         if(!$this->SendUserConfirmationEmail($formvars))
  118.         {
  119.             return false;
  120.         }
  121.  
  122.         $this->SendAdminIntimationEmail($formvars);
  123.  
  124.         return true;
  125.     }
  126.  
  127. /*  ==========================================================================
  128.     Confirm User
  129.  
  130.     <label for='code'>Confirmation Code:*
  131.         <input type='text' name='code' id='code' maxlength="50" />
  132.     </label>
  133.  
  134.     <?php
  135.         if(isset($_GET['code']))
  136.         {
  137.            if($members->ConfirmUser())
  138.            {
  139.                 $members->RedirectToURL("thank-you-regd.html");
  140.            }
  141.         }
  142.     ?>
  143.  
  144.     ========================================================================== */
  145.     function ConfirmUser()
  146.     {
  147.         if(empty($_GET['code'])||strlen($_GET['code'])<=10)
  148.         {
  149.             $this->HandleError("Please provide the confirm code");
  150.             return false;
  151.         }
  152.         $user_rec = array();
  153.         if(!$this->UpdateDBRecForConfirmation($user_rec))
  154.         {
  155.             return false;
  156.         }
  157.        
  158.         $this->SendUserWelcomeEmail($user_rec);
  159.        
  160.         $this->SendAdminIntimationOnRegComplete($user_rec);
  161.        
  162.         return true;
  163.     }
  164.  
  165. /*  ==========================================================================
  166.     Login
  167.  
  168.     <input type='hidden' name='submitted' id='submitted' value='1'/>
  169.  
  170.     <?php
  171.         if(isset($_POST['submitted']))
  172.         {
  173.            if($members->Login())
  174.            {
  175.                 $members->RedirectToURL("login-home.php");
  176.            }
  177.         }
  178.     ?>
  179.  
  180.     ========================================================================== */
  181.     function Login()
  182.     {
  183.         if(empty($_POST['user_email']))
  184.         {
  185.             $this->HandleError("Email is empty!");
  186.             return false;
  187.         }
  188.        
  189.         if(empty($_POST['user_password']))
  190.         {
  191.             $this->HandleError("Password is empty!");
  192.             return false;
  193.         }
  194.        
  195.         $email = trim($_POST['user_email']);
  196.         $password = trim($_POST['user_password']);
  197.        
  198.         if(!isset($_SESSION)){ session_start(); }
  199.         if(!$this->CheckLoginInDB($email,$password))
  200.         {
  201.             return false;
  202.         }
  203.        
  204.         $_SESSION[$this->GetLoginSessionVar()] = $email;
  205.        
  206.         return true;
  207.     }
  208.    
  209. /*  ==========================================================================
  210.     Check Login
  211.  
  212.     !! Put at the top of any access controlled document
  213.  
  214.     <?PHP
  215.         require_once("membersite_config.php");
  216.  
  217.         if(!$members->CheckLogin())
  218.         {
  219.             $members->RedirectToURL("login.php");
  220.             exit;
  221.         }
  222.     ?>
  223.  
  224.     ========================================================================== */
  225.     function CheckLogin()
  226.     {
  227.         if(!isset($_SESSION)){ session_start(); }
  228.  
  229.         $sessionvar = $this->GetLoginSessionVar();
  230.  
  231.         if(empty($_SESSION[$sessionvar]))
  232.         {
  233.         return false;
  234.         }
  235.         return true;
  236.     }
  237.  
  238. /*  ==========================================================================
  239.     Log Out
  240.  
  241.     <?php
  242.         $members->LogOut();
  243.     ?>
  244.  
  245.     ========================================================================== */
  246.     function LogOut()
  247.     {
  248.         session_start();
  249.        
  250.         $sessionvar = $this->GetLoginSessionVar();
  251.        
  252.         $_SESSION[$sessionvar]=NULL;
  253.        
  254.         unset($_SESSION[$sessionvar]);
  255.     }
  256.  
  257. /*  ==========================================================================
  258.     User Fullname (SESSION)
  259.  
  260.     Logged in as: <?= $members->UserFullName() ?>
  261.  
  262.     ========================================================================== */
  263.     function UserFullName()
  264.     {
  265.         return isset($_SESSION['user_name'])?$_SESSION['user_name']:'';
  266.     }
  267.  
  268. /*  ==========================================================================
  269.     User Email (SESSION)
  270.  
  271.     <input type="text" id="user_email" name="user_email" value="<?= $members->UserEmail() ?>" />
  272.  
  273.     ========================================================================== */
  274.     function UserEmail()
  275.     {
  276.         return isset($_SESSION['user_email'])?$_SESSION['user_email']:'';
  277.     }
  278.    
  279. /*  ==========================================================================
  280.     Checks the database for the submitted email and if matches, will send an
  281.     email for the password reset url
  282.  
  283.     <?php
  284.         $emailsent = false;
  285.  
  286.         if(isset($_POST['submitted']))
  287.         {
  288.            if($members->EmailResetPasswordLink())
  289.            {
  290.                 $members->RedirectToURL("reset-pwd-link-sent.html");
  291.                 exit;
  292.            }
  293.         }
  294.     ?>
  295.  
  296. */
  297.     function EmailResetPasswordLink()
  298.     {
  299.         if(empty($_POST['user_email']))
  300.         {
  301.             $this->HandleError("Email is empty!");
  302.             return false;
  303.         }
  304.         $user_rec = array();
  305.         if(false === $this->GetUserFromEmail($_POST['user_email'], $user_rec))
  306.         {
  307.             return false;
  308.         }
  309.         if(false === $this->SendResetPasswordLink($user_rec))
  310.         {
  311.             return false;
  312.         }
  313.         return true;
  314.     }
  315.  
  316. /*  ==========================================================================
  317.     Reset Password
  318.  
  319.     <?php
  320.         $success = false;
  321.         if($members->ResetPassword())
  322.         {
  323.             $success=true;
  324.         }
  325.     ?>
  326.  
  327.     <?php
  328.         if($success){
  329.         ?>
  330.             <h2>Password is Reset Successfully</h2>
  331.             <p>Your new password is sent to your email address.</p>
  332.         <?php
  333.         }else{
  334.         ?>
  335.             <h2>Error</h2>
  336.             <span class='error'><?php echo $members->GetErrorMessage(); ?></span>
  337.         <?php
  338.         }
  339.     ?>
  340.  
  341.     ========================================================================== */
  342.     function ResetPassword()
  343.     {
  344.         if(empty($_GET['user_email']))
  345.         {
  346.             $this->HandleError("Email is empty!");
  347.             return false;
  348.         }
  349.         if(empty($_GET['code']))
  350.         {
  351.             $this->HandleError("reset code is empty!");
  352.             return false;
  353.         }
  354.         $email = trim($_GET['user_email']);
  355.         $code = trim($_GET['code']);
  356.        
  357.         if($this->GetResetPasswordCode($email) != $code)
  358.         {
  359.             $this->HandleError("Bad reset code!");
  360.             return false;
  361.         }
  362.        
  363.         $user_rec = array();
  364.         if(!$this->GetUserFromEmail($email,$user_rec))
  365.         {
  366.             return false;
  367.         }
  368.        
  369.         $new_password = $this->ResetUserPasswordInDB($user_rec);
  370.         if(false === $new_password || empty($new_password))
  371.         {
  372.             $this->HandleError("Error updating new password");
  373.             return false;
  374.         }
  375.        
  376.         if(false == $this->SendNewPassword($user_rec,$new_password))
  377.         {
  378.             $this->HandleError("Error sending new password");
  379.             return false;
  380.         }
  381.         return true;
  382.     }
  383.  
  384. /*  ==========================================================================
  385.     Change Password
  386.  
  387.     checks if form was submitted, if successful, will redirect
  388.  
  389.     <input type='hidden' name='submitted' id='submitted' value='1'/>
  390.     <?php
  391.         if(isset($_POST['submitted']))
  392.         {
  393.            if($members->ChangePassword())
  394.            {
  395.                 $members->RedirectToURL("changed-pwd.html");
  396.            }
  397.         }
  398.     ?>
  399.  
  400.     ========================================================================== */
  401.     function ChangePassword()
  402.     {
  403.         if(!$this->CheckLogin())
  404.         {
  405.             $this->HandleError("Not logged in!");
  406.             return false;
  407.         }
  408.        
  409.         if(empty($_POST['oldpwd']))
  410.         {
  411.             $this->HandleError("Old password is empty!");
  412.             return false;
  413.         }
  414.         if(empty($_POST['newpwd']))
  415.         {
  416.             $this->HandleError("New password is empty!");
  417.             return false;
  418.         }
  419.        
  420.         $user_rec = array();
  421.         if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
  422.         {
  423.             return false;
  424.         }
  425.        
  426.         $pwd = trim($_POST['oldpwd']);
  427.  
  428.         $salt = $user_rec['user_salt'];
  429.         $hash = $this->checkhashSSHA($salt, $pwd);
  430.        
  431.         if($user_rec['user_password'] != $hash)
  432.         {
  433.             $this->HandleError("The old password does not match!");
  434.             return false;
  435.         }
  436.         $newpwd = trim($_POST['newpwd']);
  437.        
  438.         if(!$this->ChangePasswordInDB($user_rec, $newpwd))
  439.         {
  440.             return false;
  441.         }
  442.         return true;
  443.     }
  444.  
  445.     /*
  446.      *     ______ _______ ______ _____   _______ ______      _______ _______ _____   ______ _______ ______ _______
  447.      *    |   __ \   |   |   __ \     |_|_     _|      |    |   |   |    ___|     |_|   __ \    ___|   __ \     __|
  448.      *    |    __/   |   |   __ <       |_|   |_|   ---|    |       |    ___|       |    __/    ___|      <__     |
  449.      *    |___|  |_______|______/_______|_______|______|    |___|___|_______|_______|___|  |_______|___|__|_______|
  450.      *
  451.      */
  452.  
  453. /*  ==========================================================================
  454.     Get Self
  455.     ========================================================================== */
  456.     function GetSelfScript()
  457.     {
  458.         return htmlentities($_SERVER['PHP_SELF']);
  459.     }
  460.  
  461. /*  ==========================================================================
  462.     Safe Display
  463.     ========================================================================== */
  464.     function SafeDisplay($value_name)
  465.     {
  466.         if(empty($_POST[$value_name]))
  467.         {
  468.             return'';
  469.         }
  470.         return htmlentities($_POST[$value_name]);
  471.     }
  472.  
  473. /*  ==========================================================================
  474.     Redirect To URL
  475.     ========================================================================== */
  476.     function RedirectToURL($url)
  477.     {
  478.         header("Location: $url");
  479.         exit;
  480.     }
  481.  
  482. /*  ==========================================================================
  483.     Spam Trap
  484.  
  485.     <input type='text'  class='spmhidip' name='<?php echo $members->GetSpamTrapInputName(); ?>' />
  486.  
  487.     ========================================================================== */
  488.     function GetSpamTrapInputName()
  489.     {
  490.         return 'sp'.md5('KHGdnbvsgst'.$this->rand_key);
  491.     }
  492.  
  493. /*  ==========================================================================
  494.     Error Message
  495.  
  496.     Displays error on script page
  497.  
  498.     <div>
  499.         <span class='error'>
  500.             <?php echo $members->GetErrorMessage(); ?>
  501.         </span>
  502.     </div>
  503.  
  504.     ========================================================================== */
  505.     function GetErrorMessage()
  506.     {
  507.         if(empty($this->error_message))
  508.         {
  509.             return '';
  510.         }
  511.         $errormsg = nl2br(htmlentities($this->error_message));
  512.         return $errormsg;
  513.     }
  514.  
  515.     /*
  516.      *     ______ ______ _______ ___ ___ _______ _______ _______      _______ _______ _____   ______ _______ ______ _______
  517.      *    |   __ \   __ \_     _|   |   |   _   |_     _|    ___|    |   |   |    ___|     |_|   __ \    ___|   __ \     __|
  518.      *    |    __/      <_|   |_|   |   |       | |   | |    ___|    |       |    ___|       |    __/    ___|      <__     |
  519.      *    |___|  |___|__|_______|\_____/|___|___| |___| |_______|    |___|___|_______|_______|___|  |_______|___|__|_______|
  520.      *
  521.      */
  522.  
  523. /*  ==========================================================================
  524.     Error Handler
  525.     ========================================================================== */
  526.     function HandleError($err, $sqlerr = null)
  527.     {
  528.         $this->error_message .= $err."\r\n";
  529.         if($sqlerr) {
  530.             $this->error_message .= $sqlerr."\r\n";
  531.         }
  532.     }
  533.  
  534. /*  ==========================================================================
  535.     Handle DB Errors
  536.     ========================================================================== */
  537.     function HandleDBError($err, $sqlerr = null)
  538.     {
  539.         $this->HandleError($err, $sqlerr);
  540.     }
  541.  
  542. /*  ==========================================================================
  543.     Get 'From' Address
  544.     ========================================================================== */
  545.     function GetFromAddress()
  546.     {
  547.         if(!empty($this->from_address))
  548.         {
  549.             return $this->from_address;
  550.         }
  551.  
  552.         $host = $_SERVER['SERVER_NAME'];
  553.  
  554.         $from ="info@$host";
  555.         return $from;
  556.     }
  557.  
  558. /*  ==========================================================================
  559.     Get Login Session
  560.     ========================================================================== */
  561.     function GetLoginSessionVar()
  562.     {
  563.         $retvar = md5($this->rand_key);
  564.         $retvar = 'usr_'.substr($retvar,0,10);
  565.         return $retvar;
  566.     }
  567.  
  568. /*  ==========================================================================
  569.     Check User Login in DB
  570.     ========================================================================== */
  571.     function CheckLoginInDB($email,$password)
  572.     {
  573.         if(!$this->DBLogin())
  574.         {
  575.             $this->HandleError("Database login failed!");
  576.             return false;
  577.         }
  578.  
  579.         $check_db_for_email_stmt = $this->db->prepare("SELECT * FROM $this->db_table WHERE user_email = :user_email");
  580.         $check_db_for_email_stmt->execute(array('user_email' => $email));
  581.         $result = $check_db_for_email_stmt->fetchAll();
  582.  
  583.         if($result) {
  584.             $salt = $result[0]['salt'];
  585.             $encrypted_password = $result[0]['password'];
  586.             $hash = $this->checkhashSSHA($salt, $password);
  587.         }
  588.  
  589.         $user_login_stmt = $this->db->prepare("Select user_name, user_email from $this->db_table where user_email = :user_email and user_password = :hash and user_confirmcode='y'");
  590.         $user_login_stmt->execute(array('user_email' => $email, 'user_password' => $hash));
  591.         $result = $user_login_stmt->fetchAll();
  592.  
  593.         if(!$result)
  594.         {
  595.             $this->HandleError("Error logging in. The username or password does not match");
  596.             return false;
  597.         }
  598.        
  599.         $_SESSION['user_name']  = $result[0]['user_name'];
  600.         $_SESSION['user_email'] = $result[0]['user_email'];
  601.        
  602.         return true;
  603.     }
  604.  
  605. /*  ==========================================================================
  606.     Check Hash
  607.     ========================================================================== */
  608.     public function checkhashSSHA($salt, $password)
  609.     {
  610.         $hash = base64_encode(sha1($password . $salt, true) . $salt);
  611.         return $hash;
  612.     }
  613.  
  614. /*  ==========================================================================
  615.     Update DB on Registration confirmation
  616.     ========================================================================== */
  617.     function UpdateDBRecForConfirmation(&$user_rec)
  618.     {
  619.         if(!$this->DBLogin())
  620.         {
  621.             $this->HandleError("Database login failed!");
  622.             return false;
  623.         }
  624.  
  625.         $confirmcode = $_GET['code'];
  626.  
  627.         $check_confirmation_code_stmt = $this->db->prepare("Select user_name, user_email from $this->db_table where user_confirmcode = :user_confirmcode");
  628.         $check_confirmation_code_stmt->execute(array('user_confirmcode' => $confirmcode));
  629.  
  630.         $result = $check_confirmation_code_stmt->fetchAll();
  631.  
  632.         if(!$result) {
  633.             $this->HandleError("Wrong confirm code");
  634.             return false;
  635.         }
  636.  
  637.         $row = $result[0];
  638.         $user_rec['user_name'] = $row['user_name'];
  639.         $user_rec['user_email'] = $row['user_email'];
  640.  
  641.         try {
  642.             $update_confirmation_code_stmt = $this->db->prepare("Update $this->db_table Set user_confirmcode = 'y' Where user_confirmcode = :user_confirmcode");
  643.             $update_confirmation_code_stmt->execute(array('user_confirmcode' => $confirmcode));
  644.         } catch(PDOException $e) {
  645.             $this->HandleDBError("Error inserting data to the table", $e->getMessage());
  646.             return false;
  647.         }
  648.         return true;
  649.     }
  650.  
  651. /*  ==========================================================================
  652.     Reset user password in DB
  653.     ========================================================================== */
  654.     function ResetUserPasswordInDB($user_rec)
  655.     {
  656.         $new_password = substr(md5(uniqid()),0,10);
  657.        
  658.         if(false == $this->ChangePasswordInDB($user_rec,$new_password))
  659.         {
  660.             return false;
  661.         }
  662.         return $new_password;
  663.     }
  664.  
  665. /*  ==========================================================================
  666.     Change password in DB
  667.     ========================================================================== */
  668.     function ChangePasswordInDB($user_rec, $newpwd)
  669.     {
  670.         $hash = $this->hashSSHA($newpwd);
  671.  
  672.         $new_password = $hash["encrypted"];
  673.  
  674.         $salt = $hash["salt"];
  675.  
  676.         try {
  677.             $change_password_in_db = $this->db->prepare("Update $this->db_table Set user_password = :user_password, user_salt = :user_salt Where user_id = :user_id");
  678.             $change_password_in_db->execute(array('user_password' => $new_password, 'user_salt' => $salt, 'user_id' => $user_rec['user_id']));
  679.         } catch(PDOException $e) {
  680.             $this->HandleDBError("Error updating the password", $e->getMessage());
  681.             return false;
  682.         }
  683.         return true;
  684.     }
  685.  
  686. /*  ==========================================================================
  687.  
  688.     ========================================================================== */
  689.     function GetUserFromEmail($email,&$user_rec)
  690.     {
  691.         if(!$this->DBLogin())
  692.         {
  693.             $this->HandleError("Database login failed!");
  694.             return false;
  695.         }
  696.  
  697.         $get_user_from_email_stmt = $this->db->prepare("Select * from $this->db_table where user_email = :user_email");
  698.         $get_user_from_email_stmt->execute(array(':user_email' => $email));
  699.         $result = $get_user_from_email_stmt->fetchAll();
  700.  
  701.         if(!$result)
  702.         {
  703.             $this->HandleError("There is no user with email: $email");
  704.             return false;
  705.         }
  706.         $user_rec = $result[0];
  707.        
  708.         return true;
  709.     }
  710.  
  711. /*  ==========================================================================
  712.  
  713.     ========================================================================== */
  714.     function SendUserWelcomeEmail(&$user_rec)
  715.     {
  716.         $mailer = new PHPMailer();
  717.        
  718.         $mailer->CharSet = 'utf-8';
  719.        
  720.         $mailer->AddAddress($user_rec['user_email'],$user_rec['user_name']);
  721.        
  722.         $mailer->Subject = "Welcome to ".$this->sitename;
  723.  
  724.         $mailer->From = $this->GetFromAddress();        
  725.        
  726.         $mailer->Body ="Hello ".$user_rec['user_name']."\r\n\r\n".
  727.         "Welcome! Your registration  with ".$this->sitename." is completed.\r\n".
  728.         "\r\n".
  729.         "Regards,\r\n".
  730.         "Webmaster\r\n".
  731.         $this->sitename;
  732.  
  733.         if(!$mailer->Send())
  734.         {
  735.             $this->HandleError("Failed sending user welcome email.");
  736.             return false;
  737.         }
  738.         return true;
  739.     }
  740.  
  741. /*  ==========================================================================
  742.  
  743.     ========================================================================== */
  744.     function SendAdminIntimationOnRegComplete(&$user_rec)
  745.     {
  746.         if(empty($this->admin_email))
  747.         {
  748.             return false;
  749.         }
  750.         $mailer = new PHPMailer();
  751.        
  752.         $mailer->CharSet = 'utf-8';
  753.        
  754.         $mailer->AddAddress($this->admin_email);
  755.        
  756.         $mailer->Subject = "Registration Completed: ".$user_rec['user_name'];
  757.  
  758.         $mailer->From = $this->GetFromAddress();        
  759.        
  760.         $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
  761.         "Name: ".$user_rec['user_name']."\r\n".
  762.         "Email address: ".$user_rec['user_email']."\r\n";
  763.        
  764.         if(!$mailer->Send())
  765.         {
  766.             return false;
  767.         }
  768.         return true;
  769.     }
  770.  
  771. /*  ==========================================================================
  772.  
  773.     ========================================================================== */
  774.     function GetResetPasswordCode($email)
  775.     {
  776.        return substr(md5($email.$this->sitename.$this->rand_key),0,10);
  777.     }
  778.  
  779. /*  ==========================================================================
  780.  
  781.     ========================================================================== */
  782.     function SendResetPasswordLink($user_rec)
  783.     {
  784.         $email = $user_rec['user_email'];
  785.        
  786.         $mailer = new PHPMailer();
  787.        
  788.         $mailer->CharSet = 'utf-8';
  789.        
  790.         $mailer->AddAddress($email,$user_rec['user_name']);
  791.        
  792.         $mailer->Subject = "Your reset password request at ".$this->sitename;
  793.  
  794.         $mailer->From = $this->GetFromAddress();
  795.        
  796.         $link = $this->GetAbsoluteURLFolder().
  797.                 '/resetpwd.php?email='.
  798.                 urlencode($email).'&code='.
  799.                 urlencode($this->GetResetPasswordCode($email));
  800.  
  801.         $mailer->Body ="Hello ".$user_rec['user_name']."\r\n\r\n".
  802.         "There was a request to reset your password at ".$this->sitename."\r\n".
  803.         "Please click the link below to complete the request: \r\n".$link."\r\n".
  804.         "Regards,\r\n".
  805.         "Webmaster\r\n".
  806.         $this->sitename;
  807.        
  808.         if(!$mailer->Send())
  809.         {
  810.             return false;
  811.         }
  812.         return true;
  813.     }
  814.  
  815. /*  ==========================================================================
  816.  
  817.     ========================================================================== */
  818.     function SendNewPassword($user_rec, $new_password)
  819.     {
  820.         $email = $user_rec['user_email'];
  821.        
  822.         $mailer = new PHPMailer();
  823.        
  824.         $mailer->CharSet = 'utf-8';
  825.        
  826.         $mailer->AddAddress($email,$user_rec['user_name']);
  827.        
  828.         $mailer->Subject = "Your new password for ".$this->sitename;
  829.  
  830.         $mailer->From = $this->GetFromAddress();
  831.        
  832.         $mailer->Body ="Hello ".$user_rec['user_name']."\r\n\r\n".
  833.         "Your password is reset successfully. ".
  834.         "Here is your updated login:\r\n".
  835.         "username:".$user_rec['user_name']."\r\n".
  836.         "password:$new_password\r\n".
  837.         "\r\n".
  838.         "Login here: ".$this->GetAbsoluteURLFolder()."/login.php\r\n".
  839.         "\r\n".
  840.         "Regards,\r\n".
  841.         "Webmaster\r\n".
  842.         $this->sitename;
  843.        
  844.         if(!$mailer->Send())
  845.         {
  846.             return false;
  847.         }
  848.         return true;
  849.     }
  850.  
  851. /*  ==========================================================================
  852.  
  853.     ========================================================================== */
  854.     function ValidateRegistrationSubmission()
  855.     {
  856.         //This is a hidden input field. Humans won't fill this field.
  857.         if(!empty($_POST[$this->GetSpamTrapInputName()]) )
  858.         {
  859.             //The proper error is not given intentionally
  860.             $this->HandleError("Automated submission prevention: case 2 failed");
  861.             return false;
  862.         }
  863.        
  864.         $validator = new FormValidator();
  865.         $validator->addValidation("user_name","req","Please fill in Name");
  866.         $validator->addValidation("user_email","email","The input for Email should be a valid email value");
  867.         $validator->addValidation("user_email","req","Please fill in Email");
  868.         $validator->addValidation("user_password","req","Please fill in Password");
  869.  
  870.  
  871.         if(!$validator->ValidateForm())
  872.         {
  873.  
  874.             $error='';
  875.             $error_hash = $validator->GetErrors();
  876.             foreach($error_hash as $inpname => $inp_err)
  877.             {
  878.                 $error .= $inpname.':'.$inp_err."\n";
  879.             }
  880.             $this->HandleError($error);
  881.             return false;
  882.         }
  883.         return true;
  884.     }
  885.  
  886. /*  ==========================================================================
  887.  
  888.     ========================================================================== */
  889.     function CollectRegistrationSubmission(&$formvars)
  890.     {
  891.         $formvars['user_name'] = $this->Sanitize($_POST['user_name']);
  892.         $formvars['user_email'] = $this->Sanitize($_POST['user_email']);
  893.         $formvars['user_phone'] = $this->Sanitize($_POST['user_phone']);
  894.         $formvars['user_password'] = $this->Sanitize($_POST['user_password']);
  895.  
  896.         $confirmcode = $this->MakeConfirmationMd5($formvars['user_email']);
  897.         $formvars['user_confirmcode'] = $confirmcode;
  898.     }
  899.  
  900. /*  ==========================================================================
  901.  
  902.     ========================================================================== */
  903.     function SendUserConfirmationEmail(&$formvars)
  904.     {
  905.         $mailer = new PHPMailer();
  906.        
  907.         $mailer->CharSet = 'utf-8';
  908.        
  909.         $mailer->AddAddress($formvars['user_email'],$formvars['user_name']);
  910.        
  911.         $mailer->Subject = "Your registration with ".$this->sitename;
  912.  
  913.         $mailer->From = $this->GetFromAddress();        
  914.  
  915.         $confirmcode = $formvars['user_confirmcode'];
  916.        
  917.         $confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;
  918.        
  919.         $mailer->Body ="Hello ".$formvars['user_name']."\r\n\r\n".
  920.         "Thanks for your registration with ".$this->sitename."\r\n".
  921.         "Please click the link below to confirm your registration.\r\n".
  922.         "$confirm_url\r\n".
  923.         "\r\n".
  924.         "Regards,\r\n".
  925.         "Webmaster\r\n".
  926.         $this->sitename;
  927.  
  928.         if(!$mailer->Send())
  929.         {
  930.             $this->HandleError("Failed sending registration confirmation email.");
  931.             return false;
  932.         }
  933.         return true;
  934.     }
  935.  
  936. /*  ==========================================================================
  937.  
  938.     ========================================================================== */
  939.     function GetAbsoluteURLFolder()
  940.     {
  941.         $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
  942.  
  943.         $urldir ='';
  944.         $pos = strrpos($_SERVER['REQUEST_URI'],'/');
  945.         if(false !==$pos)
  946.         {
  947.             $urldir = substr($_SERVER['REQUEST_URI'],0,$pos);
  948.         }
  949.  
  950.         $scriptFolder .= $_SERVER['HTTP_HOST'].$urldir;
  951.  
  952.         return $scriptFolder;
  953.     }
  954.  
  955. /*  ==========================================================================
  956.  
  957.     ========================================================================== */
  958.     function SendAdminIntimationEmail(&$formvars)
  959.     {
  960.         if(empty($this->admin_email))
  961.         {
  962.             return false;
  963.         }
  964.         $mailer = new PHPMailer();
  965.        
  966.         $mailer->CharSet = 'utf-8';
  967.        
  968.         $mailer->AddAddress($this->admin_email);
  969.        
  970.         $mailer->Subject = "New registration: ".$formvars['user_name'];
  971.  
  972.         $mailer->From = $this->GetFromAddress();        
  973.        
  974.         $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
  975.         "Name: ".$formvars['user_name']."\r\n".
  976.         "Email address: ".$formvars['user_email']."\r\n".
  977.         "Phone number: ".$formvars['user_phone'];
  978.        
  979.         if(!$mailer->Send())
  980.         {
  981.             return false;
  982.         }
  983.         return true;
  984.     }
  985.  
  986. /*  ==========================================================================
  987.  
  988.     ========================================================================== */
  989.     function SaveToDatabase(&$formvars)
  990.     {
  991.         if(!$this->DBLogin())
  992.         {
  993.             $this->HandleError("Database login failed!");
  994.             return false;
  995.         }
  996.         if(!$this->Ensuretable())
  997.         {
  998.             return false;
  999.         }
  1000.         if(!$this->IsFieldUnique($formvars,'user_email'))
  1001.         {
  1002.             $this->HandleError("This email is already registered");
  1003.             return false;
  1004.         }
  1005.         if(!$this->InsertIntoDB($formvars))
  1006.         {
  1007.             $this->HandleError("Inserting to Database failed!");
  1008.             return false;
  1009.         }
  1010.         return true;
  1011.     }
  1012. /*  ==========================================================================
  1013.  
  1014.     ========================================================================== */
  1015.     function IsFieldUnique($formvars,$fieldname)
  1016.     {
  1017.         $fieldname = $this->db->quote($fieldname);
  1018.  
  1019.         $is_field_unique_stmt = $this->db->prepare("select user_email from $this->db_table where $fieldname = :fieldname");
  1020.         $is_field_unique_stmt->execute(array('fieldname' => $formvars[$fieldname]));
  1021.         $result = $is_field_unique_stmt->fetchAll();
  1022.  
  1023.         // if there is a result (field is not unique), return false
  1024.         if($result)
  1025.         {
  1026.             return false;
  1027.         }
  1028.         return true;
  1029.     }
  1030.  
  1031. /*  ==========================================================================
  1032.  
  1033.     ========================================================================== */
  1034.     function DBLogin()
  1035.     {
  1036.         try {
  1037.             $this->db = new PDO("mysql:dbname={$this->db_name};host={$this->db_host};charset=utf8", $this->db_username, $this->db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
  1038.         } catch(PDOException $e) {
  1039.             $this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct", $e->getMessage());
  1040.             return false;
  1041.         }
  1042.         return true;
  1043.     }
  1044.  
  1045. /*  ==========================================================================
  1046.  
  1047.     ========================================================================== */
  1048.     function Ensuretable()
  1049.     {
  1050.         try {
  1051.             $ensure_table_stmt = $this->db->query("select 1 from $this->db_table");
  1052.             $result = $ensure_table_stmt->fetchAll();
  1053.         } catch (PDOException $e) {
  1054.             // We got an exception == table not found
  1055.             $result = false;
  1056.         }
  1057.  
  1058.         // if result is false user table is created
  1059.         if(!$result) {
  1060.             return $this->CreateTable();
  1061.         }
  1062.         return true;
  1063.     }
  1064.  
  1065. /*  ==========================================================================
  1066.  
  1067.     ========================================================================== */
  1068.     function CreateTable()
  1069.     {
  1070.         $create_table_stmt =    "Create Table $this->db_table (".
  1071.                                 "user_id INT NOT NULL AUTO_INCREMENT ,".
  1072.                                 "user_name VARCHAR( 128 ) NOT NULL ,".
  1073.                                 "user_email VARCHAR( 64 ) NOT NULL ,".
  1074.                                 "user_phone VARCHAR( 16 ) ,".
  1075.                                 "user_salt VARCHAR( 50 ) NOT NULL ,".
  1076.                                 "user_stripe_id VARCHAR( 64 ) ,".
  1077.                                 "user_password VARCHAR( 80 ) NOT NULL ,".
  1078.                                 "user_confirmcode VARCHAR(32) ,".
  1079.                                 "PRIMARY KEY ( user_id )".
  1080.                                 ")";
  1081.  
  1082.         try {
  1083.             $this->db->query($create_table_stmt);
  1084.         } catch(PDOException $e) {
  1085.             $this->HandleDBError("Error creating the table", $e->getMessage());
  1086.             return false;
  1087.         }
  1088.  
  1089.         return true;
  1090.     }
  1091.  
  1092. /*  ==========================================================================
  1093.  
  1094.     ========================================================================== */
  1095.     function InsertIntoDB(&$formvars)
  1096.     {
  1097.         $hash = $this->hashSSHA($formvars['user_password']);
  1098.  
  1099.         $encrypted_password = $hash["encrypted"];
  1100.            
  1101.         $salt = $hash["salt"];
  1102.  
  1103.         try {
  1104.             $insert_user_stmt = $this->db->prepare("INSERT INTO $this->db_table
  1105.                                                    (user_name, user_email, user_phone, user_password, user_salt, user_stripe_id, user_confirmcode)
  1106.                                                    VALUES
  1107.                                                    (:user_name,:user_email,:user_phone,:user_password,:user_salt,:user_stripe_id,:user_confirmcode)");
  1108.  
  1109.             $insert_user_stmt->execute( array(  'user_name' => $formvars['user_name'],
  1110.                                                 'user_email' => $formvars['user_email'],
  1111.                                                 'user_phone' => $formvars['user_phone'],
  1112.                                                 'user_password' => $encrypted_password,
  1113.                                                 'user_salt' => $salt,
  1114.                                                 'user_stripe_id' => $formvars['user_stripe_id'],
  1115.                                                 'user_confirmcode' => $formvars['user_confirmcode']));
  1116.         } catch(PDOException $e) {
  1117.             $this->HandleDBError("Error inserting data to the table", $e->getMessage());
  1118.             return false;
  1119.         }
  1120.  
  1121.         return true;
  1122.     }
  1123.  
  1124. /*  ==========================================================================
  1125.  
  1126.     ========================================================================== */
  1127.     function hashSSHA($password)
  1128.     {
  1129.         $salt = sha1(rand());
  1130.         $salt = substr($salt, 0, 10);
  1131.         $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
  1132.         $hash = array("salt" => $salt, "encrypted" => $encrypted);
  1133.         return $hash;
  1134.     }
  1135.  
  1136. /*  ==========================================================================
  1137.  
  1138.     ========================================================================== */
  1139.     function MakeConfirmationMd5($email)
  1140.     {
  1141.         $randno1 = rand();
  1142.         $randno2 = rand();
  1143.         return md5($email.$this->rand_key.$randno1.''.$randno2);
  1144.     }
  1145.  
  1146. /*  ==========================================================================
  1147.  
  1148.     Sanitize() function removes any potential threat from the
  1149.     data submitted. Prevents email injections or any other hacker attempts.
  1150.     if $remove_nl is true, newline chracters are removed from the input.
  1151.  
  1152.     ========================================================================== */
  1153.     function Sanitize($str,$remove_nl=true)
  1154.     {
  1155.         if($remove_nl)
  1156.         {
  1157.             $injections = array('/(\n+)/i',
  1158.                 '/(\r+)/i',
  1159.                 '/(\t+)/i',
  1160.                 '/(%0A+)/i',
  1161.                 '/(%0D+)/i',
  1162.                 '/(%08+)/i',
  1163.                 '/(%09+)/i'
  1164.             );
  1165.             $str = preg_replace($injections,'',$str);
  1166.         }
  1167.  
  1168.         return $str;
  1169.     }
  1170.  
  1171. } // end of Members() class
Add Comment
Please, Sign In to add comment