123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426 |
- <?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,$permissionRight = null){
- if($this->superadmin == 1) return true;
- global $myFirm;
- $firm = is_object($myFirm) && $myFirm->id !=0 ? $myFirm->id : 0;
- if(isset($permissionRight)){
- if(!isset($this->rights['permission'][$section]) || !isset($this->rights['permission'][$section][$right])) return false;
- if(isset($this->rights['permission'][$section][$right][$permissionRight]) && $this->rights['permission'][$section][$right][$permissionRight] ) return true;
- return false;
-
- }
- 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::check_access('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;
- $permissions = Permission::staticQuery('SELECT * FROM {{table}} WHERE (targetEntity="user" AND targetUid=?) OR (targetEntity="rank" AND targetUid IN('.implode(',',$ranksId).'))',array($this->login),true);
- $this->rights['permission'] = array();
- foreach ($permissions as $permission) {
- if(!isset($this->rights['permission'][$permission->entity])) $this->rights['permission'][$permission->entity] = array();
-
- if(!isset($this->rights['permission'][$permission->entity][$permission->uid])){
- $this->rights['permission'][$permission->entity][$permission->uid] = array(
- 'read' => false,
- 'edit' => false,
- 'delete' => false,
- 'recursive' => false,
- 'configure' => false
- );
- }
- if($permission->read) $this->rights['permission'][$permission->entity][$permission->uid]['read'] = true;
- if($permission->edit) $this->rights['permission'][$permission->entity][$permission->uid]['edit'] = true;
- if($permission->delete) $this->rights['permission'][$permission->entity][$permission->uid]['delete'] = true;
- if($permission->recursive) $this->rights['permission'][$permission->entity][$permission->uid]['recursive'] = true;
- if($permission->configure) $this->rights['permission'][$permission->entity][$permission->uid]['configure'] = true;
- }
- }
- 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';
- if(!$this->check_avatar_path_length()) return $avatar;
- $files = glob(__ROOT__.FILE_PATH.AVATAR_PATH.self::format_avatar_name($this->login).self::get_avatar_extension_brace(),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='.urlencode($this->login).'&extension='.$extension[1];
- }
- return $avatar;
- }
- public function check_avatar_path_length(){
- return strlen($this->login) <= OS_path_max_length() - strlen(__ROOT__.FILE_PATH.AVATAR_PATH) - strlen(User::get_avatar_extension_brace());
- }
- public static function format_avatar_name($text){
- return iconv('utf-8','windows-1256//IGNORE', $text);
- }
- public static function get_avatar_extension_brace(){
- return ".{jpg,png,jpeg,gif}";
- }
- 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,htmlspecialchars_decode($login),htmlspecialchars_decode($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, $force=false){
- foreach(User::getAll($loadRight, $force) as $user){
- if($user->login != $login) continue;
- return $user;
- }
- return new User();
- }
- public function lastname(){
- return mb_strtoupper(htmlspecialchars_decode(mb_strtolower($this->name)));
- }
- public function firstname(){
- return htmlspecialchars_decode($this->firstname);
- }
- public function fullName(){
- $fullName = ucfirst($this->firstname()).' '.$this->lastname();
- 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;
- }
- public function getRanksId(){
- global $myFirm;
- return array_keys($this->ranks[$myFirm->id]);
- }
- //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();
- }
- }
|