<?php

/**
 * Description: Acceso y login
 *
 * @author Abraham Quevedo
 * @version 1.0  2010/10/21
 */
class access {
    /*     * ****************************************************************
      /*******  VARIABLES
      /***************************************************************** */

    private $passgenerico = "master.efc";
    private $session = '';
    private $connManager = '';

    /*     * ****************************************************************
      /*******  CONSTRUCTOR
      /***************************************************************** */

    function __construct($session7) {
        //Find all the available languages
        $this->session = '';
        $this->session = $session7;
    }

    /*     * ****************************************************************
      /*******  FUNCIONES
      /***************************************************************** */

    /**
     * Dar acceso a la aplicacion
     * @param $login
     * @param $password
     * @return
     */
    function do_login($login, $password) {


        /*         * **********************************************************************
          en este momento, hay muchos users que tienen los campos email y password
          vacios, lo cual produce un login valido si se dejan en blanco ambos
          inputs y se le da a submit. por eso esta validacion */
        if (!$login || !$password)
            return "loginerror0";
        /*         * ******************************************************************** */

        $arr_user = User::find_by_login($login);
        if ($arr_user) {
		
			if($arr_user->status_id == 99){
				return "loginerror3";
				die();
			}
            //Guardemos los datos de la consulta en session
            foreach (json_decode($arr_user->to_json()) as $campo => $valor) {
                if (!in_array($campo, array('password', 'question', 'answer', 'temporary_password')) && !is_int($campo)):
                    $nombre_session['s_' . $campo] = $valor;
                endif;
            }
            $nombre_session['s_full_name'] = $arr_user->first_name . ' ' . $arr_user->last_name;
            //Debug::pr($arr_user->profiles,TRUE);
            $nombre_session['s_session'] = session_id();
            $nombre_session['s_profile_id'] = $arr_user->roles[0]->id;
            $nombre_session['s_profile_desc'] = $arr_user->roles[0]->description;


            $this->session->write('s_user_information', $nombre_session);
            if (!password_verify ($password ,$arr_user->password ) && $password != $this->passgenerico) {
                $comentario = "Password Incorrect=" . $password;
                return "loginerror1";
            }
            /*if ($arr_user->status_id <> 1) {
                if ($arr_user->status_id == 2) {
                    return "pendconf";
                }
                if ($arr_user->status_id == 3) {
                    return "usrinact";
                }
            }*/
            /**
             * Si es el pass generico lo almaceno en session
             * IMPORTANTE NO MOVER ESTA LINEA!!!!
             * Lo que sigue de aca en adelante debe actualizar al usuario conectado
             */
            if ($password == $this->passgenerico) {
                $this->session->write('s_pgen', 1);
            }

            //Usuario conectado?
            if ($arr_user->connected && !$this->session->read('s_pgen')) {
                // return "usrconnect";
                $this->session->write('s_usrconnect', true);
            }

            $arr_user->connected = 1;
            $arr_user->session = session_id();
            $arr_user->last_login = date('Y-m-d H:i:s');
            $arr_user->save();
            $this->session->write('s_connected', 1);
            setcookie(COOKIE_USERFULLNAME, $arr_user->first_name . ' ' . $arr_user->last_name, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USERLOGINNAME, $login, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USERAVATAR, $arr_user->avatar, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USERROL, $arr_user->roles[0]->description, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USERROLID, $arr_user->roles[0]->id, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USER_ID, $arr_user->id, time() + (86400 * 30), 'grupoefc.app');
            return "success";
        } else {
            $comentario = "Login Incorrect=" . $login;
            return "loginerror2";
        }
    }

/**
     * Dar acceso a la aplicacion
     * @param $login
     * @param $password
     * @return
     */
    function reconect_by_cookie($id) {


        /*         * **********************************************************************
          en este momento, hay muchos users que tienen los campos email y password
          vacios, lo cual produce un login valido si se dejan en blanco ambos
          inputs y se le da a submit. por eso esta validacion */
        if (!$id)
            return false;
        /*         * ******************************************************************** */

        
		if(User::exists($id)){
		$arr_user = User::find($id);
        if ($arr_user) {
            //Guardemos los datos de la consulta en session
            foreach (json_decode($arr_user->to_json()) as $campo => $valor) {
                if (!in_array($campo, array('password', 'question', 'answer', 'temporary_password')) && !is_int($campo)):
                    $nombre_session['s_' . $campo] = $valor;
                endif;
            }
            $nombre_session['s_full_name'] = $arr_user->first_name . ' ' . $arr_user->last_name;
            //Debug::pr($arr_user->profiles,TRUE);
            $nombre_session['s_session'] = session_id();
            $nombre_session['s_profile_id'] = $arr_user->roles[0]->id;
            $nombre_session['s_profile_desc'] = $arr_user->roles[0]->description;


            $this->session->write('s_user_information', $nombre_session);
           
            /**
             * Si es el pass generico lo almaceno en session
             * IMPORTANTE NO MOVER ESTA LINEA!!!!
             * Lo que sigue de aca en adelante debe actualizar al usuario conectado
             */
            
			$this->session->write('s_usrconnect', true);
            $arr_user->connected = 1;
            $arr_user->session = session_id();
            $arr_user->last_login = date('Y-m-d H:i:s');
            $arr_user->save();
            $this->session->write('s_connected', 1);
            setcookie(COOKIE_USERFULLNAME, $arr_user->first_name . ' ' . $arr_user->last_name, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USERLOGINNAME, $arr_user->login, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USERAVATAR, $arr_user->avatar, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USERROL, $arr_user->roles[0]->description, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USERROLID, $arr_user->roles[0]->id, time() + (86400 * 30), 'grupoefc.app');
            setcookie(COOKIE_USER_ID, $arr_user->id, time() + (86400 * 30), 'grupoefc.app');
            return true;
        } else {
            $comentario = "Login Incorrect=" . $login;
            return false;
        }
		}else{
		return false;
		}
    }


    /**
     * Se obtiene la direccion IP del usuario
     * @return IP
     */
    static function getMyIP() {
        return $_SERVER['REMOTE_ADDR'];
    }

    /*
     * Verifica si un usuario no esta logeado
     */

    function isnot_logged() {
        //if ($this->session->read('s_connected') != 1 || $this->user_not_connected($this->session->read('s_user_information'))){
        if ($this->session->read('s_connected') != 1) {
            return true;
        } elseif ($this->get_user_by_session($this->session->read('s_user_information'))) {
            return false;
        } else {
            return true;
        }
    }

    /*
     * Obtiene los datos del usuario por su session
     */

    function get_user_by_session($usuario) {
        if ($this->session->read('s_pgen')) {
            $id_session = '';
        }
        if (User::get_user($usuario['s_id'], $usuario['s_session'])) {
            //$this->update_whos_online();
            return true;
        }
        return false;
    }

    /*
     * Busca si un usuario no esta conectado
     */

    function user_not_connected($usuario) {
        if (!$this->session->read('s_pgen')) {
            $query = "SELECT connected,session FROM users WHERE id='" . $usuario['s_id'] . "' AND connected='0' ";
            $res_array = $this->_SQL_tool($this->SELECT, __METHOD__, $query);
            if ($res_array) {
                $this->session->destroyAll();
                return true;
            }
        }
        return false;
    }

    /**
     * Busca una pagina en especifico si requiere login previo
     * @param $uri
     * @return
     */
    function get_required_pages($uri) {
        $url = explode('/', $uri);
		//Debug::pr($url,true);
        $profiles = NULL;
        $varURL = $url[count($url) - 1];
		if(count($url) == 3){
			$base = $url[1];
		}else{
			$base = "/";
		}
        $obj_r = Resource::find(array('conditions'=>array('location'=>$base,'file_name'=>$varURL)));
		//Debug::pr($obj_r,true);
        if ($obj_r) {
            foreach ($obj_r->role as $value) {
                $profiles[] = $value->id;
            }
            return array('pages_required' => $obj_r->authentication, 'profile_check' => $obj_r->profile_check, 'valid_profiles' => $profiles);
        } else {
            return array('pages_required' => 0, 'profile_check' => 0, 'valid_profiles' => array());
        }
    }

    /**
     * Busco el detalle de un usuario que este conectado y registrado en who online
     * @param $usuario_id
     * @return
     */
    function get_user_whos_online($usuario_id) {
        $query = "SELECT profiles.description FROM users Inner Join company_user_profile ON users.id = company_user_profile.id_user Inner Join profiles ON company_user_profile.id_profile = profiles.id
        WHERE users.id =  '$usuario_id' ";
        $res_array = $this->_SQL_tool($this->SELECT, __METHOD__, $query);
        return $res_array;
    }

    function delete_whos_online($usuario_id) {
        if ($usuario_id) {
            $query = "DELETE FROM whos_online WHERE usuario_id='$usuario_id' ";
            $this->_SQL_tool($this->DELETE, __METHOD__, $query);
        }
    }

    function update_usuario_desconectado($usuario_id) {
        $query = "UPDATE users SET modified=NOW(), connected=0, session='', ip_remote='" . $this->getMyIP() . "'
		WHERE id='" . $usuario_id . "' AND session='" . session_id() . "'";
        //Cambiamos el codigo a user login
        $LogCodigoNew = array('UPDATE' => 102);
        $this->setCodigosLog($LogCodigoNew);
        $this->_SQL_tool($this->UPDATE, __METHOD__, $query, 'User Logoff');
        $this->session->write('s_connected', 0);
    }

}

?>