User.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. <?php
  2. /**
  3. * Define an application user.
  4. * @author valentin carruesco
  5. * @category Core
  6. * @license copyright
  7. */
  8. class User extends Entity
  9. {
  10. public $id,$login,$password,$function,$name,$firstname,$mail,
  11. $state,$rights,$firms,$superadmin,$token,
  12. $preferences,$phone,$mobile,
  13. $groups,$ranks,$manager,$service,$origin,$meta;
  14. protected $fields =
  15. array(
  16. 'id' => 'key',
  17. 'login' => 'string',
  18. 'password' => 'string',
  19. 'name' => 'string',
  20. 'function' => 'string',
  21. 'firstname' => 'string',
  22. 'token' => 'string',
  23. 'mail' => 'string',
  24. 'state' => 'string',
  25. 'phone' => 'string',
  26. 'mobile' => 'string',
  27. 'manager' => 'string',
  28. 'origin' => 'string',
  29. 'service' => 'string',
  30. 'superadmin' => 'int'
  31. );
  32. function __construct(){
  33. parent::__construct();
  34. $this->token = self::generateToken();
  35. $this->meta = array();
  36. }
  37. public static function getAll($loadRight=true, $force=false){
  38. $users = array();
  39. if(isset($_SESSION['users']))
  40. $users = unserialize($_SESSION['users']);
  41. if(empty($users) || $force){
  42. Plugin::callHook('user_load',array(&$users, $loadRight));
  43. uasort($users, function($a, $b){ return strcmp($a->name, $b->name); });
  44. foreach (self::loadAll(array('state'=>User::ACTIVE), array(' name ASC ')) as $baseUser) {
  45. $existingKey = null;
  46. if($loadRight){
  47. if(!isset($baseUser->ranks)) $baseUser->ranks = array();
  48. if(!isset($baseUser->firms)) $baseUser->firms = array();
  49. $baseUser->loadRanks();
  50. $baseUser->loadRights();
  51. }
  52. if(isset($baseUser->manager) && $baseUser->manager!="") $baseUser->manager = User::load(array('login'=>$baseUser->manager));
  53. foreach ($users as $key => $otherUser) {
  54. //permet la predominance des users db sur les user foreign type type
  55. if($otherUser->login == $baseUser->login){
  56. $existingKey = $key;
  57. break;
  58. }
  59. }
  60. if(isset($existingKey)){
  61. $users[$existingKey] = $baseUser;
  62. }else{
  63. $users[] = $baseUser;
  64. }
  65. }
  66. $_SESSION['users'] = serialize($users);
  67. }
  68. return $users;
  69. }
  70. public function __sleep(){
  71. return array_merge(array('rights','ranks','firms','preferences','meta'),array_keys($this->toArray()));
  72. }
  73. public function can($section,$right,$permissionRight = null){
  74. if($this->superadmin == 1) return true;
  75. global $myFirm;
  76. $firm = is_object($myFirm) && $myFirm->id !=0 ? $myFirm->id : 0;
  77. if(isset($permissionRight)){
  78. if(!isset($this->rights['permission'][$section]) || !isset($this->rights['permission'][$section][$right])) return false;
  79. if(isset($this->rights['permission'][$section][$right][$permissionRight]) && $this->rights['permission'][$section][$right][$permissionRight] ) return true;
  80. return false;
  81. }
  82. if(isset($this->rights[$section][$firm][$right])){
  83. return $this->rights[$section][$firm][$right]==1;
  84. }
  85. if(isset($this->rights[$section][0][$right])){
  86. return $this->rights[$section][0][$right]==1;
  87. }
  88. return false;
  89. }
  90. //Lance les exception appropriées en fonction du droit ou des droits spécifiés
  91. // ex : User::check_access('document','configure');
  92. public static function check_access($section,$right){
  93. global $myUser;
  94. if(!isset($myUser) || !is_object($myUser) || !$myUser->connected()) throw new Exception("Contrôle d'accès - Vous devez être connecté",401);
  95. if(!$myUser->can($section,$right)) throw new Exception("Contrôle d'accès - Permissions insuffisantes",403);
  96. }
  97. public function hasRank($rankId){
  98. if($this->superadmin) return true;
  99. $rankIds = array();
  100. global $myFirm;
  101. if(empty($this->ranks) || !isset($this->ranks[$myFirm->id])) return false;
  102. foreach ($this->ranks[$myFirm->id] as $rank)
  103. $rankIds[$rank->id] = true;
  104. return isset($rankIds[$rankId]);
  105. }
  106. public function preference($key=null, $value=null){
  107. if(!isset($key) && !isset($value)) return $this->preferences;
  108. if(isset($key) && !isset($value)) return isset($this->preferences[$key])?$this->preferences[$key]:'';
  109. if(isset($key) && isset($value)){
  110. $this->preferences[$key] = $value;
  111. $preference = UserPreference::load(array('key'=>$key,'user'=>$this->login));
  112. if(!$preference) $preference = new UserPreference();
  113. $preference->key = $key;
  114. $preference->value = $value;
  115. $preference->user = $this->login;
  116. $preference->save();
  117. }
  118. }
  119. public function loadRanks(){
  120. foreach (UserFirmRank::loadAll(array('user'=>$this->login), null, null, array('*'),1) as $firmRank) {
  121. $rank = $firmRank->join('rank');
  122. $firm = $firmRank->join('firm');
  123. $this->firms[$firm->id] = $firm;
  124. if(!isset($this->ranks[$firmRank->firm])) $this->ranks[$firmRank->firm] = array();
  125. $this->ranks[$firmRank->firm][$rank->id]= $rank;
  126. }
  127. }
  128. public function loadPreferences(){
  129. $this->preferences = array();
  130. foreach(UserPreference::loadAll(array('user'=>$this->login)) as $line):
  131. $this->preferences[$line->key] = $line->value;
  132. endforeach;
  133. }
  134. public function loadRights(){
  135. global $myFirm;
  136. $this->rights = array();
  137. if($this->superadmin) return;
  138. if(!isset($this->ranks)) $this->ranks = array();
  139. if(!isset($myFirm) || !isset($this->ranks[$myFirm->id]) || count($this->ranks[$myFirm->id])==0) return;
  140. $ranksId = array();
  141. foreach($this->ranks[$myFirm->id] as $rank){
  142. if(!isset($rank->id) || !is_numeric($rank->id)) continue;
  143. $ranksId[] = $rank->id;
  144. }
  145. if(count($ranksId)==0) return;
  146. $rights = Right::staticQuery('SELECT * FROM {{table}} WHERE rank IN('.implode(',',$ranksId).')',array(),true);
  147. foreach($rights as $right):
  148. //Pour le premier rang qui aborde cette section on met tous les droits à false
  149. if(!isset($this->rights[$right->section][$right->firm])){
  150. $this->rights[$right->section][$right->firm] = array(
  151. 'read' => false,
  152. 'edit' => false,
  153. 'delete' => false,
  154. 'configure' => false
  155. );
  156. }
  157. //Puis on complete uniquement les droits à true sur la section pour chaques rangs additionnels
  158. if($right->read) $this->rights[$right->section][$right->firm]['read'] = true;
  159. if($right->edit) $this->rights[$right->section][$right->firm]['edit'] = true;
  160. if($right->delete) $this->rights[$right->section][$right->firm]['delete'] = true;
  161. if($right->configure) $this->rights[$right->section][$right->firm]['configure'] = true;
  162. endforeach;
  163. $permissions = Permission::staticQuery('SELECT * FROM {{table}} WHERE (targetEntity="user" AND targetUid=?) OR (targetEntity="rank" AND targetUid IN('.implode(',',$ranksId).'))',array($this->login),true);
  164. $this->rights['permission'] = array();
  165. foreach ($permissions as $permission) {
  166. if(!isset($this->rights['permission'][$permission->entity])) $this->rights['permission'][$permission->entity] = array();
  167. if(!isset($this->rights['permission'][$permission->entity][$permission->uid])){
  168. $this->rights['permission'][$permission->entity][$permission->uid] = array(
  169. 'read' => false,
  170. 'edit' => false,
  171. 'delete' => false,
  172. 'recursive' => false,
  173. 'configure' => false
  174. );
  175. }
  176. if($permission->read) $this->rights['permission'][$permission->entity][$permission->uid]['read'] = true;
  177. if($permission->edit) $this->rights['permission'][$permission->entity][$permission->uid]['edit'] = true;
  178. if($permission->delete) $this->rights['permission'][$permission->entity][$permission->uid]['delete'] = true;
  179. if($permission->recursive) $this->rights['permission'][$permission->entity][$permission->uid]['recursive'] = true;
  180. if($permission->configure) $this->rights['permission'][$permission->entity][$permission->uid]['configure'] = true;
  181. }
  182. }
  183. public function getFirms(){
  184. $this->firms = array();
  185. 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):
  186. $this->firms[$firm->id] = $firm;
  187. endforeach;
  188. }
  189. public function haveFirm($id){
  190. return in_array($id, array_keys($this->firms));
  191. }
  192. public function getAvatar($getPath = false){
  193. $avatar = 'img/default-avatar.png';
  194. if(!$this->check_avatar_path_length()) return $avatar;
  195. $files = glob(__ROOT__.FILE_PATH.AVATAR_PATH.self::format_avatar_name($this->login).self::get_avatar_extension_brace(),GLOB_BRACE);
  196. if(count($files)>0){
  197. if($getPath) return $files[0];
  198. preg_match("/\.(\w{3,4})$|\?/m", $files[0], $extension);
  199. $avatar = 'action.php?action=account_avatar_download&user='.urlencode($this->login).'&extension='.$extension[1];
  200. }
  201. return $avatar;
  202. }
  203. public function check_avatar_path_length(){
  204. return strlen($this->login) <= OS_path_max_length() - strlen(__ROOT__.FILE_PATH.AVATAR_PATH) - strlen(User::get_avatar_extension_brace());
  205. }
  206. public static function format_avatar_name($text){
  207. return iconv('utf-8','windows-1256//IGNORE', $text);
  208. }
  209. public static function get_avatar_extension_brace(){
  210. return ".{jpg,png,jpeg,gif}";
  211. }
  212. public static function check($login, $password, $loadRight = true) {
  213. global $myFirm;
  214. $user = self::load(array('login' => $login, 'password' => self::password_encrypt($password)));
  215. //load from plugins
  216. Plugin::callHook("user_login", array(&$user,htmlspecialchars_decode($login),htmlspecialchars_decode($password),$loadRight));
  217. //load from db
  218. if($user!=false){
  219. $user->ranks = empty($user->ranks) ? array() : $user->ranks;
  220. $user->firms = empty($user->firms) ? array() : $user->firms;
  221. if(isset($user->manager) && !empty($user->manager) && !is_object($user->manager)) $user->manager = self::byLogin($user->manager);
  222. $user->loadRanks();
  223. $user->loadPreferences();
  224. if($user->superadmin == 1){
  225. foreach(Firm::loadAll() as $firm)
  226. $firms[$firm->id] = $firm;
  227. $user->setFirms($firms);
  228. }
  229. if(!empty($user->firms)){
  230. $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : key($user->firms);
  231. $myFirm = isset($user->firms[$defaultFirm]) ? $user->firms[$defaultFirm]:reset($user->firms);
  232. if(!isset($user->firms[$defaultFirm])) $user->preference('default_firm',$myFirm->id);
  233. }
  234. if($loadRight) $user->loadRights();
  235. }
  236. $user = is_object($user) ? $user : new self();
  237. return $user;
  238. }
  239. public static function byLogin($login, $loadRight=true, $force=false){
  240. foreach(User::getAll($loadRight, $force) as $user){
  241. if($user->login != $login) continue;
  242. return $user;
  243. }
  244. return new User();
  245. }
  246. public function lastname(){
  247. return mb_strtoupper(htmlspecialchars_decode(mb_strtolower($this->name)));
  248. }
  249. public function firstname(){
  250. return htmlspecialchars_decode($this->firstname);
  251. }
  252. public function fullName(){
  253. $fullName = ucfirst($this->firstname()).' '.$this->lastname();
  254. return trim($fullName) != '' ? $fullName : $this->login;
  255. }
  256. public function initials(){
  257. $firstname = str_replace(array(' ','\''),'-',$this->firstname);
  258. $firstname = explode('-',$firstname);
  259. $result = '';
  260. foreach($firstname as $pren){
  261. $result.= strtoupper(substr($pren,0,1));
  262. }
  263. return $result.strtoupper(substr($this->name,0,1));
  264. }
  265. public function subordinates(){
  266. $subordinates = array();
  267. foreach (User::getAll() as $user) {
  268. if(is_object($user->manager) && $user->manager->login == $this->login) $subordinates[] = $user;
  269. }
  270. return $subordinates;
  271. }
  272. public static function password_formats(){
  273. $formats = array(
  274. array('pattern'=>'|[0-9]|i','label'=>'Le mot de passe doit comporter au minimum 1 chiffre (norme ANSSI)'),
  275. array('pattern'=>'|[A-Z]|','label'=>'Le mot de passe doit comporter au minimum 1 majuscule (norme ANSSI)'),
  276. array('pattern'=>'|[^A-Za-z0-9éèêëàäâïîöôûüù]|i','label'=>'Le mot de passe doit comporter au minimum 1 caractère spécial (norme ANSSI)'),
  277. array('pattern'=>'|.{6,}|','label'=>'Le mot de passe doit comporter au minimum 6 caractères'),
  278. array('pattern'=>'|.{12,}|','label'=>'Le mot de passe doit comporter au minimum 12 caractères (norme ANSSI)'),
  279. );
  280. return $formats;
  281. }
  282. public static function check_password_format($password){
  283. global $conf;
  284. $errors = array();
  285. $formats = array();
  286. foreach (self::password_formats() as $format) {
  287. $formats[$format['pattern']] = $format;
  288. }
  289. $selectedFormats = json_decode($conf->get('password_format'),true);
  290. if(is_array($selectedFormats)){
  291. foreach($selectedFormats as $pattern){
  292. if(!isset($formats[$pattern])) continue;
  293. $format = $formats[$pattern];
  294. if(!preg_match($pattern, $password)) $errors[] = $format['label'];
  295. }
  296. }
  297. return $errors;
  298. }
  299. public static function password_encrypt($password){
  300. return sha1(md5($password));
  301. }
  302. public function connected(){
  303. return !empty($this->login);
  304. }
  305. public function setLogin($login){
  306. $this->login = $login;
  307. }
  308. public function setName($name){
  309. $this->name = $name;
  310. }
  311. public function setFirstName($firstname){
  312. $this->firstname = $firstname;
  313. }
  314. public function setMail($mail){
  315. $this->mail = $mail;
  316. }
  317. public function setPhone($phone){
  318. $this->phone = $phone;
  319. }
  320. public function setMobile($mobile){
  321. $this->mobile = $mobile;
  322. }
  323. public function setFunction($function){
  324. $this->function = $function;
  325. }
  326. public function setGroups($groups){
  327. $this->groups = $groups;
  328. }
  329. public static function generateToken(){
  330. return substr(md5(uniqid(rand(), true)),0,10);
  331. }
  332. public function getGroups(){
  333. return (is_array($this->groups) ? $this->groups : array());
  334. }
  335. public function setFirms($firms){
  336. if(empty($firms)) return;
  337. $this->firms = $firms;
  338. }
  339. public function getRanksId(){
  340. global $myFirm;
  341. return array_keys($this->ranks[$myFirm->id]);
  342. }
  343. //Retourne un objet manager (User vide si pas de manager) quel que soit le provider d'entré (ad : objet, db: login)
  344. public function manager(){
  345. $manager = new User();
  346. if(!isset($this->manager)) return $manager;
  347. if(is_object($this->manager)) $manager = $this->manager;
  348. if(is_string($this->manager) && !empty($this->manager)) $manager = User::byLogin($this->manager);
  349. return is_object($manager) ? $manager: new User();
  350. }
  351. }