action.php 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  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. /*
  16. Authentification
  17. */
  18. //Connexion
  19. Action::register('core_login',function(&$response){
  20. global $myUser,$myFirm,$_,$conf;
  21. try {
  22. if(!isset($_['login'])) $_['login'] = 'anonymous';
  23. if(!isset($_['password'])) $_['password'] = '';
  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. $myUser = User::check($_['login'],html_entity_decode($_['password']));
  32. if(!$myUser) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  33. if(file_exists(File::dir().SLASH.'enabled.maintenance') && $myUser->superadmin != 1) throw new Exception('Seul un compte Super Admin peut se connecter en mode maintenance');
  34. if(!$myUser->connected()) throw new Exception('Identifiant ou mot de passe incorrect');
  35. //Suppression du token de reset de password s'il se reconnecte entre temps
  36. UserPreference::delete(array('user'=>$myUser->login,'key'=>'lost_password'));
  37. $myUser->loadPreferences();
  38. if(is_numeric($myUser->preference('default_firm')) && $myUser->haveFirm($myUser->preference('default_firm'))){
  39. $_SESSION['firm'] = serialize(Firm::getById($myUser->preference('default_firm')));
  40. if(!$_SESSION['firm']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  41. } else if(count($myUser->firms)!=0) {
  42. $_SESSION['firm'] = serialize(reset($myUser->firms));
  43. if(!$_SESSION['firm']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  44. } else {
  45. throw new Exception('Ce compte n\'est actif sur aucun établissement');
  46. }
  47. $myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']) : new Firm();
  48. if(!$myFirm) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  49. $_SESSION['currentUser'] = serialize($myUser);
  50. if(!$_SESSION['currentUser']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
  51. //Gestion de l'inactivité de l'utilisateur
  52. $inactivityDelay = $conf->get('logout_inactivity_delay');
  53. if(!empty($inactivityDelay) && is_numeric($inactivityDelay)){
  54. $response['inactivityDelay'] = $inactivityDelay;
  55. $myUser->meta['lastActivity'] = time();
  56. }
  57. if(isset($_['rememberMe']) && $_['rememberMe']){
  58. $cookie = password_hash(mt_rand(0,1000000000000).uniqid("", true).mt_rand(0,1000000000000), PASSWORD_DEFAULT);
  59. $myUser->preference('cookie',$cookie);
  60. make_cookie(COOKIE_NAME, $cookie);
  61. } else {
  62. $myUser->preference('cookie','');
  63. }
  64. $response['redirect'] = isset($_['url']) ? base64_decode($_['url']) : 'index.php';
  65. if(isset($_SESSION['last_request']) && !isset($_['url'])){
  66. $response['redirect'] = $_SESSION['last_request'];
  67. unset($_SESSION['last_request']);
  68. }
  69. Plugin::callHook('user_logged',array(&$myUser));
  70. //permet la redirection classic pour certains plugin d'authentification qui ne passent pas par le formulaire ajax
  71. if(isset($_['redirect']) && $_['redirect']=='classic'){
  72. header('location: '. $response['redirect']);
  73. exit();
  74. }
  75. Log::put("Connexion réussie avec \"".$myUser->login."\"",'Utilisateur');
  76. } catch(Exception $e){
  77. Log::put("Échec de la connexion avec ".$_['login']." : ".$e->getMessage(),'Utilisateur');
  78. //La vérification sur le code 509 permet d'éviter d'allonger le temps de ban à chaque tentative
  79. if($e->getCode()!=509) Log::put($_['login'],'auth_fail');
  80. throw new Exception($e->getMessage());
  81. }
  82. });
  83. //Déconnexion
  84. Action::register('core_logout',function(&$response){
  85. global $myUser,$_;
  86. $url = $myUser->disconnect(isset($_['url'])?$_['url']:null);
  87. Plugin::callHook('logout',array($url,$myUser));
  88. $response['redirect'] = $url;
  89. });
  90. //Vérification de la présence
  91. Action::register('initialize_activity',function(&$response){
  92. global $myUser;
  93. if(!$myUser->connected()) throw new Exception("Permission non accordée");
  94. $myUser->meta['lastActivity'] = time();
  95. });
  96. /** Tables de recherches **/
  97. //Save des colonnes dynamiques
  98. Action::register('core_table_colum_save',function(&$response){
  99. global $myUser,$_;
  100. if(!$myUser->connected()) return;
  101. $preferences = json_decode($myUser->preference('search_columns'),true);
  102. if(!$preferences) $preferences = array();
  103. if(!isset($_['slug'])) return $response;
  104. if(empty($_['added'])) $_['added'] = array();
  105. $preferences[$_['slug']] = $_['added'];
  106. $myUser->preference('search_columns',json_encode($preferences));
  107. $_SESSION['currentUser'] = serialize($myUser);
  108. });
  109. //Load des colonnes dynamiques
  110. Action::register('core_table_colum_search',function(&$response){
  111. global $myUser,$_;
  112. if(!isset($myUser)) throw new Exception("Utilisateur non définis");
  113. $response = json_decode($myUser->preference('search_columns'),true);
  114. if(!$response) $response = array();
  115. return $response;
  116. });
  117. //Save des fitlres de recherches en preference
  118. Action::register('core_filter_save',function(&$response){
  119. global $myUser,$_;
  120. if(!$myUser->connected()) throw new Exception("Permission non accordée");
  121. $preferences = json_decode($myUser->preference('search_filters'),true);
  122. if(!$preferences) $preferences = array();
  123. if(!isset($_['slug'])) return $response;
  124. if(empty($_['label'])) throw new Exception("Libellé obligatoire");
  125. function filter_recursive_save($filters){
  126. foreach($filters as $i=>$advanced){
  127. if(isset($filters[$i]['operator'])) $filters[$i]['operator'] = html_entity_decode($filters[$i]['operator']);
  128. if(isset($filters[$i]['group'])) $filters[$i]['group'] = filter_recursive_save($filters[$i]['group']);
  129. if(!isset($filters[$i]['value'])) continue;
  130. foreach($filters[$i]['value'] as $j => $value)
  131. $filters[$i]['value'][$j] = html_entity_decode($value,ENT_QUOTES,'UTF-8');
  132. }
  133. return $filters;
  134. }
  135. if(isset($_['filters']['keyword'])) $_['filters']['keyword'] = html_entity_decode($_['filters']['keyword'],ENT_QUOTES,'UTF-8');
  136. if(isset($_['filters']['advanced'])) $_['filters']['advanced'] = filter_recursive_save($_['filters']['advanced']);
  137. if(!isset($preferences[$_['slug']])) $preferences[$_['slug']] = array();
  138. $_['label'] = html_entity_decode($_['label'],ENT_QUOTES,'UTF-8');
  139. $uid = base64_encode($_['label']);
  140. $preferences[$_['slug']][$uid] = array(
  141. 'label' => $_['label'],
  142. 'uid' => $uid,
  143. 'filters'=> $_['filters']
  144. );
  145. $myUser->preference('search_filters',json_encode($preferences));
  146. $response['message'] = 'Recherche enregistrée';
  147. $_SESSION['currentUser'] = serialize($myUser);
  148. });
  149. /**
  150. * Suppression d'une recherche enregistrée
  151. * @param boolean global Définit si la recherche est globale ou non
  152. * @param string slug Représente le slug de la table de résultats associée
  153. * @param
  154. * */
  155. Action::register('core_filter_delete',function(&$response){
  156. global $myUser,$_;
  157. if(!$myUser->connected()) throw new Exception("Permission denied");
  158. if(!$myUser->superadmin && isset($_['global']) && !empty($_['global'])) throw new Exception("Impossible de supprimer une recherche partagée");
  159. $preferences = json_decode($myUser->preference('search_filters'),true);
  160. unset($preferences[$_['slug']][$_['uid']]);
  161. $myUser->preference('search_filters',json_encode($preferences));
  162. $_SESSION['currentUser'] = serialize($myUser);
  163. });
  164. Action::register('core_filter_global_save',function(&$response){
  165. global $myUser,$_,$conf;
  166. if((empty($_['rightSection']) && !$myUser->superadmin) || (isset($_['rightSection']) && !$myUser->can($_['rightSection'], 'configure'))) throw new Exception("Permissions insuffisantes", 403);
  167. if(empty($_['slug']) || empty($_['uid'])) return $response;
  168. $globalPreferences = json_decode($conf->get('search_filters'),true);
  169. $preferences = json_decode($myUser->preference('search_filters'),true);
  170. if($_['state']==1){
  171. $globalPreferences[$_['slug']][$_['uid']] = $preferences[$_['slug']][$_['uid']];
  172. unset($preferences[$_['slug']][$_['uid']]);
  173. }else{
  174. $preferences[$_['slug']][$_['uid']] = $globalPreferences[$_['slug']][$_['uid']];
  175. unset($globalPreferences[$_['slug']][$_['uid']]);
  176. }
  177. $conf->put('search_filters',json_encode($globalPreferences));
  178. $myUser->preference('search_filters',json_encode($preferences));
  179. $_SESSION['currentUser'] = serialize($myUser);
  180. });
  181. Action::register('core_filter_search',function(&$response){
  182. global $myUser,$_,$conf;
  183. if(!isset($myUser)) throw new Exception("Utilisateur non définis");
  184. if(empty($_['slug'])) return $response;
  185. $searches = array();
  186. $globalPreferences = json_decode($conf->get('search_filters'),true);
  187. $preferences = json_decode($myUser->preference('search_filters'),true);
  188. if(is_array($preferences) && isset($preferences[$_['slug']])){
  189. foreach($preferences[$_['slug']] as $preference){
  190. if(!isset($preference['label'])) continue;
  191. $preference['global'] = 0;
  192. $searches[$preference['uid']] = $preference;
  193. }
  194. }
  195. if(is_array($globalPreferences ) && isset($globalPreferences[$_['slug']])){
  196. foreach($globalPreferences[$_['slug']] as $preference){
  197. if(!isset($preference['label'])) continue;
  198. $preference['global'] = 1;
  199. $searches[$preference['uid']] = $preference;
  200. }
  201. }
  202. $response['filters'] = $searches;
  203. });
  204. /** LOGS */
  205. Action::register('core_search_log',function(&$response){
  206. global $myUser,$_;
  207. User::check_access('log','read');
  208. $limit = isset($_['export']) && $_['export'] == 'true' ? 5000 : 150;
  209. $data = array();
  210. $query = 'SELECT * FROM {{table}} WHERE 1';
  211. //Recherche simple
  212. if(!empty($_['filters']['keyword'])){
  213. $query .= ' AND label LIKE ?';
  214. $data[] = '%'.$_['filters']['keyword'].'%';
  215. }
  216. //Recherche avancée
  217. if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('label','category','creator','created','ip'),$query,$data);
  218. //Tri des colonnes
  219. if(isset($_['sort']))
  220. sort_secure_query($_['sort'],array('label','ip','created','category','creator'),$query,$data);
  221. else
  222. $query .= ' ORDER BY created DESC, id DESC ';
  223. //Pagination
  224. $response['pagination'] = Log::paginate($limit,(!empty($_['page'])?$_['page']:0),$query,$data);
  225. foreach(Log::staticQuery($query,$data,true) as $log){
  226. $row = $log->toArray(true);
  227. $row['created'] = date('d/m/Y H:i:s', $log->created);
  228. $row['created_full'] = date('Y-m-d', $log->created);
  229. if(!empty($_['filters']['keyword'])){
  230. $row['label'] = preg_replace_callback('|(.*)('.$_['filters']['keyword'].')(.*)|i', function($matches){
  231. return $matches[1].'<mark><strong>'.$matches[2].'</strong></mark>'.$matches[3];
  232. }, htmlentities($log->label, ENT_QUOTES));
  233. }
  234. $response['rows'][] = $row;
  235. }
  236. //Export des données
  237. if(isset($_['export']) && $_['export'] == 'true') {
  238. //Clear des marqueurs HTML
  239. foreach($response['rows'] as $i => $row) {
  240. $row['label'] = html_entity_decode(strip_tags($row['label']));
  241. $response['rows'][$i] = $row;
  242. }
  243. $mapping = array(
  244. 'Date' => array('slug'=>'created_full', 'type'=>'DD/MM/YYYY'),
  245. 'Catégorie' => 'category',
  246. 'Libellé' => 'label',
  247. 'Utilisateur' => 'creator',
  248. 'Ip' => 'ip',
  249. );
  250. $export = Excel::exportArray($response['rows'], $mapping, 'Logs');
  251. File::downloadStream($export,'export-logs-'.date('ymd').'.xlsx');
  252. Log::put("Export logs : ".(isset($_['filters']) ? " Filtres: ".json_encode($_['filters']) : '').", Tri: ".(isset($_['sort'])?json_encode($_['sort']):'').", Page: ".$_['page'],'Produit');
  253. exit();
  254. }
  255. });
  256. /* Gestion des entitées */
  257. //Récuperation d'une liste d'entitées en fonction du plugin ciblé
  258. Action::register('core_entity_search',function(&$response){
  259. global $myUser,$_;
  260. if(!$myUser->connected()) throw new Exception("Permission refusée");
  261. if(empty($_['plugin'])) throw new Exception('Plugin non spécifié');
  262. foreach(glob($_['plugin'].SLASH.'*.class.php') as $file){
  263. require_once($file);
  264. $class = str_replace('.class.php','',basename($file));
  265. if(!is_subclass_of($class, 'Entity')) continue;
  266. $instance = new $class();
  267. $label = $class;
  268. $table = strtolower($class);
  269. if(property_exists($instance,'entityLabel') && !empty($instance->entityLabel)) $label = $instance->entityLabel;
  270. if(method_exists($instance,'tableName') && !empty($instance->tableName())) $table = $instance->tableName();
  271. $response['rows'][] = array(
  272. 'class'=> $class,
  273. 'label'=> $label,
  274. 'table'=> $table ,
  275. 'path' => $file
  276. );
  277. }
  278. });
  279. //Récuperation des infos générales d'une entitée
  280. Action::register('core_entity_edit',function(&$response){
  281. global $myUser,$_;
  282. if(!$myUser->connected()) throw new Exception("Permission refusée");
  283. if(empty($_['path'])) throw new Exception('Chemin non spécifié');
  284. $file = $_['path'];
  285. require_once($file);
  286. $class = str_replace('.class.php','',basename($file));
  287. if(!is_subclass_of($class, 'Entity')) return;
  288. $instance = new $class();
  289. $label = $class;
  290. $table = strtolower($class);
  291. if(property_exists($instance,'entityLabel') && !empty($instance->entityLabel)) $label = $instance->entityLabel;
  292. if(method_exists($instance,'tableName') && !empty($instance->tableName())) $table = $instance->tableName();
  293. $response = array(
  294. 'class'=> $class,
  295. 'label'=> $label,
  296. 'table'=> $table ,
  297. 'path' => $file,
  298. 'plugin' => Plugin::parseManifest(dirname($file).SLASH.'app.json')
  299. );
  300. });
  301. //Récuperation de la liste des attributs d'une entitée
  302. Action::register('core_entity_attribute_search',function(&$response){
  303. global $myUser,$_;
  304. if(!$myUser->connected()) throw new Exception("Permission refusée");
  305. if(empty($_['path'])) throw new Exception('Chemin non spécifié');
  306. $file = $_['path'];
  307. require_once($file);
  308. $class = str_replace('.class.php','',basename($file));
  309. if(!is_subclass_of($class, 'Entity')) return;
  310. $instance = new $class();
  311. $fields = $instance->fields(false);
  312. if(property_exists($instance,'links')){
  313. foreach($instance->links as $field=>$classFile){
  314. $classFile = __ROOT__.SLASH.$classFile;
  315. if(!file_exists($classFile)) continue;
  316. require_once($classFile);
  317. $subClass = str_replace('.class.php','',basename($classFile));
  318. if(!is_subclass_of($subClass, 'Entity')) continue;
  319. $subInstance = new $subClass();
  320. $fields[$field]['entity'] = $subClass;
  321. $fields[$field]['classFile'] = $classFile;
  322. $fields[$field]['childs'] = $subInstance->fields(false);
  323. }
  324. };
  325. $response['fields'] = $fields;
  326. });
  327. /* PLUGINS */
  328. Action::register('core_plugin_search',function(&$response){
  329. global $myUser,$_;
  330. User::check_access('plugin','read');
  331. $includeCore = isset($_['includeCore']) && $_['includeCore']==true ;
  332. $firms = array();
  333. foreach(Firm::loadAll() as $firm)
  334. $firms[] = $firm->toArray();
  335. foreach(Plugin::getAll(true) as $plugin)
  336. $firmPluginMapping[$plugin->id] = $plugin->firms;
  337. foreach(Plugin::getAll(false,$includeCore) as $plugin){
  338. $plugin->folder = array('name'=>$plugin->folder,'path'=>$plugin->path());
  339. foreach($plugin->require as $id=>$version)
  340. $plugin->required[] = array('id'=>$id, 'version'=>$version);
  341. $row = $plugin->toArray();
  342. $row['firms'] = array_values($firms);
  343. foreach($row['firms'] as $i=>$firm){
  344. $row['firms'][$i]['value'] = isset($firmPluginMapping[$plugin->id]) && in_array($firm['id'],$firmPluginMapping[$plugin->id]) ? 1 : 0;
  345. }
  346. $response['rows'][] = $row;
  347. }
  348. });
  349. Action::register('core_plugin_state_save',function(&$response){
  350. global $myUser,$_;
  351. User::check_access('plugin','configure');
  352. $plugin = Plugin::getById($_['plugin']);
  353. if($_['state']){
  354. $states = Plugin::states();
  355. $missingRequire = array();
  356. foreach($plugin->require as $require=>$version):
  357. $req = Plugin::getById($require);
  358. if($req == null || $req==false || !$req->state || $req->version!=$version)
  359. $missingRequire[]= $require.' - '.$version;
  360. endforeach;
  361. if(count($missingRequire)!=0) throw new Exception("Plugins pré-requis non installés : ".implode(',',$missingRequire));
  362. }
  363. Plugin::state($_['plugin'],$_['state']);
  364. Log::put(($_['state']?'Activation':'Désactivation')." du plugin ".$_['plugin'],'Plugin');
  365. });
  366. /** ETABLISSEMENT */
  367. //Récuperation d'une liste de etablissement
  368. Action::register('core_firm_search',function(&$response){
  369. global $_;
  370. User::check_access('firm','read');
  371. // OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
  372. $query = 'SELECT main.* FROM '.Firm::tableName().' main WHERE 1';
  373. $data = array();
  374. //Recherche simple
  375. if(!empty($_['filters']['keyword'])){
  376. $query .= ' AND main.label LIKE ?';
  377. $data[] = '%'.$_['filters']['keyword'].'%';
  378. }
  379. //Recherche avancée
  380. if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('main.label','main.description','main.logo','main.mail','main.phone','main.fax','main.street','main.street2','main.city','main.zipcode','main.siret','main.iban'),$query,$data);
  381. //Tri des colonnes
  382. if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.label','main.description','main.logo','main.mail','main.phone','main.fax','main.street','main.street2','main.city','main.zipcode','main.siret','main.iban'),$query,$data);
  383. //Pagination
  384. //Par défaut pour une recherche, 20 items, pour un export 5000 max
  385. $itemPerPage = !empty($_['itemPerPage']) ? $_['itemPerPage'] : 20;
  386. //force le nombre de page max a 50 coté serveur
  387. $itemPerPage = $itemPerPage>50 ? 50 : $itemPerPage;
  388. if($_['export'] == 'true') $itemPerPage = 5000;
  389. $response['pagination'] = Firm::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');
  390. $firms = Firm::staticQuery($query,$data,true,0);
  391. $response['rows'] = array();
  392. foreach($firms as $firm){
  393. $row = $firm->toArray();
  394. $row['description'] = html_entity_decode($row['description']);
  395. $row['logo'] = $firm->logo('url');
  396. if($_['export'] == 'true'){
  397. $row['created'] = date('d-m-Y',$row['created']);
  398. $row['updated'] = date('d-m-Y',$row['updated']);
  399. }
  400. $response['rows'][] = $row;
  401. }
  402. /* Mode export */
  403. if($_['export'] == 'true'){
  404. if(empty($response['rows'])) $response['rows'][] = array('Vide'=>'Aucune données');
  405. $fieldsMapping = array();
  406. foreach (Firm::fields(false) as $key => $value)
  407. $fieldsMapping[$value['label']] = $key;
  408. $stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
  409. File::downloadStream($stream,'export-etablissements-'.date('d-m-Y').'.xlsx');
  410. exit();
  411. }
  412. });
  413. //Ajout ou modification d'élément etablissement
  414. Action::register('core_firm_save',function(&$response){
  415. global $_;
  416. User::check_access('firm','edit');
  417. $item = Firm::provide();
  418. $item->label = $_['label'];
  419. $item->description = $_['description'];
  420. $item->mail = $_['mail'];
  421. $item->phone = $_['phone'];
  422. $item->fax = $_['fax'];
  423. $item->street = $_['street'];
  424. $item->street2 = $_['street2'];
  425. $item->city = $_['city'];
  426. $item->zipcode = $_['zipcode'];
  427. $item->siret = $_['siret'];
  428. $item->iban = $_['iban'];
  429. $item->save();
  430. //Ajout upload Logo
  431. if(!empty($_['logo']))
  432. File::save_component('logo', 'core/public/firm/'.$item->id.'/logo.{{extension}}');
  433. $response = $item->toArray();
  434. });
  435. //Suppression d'élement etablissement
  436. Action::register('core_firm_delete',function(&$response){
  437. global $_;
  438. User::check_access('firm','delete');
  439. if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
  440. $firm = Firm::getById($_['id']);
  441. Firm::deleteById($firm->id);
  442. //Suppression de l'établissmeent supprimé dans les plugins activés
  443. $states = Plugin::states();
  444. foreach ($states as $plugin => $firms) {
  445. $key = array_search($_['id'], $firms);
  446. if($key === false) continue;
  447. unset($firms[$key]);
  448. $states[$plugin] = array_values($firms);
  449. }
  450. Plugin::states($states);
  451. //Suppression des liens UFR et des droits associés
  452. UserFirmRank::delete(array('firm'=>$_['id']));
  453. Right::delete(array('firm'=>$_['id']));
  454. Log::put("Suppression de l'établissement ".$firm->toText(),'Etablissement');
  455. });
  456. //Firm : Gestion upload Logo
  457. Action::register('core_firm_logo',function(&$response){
  458. File::handle_component(array(
  459. 'namespace' => 'core', //stockés dans file/core/*.*
  460. 'access' => 'core', // crud sur core,
  461. 'size' => '1000000000', // taille max
  462. 'limit' => '1', // nb max de fichiers
  463. 'storage' => 'core/public/firm/{{data.id}}/logo.*' //chemin complet vers le fichier stocké
  464. ),$response);
  465. });
  466. Action::register('core_firm_select',function(&$response){
  467. global $myUser,$_,$myFirm;
  468. try{
  469. if(!$myUser->connected()) throw new Exception("Permission denied");
  470. if(!$myUser->haveFirm( $_['firm'])) throw new Exception("Vous n'avez pas accès à cet établissement");
  471. $myFirm = Firm::getById($_['firm']);
  472. $_SESSION['firm'] = serialize($myFirm);
  473. $myUser->preference('default_firm',$myFirm->id);
  474. $myUser->loadRights();
  475. $_SESSION['currentUser'] = serialize($myUser);
  476. if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
  477. if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
  478. header('location: index.php');
  479. }catch(Exception $e){
  480. header('location: index.php?error='.urlencode($e->getMessage()));
  481. }
  482. });
  483. Action::register('core_firm_autocomplete',function(&$response){
  484. global $myUser,$_;
  485. if(!$myUser->can('firm','read')) throw new Exception("Vous n'avez pas acces aux établissements");
  486. $response['rows'] = array();
  487. if($_['keyword'] == '') return;
  488. foreach(Firm::loadAll(array('label:like'=> '%'.$_['keyword'].'%' ),array('label')) as $firm){
  489. $response['rows'][] = array(
  490. 'label'=>$firm->label,
  491. 'id'=>$firm->id,
  492. 'description'=>$firm->description
  493. );
  494. }
  495. });
  496. Action::register('core_firm_by_uid',function(&$response){
  497. global $myUser,$_;
  498. if(!$myUser->can('firm','read')) throw new Exception("Vous n'avez pas acces aux établissements");
  499. $response['items'] = array();
  500. $firms = $_['items'];
  501. foreach(Firm::loadAll(array('id:IN'=>implode(',',$firms))) as $item){
  502. $row = $item->toArray();
  503. $row['label'] = $item->label;
  504. $row['id'] = $item->id;
  505. $response['items'][$item->id] = $row;
  506. }
  507. });
  508. /** LIEN ETABLISSEMENT / PLUGIN **/
  509. Action::register('core_firm_plugin_search',function(&$response){
  510. global $myUser,$_;
  511. User::check_access('plugin','configure');
  512. if(!isset($_['firm'])) throw new Exception("Établissement non spécifié");
  513. $wholePlugins = array();
  514. if($_['firm'] == '0'){
  515. foreach(Firm::loadAll() as $firm){
  516. foreach(Plugin::getAll(true) as $plugin){
  517. $wholePlugins[$plugin->id][$firm->id] = in_array($firm->id, $plugin->firms) ? 1 : 0;
  518. }
  519. }
  520. }
  521. foreach(Plugin::getAll(true) as $plugin){
  522. if($_['firm'] == '0'){
  523. $plugin->state = count(array_unique($wholePlugins[$plugin->id])) === 1 ? end($wholePlugins[$plugin->id]) : 2;
  524. }else{
  525. $plugin->state = in_array($_['firm'], $plugin->firms) ? 1 : 0;
  526. }
  527. $response['rows'][] = $plugin;
  528. }
  529. });
  530. Action::register('core_firm_plugin_save',function(&$response){
  531. global $myUser,$_;
  532. User::check_access('plugin','configure');
  533. $firms = Firm::loadAll();
  534. $firms[] = Firm::anonymous_firm();
  535. foreach($firms as $firm){
  536. if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
  537. $states = Plugin::states();
  538. $firms = $states[$_['plugin']];
  539. $key = array_search($firm->id, $firms);
  540. if($_['state']==0 && $key !== false){
  541. unset($firms[$key]);
  542. }else if($_['state']==1 && $key === false){
  543. $firms[] = $firm->id;
  544. }
  545. $states[$_['plugin']] = array_values($firms);
  546. Plugin::states($states);
  547. }
  548. });
  549. /** LIEN ETABLISSEMENT / UTILISATEUR / RANG **/
  550. Action::register('core_userfirmrank_search',function(&$response){
  551. global $myUser,$_;
  552. User::check_access('rank','read');
  553. $firms = array($_['firm']);
  554. if($_['firm'] == 0){
  555. $firms = array();
  556. foreach(Firm::loadAll() as $firm)
  557. $firms[] = $firm->id;
  558. }
  559. $users = array();
  560. foreach(User::getAll(array('right'=>false)) as $user)
  561. $users[$user->login] = $user;
  562. foreach(UserFirmRank::staticQuery("SELECT *, ufr.id id, u.id uid, r.label rank, f.label firm
  563. FROM {{table}} ufr
  564. LEFT JOIN ".User::tableName()." u ON ufr.user=u.login
  565. LEFT JOIN ".Rank::tableName()." r ON r.id=ufr.rank
  566. LEFT JOIN ".Firm::tableName()." f ON f.id=ufr.firm
  567. WHERE ufr.firm IN (".str_repeat('?,', count($firms) - 1) . '?'.")",$firms,false) as $userFirmRank){
  568. if(empty($myUser->superadmin) && !empty($userFirmRank['superadmin'])) continue;
  569. $user = isset($users[$userFirmRank['user']]) ? $users[$userFirmRank['user']] : new User();
  570. // Petit trick pour l'affichage mustache
  571. $userFirmRank['superadmin'] = !empty($userFirmRank['superadmin']);
  572. $userFirmRank['avatar'] = $user->getAvatar();
  573. $userFirmRank['password'] = '';
  574. $user->name = $user->lastname();
  575. $user->firstname = $user->firstname();
  576. $userFirmRank['user'] = $user;
  577. $response['rows'][] = $userFirmRank;
  578. }
  579. });
  580. Action::register('core_userfirmrank_save',function(&$response){
  581. global $myUser,$_;
  582. User::check_access('rank','edit');
  583. if(!isset($_['firm'])) throw new Exception('Champ "Établissement" obligatoire');
  584. if(!isset($_['user']) || empty($_['user'])) throw new Exception('Champ "Utilisateur" obligatoire');
  585. if(!isset($_['rank']) || empty($_['rank'])) throw new Exception('Champ "Rang" obligatoire');
  586. foreach(Firm::loadAll() as $firm){
  587. if($_['firm'] != 0 && $_['firm'] != $firm->id) continue;
  588. $user = User::byLogin(stripslashes($_['user']));
  589. $rank = Rank::getById($_['rank']);
  590. if($user->origin == 'active_directory' && (!array_key_exists($firm->id, $user->firms) || !$firm->has_plugin('fr.core.activedirectory'))) continue;
  591. $userFirmRank = UserFirmRank::provide();
  592. $exist = is_null($userFirmRank->id) || $_['firm'] == 0 ? UserFirmRank::rowCount(array('user'=>$user->login,'firm'=>$firm->id,'rank'=>$_['rank'])) : UserFirmRank::rowCount(array('id:!='=>$userFirmRank->id,'user'=>$user->login,'firm'=>$firm->id,'rank'=>$_['rank']));
  593. if($exist > 0){
  594. $response['warning'][] = "Le rang ".$rank->label." est déja défini pour ".$user->fullName()." sur l'établissement ".$firm->label;
  595. continue;
  596. }
  597. $userFirmRank->fromArray($_);
  598. $userFirmRank->firm = $firm->id;
  599. $userFirmRank->user = $user->login;
  600. $userFirmRank->save();
  601. $response['success'][] = "Rang ".$rank->label." ajouté pour ".$user->fullName()." sur l'établissement ".$firm->label;
  602. }
  603. });
  604. Action::register('core_userfirmrank_edit',function(&$response){
  605. global $myUser,$_;
  606. User::check_access('rank','edit');
  607. $userFirmRank = UserFirmRank::getById($_['id']);
  608. $response = $userFirmRank;
  609. });
  610. Action::register('core_userfirmrank_delete',function(&$response){
  611. global $myUser,$_,$conf;
  612. User::check_access('rank','delete');
  613. $userFirmRank = UserFirmRank::provide();
  614. $user = User::byLogin($userFirmRank->user);
  615. if($user->preference('default_firm') == $userFirmRank->firm)
  616. UserPreference::delete(array('user'=>$user->login, 'key'=>'default_firm'));
  617. UserFirmRank::deleteById($_['id']);
  618. });
  619. /** UTILISATEURS **/
  620. Action::register('core_user_search',function(&$response){
  621. global $myUser,$_;
  622. User::check_access('user','read');
  623. foreach(User::getAll(array('right'=>false,'force'=> true)) as $user){
  624. if($user->state == User::INACTIVE || (!$myUser->superadmin && $user->superadmin)) continue;
  625. $user->login = htmlspecialchars_decode($user->login);
  626. $user->name = $user->lastname();
  627. $user->firstname = $user->firstname();
  628. $user->avatar = $user->getAvatar();
  629. $user->formatedLogin = urlencode($user->login);
  630. $response['rows'][] = $user;
  631. }
  632. });
  633. Action::register('core_user_autocomplete',function(&$response){
  634. global $myUser,$_,$myFirm;
  635. if(!$myUser->can('user','read')) throw new Exception("Vous n'avez pas acces aux utilisateurs");
  636. $response['rows'] = array();
  637. $scope = isset($_['data']['scope']) ? $_['data']['scope'] : $myFirm->id;
  638. if($_['keyword'] == '') return;
  639. if(in_array('user', $_['data']['types'])){
  640. foreach(User::getAll(array('right'=>true) ) as $user){
  641. if($scope!= 0 && !isset($user->firms[$scope])) continue;
  642. if(preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->fullName())) || preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->login))){
  643. $response['rows'][] = array(
  644. 'fullname'=>html_decode_utf8($user->fullName()),
  645. 'name'=>$user->fullName(),
  646. 'uid'=>html_decode_utf8(addslashes($user->login)),
  647. 'id'=>$user->login,
  648. 'mail'=>$user->mail,
  649. 'type'=>'user',
  650. 'avatar'=>$user->getAvatar(),
  651. 'function'=>$user->function
  652. );
  653. }
  654. }
  655. }
  656. if(in_array('rank', $_['data']['types'])){
  657. foreach(Rank::staticQuery('SELECT * FROM {{table}} WHERE label LIKE ?',array('%'.$_['keyword'].'%'),true) as $rank){
  658. $response['rows'][] = array(
  659. 'fullname'=>html_decode_utf8($rank->label),
  660. 'name'=>$rank->label,
  661. 'uid'=>$rank->id,
  662. 'id'=>$rank->id,
  663. 'type'=>'rank',
  664. 'description'=>$rank->description,
  665. );
  666. }
  667. }
  668. });
  669. Action::register('core_user_by_uid',function(&$response){
  670. global $myUser,$_;
  671. if(!$myUser->can('user','read')) throw new Exception("Vous n'avez pas acces aux utilisateurs");
  672. $response['users'] = array();
  673. $ranks = array();
  674. $users = array();
  675. foreach($_['uids'] as $uid){
  676. if(is_numeric($uid)){
  677. $ranks[] = $uid;
  678. continue;
  679. }
  680. //user
  681. $item = User::byLogin($uid);
  682. if(!$item->login) {
  683. $item->login = $uid;
  684. $item->fullName = $uid;
  685. $item->uid = $uid;
  686. }
  687. $row = $item->toArray();
  688. $row['fullname'] = html_decode_utf8($item->fullName());
  689. $row['name'] = $item->fullName();
  690. $row['uid'] = html_decode_utf8(addslashes($item->login));
  691. $row['id'] = $item->login;
  692. $row['type'] = 'user';
  693. unset($row['password']);
  694. unset($row['token']);
  695. $response['users'][$item->login] = $row;
  696. }
  697. //rank
  698. foreach(Rank::loadAll(array('id:IN'=>implode(',',$ranks))) as $item){
  699. $row = $item->toArray();
  700. $row['fullname'] = $item->label;
  701. $row['name'] = $item->label;
  702. $row['uid'] = $item->id;
  703. $row['id'] = $item->id;
  704. $row['type'] = 'rank';
  705. $response['users'][$item->id] = $row;
  706. }
  707. });
  708. /* Compte/Profil utilisateur */
  709. Action::register('core_account_lost_password',function(&$response){
  710. global $myUser,$myFirm,$_,$conf;
  711. if(!isset($_['mail']) || empty($_['mail']) || !check_mail(trim($_['mail']))) throw new Exception("Adresse e-mail non spécifiée ou incorrecte");
  712. foreach(User::getAll(array('right'=>false) ) as $user){
  713. if(mb_strtolower($user->mail) != mb_strtolower(trim($_['mail']))) continue;
  714. $token = sha1(time().mt_rand(0,1000));
  715. $linkToken = base64_encode($user->login.'::'.$token.'::1');
  716. UserPreference::delete(array('user'=>$user->login,'key'=>'lost_password'));
  717. $saved = new UserPreference();
  718. $saved->user = $user->login;
  719. $saved->key = 'lost_password';
  720. $saved->value = $token;
  721. $saved->save();
  722. $mail = new Mail;
  723. $mail->expeditor = !empty($conf->get('password_lost_expeditor'))?$conf->get('password_lost_expeditor'):"";
  724. $mail->title = "Récupération de mot de passe oublié";
  725. $data = array(
  726. 'link' => ROOT_URL.'/account.lost.php?token='.$linkToken,
  727. 'url' => ROOT_URL,
  728. 'firstname' => $user->firstname,
  729. );
  730. if(!empty($conf->get('password_lost_firm')) && $firm = Firm::getById($conf->get('password_lost_firm'))){
  731. $mail->firm = utf8_decode($firm->label);
  732. $data['firm'] = $firm->label;
  733. $data['logo'] = ROOT_URL.'/'.$firm->logo('url');
  734. }
  735. if(!empty($conf->get('password_lost_mail_expire'))){
  736. $expDays = intval($conf->get('password_lost_mail_expire'));
  737. $data['expDays'] = $expDays;
  738. $data['expDaysPlural'] = $expDays>1?"s":"";
  739. $data['expDate'] = !empty($expDays) ? date("d/m/Y à H:i", strtotime($expDays." days")) : '';
  740. }
  741. $mail->template(__DIR__.SLASH.'mail.reset.password.html',$data,true);
  742. $mail->recipients['to'][] = $user->mail;
  743. $mail->send();
  744. Log::put("Demande de récupération de mot de passe : ".$user->toText(),'Utilisateur');
  745. return;
  746. }
  747. throw new Exception("Aucun compte ne correspond, veuillez contacter un administrateur");
  748. });
  749. Action::register('core_account_api_save',function(&$response){
  750. global $myUser,$myFirm,$_,$conf;
  751. User::check_access('account','edit');
  752. $myUser->preference('api_enabled',$_['api-enabled']);
  753. $myUser->loadPreferences();
  754. $_SESSION['currentUser'] = serialize($myUser);
  755. });
  756. Action::register('core_account_save',function(&$response){
  757. global $myUser,$myFirm,$_,$conf;
  758. User::check_access('account','edit');
  759. if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
  760. if(preg_match('|[,'.preg_quote(htmlspecialchars_decode($conf->get('login_forbidden_char'))).']|i', htmlspecialchars_decode($_['login']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans l'identifiant");
  761. if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Adresse mail obligatoire');
  762. $_['mail'] = mb_strtolower(trim($_['mail']));
  763. $_['login'] = mb_strtolower(trim($_['login']));
  764. $userForm = new User();
  765. $userForm->fromArray($_);
  766. if(empty($userForm->login) && (!isset($_['password']) || empty($_['password']))) throw new Exception("Mot de passe obligatoire");
  767. //Vérifications & formattage des données
  768. $userForm->firstname = mb_ucfirst(mb_strtolower($userForm->firstname));
  769. $userForm->name = mb_strtoupper($userForm->name);
  770. if(!empty($userForm->mail) && !check_mail($userForm->mail)) throw new Exception('Le format du champ "Mail" est invalide');
  771. if(!empty($userForm->phone) && !check_phone_number($userForm->phone)) throw new Exception('Le format du champ "Téléphone fixe" est invalide');
  772. $userForm->phone = !empty($userForm->phone) ? normalize_phone_number($userForm->phone) : '';
  773. if(!empty($userForm->mobile) && !check_phone_number($userForm->mobile)) throw new Exception('Le format du champ "Téléphone mobile" est invalide');
  774. $userForm->mobile = !empty($userForm->mobile) ? normalize_phone_number($userForm->mobile) : '';
  775. if(!empty($conf->get('password_forbidden_char')) && preg_match('|['.preg_quote(htmlspecialchars_decode($conf->get('password_forbidden_char'))).']|i', htmlspecialchars_decode($_['password']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans le mot de passe");
  776. if($_['password'] != $_['password2']) throw new Exception("Mot de passe et confirmation non similaires");
  777. //Recuperation des hash des precedents passwords
  778. $chain = explode('-',$myUser->preference('account_chain'));
  779. if(!empty(trim($_['password']))) {
  780. $hashedPassword = User::password_encrypt('$a1u7'.$_['password'].'$y$1');
  781. if(in_array($hashedPassword, $chain) && !$myUser->superadmin) throw new Exception("Vous devez choisir un mot de passe différent des précédents");
  782. if(count($chain)==10) array_shift($chain);
  783. $chain[] = $hashedPassword;
  784. $myUser->preference('account_chain',implode('-',$chain));
  785. }
  786. //save des comptes type db
  787. if($myUser->origin == ''){
  788. if(!empty(trim($_['password']))){
  789. $passwordErrors = User::check_password_format($_['password']);
  790. if(count($passwordErrors)!=0 && !$myUser->superadmin) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : <br>".implode("<br>",$passwordErrors));
  791. 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");
  792. $myUser->password = User::password_encrypt($_['password']);
  793. $myUser->preference('passwordTime',time());
  794. }
  795. $myUser->firstname = $userForm->firstname;
  796. $myUser->name = $userForm->name;
  797. $myUser->mail = $userForm->mail;
  798. $myUser->function = $userForm->function;
  799. $myUser->phone = $userForm->phone;
  800. $myUser->mobile = $userForm->mobile;
  801. $myUser->manager = is_object($myUser->manager) ? $myUser->manager->login : $myUser->manager;
  802. if(is_array($myUser->meta)) $myUser->meta = json_encode($myUser->meta);
  803. $myUser->save();
  804. if($myUser->superadmin == 1){
  805. foreach(Firm::loadAll() as $firm)
  806. $firms[$firm->id] = $firm;
  807. $myUser->setFirms($firms);
  808. }
  809. }
  810. //Save de l'avatar
  811. if(!empty($_FILES['avatar']) && $_FILES['avatar']['size']!=0 ){
  812. $login = User::format_avatar_name($myUser->login);
  813. foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.$login.".*") as $filename)
  814. unlink($filename);
  815. $avatar = File::upload('avatar',AVATAR_PATH.$login.'.{{ext}}',104857060,array('jpg','png','jpeg','gif'));
  816. Image::resize($avatar['absolute'],150,150);
  817. }
  818. //save des comptes types plugin
  819. Plugin::callHook("user_save",array(&$myUser,$userForm,&$response));
  820. $myUser->loadRights();
  821. if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
  822. if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
  823. $_SESSION['currentUser'] = serialize($myUser);
  824. });
  825. Action::register('core_account_avatar_download',function(&$response){
  826. global $myUser,$_;
  827. User::check_access('profile','read');
  828. try {
  829. $user = str_replace(array('..','/'),'',$_['user']);
  830. $extension = str_replace(array('..','/'),'',$_['extension']);
  831. File::downloadFile(File::dir().AVATAR_PATH.User::format_avatar_name($user).'.'.$extension,null, null, null, true,false);
  832. } catch(Exception $e) {
  833. File::downloadFile('img/default-avatar.png',null, null, null, true,false);
  834. }
  835. });
  836. Action::register('core_account_avatar_delete',function(&$response){
  837. global $myUser,$_;
  838. if(!$user = User::byLogin($_['login'])) throw new Exception("Utilisateur inconnu");
  839. if($myUser->login!=$user->login && !$myUser->can('user', 'edit')) throw new Exception("Permissions insuffisantes",403);
  840. foreach(glob(__ROOT__.FILE_PATH.AVATAR_PATH.User::format_avatar_name($user->login).".*") as $filename)
  841. unlink($filename);
  842. if(!file_exists(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails')) return;
  843. foreach(glob(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails'.SLASH.User::format_avatar_name($user->login).".*") as $filename)
  844. unlink($filename);
  845. });
  846. Action::register('core_user_save',function(&$response){
  847. global $myUser,$_,$conf;
  848. User::check_access('user','edit');
  849. if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
  850. if(preg_match('|[,'.preg_quote(htmlspecialchars_decode($conf->get('login_forbidden_char'))).']|i', htmlspecialchars_decode($_['login']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans l'identifiant");
  851. //Calcule de la taille max du login en focntion du chemin absolu pour avatar + extension (5)
  852. $osElementMaxLength = OS_path_max_length() - strlen(__ROOT__.FILE_PATH.AVATAR_PATH) - strlen(User::get_avatar_extension_brace());
  853. if(strlen($_['login']) > $osElementMaxLength) throw new Exception("Identifiant trop long : maximum ".$osElementMaxLength." caractères");
  854. $osElementMaxLength = OS_element_max_length();
  855. if(strlen($_['login']) > $osElementMaxLength) throw new Exception("Identifiant trop long : maximum ".$osElementMaxLength." caractères");
  856. if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Le champ "Mail" est obligatoire');
  857. if(!check_mail($_['mail'])) throw new Exception('Le format du champ "Mail" est invalide');
  858. if(!empty($conf->get('password_forbidden_char')) && preg_match('|['.preg_quote(htmlspecialchars_decode($conf->get('password_forbidden_char'))).']|i', htmlspecialchars_decode($_['password']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans le mot de passe");
  859. if($_['password'] != $_['password2']) throw new Exception("Mot de passe et confirmation non similaires");
  860. $_['mail'] = mb_strtolower(trim($_['mail']));
  861. $_['login'] = trim($_['login']);
  862. $user = User::byLogin($_['login']);
  863. $user = $user && empty($user->origin) ? $user : new User();
  864. //Check si un user n'existe pas déjà avec ce login (on récupère tous les users car user peut être supprimé logiquement / désactivé uniquement)
  865. if(empty($user->id)){
  866. $tryExisting = User::byLogin($_['login']);
  867. if($tryExisting && $tryExisting->state=='published')
  868. throw new Exception("Un utilisateur existe déjà avec cet identifiant");
  869. }
  870. if(!$user->login) $user->login = $_['login'];
  871. foreach(User::getAll(array('right'=>false)) as $existingUser)
  872. if($existingUser->mail == $_['mail'] && $existingUser->login != $user->login) throw new Exception("Un utilisateur existe déjà avec cette adresse e-mail");
  873. if($user->id == 0 && (!isset($_['password']) || empty($_['password']))) throw new Exception("Mot de passe obligatoire");
  874. if(!empty(trim($_['password']))){
  875. $passwordErrors = User::check_password_format(html_entity_decode($_['password']));
  876. if(count($passwordErrors)!=0 && !$myUser->superadmin) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : <br>".implode("<br>",$passwordErrors));
  877. if($_['password']==$_['login'] || $_['password']==$_['mail'] ) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant ou à l'e-mail");
  878. $user->password = User::password_encrypt(html_entity_decode($_['password']));
  879. $user->preference('passwordTime',time());
  880. }
  881. $user->firstname = mb_ucfirst(mb_strtolower($_['firstname']));
  882. $user->name = mb_strtoupper($_['name']);
  883. $user->mail = $_['mail'];
  884. $user->state = User::ACTIVE;
  885. if(isset($_['manager'])) $user->manager = $_['manager'];
  886. if(is_array($user->meta)) $user->meta = json_encode($user->meta);
  887. $user->save();
  888. if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
  889. if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
  890. $user->password = '';
  891. Log::put("Création/Modification de l'utilisateur ".$user->login,'Utilisateur');
  892. });
  893. Action::register('core_user_edit',function(&$response){
  894. global $myUser,$_;
  895. User::check_access('user','edit');
  896. $user = User::byLogin($_['login'], true, true);
  897. $user->login = htmlspecialchars_decode($user->login);
  898. $user->name = $user->lastname();
  899. $user->firstname = $user->firstname();
  900. if(!$user) throw new Exception("Utilisateur non identifié");
  901. $user->password = '';
  902. $response = $user;
  903. });
  904. Action::register('core_user_delete',function(&$response){
  905. global $myUser,$_;
  906. User::check_access('user','delete');
  907. $user = User::byLogin($_['login'], true, true);
  908. if(!$user) throw new Exception("Utilisateur non identifié");
  909. $user->loadRanks();
  910. if($user->superadmin == 1) throw new Exception("Vous ne pouvez pas supprimer le compte Super Admin");
  911. if($user->login == $myUser->login) throw new Exception("Vous ne pouvez pas supprimer votre propre compte");
  912. if(!$user = User::getById($user->id)) throw new Exception("Impossible de supprimer un compte en dehors de de la base de données");
  913. $user->state = User::INACTIVE;
  914. $user->save();
  915. foreach(UserFirmRank::loadAll(array('user'=>$user->login)) as $ufrLink)
  916. UserFirmRank::deleteById($ufrLink->id);
  917. if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
  918. if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
  919. Log::put("Suppression de l'utilisateur ".$user->toText(),'Utilisateur');
  920. });
  921. /** DROITS **/
  922. Action::register('core_right_search',function(&$response){
  923. global $myUser,$_;
  924. if(!$myUser->connected()) return $response;
  925. foreach(Right::loadAll(array('scope'=>$_['scope'],'uid'=>$_['uid'],'firm:IN'=>array($_['firm'],'NULL') )) as $right){
  926. $row = $right->toArray();
  927. if(!$right->read) unset($row['read']);
  928. if(!$right->edit) unset($row['edit']);
  929. if(!$right->delete) unset($row['delete']);
  930. if(!$right->configure) unset($row['configure']);
  931. if(!$right->recursive) unset($row['recursive']);
  932. if($row['firm']=='0') unset($row['firm']);
  933. if($right->targetScope == 'rank'){
  934. $row['target'] = '<i class="far fa-address-card"></i> '.Rank::getById($right->targetUid)->label;
  935. }else{
  936. $user = User::byLogin($right->targetUid);
  937. $row['target'] = '<img class="avatar avatar-mini avatar-rounded" src="'.$user->getAvatar().'"> '.$user->fullName();
  938. }
  939. $response['rows'][] = $row;
  940. }
  941. });
  942. //Récuperation ou edition d'élément right
  943. Action::register('core_right_save',function(&$response){
  944. global $myUser,$_;
  945. $right = new Right();
  946. $right->fromArray($_);
  947. $scopes = Right::availables('scope');
  948. if(!isset($scopes[$right->scope]) ||!isset($scopes[$right->scope]['check'])) throw new Exception("Aucun control d'accès n'a été défini sur cette section");
  949. if(!$myUser->superadmin){ //todo décommenter
  950. $check = $scopes[$right->scope]['check'];
  951. $check('save',$right);
  952. }
  953. $right->save();
  954. });
  955. Action::register('core_right_delete',function(&$response){
  956. global $myUser,$_;
  957. $right = Right::getById($_['id']);
  958. $scopes = Right::availables('scope');
  959. if(!isset($scopes[$right->scope]) ||!isset($scopes[$right->scope]['check'])) throw new Exception("Aucun control d'accès n'a été défini sur cette section");
  960. if(!$myUser->superadmin){ //todo décommenter
  961. $check = $scopes[$right->scope]['check'];
  962. $check('delete',$right);
  963. }
  964. Right::deleteById($_['id']);
  965. });
  966. //////////////////////
  967. Action::register('core_right_search',function(&$response){
  968. global $myUser,$_;
  969. User::check_access('rank','edit');
  970. if(!isset($_['firm'])) throw new Exception("Etablissement non spécifié");
  971. $wholeRights = array();
  972. $scopes = array();
  973. $scopes = Right::availables('scope');
  974. $firms = Firm::loadAll();
  975. $firms[] = Firm::anonymous_firm();
  976. foreach($firms as $firm){
  977. if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
  978. $rights = Right::loadAll(array('targetUid'=>$_['targetUid'],'firm'=>$firm->id));
  979. $rightsTable = array();
  980. foreach($rights as $right)
  981. $rightsTable[$right->scope] = $right;
  982. if($_['firm'] == '0'){
  983. foreach($scopes as $scope=>$options) {
  984. $right = isset($rightsTable[$scope])? $rightsTable[$scope] : new Right();
  985. $wholeRights[$scope]['read'][$firm->id] = (int)$right->read;
  986. $wholeRights[$scope]['edit'][$firm->id] = (int)$right->edit;
  987. $wholeRights[$scope]['delete'][$firm->id] = (int)$right->delete;
  988. $wholeRights[$scope]['configure'][$firm->id] = (int)$right->configure;
  989. }
  990. }
  991. }
  992. foreach ($scopes as $scope=>$options) {
  993. if(!$options['global']) continue;
  994. if($_['firm'] == '0'){
  995. $read = count(array_unique($wholeRights[$scope]['read'])) === 1 ? end($wholeRights[$scope]['read']) : 2;
  996. $edit = count(array_unique($wholeRights[$scope]['edit'])) === 1 ? end($wholeRights[$scope]['edit']) : 2;
  997. $delete = count(array_unique($wholeRights[$scope]['delete'])) === 1 ? end($wholeRights[$scope]['delete']) : 2;
  998. $configure = count(array_unique($wholeRights[$scope]['configure'])) === 1 ? end($wholeRights[$scope]['configure']) : 2;
  999. }else{
  1000. $right = isset($rightsTable[$scope])? $rightsTable[$scope] : new Right();
  1001. $read = $right->read;
  1002. $edit = $right->edit;
  1003. $delete = $right->delete;
  1004. $configure = $right->configure;
  1005. }
  1006. $response['rows'][] = array(
  1007. 'scope'=>$scope,
  1008. 'description'=>$options['label'],
  1009. 'read'=>(int)$read,
  1010. 'edit'=>(int)$edit,
  1011. 'delete'=>(int)$delete,
  1012. 'configure'=>(int)$configure
  1013. );
  1014. usort($response['rows'], function($a, $b){
  1015. return strcmp($a['scope'], $b['scope']);
  1016. });
  1017. }
  1018. });
  1019. Action::register('core_right_toggle',function(&$response){
  1020. global $myUser,$_,$myFirm;
  1021. User::check_access('rank','edit');
  1022. if(!isset($_['scope']) || empty($_['scope'])) throw new Exception("Scope non spécifié");
  1023. if(!isset($_['targetUid']) || empty($_['targetUid'])) throw new Exception("target Uid non spécifié");
  1024. if(!isset($_['right']) || empty($_['right'])) throw new Exception("Droit non spécifié");
  1025. if(!isset($_['firm'])) throw new Exception("Établissement non spécifié");
  1026. $firms = Firm::loadAll();
  1027. $firms[] = Firm::anonymous_firm();
  1028. foreach($firms as $firm){
  1029. if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
  1030. $item = Right::load(array('targetUid'=>$_['targetUid'],'firm'=>$firm->id,'scope'=>$_['scope']));
  1031. $item = !$item ? new Right() : $item ;
  1032. $item->targetUid = $_['targetUid'];
  1033. $item->firm = $firm->id;
  1034. $item->targetScope = 'rank';
  1035. $item->scope = $_['scope'];
  1036. $item->{$_['right']} = $_['state'];
  1037. $item->save();
  1038. $myUser->loadRights();
  1039. $_SESSION['currentUser'] = serialize($myUser);
  1040. }
  1041. });
  1042. /** RANGS **/
  1043. Action::register('core_rank_search',function(&$response){
  1044. global $myUser,$_;
  1045. User::check_access('rank','read');
  1046. $rankQry = 'SELECT *,(SELECT GROUP_CONCAT(CONCAT(f.label,":",`scope`,":",`read`,":",`edit`,":",`delete`,":",`configure`))
  1047. FROM `'.Right::tableName().'` r LEFT JOIN firm f ON f.id = r.firm
  1048. WHERE (r.read=? OR r.edit=? OR r.delete=? OR r.configure=?) AND r.targetUid={{table}}.id) as rights
  1049. FROM {{table}}';
  1050. $ranks = Rank::staticQuery($rankQry,array(1,1,1,1),true);
  1051. foreach($ranks as $rank){
  1052. $row = $rank->toArray(true);
  1053. //Gestion des rights sur les rangs "coeur" ayant des perms
  1054. $row['read'] = $row['edit'] = $row['delete'] = $row['configure'] = true;
  1055. if($rights = Right::loadAll(array('scope'=>'rank', 'uid'=>$rank->id))){
  1056. if(!$myUser->can('rank','read',$rank->id)) continue;
  1057. $row['edit'] = $myUser->can('rank','edit',$rank->id);
  1058. $row['delete'] = $myUser->can('rank','delete',$rank->id);
  1059. $row['configure'] = $myUser->can('rank','configure',$rank->id);
  1060. }
  1061. $row['rights'] = array();
  1062. foreach (explode(',', $rank->foreign('rights')) as $right) {
  1063. $infos = explode(':', $right);
  1064. $row['rights'][] = array(
  1065. 'configure' => !empty(array_pop($infos)),
  1066. 'delete' => !empty(array_pop($infos)),
  1067. 'edit' => !empty(array_pop($infos)),
  1068. 'read' => !empty(array_pop($infos)),
  1069. 'scope' => array_pop($infos),
  1070. 'firm' => array_pop($infos)
  1071. );
  1072. usort($row['rights'], function($a, $b){
  1073. return strcmp($a['firm'], $b['firm']);
  1074. });
  1075. }
  1076. $response['rows'][] = $row;
  1077. }
  1078. });
  1079. Action::register('core_rank_save',function(&$response){
  1080. global $myUser,$_;
  1081. User::check_access('rank','edit');
  1082. if(!isset($_['label']) || empty($_['label'])) throw new Exception("Libellé obligatoire");
  1083. $item = isset($_['id']) && !empty($_['id']) ? Rank::getById($_['id']) : new Rank();
  1084. $item->label = $_['label'];
  1085. $item->description = $_['description'];
  1086. $item->save();
  1087. Log::put("Ajout/Modification du rang ".$item->toText(),'Rang');
  1088. });
  1089. Action::register('core_rank_edit',function(&$response){
  1090. global $myUser,$_;
  1091. User::check_access('rank','edit');
  1092. $response = Rank::getById($_['id']);
  1093. });
  1094. Action::register('core_rank_delete',function(&$response){
  1095. global $myUser,$_;
  1096. User::check_access('rank','delete');
  1097. $rank = Rank::getById($_['id']);
  1098. Rank::deleteById($_['id']);
  1099. Log::put("Suppression du rang ".$rank->toText(),'Rang');
  1100. });
  1101. /** LISTES **/
  1102. Action::register('core_dictionary_search',function(&$response){
  1103. global $myUser,$_;
  1104. User::check_access('dictionary','read');
  1105. $parent = '';
  1106. if(!empty($_['parent']) && is_numeric($_['parent']))
  1107. $parent = $_['parent'];
  1108. foreach(Dictionary::loadAll(array('parent'=>$parent, 'state'=>Dictionary::ACTIVE), array(' label ASC ')) as $item){
  1109. $item->label = html_entity_decode($item->label);
  1110. $response['rows'][] = $item->toArray();
  1111. }
  1112. });
  1113. Action::register('core_dictionary_save',function(&$response){
  1114. global $myUser,$_;
  1115. User::check_access('dictionary','edit');
  1116. if(!isset($_['label']) || empty(trim($_['label']))) throw new Exception("Libellé obligatoire");
  1117. if(!is_numeric($_['parent'])){
  1118. if($myUser->can('dictionary','configure'))
  1119. $_['parent'] = 0;
  1120. else
  1121. throw new Exception("Veuillez sélectionner une liste");
  1122. }
  1123. $item = Dictionary::provide();
  1124. $item->label = trim($_['label']);
  1125. $item->parent = $_['parent'];
  1126. $item->state = Dictionary::ACTIVE;
  1127. if(!empty($_['slug'])){
  1128. $parameters = array('slug'=>$_['slug'], 'state'=>Dictionary::ACTIVE);
  1129. if(isset($item->id) && !empty($item->id)) $parameters['id:!='] = $item->id;
  1130. if(Dictionary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé");
  1131. $item->slug = $_['slug'];
  1132. }
  1133. if(empty($item->slug)){
  1134. $parentSlug = $_['parent'] == 0 ? '' : Dictionary::getById($_['parent'])->slug;
  1135. $slug = empty($parentSlug) ? $_['label'] : $parentSlug.'-'.$_['label'];
  1136. $item->slug = generateSlug($slug, Dictionary::class, 'slug', '', '_');
  1137. }
  1138. if(isset($_['sublistlabel'])) $item->sublistlabel = $_['sublistlabel'];
  1139. $item->save();
  1140. Log::put("Création/Modification de l'item de liste ".$item->toText(),'Liste');
  1141. });
  1142. Action::register('core_dictionary_edit',function(&$response){
  1143. global $myUser,$_;
  1144. User::check_access('dictionary','edit');
  1145. $dictionary = Dictionary::getById($_['id']);
  1146. $response = $dictionary->toArray(true);
  1147. });
  1148. Action::register('core_dictionary_delete',function(&$response){
  1149. global $myUser,$_;
  1150. User::check_access('dictionary','delete');
  1151. if(!isset($_['id']) || empty($_['id'])) throw new Exception("Aucun identifiant spécifié");
  1152. $item = Dictionary::getById($_['id']);
  1153. $item->state = Dictionary::INACTIVE;
  1154. $item->save();
  1155. Dictionary::change(array('state'=>Dictionary::INACTIVE), array('parent'=>$item->id));
  1156. Log::put("Suppression de la liste et des sous-listes associées".$item->toText(), 'Liste');
  1157. });
  1158. Action::register('core_dictionary_get_parent',function(&$response){
  1159. global $myUser,$_;
  1160. if(!$myUser->connected()) throw new Exception("permission denied");
  1161. $selected = Dictionary::loadAll(array("id"=>$_['selected']));
  1162. foreach ($selected as $item) {
  1163. if($item->parent == 0) {
  1164. $parents = Dictionary::loadAll(array("parent"=>$item->parent), array(' label ASC '));
  1165. } else {
  1166. $tmpParent = Dictionary::loadAll(array("id"=>$item->parent), array(' label ASC '));
  1167. $parents = Dictionary::loadAll(array("parent"=>$tmpParent[0]->parent), array(' label ASC '));
  1168. }
  1169. $parentId = !empty($tmpParent) ? $tmpParent[0]->id : '';
  1170. $response['rows'][] = array(
  1171. 'parents'=> $parents,
  1172. 'currentId'=> $item->id,
  1173. 'parentId'=> $parentId,
  1174. 'label'=> $item->label
  1175. );
  1176. }
  1177. });
  1178. Action::register('core_dictionary_component_load',function(&$response){
  1179. global $myUser,$_;
  1180. //double check afin de laisse la possiubilité aux non connectés de voir les listes sur certains projets
  1181. if(!$myUser->connected() && !$myUser->can('dictionary','read')){
  1182. $response['content'] = array();
  1183. return;
  1184. }
  1185. $dictionnaries = array();
  1186. if(isset($_['slug']) && $_['slug'] != ""){
  1187. $dictionnaries = Dictionary::load(array("slug"=>$_['slug']));
  1188. }else{
  1189. $dictionnaries = new Dictionary();
  1190. $dictionnaries->id = 0;
  1191. }
  1192. if(isset($_['parentId']) && $_['parentId'] != ""){
  1193. $dictionnaries = Dictionary::getById($_['parentId']);
  1194. $dictionnaries->id = 0;
  1195. }
  1196. if($dictionnaries) {
  1197. $dictionnaries = $dictionnaries->toArray();
  1198. if(!isset($_['depth'])) $_['depth'] = 1;
  1199. $dictionnaries['childs'] = Dictionary::childs(array('id'=>$dictionnaries['id']),array('depth'=>$_['depth'],'format'=>'array'));
  1200. }
  1201. if(isset($_['value']) && $_['value'] != "" ){
  1202. $output = is_numeric($_['value']) ? 'id' : 'slug';
  1203. if($output == 'id' && $_['value'] == 0) return $dictionnaries;
  1204. if(!$_['hierarchy'] || (isset($_['slug']) && $_['slug'] == "" )){
  1205. foreach ($dictionnaries['childs'] as $i => $child) {
  1206. if($child[$output] == $_['value']) $child['selected'] = true;
  1207. $dictionnaries['childs'][$i] = $child;
  1208. }
  1209. } else {
  1210. $dictionnaries = Dictionary::hierarchy($_['value'],$_['slug']);
  1211. }
  1212. }
  1213. $response['content'] = $dictionnaries;
  1214. });
  1215. Action::register('core_dictionary_slug_proposal',function(&$response){
  1216. global $myUser,$_;
  1217. if(!$myUser->connected()) throw new Exception("Permission denied");
  1218. if(!isset($_['label']) || empty($_['label'])) return;
  1219. //Check si l'item n'a pas déjà un slug
  1220. if(isset($_['id']) && !empty($_['id']) && is_numeric($_['id'])){
  1221. $item = Dictionary::provide();
  1222. if(!empty($item->slug)) return;
  1223. }
  1224. $parentSlug = empty($_['parent']) ? '' : Dictionary::getById($_['parent'])->slug;
  1225. $slug = empty($parentSlug) ? $_['label'] : $parentSlug.'_'.$_['label'];
  1226. $response['slug'] = generateSlug($slug, Dictionary::class, 'slug', '', '_');
  1227. });
  1228. /* Composant tag list */
  1229. Action::register('core_tag_list_autocomplete',function(&$response){
  1230. global $myUser,$_;
  1231. if(!$myUser->can('dictionary','read')) throw new Exception("Vous n'avez pas acces aux listes");
  1232. $response['rows'] = array();
  1233. foreach(Dictionary::staticQuery('SELECT * FROM {{table}} WHERE parent=(SELECT id from {{table}} WHERE slug= ? LIMIT 1) AND label LIKE ? AND state = ? ',array($_['data']['parent'],'%'.$_['keyword'].'%',Dictionary::ACTIVE),true) as $item){
  1234. $response['rows'][] = array(
  1235. 'name'=>$item->label,
  1236. 'id'=>$item->id,
  1237. 'slug'=>$item->slug
  1238. );
  1239. }
  1240. });
  1241. Action::register('core_tag_list_autocreate',function(&$response){
  1242. global $myUser,$_;
  1243. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  1244. $response = array();
  1245. $parent = Dictionary::bySlug($_['slug']);
  1246. $newtag = new Dictionary();
  1247. $newtag->state = Dictionary::ACTIVE;
  1248. $newtag->parent= $parent->id;
  1249. $newtag->label= $_['label'];
  1250. $newtag->slug= $parent->slug.'-'.slugify($_['label']);
  1251. $newtag->save();
  1252. $response = array(
  1253. 'name'=>$newtag->label,
  1254. 'id'=>$newtag->id,
  1255. 'slug'=>$newtag->slug
  1256. );
  1257. });
  1258. Action::register('core_tag_list_by_id',function(&$response){
  1259. global $myUser,$_;
  1260. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  1261. $response['tags'] = array();
  1262. $ids = explode(',',$_['id']);
  1263. foreach(Dictionary::loadAll(array('id:IN'=>$ids)) as $dictionary){
  1264. $dictionaryMapping[$dictionary->id] = $dictionary;
  1265. }
  1266. foreach ($ids as $id) {
  1267. if(!isset($dictionaryMapping[$id])) continue;
  1268. $item = $dictionaryMapping[$id];
  1269. $row = $item->toArray();
  1270. $row['label'] = $item->label;
  1271. $row['slug'] = $item->slug;
  1272. $row['id'] = $item->id;
  1273. $response['tags'][] = $row;
  1274. }
  1275. });
  1276. /** Composant tableau de dictionary */
  1277. Action::register('core_dictionary_table_search',function(&$response){
  1278. global $myUser,$_;
  1279. if(!$myUser->connected()) throw new Exception("permission denied");
  1280. if(!is_numeric($_['id'])) throw new Exception("Aucun identifiant de liste spécifié");
  1281. $dic = Dictionary::getById($_['id']);
  1282. $response['dictionary'] = $dic->toArray(true);
  1283. foreach (Dictionary::childs(array('slug'=>$dic->slug)) as $child)
  1284. $response['rows'][] = $child->toArray(true);
  1285. });
  1286. Action::register('core_dictionary_table_save',function(&$response){
  1287. global $myUser,$_;
  1288. if(!$myUser->connected()) throw new Exception("Permission denied");
  1289. if(!isset($_['label']) || empty($_['label'])) throw new Exception("Aucun libellé de liste renseigné");
  1290. if(!isset($_['id']) && !isset($_['list'])) throw new Exception("Aucun identifiant de liste ou de parent de liste trouvé");
  1291. $dic = isset($_['id']) && !empty($_['id'])? Dictionary::getById($_['id']) : new Dictionary();
  1292. $dic->parent = $_['list'];
  1293. $dic->label = $_['label'];
  1294. if(isset($_['slug']) && !empty($_['slug'])) {
  1295. $parameters = array('slug'=>$_['slug'], 'state'=>Dictionary::ACTIVE);
  1296. if(isset($dic->id) && !empty($dic->id)) $parameters['id:!='] = $dic->id;
  1297. if(Dictionary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé");
  1298. $dic->slug = $_['slug'];
  1299. }
  1300. $dic->state = Dictionary::ACTIVE;
  1301. $dic->save();
  1302. });
  1303. /* COMPOSANT LOCATION */
  1304. Action::register('core_location_search',function(&$response){
  1305. global $myUser,$_,$conf;
  1306. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  1307. $appUrl = $conf->get('maps_api_suggest_url');
  1308. $appId = $conf->get('maps_api_id');
  1309. $appKey = $conf->get('maps_api_key');
  1310. if(empty($appUrl) || empty($appId) || empty($appKey)) throw new Exception("Impossible d'initialiser le composant de localisation");
  1311. if(!isset($_['keyword']) || empty($_['keyword'])) return;
  1312. $default = array(
  1313. 'query' => $_['keyword'],
  1314. 'app_id' => $appId,
  1315. 'app_code' => $appKey
  1316. );
  1317. $params = array_merge($default, $_['data']);
  1318. $curlOpt = array(
  1319. CURLOPT_URL => sprintf("%s?%s", $appUrl, http_build_query($params)),
  1320. CURLOPT_HTTPHEADER => array(
  1321. 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
  1322. 'Content-Type: application/json',
  1323. ),
  1324. CURLOPT_RETURNTRANSFER => 1,
  1325. CURLOPT_HTTPAUTH => CURLAUTH_ANY,
  1326. CURLOPT_SSL_VERIFYPEER => false,
  1327. CURLOPT_SSL_VERIFYHOST => false,
  1328. );
  1329. $ch = curl_init();
  1330. curl_setopt_array($ch, $curlOpt);
  1331. $result = curl_exec($ch);
  1332. if($result === false) throw new Exception("Erreur de récupération cURL : ".curl_error($curl));
  1333. $result = json_decode($result);
  1334. $infos = curl_getinfo($ch);
  1335. curl_close($ch);
  1336. $response['rows'] = $result->suggestions;
  1337. });
  1338. Action::register('core_location_detail_search',function(&$response){
  1339. global $myUser,$_,$conf;
  1340. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  1341. $appUrl = $conf->get('maps_api_geocode_url');
  1342. $appId = $conf->get('maps_api_id');
  1343. $appKey = $conf->get('maps_api_key');
  1344. if(empty($appUrl) || empty($appId) || empty($appKey)) throw new Exception("Impossible de récupérer les détails de la localisation");
  1345. if(!isset($_['locationId']) || empty($_['locationId'])) return;
  1346. $params = array(
  1347. 'locationid' => $_['locationId'],
  1348. 'app_id' => $appId,
  1349. 'app_code' => $appKey
  1350. );
  1351. $curlOpt = array(
  1352. CURLOPT_URL => sprintf("%s?%s", $appUrl, http_build_query($params)),
  1353. CURLOPT_HTTPHEADER => array(
  1354. 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
  1355. 'Content-Type: application/json',
  1356. ),
  1357. CURLOPT_RETURNTRANSFER => 1,
  1358. CURLOPT_HTTPAUTH => CURLAUTH_ANY,
  1359. CURLOPT_SSL_VERIFYPEER => false,
  1360. CURLOPT_SSL_VERIFYHOST => false,
  1361. );
  1362. $ch = curl_init();
  1363. curl_setopt_array($ch, $curlOpt);
  1364. $response = curl_exec($ch);
  1365. if($response === false) throw new Exception("Erreur de récupération cURL : ".curl_error($curl));
  1366. $response = json_decode($response);
  1367. $infos = curl_getinfo($ch);
  1368. curl_close($ch);
  1369. });
  1370. /** CRONTAB */
  1371. Action::register('core_cron',function(&$response){
  1372. try{
  1373. if(php_sapi_name() !== 'cli') throw new Exception("Le cron ne peut être executé qu'en mode CLI depuis le serveur");
  1374. Plugin::callHook('cron', array(time()));
  1375. }catch(Exception $e){
  1376. file_put_contents(__DIR__.SLASH.'cron.log',date('d-m-Y H:i').' | '.$e->getMessage().PHP_EOL,FILE_APPEND);
  1377. }
  1378. });
  1379. /** FILES & UPLOADS */
  1380. //Gestion de l'upload temporaire (avant soumission d'un form)
  1381. Action::register('core_temporary_file_upload',function(&$response){
  1382. global $myUser,$_;
  1383. User::check_access('file','edit');
  1384. $response['previews'] = array();
  1385. $fileIndex = isset($_FILES[$_['index']]) ? $_FILES[$_['index']] : $_FILES['document'];
  1386. File::clear_temp();
  1387. for($i=0; $i<count($_FILES[$_['index']]['name']);$i++) {
  1388. $tempPath = File::temp().basename($fileIndex['tmp_name'][$i]);
  1389. move_uploaded_file($fileIndex['tmp_name'][$i], $tempPath);
  1390. $ext = getExt($fileIndex['name'][$i]);
  1391. $response['previews'][] = array(
  1392. 'path' => basename($fileIndex['tmp_name'][$i]),
  1393. 'name' => $fileIndex['name'][$i],
  1394. 'temporary' => true,
  1395. 'ext' => $ext,
  1396. 'url' => 'action.php?action=core_temporary_file_download&name='.$fileIndex['name'][$i].'&path='.basename($fileIndex['tmp_name'][$i]),
  1397. 'icon' => getExtIcon($ext)
  1398. );
  1399. }
  1400. });
  1401. Action::register('core_temporary_file_download',function(&$response){
  1402. global $myUser,$_;
  1403. User::check_access('file','read');
  1404. File::downloadFile(File::temp().$_['path'],$_['name']);
  1405. });
  1406. /** GENERAL SETTINGS **/
  1407. Action::register('core_general_settings_save',function(&$response){
  1408. global $myUser, $_, $conf;
  1409. User::check_access('setting_global','configure');
  1410. $_FILES = normalize_php_files();
  1411. if(isset($_FILES['fields'])) $_FILES = $_FILES['fields'];
  1412. $coreFolder = __ROOT__.FILE_PATH.'core'.SLASH;
  1413. if(!file_exists($coreFolder)) mkdir($coreFolder,0755,true);
  1414. //Ajout logo
  1415. if(!empty($_['logo-light'])){
  1416. $logo = File::save_component('logo-light', 'core/public/logo.{{extension}}');
  1417. Image::resize($logo[0]['absolute'], 200, 200);
  1418. Image::toPng($logo[0]['absolute']);
  1419. unset($_['logo-light']);
  1420. }
  1421. //Ajout logo dark
  1422. if(!empty($_['logo-dark'])){
  1423. $logo = File::save_component('logo-dark', 'core/public/logo.dark.{{extension}}');
  1424. Image::resize($logo[0]['absolute'], 200, 200);
  1425. Image::toPng($logo[0]['absolute']);
  1426. unset($_['logo-dark']);
  1427. }
  1428. //Ajout favicon
  1429. if(!empty($_['favicon'])){
  1430. $logo = File::save_component('favicon', 'core/public/favicon.{{extension}}');
  1431. Image::resize($logo[0]['absolute'], 16, 16);
  1432. Image::toPng($logo[0]['absolute']);
  1433. unset($_['favicon']);
  1434. }
  1435. //Durée de conservation des logs
  1436. foreach(Log::staticQuery('SELECT DISTINCT category FROM {{table}}',array(),true) as $log):
  1437. $slug = slugify($log->category);
  1438. $key = 'log_retention_time_'.$slug;
  1439. if(!isset($_[$key])) continue;
  1440. if($_[$key] == 0 || !is_numeric($_[$key])) $_[$key] = '';
  1441. $conf->put($key,$_[$key]);
  1442. endforeach;
  1443. //Gestion save des configuration générales
  1444. foreach(Configuration::setting('configuration-global') as $key => $value){
  1445. if(!is_array($value)) continue;
  1446. $allowedSettings[] = $key;
  1447. }
  1448. if(isset($_['logout_inactivity_delay']) && !empty($_['logout_inactivity_delay']) && $_['logout_inactivity_delay'] < 60) throw new Exception("Le délai d'inactivité doit être supérieur ou égal à 60");
  1449. foreach($_ as $key => $value)
  1450. if(in_array($key, $allowedSettings)) $conf->put($key, $value);
  1451. //Politique de mot de passes
  1452. if(isset($_['password_format'])) $conf->put('password_format',$_['password_format']);
  1453. //Maintenance
  1454. if(isset($_['maintenance'])){
  1455. if($_['maintenance']){
  1456. if(file_exists(File::dir().SLASH.'disabled.maintenance')) rename(File::dir().SLASH.'disabled.maintenance', File::dir().SLASH.'enabled.maintenance');
  1457. file_put_contents(File::dir().SLASH.'enabled.maintenance', trim($_['maintenance-content']));
  1458. } else {
  1459. if(file_exists(File::dir().SLASH.'enabled.maintenance')) rename(File::dir().SLASH.'enabled.maintenance', File::dir().SLASH.'disabled.maintenance');
  1460. file_put_contents(File::dir().SLASH.'disabled.maintenance', trim($_['maintenance-content']));
  1461. }
  1462. }
  1463. });
  1464. Action::register('core_general_password_reset_delay',function(&$response){
  1465. global $myUser, $_, $conf;
  1466. User::check_access('setting_global','configure');
  1467. foreach(User::getAll(array('right'=>false)) as $user)
  1468. $user->preference('passwordTime',strtotime('01/01/1990'));
  1469. });
  1470. //Récupération logo application générale
  1471. Action::register('core_general_logo',function(&$response){
  1472. global $myUser,$_;
  1473. User::check_access('setting_global','configure');
  1474. $variant = '';
  1475. if(!empty($_['data']) && !empty($_['data']['variant'])){
  1476. $variant = $_['data']['variant'];
  1477. $variant = $variant == 'light' ? '' : '.'.$variant;
  1478. }
  1479. File::handle_component(array(
  1480. 'namespace' => 'core', //stockés dans core/*.*
  1481. 'access' => 'setting_global', // crud sur core,
  1482. 'size' => '10000000', // taille max
  1483. 'storage' => 'core/public/logo'.$variant.'.{png,jpg,jpeg,gif}' //chemin complet vers le fichier stocké
  1484. ),$response);
  1485. });
  1486. //Récupération logo application générale
  1487. Action::register('core_general_favicon',function(&$response){
  1488. global $myUser,$_;
  1489. User::check_access('setting_global','configure');
  1490. File::handle_component(array(
  1491. 'namespace' => 'core', //stockés dans core/*.*
  1492. 'access' => 'setting_global', // crud sur core,
  1493. 'size' => '1000000', // taille max
  1494. 'extension' => 'png', // png uniquement
  1495. 'storage' => 'core/public/favicon.png' //chemin complet vers le fichier stocké
  1496. ),$response);
  1497. });
  1498. //Permet de se connecter "en tant que"
  1499. Action::register('core_user_impersonation',function(&$response){
  1500. try{
  1501. global $myUser,$myFirm,$_,$conf;
  1502. if(!$myUser->superadmin) throw new Exception("Seul le super administrateur peut exécuter cette fonctionnalité");
  1503. if(!isset($_['login'])) throw new Exception("Identifiant non spécifié");
  1504. if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
  1505. if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
  1506. $myUser = User::connectLogin($_['login']);
  1507. Log::put("Impersonation de l'utilisateur : ".$myUser->login,"Utilisateur");
  1508. $_SESSION['currentUser'] = serialize($myUser);
  1509. $_SESSION['firm'] = serialize($myFirm);
  1510. header('location: index.php?info='.rawurlencode('Connecté avec l\'utilisateur : '.$myUser->login));
  1511. } catch(Exception $e){
  1512. header('location: setting.php?section=user&error='.rawurlencode($e->getMessage()));
  1513. }
  1514. });
  1515. /* HISTORY */
  1516. Action::register('core_history_search',function(&$response){
  1517. global $myUser,$_;
  1518. User::check_access('history','read');
  1519. $filters = array();
  1520. $response['rows'] = array();
  1521. //Récuperation du nombre de messages importants uniquement
  1522. if(!empty($_['showImportant'])){
  1523. $data = array(History::IMPORTANCE_IMPORTANT);
  1524. $query = 'SELECT scope,uid,COUNT(id) thecount FROM {{table}} WHERE importance=? AND ( ';
  1525. $i=0;
  1526. foreach ($_['scopes'] as $scope=>$values) {
  1527. $marks = array_fill(0, count($values), '?');
  1528. $data[] = $scope;
  1529. $data = array_merge($data,$values);
  1530. $query .= ($i==0 ?'' :' OR ').' (scope = ? AND uid IN('.implode(',',$marks).')) ';
  1531. $i++;
  1532. }
  1533. $query .= ' ) GROUP BY scope,uid ';
  1534. $importants = History::staticQuery($query,$data)->fetchAll();
  1535. //On renvoie 0 s'il n'y a pas de résultat afin d'afficher les notifications de l'historique
  1536. if(empty($importants)){
  1537. foreach($_['scopes'] as $scope=>$values){
  1538. foreach($values as $uid){
  1539. $importants[] = array('scope'=>$scope,'uid'=>$uid,'thecount'=>0);
  1540. }
  1541. }
  1542. }
  1543. foreach($importants as $line)
  1544. $response['rows'][] = array('scope'=>$line['scope'],'uid'=>$line['uid'],'number'=>$line['thecount']);
  1545. //Récuperation du detail ghistorique pour un item
  1546. }else{
  1547. $filters['scope'] = $_['scope'];
  1548. if(isset($_['uid'])) $filters['uid'] = $_['uid'];
  1549. if(!empty($_['keyword'])) $filters['comment:LIKE'] = '%'.$_['keyword'].'%';
  1550. foreach(History::loadAll($filters,array('sort DESC')) as $history){
  1551. $row = $history->toArray();
  1552. $row['type'] = History::types($row['type']);
  1553. $row['comment'] = html_entity_decode($row['comment'],ENT_QUOTES,'UTF-8');
  1554. $row['created'] =array(
  1555. 'fullname'=>complete_date($row['created']),
  1556. 'time'=>date('H:i',$row['created'])
  1557. );
  1558. $user = User::byLogin($row['creator']);
  1559. $row['creator'] = array('fullname'=>(!is_null($user->login) ? $user->fullName() : $row['creator']));
  1560. $response['rows'][] = $row;
  1561. }
  1562. }
  1563. });
  1564. Action::register('core_history_importance_save',function(&$response){
  1565. global $myUser,$_;
  1566. User::check_access('history','edit');
  1567. $item = History::provide();
  1568. if(is_null($item->id)) return;
  1569. $item->importance = $_['importance'];
  1570. $item->save();
  1571. $response = $item->toArray();
  1572. });
  1573. Action::register('core_history_save',function(&$response){
  1574. global $myUser,$_,$myFirm;
  1575. User::check_access('history','edit');
  1576. $item = History::provide();
  1577. if(!$item) return;
  1578. if(isset($_['comment'])) $item->comment = $_['comment'];
  1579. $item->uid = $_['uid'];
  1580. //Si pas d'ordre défini on récupere l'ordre maximum
  1581. if(empty($_['sort'])) {
  1582. $query = History::staticQuery('SELECT MAX(sort) maxsort FROM {{table}} WHERE scope = ? AND uid= ? ',array($_['scope'],$item->uid));
  1583. $row = $query->fetch();
  1584. $_['sort'] = $row['maxsort']+1;
  1585. }
  1586. //Si l'ordre est intercalé a la place de l'ordre "replaceSort", on décale la rangée de "replaceSort" à n et on attribute "replaceSort" à l'élement
  1587. if(!empty($_['replaceSort'])) {
  1588. $_['sort'] = $_['replaceSort'];
  1589. History::staticQuery('UPDATE {{table}} SET sort = sort+1 WHERE sort >= ? AND scope = ? AND uid= ?',
  1590. array($_['replaceSort'],$_['scope'],$item->uid)) ;
  1591. }
  1592. $item->sort = $_['sort'];
  1593. $item->scope = $_['scope'];
  1594. $item->importance = $_['importance'];
  1595. $item->type = History::TYPE_COMMENT;
  1596. $item->meta = json_encode(array('url'=>$_['meta']));
  1597. $item->save();
  1598. if(!is_null($item->comment) && $myFirm->has_plugin('fr.core.notification')){
  1599. $mentionned = get_mention($item->comment);
  1600. if(isset($mentionned['user']) && !empty($mentionned['user'])){
  1601. $recipients = array();
  1602. foreach($mentionned['user'] as $user)
  1603. $recipients[] = $user->login;
  1604. $url = array();
  1605. if(!is_null($item->meta)){
  1606. $data = json_decode($item->meta,true);
  1607. foreach($data['url'] as $parameter=>$value)
  1608. $url[] = $parameter."=".$value;
  1609. }
  1610. $url = empty($url) ? '' : '?'.implode('&',$url);
  1611. // GESTION ENVOI NOTIFICATION
  1612. Plugin::callHook('emit_notification',array(array(
  1613. 'label' => 'Vous avez été mentionné dans un commentaire...',
  1614. 'html' => 'Un utilisateur vous a mentionné '.$item->scope,
  1615. 'type' => "notice",
  1616. 'meta' => array('link' => ROOT_URL.'/index.php'.$url),
  1617. 'recipients' => $recipients
  1618. )
  1619. ));
  1620. }
  1621. }
  1622. $response = $item->toArray();
  1623. });
  1624. Action::register('core_history_delete',function(&$response){
  1625. global $myUser,$_;
  1626. User::check_access('history','delete');
  1627. History::deleteById($_['id']);
  1628. });
  1629. /* CONTACT */
  1630. Action::register('core_contact_autocomplete',function(&$response){
  1631. global $myUser,$_;
  1632. if(!$myUser->can('contact','read')) throw new Exception("Vous n'avez pas acces aux contacts");
  1633. $response['rows'] = array();
  1634. $query = 'SELECT * FROM {{table}} p WHERE 1 ';
  1635. if(isset($_['keyword'])){
  1636. $query .= ' AND (p.firstname LIKE ? OR p.name LIKE ?) ';
  1637. $data = array('%'.$_['keyword'].'%','%'.$_['keyword'].'%');
  1638. }
  1639. if(isset($_['data']) && isset($_['data']['scope'])){
  1640. $query .= ' AND p.scope= ? ';
  1641. $data[]= $_['data']['scope'];
  1642. }
  1643. if(isset($_['data']) && isset($_['data']['uid'])){
  1644. $uids = array();
  1645. foreach($_['data']['uid'] as $uid){
  1646. $uids[] = '?';
  1647. $data[]= $uid;
  1648. }
  1649. $query .= ' AND p.uid IN ('.implode(',',$uids).') ';
  1650. }
  1651. $query .= ' ORDER BY name,firstname LIMIT 15';
  1652. foreach(ContactPerson::staticQuery($query,$data,true) as $item){
  1653. $response['rows'][] = array(
  1654. 'label'=>html_decode_utf8($item->fullName()),
  1655. 'id'=>$item->id,
  1656. 'job'=>$item->job
  1657. );
  1658. }
  1659. });
  1660. Action::register('core_contact_by_uid',function(&$response){
  1661. global $myUser,$_;
  1662. if(!$myUser->can('contact','read')) throw new Exception("Vous n'avez pas acces aux contacts");
  1663. $response['items'] = array();
  1664. $items = $_['items'];
  1665. foreach(ContactPerson::loadAll(array('id:IN'=>implode(',',$items))) as $item){
  1666. $row = $item->toArray();
  1667. $row['label'] = $item->fullname();
  1668. $row['job'] = $item->job;
  1669. $row['id'] = $item->id;
  1670. $response['items'][$item->id] = $row;
  1671. }
  1672. });
  1673. /** Gestion des fichiers **/
  1674. Action::register('core_file_search',function(&$response){
  1675. global $myUser, $_, $conf;
  1676. User::check_access('file','read');
  1677. $programRoot = rtrim(File::dir(),SLASH);
  1678. $root = !empty($_['root']) ? $programRoot.SLASH.trim($_['root'],SLASH) : $programRoot;
  1679. if(isset($_['folder']) && ($_['folder']=='.' || $_['folder']=='..')) $_['folder']=='';
  1680. $target = (!empty($_['folder'])) ? $programRoot.SLASH.rtrim($_['folder'],SLASH) : $root;
  1681. $path = explode(SLASH,str_replace($root,'',$target));
  1682. $path = array_values(array_filter($path));
  1683. $files = glob($root.SLASH.'*');
  1684. $currentPath = '';
  1685. for($i=0;$i<count($path);$i++){
  1686. $currentPath.= $path[$i].SLASH;
  1687. $files = array_merge($files,glob(File::dir().$currentPath.'*'));
  1688. }
  1689. $response['tree'] = array();
  1690. foreach($files as $file){
  1691. if(!is_dir($file)) continue;
  1692. $relativePath = str_replace( $root.SLASH,'',$file);
  1693. $response['tree'][] = $relativePath;
  1694. }
  1695. });
  1696. /** CUSTOM REWRITE */
  1697. Action::register('rewrite',function(&$response){
  1698. try{
  1699. $root = substr($_SERVER['SCRIPT_NAME'], 0,strrpos($_SERVER['SCRIPT_NAME'] , '/'));
  1700. $requested = substr($_SERVER['REQUEST_URI'], strlen($root)+1);
  1701. ob_start();
  1702. Plugin::callHook('rewrite',array($requested));
  1703. $stream = ob_get_clean();
  1704. if($stream !='') echo $stream;
  1705. }catch(Exception $e){
  1706. exit('<div style="width:300px;margin:30px auto;padding:15px;background:#cecece;text-align:center;font-family:Arial">'.$e->getMessage().'</div>');
  1707. }
  1708. });
  1709. /** ACTIONS DE PLUGINS */
  1710. if(isset($GLOBALS['actions'][$_['action']])) Action::write($GLOBALS['actions'][$_['action']]);
  1711. ?>