<?php

/**
 * Define an application user.
 * @author valentin carruesco
 * @category Core
 * @license copyright
 */
class User extends Entity
{
    public $id,$login,$password,$function,$name,$firstname,$mail,
    $state,$rights,$firms,$superadmin,$token,
    $preferences,$phone,$mobile,
    $groups,$ranks,$manager,$service,$origin,$meta;

    protected $fields =
    array(
        'id' => 'key',
        'login' => 'string',
        'password' => 'string',
        'name' => 'string',
        'function' => 'string',
        'firstname' => 'string',
        'token' => 'string',
        'mail' => 'string',
        'state' => 'string',
        'phone' => 'string',
        'mobile' => 'string',
        'manager' => 'string',
        'origin' => 'string',
        'service' => 'string',
        'superadmin' => 'int'
    );

    function  __construct(){
        parent::__construct();
        $this->token = self::generateToken();
        $this->meta = array();
    }

    public static function getAll($loadRight=true, $force=false){
        $users = array();
        if(isset($_SESSION['users']))
            $users = unserialize($_SESSION['users']);

        if(empty($users) || $force){
            Plugin::callHook('user_load',array(&$users, $loadRight));
            uasort($users, function($a, $b){ return strcmp($a->name, $b->name); });

            foreach (self::loadAll(array('state'=>User::ACTIVE), array(' name ASC ')) as $baseUser) {
                $existingKey = null;

                if($loadRight){
                    if(!isset($baseUser->ranks)) $baseUser->ranks = array();
                    if(!isset($baseUser->firms)) $baseUser->firms = array();
                    $baseUser->loadRanks();
                    $baseUser->loadRights();
                }
                if(isset($baseUser->manager) && $baseUser->manager!="") $baseUser->manager = User::load(array('login'=>$baseUser->manager));

                foreach ($users as $key => $otherUser) {
                    //permet la predominance des users db sur les user foreign type type
                    if($otherUser->login == $baseUser->login){
                        $existingKey = $key;
                        break;
                    }
                }
                if(isset($existingKey)){
                    $users[$existingKey] = $baseUser;
                }else{
                    $users[] = $baseUser;
                } 
            }
            $_SESSION['users'] = serialize($users);
        }

        return $users;
    }
    
    public function __sleep(){
        return array_merge(array('rights','ranks','firms','preferences','meta'),array_keys($this->toArray()));
    }

    public function can($section,$right){
        if($this->superadmin == 1) return true;
        global $myFirm;
        $firm = is_object($myFirm) && $myFirm->id !=0 ? $myFirm->id : 0;

        if(isset($this->rights[$section][$firm][$right])){
            return $this->rights[$section][$firm][$right]==1;
        }
        if(isset($this->rights[$section][0][$right])){
            return $this->rights[$section][0][$right]==1;
        }
        return false;
    }

    //Lance les exception appropriées en fonction du droit ou des droits spécifiés
    // ex : User::checkAccess('document','configure');
    public static function check_access($section,$right){
        global $myUser;
        if(!isset($myUser) || !is_object($myUser) || !$myUser->connected()) throw new Exception("Contrôle d'accès - Vous devez être connecté",401);
        if(!$myUser->can($section,$right)) throw new Exception("Contrôle d'accès - Permissions insuffisantes",403);
    }

    public function hasRank($rankId){
        if($this->superadmin) return true;
        $rankIds = array();
        global $myFirm;
        if(empty($this->ranks) || !isset($this->ranks[$myFirm->id])) return false;
        foreach ($this->ranks[$myFirm->id] as $rank)
            $rankIds[$rank->id] = true;
        return isset($rankIds[$rankId]);
    }

    public function preference($key=null, $value=null){   
        if(!isset($key) && !isset($value)) return $this->preferences;
        if(isset($key) && !isset($value)) return isset($this->preferences[$key])?$this->preferences[$key]:'';

        if(isset($key) && isset($value)){
            $this->preferences[$key] = $value;
            $preference = UserPreference::load(array('key'=>$key,'user'=>$this->login));
            if(!$preference) $preference = new UserPreference();
            $preference->key = $key;
            $preference->value = $value;
            $preference->user = $this->login;
            $preference->save();
        }
    }

    public function loadRanks(){
        foreach (UserFirmRank::loadAll(array('user'=>$this->login), null,  null,  array('*'),1) as $firmRank) {
            $rank = $firmRank->join('rank');
            $firm = $firmRank->join('firm');
            $this->firms[$firm->id] = $firm;
            if(!isset($this->ranks[$firmRank->firm])) $this->ranks[$firmRank->firm] = array();
            $this->ranks[$firmRank->firm][$rank->id]= $rank;
        }
    }

    public function loadPreferences(){
        $this->preferences = array();
        foreach(UserPreference::loadAll(array('user'=>$this->login)) as $line):
            $this->preferences[$line->key] = $line->value;
        endforeach;
    }

    
    public function loadRights(){
        global $myFirm;
        $this->rights = array();
        if($this->superadmin) return;
        
        if(!isset($this->ranks)) $this->ranks = array();
        if(!isset($myFirm) || !isset($this->ranks[$myFirm->id]) || count($this->ranks[$myFirm->id])==0) return;

        $ranksId = array();
        foreach($this->ranks[$myFirm->id] as $rank){
            if(!isset($rank->id) || !is_numeric($rank->id)) continue;
            $ranksId[] = $rank->id;
        }
        if(count($ranksId)==0) return;

        $rights = Right::staticQuery('SELECT * FROM {{table}} WHERE rank IN('.implode(',',$ranksId).')',array(),true);
        foreach($rights as $right):
            //Pour le premier rang qui aborde cette section on met tous les droits à false
            if(!isset($this->rights[$right->section][$right->firm])){
                $this->rights[$right->section][$right->firm] = array(
                    'read' => false,
                    'edit' => false,
                    'delete' => false,
                    'configure' => false
                );
            }
            //Puis on complete uniquement les droits à true sur la section pour chaques rangs additionnels
            if($right->read) $this->rights[$right->section][$right->firm]['read'] = true;
            if($right->edit) $this->rights[$right->section][$right->firm]['edit'] = true;
            if($right->delete) $this->rights[$right->section][$right->firm]['delete'] = true;
            if($right->configure) $this->rights[$right->section][$right->firm]['configure'] = true;
        endforeach;
    }
    
    public function getFirms(){
        $this->firms = array();
        foreach(Firm::staticQuery('SELECT f.* FROM {{table}} f LEFT JOIN '.UserFirmRank::tableName().' uf ON uf.firm=f.id WHERE uf.user=?',array($this->login),true) as $firm):

            $this->firms[$firm->id] = $firm;
        endforeach;
    }

    public function haveFirm($id){
        return in_array($id, array_keys($this->firms));
    }

    public function getAvatar($getPath = false){
        $avatar = 'img/default-avatar.png';
        $files = glob(__ROOT__.FILE_PATH.AVATAR_PATH.$this->login.'.{jpg,png,jpeg,gif}',GLOB_BRACE);
        if(count($files)>0){
            if($getPath) return $files[0];
            preg_match("/\.(\w{3,4})$|\?/m", $files[0], $extension);
            $avatar = 'action.php?action=account_avatar_download&user='.$this->login.'&extension='.$extension[1];
        }
        return $avatar;
    }

    public static function check($login, $password, $loadRight = true) {   
        global $myFirm;
        $user = self::load(array('login' => $login, 'password' => self::password_encrypt($password)));
        
        //load from plugins
        Plugin::callHook("user_login", array(&$user,$login,$password,$loadRight));

        //load from db
        if($user!=false){
            $user->ranks = empty($user->ranks) ? array() : $user->ranks;
            $user->firms = empty($user->firms) ? array() : $user->firms;
            if(isset($user->manager) && !empty($user->manager) && !is_object($user->manager)) $user->manager = self::byLogin($user->manager);
            $user->loadRanks();
            $user->loadPreferences();

            if($user->superadmin == 1){
                foreach(Firm::loadAll() as $firm)
                    $firms[$firm->id] = $firm;
                $user->setFirms($firms);
            }

            if(!empty($user->firms)){
                $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : key($user->firms);
                $myFirm = isset($user->firms[$defaultFirm]) ? $user->firms[$defaultFirm]:reset($user->firms);
                if(!isset($user->firms[$defaultFirm])) $user->preference('default_firm',$myFirm->id);
            }
            if($loadRight) $user->loadRights();
        }

        $user = is_object($user) ? $user : new self();
        return $user;
    }

    public static function byLogin($login,$loadRight=true){
        foreach(User::getAll($loadRight) as $user)
            if($user->login == $login) return $user;
        return new User();
    }

    public function fullName()
    {
        $fullName = ucfirst($this->firstname).' '.mb_strtoupper($this->name);
        return trim($fullName) != '' ? $fullName : $this->login;
    }

    public function initials(){
        $firstname = str_replace(array(' ','\''),'-',$this->firstname);
        $firstname = explode('-',$firstname);
        $result = '';
        foreach($firstname as $pren){
            $result.= strtoupper(substr($pren,0,1));
        }
        return $result.strtoupper(substr($this->name,0,1));

    }

     public function subordinates(){
        $subordinates = array();
        foreach (User::getAll() as $user) {
            if(is_object($user->manager) && $user->manager->login == $this->login) $subordinates[] = $user;
        }
        return $subordinates;
    }

    public static function password_formats(){
        $formats = array(
            array('pattern'=>'|[0-9]|i','label'=>'Le mot de passe doit comporter au minimum 1 chiffre (norme ANSSI)'),
            array('pattern'=>'|[A-Z]|','label'=>'Le mot de passe doit comporter au minimum 1 majuscule (norme ANSSI)'),
            array('pattern'=>'|[^A-Za-z0-9éèêëàäâïîöôûüù]|i','label'=>'Le mot de passe doit comporter au minimum 1 caractère spécial (norme ANSSI)'),
            array('pattern'=>'|.{6,}|','label'=>'Le mot de passe doit comporter au minimum 6 caractères'),
            array('pattern'=>'|.{12,}|','label'=>'Le mot de passe doit comporter au minimum 12 caractères (norme ANSSI)'),
        );
        return $formats;
    }

    public static function check_password_format($password){
        global $conf;
        $errors = array();
        $formats = array();
        foreach (self::password_formats() as $format) {
            $formats[$format['pattern']] = $format;
        } 
        $selectedFormats = json_decode($conf->get('password_format'),true);

        if(is_array($selectedFormats)){
            foreach($selectedFormats as $pattern){
                if(!isset($formats[$pattern])) continue;
                $format = $formats[$pattern];
                if(!preg_match($pattern, $password)) $errors[] = $format['label'];
            }
        }
        return $errors;
    }



    public static function password_encrypt($password){
        return sha1(md5($password));
    }

    public function connected(){
        return !empty($this->login);
    }

    public function setLogin($login){
        $this->login = $login;
    }

    public function setName($name){
        $this->name = $name;
    }

    public function setFirstName($firstname){
        $this->firstname = $firstname;
    }

    public function setMail($mail){
        $this->mail = $mail;
    }

    public function setPhone($phone){
        $this->phone = $phone;
    }

    public function setMobile($mobile){
        $this->mobile = $mobile;
    }

    public function setFunction($function){
        $this->function = $function;
    }

    public function setGroups($groups){
        $this->groups = $groups;
    }

    public static function generateToken(){
        return substr(md5(uniqid(rand(), true)),0,10);
    }

    public function getGroups(){
        return (is_array($this->groups) ? $this->groups : array());
    }

    public function setFirms($firms){
        if(empty($firms)) return;
        $this->firms = $firms;
    }

        //Retourne un objet manager (User vide si pas de manager) quel que soit le provider d'entré (ad : objet, db: login)
    public function manager(){
        $manager = new User();
        if(!isset($this->manager)) return $manager;
        if(is_object($this->manager)) $manager = $this->manager;
        if(is_string($this->manager) && !empty($this->manager)) $manager = User::byLogin($this->manager);
       
        return is_object($manager) ? $manager: new User();
    }
}
