Guest User

Untitled

a guest
Jun 17th, 2013
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.58 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. /* Check if username is banned */
  270. else if($database->usernameBanned($subuser)){
  271. $form->setError($field, "* Username banned");
  272. }
  273. }
  274.  
  275. /* Password error checking */
  276. $field = "pass"; //Use field name for password
  277. if(!$subpass){
  278. $form->setError($field, "* Password not entered");
  279. }
  280. else{
  281. /* Spruce up password and check length*/
  282. $subpass = stripslashes($subpass);
  283. if(strlen($subpass) < 4){
  284. $form->setError($field, "* Password too short");
  285. }
  286. /* Check if password is not alphanumeric */
  287. else if(!preg_match("/^([0-9a-z])+$/i", ($subpass = trim($subpass)))){
  288. $form->setError($field, "* Password not alphanumeric");
  289. }
  290. /**
  291. * Note: I trimmed the password only after I checked the length
  292. * because if you fill the password field up with spaces
  293. * it looks like a lot more characters than 4, so it looks
  294. * kind of stupid to report "password too short".
  295. */
  296. }
  297.  
  298. /* Email error checking */
  299. $field = "email"; //Use field name for email
  300. if(!$subemail || strlen($subemail = trim($subemail)) == 0){
  301. $form->setError($field, "* Email not entered");
  302. }
  303. else{
  304. /* Check if valid email address */
  305. $regex = "/^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
  306. ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
  307. ."\.([a-z]{2,}){1}$/i";
  308. if(!preg_match($regex,$subemail)){
  309. $form->setError($field, "* Email invalid");
  310. }
  311. $subemail = stripslashes($subemail);
  312. }
  313.  
  314. /* Errors exist, have user correct them */
  315. if($form->num_errors > 0){
  316. return 1; //Errors with form
  317. }
  318. /* No errors, add the new account to the */
  319. else{
  320. if($database->addNewUser($subuser, md5($subpass), $subemail)){
  321. if(EMAIL_WELCOME){
  322. $mailer->sendWelcome($subuser,$subemail,$subpass);
  323. }
  324. return 0; //New user added succesfully
  325. }else{
  326. return 2; //Registration attempt failed
  327. }
  328. }
  329. }
  330.  
  331. /**
  332. * editAccount - Attempts to edit the user's account information
  333. * including the password, which it first makes sure is correct
  334. * if entered, if so and the new password is in the right
  335. * format, the change is made. All other fields are changed
  336. * automatically.
  337. */
  338. function editAccount($subcurpass, $subnewpass, $subemail){
  339. global $database, $form; //The database and form object
  340. /* New password entered */
  341. if($subnewpass){
  342. /* Current Password error checking */
  343. $field = "curpass"; //Use field name for current password
  344. if(!$subcurpass){
  345. $form->setError($field, "* Current Password not entered");
  346. }
  347. else{
  348. /* Check if password too short or is not alphanumeric */
  349. $subcurpass = stripslashes($subcurpass);
  350. if(strlen($subcurpass) < 4 ||
  351. !preg_match("/^([0-9a-z])+$/i", ($subcurpass = trim($subcurpass)))){
  352. $form->setError($field, "* Current Password incorrect");
  353. }
  354. /* Password entered is incorrect */
  355. if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){
  356. $form->setError($field, "* Current Password incorrect");
  357. }
  358. }
  359.  
  360. /* New Password error checking */
  361. $field = "newpass"; //Use field name for new password
  362. /* Spruce up password and check length*/
  363. $subpass = stripslashes($subnewpass);
  364. if(strlen($subnewpass) < 4){
  365. $form->setError($field, "* New Password too short");
  366. }
  367. /* Check if password is not alphanumeric */
  368. else if(!preg_match("/^([0-9a-z])+$/i", ($subnewpass = trim($subnewpass)))){
  369. $form->setError($field, "* New Password not alphanumeric");
  370. }
  371. }
  372. /* Change password attempted */
  373. else if($subcurpass){
  374. /* New Password error reporting */
  375. $field = "newpass"; //Use field name for new password
  376. $form->setError($field, "* New Password not entered");
  377. }
  378.  
  379. /* Email error checking */
  380. $field = "email"; //Use field name for email
  381. if($subemail && strlen($subemail = trim($subemail)) > 0){
  382. /* Check if valid email address */
  383. $regex = "/^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
  384. ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
  385. ."\.([a-z]{2,}){1}$/i";
  386. if(!preg_match($regex,$subemail)){
  387. $form->setError($field, "* Email invalid");
  388. }
  389. $subemail = stripslashes($subemail);
  390. }
  391.  
  392. /* Errors exist, have user correct them */
  393. if($form->num_errors > 0){
  394. return false; //Errors with form
  395. }
  396.  
  397. /* Update password since there were no errors */
  398. if($subcurpass && $subnewpass){
  399. $database->updateUserField($this->username,"password",md5($subnewpass));
  400. }
  401.  
  402. /* Change Email */
  403. if($subemail){
  404. $database->updateUserField($this->username,"email",$subemail);
  405. }
  406.  
  407. /* Success! */
  408. return true;
  409. }
  410.  
  411. /**
  412. * isAdmin - Returns true if currently logged in user is
  413. * an administrator, false otherwise.
  414. */
  415. function isAdmin(){
  416. return ($this->userlevel == ADMIN_LEVEL ||
  417. $this->username == ADMIN_NAME);
  418. }
  419.  
  420. /**
  421. * generateRandID - Generates a string made up of randomized
  422. * letters (lower and upper case) and digits and returns
  423. * the md5 hash of it to be used as a userid.
  424. */
  425. function generateRandID(){
  426. return md5($this->generateRandStr(16));
  427. }
  428.  
  429. /**
  430. * generateRandStr - Generates a string made up of randomized
  431. * letters (lower and upper case) and digits, the length
  432. * is a specified parameter.
  433. */
  434. function generateRandStr($length){
  435. $randstr = "";
  436. for($i=0; $i<$length; $i++){
  437. $randnum = mt_rand(0,61);
  438. if($randnum < 10){
  439. $randstr .= chr($randnum+48);
  440. }else if($randnum < 36){
  441. $randstr .= chr($randnum+55);
  442. }else{
  443. $randstr .= chr($randnum+61);
  444. }
  445. }
  446. return $randstr;
  447. }
  448. };
  449.  
  450.  
  451. /**
  452. * Initialize session object - This must be initialized before
  453. * the form object because the form uses session variables,
  454. * which cannot be accessed unless the session has started.
  455. */
  456. $session = new Session;
  457.  
  458. /* Initialize form object */
  459. $form = new Form;
  460.  
  461. ?>
Advertisement
Add Comment
Please, Sign In to add comment