Login completo, campos extras agregados a la base de datos.
[CLab.git] / include / session.php
blob681274babf70d37d54c99cfd042cfe7f939904a2
1 <?
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.
8 * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
9 * Last Updated: August 19, 2004
11 include("database.php");
12 include("mailer.php");
13 include("form.php");
15 class Session
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.
31 /* Class constructor */
32 function Session(){
33 $this->time = time();
34 $this->startSession();
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.
44 function startSession(){
45 global $database; //The database connection
46 session_start(); //Tell PHP to start the session
48 /* Determine if user is logged in */
49 $this->logged_in = $this->checkLogin();
51 /**
52 * Set guest value to users not logged in, and update
53 * active guests table accordingly.
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);
60 /* Update users last active timestamp */
61 else{
62 $database->addActiveUser($this->username, $this->time);
65 /* Remove inactive visitors from database */
66 $database->removeInactiveUsers();
67 $database->removeInactiveGuests();
69 /* Set referrer page */
70 if(isset($_SESSION['url'])){
71 $this->referrer = $_SESSION['url'];
72 }else{
73 $this->referrer = "/";
76 /* Set current url */
77 $this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];
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.
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'];
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;
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;
113 /* User not logged in */
114 else{
115 return false;
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.
125 function login($subuser, $subpass, $subremember){
126 global $database, $form; //The database and form object
128 /* Username error checking */
129 $field = "user"; //Use field name for username
130 if(!$subuser || strlen($subuser = trim($subuser)) == 0){
131 $form->setError($field, "* Username not entered");
133 else{
134 /* Check if username is not alphanumeric */
135 if(!eregi("^([0-9a-z])*$", $subuser)){
136 $form->setError($field, "* Username not alphanumeric");
140 /* Password error checking */
141 $field = "pass"; //Use field name for password
142 if(!$subpass){
143 $form->setError($field, "* Password not entered");
146 /* Return if form errors exist */
147 if($form->num_errors > 0){
148 return false;
151 /* Checks that username is in database and password is correct */
152 $subuser = stripslashes($subuser);
153 $result = $database->confirmUserPass($subuser, md5($subpass));
155 /* Check error codes */
156 if($result == 1){
157 $field = "user";
158 $form->setError($field, "* Username not found");
160 else if($result == 2){
161 $field = "pass";
162 $form->setError($field, "* Invalid password");
165 /* Return if form errors exist */
166 if($form->num_errors > 0){
167 return false;
170 /* Username and password correct, register session variables */
171 $this->userinfo = $database->getUserInfo($subuser);
172 $this->username = $_SESSION['username'] = $this->userinfo['username'];
173 $this->userid = $_SESSION['userid'] = $this->generateRandID();
174 $this->userlevel = $this->userinfo['userlevel'];
176 /* Insert userid into database and update active users table */
177 $database->updateUserField($this->username, "userid", $this->userid);
178 $database->addActiveUser($this->username, $this->time);
179 $database->removeActiveGuest($_SERVER['REMOTE_ADDR']);
182 * This is the cool part: the user has requested that we remember that
183 * he's logged in, so we set two cookies. One to hold his username,
184 * and one to hold his random value userid. It expires by the time
185 * specified in constants.php. Now, next time he comes to our site, we will
186 * log him in automatically, but only if he didn't log out before he left.
188 if($subremember){
189 setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
190 setcookie("cookid", $this->userid, time()+COOKIE_EXPIRE, COOKIE_PATH);
193 /* Login completed successfully */
194 return true;
198 * logout - Gets called when the user wants to be logged out of the
199 * website. It deletes any cookies that were stored on the users
200 * computer as a result of him wanting to be remembered, and also
201 * unsets session variables and demotes his user level to guest.
203 function logout(){
204 global $database; //The database connection
206 * Delete cookies - the time must be in the past,
207 * so just negate what you added when creating the
208 * cookie.
210 if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
211 setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
212 setcookie("cookid", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
215 /* Unset PHP session variables */
216 unset($_SESSION['username']);
217 unset($_SESSION['userid']);
219 /* Reflect fact that user has logged out */
220 $this->logged_in = false;
223 * Remove from active users table and add to
224 * active guests tables.
226 $database->removeActiveUser($this->username);
227 $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
229 /* Set user level to guest */
230 $this->username = GUEST_NAME;
231 $this->userlevel = GUEST_LEVEL;
235 * register - Gets called when the user has just submitted the
236 * registration form. Determines if there were any errors with
237 * the entry fields, if so, it records the errors and returns
238 * 1. If no errors were found, it registers the new user and
239 * returns 0. Returns 2 if registration failed.
241 function register($subuser, $subpass, $subemail, $nombre, $catedratico, $tipo, $departamento){
242 global $database, $form, $mailer; //The database, form and mailer object
244 /* Username error checking */
245 $field = "user"; //Use field name for username
246 if(!$subuser || strlen($subuser = trim($subuser)) == 0){
247 $form->setError($field, "* Username not entered");
249 else{
250 /* Spruce up username, check length */
251 $subuser = stripslashes($subuser);
252 if(strlen($subuser) < 5){
253 $form->setError($field, "* Username below 5 characters");
255 else if(strlen($subuser) > 30){
256 $form->setError($field, "* Username above 30 characters");
258 /* Check if username is not alphanumeric */
259 else if(!eregi("^([0-9a-z])+$", $subuser)){
260 $form->setError($field, "* Username not alphanumeric");
262 /* Check if username is reserved */
263 else if(strcasecmp($subuser, GUEST_NAME) == 0){
264 $form->setError($field, "* Username reserved word");
266 /* Check if username is already in use */
267 else if($database->usernameTaken($subuser)){
268 $form->setError($field, "* Username already in use");
270 /* Check if username is banned */
271 else if($database->usernameBanned($subuser)){
272 $form->setError($field, "* Username banned");
276 /* Password error checking */
277 $field = "pass"; //Use field name for password
278 if(!$subpass){
279 $form->setError($field, "* Password not entered");
281 else{
282 /* Spruce up password and check length*/
283 $subpass = stripslashes($subpass);
284 if(strlen($subpass) < 4){
285 $form->setError($field, "* Password too short");
287 /* Check if password is not alphanumeric */
288 else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){
289 $form->setError($field, "* Password not alphanumeric");
292 * Note: I trimmed the password only after I checked the length
293 * because if you fill the password field up with spaces
294 * it looks like a lot more characters than 4, so it looks
295 * kind of stupid to report "password too short".
299 /* Email error checking */
300 $field = "email"; //Use field name for email
301 if(!$subemail || strlen($subemail = trim($subemail)) == 0){
302 $form->setError($field, "* Email not entered");
304 else{
305 /* Check if valid email address */
306 $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
307 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
308 ."\.([a-z]{2,}){1}$";
309 if(!eregi($regex,$subemail)){
310 $form->setError($field, "* Email invalid");
312 $subemail = stripslashes($subemail);
315 /* Errors exist, have user correct them */
316 if($form->num_errors > 0){
317 return 1; //Errors with form
319 /* No errors, add the new account to the */
320 else{
321 if($database->addNewUser($subuser, md5($subpass), $subemail, $nombre, $catedratico, $tipo, $departamento)){
322 if(EMAIL_WELCOME){
323 $mailer->sendWelcome($subuser,$subemail,$subpass);
325 return 0; //New user added succesfully
326 }else{
327 return 2; //Registration attempt failed
333 * editAccount - Attempts to edit the user's account information
334 * including the password, which it first makes sure is correct
335 * if entered, if so and the new password is in the right
336 * format, the change is made. All other fields are changed
337 * automatically.
339 function editAccount($subcurpass, $subnewpass, $subemail){
340 global $database, $form; //The database and form object
341 /* New password entered */
342 if($subnewpass){
343 /* Current Password error checking */
344 $field = "curpass"; //Use field name for current password
345 if(!$subcurpass){
346 $form->setError($field, "* Current Password not entered");
348 else{
349 /* Check if password too short or is not alphanumeric */
350 $subcurpass = stripslashes($subcurpass);
351 if(strlen($subcurpass) < 4 ||
352 !eregi("^([0-9a-z])+$", ($subcurpass = trim($subcurpass)))){
353 $form->setError($field, "* Current Password incorrect");
355 /* Password entered is incorrect */
356 if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){
357 $form->setError($field, "* Current Password incorrect");
361 /* New Password error checking */
362 $field = "newpass"; //Use field name for new password
363 /* Spruce up password and check length*/
364 $subpass = stripslashes($subnewpass);
365 if(strlen($subnewpass) < 4){
366 $form->setError($field, "* New Password too short");
368 /* Check if password is not alphanumeric */
369 else if(!eregi("^([0-9a-z])+$", ($subnewpass = trim($subnewpass)))){
370 $form->setError($field, "* New Password not alphanumeric");
373 /* Change password attempted */
374 else if($subcurpass){
375 /* New Password error reporting */
376 $field = "newpass"; //Use field name for new password
377 $form->setError($field, "* New Password not entered");
380 /* Email error checking */
381 $field = "email"; //Use field name for email
382 if($subemail && strlen($subemail = trim($subemail)) > 0){
383 /* Check if valid email address */
384 $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
385 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
386 ."\.([a-z]{2,}){1}$";
387 if(!eregi($regex,$subemail)){
388 $form->setError($field, "* Email invalid");
390 $subemail = stripslashes($subemail);
393 /* Errors exist, have user correct them */
394 if($form->num_errors > 0){
395 return false; //Errors with form
398 /* Update password since there were no errors */
399 if($subcurpass && $subnewpass){
400 $database->updateUserField($this->username,"password",md5($subnewpass));
403 /* Change Email */
404 if($subemail){
405 $database->updateUserField($this->username,"email",$subemail);
408 /* Success! */
409 return true;
413 * isAdmin - Returns true if currently logged in user is
414 * an administrator, false otherwise.
416 function isAdmin(){
417 return ($this->userlevel == ADMIN_LEVEL ||
418 $this->username == ADMIN_NAME);
422 * generateRandID - Generates a string made up of randomized
423 * letters (lower and upper case) and digits and returns
424 * the md5 hash of it to be used as a userid.
426 function generateRandID(){
427 return md5($this->generateRandStr(16));
431 * generateRandStr - Generates a string made up of randomized
432 * letters (lower and upper case) and digits, the length
433 * is a specified parameter.
435 function generateRandStr($length){
436 $randstr = "";
437 for($i=0; $i<$length; $i++){
438 $randnum = mt_rand(0,61);
439 if($randnum < 10){
440 $randstr .= chr($randnum+48);
441 }else if($randnum < 36){
442 $randstr .= chr($randnum+55);
443 }else{
444 $randstr .= chr($randnum+61);
447 return $randstr;
453 * Initialize session object - This must be initialized before
454 * the form object because the form uses session variables,
455 * which cannot be accessed unless the session has started.
457 $session = new Session;
459 /* Initialize form object */
460 $form = new Form;