action.php 46 KB

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