User.class.php 12 KB

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