Implementación de edición completa de Instructores. Parche 4.
[CLab.git] / include / sesion.php
blobb002a01e7d41fabe232a242bf6d2c8addd5e1fee
1 <?
2 require_once("database.php");
3 require_once("mailer.php");
4 require_once("form.php");
5 require_once("depurar.php");
6 class Session
8 var $username; //Username given on sign-up
9 var $userid; //Random value generated on current login
10 var $userlevel; //The level to which the user pertains
11 var $time; //Time user was last active (page loaded)
12 var $logged_in; //True if user is logged in, false otherwise
13 var $userinfo = array(); //The array holding all user info
14 var $url; //The page url current being viewed
15 var $referrer; //Last recorded site page viewed
16 /**
17 * Note: referrer should really only be considered the actual
18 * page referrer in process.php, any other time it may be
19 * inaccurate.
22 /* Class constructor */
23 function Session(){
24 $this->time = time();
25 $this->startSession();
28 /**
29 * startSession - Performs all the actions necessary to
30 * initialize this session object. Tries to determine if the
31 * the user has logged in already, and sets the variables
32 * accordingly. Also takes advantage of this page load to
33 * update the active visitors tables.
35 function startSession(){
36 global $database; //The database connection
37 session_start(); //Tell PHP to start the session
39 /* Determine if user is logged in */
40 $this->logged_in = $this->checkLogin();
42 /**
43 * Set guest value to users not logged in, and update
44 * active guests table accordingly.
46 if(!$this->logged_in){
47 $this->username = $_SESSION['username'] = GUEST_NAME;
48 $this->userlevel = GUEST_LEVEL;
49 $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
51 /* Update users last active timestamp */
52 else{
53 $database->addActiveUser($this->username, $this->time);
56 /* Remove inactive visitors from database */
57 $database->removeInactiveUsers();
58 $database->removeInactiveGuests();
60 /* Set referrer page */
61 if(isset($_SESSION['url'])){
62 $this->referrer = $_SESSION['url'];
63 }else{
64 $this->referrer = "/";
67 /* Set current url */
68 $this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];
71 /**
72 * checkLogin - Checks if the user has already previously
73 * logged in, and a session with the user has already been
74 * established. Also checks to see if user has been remembered.
75 * If so, the database is queried to make sure of the user's
76 * authenticity. Returns true if the user has logged in.
78 function checkLogin(){
79 global $database; //The database connection
80 /* Check if user has been remembered */
81 if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
82 $this->username = $_SESSION['username'] = $_COOKIE['cookname'];
83 $this->userid = $_SESSION['userid'] = $_COOKIE['cookid'];
84 DEPURAR ("Check Login: " . $this->username);
87 DEPURAR ("Check Login GUEST_NAME: " . GUEST_NAME);
88 /* Username and userid have been set and not guest */
89 if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&
90 $_SESSION['username'] != GUEST_NAME){
91 DEPURAR ("Check Login: Username and userid have been set and not guest");
92 /* Confirm that username and userid are valid */
93 if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){
94 echo "Check Login: Variables are incorrect, user not logged in<br />";
95 /* Variables are incorrect, user not logged in */
96 unset($_SESSION['username']);
97 unset($_SESSION['userid']);
98 return false;
100 DEPURAR ("Check Login SESSION[username]: " . $_SESSION['username']);
101 /* User is logged in, set class variables */
102 $this->userinfo = $database->getUserInfo($_SESSION['username']);
103 $this->username = $this->userinfo['username'];
104 $this->userid = $this->userinfo['userid'];
105 $this->userlevel = $this->userinfo['userlevel'];
106 DEPURAR ("Check Login IN!");
107 return true;
109 /* User not logged in */
110 else{
111 DEPURAR("Check Login NOT IN!");
112 return false;
117 * login - The user has submitted his username and password
118 * through the login form, this function checks the authenticity
119 * of that information in the database and creates the session.
120 * Effectively logging in the user if all goes well.
122 function login($subuser, $subpass, $subremember){
123 global $database, $form; //The database and form object
124 DEPURAR ("Login:".$subuser);
125 /* Username error checking */
126 $field = "user"; //Use field name for username
127 if(!$subuser || strlen($subuser = trim($subuser)) == 0){
128 $form->setError($field, "* No se ingreso Código o Carné del Instructor");
130 else{
131 /* Check if username is not alphanumeric */
132 if(!eregi("^([0-9a-z])*$", $subuser)){
133 $form->setError($field, "* Username not alphanumeric");
137 /* Password error checking */
138 /*$field = "pass"; //Use field name for password
139 if(!$subpass){
140 $form->setError($field, "* Olvidó ingresar la clave");
143 /* Return if form errors exist */
144 if($form->num_errors > 0){
145 return false;
147 DEPURAR ("Login: Checks 1 passed");
148 /* Checks that username is in database and password is correct */
149 $subuser = stripslashes($subuser);
150 $result = $database->confirmUserPass($subuser, md5($subpass));
152 /* Check error codes */
153 if($result == 1){
154 $field = "user";
155 $form->setError($field, "* Código o Carné de Instructor no encontrado");
156 DEPURAR ("Login: Not user");
158 else if($result == 2){
159 $field = "pass";
160 $form->setError($field, "* Clave inválida");
161 DEPURAR ("Login: Not Pass");
164 /* Return if form errors exist */
165 if($form->num_errors > 0){
166 return false;
168 DEPURAR ("Login: Checks 2 passed");
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'];
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']);
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.
187 if($subremember){
188 setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
189 setcookie("cookid", $this->userid, time()+COOKIE_EXPIRE, COOKIE_PATH);
191 DEPURAR ("Login: IN");
192 /* Login completed successfully */
193 return true;
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.
202 function logout(){
203 global $database; //The database connection
205 * Delete cookies - the time must be in the past,
206 * so just negate what you added when creating the
207 * cookie.
209 if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
210 setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
211 setcookie("cookid", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
214 /* Unset PHP session variables */
215 unset($_SESSION['username']);
216 unset($_SESSION['userid']);
218 /* Reflect fact that user has logged out */
219 $this->logged_in = false;
222 * Remove from active users table and add to
223 * active guests tables.
225 $database->removeActiveUser($this->username);
226 $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
228 /* Set user level to guest */
229 $this->username = GUEST_NAME;
230 $this->userlevel = GUEST_LEVEL;
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.
240 function register($subuser, $subpass, $subemail, $nombre, $encargado, $catedratico, $tipo, $departamento){
241 global $database, $form, $mailer; //The database, form and mailer object
243 $form->setValue("nombre", $nombre);
244 $form->setValue("encargado", $encargado);
245 $form->setValue("catedratico", $catedratico);
246 $form->setValue("tipo", $tipo);
247 $form->setValue("departamento", $departamento);
249 /* Username error checking */
250 $field = "user"; //Use field name for username
251 if(!$subuser || strlen($subuser = trim($subuser)) == 0){
252 $form->setError($field, "* Nombre de usuario no ingresado");
254 else{
255 /* Spruce up username, check length */
256 $subuser = stripslashes($subuser);
257 if(strlen($subuser) < 5){
258 $form->setError($field, "* Código o Carné de Instructor menor a 5 caracteres");
260 else if(strlen($subuser) > 30){
261 $form->setError($field, "* Código o Carné de Instructor mayor a 30 caracteres");
263 /* Check if username is not alphanumeric */
264 else if(!eregi("^([0-9a-z])+$", $subuser)){
265 $form->setError($field, "* Código o Carné de Instructor no Alfanumerico");
267 /* Check if username is reserved */
268 else if(strcasecmp($subuser, GUEST_NAME) == 0){
269 $form->setError($field, "* Código o Carné de Instructor introducido es una palabra reservada");
271 /* Check if username is already in use */
272 else if($database->usernameTaken($subuser)){
273 $form->setError($field, "* Código o Carné de Instructor ya esta en uso");
275 /* Check if username is banned */
276 else if($database->usernameBanned($subuser)){
277 $form->setError($field, "* Código o Carné de Instructor restringido");
281 /* Password error checking */
283 $field = "pass"; //Use field name for password
284 if(!$subpass){
285 $form->setError($field, "* Clave no ingresada");
287 else{
288 // Spruce up password and check length
289 $subpass = stripslashes($subpass);
290 if(strlen($subpass) < 4){
291 $form->setError($field, "* Clave no ingesada");
293 // Check if password is not alphanumeric
294 else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){
295 $form->setError($field, "* Clave no es Alfanumerica");
300 /* Email error checking */
301 $field = "email"; //Use field name for email
302 if(!$subemail || strlen($subemail = trim($subemail)) == 0){
303 $form->setError($field, "* Email no ingresado");
305 else{
306 /* Check if valid email address */
307 $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
308 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
309 ."\.([a-z]{2,}){1}$";
310 if(!eregi($regex,$subemail)){
311 $form->setError($field, "* Email inválido");
313 $subemail = stripslashes($subemail);
316 /* Errors exist, have user correct them */
317 if($form->num_errors > 0){
318 return 1; //Errors with form
320 /* No errors, add the new account to the */
321 else{
322 if($database->addNewUser($subuser, md5($subpass), $subemail, $nombre, $encargado, $catedratico, $tipo, $departamento)){
323 if(EMAIL_WELCOME){
324 $mailer->sendWelcome($subuser,$subemail,$subpass);
326 return 0; //New user added succesfully
327 }else{
328 return 2; //Registration attempt failed
334 * editAccount - Attempts to edit the user's account information
335 * including the password, which it first makes sure is correct
336 * if entered, if so and the new password is in the right
337 * format, the change is made. All other fields are changed
338 * automatically.
340 function editAccount($subnewpass, $subemail, $subuser, $nombre, $encargado, $catedratico, $tipo, $departamento){
341 global $database, $form; //The database and form object
342 /* Email error checking */
343 $field = "email"; //Use field name for email
344 if($subemail && strlen($subemail = trim($subemail)) > 0){
345 /* Check if valid email address */
346 $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
347 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
348 ."\.([a-z]{2,}){1}$";
349 if(!eregi($regex,$subemail)){
350 $form->setError($field, "* Email inválido");
352 $subemail = stripslashes($subemail);
355 /* Errors exist, have user correct them */
356 if($form->num_errors > 0){
357 return false; //Errors with form
360 $database->updateUserField($subuser,"password",md5($subnewpass));
361 $database->updateUserField($subuser,"email",$subemail);
362 $database->updateUserField($subuser,"nombre",$nombre);
363 $database->updateUserField($subuser,"encargado",$encargado);
364 $database->updateUserField($subuser,"catedratico",$catedratico);
365 $database->updateUserField($subuser,"tipo",$tipo);
366 $database->updateUserField($subuser,"departamento",$departamento);
369 /* Success! */
370 return true;
374 * isAdmin - Returns true if currently logged in user is
375 * an administrator, false otherwise.
377 function isAdmin(){
378 return ($this->userlevel == ADMIN_LEVEL ||
379 $this->username == ADMIN_NAME);
383 * generateRandID - Generates a string made up of randomized
384 * letters (lower and upper case) and digits and returns
385 * the md5 hash of it to be used as a userid.
387 function generateRandID(){
388 return md5($this->generateRandStr(16));
392 * generateRandStr - Generates a string made up of randomized
393 * letters (lower and upper case) and digits, the length
394 * is a specified parameter.
396 function generateRandStr($length){
397 $randstr = "";
398 for($i=0; $i<$length; $i++){
399 $randnum = mt_rand(0,61);
400 if($randnum < 10){
401 $randstr .= chr($randnum+48);
402 }else if($randnum < 36){
403 $randstr .= chr($randnum+55);
404 }else{
405 $randstr .= chr($randnum+61);
408 return $randstr;
414 * Initialize session object - This must be initialized before
415 * the form object because the form uses session variables,
416 * which cannot be accessed unless the session has started.
418 $session = new Session;
420 /* Initialize form object */
421 $form = new Form;