action.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  1. <?php
  2. if(!ini_get('safe_mode')) @set_time_limit(0);
  3. require_once __DIR__.DIRECTORY_SEPARATOR."common.php";
  4. if(php_sapi_name() == 'cli'){
  5. array_shift($_SERVER['argv']);
  6. $_['action'] = array_shift($_SERVER['argv']);
  7. foreach ($_SERVER['argv'] as $keyvalue) {
  8. $infos = explode('=',$keyvalue);
  9. $key = $infos[0];
  10. $value = count($infos)<2 ? '' : $infos[1];
  11. $_[$key] = $value;
  12. }
  13. }
  14. if(!isset($_['action'])) throw new Exception('Action inexistante');
  15. //Execution du code en fonction de l'action
  16. switch ($_['action']){
  17. case 'login':
  18. Action::write(function(&$response){
  19. global $myUser,$myFirm,$_,$conf;
  20. try {
  21. if(!isset($_['login'])) $_['login'] = 'anonymous';
  22. if(!isset($_['password'])) $_['password'] = '';
  23. // ETAPE 1
  24. Log::put("Tentative de connexion avec le login \"".$_['login']."\"",'Utilisateur');
  25. if($conf->get('account_block')==1){
  26. $try = is_numeric($conf->get('account_block_try')) ?$conf->get('account_block_try') : 5;
  27. $delay = is_numeric($conf->get('account_block_delay')) ?$conf->get('account_block_delay') : 10;
  28. $trying = Log::loadAll(array('category'=>'auth_fail', 'label'=>$_['login'], 'created:>'=>(time() - ($delay*60))));
  29. if(count($trying)>=$try) throw new Exception("Suite à un trop grand nombre de tentatives, votre compte est bloqué pour un délai de ".$delay." minutes",509);
  30. }
  31. // ETAPE 3
  32. $myUser = User::check($_['login'],$_['password']);
  33. if(!$myUser)
  34. throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  35. // ETAPE 4
  36. if(file_exists('enabled.maintenance') && $myUser->superadmin != 1)
  37. throw new Exception('Seul un compte Super Admin peut se connecter en mode maintenance');
  38. // ETAPE 5
  39. if(!$myUser->connected())
  40. throw new Exception('Identifiant ou mot de passe incorrect');
  41. $myUser->loadPreferences();
  42. // ETAPE 6
  43. if(is_numeric($myUser->preference('default_firm')) && $myUser->haveFirm($myUser->preference('default_firm'))){
  44. $_SESSION['firm'] = serialize(Firm::getById($myUser->preference('default_firm')));
  45. if(!$_SESSION['firm'])
  46. throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  47. } else if(count($myUser->firms)!=0) {
  48. $_SESSION['firm'] = serialize(reset($myUser->firms));
  49. if(!$_SESSION['firm'])
  50. throw new Exception(" Problème lors de la connexion, veuillez contacter l'administrateur");
  51. } else {
  52. throw new Exception('Ce compte n\'est actif sur aucun établissement');
  53. }
  54. // ETAPE 7
  55. $myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']) : new Firm();
  56. if(!$myFirm)
  57. throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  58. // ETAPE 8
  59. $_SESSION['currentUser'] = serialize($myUser);
  60. if(!$_SESSION['currentUser'])
  61. throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  62. // ETAPE 10
  63. if(isset($_['rememberMe']) && $_['rememberMe']=='on'){
  64. $cookie = sha1('$^é"'.mt_rand(0,100000).'=)àç_è');
  65. $myUser->preference('cookie',$cookie);
  66. make_cookie(COOKIE_NAME, $cookie);
  67. } else {
  68. $myUser->preference('cookie','');
  69. }
  70. $response['redirect'] = isset($_['url']) ? base64_decode($_['url']) : 'index.php';
  71. if(isset($_SESSION['last_request']) && !isset($_['url'])){
  72. $response['redirect'] = $_SESSION['last_request'];
  73. unset($_SESSION['last_request']);
  74. }
  75. //permet la redirection classic pour certains plugin d'authentification qui ne passent pas par le formulaire ajax
  76. if(isset($_['redirect']) && $_['redirect']=='classic'){
  77. header('location: '. $response['redirect']);
  78. exit();
  79. }
  80. // ETAPE 11
  81. Log::put("Connexion réussie avec \"".$myUser->login."\"",'Utilisateur');
  82. } catch(Exception $e){
  83. Log::put("Echec de la connexion avec ".$_['login']." : ".$e->getMessage(),'Utilisateur');
  84. //La vérification sur le code 509 permet d'éviter d'allonger le temps de ban à chaque tentative
  85. if($e->getCode()!=509) Log::put('anonymous','auth_fail');
  86. throw new Exception($e->getMessage());
  87. }
  88. });
  89. break;
  90. case 'logout':
  91. global $myUser;
  92. if(isset($myUser->login)) $myUser->preference('cookie','');
  93. $url = 'index.php';
  94. if(isset($_['url'])) $url = base64_decode($_['url']);
  95. //Permet la redirection vers une url spécifique lors de la déco
  96. if(isset($_SESSION['logout_redirect'])) $url = $_SESSION['logout_redirect'];
  97. unset($_SESSION['currentUser']);
  98. unset($_SESSION['firm']);
  99. session_destroy();
  100. unset($_COOKIE[COOKIE_NAME]);
  101. setcookie(COOKIE_NAME, null, -1, '/');
  102. $redirect = $url;
  103. Plugin::callHook('logout',array($url,$myUser));
  104. header('location: '.$redirect);
  105. break;
  106. /** FILTERS **/
  107. case 'filter_save':
  108. Action::write(function(&$response){
  109. global $myUser,$_;
  110. $preferences = json_decode($myUser->preference('search_filters'),true);
  111. if(!$preferences) $preferences = array();
  112. if(isset($_['filters']['advanced'])){
  113. foreach($_['filters']['advanced'] as $i=>$advanced){
  114. $advanced['operator'] = html_entity_decode($advanced['operator']);
  115. $_['filters']['advanced'][$i] = $advanced;
  116. }
  117. }
  118. $preferences[$_['slug']] = $_['filters'];
  119. $myUser->preference('search_filters',json_encode($preferences));
  120. $response['message'] = 'Recherche enregistrée';
  121. $_SESSION['currentUser'] = serialize($myUser);
  122. });
  123. break;
  124. case 'filter_load':
  125. Action::write(function(&$response){
  126. global $myUser,$_;
  127. $preferences = json_decode($myUser->preference('search_filters'),true);
  128. if(!$preferences) $preferences = array();
  129. $response['filters'] = array();
  130. if(isset($preferences[$_['slug']])) $response['filters'] = $preferences[$_['slug']];
  131. });
  132. break;
  133. /** LOGS */
  134. case 'search_log':
  135. Action::write(function(&$response){
  136. global $myUser,$_;
  137. User::check_access('log','read');
  138. $query = 'SELECT * FROM {{table}} WHERE 1';
  139. $data = array();
  140. //Recherche simple
  141. if(!empty($_['filters']['keyword'])){
  142. $query .= ' AND label LIKE ?';
  143. $data[] = '%'.$_['filters']['keyword'].'%';
  144. }
  145. //Recherche avancée
  146. if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('category','creator','created','ip'),$query,$data);
  147. //Tri des colonnes
  148. if(isset($_['sort']))
  149. sort_secure_query($_['sort'],array('label','ip','created','category','creator'),$query,$data);
  150. else
  151. $query .= ' ORDER BY created DESC, id DESC ';
  152. //Pagination
  153. $response['pagination'] = Log::paginate(100,(!empty($_['page'])?$_['page']:0),$query,$data);
  154. foreach(Log::staticQuery($query,$data,true) as $log){
  155. $log->created = date('d/m/Y H:i:s',$log->created);
  156. if(!empty($_['keyword'])){
  157. $log->label = preg_replace_callback('|(.*)('.$_['keyword'].')(.*)|i', function($matches){
  158. return $matches[1].'<mark>'.$matches[2].'</mark>'.$matches[3];
  159. }, $log->label);
  160. }
  161. //evite les json encode crash lorsque la chaine contient des caractères spéciaux non utf-8
  162. $log->label = htmlentities($log->label);
  163. $response['rows'][] = $log;
  164. }
  165. });
  166. break;
  167. /** PLUGINS **/
  168. case 'search_plugin':
  169. Action::write(function(&$response){
  170. global $myUser,$_;
  171. User::check_access('plugin','read');
  172. foreach(Plugin::getAll() as $plugin){
  173. $plugin->folder = array('name'=>$plugin->folder,'path'=>$plugin->path());
  174. $response['rows'][] = $plugin;
  175. }
  176. });
  177. break;
  178. case 'change_plugin_state':
  179. Action::write(function(&$response){
  180. global $myUser,$_;
  181. User::check_access('plugin','configure');
  182. $plugin = Plugin::getById($_['plugin']);
  183. if($_['state']){
  184. $states = Plugin::states();
  185. $missingRequire = array();
  186. foreach($plugin->require as $require=>$version):
  187. $req = Plugin::getById($require);
  188. if($req == null || $req==false || !$req->state || $req->version!=$version)
  189. $missingRequire[]= $require.' - '.$version;
  190. endforeach;
  191. if(count($missingRequire)!=0) throw new Exception("Plugins pré-requis non installés : ".implode(',',$missingRequire));
  192. }
  193. Plugin::state($_['plugin'],$_['state']);
  194. //TODO - mettre en place un timeout - core_reference();
  195. Log::put(($_['state']?'Activation':'Désactivation')." du plugin ".$_['plugin'],'Plugin');
  196. });
  197. break;
  198. /** LIEN ETABLISSEMENT / PLUGIN **/
  199. case 'search_firm_plugin':
  200. Action::write(function(&$response){
  201. global $myUser,$_;
  202. User::check_access('plugin','configure');
  203. if(!isset($_['firm'])) throw new Exception("Etablissement non spécifié");
  204. $wholePlugins = array();
  205. if($_['firm'] == '0'){
  206. foreach(Firm::loadAll() as $firm){
  207. foreach(Plugin::getAll(true) as $plugin){
  208. $wholePlugins[$plugin->id][$firm->id] = in_array($firm->id, $plugin->firms) ? 1 : 0;
  209. }
  210. }
  211. }
  212. foreach(Plugin::getAll(true) as $plugin){
  213. if($_['firm'] == '0'){
  214. $plugin->state = count(array_unique($wholePlugins[$plugin->id])) === 1 ? end($wholePlugins[$plugin->id]) : 2;
  215. }else{
  216. $plugin->state = in_array($_['firm'], $plugin->firms) ? 1 : 0;
  217. }
  218. $response['rows'][] = $plugin;
  219. }
  220. });
  221. break;
  222. case 'toggle_firm_plugin':
  223. Action::write(function(&$response){
  224. global $myUser,$_;
  225. User::check_access('plugin','configure');
  226. foreach(Firm::loadAll() as $firm){
  227. if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
  228. $states = Plugin::states();
  229. $firms = $states[$_['plugin']];
  230. $key = array_search($firm->id, $firms);
  231. if($_['state']==0 && $key !== false){
  232. unset($firms[$key]);
  233. }else if($_['state']==1 && $key === false){
  234. $firms[] = $firm->id;
  235. }
  236. $states[$_['plugin']] = array_values($firms);
  237. Plugin::states($states);
  238. }
  239. });
  240. break;
  241. /** ETABLISSEMENT */
  242. case 'select_firm':
  243. global $myUser,$_,$myFirm;
  244. try{
  245. if(!$myUser->haveFirm( $_['firm'])) throw new Exception("Vous n'avez pas accès à cet établissement");
  246. $myFirm = Firm::getById($_['firm']);
  247. $_SESSION['firm'] = serialize($myFirm);
  248. $myUser->preference('default_firm',$myFirm->id);
  249. $myUser->loadRights();
  250. $_SESSION['currentUser'] = serialize($myUser);
  251. header('location: index.php');
  252. }catch(Exception $e){
  253. header('location: index.php?error='.urlencode($e->getMessage()));
  254. }
  255. break;
  256. case 'search_firm':
  257. Action::write(function(&$response){
  258. global $myUser,$_;
  259. User::check_access('firm','read');
  260. foreach(Firm::loadAll()as $firm){
  261. $row = $firm->toArray();
  262. $row['address'] = $firm->address();
  263. $response['rows'][] = $row;
  264. }
  265. });
  266. break;
  267. case 'firm_logo_download':
  268. global $myUser,$_;
  269. try {
  270. File::downloadFile(File::dir().Firm::logo_path().$_['firm'].'.'.$_['extension']);
  271. } catch(Exception $e) {
  272. File::downloadFile('img/default-image.png');
  273. }
  274. break;
  275. case 'firm_logo_delete':
  276. Action::write(function(&$response){
  277. global $myUser,$_;
  278. User::check_access('firm','edit');
  279. $firm = Firm::provide();
  280. if(!$firm) throw new Exception("Établissement non identifié");
  281. foreach (glob(__ROOT__.FILE_PATH.Firm::logo_path().$firm->id.".*") as $filename)
  282. unlink($filename);
  283. if(!file_exists(__ROOT__.FILE_PATH.Firm::logo_path().'.thumbnails')) return;
  284. foreach (glob(__ROOT__.FILE_PATH.Firm::logo_path().'.thumbnails'.SLASH.$firm->id.".*") as $filename) {
  285. unlink($filename);
  286. }
  287. });
  288. break;
  289. case 'save_firm':
  290. global $myUser,$_;
  291. try{
  292. User::check_access('firm','edit');
  293. $firm = Firm::provide();
  294. $firm->fromArray($_);
  295. if(empty($firm->label)) throw new Exception("Vous devez remplir au moins le libellé de l'entreprise");
  296. $firm->save();
  297. //Ajout de l'image à la base de media
  298. if(!empty($_FILES['logo']) && $_FILES['logo']['size']!=0 ){
  299. foreach (glob(Firm::logo_path().$firm->id.".*") as $filename) {
  300. unlink($filename);
  301. }
  302. $logo = File::upload('logo',Firm::logo_path().$firm->id.'.{{ext}}',1048576,array('jpg','png','jpeg'));
  303. Image::resize($logo['absolute'],200,200);
  304. }
  305. Log::put("Ajout/Modification de l'établissement ".$firm->toText(),'Etablissement');
  306. header('location: setting.php?section=firm&success=Établissement enregistré');
  307. }catch(Exception $e){
  308. header('location: firm.php?id='.$firm->id.'&error='.$e->getMessage());
  309. }
  310. break;
  311. case 'delete_firm':
  312. Action::write(function(&$response){
  313. global $myUser,$_;
  314. User::check_access('firm','delete');
  315. $firm =Firm::getById($_['id']);
  316. Firm::deleteById($_['id']);
  317. $states = Plugin::states();
  318. foreach ($states as $plugin => $firms) {
  319. $key = array_search($_['id'], $firms);
  320. if($key === false) continue;
  321. unset($firms[$key]);
  322. $states[$plugin] = array_values($firms);
  323. }
  324. Plugin::states($states);
  325. UserFirmRank::delete(array('firm'=>$_['id']));
  326. Right::delete(array('firm'=>$_['id']));
  327. Log::put("Suppression de l'établissement ".$firm->toText(),'Etablissement');
  328. });
  329. break;
  330. /** LIEN ETABLISSEMENT / UTILISATEUR / RANG **/
  331. case 'search_userfirmrank':
  332. Action::write(function(&$response){
  333. global $myUser,$_;
  334. User::check_access('firm','read');
  335. if($_['firm'] == 0)
  336. foreach(Firm::loadAll() as $firm)
  337. $firms[] = $firm->id;
  338. else
  339. $firms[] = $_['firm'];
  340. $users = array();
  341. foreach(User::getAll(false) as $user)
  342. $users[$user->login] = $user;
  343. foreach(UserFirmRank::staticQuery("SELECT *, ufr.id id, u.id uid, r.label rank, f.label firm
  344. FROM {{table}} ufr
  345. LEFT JOIN ".User::tableName()." u ON ufr.user=u.login
  346. LEFT JOIN ".Rank::tableName()." r ON r.id=ufr.rank
  347. LEFT JOIN ".Firm::tableName()." f ON f.id=ufr.firm
  348. WHERE ufr.firm IN ('".implode("','",$firms)."')",array(),false) as $userFirmRank){
  349. $user = isset($users[$userFirmRank['user']]) ? $users[$userFirmRank['user']] : new User();
  350. // Petit trick pour l'affichage mustache
  351. if($user->superadmin != 1) $userFirmRank['superadmin'] = null;
  352. $userFirmRank['avatar'] = $user->getAvatar();
  353. $userFirmRank['password'] = '';
  354. $userFirmRank['user'] = $user;
  355. $response['rows'][] = $userFirmRank;
  356. }
  357. });
  358. break;
  359. case 'save_userfirmrank':
  360. Action::write(function(&$response){
  361. global $myUser,$_;
  362. User::check_access('firm','edit');
  363. if(!isset($_['firm'])) throw new Exception('Champ "Établissement" obligatoire');
  364. if(!isset($_['user']) || empty($_['user'])) throw new Exception('Champ "Utilisateur" obligatoire');
  365. if(!isset($_['rank']) || empty($_['rank'])) throw new Exception('Champ "Rang" obligatoire');
  366. foreach(Firm::loadAll() as $firm){
  367. if($_['firm'] != 0 && $_['firm'] != $firm->id) continue;
  368. $userFirmRank = UserFirmRank::provide();
  369. $exist = is_null($userFirmRank->id) || $_['firm'] == 0 ? UserFirmRank::rowCount(array('user'=>$_['user'],'firm'=>$firm->id,'rank'=>$_['rank'])) : UserFirmRank::rowCount(array('id:!='=>$userFirmRank->id,'user'=>$_['user'],'firm'=>$firm->id,'rank'=>$_['rank']));
  370. if($exist > 0) throw new Exception("Ce rang est déja défini pour cet utilisateur et l'établissement ".$firm->label);
  371. $userFirmRank->fromArray($_);
  372. $userFirmRank->firm = $firm->id;
  373. $userFirmRank->save();
  374. $response['success'][] = $firm->label;
  375. }
  376. });
  377. break;
  378. case 'edit_userfirmrank':
  379. Action::write(function(&$response){
  380. global $myUser,$_;
  381. User::check_access('firm','edit');
  382. $userFirmRank = UserFirmRank::getById($_['id']);
  383. $response = $userFirmRank;
  384. });
  385. break;
  386. case 'delete_userfirmrank':
  387. Action::write(function(&$response){
  388. global $myUser,$_,$conf;
  389. User::check_access('firm','delete');
  390. $userFirmRank = UserFirmRank::provide();
  391. $user = User::byLogin($userFirmRank->user);
  392. if($user->preference('default_firm') == $userFirmRank->firm)
  393. UserPreference::delete(array('user'=>$user->login, 'key'=>'default_firm'));
  394. UserFirmRank::deleteById($_['id']);
  395. });
  396. break;
  397. /** UTILISATEURS **/
  398. case 'search_user':
  399. Action::write(function(&$response){
  400. global $myUser,$_;
  401. User::check_access('user','read');
  402. foreach(User::getAll() as $user){
  403. if($user->state == User::INACTIVE) continue;
  404. $user->avatar = $user->getAvatar();
  405. $response['rows'][] = $user;
  406. }
  407. });
  408. break;
  409. case 'user_autocomplete':
  410. Action::write(function(&$response){
  411. global $myUser,$_;
  412. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  413. $response['rows'] = array();
  414. if($_['keyword'] == '') return;
  415. if(in_array('user', $_['data']['types'])){
  416. foreach(User::getAll() as $user){
  417. if(preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->fullName())) || preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', $user->login)){
  418. $response['rows'][] = array(
  419. 'name'=>$user->fullName(),
  420. 'id'=>$user->login,
  421. 'mail'=>$user->mail,
  422. 'type'=>'user',
  423. 'avatar'=>$user->getAvatar(),
  424. 'function'=>$user->function
  425. );
  426. }
  427. }
  428. }
  429. if( in_array('rank', $_['data']['types']) ){
  430. foreach(Rank::staticQuery('SELECT * FROM {{table}} WHERE label LIKE ?',array('%'.$_['keyword'].'%'),true) as $rank){
  431. $response['rows'][] = array(
  432. 'name'=>$rank->label,
  433. 'id'=>$rank->id,
  434. 'type'=>'rank',
  435. 'description'=>$rank->description,
  436. );
  437. }
  438. }
  439. });
  440. break;
  441. case 'user_by_uid':
  442. Action::write(function(&$response){
  443. global $myUser,$_;
  444. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  445. $response['users'] = array();
  446. $ranks = array();
  447. $users = array();
  448. foreach ($_['uids'] as $uid) {
  449. if(is_numeric($uid)){
  450. $ranks[] = $uid;
  451. continue;
  452. }
  453. //user
  454. $item = User::byLogin($uid);
  455. if(!$item) continue;
  456. $row = $item->toArray();
  457. $row['fullname'] = $item->fullName();
  458. $row['type'] = 'user';
  459. $row['uid'] = $item->login;
  460. unset($row['password']);
  461. unset($row['token']);
  462. $response['users'][$row['uid']] = $row;
  463. }
  464. //rank
  465. foreach(Rank::loadAll(array('id:IN'=>implode(',',$ranks))) as $item){
  466. $row = $item->toArray();
  467. $row['fullname'] = $item->label;
  468. $row['type'] = 'rank';
  469. $row['uid'] = $item->id;
  470. $response['users'][$row['uid']] = $row;
  471. }
  472. });
  473. break;
  474. case 'account_lost_password':
  475. Action::write(function(&$response){
  476. global $myUser,$myFirm,$_,$conf;
  477. if(!isset($_['mail']) || empty($_['mail']) || !check_mail($_['mail'])) throw new Exception("Adresse e-mail non spécifiée ou incorrecte");
  478. foreach(User::getAll() as $user){
  479. if(strtolower($user->mail) == strtolower($_['mail'])){
  480. $token = sha1(time().mt_rand(0,1000));
  481. $linkToken = base64_encode($user->login.'::'.$token);
  482. UserPreference::delete(array('user'=>$user->login,'key'=>'lost_password'));
  483. $saved = new UserPreference();
  484. $saved->user = $user->login;
  485. $saved->key = 'lost_password';
  486. $saved->value = $token;
  487. $saved->save();
  488. $mail = new Mail();
  489. $mail->title="Mot de passe perdu";
  490. $link = ROOT_URL.'/account.lost.php?token='.$linkToken;
  491. $mail->message = "
  492. Vous recevez cet e-mail parce que quelqu'un a fait une demande de changement de mot de passe pour votre compte sur ".ROOT_URL.".
  493. <br/>Si il s'agit bien de vous, <a href='".$link."'>Cliquez ici pour changer votre mot de passe</a> ou copiez collez le lien suivant dans votre navigateur préféré.
  494. <br/>Si vous n'êtes pas à l'origine de ce mail, aucune action n'est requise.";
  495. $mail->recipients['to'][] = $user->mail;
  496. $mail->send();
  497. return;
  498. }
  499. }
  500. throw new Exception("Aucun compte ne correspond à l'e-mail spécifié dans notre base, veuillez contacter un administrateur pour modifier votre mot de passe.");
  501. });
  502. break;
  503. case 'account_save':
  504. Action::write(function(&$response){
  505. global $myUser,$myFirm,$_;
  506. User::check_access('account','edit');
  507. if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
  508. if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Adresse mail obligatoire');
  509. $userForm = new User();
  510. $userForm->fromArray($_);
  511. if(empty($userForm->login))
  512. if(!isset($_['password']) || empty($_['password'])) throw new Exception("Mot de passe obligatoire");
  513. //Vérifications & formattage des données
  514. $userForm->firstname = ucfirst($userForm->firstname);
  515. $userForm->name = mb_strtoupper($userForm->name);
  516. if(!empty($userForm->mail) && !check_mail($userForm->mail)) throw new Exception('Le format du champ "Mail" est invalide');
  517. if(!empty($userForm->phone) && !check_phone_number($userForm->phone)) throw new Exception('Le format du champ "Téléphone fixe" est invalide');
  518. $userForm->phone = !empty($userForm->phone) ? normalize_phone_number($userForm->phone) : '';
  519. if(!empty($userForm->mobile) && !check_phone_number($userForm->mobile)) throw new Exception('Le format du champ "Téléphone mobile" est invalide');
  520. $userForm->mobile = !empty($userForm->mobile) ? normalize_phone_number($userForm->mobile) : '';
  521. if($_['password']!=$_['password2']) throw new Exception("Mot de passe et confirmation non similaires");
  522. //Recuperation des hash des precedents passwords
  523. $chain = explode('-',$myUser->preference('account_chain'));
  524. if(!empty(trim($_['password']))) {
  525. $hashedPassword = sha1(md5('$a1u7'.$_['password'].'$y$1'));
  526. if(in_array($hashedPassword, $chain) && !$myUser->superadmin) throw new Exception("Vous devez choisir un mot de passe différent des précédents");
  527. if(count($chain)==10) array_shift($chain);
  528. $chain[] = $hashedPassword;
  529. $myUser->preference('account_chain',implode('-',$chain));
  530. }
  531. //save des comptes type db
  532. if($myUser->origin == ''){
  533. if(!empty(trim($_['password']))){
  534. $passwordErrors = User::check_password_format($_['password']);
  535. if(count($passwordErrors)!=0 && !$myUser->superadmin) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : ".implode(',',$passwordErrors));
  536. if(($_['password']==$myUser->login || $_['password']==$myUser->mail) && !$myUser->superadmin) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant ou à l'e-mail");
  537. $myUser->password = sha1(md5($_['password']));
  538. }
  539. $myUser->firstname = $userForm->firstname;
  540. $myUser->name = $userForm->name;
  541. $myUser->mail = $userForm->mail;
  542. $myUser->function = $userForm->function;
  543. $myUser->phone = $userForm->phone;
  544. $myUser->mobile = $userForm->mobile;
  545. $myUser->manager = is_object($myUser->manager) ? $myUser->manager->login : $myUser->manager;
  546. $myUser->save();
  547. if($myUser->superadmin == 1){
  548. foreach(Firm::loadAll() as $firm)
  549. $firms[$firm->id] = $firm;
  550. $myUser->setFirms($firms);
  551. }
  552. }
  553. $myUser->preference('passwordTime',time());
  554. //save de l'avatar
  555. if(!empty($_FILES['avatar']) && $_FILES['avatar']['size']!=0 ){
  556. foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.$myUser->login.".*") as $filename) {
  557. unlink($filename);
  558. }
  559. $logo = File::upload('avatar',AVATAR_PATH.$myUser->login.'.{{ext}}',104857060,array('jpg','png','jpeg','gif'));
  560. Image::resize($logo['absolute'],150,150);
  561. }
  562. //save des comptes types plugin
  563. Plugin::callHook("user_save",array(&$myUser,$userForm,&$response));
  564. $myUser->loadRights();
  565. unset($_SESSION['users']);
  566. $_SESSION['currentUser'] = serialize($myUser);
  567. });
  568. break;
  569. case 'account_avatar_download':
  570. global $myUser,$_;
  571. try {
  572. $user = str_replace(array('..','/'),'',$_['user']);
  573. $extension = str_replace(array('..','/'),'',$_['extension']);
  574. File::downloadFile(File::dir().AVATAR_PATH.$user.'.'.$extension);
  575. } catch(Exception $e) {
  576. File::downloadFile('img/default-avatar.png');
  577. }
  578. break;
  579. case 'account_avatar_delete':
  580. Action::write(function(&$response){
  581. global $myUser,$_;
  582. $user = User::byLogin($_['login']);
  583. if(!$user) throw new Exception("Utilisateur non identifié");
  584. if($myUser->login!=$user->login && !$myUser->can('user', 'edit')) throw new Exception("Permissions insuffisantes",403);
  585. foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.$user->login.".*") as $filename) {
  586. unlink($filename);
  587. }
  588. if(!file_exists(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails')) return;
  589. foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails'.SLASH.$user->login.".*") as $filename) {
  590. unlink($filename);
  591. }
  592. });
  593. break;
  594. case 'save_user':
  595. Action::write(function(&$response){
  596. global $myUser,$_;
  597. User::check_access('user','edit');
  598. if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
  599. if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Le champ "Mail" est obligatoire');
  600. if(!check_mail($_['mail'])) throw new Exception('Le format du champ "Mail" est invalide');
  601. if($_['password']!=$_['password2']) throw new Exception("Mot de passe et confirmation non similaires");
  602. $user = User::byLogin($_['login']);
  603. $user = $user ? $user : new User();
  604. if($user->id == 0)
  605. if(!isset($_['password']) || empty($_['password'])) throw new Exception("Mot de passe obligatoire");
  606. if(!empty(trim($_['password']))){
  607. $passwordErrors = User::check_password_format(html_entity_decode($_['password']));
  608. if(count($passwordErrors)!=0) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : ".implode(',',$passwordErrors));
  609. if($_['password']==$_['login'] || $_['password']==$_['mail'] ) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant ou à l'e-mail");
  610. $user->password = sha1(md5($_['password']));
  611. $user->preference('passwordTime',time());
  612. }
  613. $user->firstname = ucfirst($_['firstname']);
  614. $user->name = mb_strtoupper($_['name']);
  615. $user->mail = $_['mail'];
  616. $user->state = User::ACTIVE;
  617. if(isset($_['manager'])) $user->manager = $_['manager'];
  618. //Check si un user n'existe pas déjà avec ce login
  619. if(empty($user->id) && User::load(array('login'=>$_['login']))) throw new Exception("Un utilisateur existe déjà avec cet identifiant");
  620. if(!$user->login) $user->login = $_['login'];
  621. $user->save();
  622. unset($_SESSION['users']);
  623. $user->password = '';
  624. Log::put("Création/Modification de l'utilisateur ".$user->toText(),'Utilisateur');
  625. });
  626. break;
  627. case 'edit_user':
  628. Action::write(function(&$response){
  629. global $myUser,$_;
  630. User::check_access('user','edit');
  631. $user = User::byLogin($_['login']);
  632. if(!$user) throw new Exception("Utilisateur non identifié");
  633. $user->password = '';
  634. $response = $user;
  635. });
  636. break;
  637. case 'delete_user':
  638. Action::write(function(&$response){
  639. global $myUser,$_;
  640. User::check_access('user','delete');
  641. $user = User::byLogin($_['login']);
  642. if(!$user) throw new Exception("Utilisateur non identifié");
  643. if($user->superadmin == 1) throw new Exception("Vous ne pouvez pas supprimer le compte super admin");
  644. if($user->login == $myUser->login) throw new Exception("Vous ne pouvez pas supprimer votre propre compte");
  645. $user = User::getById($user->id);
  646. $user->state = User::INACTIVE;
  647. $user->save();
  648. foreach(UserFirmRank::loadAll(array('user'=>$user->login)) as $ufrLink)
  649. UserFirmRank::deleteById($ufrLink->id);
  650. unset($_SESSION['users']);
  651. Log::put("Suppression de l'utilisateur ".$user->toText(),'Utilisateur');
  652. });
  653. break;
  654. /** DROITS **/
  655. case 'search_right':
  656. Action::write(function(&$response){
  657. global $myUser,$_;
  658. User::check_access('rank','edit');
  659. if(!isset($_['firm'])) throw new Exception("Etablissement non spécifié");
  660. $wholeRights = array();
  661. $sections = array();
  662. Plugin::callHook('section',array(&$sections));
  663. foreach(Firm::loadAll() as $firm){
  664. if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
  665. $rights = Right::loadAll(array('rank'=>$_['rank'],'firm'=>$firm->id));
  666. $rightsTable = array();
  667. foreach($rights as $right)
  668. $rightsTable[$right->section] = $right;
  669. if($_['firm'] == '0'){
  670. foreach($sections as $section=>$description) {
  671. $right = isset($rightsTable[$section])? $rightsTable[$section] : new Right();
  672. $wholeRights[$section]['read'][$firm->id] = (int)$right->read;
  673. $wholeRights[$section]['edit'][$firm->id] = (int)$right->edit;
  674. $wholeRights[$section]['delete'][$firm->id] = (int)$right->delete;
  675. $wholeRights[$section]['configure'][$firm->id] = (int)$right->configure;
  676. }
  677. }
  678. }
  679. foreach ($sections as $section=>$description) {
  680. if($_['firm'] == '0'){
  681. $read = count(array_unique($wholeRights[$section]['read'])) === 1 ? end($wholeRights[$section]['read']) : 2;
  682. $edit = count(array_unique($wholeRights[$section]['edit'])) === 1 ? end($wholeRights[$section]['edit']) : 2;
  683. $delete = count(array_unique($wholeRights[$section]['delete'])) === 1 ? end($wholeRights[$section]['delete']) : 2;
  684. $configure = count(array_unique($wholeRights[$section]['configure'])) === 1 ? end($wholeRights[$section]['configure']) : 2;
  685. }else{
  686. $right = isset($rightsTable[$section])? $rightsTable[$section] : new Right();
  687. $read = $right->read;
  688. $edit = $right->edit;
  689. $delete = $right->delete;
  690. $configure = $right->configure;
  691. }
  692. $response['rows'][] = array(
  693. 'section'=>$section,
  694. 'description'=>$description,
  695. 'read'=>(int)$read,
  696. 'edit'=>(int)$edit,
  697. 'delete'=>(int)$delete,
  698. 'configure'=>(int)$configure
  699. );
  700. usort($response['rows'], function($a, $b){
  701. return strcmp($a['section'], $b['section']);
  702. });
  703. }
  704. });
  705. break;
  706. case 'toggle_right':
  707. Action::write(function(&$response){
  708. global $myUser,$_,$myFirm;
  709. User::check_access('rank','edit');
  710. if(!isset($_['section']) || empty($_['section'])) throw new Exception("Droit non spécifié");
  711. if(!isset($_['rank']) || empty($_['rank'])) throw new Exception("Rang non spécifié");
  712. if(!isset($_['right']) || empty($_['right'])) throw new Exception("Droit non spécifié");
  713. if(!isset($_['firm'])) throw new Exception("Etablissement non spécifié");
  714. foreach(Firm::loadAll() as $firm){
  715. if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
  716. $item = Right::load(array('rank'=>$_['rank'],'firm'=>$firm->id,'section'=>$_['section']));
  717. $item = !$item ? new Right() : $item ;
  718. $item->rank = $_['rank'];
  719. $item->firm = $firm->id;
  720. $item->section = $_['section'];
  721. $item->{$_['right']} = $_['state'];
  722. $item->save();
  723. $myUser->loadRights();
  724. $_SESSION['currentUser'] = serialize($myUser);
  725. }
  726. });
  727. break;
  728. /** RANGS **/
  729. case 'search_rank':
  730. Action::write(function(&$response){
  731. global $myUser,$_;
  732. User::check_access('rank','read');
  733. foreach(Rank::loadAll() as $rank){
  734. $row = $rank->toArray(true);
  735. $response['rows'][] = $row;
  736. }
  737. });
  738. break;
  739. case 'save_rank':
  740. Action::write(function(&$response){
  741. global $myUser,$_;
  742. User::check_access('rank','edit');
  743. if(!isset($_['label']) || empty($_['label'])) throw new Exception("Libellé obligatoire");
  744. $item = isset($_['id']) && !empty($_['id']) ? Rank::getById($_['id']) : new Rank();
  745. $item->label = $_['label'];
  746. $item->description = $_['description'];
  747. $item->save();
  748. Log::put("Ajout/Modification du rang ".$item->toText(),'Rang');
  749. });
  750. break;
  751. case 'edit_rank':
  752. Action::write(function(&$response){
  753. global $myUser,$_;
  754. User::check_access('rank','edit');
  755. $response = Rank::getById($_['id']);
  756. });
  757. break;
  758. case 'delete_rank':
  759. Action::write(function(&$response){
  760. global $myUser,$_;
  761. User::check_access('rank','delete');
  762. $rank = Rank::getById($_['id']);
  763. Rank::deleteById($_['id']);
  764. Log::put("Suppression du rang ".$rank->toText(),'Rang');
  765. });
  766. break;
  767. /** LISTES **/
  768. case 'search_dictionnary':
  769. Action::write(function(&$response){
  770. global $myUser,$_;
  771. User::check_access('dictionnary','read');
  772. foreach(Dictionnary::loadAll(array('parent'=>$_['parent'], 'state'=>Dictionnary::ACTIVE), array(' label ASC ')) as $item){
  773. $item->label = html_entity_decode($item->label);
  774. $response['rows'][] = $item;
  775. }
  776. });
  777. break;
  778. case 'save_dictionnary':
  779. Action::write(function(&$response){
  780. global $myUser,$_;
  781. User::check_access('dictionnary','edit');
  782. if(!isset($_['label']) || empty($_['label'])) throw new Exception("Libellé obligatoire");
  783. if(!is_numeric($_['parent'])){
  784. if($myUser->superadmin == 1)
  785. $_['parent'] = 0;
  786. else
  787. throw new Exception("Veuillez sélectionner une liste");
  788. }
  789. $item = Dictionnary::provide();
  790. $item->label = $_['label'];
  791. $item->parent = $_['parent'];
  792. $item->state = Dictionnary::ACTIVE;
  793. if(isset($_['slug']) && !empty($_['slug'])) {
  794. $parameters = array('slug'=>$_['slug'], 'state'=>Dictionnary::ACTIVE);
  795. if(isset($item->id) && !empty($item->id)) $parameters['id:!='] = $item->id;
  796. if(Dictionnary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé");
  797. }
  798. $item->slug = $_['slug'];
  799. if(isset($_['sublistlabel'])) $item->sublistlabel = $_['sublistlabel'];
  800. $item->save();
  801. Log::put("Création/Modification de l'item de liste ".$item->toText(),'Liste');
  802. });
  803. break;
  804. case 'edit_dictionnary':
  805. Action::write(function(&$response){
  806. global $myUser,$_;
  807. User::check_access('dictionnary','edit');
  808. $dictionnary = Dictionnary::getById($_['id']);
  809. $response = $dictionnary->toArray(true);
  810. });
  811. break;
  812. case 'delete_dictionnary':
  813. Action::write(function(&$response){
  814. global $myUser,$_;
  815. User::check_access('dictionnary','delete');
  816. if(!isset($_['id']) || empty($_['id'])) throw new Exception("Aucun identifiant spécifié");
  817. $item = Dictionnary::getById($_['id']);
  818. $item->state = Dictionnary::INACTIVE;
  819. $item->save();
  820. Dictionnary::change(array('state'=>Dictionnary::INACTIVE), array('parent'=>$item->id));
  821. Log::put("Suppression de la liste et des sous-listes associées".$item->toText(), 'Liste');
  822. });
  823. break;
  824. case 'get_parent_dictionnary':
  825. Action::write (function (&$response){
  826. global $myUser,$_;
  827. $selected = Dictionnary::loadAll(array("id"=>$_['selected']));
  828. foreach ($selected as $item) {
  829. if($item->parent == 0) {
  830. $parents = Dictionnary::loadAll(array("parent"=>$item->parent), array(' label ASC '));
  831. } else {
  832. $tmpParent = Dictionnary::loadAll(array("id"=>$item->parent), array(' label ASC '));
  833. $parents = Dictionnary::loadAll(array("parent"=>$tmpParent[0]->parent), array(' label ASC '));
  834. }
  835. $parentId = !empty($tmpParent) ? $tmpParent[0]->id : '';
  836. $response['rows'][] = array(
  837. 'parents'=> $parents,
  838. 'currentId'=> $item->id,
  839. 'parentId'=> $parentId,
  840. 'label'=> $item->label
  841. );
  842. }
  843. });
  844. break;
  845. case 'load_dictionnary_component':
  846. Action::write (function (&$response){
  847. global $myUser,$_;
  848. $dictionnaries = array();
  849. if(isset($_['slug']) && $_['slug'] != "")
  850. $dictionnaries = Dictionnary::load(array("slug"=>$_['slug']));
  851. if(isset($_['parentId']) && $_['parentId'] != "")
  852. $dictionnaries = Dictionnary::getById($_['parentId']);
  853. if($dictionnaries) {
  854. $children = Dictionnary::childs(array('id'=>$dictionnaries->id));
  855. $dictionnaries->childs = $children;
  856. }
  857. if(isset($_['value']) && $_['value'] != "" && $_['value'] != 0){
  858. if(!$_['hierarchy']){
  859. foreach ($dictionnaries->childs as $i => $child) {
  860. if($child->id == $_['value']) $child->selected = true;
  861. $dictionnaries->childs[$i] = $child;
  862. }
  863. } else {
  864. $dictionnaries = Dictionnary::hierarchy($_['value']);
  865. }
  866. }
  867. $response['content'] = $dictionnaries;
  868. });
  869. break;
  870. /* Composant tag list */
  871. case 'tag_list_autocomplete':
  872. Action::write(function(&$response){
  873. global $myUser,$_;
  874. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  875. $response['rows'] = array();
  876. foreach(Dictionnary::staticQuery('SELECT * FROM {{table}} WHERE parent=(SELECT id from {{table}} WHERE slug= ? LIMIT 1) AND label LIKE ?',array($_['data']['parent'],'%'.$_['keyword'].'%'),true) as $item){
  877. $response['rows'][] = array(
  878. 'name'=>$item->label,
  879. 'id'=>$item->id,
  880. 'slug'=>$item->slug
  881. );
  882. }
  883. });
  884. break;
  885. case 'tag_list_by_id':
  886. Action::write(function(&$response){
  887. global $myUser,$_;
  888. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  889. $response['tags'] = array();
  890. foreach (explode(',',$_['id']) as $id) {
  891. $item = Dictionnary::getById($id);
  892. $item = !$item ? new Dictionnary(): $item;
  893. $row = $item->toArray();
  894. $row['name'] = $item->label;
  895. $row['slug'] = $item->slug;
  896. $row['id'] = $item->id;
  897. $response['tags'][] = $row;
  898. }
  899. });
  900. break;
  901. /** TABLEAU DE DICTIONNARY */
  902. case 'dictionnary_table_search':
  903. Action::write(function(&$response){
  904. global $myUser,$_;
  905. if(!is_numeric($_['id'])) throw new Exception("Aucun identifiant de liste spécifié");
  906. $dic = Dictionnary::getById($_['id']);
  907. $response['dictionnary'] = $dic->toArray(true);
  908. foreach (Dictionnary::childs(array('slug'=>$dic->slug)) as $child) {
  909. $response['rows'][] = $child->toArray(true);
  910. }
  911. });
  912. break;
  913. case 'dictionnary_table_save':
  914. Action::write(function(&$response){
  915. global $myUser,$_;
  916. if(!isset($_['label']) || empty($_['label'])) throw new Exception("Aucun libellé de liste renseigné");
  917. if(!isset($_['id']) && !isset($_['list'])) throw new Exception("Aucun identifiant de liste ou de parent de liste trouvé");
  918. $dic = isset($_['id']) && !empty($_['id'])? Dictionnary::getById($_['id']) : new Dictionnary();
  919. $dic->parent = $_['list'];
  920. $dic->label = $_['label'];
  921. if(isset($_['slug']) && !empty($_['slug'])) {
  922. $parameters = array('slug'=>$_['slug'], 'state'=>Dictionnary::ACTIVE);
  923. if(isset($dic->id) && !empty($dic->id)) $parameters['id:!='] = $dic->id;
  924. if(Dictionnary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé");
  925. }
  926. $dic->slug = $_['slug'];
  927. $dic->state = Dictionnary::ACTIVE;
  928. $dic->save();
  929. });
  930. break;
  931. /** CRONTAB */
  932. case 'cron':
  933. try{
  934. if(php_sapi_name() !== 'cli') throw new Exception("Le cron ne peut être executé qu'en mode CLI depuis le serveur");
  935. Plugin::callHook('cron');
  936. }catch(Exception $e){
  937. file_put_contents(__DIR__.SLASH.'cron.log',date('d-m-Y H:i').' | '.$e->getMessage().PHP_EOL,FILE_APPEND);
  938. }
  939. break;
  940. /** FILES & UPLOADS */
  941. //Gestion de l'upload temporaire (avant soumission d'un form)
  942. case 'upload_temporary_file':
  943. Action::write(function(&$response){
  944. global $myUser,$_;
  945. User::check_access('file','edit');
  946. $response['previews'] = array();
  947. File::clear_temp();
  948. for ($i=0; $i<count($_FILES['document']['name']);$i++) {
  949. $tempPath = File::temp().basename($_FILES['document']['tmp_name'][$i]);
  950. move_uploaded_file($_FILES['document']['tmp_name'][$i], $tempPath);
  951. $response['previews'][] = array(
  952. 'path' => basename($_FILES['document']['tmp_name'][$i]),
  953. 'name' => $_FILES['document']['name'][$i],
  954. 'temporary' => true,
  955. 'url' => 'action.php?action=download_temporary_file&name='.$_FILES['document']['name'][$i].'&path='.basename($_FILES['document']['tmp_name'][$i]),
  956. 'icon' => getExtIcon(getExt($_FILES['document']['name'][$i]))
  957. );
  958. }
  959. });
  960. break;
  961. case 'download_temporary_file':
  962. global $myUser,$_;
  963. User::check_access('file','read');
  964. File::downloadFile(File::temp().$_['path'],$_['name']);
  965. break;
  966. /** GENERAL SETTINGS **/
  967. case 'general_settings_save':
  968. Action::write(function(&$response){
  969. global $myUser, $_, $conf;
  970. User::check_access('setting_global','configure');
  971. //Durée de conservation des logs
  972. foreach(Log::staticQuery('SELECT DISTINCT category FROM {{table}}',array(),true) as $log):
  973. $slug = slugify($log->category);
  974. $key = 'log_retention_time_'.$slug;
  975. if(!isset($_[$key])) continue;
  976. if($_[$key] == 0 || !is_numeric($_[$key])) $_[$key] = '';
  977. $conf->put($key,$_[$key]);
  978. endforeach;
  979. //Save du logo clair de l'application
  980. if(!empty($_FILES['logo']) && $_FILES['logo']['size']!=0 ){
  981. $logo = File::upload('logo','core'.SLASH.'logo.{{ext}}', 1048576, array('jpg','png','jpeg'));
  982. Image::resize($logo['absolute'], 200, 200);
  983. Image::toPng($logo['absolute']);
  984. }
  985. //Save du logo sombre de l'application
  986. if(!empty($_FILES['logo_dark']) && $_FILES['logo_dark']['size']!=0 ){
  987. $logo = File::upload('logo_dark','core'.SLASH.'logo.dark.{{ext}}', 1048576, array('jpg','png','jpeg'));
  988. Image::resize($logo['absolute'], 200, 200);
  989. Image::toPng($logo['absolute']);
  990. }
  991. if(!empty($_FILES['favicon']) && $_FILES['favicon']['size']!=0 ){
  992. $logo = File::upload('favicon','core'.SLASH.'favicon.{{ext}}', 1048576, array('png'));
  993. Image::resize($logo['absolute'], 64, 64);
  994. Image::toPng($logo['absolute']);
  995. }
  996. //Gestion save des configuration générales
  997. foreach(Configuration::setting('configuration-global') as $key => $value){
  998. if(!is_array($value)) continue;
  999. $allowedSettings[] = $key;
  1000. }
  1001. foreach ($_ as $key => $value)
  1002. if(in_array($key, $allowedSettings)) $conf->put($key, $value);
  1003. //Politique de mot de passes
  1004. if(isset($_['password_format'])) $conf->put('password_format',$_['password_format']);
  1005. //Maintenance
  1006. if(isset($_['maintenance'])){
  1007. if($_['maintenance']){
  1008. if(file_exists('disabled.maintenance')) rename('disabled.maintenance', 'enabled.maintenance');
  1009. file_put_contents('enabled.maintenance', $_['maintenance-content']);
  1010. } else {
  1011. if(file_exists('enabled.maintenance')) rename('enabled.maintenance', 'disabled.maintenance');
  1012. file_put_contents('disabled.maintenance', $_['maintenance-content']);
  1013. }
  1014. }
  1015. });
  1016. break;
  1017. case 'general_reset_password_delay':
  1018. Action::write(function(&$response){
  1019. global $myUser, $_, $conf;
  1020. User::check_access('setting_global','configure');
  1021. foreach(User::getAll() as $user){
  1022. $user->preference('passwordTime',strtotime('01/01/1990'));
  1023. }
  1024. });
  1025. break;
  1026. //Récupération logo application générale
  1027. case 'general_logo_download':
  1028. global $_;
  1029. $variant = isset($_['variant']) && in_array($_['variant'], array('dark')) ? '.'.$_['variant'] : '';
  1030. $logoPath = File::dir().'core'.SLASH.'logo'.$variant.'.png';
  1031. $path = file_exists($logoPath) ? $logoPath : __ROOT__.SLASH.'img'.SLASH.'logo'.SLASH.'default-logo'.$variant.'.png';
  1032. File::downloadFile($path,'logo.png','image/png');
  1033. break;
  1034. //Suppression logo de l'application
  1035. case 'general_logo_delete':
  1036. Action::write(function(&$response){
  1037. global $myUser,$_;
  1038. User::check_access('setting_global','configure');
  1039. foreach (glob(File::dir().'core'.SLASH."logo.*") as $filename)
  1040. unlink($filename);
  1041. });
  1042. break;
  1043. //Récupération favicon application générale
  1044. case 'general_favicon_download':
  1045. $faviconPath = File::dir().'core'.SLASH.'favicon.png';
  1046. $path = file_exists($faviconPath) ? $faviconPath : __ROOT__.SLASH.'img'.SLASH.'logo'.SLASH.'default-favicon.png';
  1047. File::downloadFile($path,'favicon.png','image/png');
  1048. break;
  1049. //Suppression favicon de l'application
  1050. case 'general_favicon_delete':
  1051. Action::write(function(&$response){
  1052. global $myUser,$_;
  1053. User::check_access('setting_global','configure');
  1054. foreach (glob(File::dir().'core'.SLASH."favicon.*") as $filename)
  1055. unlink($filename);
  1056. });
  1057. break;
  1058. case 'user_impersonation':
  1059. try{
  1060. global $myUser,$myFirm,$_;
  1061. if(!$myUser->superadmin) throw new Exception("Seul le super administrateur peut exécuter cette fonctionnalité");
  1062. if(!isset($_['login'])) throw new Exception("Identifiant non spécifié");
  1063. unset($_SESSION['users']);
  1064. $user = new User();
  1065. $user = User::load(array('login' => $_['login']));
  1066. Plugin::callHook("user_login", array(&$user,$_['login'],null,true,true,true));
  1067. if($user!=false){
  1068. $user->ranks = empty($user->ranks) ? array() : $user->ranks;
  1069. $user->firms = empty($user->firms) ? array() : $user->firms;
  1070. $user->loadRanks();
  1071. $user->loadPreferences();
  1072. $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : key($user->firms);
  1073. $myFirm = isset($user->firms[$defaultFirm]) ? $user->firms[$defaultFirm]:reset($user->firms);
  1074. if(!isset($defaultFirm) || empty($defaultFirm)) throw new Exception("Ce compte n'est actif sur aucun établissement");
  1075. }
  1076. $user->loadRights();
  1077. if($user == false || empty($user->login)) throw new Exception("Utilisateur inexistant");
  1078. $myUser = $user;
  1079. $_SESSION['currentUser'] = serialize($myUser);
  1080. $_SESSION['firm'] = serialize($myFirm);
  1081. header('location: index.php?info='.rawurlencode('Connecté avec l\'utilisateur : '.$user->login));
  1082. } catch(Exception $e){
  1083. header('location: setting.php?section=user&error='.rawurlencode($e->getMessage()));
  1084. }
  1085. break;
  1086. /** CUSTOM API */
  1087. // pour obtenir un schema de toutes les api actives : http://url.com/api/schema?pretty
  1088. case 'api':
  1089. /* CORE API */
  1090. //Infos api
  1091. $api = new Api("core", "Api du coeur applicatif");
  1092. $api->route('infos','retourne les informations sur l\'environnement','GET',function($request,&$response){
  1093. global $myUser;
  1094. if(!$myUser->connected()) throw new Exception("Credentials are missing",401);
  1095. $repository = '';
  1096. if(file_exists(__DIR__.SLASH.'.git'.SLASH.'config')){
  1097. $stream = file_get_contents(__DIR__.SLASH.'.git'.SLASH.'config');
  1098. preg_match('|url = (.*\.fr)[:/]([^\n]*)|is', $stream,$match);
  1099. $repository = $match[2];
  1100. $repositoryUrl = preg_replace('|[^@]*@|i','http://',$match[1]).'/'.$match[2];
  1101. }
  1102. if(file_exists(__DIR__.SLASH.'.git'.SLASH.'refs'.SLASH.'heads'.SLASH.'master'))
  1103. $commitVersion = str_replace(array("\n","\r"),"",file_get_contents(__DIR__.SLASH.'.git'.SLASH.'refs'.SLASH.'heads'.SLASH.'master'));
  1104. $response['application']['label'] = PROGRAM_NAME;
  1105. $response['application']['version'] = SOURCE_VERSION;
  1106. $response['application']['versionning']['type'] = 'git';
  1107. $response['application']['versionning']['repository'] = $repository;
  1108. $response['application']['versionning']['repository_url'] = $repositoryUrl;
  1109. $response['application']['versionning']['commit_version'] = $commitVersion;
  1110. $response['application']['timezone'] = TIME_ZONE;
  1111. $response['php']['version'] = phpversion();
  1112. $response['apache']['version'] = apache_get_version();
  1113. $response['database']['type'] = BASE_SGBD;
  1114. $response['database']['version'] = Database::version();
  1115. $response['database']['host'] = BASE_HOST;
  1116. $response['os']['type'] = PHP_OS;
  1117. $response['os']['time'] = time();
  1118. });
  1119. //user api
  1120. $api->route('users','retourne la liste des utilisateurs du logiciel','GET',function($request,&$response){
  1121. global $myUser;
  1122. if(!$myUser->connected()) throw new Exception("Credentials are missing",401);
  1123. $response['users'] = array();
  1124. if(isset($request['parameters']['sort'])) throw new Exception("Sort is not implemented for users",501);
  1125. if(isset($request['parameters']['filter'])) throw new Exception("Filter is not implemented for users",501);
  1126. foreach (User::getAll() as $i=>$user) {
  1127. if(isset($request['parameters']['limit']) && $request['parameters']['limit']==$i) break;
  1128. $row = $user->toArray();
  1129. unset($row['password']);
  1130. unset($row['manager']);
  1131. $row['origin'] = !isset($row['id']) ? 'plugin': 'database';
  1132. $response['users'][] = $row;
  1133. }
  1134. });
  1135. $api->route('users/[userid]','ajoute/modifie un utilisateur du logiciel','PUT',function($request,&$response){
  1136. global $myUser;
  1137. if(!$myUser->connected()) throw new Exception("Credentials are missing",401);
  1138. $response['user'] = array();
  1139. //Création
  1140. $_ = $request['parameters'];
  1141. $form = json_decode($request['body'],true);
  1142. if(!$form) throw new Exception("Invalid JSON body",400);
  1143. User::check_access('user','edit');
  1144. if(!empty($request['pathes'])){
  1145. $user = User::byLogin($request['pathes'][0]);
  1146. if(empty($user->login)) throw new Exception("User not found", 404);
  1147. $response['code'] = 200; //Modifié
  1148. }else{
  1149. $user = new User();
  1150. if(!isset($form['login']) || empty($form['login'])) throw new Exception("Identifiant obligatoire",400);
  1151. if(!isset($form['password']) || empty($form['password'])) throw new Exception("Mot de passe obligatoire",400);
  1152. if(!isset($form['mail']) || empty($form['mail'])) throw new Exception('Le champ "Mail"est obligatoire',400);
  1153. //Check si un user n'existe pas déjà avec ce login
  1154. if(User::load(array('login'=>$form['login']))) throw new Exception("Un utilisateur existe déjà avec cet identifiant",400);
  1155. $user->login = $form['login'];
  1156. $response['code'] = 201; //Créé
  1157. }
  1158. if(!empty(trim($form['password']))){
  1159. $passwordErrors = User::check_password_format(html_entity_decode($form['password']));
  1160. if(count($passwordErrors)!=0) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : ".implode(',',$passwordErrors),400);
  1161. if($form['password']==$form['login'] || $form['password']==$form['mail'] ) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant ou à l'e-mail",400);
  1162. $user->password = sha1(md5($form['password']));
  1163. $user->preference('passwordTime',time());
  1164. }
  1165. if(isset($form['firstname'])) $user->firstname = ucfirst($form['firstname']);
  1166. if(isset($form['name'])) $user->name = mb_strtoupper($form['name']);
  1167. if(isset($form['mail'])) $user->mail = $form['mail'];
  1168. $user->state = User::ACTIVE;
  1169. if(isset($form['manager'])) $user->manager = $form['manager'];
  1170. $user->save();
  1171. Log::put("Création/Modification de l'utilisateur ".$user->toText(),'Utilisateur');
  1172. $response['user'] = array('id'=>$user->id,'login'=>$user->login);
  1173. });
  1174. //user api
  1175. $api->route('users/userid','Supprime un utilisateur du logiciel','DELETE',function($request,&$response){
  1176. global $myUser;
  1177. if(!$myUser->connected()) throw new Exception("Credentials are missing",401);
  1178. if(empty($request['pathes'])) throw new Exception("You must spcify user login", 400);
  1179. User::check_access('user','delete');
  1180. $user = User::byLogin($request['pathes'][0]);
  1181. if(!$user) throw new Exception("User not found",404);
  1182. if($user->superadmin == 1) throw new Exception("You can't delete superadmin account",403);
  1183. if($user->login == $myUser->login) throw new Exception("You can't delete your own account",403);
  1184. if(empty($user->id)) throw new Exception("You cant delete no db account", 400);
  1185. $user = User::getById($user->id);
  1186. $user->state = User::INACTIVE;
  1187. $user->save();
  1188. foreach(UserFirmRank::loadAll(array('user'=>$user->login)) as $ufrLink)
  1189. UserFirmRank::deleteById($ufrLink->id);
  1190. unset($_SESSION['users']);
  1191. Log::put("Suppression de l'utilisateur ".$user->toText(),'Utilisateur');
  1192. $response['code'] = 204;
  1193. });
  1194. $api->register();
  1195. /* FIN CORE API */
  1196. Api::run();
  1197. break;
  1198. /** CUSTOM REWRITE */
  1199. case 'rewrite':
  1200. try{
  1201. $root = substr($_SERVER['SCRIPT_NAME'], 0,strrpos($_SERVER['SCRIPT_NAME'] , '/'));
  1202. $requested = substr($_SERVER['REQUEST_URI'], strlen($root)+1);
  1203. ob_start();
  1204. Plugin::callHook('rewrite',array($requested));
  1205. $stream = ob_get_clean();
  1206. if($stream !='') echo $stream;
  1207. }catch(Exception $e){
  1208. exit('<div style="width:300px;margin:30px auto;padding:15px;background:#cecece;text-align:center;font-family:Arial">'.$e->getMessage().'</div>');
  1209. }
  1210. break;
  1211. /** ACTIONS DE PLUGINS */
  1212. default:
  1213. Plugin::callHook('action');
  1214. break;
  1215. }
  1216. ?>