ID's para los comboboxes
[ecomupi.git] / include / sesion.php
blobbaa8ea6b15667a5d7e5f660b7cf65606ed779b8b
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 $codigo; //codigo 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
17 /* Class constructor */
18 function Session(){
19 $this->time = time();
20 $this->startSession();
23 /**
24 * startSession - Performs all the actions necessary to
25 * initialize this session object. Tries to determine if the
26 * the user has logged in already, and sets the variables
27 * accordingly. Also takes advantage of this page load to
28 * update the active visitors tables.
30 function startSession(){
31 global $database; //The database connection
32 session_start(); //Tell PHP to start the session
33 /* Determine if user is logged in */
34 $this->logged_in = $this->checkLogin();
36 /**
37 * Set guest value to users not logged in, and update
38 * active guests table accordingly.
40 if(!$this->logged_in){
41 $this->codigo = $_SESSION['codigo'] = GUEST_NAME;
42 $this->userlevel = GUEST_LEVEL;
43 $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
45 /* Update users last active timestamp */
46 else{
47 $database->addActiveUser($this->codigo, $this->time);
50 /* Remove inactive visitors from database */
51 $database->removeInactiveUsers();
52 $database->removeInactiveGuests();
55 /**
56 * checkLogin - Checks if the user has already previously
57 * logged in, and a session with the user has already been
58 * established. Also checks to see if user has been remembered.
59 * If so, the database is queried to make sure of the user's
60 * authenticity. Returns true if the user has logged in.
62 function checkLogin(){
63 global $database; //The database connection
64 /* Check if user has been remembered */
65 if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
66 $this->codigo = $_SESSION['codigo'] = $_COOKIE['cookname'];
67 $this->userid = $_SESSION['userid'] = $_COOKIE['cookid'];
68 DEPURAR ("Check Login: " . $this->codigo);
71 DEPURAR ("Check Login GUEST_NAME: " . GUEST_NAME);
72 /* codigo and userid have been set and not guest */
73 if(isset($_SESSION['codigo']) && isset($_SESSION['userid']) &&
74 $_SESSION['codigo'] != GUEST_NAME){
75 DEPURAR ("Check Login: codigo and userid have been set and not guest");
76 /* Confirm that codigo and userid are valid */
77 if($database->confirmUserID($_SESSION['codigo'], $_SESSION['userid']) != 0){
78 DEPURAR("Check Login: Variables are incorrect, user not logged in");
79 /* Variables are incorrect, user not logged in */
80 unset($_SESSION['codigo']);
81 unset($_SESSION['userid']);
82 return false;
84 DEPURAR ("Check Login SESSION[codigo]: " . $_SESSION['codigo']);
85 /* User is logged in, set class variables */
86 $this->userinfo = $database->getUserInfo($_SESSION['codigo']);
87 $this->codigo = $this->userinfo['codigo'];
88 $this->userid = $this->userinfo['userid'];
89 $this->userlevel = $this->userinfo['userlevel'];
90 DEPURAR ("Check Login IN!");
91 return true;
93 /* User not logged in */
94 else{
95 DEPURAR("Check Login NOT IN!");
96 return false;
101 * login - The user has submitted his codigo and clave
102 * through the login form, this function checks the authenticity
103 * of that information in the database and creates the session.
104 * Effectively logging in the user if all goes well.
106 function login($subuser, $subpass, $subremember){
107 global $database, $form; //The database and form object
108 DEPURAR ("Login:".$subuser);
109 /* codigo error checking */
110 $field = "codigo"; //Use field name for codigo
111 if(!$subuser || strlen($subuser = trim($subuser)) == 0){
112 $form->setError($field, "* No se ingreso Código o Carné del Instructor");
114 else{
115 /* Check if codigo is not alphanumeric */
116 if(!eregi("^([0-9a-z])*$", $subuser)){
117 $form->setError($field, "* codigo not alphanumeric");
121 /* clave error checking */
122 $field = "clave"; //Use field name for clave
123 if(!$subpass){
124 $form->setError($field, "* Olvidó ingresar la clave");
127 /* Return if form errors exist */
128 if($form->num_errors > 0){
129 return false;
131 DEPURAR ("Login: Checks 1 passed");
132 /* Checks that codigo is in database and clave is correct */
133 $subuser = stripslashes($subuser);
134 $result = $database->confirmUserPass($subuser, md5($subpass));
136 /* Check error codes */
137 if($result == 1){
138 $field = "codigo";
139 $form->setError($field, "* Código o Carné de Instructor no encontrado");
140 DEPURAR ("Login: Not user");
142 else if($result == 2){
143 $field = "clave";
144 $form->setError($field, "* Clave inválida");
145 DEPURAR ("Login: Not clave");
148 /* Return if form errors exist */
149 if($form->num_errors > 0){
150 return false;
152 DEPURAR ("Login: Checks 2 passed");
153 /* codigo and clave correct, register session variables */
154 $this->userinfo = $database->getUserInfo($subuser);
155 $this->codigo = $_SESSION['codigo'] = $this->userinfo['codigo'];
156 $this->userid = $_SESSION['userid'] = $this->generateRandID();
157 $this->userlevel = $this->userinfo['userlevel'];
159 /* Insert userid into database and update active users table */
160 $database->updateUserField($this->codigo, "userid", $this->userid);
161 $database->addActiveUser($this->codigo, $this->time);
162 $database->removeActiveGuest($_SERVER['REMOTE_ADDR']);
165 * This is the cool part: the user has requested that we remember that
166 * he's logged in, so we set two cookies. One to hold his codigo,
167 * and one to hold his random value userid. It expires by the time
168 * specified in constants.php. Now, next time he comes to our site, we will
169 * log him in automatically, but only if he didn't log out before he left.
171 if($subremember){
172 setcookie("cookname", $this->codigo, time()+COOKIE_EXPIRE, COOKIE_PATH);
173 setcookie("cookid", $this->userid, time()+COOKIE_EXPIRE, COOKIE_PATH);
175 DEPURAR ("Login: IN");
176 /* Login completed successfully */
177 return true;
181 * logout - Gets called when the user wants to be logged out of the
182 * website. It deletes any cookies that were stored on the users
183 * computer as a result of him wanting to be remembered, and also
184 * unsets session variables and demotes his user level to guest.
186 function logout(){
187 global $database; //The database connection
189 * Delete cookies - the time must be in the past,
190 * so just negate what you added when creating the
191 * cookie.
193 if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
194 setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
195 setcookie("cookid", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
198 /* Unset PHP session variables */
199 unset($_SESSION['codigo']);
200 unset($_SESSION['userid']);
202 /* Reflect fact that user has logged out */
203 $this->logged_in = false;
206 * Remove from active users table and add to
207 * active guests tables.
209 $database->removeActiveUser($this->codigo);
210 $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
212 /* Set user level to guest */
213 $this->codigo = GUEST_NAME;
214 $this->userlevel = GUEST_LEVEL;
218 * register - Gets called when the user has just submitted the
219 * registration form. Determines if there were any errors with
220 * the entry fields, if so, it records the errors and returns
221 * 1. If no errors were found, it registers the new user and
222 * returns 0. Returns 2 if registration failed.
224 function register($codigo, $clave, $nombre, $razon, $email, $telefono1, $telefono2, $telefono3, $logotipo, $notas){
225 global $database, $form, $mailer; //The database, form and mailer object
226 $codigo = trim($codigo);
227 $form->setValue("codigo", $codigo);
228 $form->setValue("clave", $clave);
229 $form->setValue("nombre", $nombre);
230 $form->setValue("razon", $razon);
231 $form->setValue("email", $email);
232 $form->setValue("telefono1", $telefono1);
233 $form->setValue("telefono2", $telefono2);
234 $form->setValue("telefono3", $telefono3);
235 $form->setValue("notas", $notas);
237 //print_r (array($codigo, $clave, $nombre, $razon, $email, $telefono1, $telefono2, $telefono3, $logotipo, $notas));
238 /* codigo error checking */
239 $field = "codigo";
240 if(!$codigo){
241 $form->setError($field, "* Nombre de usuario no ingresado");
243 else{
244 /* Spruce up codigo, check length */
245 $codigo = stripslashes($codigo);
246 if(strlen($codigo) < 5){
247 $form->setError($field, "* Código fiscal o nombre de usuario debe ser mayor a 5 caracteres");
249 else if(strlen($codigo) > 100){
250 $form->setError($field, "* Código fiscal o nombre de usuario debe ser menor de 100 caracteres");
252 /* Check if codigo is not alphanumeric */
253 else if(!eregi("^([0-9a-z])+$", $codigo)){
254 $form->setError($field, "* Código fiscal o nombre de usuario debe ser Alfanumerico");
256 /* Check if codigo is reserved */
257 else if(strcasecmp($codigo, GUEST_NAME) == 0){
258 $form->setError($field, "* Código fiscal o nombre de usuario introducido es una palabra reservada");
260 /* Check if codigo is already in use */
261 else if($database->codigoTaken($codigo)){
262 $form->setError($field, "* Código fiscal o nombre de usuario ya esta en uso");
266 $field = "clave";
267 if(!$clave){
268 $form->setError($field, "* Clave no ingresada");
270 else{
271 // Spruce up clave and check length
272 $clave = stripslashes($clave);
273 if(strlen($clave) < 4){
274 $form->setError($field, "* Clave debe ser mayor a 4 caracteres");
276 // Check if clave is not alphanumeric
277 else if(!eregi("^([0-9a-z])+$", ($clave = trim($clave)))){
278 $form->setError($field, "* Clave no es Alfanumerica");
283 /* Email error checking */
284 $field = "email"; //Use field name for email
286 if(!$email){
287 $form->setError($field, "* Email no ingresado");
290 else{
292 /* Check if valid email address */
293 $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
294 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
295 ."\.([a-z]{2,}){1}$";
296 if(!eregi($regex,$email)){
297 $form->setError($field, "* Email inválido");
299 $email = stripslashes($email);
302 /* Errors exist, have user correct them */
303 if($form->num_errors > 0){
304 return 1; //Errors with form
305 } else {
306 $idImg = CargarImagenEnBD("logotipo","LOGOTIPOS");
307 if($database->addNewUser($codigo, md5($clave), $nombre, $razon, $email, $telefono1, $telefono2, $telefono3, $idImg, $notas)){
308 if(EMAIL_WELCOME){
309 $mailer->sendWelcome($codigo,$email,$clave);
311 return 0; //New user added succesfully
312 }else{
313 return 2; //Registration attempt failed
319 * editAccount - Attempts to edit the user's account information
320 * including the clave, which it first makes sure is correct
321 * if entered, if so and the new clave is in the right
322 * format, the change is made. All other fields are changed
323 * automatically.
325 function editAccount($subnewpass, $codigo, $nombre, $razon, $email, $telefono1, $telefono2, $telefono3, $logotipo, $notas){
326 global $database, $form; //The database and form object
327 $form->setValue("clave", $clave);
328 $form->setValue("nombre", $nombre);
329 $form->setValue("razon", $razon);
330 $form->setValue("email", $email);
331 $form->setValue("telefono1", $telefono1);
332 $form->setValue("telefono2", $telefono2);
333 $form->setValue("telefono3", $telefono3);
334 $form->setValue("notas", $notas);
335 /* Email error checking */
336 $field = "email"; //Use field name for email
337 if($email && strlen($email = trim($email)) > 0){
338 /* Check if valid email address */
339 $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
340 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
341 ."\.([a-z]{2,}){1}$";
342 if(!eregi($regex,$email)){
343 $form->setError($field, "* Email inválido");
345 $email = stripslashes($email);
348 /* Errors exist, have user correct them */
349 if($form->num_errors > 0){
350 return false; //Errors with form
352 if ( !$_FILES['logotipo']['error'] ) {
353 $Pre_Id = isset($_POST['ConservarLogotipo2']) ? $_POST['ConservarLogotipo2'] : 0;
354 $idImg = CargarImagenEnBD("logotipo","LOGOTIPOS", $Pre_Id);
355 } else {
356 if ( isset ($_POST['ConservarLogotipo']) ){
357 $idImg = $_POST['ConservarLogotipo2'];
358 } else {
359 $idImg = 0;
362 $database->updateUserField($codigo,"clave",md5($subnewpass));
363 $database->updateUserField($codigo,"nombre",$nombre);
364 $database->updateUserField($codigo,"razon",$razon);
365 $database->updateUserField($codigo,"email",$email);
366 $database->updateUserField($codigo,"telefono1",$telefono1);
367 $database->updateUserField($codigo,"telefono2",$telefono2);
368 $database->updateUserField($codigo,"telefono3",$telefono3);
369 $database->updateUserField($codigo,"logotipo",$idImg);
370 $database->updateUserField($codigo,"notas",$notas);
373 /* Success! */
374 return true;
378 * isAdmin - Returns true if currently logged in user is
379 * an administrator, false otherwise.
381 function isAdmin(){
382 return ($this->userlevel == ADMIN_LEVEL ||
383 $this->codigo == ADMIN_NAME);
387 * generateRandID - Generates a string made up of randomized
388 * letters (lower and upper case) and digits and returns
389 * the md5 hash of it to be used as a userid.
391 function generateRandID(){
392 return md5($this->generateRandStr(16));
396 * generateRandStr - Generates a string made up of randomized
397 * letters (lower and upper case) and digits, the length
398 * is a specified parameter.
400 function generateRandStr($length){
401 $randstr = "";
402 for($i=0; $i<$length; $i++){
403 $randnum = mt_rand(0,61);
404 if($randnum < 10){
405 $randstr .= chr($randnum+48);
406 }else if($randnum < 36){
407 $randstr .= chr($randnum+55);
408 }else{
409 $randstr .= chr($randnum+61);
412 return $randstr;
418 * Initialize session object - This must be initialized before
419 * the form object because the form uses session variables,
420 * which cannot be accessed unless the session has started.
422 $session = new Session;
423 /* Initialize form object */
424 $form = new Form;