User.class.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. <?php
  2. /**
  3. * Define an application user.
  4. * @author valentin carruesco
  5. * @category Core
  6. * @license MIT
  7. */
  8. class User extends Entity {
  9. public $id,$login,$password,$function,$name,$firstname,$mail,$state,$rights,$firms,$superadmin,$token,$preferences,$phone,$mobile,$groups,$ranks,$manager,$service,$origin,$meta;
  10. public $entityLabel = 'Utilisateur';
  11. public $fields = array(
  12. 'id' => 'key',
  13. 'login' => array('label'=>'Identifiant','type'=>'string'),
  14. 'password' => array('label'=>'Mot de passe','type'=>'password'),
  15. 'name' => array('label'=>'Nom','type'=>'string'),
  16. 'function' => array('label'=>'Fonction','type'=>'string'),
  17. 'firstname' => array('label'=>'Prénom','type'=>'text'),
  18. 'token' => array('label'=>'Token','type'=>'string'),
  19. 'mail' => array('label'=>'E-mail','type'=>'mail'),
  20. 'state' => array('label'=>'Etat','type'=>'string'),
  21. 'phone' => array('label'=>'Téléphone','type'=>'phone'),
  22. 'mobile' => array('label'=>'Téléphone portable','type'=>'phone'),
  23. 'manager' => array('label'=>'Manager','type'=>'user'),
  24. 'origin' => array('label'=>'Origine','type'=>'text'),
  25. 'service' => array('label'=>'Service','type'=>'text'),
  26. 'meta' => array('label'=>'Meta informations','type'=>'text')
  27. );
  28. function __construct(){
  29. global $myUser, $myFirm, $conf;
  30. parent::__construct();
  31. $this->token = self::generateToken();
  32. $this->meta = array();
  33. $this->ranks = array();
  34. $this->firms = array();
  35. }
  36. public static function getAll($options = array()){
  37. $users = array();
  38. $options = array_merge(array(
  39. 'right' => true,
  40. 'manager' => true,
  41. 'force' =>false
  42. ),$options);
  43. if(isset($_SESSION['users_'.($options['right']?'rights':'norights')]))
  44. $users = unserialize($_SESSION['users_'.($options['right']?'rights':'norights')]);
  45. if(empty($users) || $options['force']){
  46. $users = array();
  47. //récuperation des users non db (plugin ad ...)
  48. Plugin::callHook('user_get_all',array(&$users,$options));
  49. $logins = array();
  50. //Récuperation des users db
  51. foreach (self::loadAll(array('state'=>User::ACTIVE), array(' name ASC ')) as $baseUser)
  52. $users[$baseUser->login] = $baseUser;
  53. //récuperation des logins concernés pour requettage
  54. foreach($users as $key=>$user){
  55. //chargement des managers pour les origines db
  56. if($options['manager'] && empty($user->origin) && !empty($user->manager) && isset($users[$user->manager])){
  57. $users[$key]->manager = $users[$user->manager];
  58. }
  59. $logins[] = $user->login;
  60. }
  61. if($options['right']){
  62. $ranksId = array();
  63. //Ajout des rangs depuis les liens user/firm/rank
  64. foreach (UserFirmRank::loadAll(array('user:IN'=>$logins ), null, null, array('*'), 1) as $firmRank) {
  65. $rank = $firmRank->join('rank');
  66. $firm = $firmRank->join('firm');
  67. $ranksId[] = $rank->id;
  68. $users[$firmRank->user]->firms[$firm->id] = $firm;
  69. if(!isset($users[$firmRank->user]->ranks[$firmRank->firm])) $users[$firmRank->user]->ranks[$firmRank->firm] = array();
  70. $users[$firmRank->user]->ranks[$firmRank->firm][$rank->id] = $rank;
  71. if(empty($users[$firmRank->user]->superadmin) && $rank->superadmin) $users[$firmRank->user]->superadmin = boolval($rank->superadmin);
  72. }
  73. //récuperation des droits ciblés sur user et rangs pour les user et rang user concernés
  74. $rights = Right::staticQuery('SELECT * FROM {{table}} WHERE
  75. (targetScope="user" AND targetUid IN ('.implode(',',array_fill(0,count($logins),'?')).')) OR (targetScope="rank" AND targetUid IN('.implode(',',array_fill(0,count($ranksId),'?')).')) ',array_merge($logins,$ranksId),true);
  76. $rightsForRank = array();
  77. foreach($rights as $right):
  78. //pour les rangs on remplis un tableau de mapping qu'on redistribuera plus tard
  79. if($right->targetScope =='rank'){
  80. if(!isset($rightsForRank[$right->targetUid])) $rightsForRank[$right->targetUid] = array();
  81. $rightsForRank[$right->targetUid][]= $right;
  82. //pour les users
  83. }else{
  84. //Pour le premier rang qui aborde cette scope on met tous les droits à false
  85. if(!isset($users[$right->targetUid]->rights[$right->scope][$right->firm][$right->uid])){
  86. $users[$right->targetUid]->rights[$right->scope][$right->firm][$right->uid] = array(
  87. 'read' => false,
  88. 'edit' => false,
  89. 'delete' => false,
  90. 'recursive' => false,
  91. 'configure' => false
  92. );
  93. }
  94. //Puis on complete uniquement les droits à true sur la scope pour chaques rangs additionnels
  95. if($right->read) $users[$right->targetUid]->rights[$right->scope][$right->firm][$right->uid]['read'] = true;
  96. if($right->edit) $users[$right->targetUid]->rights[$right->scope][$right->firm][$right->uid]['edit'] = true;
  97. if($right->delete) $users[$right->targetUid]->rights[$right->scope][$right->firm][$right->uid]['delete'] = true;
  98. if($right->configure) $users[$right->targetUid]->rights[$right->scope][$right->firm][$right->uid]['configure'] = true;
  99. }
  100. endforeach;
  101. //pour chaque user
  102. foreach($users as $key=>$user){
  103. //onrecupere les firms
  104. foreach($user->ranks as $firmrank){
  105. //on liste les rangs du user pour cette firm
  106. foreach($firmrank as $rank){
  107. //si un de ces rangs possede des droits liés
  108. if(!isset($rightsForRank[$rank->id])) continue;
  109. //pour chaque droit liées on les applique au user
  110. foreach($rightsForRank[$rank->id] as $right){
  111. //Pour le premier rang qui aborde cette scope on met tous les droits à false
  112. if(!isset($users[$key]->rights[$right->scope][$right->firm][$right->uid])){
  113. $users[$key]->rights[$right->scope][$right->firm][$right->uid] = array(
  114. 'read' => false,
  115. 'edit' => false,
  116. 'delete' => false,
  117. 'recursive' => false,
  118. 'configure' => false
  119. );
  120. }
  121. //Puis on complete uniquement les droits à true sur la scope pour chaques rangs additionnels
  122. if($right->read) $users[$key]->rights[$right->scope][$right->firm][$right->uid]['read'] = true;
  123. if($right->edit) $users[$key]->rights[$right->scope][$right->firm][$right->uid]['edit'] = true;
  124. if($right->delete) $users[$key]->rights[$right->scope][$right->firm][$right->uid]['delete'] = true;
  125. if($right->configure) $users[$key]->rights[$right->scope][$right->firm][$right->uid]['configure'] = true;
  126. }
  127. }
  128. }
  129. }
  130. }
  131. //sort des users par noms
  132. uasort($users, function($a, $b){ return strcmp($a->name, $b->name); });
  133. $_SESSION['users_'.($options['right']?'rights':'norights')] = serialize($users);
  134. }
  135. return $users;
  136. }
  137. public function __sleep(){
  138. $fields = $this->toArray();
  139. unset($fields['fullName'], $fields['initials']);
  140. return array_merge(array('superadmin','rights','groups','ranks','firms','preferences'),array_keys($fields));
  141. }
  142. //Surchage de toArray pour prendre en compte le fullName et les initials régulierement utilisé en toArray
  143. public function toArray($decoded=false) {
  144. $fields = parent::toArray($decoded);
  145. $fields['fullName'] = $this->fullName();
  146. $fields['initials'] = $this->initials();
  147. unset($fields['password']);
  148. unset($fields['token']);
  149. if(isset($fields['manager']) && is_object($fields['manager'])) $fields['manager'] = $fields['manager']->toArray();
  150. if($decoded){
  151. $fields['fullName'] = html_entity_decode($fields['fullName']);
  152. $fields['initials'] = html_entity_decode($fields['initials']);
  153. }
  154. return $fields;
  155. }
  156. // $this->rights[$right->scope][$right->uid][$right->firm]
  157. public function can($scope,$right,$uid=0,$options = array()){
  158. if($this->superadmin == 1) return true;
  159. global $myFirm;
  160. $firm = is_object($myFirm) && $myFirm->id !=0 ? $myFirm->id : 0;
  161. // Recherche dans les droits ciblé sur la firm courante
  162. if(isset($this->rights[$scope][$firm][$uid][$right]))
  163. return $this->rights[$scope][$firm][$uid][$right]==1;
  164. // Recherche dans les droits non ciblés sur une firm
  165. if(isset($this->rights[$scope][0][$uid][$right]))
  166. return $this->rights[$scope][0][$uid][$right]==1;
  167. if(isset($options['contains']) && $options['contains'] == true){
  168. if(isset($this->rights[$scope])) {
  169. $rightArray = array();
  170. if(isset($this->rights[$scope][0]))
  171. $rightArray =$this->rights[$scope][0];
  172. if(isset($this->rights[$scope][$myFirm->id]))
  173. $rightArray = $this->rights[$scope][$myFirm->id];
  174. foreach($rightArray as $uid=>$rights){
  175. if(!isset($rights[$right]) || !$rights[$right]) continue;
  176. return true;
  177. }
  178. }
  179. }
  180. return false;
  181. }
  182. //Lance les exception appropriées en fonction du droit ou des droits spécifiés
  183. // ex : User::check_access('document','configure');
  184. public static function check_access($scope,$right,$uid=0){
  185. global $myUser;
  186. if(!isset($myUser) || !is_object($myUser) || !$myUser->connected()) throw new Exception("Contrôle d'accès - Vous devez être connecté",401);
  187. if(!$myUser->can($scope,$right,$uid)) throw new Exception("Contrôle d'accès - Permissions insuffisantes ('".$scope.".".$right."')",403);
  188. }
  189. //Vérifie que l'utilisateur courant est lié a l'id du rang spécifié
  190. public function hasRank($rankId){
  191. if($this->superadmin) return true;
  192. $rankIds = array();
  193. global $myFirm;
  194. if(empty($this->ranks) || !isset($this->ranks[$myFirm->id])) return false;
  195. foreach ($this->ranks[$myFirm->id] as $rank)
  196. $rankIds[$rank->id] = true;
  197. return isset($rankIds[$rankId]);
  198. }
  199. public function preference($key=null, $value=null){
  200. global $myUser;
  201. if(!isset($key) && !isset($value)) return $this->preferences;
  202. if(isset($key) && !isset($value)) return isset($this->preferences[$key])?$this->preferences[$key]:'';
  203. if(isset($key) && isset($value)){
  204. $this->preferences[$key] = $value;
  205. $preference = UserPreference::load(array('key'=>$key,'user'=>$this->login));
  206. if(!$preference) $preference = new UserPreference();
  207. $preference->key = $key;
  208. $preference->value = $value;
  209. $preference->user = $this->login;
  210. $preference->save();
  211. if($myUser->login == $this->login) $_SESSION['currentUser'] = serialize($this);
  212. }
  213. }
  214. public function loadRanks(){
  215. //Ajout des rangs depuis les liens user/firm/rank
  216. foreach (UserFirmRank::loadAll(array('user'=>$this->login), null, null, array('*'), 1) as $firmRank) {
  217. $rank = $firmRank->join('rank');
  218. $firm = $firmRank->join('firm');
  219. $this->firms[$firm->id] = $firm;
  220. if(!isset($this->ranks[$firmRank->firm])) $this->ranks[$firmRank->firm] = array();
  221. $this->ranks[$firmRank->firm][$rank->id] = $rank;
  222. if(empty($this->superadmin) && $rank->superadmin) $this->superadmin = boolval($rank->superadmin);
  223. }
  224. }
  225. public function loadPreferences(){
  226. $this->preferences = array();
  227. foreach(UserPreference::loadAll(array('user'=>$this->login)) as $line):
  228. $this->preferences[$line->key] = $line->value;
  229. endforeach;
  230. }
  231. //@TODO: Ajouter paramètre $firm pour cibler la récup
  232. //des droits pour une firm en particulier et plus $myFirm
  233. public function loadRights(){
  234. global $myFirm;
  235. $this->rights = array();
  236. if($this->superadmin) return;
  237. if(!isset($this->ranks)) $this->ranks = array();
  238. if(!isset($myFirm) || !isset($this->ranks[$myFirm->id]) || count($this->ranks[$myFirm->id])==0) return;
  239. $ranksId = array();
  240. foreach($this->ranks[$myFirm->id] as $rank){
  241. if(!isset($rank->id) || !is_numeric($rank->id)) continue;
  242. $ranksId[] = $rank->id;
  243. }
  244. if(count($ranksId)==0) return;
  245. $rights = Right::staticQuery('SELECT * FROM {{table}} WHERE (targetScope="user" AND targetUid=?) OR (targetScope="rank" AND targetUid IN('.str_repeat('?,', count($ranksId) - 1) . '?'.'))',array_merge(array($this->login), $ranksId),true);
  246. foreach($rights as $right):
  247. //Pour le premier rang qui aborde cette scope on met tous les droits à false
  248. if(!isset($this->rights[$right->scope][$right->firm][$right->uid])){
  249. $this->rights[$right->scope][$right->firm][$right->uid] = array(
  250. 'read' => false,
  251. 'edit' => false,
  252. 'delete' => false,
  253. 'recursive' => false,
  254. 'configure' => false
  255. );
  256. }
  257. //Puis on complete uniquement les droits à true sur la scope pour chaques rangs additionnels
  258. if($right->read) $this->rights[$right->scope][$right->firm][$right->uid]['read'] = true;
  259. if($right->edit) $this->rights[$right->scope][$right->firm][$right->uid]['edit'] = true;
  260. if($right->delete) $this->rights[$right->scope][$right->firm][$right->uid]['delete'] = true;
  261. if($right->configure) $this->rights[$right->scope][$right->firm][$right->uid]['configure'] = true;
  262. endforeach;
  263. /*
  264. $permissions = Right::staticQuery('SELECT * FROM {{table}} WHERE (targetScope="user" AND targetUid=?) OR (targetScope="rank" AND targetUid IN('.str_repeat('?,', count($ranksId) - 1) . '?'.'))',array_merge(array($this->login), $ranksId),true);
  265. $this->rights['permission'] = array();
  266. foreach ($permissions as $permission) {
  267. if(!isset($this->rights['permission'][$permission->scope])) $this->rights['permission'][$permission->scope] = array();
  268. if(!isset($this->rights['permission'][$permission->scope][$permission->uid])){
  269. $this->rights['permission'][$permission->scope][$permission->uid] = array(
  270. 'read' => false,
  271. 'edit' => false,
  272. 'delete' => false,
  273. 'recursive' => false,
  274. 'configure' => false
  275. );
  276. }
  277. if($permission->read) $this->rights['permission'][$permission->scope][$permission->uid]['read'] = true;
  278. if($permission->edit) $this->rights['permission'][$permission->scope][$permission->uid]['edit'] = true;
  279. if($permission->delete) $this->rights['permission'][$permission->scope][$permission->uid]['delete'] = true;
  280. if($permission->recursive) $this->rights['permission'][$permission->scope][$permission->uid]['recursive'] = true;
  281. if($permission->configure) $this->rights['permission'][$permission->scope][$permission->uid]['configure'] = true;
  282. }
  283. */
  284. }
  285. public function getFirms(){
  286. $this->firms = array();
  287. 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):
  288. $this->firms[$firm->id] = $firm;
  289. endforeach;
  290. }
  291. //Vérifie que l'utilisateur courant est lié à l'id établissement spécifié
  292. //tags : hasFirm
  293. public function haveFirm($id){
  294. return in_array($id, array_keys($this->firms));
  295. }
  296. public function getAvatar($getPath = false){
  297. $avatar = 'img/default-avatar.png';
  298. if(!$this->check_avatar_path_length()) return $avatar;
  299. $files = glob(__ROOT__.FILE_PATH.AVATAR_PATH.self::format_avatar_name($this->login).self::get_avatar_extension_brace(),GLOB_BRACE);
  300. if(count($files)>0){
  301. if($getPath) return $files[0];
  302. preg_match("/\.(\w{3,4})$|\?/m", $files[0], $extension);
  303. $avatar = 'action.php?action=core_account_avatar_download&user='.urlencode($this->login).'&extension='.$extension[1];
  304. }
  305. return $avatar;
  306. }
  307. public function check_avatar_path_length(){
  308. return strlen($this->login) <= OS_path_max_length() - strlen(__ROOT__.FILE_PATH.AVATAR_PATH) - strlen(User::get_avatar_extension_brace());
  309. }
  310. public static function format_avatar_name($text){
  311. return iconv('utf-8','windows-1256//IGNORE', $text);
  312. }
  313. public static function get_avatar_extension_brace(){
  314. return ".{jpg,png,jpeg,gif}";
  315. }
  316. public static function initialization(&$user, $loadRight){
  317. global $myFirm,$conf;
  318. //Ajout du check de l'état du user
  319. if(!empty($user->state) && $user->state!=User::ACTIVE) return new self;
  320. $user->ranks = empty($user->ranks) ? array() : $user->ranks;
  321. $user->firms = empty($user->firms) ? array() : $user->firms;
  322. if(isset($user->manager) && !empty($user->manager) && !is_object($user->manager)) $user->manager = self::byLogin($user->manager);
  323. $user->loadRanks();
  324. $user->loadPreferences();
  325. //Suppression des rangs et de la firm Anonyme
  326. if(isset($user->ranks[-1])) unset($user->ranks[-1]);
  327. if(isset($user->firms[-1])) unset($user->firms[-1]);
  328. //Set des rangs et droits pour le SuperAdmin
  329. if($user->superadmin == 1){
  330. foreach(Firm::loadAll() as $firm) {
  331. $user->firms[$firm->id] = $firm;
  332. foreach (Rank::loadAll() as $rank)
  333. $user->ranks[$firm->id][$rank->id] = $rank;
  334. }
  335. }
  336. //Set de l'établissement par défaut
  337. if(!empty($user->firms)){
  338. $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : key($user->firms);
  339. $myFirm = isset($user->firms[$defaultFirm]) ? $user->firms[$defaultFirm] : reset($user->firms);
  340. if(!isset($user->firms[$defaultFirm])) $user->preference('default_firm',$myFirm->id);
  341. //Ajout des rang par défaut user connecté
  342. if(!empty($conf->get('connected_default_rank'))) {
  343. foreach(Rank::loadAll(array('id:IN'=>$conf->get('connected_default_rank'))) as $rank){
  344. foreach ($user->firms as $firm) {
  345. if(!isset($user->ranks[$firm->id])) $user->ranks[$firm->id] = array();
  346. $user->ranks[$firm->id][$rank->id] = $rank;
  347. }
  348. }
  349. }
  350. }
  351. if($loadRight) $user->loadRights();
  352. }
  353. public static function check($login, $password, $loadRight=true){
  354. global $myFirm,$conf;
  355. //Load from db
  356. $user = self::load(array('login'=>$login));
  357. if($user && !password_verify($password, $user->password)) $user = false;
  358. //Load from plugins
  359. Plugin::callHook("user_login", array(&$user,htmlspecialchars_decode($login),htmlspecialchars_decode($password),$loadRight));
  360. //init user
  361. if($user!=false) self::initialization($user, $loadRight);
  362. $user = is_object($user) ? $user : new self;
  363. return $user;
  364. }
  365. //Connecte unn utilisateur sans recourir au mot de passe
  366. public static function connectLogin($login){
  367. global $myFirm,$conf;
  368. //Load from db
  369. $user = self::load(array('login'=>$login,'state'=>User::ACTIVE));
  370. //Load from plugins
  371. Plugin::callHook("user_login", array(&$user,htmlspecialchars_decode($login),null,true,true,true));
  372. if($user!=false)
  373. self::initialization($user, true);
  374. $user = is_object($user) ? $user : new self;
  375. return $user;
  376. }
  377. public static function byLogin($login, $loadRight=true, $force=false){
  378. foreach(User::getAll(array('right'=>$loadRight, 'force'=>$force)) as $user){
  379. if($user->login != $login) continue;
  380. return $user;
  381. }
  382. return new User();
  383. }
  384. public function lastname(){
  385. return mb_strtoupper(htmlspecialchars_decode(mb_strtolower($this->name)));
  386. }
  387. public function firstname(){
  388. return mb_ucfirst(htmlspecialchars_decode(mb_strtolower($this->firstname)));
  389. }
  390. public function fullName(){
  391. $fullName = $this->firstname().' '.$this->lastname();
  392. return trim($fullName) != '' ? $fullName : $this->login;
  393. }
  394. public function initials(){
  395. $fullname = str_replace(array(' ','\''),'-',implode(' ',array($this->firstname.' '.$this->name)));
  396. $fullname = explode('-',$fullname);
  397. $result = '';
  398. foreach($fullname as $value)
  399. $result.= mb_strtoupper(mb_substr($value,0,1));
  400. return $result;
  401. }
  402. public function subordinates(){
  403. $subordinates = array();
  404. foreach (User::getAll() as $user) {
  405. if(is_object($user->manager) && $user->manager->login == $this->login) $subordinates[] = $user;
  406. }
  407. return $subordinates;
  408. }
  409. public static function generate_password($length=16,$iteration=0){
  410. global $conf;
  411. if($length<0) $length = 16;
  412. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
  413. '0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';
  414. //Suppression des caractères interdits en conf de la chaîne de traitement
  415. $chars = str_replace(preg_split('//u', htmlspecialchars_decode($conf->get('password_forbidden_char')), null, PREG_SPLIT_NO_EMPTY), '', $chars);
  416. $str = '';
  417. $max = strlen($chars) - 1;
  418. for ($i=0; $i<$length; $i++)
  419. $str .= $chars[mt_rand(0, $max)];
  420. //Génère un password tant que ne correspond pas aux règles définies
  421. //(maximum 100 itérations pour éviter boucle infinie)
  422. if(!empty(self::check_password_format($str)) && $iteration<100) $str = self::generate_password($length,++$iteration);
  423. return $str;
  424. }
  425. public static function password_formats(){
  426. $formats = array(
  427. array('pattern'=>'|[0-9]|i','label'=>'Le mot de passe doit comporter au minimum 1 chiffre (norme ANSSI)'),
  428. array('pattern'=>'|[A-Z]|','label'=>'Le mot de passe doit comporter au minimum 1 majuscule (norme ANSSI)'),
  429. array('pattern'=>'|[^A-Za-z0-9éèêëàäâïîöôûüù]|i','label'=>'Le mot de passe doit comporter au minimum 1 caractère spécial (norme ANSSI)'),
  430. array('pattern'=>'|.{6,}|','label'=>'Le mot de passe doit comporter au minimum 6 caractères'),
  431. array('pattern'=>'|.{12,}|','label'=>'Le mot de passe doit comporter au minimum 12 caractères (norme ANSSI)'),
  432. );
  433. return $formats;
  434. }
  435. public static function check_password_format($password){
  436. global $conf;
  437. $errors = array();
  438. $formats = array();
  439. foreach (self::password_formats() as $format) {
  440. $formats[$format['pattern']] = $format;
  441. }
  442. $selectedFormats = json_decode($conf->get('password_format'),true);
  443. if(is_array($selectedFormats)){
  444. foreach($selectedFormats as $pattern){
  445. if(!isset($formats[$pattern])) continue;
  446. $format = $formats[$pattern];
  447. if(!preg_match($pattern, $password)) $errors[] = $format['label'];
  448. }
  449. }
  450. return $errors;
  451. }
  452. public static function password_encrypt($password){
  453. return password_hash($password, PASSWORD_DEFAULT);
  454. }
  455. public function connected(){
  456. return !empty($this->login);
  457. }
  458. public function disconnect($redirect=null){
  459. global $conf;
  460. if(isset($this->login)) $this->preference('cookie','');
  461. $url = 'index.php';
  462. if(!is_null($redirect)) $url = base64_decode($redirect);
  463. //Permet la redirection vers une url spécifique lors de la déco
  464. if(isset($_SESSION['logout_redirect'])) $url = $_SESSION['logout_redirect'];
  465. unset($_SESSION['currentUser']);
  466. unset($_SESSION['firm']);
  467. session_destroy();
  468. unset($_COOKIE[COOKIE_NAME]);
  469. setcookie(COOKIE_NAME, null, -1, '/');
  470. return $url;
  471. }
  472. public function setLogin($login){
  473. $this->login = $login;
  474. }
  475. public function setName($name){
  476. $this->name = $name;
  477. }
  478. public function setFirstName($firstname){
  479. $this->firstname = $firstname;
  480. }
  481. public function setMail($mail){
  482. $this->mail = $mail;
  483. }
  484. public function setPhone($phone){
  485. $this->phone = $phone;
  486. }
  487. public function setMobile($mobile){
  488. $this->mobile = $mobile;
  489. }
  490. public function setFunction($function){
  491. $this->function = $function;
  492. }
  493. public function setGroups($groups){
  494. $this->groups = $groups;
  495. }
  496. public static function generateToken(){
  497. return substr(md5(uniqid(rand(), true)),0,10);
  498. }
  499. public function getGroups(){
  500. return (is_array($this->groups) ? $this->groups : array());
  501. }
  502. public function setFirms($firms){
  503. if(empty($firms)) return;
  504. $this->firms = $firms;
  505. }
  506. public function getRanksId($firmId=null){
  507. if(empty($this->ranks)) return array();
  508. $ranks = array();
  509. if(!empty($firmId)) {
  510. //On ne rassemble pas les conditions pour ne pas passer dans le else si la sous-condition est fausse et donc garder un array vide
  511. if(!empty($this->ranks[$firmId])) $ranks = array_keys($this->ranks[$firmId]);
  512. } else {
  513. foreach($this->ranks as $fId => $userRanks)
  514. $ranks[$fId] = array_keys($userRanks);
  515. }
  516. return $ranks;
  517. }
  518. //Retourne un objet manager (User vide si pas de manager) quel que soit le provider d'entré (ad : objet, db: login)
  519. public function manager(){
  520. $manager = new User();
  521. if(!isset($this->manager)) return $manager;
  522. if(is_object($this->manager)) $manager = $this->manager;
  523. if(is_string($this->manager) && !empty($this->manager)) $manager = User::byLogin($this->manager);
  524. return is_object($manager) ? $manager: new User();
  525. }
  526. }