User.class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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){
  74. if($this->superadmin == 1) return true;
  75. global $myFirm;
  76. $firm = is_object($myFirm) && $myFirm->id !=0 ? $myFirm->id : 0;
  77. if(isset($this->rights[$section][$firm][$right])){
  78. return $this->rights[$section][$firm][$right]==1;
  79. }
  80. if(isset($this->rights[$section][0][$right])){
  81. return $this->rights[$section][0][$right]==1;
  82. }
  83. return false;
  84. }
  85. //Lance les exception appropriées en fonction du droit ou des droits spécifiés
  86. // ex : User::check_access('document','configure');
  87. public static function check_access($section,$right){
  88. global $myUser;
  89. if(!isset($myUser) || !is_object($myUser) || !$myUser->connected()) throw new Exception("Contrôle d'accès - Vous devez être connecté",401);
  90. if(!$myUser->can($section,$right)) throw new Exception("Contrôle d'accès - Permissions insuffisantes",403);
  91. }
  92. public function hasRank($rankId){
  93. if($this->superadmin) return true;
  94. $rankIds = array();
  95. global $myFirm;
  96. if(empty($this->ranks) || !isset($this->ranks[$myFirm->id])) return false;
  97. foreach ($this->ranks[$myFirm->id] as $rank)
  98. $rankIds[$rank->id] = true;
  99. return isset($rankIds[$rankId]);
  100. }
  101. public function preference($key=null, $value=null){
  102. if(!isset($key) && !isset($value)) return $this->preferences;
  103. if(isset($key) && !isset($value)) return isset($this->preferences[$key])?$this->preferences[$key]:'';
  104. if(isset($key) && isset($value)){
  105. $this->preferences[$key] = $value;
  106. $preference = UserPreference::load(array('key'=>$key,'user'=>$this->login));
  107. if(!$preference) $preference = new UserPreference();
  108. $preference->key = $key;
  109. $preference->value = $value;
  110. $preference->user = $this->login;
  111. $preference->save();
  112. }
  113. }
  114. public function loadRanks(){
  115. foreach (UserFirmRank::loadAll(array('user'=>$this->login), null, null, array('*'),1) as $firmRank) {
  116. $rank = $firmRank->join('rank');
  117. $firm = $firmRank->join('firm');
  118. $this->firms[$firm->id] = $firm;
  119. if(!isset($this->ranks[$firmRank->firm])) $this->ranks[$firmRank->firm] = array();
  120. $this->ranks[$firmRank->firm][$rank->id]= $rank;
  121. }
  122. }
  123. public function loadPreferences(){
  124. $this->preferences = array();
  125. foreach(UserPreference::loadAll(array('user'=>$this->login)) as $line):
  126. $this->preferences[$line->key] = $line->value;
  127. endforeach;
  128. }
  129. public function loadRights(){
  130. global $myFirm;
  131. $this->rights = array();
  132. if($this->superadmin) return;
  133. if(!isset($this->ranks)) $this->ranks = array();
  134. if(!isset($myFirm) || !isset($this->ranks[$myFirm->id]) || count($this->ranks[$myFirm->id])==0) return;
  135. $ranksId = array();
  136. foreach($this->ranks[$myFirm->id] as $rank){
  137. if(!isset($rank->id) || !is_numeric($rank->id)) continue;
  138. $ranksId[] = $rank->id;
  139. }
  140. if(count($ranksId)==0) return;
  141. $rights = Right::staticQuery('SELECT * FROM {{table}} WHERE rank IN('.implode(',',$ranksId).')',array(),true);
  142. foreach($rights as $right):
  143. //Pour le premier rang qui aborde cette section on met tous les droits à false
  144. if(!isset($this->rights[$right->section][$right->firm])){
  145. $this->rights[$right->section][$right->firm] = array(
  146. 'read' => false,
  147. 'edit' => false,
  148. 'delete' => false,
  149. 'configure' => false
  150. );
  151. }
  152. //Puis on complete uniquement les droits à true sur la section pour chaques rangs additionnels
  153. if($right->read) $this->rights[$right->section][$right->firm]['read'] = true;
  154. if($right->edit) $this->rights[$right->section][$right->firm]['edit'] = true;
  155. if($right->delete) $this->rights[$right->section][$right->firm]['delete'] = true;
  156. if($right->configure) $this->rights[$right->section][$right->firm]['configure'] = true;
  157. endforeach;
  158. }
  159. public function getFirms(){
  160. $this->firms = array();
  161. 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):
  162. $this->firms[$firm->id] = $firm;
  163. endforeach;
  164. }
  165. public function haveFirm($id){
  166. return in_array($id, array_keys($this->firms));
  167. }
  168. public function getAvatar($getPath = false){
  169. $avatar = 'img/default-avatar.png';
  170. if(!$this->check_avatar_path_length()) return $avatar;
  171. $files = glob(__ROOT__.FILE_PATH.AVATAR_PATH.self::format_avatar_name($this->login).self::get_avatar_extension_brace(),GLOB_BRACE);
  172. if(count($files)>0){
  173. if($getPath) return $files[0];
  174. preg_match("/\.(\w{3,4})$|\?/m", $files[0], $extension);
  175. $avatar = 'action.php?action=account_avatar_download&user='.urlencode($this->login).'&extension='.$extension[1];
  176. }
  177. return $avatar;
  178. }
  179. public function check_avatar_path_length(){
  180. return strlen($this->login) <= OS_path_max_length() - strlen(__ROOT__.FILE_PATH.AVATAR_PATH) - strlen(User::get_avatar_extension_brace());
  181. }
  182. public static function format_avatar_name($text){
  183. return iconv('utf-8','windows-1256//IGNORE', $text);
  184. }
  185. public static function get_avatar_extension_brace(){
  186. return ".{jpg,png,jpeg,gif}";
  187. }
  188. public static function check($login, $password, $loadRight = true) {
  189. global $myFirm;
  190. $user = self::load(array('login' => $login, 'password' => self::password_encrypt($password)));
  191. //load from plugins
  192. Plugin::callHook("user_login", array(&$user,htmlspecialchars_decode($login),htmlspecialchars_decode($password),$loadRight));
  193. //load from db
  194. if($user!=false){
  195. $user->ranks = empty($user->ranks) ? array() : $user->ranks;
  196. $user->firms = empty($user->firms) ? array() : $user->firms;
  197. if(isset($user->manager) && !empty($user->manager) && !is_object($user->manager)) $user->manager = self::byLogin($user->manager);
  198. $user->loadRanks();
  199. $user->loadPreferences();
  200. if($user->superadmin == 1){
  201. foreach(Firm::loadAll() as $firm)
  202. $firms[$firm->id] = $firm;
  203. $user->setFirms($firms);
  204. }
  205. if(!empty($user->firms)){
  206. $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : key($user->firms);
  207. $myFirm = isset($user->firms[$defaultFirm]) ? $user->firms[$defaultFirm]:reset($user->firms);
  208. if(!isset($user->firms[$defaultFirm])) $user->preference('default_firm',$myFirm->id);
  209. }
  210. if($loadRight) $user->loadRights();
  211. }
  212. $user = is_object($user) ? $user : new self();
  213. return $user;
  214. }
  215. public static function byLogin($login, $loadRight=true, $force=false){
  216. foreach(User::getAll($loadRight, $force) as $user){
  217. if($user->login != $login) continue;
  218. return $user;
  219. }
  220. return new User();
  221. }
  222. public function lastname(){
  223. return mb_strtoupper(htmlspecialchars_decode(mb_strtolower($this->name)));
  224. }
  225. public function firstname(){
  226. return htmlspecialchars_decode($this->firstname);
  227. }
  228. public function fullName(){
  229. $fullName = ucfirst($this->firstname()).' '.$this->lastname();
  230. return trim($fullName) != '' ? $fullName : $this->login;
  231. }
  232. public function initials(){
  233. $firstname = str_replace(array(' ','\''),'-',$this->firstname);
  234. $firstname = explode('-',$firstname);
  235. $result = '';
  236. foreach($firstname as $pren){
  237. $result.= strtoupper(substr($pren,0,1));
  238. }
  239. return $result.strtoupper(substr($this->name,0,1));
  240. }
  241. public function subordinates(){
  242. $subordinates = array();
  243. foreach (User::getAll() as $user) {
  244. if(is_object($user->manager) && $user->manager->login == $this->login) $subordinates[] = $user;
  245. }
  246. return $subordinates;
  247. }
  248. public static function password_formats(){
  249. $formats = array(
  250. array('pattern'=>'|[0-9]|i','label'=>'Le mot de passe doit comporter au minimum 1 chiffre (norme ANSSI)'),
  251. array('pattern'=>'|[A-Z]|','label'=>'Le mot de passe doit comporter au minimum 1 majuscule (norme ANSSI)'),
  252. array('pattern'=>'|[^A-Za-z0-9éèêëàäâïîöôûüù]|i','label'=>'Le mot de passe doit comporter au minimum 1 caractère spécial (norme ANSSI)'),
  253. array('pattern'=>'|.{6,}|','label'=>'Le mot de passe doit comporter au minimum 6 caractères'),
  254. array('pattern'=>'|.{12,}|','label'=>'Le mot de passe doit comporter au minimum 12 caractères (norme ANSSI)'),
  255. );
  256. return $formats;
  257. }
  258. public static function check_password_format($password){
  259. global $conf;
  260. $errors = array();
  261. $formats = array();
  262. foreach (self::password_formats() as $format) {
  263. $formats[$format['pattern']] = $format;
  264. }
  265. $selectedFormats = json_decode($conf->get('password_format'),true);
  266. if(is_array($selectedFormats)){
  267. foreach($selectedFormats as $pattern){
  268. if(!isset($formats[$pattern])) continue;
  269. $format = $formats[$pattern];
  270. if(!preg_match($pattern, $password)) $errors[] = $format['label'];
  271. }
  272. }
  273. return $errors;
  274. }
  275. public static function password_encrypt($password){
  276. return sha1(md5($password));
  277. }
  278. public function connected(){
  279. return !empty($this->login);
  280. }
  281. public function setLogin($login){
  282. $this->login = $login;
  283. }
  284. public function setName($name){
  285. $this->name = $name;
  286. }
  287. public function setFirstName($firstname){
  288. $this->firstname = $firstname;
  289. }
  290. public function setMail($mail){
  291. $this->mail = $mail;
  292. }
  293. public function setPhone($phone){
  294. $this->phone = $phone;
  295. }
  296. public function setMobile($mobile){
  297. $this->mobile = $mobile;
  298. }
  299. public function setFunction($function){
  300. $this->function = $function;
  301. }
  302. public function setGroups($groups){
  303. $this->groups = $groups;
  304. }
  305. public static function generateToken(){
  306. return substr(md5(uniqid(rand(), true)),0,10);
  307. }
  308. public function getGroups(){
  309. return (is_array($this->groups) ? $this->groups : array());
  310. }
  311. public function setFirms($firms){
  312. if(empty($firms)) return;
  313. $this->firms = $firms;
  314. }
  315. //Retourne un objet manager (User vide si pas de manager) quel que soit le provider d'entré (ad : objet, db: login)
  316. public function manager(){
  317. $manager = new User();
  318. if(!isset($this->manager)) return $manager;
  319. if(is_object($this->manager)) $manager = $this->manager;
  320. if(is_string($this->manager) && !empty($this->manager)) $manager = User::byLogin($this->manager);
  321. return is_object($manager) ? $manager: new User();
  322. }
  323. }