Advertisement
Guest User

include/session.php

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