123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100 |
- <?php
- if(!ini_get('safe_mode')) @set_time_limit(0);
- require_once __DIR__.DIRECTORY_SEPARATOR."common.php";
- if(php_sapi_name() == 'cli'){
- array_shift($_SERVER['argv']);
- $_['action'] = array_shift($_SERVER['argv']);
- foreach ($_SERVER['argv'] as $keyvalue) {
- $infos = explode('=',$keyvalue);
- $key = $infos[0];
- $value = count($infos)<2 ? '' : $infos[1];
- $_[$key] = $value;
- }
- }
- if(!isset($_['action'])) throw new Exception('Action inexistante');
- /*
- Authentification
- */
- //Connexion
- Action::register('core_login',function(&$response){
- global $myUser,$myFirm,$_,$conf;
- try {
- if(!isset($_['login'])) $_['login'] = 'anonymous';
- if(!isset($_['password'])) $_['password'] = '';
- Log::put("Tentative de connexion avec le login \"".$_['login']."\"",'Utilisateur');
- if($conf->get('account_block')==1){
- $try = is_numeric($conf->get('account_block_try')) ? $conf->get('account_block_try') : 5;
- $delay = is_numeric($conf->get('account_block_delay')) ? $conf->get('account_block_delay') : 10;
- $trying = Log::loadAll(array('category'=>'auth_fail', 'label'=>$_['login'], 'created:>'=>(time() - ($delay*60))));
- 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);
- }
- $myUser = User::check($_['login'],html_entity_decode($_['password']));
- if(!$myUser) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
- 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');
- if(!$myUser->connected()) throw new Exception('Identifiant ou mot de passe incorrect');
- //Suppression du token de reset de password s'il se reconnecte entre temps
- UserPreference::delete(array('user'=>$myUser->login,'key'=>'lost_password'));
- $myUser->loadPreferences();
- if(is_numeric($myUser->preference('default_firm')) && $myUser->haveFirm($myUser->preference('default_firm'))){
- $_SESSION['firm'] = serialize(Firm::getById($myUser->preference('default_firm')));
- if(!$_SESSION['firm']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
- } else if(count($myUser->firms)!=0) {
- $_SESSION['firm'] = serialize(reset($myUser->firms));
- if(!$_SESSION['firm']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
- } else {
- throw new Exception('Ce compte n\'est actif sur aucun établissement');
- }
- $myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']) : new Firm();
- if(!$myFirm) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
- $_SESSION['currentUser'] = serialize($myUser);
- if(!$_SESSION['currentUser']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
- //Gestion de l'inactivité de l'utilisateur
- $inactivityDelay = $conf->get('logout_inactivity_delay');
- if(!empty($inactivityDelay) && is_numeric($inactivityDelay)){
- $response['inactivityDelay'] = $inactivityDelay;
- $myUser->meta['lastActivity'] = time();
- }
- if(isset($_['rememberMe']) && $_['rememberMe']){
- $cookie = password_hash(mt_rand(0,1000000000000).uniqid("", true).mt_rand(0,1000000000000), PASSWORD_DEFAULT);
- $myUser->preference('cookie',$cookie);
- make_cookie(COOKIE_NAME, $cookie);
- } else {
- $myUser->preference('cookie','');
- }
- $response['redirect'] = isset($_['url']) ? base64_decode($_['url']) : 'index.php';
- if(isset($_SESSION['last_request']) && !isset($_['url'])){
- $response['redirect'] = $_SESSION['last_request'];
- unset($_SESSION['last_request']);
- }
- Plugin::callHook('user_logged',array(&$myUser));
- //permet la redirection classic pour certains plugin d'authentification qui ne passent pas par le formulaire ajax
- if(isset($_['redirect']) && $_['redirect']=='classic'){
- header('location: '. $response['redirect']);
- exit();
- }
- Log::put("Connexion réussie avec \"".$myUser->login."\"",'Utilisateur');
- } catch(Exception $e){
- Log::put("Échec de la connexion avec ".$_['login']." : ".$e->getMessage(),'Utilisateur');
- //La vérification sur le code 509 permet d'éviter d'allonger le temps de ban à chaque tentative
- if($e->getCode()!=509) Log::put($_['login'],'auth_fail');
- throw new Exception($e->getMessage());
- }
- });
- //Déconnexion
- Action::register('core_logout',function(&$response){
- global $myUser,$_;
- $url = $myUser->disconnect(isset($_['url'])?$_['url']:null);
- Plugin::callHook('logout',array($url,$myUser));
- $response['redirect'] = $url;
- });
- //Vérification de la présence
- Action::register('initialize_activity',function(&$response){
- global $myUser;
- if(!$myUser->connected()) throw new Exception("Permission non accordée");
- $myUser->meta['lastActivity'] = time();
- });
- /** Tables de recherches **/
- //Save des colonnes dynamiques
- Action::register('core_table_colum_save',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) return;
- $preferences = json_decode($myUser->preference('search_columns'),true);
- if(!$preferences) $preferences = array();
- if(!isset($_['slug'])) return $response;
- if(empty($_['added'])) $_['added'] = array();
- $preferences[$_['slug']] = $_['added'];
- $myUser->preference('search_columns',json_encode($preferences));
- $_SESSION['currentUser'] = serialize($myUser);
- });
- //Load des colonnes dynamiques
- Action::register('core_table_colum_search',function(&$response){
- global $myUser,$_;
- if(!isset($myUser)) throw new Exception("Utilisateur non définis");
- $response = json_decode($myUser->preference('search_columns'),true);
- if(!$response) $response = array();
- return $response;
- });
- //Save des fitlres de recherches en preference
- Action::register('core_filter_save',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Permission non accordée");
- $preferences = json_decode($myUser->preference('search_filters'),true);
- if(!$preferences) $preferences = array();
- if(!isset($_['slug'])) return $response;
- if(empty($_['label'])) throw new Exception("Libellé obligatoire");
- function filter_recursive_save($filters){
- foreach($filters as $i=>$advanced){
- if(isset($filters[$i]['operator'])) $filters[$i]['operator'] = html_entity_decode($filters[$i]['operator']);
- if(isset($filters[$i]['group'])) $filters[$i]['group'] = filter_recursive_save($filters[$i]['group']);
- if(!isset($filters[$i]['value'])) continue;
- foreach($filters[$i]['value'] as $j => $value)
- $filters[$i]['value'][$j] = html_entity_decode($value,ENT_QUOTES,'UTF-8');
- }
- return $filters;
- }
- if(isset($_['filters']['keyword'])) $_['filters']['keyword'] = html_entity_decode($_['filters']['keyword'],ENT_QUOTES,'UTF-8');
- if(isset($_['filters']['advanced'])) $_['filters']['advanced'] = filter_recursive_save($_['filters']['advanced']);
- if(!isset($preferences[$_['slug']])) $preferences[$_['slug']] = array();
- $_['label'] = html_entity_decode($_['label'],ENT_QUOTES,'UTF-8');
- $uid = base64_encode($_['label']);
- $preferences[$_['slug']][$uid] = array(
- 'label' => $_['label'],
- 'uid' => $uid,
- 'filters'=> $_['filters']
- );
- $myUser->preference('search_filters',json_encode($preferences));
- $response['message'] = 'Recherche enregistrée';
- $_SESSION['currentUser'] = serialize($myUser);
- });
- /**
- * Suppression d'une recherche enregistrée
- * @param boolean global Définit si la recherche est globale ou non
- * @param string slug Représente le slug de la table de résultats associée
- * @param
- * */
- Action::register('core_filter_delete',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Permission denied");
- if(!$myUser->superadmin && isset($_['global']) && !empty($_['global'])) throw new Exception("Impossible de supprimer une recherche partagée");
- $preferences = json_decode($myUser->preference('search_filters'),true);
- unset($preferences[$_['slug']][$_['uid']]);
- $myUser->preference('search_filters',json_encode($preferences));
- $_SESSION['currentUser'] = serialize($myUser);
- });
- Action::register('core_filter_global_save',function(&$response){
- global $myUser,$_,$conf;
- if((empty($_['rightSection']) && !$myUser->superadmin) || (isset($_['rightSection']) && !$myUser->can($_['rightSection'], 'configure'))) throw new Exception("Permissions insuffisantes", 403);
- if(empty($_['slug']) || empty($_['uid'])) return $response;
- $globalPreferences = json_decode($conf->get('search_filters'),true);
- $preferences = json_decode($myUser->preference('search_filters'),true);
- if($_['state']==1){
- $globalPreferences[$_['slug']][$_['uid']] = $preferences[$_['slug']][$_['uid']];
- unset($preferences[$_['slug']][$_['uid']]);
- }else{
- $preferences[$_['slug']][$_['uid']] = $globalPreferences[$_['slug']][$_['uid']];
- unset($globalPreferences[$_['slug']][$_['uid']]);
- }
- $conf->put('search_filters',json_encode($globalPreferences));
- $myUser->preference('search_filters',json_encode($preferences));
- $_SESSION['currentUser'] = serialize($myUser);
- });
- Action::register('core_filter_search',function(&$response){
- global $myUser,$_,$conf;
- if(!isset($myUser)) throw new Exception("Utilisateur non définis");
- if(empty($_['slug'])) return $response;
- $searches = array();
- $globalPreferences = json_decode($conf->get('search_filters'),true);
- $preferences = json_decode($myUser->preference('search_filters'),true);
- if(is_array($preferences) && isset($preferences[$_['slug']])){
- foreach($preferences[$_['slug']] as $preference){
- if(!isset($preference['label'])) continue;
- $preference['global'] = 0;
- $searches[$preference['uid']] = $preference;
- }
- }
- if(is_array($globalPreferences ) && isset($globalPreferences[$_['slug']])){
- foreach($globalPreferences[$_['slug']] as $preference){
- if(!isset($preference['label'])) continue;
- $preference['global'] = 1;
- $searches[$preference['uid']] = $preference;
- }
- }
- $response['filters'] = $searches;
- });
- /** LOGS */
- Action::register('core_search_log',function(&$response){
- global $myUser,$_;
- User::check_access('log','read');
- $limit = isset($_['export']) && $_['export'] == 'true' ? 5000 : 150;
- $data = array();
- $query = 'SELECT * FROM {{table}} WHERE 1';
- //Recherche simple
- if(!empty($_['filters']['keyword'])){
- $query .= ' AND label LIKE ?';
- $data[] = '%'.$_['filters']['keyword'].'%';
- }
- //Recherche avancée
- if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('label','category','creator','created','ip'),$query,$data);
- //Tri des colonnes
- if(isset($_['sort']))
- sort_secure_query($_['sort'],array('label','ip','created','category','creator'),$query,$data);
- else
- $query .= ' ORDER BY created DESC, id DESC ';
- //Pagination
- $response['pagination'] = Log::paginate($limit,(!empty($_['page'])?$_['page']:0),$query,$data);
- foreach(Log::staticQuery($query,$data,true) as $log){
- $row = $log->toArray(true);
- $row['created'] = date('d/m/Y H:i:s', $log->created);
- $row['created_full'] = date('Y-m-d', $log->created);
- if(!empty($_['filters']['keyword'])){
- $row['label'] = preg_replace_callback('|(.*)('.$_['filters']['keyword'].')(.*)|i', function($matches){
- return $matches[1].'<mark><strong>'.$matches[2].'</strong></mark>'.$matches[3];
- }, htmlentities($log->label, ENT_QUOTES));
- }
- $response['rows'][] = $row;
- }
- //Export des données
- if(isset($_['export']) && $_['export'] == 'true') {
- //Clear des marqueurs HTML
- foreach($response['rows'] as $i => $row) {
- $row['label'] = html_entity_decode(strip_tags($row['label']));
- $response['rows'][$i] = $row;
- }
- $mapping = array(
- 'Date' => array('slug'=>'created_full', 'type'=>'DD/MM/YYYY'),
- 'Catégorie' => 'category',
- 'Libellé' => 'label',
- 'Utilisateur' => 'creator',
- 'Ip' => 'ip',
- );
- $export = Excel::exportArray($response['rows'], $mapping, 'Logs');
- File::downloadStream($export,'export-logs-'.date('ymd').'.xlsx');
- Log::put("Export logs : ".(isset($_['filters']) ? " Filtres: ".json_encode($_['filters']) : '').", Tri: ".(isset($_['sort'])?json_encode($_['sort']):'').", Page: ".$_['page'],'Produit');
- exit();
- }
- });
- /* Gestion des entitées */
- //Récuperation d'une liste d'entitées en fonction du plugin ciblé
- Action::register('core_entity_search',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Permission refusée");
- if(empty($_['plugin'])) throw new Exception('Plugin non spécifié');
- foreach(glob($_['plugin'].SLASH.'*.class.php') as $file){
- require_once($file);
- $class = str_replace('.class.php','',basename($file));
- if(!is_subclass_of($class, 'Entity')) continue;
- $instance = new $class();
- $label = $class;
- $table = strtolower($class);
- if(property_exists($instance,'entityLabel') && !empty($instance->entityLabel)) $label = $instance->entityLabel;
- if(method_exists($instance,'tableName') && !empty($instance->tableName())) $table = $instance->tableName();
- $response['rows'][] = array(
- 'class'=> $class,
- 'label'=> $label,
- 'table'=> $table ,
- 'path' => $file
- );
- }
- });
- //Récuperation des infos générales d'une entitée
- Action::register('core_entity_edit',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Permission refusée");
- if(empty($_['path'])) throw new Exception('Chemin non spécifié');
- $file = $_['path'];
- require_once($file);
- $class = str_replace('.class.php','',basename($file));
- if(!is_subclass_of($class, 'Entity')) return;
- $instance = new $class();
- $label = $class;
- $table = strtolower($class);
- if(property_exists($instance,'entityLabel') && !empty($instance->entityLabel)) $label = $instance->entityLabel;
- if(method_exists($instance,'tableName') && !empty($instance->tableName())) $table = $instance->tableName();
- $response = array(
- 'class'=> $class,
- 'label'=> $label,
- 'table'=> $table ,
- 'path' => $file,
- 'plugin' => Plugin::parseManifest(dirname($file).SLASH.'app.json')
- );
- });
- //Récuperation de la liste des attributs d'une entitée
- Action::register('core_entity_attribute_search',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Permission refusée");
- if(empty($_['path'])) throw new Exception('Chemin non spécifié');
- $file = $_['path'];
- require_once($file);
- $class = str_replace('.class.php','',basename($file));
- if(!is_subclass_of($class, 'Entity')) return;
- $instance = new $class();
- $fields = $instance->fields(false);
- if(property_exists($instance,'links')){
- foreach($instance->links as $field=>$classFile){
- $classFile = __ROOT__.SLASH.$classFile;
- if(!file_exists($classFile)) continue;
- require_once($classFile);
- $subClass = str_replace('.class.php','',basename($classFile));
- if(!is_subclass_of($subClass, 'Entity')) continue;
- $subInstance = new $subClass();
- $fields[$field]['entity'] = $subClass;
- $fields[$field]['classFile'] = $classFile;
- $fields[$field]['childs'] = $subInstance->fields(false);
- }
- };
- $response['fields'] = $fields;
- });
- /* PLUGINS */
- Action::register('core_plugin_search',function(&$response){
- global $myUser,$_;
- User::check_access('plugin','read');
- $includeCore = isset($_['includeCore']) && $_['includeCore']==true ;
- $firms = array();
- foreach(Firm::loadAll() as $firm)
- $firms[] = $firm->toArray();
- foreach(Plugin::getAll(true) as $plugin)
- $firmPluginMapping[$plugin->id] = $plugin->firms;
- foreach(Plugin::getAll(false,$includeCore) as $plugin){
- $plugin->folder = array('name'=>$plugin->folder,'path'=>$plugin->path());
- foreach($plugin->require as $id=>$version)
- $plugin->required[] = array('id'=>$id, 'version'=>$version);
- $row = $plugin->toArray();
- $row['firms'] = array_values($firms);
- foreach($row['firms'] as $i=>$firm){
- $row['firms'][$i]['value'] = isset($firmPluginMapping[$plugin->id]) && in_array($firm['id'],$firmPluginMapping[$plugin->id]) ? 1 : 0;
- }
- $response['rows'][] = $row;
- }
- });
- Action::register('core_plugin_state_save',function(&$response){
- global $myUser,$_;
- User::check_access('plugin','configure');
- $plugin = Plugin::getById($_['plugin']);
- if($_['state']){
- $states = Plugin::states();
- $missingRequire = array();
- foreach($plugin->require as $require=>$version):
- $req = Plugin::getById($require);
- if($req == null || $req==false || !$req->state || $req->version!=$version)
- $missingRequire[]= $require.' - '.$version;
- endforeach;
- if(count($missingRequire)!=0) throw new Exception("Plugins pré-requis non installés : ".implode(',',$missingRequire));
- }
- Plugin::state($_['plugin'],$_['state']);
- Log::put(($_['state']?'Activation':'Désactivation')." du plugin ".$_['plugin'],'Plugin');
- });
- /** ETABLISSEMENT */
- //Récuperation d'une liste de etablissement
- Action::register('core_firm_search',function(&$response){
- global $_;
- User::check_access('firm','read');
- // OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
- $query = 'SELECT main.* FROM '.Firm::tableName().' main WHERE 1';
- $data = array();
- //Recherche simple
- if(!empty($_['filters']['keyword'])){
- $query .= ' AND main.label LIKE ?';
- $data[] = '%'.$_['filters']['keyword'].'%';
- }
- //Recherche avancée
- 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);
- //Tri des colonnes
- 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);
- //Pagination
- //Par défaut pour une recherche, 20 items, pour un export 5000 max
- $itemPerPage = !empty($_['itemPerPage']) ? $_['itemPerPage'] : 20;
- //force le nombre de page max a 50 coté serveur
- $itemPerPage = $itemPerPage>50 ? 50 : $itemPerPage;
- if($_['export'] == 'true') $itemPerPage = 5000;
- $response['pagination'] = Firm::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');
- $firms = Firm::staticQuery($query,$data,true,0);
- $response['rows'] = array();
- foreach($firms as $firm){
- $row = $firm->toArray();
- $row['description'] = html_entity_decode($row['description']);
- $row['logo'] = $firm->logo('url');
- if($_['export'] == 'true'){
- $row['created'] = date('d-m-Y',$row['created']);
- $row['updated'] = date('d-m-Y',$row['updated']);
- }
- $response['rows'][] = $row;
- }
- /* Mode export */
- if($_['export'] == 'true'){
- if(empty($response['rows'])) $response['rows'][] = array('Vide'=>'Aucune données');
- $fieldsMapping = array();
- foreach (Firm::fields(false) as $key => $value)
- $fieldsMapping[$value['label']] = $key;
- $stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
- File::downloadStream($stream,'export-etablissements-'.date('d-m-Y').'.xlsx');
- exit();
- }
- });
- //Ajout ou modification d'élément etablissement
- Action::register('core_firm_save',function(&$response){
- global $_;
- User::check_access('firm','edit');
- $item = Firm::provide();
- $item->label = $_['label'];
- $item->description = $_['description'];
- $item->mail = $_['mail'];
- $item->phone = $_['phone'];
- $item->fax = $_['fax'];
- $item->street = $_['street'];
- $item->street2 = $_['street2'];
- $item->city = $_['city'];
- $item->zipcode = $_['zipcode'];
- $item->siret = $_['siret'];
- $item->iban = $_['iban'];
- $item->save();
- //Ajout upload Logo
- if(!empty($_['logo']))
- File::save_component('logo', 'core/public/firm/'.$item->id.'/logo.{{extension}}');
- $response = $item->toArray();
- });
- //Suppression d'élement etablissement
- Action::register('core_firm_delete',function(&$response){
- global $_;
- User::check_access('firm','delete');
- if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
- $firm = Firm::getById($_['id']);
- Firm::deleteById($firm->id);
- //Suppression de l'établissmeent supprimé dans les plugins activés
- $states = Plugin::states();
- foreach ($states as $plugin => $firms) {
- $key = array_search($_['id'], $firms);
- if($key === false) continue;
- unset($firms[$key]);
- $states[$plugin] = array_values($firms);
- }
- Plugin::states($states);
- //Suppression des liens UFR et des droits associés
- UserFirmRank::delete(array('firm'=>$_['id']));
- Right::delete(array('firm'=>$_['id']));
- Log::put("Suppression de l'établissement ".$firm->toText(),'Etablissement');
- });
- //Firm : Gestion upload Logo
- Action::register('core_firm_logo',function(&$response){
- File::handle_component(array(
- 'namespace' => 'core', //stockés dans file/core/*.*
- 'access' => 'core', // crud sur core,
- 'size' => '1000000000', // taille max
- 'limit' => '1', // nb max de fichiers
- 'storage' => 'core/public/firm/{{data.id}}/logo.*' //chemin complet vers le fichier stocké
- ),$response);
- });
- Action::register('core_firm_select',function(&$response){
- global $myUser,$_,$myFirm;
- try{
- if(!$myUser->connected()) throw new Exception("Permission denied");
- if(!$myUser->haveFirm( $_['firm'])) throw new Exception("Vous n'avez pas accès à cet établissement");
- $myFirm = Firm::getById($_['firm']);
- $_SESSION['firm'] = serialize($myFirm);
- $myUser->preference('default_firm',$myFirm->id);
- $myUser->loadRights();
- $_SESSION['currentUser'] = serialize($myUser);
- if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
- if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
- header('location: index.php');
- }catch(Exception $e){
- header('location: index.php?error='.urlencode($e->getMessage()));
- }
- });
- Action::register('core_firm_autocomplete',function(&$response){
- global $myUser,$_;
- if(!$myUser->can('firm','read')) throw new Exception("Vous n'avez pas acces aux établissements");
- $response['rows'] = array();
- if($_['keyword'] == '') return;
- foreach(Firm::loadAll(array('label:like'=> '%'.$_['keyword'].'%' ),array('label')) as $firm){
- $response['rows'][] = array(
- 'label'=>$firm->label,
- 'id'=>$firm->id,
- 'description'=>$firm->description
- );
- }
- });
- Action::register('core_firm_by_uid',function(&$response){
- global $myUser,$_;
- if(!$myUser->can('firm','read')) throw new Exception("Vous n'avez pas acces aux établissements");
- $response['items'] = array();
- $firms = $_['items'];
- foreach(Firm::loadAll(array('id:IN'=>implode(',',$firms))) as $item){
- $row = $item->toArray();
- $row['label'] = $item->label;
- $row['id'] = $item->id;
- $response['items'][$item->id] = $row;
- }
- });
- /** LIEN ETABLISSEMENT / PLUGIN **/
- Action::register('core_firm_plugin_search',function(&$response){
- global $myUser,$_;
- User::check_access('plugin','configure');
- if(!isset($_['firm'])) throw new Exception("Établissement non spécifié");
- $wholePlugins = array();
- if($_['firm'] == '0'){
- foreach(Firm::loadAll() as $firm){
- foreach(Plugin::getAll(true) as $plugin){
- $wholePlugins[$plugin->id][$firm->id] = in_array($firm->id, $plugin->firms) ? 1 : 0;
- }
- }
- }
- foreach(Plugin::getAll(true) as $plugin){
- if($_['firm'] == '0'){
- $plugin->state = count(array_unique($wholePlugins[$plugin->id])) === 1 ? end($wholePlugins[$plugin->id]) : 2;
- }else{
- $plugin->state = in_array($_['firm'], $plugin->firms) ? 1 : 0;
- }
- $response['rows'][] = $plugin;
- }
- });
- Action::register('core_firm_plugin_save',function(&$response){
- global $myUser,$_;
- User::check_access('plugin','configure');
- $firms = Firm::loadAll();
- $firms[] = Firm::anonymous_firm();
- foreach($firms as $firm){
- if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
- $states = Plugin::states();
- $firms = $states[$_['plugin']];
- $key = array_search($firm->id, $firms);
- if($_['state']==0 && $key !== false){
- unset($firms[$key]);
- }else if($_['state']==1 && $key === false){
- $firms[] = $firm->id;
- }
- $states[$_['plugin']] = array_values($firms);
- Plugin::states($states);
- }
- });
- /** LIEN ETABLISSEMENT / UTILISATEUR / RANG **/
- Action::register('core_userfirmrank_search',function(&$response){
- global $myUser,$_;
- User::check_access('rank','read');
- $firms = array($_['firm']);
- if($_['firm'] == 0){
- $firms = array();
- foreach(Firm::loadAll() as $firm)
- $firms[] = $firm->id;
- }
- $users = array();
- foreach(User::getAll(array('right'=>false)) as $user)
- $users[$user->login] = $user;
- foreach(UserFirmRank::staticQuery("SELECT *, ufr.id id, u.id uid, r.label rank, f.label firm
- FROM {{table}} ufr
- LEFT JOIN ".User::tableName()." u ON ufr.user=u.login
- LEFT JOIN ".Rank::tableName()." r ON r.id=ufr.rank
- LEFT JOIN ".Firm::tableName()." f ON f.id=ufr.firm
- WHERE ufr.firm IN (".str_repeat('?,', count($firms) - 1) . '?'.")",$firms,false) as $userFirmRank){
- if(empty($myUser->superadmin) && !empty($userFirmRank['superadmin'])) continue;
- $user = isset($users[$userFirmRank['user']]) ? $users[$userFirmRank['user']] : new User();
- // Petit trick pour l'affichage mustache
- $userFirmRank['superadmin'] = !empty($userFirmRank['superadmin']);
- $userFirmRank['avatar'] = $user->getAvatar();
- $userFirmRank['password'] = '';
- $user->name = $user->lastname();
- $user->firstname = $user->firstname();
- $userFirmRank['user'] = $user;
- $response['rows'][] = $userFirmRank;
- }
- });
- Action::register('core_userfirmrank_save',function(&$response){
- global $myUser,$_;
- User::check_access('rank','edit');
- if(!isset($_['firm'])) throw new Exception('Champ "Établissement" obligatoire');
- if(!isset($_['user']) || empty($_['user'])) throw new Exception('Champ "Utilisateur" obligatoire');
- if(!isset($_['rank']) || empty($_['rank'])) throw new Exception('Champ "Rang" obligatoire');
- foreach(Firm::loadAll() as $firm){
- if($_['firm'] != 0 && $_['firm'] != $firm->id) continue;
- $user = User::byLogin(stripslashes($_['user']));
- $rank = Rank::getById($_['rank']);
- if($user->origin == 'active_directory' && (!array_key_exists($firm->id, $user->firms) || !$firm->has_plugin('fr.core.activedirectory'))) continue;
- $userFirmRank = UserFirmRank::provide();
- $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']));
- if($exist > 0){
- $response['warning'][] = "Le rang ".$rank->label." est déja défini pour ".$user->fullName()." sur l'établissement ".$firm->label;
- continue;
- }
- $userFirmRank->fromArray($_);
- $userFirmRank->firm = $firm->id;
- $userFirmRank->user = $user->login;
- $userFirmRank->save();
- $response['success'][] = "Rang ".$rank->label." ajouté pour ".$user->fullName()." sur l'établissement ".$firm->label;
- }
- });
- Action::register('core_userfirmrank_edit',function(&$response){
- global $myUser,$_;
- User::check_access('rank','edit');
- $userFirmRank = UserFirmRank::getById($_['id']);
- $response = $userFirmRank;
- });
- Action::register('core_userfirmrank_delete',function(&$response){
- global $myUser,$_,$conf;
- User::check_access('rank','delete');
- $userFirmRank = UserFirmRank::provide();
- $user = User::byLogin($userFirmRank->user);
- if($user->preference('default_firm') == $userFirmRank->firm)
- UserPreference::delete(array('user'=>$user->login, 'key'=>'default_firm'));
- UserFirmRank::deleteById($_['id']);
- });
- /** UTILISATEURS **/
- Action::register('core_user_search',function(&$response){
- global $myUser,$_;
- User::check_access('user','read');
- foreach(User::getAll(array('right'=>false,'force'=> true)) as $user){
- if($user->state == User::INACTIVE || (!$myUser->superadmin && $user->superadmin)) continue;
- $user->login = htmlspecialchars_decode($user->login);
- $user->name = $user->lastname();
- $user->firstname = $user->firstname();
- $user->avatar = $user->getAvatar();
- $user->formatedLogin = urlencode($user->login);
- $response['rows'][] = $user;
- }
- });
- Action::register('core_user_autocomplete',function(&$response){
- global $myUser,$_,$myFirm;
- if(!$myUser->can('user','read')) throw new Exception("Vous n'avez pas acces aux utilisateurs");
- $response['rows'] = array();
- $scope = isset($_['data']['scope']) ? $_['data']['scope'] : $myFirm->id;
- if($_['keyword'] == '') return;
- if(in_array('user', $_['data']['types'])){
- foreach(User::getAll(array('right'=>true) ) as $user){
- if($scope!= 0 && !isset($user->firms[$scope])) continue;
- if(preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->fullName())) || preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->login))){
- $response['rows'][] = array(
- 'fullname'=>html_decode_utf8($user->fullName()),
- 'name'=>$user->fullName(),
- 'uid'=>html_decode_utf8(addslashes($user->login)),
- 'id'=>$user->login,
- 'mail'=>$user->mail,
- 'type'=>'user',
- 'avatar'=>$user->getAvatar(),
- 'function'=>$user->function
- );
- }
- }
- }
- if(in_array('rank', $_['data']['types'])){
- foreach(Rank::staticQuery('SELECT * FROM {{table}} WHERE label LIKE ?',array('%'.$_['keyword'].'%'),true) as $rank){
- $response['rows'][] = array(
- 'fullname'=>html_decode_utf8($rank->label),
- 'name'=>$rank->label,
- 'uid'=>$rank->id,
- 'id'=>$rank->id,
- 'type'=>'rank',
- 'description'=>$rank->description,
- );
- }
- }
- });
- Action::register('core_user_by_uid',function(&$response){
- global $myUser,$_;
- if(!$myUser->can('user','read')) throw new Exception("Vous n'avez pas acces aux utilisateurs");
- $response['users'] = array();
- $ranks = array();
- $users = array();
- foreach($_['uids'] as $uid){
- if(is_numeric($uid)){
- $ranks[] = $uid;
- continue;
- }
- //user
- $item = User::byLogin($uid);
- if(!$item->login) {
- $item->login = $uid;
- $item->fullName = $uid;
- $item->uid = $uid;
- }
- $row = $item->toArray();
- $row['fullname'] = html_decode_utf8($item->fullName());
- $row['name'] = $item->fullName();
- $row['uid'] = html_decode_utf8(addslashes($item->login));
- $row['id'] = $item->login;
- $row['type'] = 'user';
- unset($row['password']);
- unset($row['token']);
- $response['users'][$item->login] = $row;
- }
- //rank
- foreach(Rank::loadAll(array('id:IN'=>implode(',',$ranks))) as $item){
- $row = $item->toArray();
- $row['fullname'] = $item->label;
- $row['name'] = $item->label;
- $row['uid'] = $item->id;
- $row['id'] = $item->id;
- $row['type'] = 'rank';
- $response['users'][$item->id] = $row;
- }
- });
- /* Compte/Profil utilisateur */
- Action::register('core_account_lost_password',function(&$response){
- global $myUser,$myFirm,$_,$conf;
- if(!isset($_['mail']) || empty($_['mail']) || !check_mail(trim($_['mail']))) throw new Exception("Adresse e-mail non spécifiée ou incorrecte");
- foreach(User::getAll(array('right'=>false) ) as $user){
- if(mb_strtolower($user->mail) != mb_strtolower(trim($_['mail']))) continue;
- $token = sha1(time().mt_rand(0,1000));
- $linkToken = base64_encode($user->login.'::'.$token.'::1');
- UserPreference::delete(array('user'=>$user->login,'key'=>'lost_password'));
- $saved = new UserPreference();
- $saved->user = $user->login;
- $saved->key = 'lost_password';
- $saved->value = $token;
- $saved->save();
- $mail = new Mail;
- $mail->expeditor = !empty($conf->get('password_lost_expeditor'))?$conf->get('password_lost_expeditor'):"";
- $mail->title = "Récupération de mot de passe oublié";
- $data = array(
- 'link' => ROOT_URL.'/account.lost.php?token='.$linkToken,
- 'url' => ROOT_URL,
- 'firstname' => $user->firstname,
- );
- if(!empty($conf->get('password_lost_firm')) && $firm = Firm::getById($conf->get('password_lost_firm'))){
- $mail->firm = utf8_decode($firm->label);
- $data['firm'] = $firm->label;
- $data['logo'] = ROOT_URL.'/'.$firm->logo('url');
- }
- if(!empty($conf->get('password_lost_mail_expire'))){
- $expDays = intval($conf->get('password_lost_mail_expire'));
- $data['expDays'] = $expDays;
- $data['expDaysPlural'] = $expDays>1?"s":"";
- $data['expDate'] = !empty($expDays) ? date("d/m/Y à H:i", strtotime($expDays." days")) : '';
- }
- $mail->template(__DIR__.SLASH.'mail.reset.password.html',$data,true);
- $mail->recipients['to'][] = $user->mail;
- $mail->send();
- Log::put("Demande de récupération de mot de passe : ".$user->toText(),'Utilisateur');
- return;
- }
- throw new Exception("Aucun compte ne correspond, veuillez contacter un administrateur");
- });
- Action::register('core_account_api_save',function(&$response){
- global $myUser,$myFirm,$_,$conf;
- User::check_access('account','edit');
- $myUser->preference('api_enabled',$_['api-enabled']);
- $myUser->loadPreferences();
- $_SESSION['currentUser'] = serialize($myUser);
- });
- Action::register('core_account_save',function(&$response){
- global $myUser,$myFirm,$_,$conf;
- User::check_access('account','edit');
- if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
- 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");
- if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Adresse mail obligatoire');
- $_['mail'] = mb_strtolower(trim($_['mail']));
- $_['login'] = mb_strtolower(trim($_['login']));
- $userForm = new User();
- $userForm->fromArray($_);
- if(empty($userForm->login) && (!isset($_['password']) || empty($_['password']))) throw new Exception("Mot de passe obligatoire");
- //Vérifications & formattage des données
- $userForm->firstname = mb_ucfirst(mb_strtolower($userForm->firstname));
- $userForm->name = mb_strtoupper($userForm->name);
- if(!empty($userForm->mail) && !check_mail($userForm->mail)) throw new Exception('Le format du champ "Mail" est invalide');
- if(!empty($userForm->phone) && !check_phone_number($userForm->phone)) throw new Exception('Le format du champ "Téléphone fixe" est invalide');
- $userForm->phone = !empty($userForm->phone) ? normalize_phone_number($userForm->phone) : '';
- if(!empty($userForm->mobile) && !check_phone_number($userForm->mobile)) throw new Exception('Le format du champ "Téléphone mobile" est invalide');
- $userForm->mobile = !empty($userForm->mobile) ? normalize_phone_number($userForm->mobile) : '';
- 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");
- if($_['password'] != $_['password2']) throw new Exception("Mot de passe et confirmation non similaires");
- //Recuperation des hash des precedents passwords
- $chain = explode('-',$myUser->preference('account_chain'));
- if(!empty(trim($_['password']))) {
- $hashedPassword = User::password_encrypt('$a1u7'.$_['password'].'$y$1');
- if(in_array($hashedPassword, $chain) && !$myUser->superadmin) throw new Exception("Vous devez choisir un mot de passe différent des précédents");
- if(count($chain)==10) array_shift($chain);
- $chain[] = $hashedPassword;
- $myUser->preference('account_chain',implode('-',$chain));
- }
- //save des comptes type db
- if($myUser->origin == ''){
- if(!empty(trim($_['password']))){
- $passwordErrors = User::check_password_format($_['password']);
- 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));
- 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");
- $myUser->password = User::password_encrypt($_['password']);
- $myUser->preference('passwordTime',time());
- }
- $myUser->firstname = $userForm->firstname;
- $myUser->name = $userForm->name;
- $myUser->mail = $userForm->mail;
- $myUser->function = $userForm->function;
- $myUser->phone = $userForm->phone;
- $myUser->mobile = $userForm->mobile;
- $myUser->manager = is_object($myUser->manager) ? $myUser->manager->login : $myUser->manager;
- if(is_array($myUser->meta)) $myUser->meta = json_encode($myUser->meta);
- $myUser->save();
- if($myUser->superadmin == 1){
- foreach(Firm::loadAll() as $firm)
- $firms[$firm->id] = $firm;
- $myUser->setFirms($firms);
- }
- }
- //Save de l'avatar
- if(!empty($_FILES['avatar']) && $_FILES['avatar']['size']!=0 ){
- $login = User::format_avatar_name($myUser->login);
- foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.$login.".*") as $filename)
- unlink($filename);
- $avatar = File::upload('avatar',AVATAR_PATH.$login.'.{{ext}}',104857060,array('jpg','png','jpeg','gif'));
- Image::resize($avatar['absolute'],150,150);
- }
- //save des comptes types plugin
- Plugin::callHook("user_save",array(&$myUser,$userForm,&$response));
- $myUser->loadRights();
- if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
- if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
- $_SESSION['currentUser'] = serialize($myUser);
- });
- Action::register('core_account_avatar_download',function(&$response){
- global $myUser,$_;
- User::check_access('profile','read');
- try {
- $user = str_replace(array('..','/'),'',$_['user']);
- $extension = str_replace(array('..','/'),'',$_['extension']);
- File::downloadFile(File::dir().AVATAR_PATH.User::format_avatar_name($user).'.'.$extension,null, null, null, true,false);
- } catch(Exception $e) {
- File::downloadFile('img/default-avatar.png',null, null, null, true,false);
- }
- });
- Action::register('core_account_avatar_delete',function(&$response){
- global $myUser,$_;
- if(!$user = User::byLogin($_['login'])) throw new Exception("Utilisateur inconnu");
- if($myUser->login!=$user->login && !$myUser->can('user', 'edit')) throw new Exception("Permissions insuffisantes",403);
- foreach(glob(__ROOT__.FILE_PATH.AVATAR_PATH.User::format_avatar_name($user->login).".*") as $filename)
- unlink($filename);
- if(!file_exists(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails')) return;
- foreach(glob(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails'.SLASH.User::format_avatar_name($user->login).".*") as $filename)
- unlink($filename);
- });
- Action::register('core_user_save',function(&$response){
- global $myUser,$_,$conf;
- User::check_access('user','edit');
- if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
- 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");
- //Calcule de la taille max du login en focntion du chemin absolu pour avatar + extension (5)
- $osElementMaxLength = OS_path_max_length() - strlen(__ROOT__.FILE_PATH.AVATAR_PATH) - strlen(User::get_avatar_extension_brace());
- if(strlen($_['login']) > $osElementMaxLength) throw new Exception("Identifiant trop long : maximum ".$osElementMaxLength." caractères");
- $osElementMaxLength = OS_element_max_length();
- if(strlen($_['login']) > $osElementMaxLength) throw new Exception("Identifiant trop long : maximum ".$osElementMaxLength." caractères");
- if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Le champ "Mail" est obligatoire');
- if(!check_mail($_['mail'])) throw new Exception('Le format du champ "Mail" est invalide');
- 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");
- if($_['password'] != $_['password2']) throw new Exception("Mot de passe et confirmation non similaires");
- $_['mail'] = mb_strtolower(trim($_['mail']));
- $_['login'] = trim($_['login']);
- $user = User::byLogin($_['login']);
- $user = $user && empty($user->origin) ? $user : new User();
- //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)
- if(empty($user->id)){
- $tryExisting = User::byLogin($_['login']);
- if($tryExisting && $tryExisting->state=='published')
- throw new Exception("Un utilisateur existe déjà avec cet identifiant");
- }
- if(!$user->login) $user->login = $_['login'];
- foreach(User::getAll(array('right'=>false)) as $existingUser)
- if($existingUser->mail == $_['mail'] && $existingUser->login != $user->login) throw new Exception("Un utilisateur existe déjà avec cette adresse e-mail");
- if($user->id == 0 && (!isset($_['password']) || empty($_['password']))) throw new Exception("Mot de passe obligatoire");
- if(!empty(trim($_['password']))){
- $passwordErrors = User::check_password_format(html_entity_decode($_['password']));
- 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));
- if($_['password']==$_['login'] || $_['password']==$_['mail'] ) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant ou à l'e-mail");
- $user->password = User::password_encrypt(html_entity_decode($_['password']));
- $user->preference('passwordTime',time());
- }
- $user->firstname = mb_ucfirst(mb_strtolower($_['firstname']));
- $user->name = mb_strtoupper($_['name']);
- $user->mail = $_['mail'];
- $user->state = User::ACTIVE;
- if(isset($_['manager'])) $user->manager = $_['manager'];
- if(is_array($user->meta)) $user->meta = json_encode($user->meta);
- $user->save();
- if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
- if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
- $user->password = '';
- Log::put("Création/Modification de l'utilisateur ".$user->login,'Utilisateur');
- });
- Action::register('core_user_edit',function(&$response){
- global $myUser,$_;
- User::check_access('user','edit');
- $user = User::byLogin($_['login'], true, true);
- $user->login = htmlspecialchars_decode($user->login);
- $user->name = $user->lastname();
- $user->firstname = $user->firstname();
- if(!$user) throw new Exception("Utilisateur non identifié");
- $user->password = '';
- $response = $user;
- });
- Action::register('core_user_delete',function(&$response){
- global $myUser,$_;
- User::check_access('user','delete');
- $user = User::byLogin($_['login'], true, true);
- if(!$user) throw new Exception("Utilisateur non identifié");
- $user->loadRanks();
- if($user->superadmin == 1) throw new Exception("Vous ne pouvez pas supprimer le compte Super Admin");
- if($user->login == $myUser->login) throw new Exception("Vous ne pouvez pas supprimer votre propre compte");
- if(!$user = User::getById($user->id)) throw new Exception("Impossible de supprimer un compte en dehors de de la base de données");
- $user->state = User::INACTIVE;
- $user->save();
- foreach(UserFirmRank::loadAll(array('user'=>$user->login)) as $ufrLink)
- UserFirmRank::deleteById($ufrLink->id);
- if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
- if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
- Log::put("Suppression de l'utilisateur ".$user->toText(),'Utilisateur');
- });
- /** DROITS **/
- Action::register('core_right_search',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) return $response;
- foreach(Right::loadAll(array('scope'=>$_['scope'],'uid'=>$_['uid'],'firm:IN'=>array($_['firm'],'NULL') )) as $right){
- $row = $right->toArray();
- if(!$right->read) unset($row['read']);
- if(!$right->edit) unset($row['edit']);
- if(!$right->delete) unset($row['delete']);
- if(!$right->configure) unset($row['configure']);
- if(!$right->recursive) unset($row['recursive']);
- if($row['firm']=='0') unset($row['firm']);
- if($right->targetScope == 'rank'){
- $row['target'] = '<i class="far fa-address-card"></i> '.Rank::getById($right->targetUid)->label;
- }else{
- $user = User::byLogin($right->targetUid);
- $row['target'] = '<img class="avatar avatar-mini avatar-rounded" src="'.$user->getAvatar().'"> '.$user->fullName();
- }
- $response['rows'][] = $row;
- }
- });
- //Récuperation ou edition d'élément right
- Action::register('core_right_save',function(&$response){
- global $myUser,$_;
- $right = new Right();
- $right->fromArray($_);
- $scopes = Right::availables('scope');
- 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");
- if(!$myUser->superadmin){ //todo décommenter
- $check = $scopes[$right->scope]['check'];
- $check('save',$right);
- }
- $right->save();
- });
- Action::register('core_right_delete',function(&$response){
- global $myUser,$_;
- $right = Right::getById($_['id']);
- $scopes = Right::availables('scope');
- 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");
- if(!$myUser->superadmin){ //todo décommenter
- $check = $scopes[$right->scope]['check'];
- $check('delete',$right);
- }
- Right::deleteById($_['id']);
- });
- //////////////////////
- Action::register('core_right_search',function(&$response){
- global $myUser,$_;
- User::check_access('rank','edit');
- if(!isset($_['firm'])) throw new Exception("Etablissement non spécifié");
- $wholeRights = array();
- $scopes = array();
- $scopes = Right::availables('scope');
- $firms = Firm::loadAll();
- $firms[] = Firm::anonymous_firm();
- foreach($firms as $firm){
- if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
- $rights = Right::loadAll(array('targetUid'=>$_['targetUid'],'firm'=>$firm->id));
- $rightsTable = array();
- foreach($rights as $right)
- $rightsTable[$right->scope] = $right;
- if($_['firm'] == '0'){
- foreach($scopes as $scope=>$options) {
- $right = isset($rightsTable[$scope])? $rightsTable[$scope] : new Right();
- $wholeRights[$scope]['read'][$firm->id] = (int)$right->read;
- $wholeRights[$scope]['edit'][$firm->id] = (int)$right->edit;
- $wholeRights[$scope]['delete'][$firm->id] = (int)$right->delete;
- $wholeRights[$scope]['configure'][$firm->id] = (int)$right->configure;
- }
- }
- }
- foreach ($scopes as $scope=>$options) {
- if(!$options['global']) continue;
- if($_['firm'] == '0'){
- $read = count(array_unique($wholeRights[$scope]['read'])) === 1 ? end($wholeRights[$scope]['read']) : 2;
- $edit = count(array_unique($wholeRights[$scope]['edit'])) === 1 ? end($wholeRights[$scope]['edit']) : 2;
- $delete = count(array_unique($wholeRights[$scope]['delete'])) === 1 ? end($wholeRights[$scope]['delete']) : 2;
- $configure = count(array_unique($wholeRights[$scope]['configure'])) === 1 ? end($wholeRights[$scope]['configure']) : 2;
- }else{
- $right = isset($rightsTable[$scope])? $rightsTable[$scope] : new Right();
- $read = $right->read;
- $edit = $right->edit;
- $delete = $right->delete;
- $configure = $right->configure;
- }
- $response['rows'][] = array(
- 'scope'=>$scope,
- 'description'=>$options['label'],
- 'read'=>(int)$read,
- 'edit'=>(int)$edit,
- 'delete'=>(int)$delete,
- 'configure'=>(int)$configure
- );
- usort($response['rows'], function($a, $b){
- return strcmp($a['scope'], $b['scope']);
- });
- }
- });
- Action::register('core_right_toggle',function(&$response){
- global $myUser,$_,$myFirm;
- User::check_access('rank','edit');
- if(!isset($_['scope']) || empty($_['scope'])) throw new Exception("Scope non spécifié");
- if(!isset($_['targetUid']) || empty($_['targetUid'])) throw new Exception("target Uid non spécifié");
- if(!isset($_['right']) || empty($_['right'])) throw new Exception("Droit non spécifié");
- if(!isset($_['firm'])) throw new Exception("Établissement non spécifié");
- $firms = Firm::loadAll();
- $firms[] = Firm::anonymous_firm();
- foreach($firms as $firm){
- if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
- $item = Right::load(array('targetUid'=>$_['targetUid'],'firm'=>$firm->id,'scope'=>$_['scope']));
- $item = !$item ? new Right() : $item ;
- $item->targetUid = $_['targetUid'];
- $item->firm = $firm->id;
- $item->targetScope = 'rank';
- $item->scope = $_['scope'];
- $item->{$_['right']} = $_['state'];
- $item->save();
- $myUser->loadRights();
- $_SESSION['currentUser'] = serialize($myUser);
- }
- });
- /** RANGS **/
- Action::register('core_rank_search',function(&$response){
- global $myUser,$_;
- User::check_access('rank','read');
- $rankQry = 'SELECT *,(SELECT GROUP_CONCAT(CONCAT(f.label,":",`scope`,":",`read`,":",`edit`,":",`delete`,":",`configure`))
- FROM `'.Right::tableName().'` r LEFT JOIN firm f ON f.id = r.firm
- WHERE (r.read=? OR r.edit=? OR r.delete=? OR r.configure=?) AND r.targetUid={{table}}.id) as rights
- FROM {{table}}';
- $ranks = Rank::staticQuery($rankQry,array(1,1,1,1),true);
- foreach($ranks as $rank){
- $row = $rank->toArray(true);
- //Gestion des rights sur les rangs "coeur" ayant des perms
- $row['read'] = $row['edit'] = $row['delete'] = $row['configure'] = true;
- if($rights = Right::loadAll(array('scope'=>'rank', 'uid'=>$rank->id))){
- if(!$myUser->can('rank','read',$rank->id)) continue;
- $row['edit'] = $myUser->can('rank','edit',$rank->id);
- $row['delete'] = $myUser->can('rank','delete',$rank->id);
- $row['configure'] = $myUser->can('rank','configure',$rank->id);
- }
- $row['rights'] = array();
- foreach (explode(',', $rank->foreign('rights')) as $right) {
- $infos = explode(':', $right);
- $row['rights'][] = array(
- 'configure' => !empty(array_pop($infos)),
- 'delete' => !empty(array_pop($infos)),
- 'edit' => !empty(array_pop($infos)),
- 'read' => !empty(array_pop($infos)),
- 'scope' => array_pop($infos),
- 'firm' => array_pop($infos)
- );
- usort($row['rights'], function($a, $b){
- return strcmp($a['firm'], $b['firm']);
- });
- }
- $response['rows'][] = $row;
- }
- });
- Action::register('core_rank_save',function(&$response){
- global $myUser,$_;
- User::check_access('rank','edit');
- if(!isset($_['label']) || empty($_['label'])) throw new Exception("Libellé obligatoire");
- $item = isset($_['id']) && !empty($_['id']) ? Rank::getById($_['id']) : new Rank();
- $item->label = $_['label'];
- $item->description = $_['description'];
- $item->save();
- Log::put("Ajout/Modification du rang ".$item->toText(),'Rang');
- });
- Action::register('core_rank_edit',function(&$response){
- global $myUser,$_;
- User::check_access('rank','edit');
- $response = Rank::getById($_['id']);
- });
- Action::register('core_rank_delete',function(&$response){
- global $myUser,$_;
- User::check_access('rank','delete');
- $rank = Rank::getById($_['id']);
- Rank::deleteById($_['id']);
- Log::put("Suppression du rang ".$rank->toText(),'Rang');
- });
- /** LISTES **/
- Action::register('core_dictionary_search',function(&$response){
- global $myUser,$_;
- User::check_access('dictionary','read');
- $parent = '';
- if(!empty($_['parent']) && is_numeric($_['parent']))
- $parent = $_['parent'];
- foreach(Dictionary::loadAll(array('parent'=>$parent, 'state'=>Dictionary::ACTIVE), array(' label ASC ')) as $item){
- $item->label = html_entity_decode($item->label);
- $response['rows'][] = $item->toArray();
- }
- });
- Action::register('core_dictionary_save',function(&$response){
- global $myUser,$_;
- User::check_access('dictionary','edit');
- if(!isset($_['label']) || empty(trim($_['label']))) throw new Exception("Libellé obligatoire");
- if(!is_numeric($_['parent'])){
- if($myUser->can('dictionary','configure'))
- $_['parent'] = 0;
- else
- throw new Exception("Veuillez sélectionner une liste");
- }
- $item = Dictionary::provide();
- $item->label = trim($_['label']);
- $item->parent = $_['parent'];
- $item->state = Dictionary::ACTIVE;
- if(!empty($_['slug'])){
- $parameters = array('slug'=>$_['slug'], 'state'=>Dictionary::ACTIVE);
- if(isset($item->id) && !empty($item->id)) $parameters['id:!='] = $item->id;
- if(Dictionary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé");
- $item->slug = $_['slug'];
- }
- if(empty($item->slug)){
- $parentSlug = $_['parent'] == 0 ? '' : Dictionary::getById($_['parent'])->slug;
- $slug = empty($parentSlug) ? $_['label'] : $parentSlug.'-'.$_['label'];
- $item->slug = generateSlug($slug, Dictionary::class, 'slug', '', '_');
- }
- if(isset($_['sublistlabel'])) $item->sublistlabel = $_['sublistlabel'];
- $item->save();
- Log::put("Création/Modification de l'item de liste ".$item->toText(),'Liste');
- });
- Action::register('core_dictionary_edit',function(&$response){
- global $myUser,$_;
- User::check_access('dictionary','edit');
- $dictionary = Dictionary::getById($_['id']);
- $response = $dictionary->toArray(true);
- });
- Action::register('core_dictionary_delete',function(&$response){
- global $myUser,$_;
- User::check_access('dictionary','delete');
- if(!isset($_['id']) || empty($_['id'])) throw new Exception("Aucun identifiant spécifié");
- $item = Dictionary::getById($_['id']);
- $item->state = Dictionary::INACTIVE;
- $item->save();
- Dictionary::change(array('state'=>Dictionary::INACTIVE), array('parent'=>$item->id));
- Log::put("Suppression de la liste et des sous-listes associées".$item->toText(), 'Liste');
- });
- Action::register('core_dictionary_get_parent',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("permission denied");
- $selected = Dictionary::loadAll(array("id"=>$_['selected']));
- foreach ($selected as $item) {
- if($item->parent == 0) {
- $parents = Dictionary::loadAll(array("parent"=>$item->parent), array(' label ASC '));
- } else {
- $tmpParent = Dictionary::loadAll(array("id"=>$item->parent), array(' label ASC '));
- $parents = Dictionary::loadAll(array("parent"=>$tmpParent[0]->parent), array(' label ASC '));
- }
- $parentId = !empty($tmpParent) ? $tmpParent[0]->id : '';
- $response['rows'][] = array(
- 'parents'=> $parents,
- 'currentId'=> $item->id,
- 'parentId'=> $parentId,
- 'label'=> $item->label
- );
- }
- });
- Action::register('core_dictionary_component_load',function(&$response){
- global $myUser,$_;
- //double check afin de laisse la possiubilité aux non connectés de voir les listes sur certains projets
- if(!$myUser->connected() && !$myUser->can('dictionary','read')){
- $response['content'] = array();
- return;
- }
- $dictionnaries = array();
- if(isset($_['slug']) && $_['slug'] != ""){
- $dictionnaries = Dictionary::load(array("slug"=>$_['slug']));
- }else{
- $dictionnaries = new Dictionary();
- $dictionnaries->id = 0;
- }
- if(isset($_['parentId']) && $_['parentId'] != ""){
- $dictionnaries = Dictionary::getById($_['parentId']);
- $dictionnaries->id = 0;
- }
- if($dictionnaries) {
- $dictionnaries = $dictionnaries->toArray();
- if(!isset($_['depth'])) $_['depth'] = 1;
- $dictionnaries['childs'] = Dictionary::childs(array('id'=>$dictionnaries['id']),array('depth'=>$_['depth'],'format'=>'array'));
- }
- if(isset($_['value']) && $_['value'] != "" ){
- $output = is_numeric($_['value']) ? 'id' : 'slug';
- if($output == 'id' && $_['value'] == 0) return $dictionnaries;
- if(!$_['hierarchy'] || (isset($_['slug']) && $_['slug'] == "" )){
- foreach ($dictionnaries['childs'] as $i => $child) {
- if($child[$output] == $_['value']) $child['selected'] = true;
- $dictionnaries['childs'][$i] = $child;
- }
- } else {
- $dictionnaries = Dictionary::hierarchy($_['value'],$_['slug']);
- }
- }
- $response['content'] = $dictionnaries;
- });
- Action::register('core_dictionary_slug_proposal',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Permission denied");
- if(!isset($_['label']) || empty($_['label'])) return;
- //Check si l'item n'a pas déjà un slug
- if(isset($_['id']) && !empty($_['id']) && is_numeric($_['id'])){
- $item = Dictionary::provide();
- if(!empty($item->slug)) return;
- }
- $parentSlug = empty($_['parent']) ? '' : Dictionary::getById($_['parent'])->slug;
- $slug = empty($parentSlug) ? $_['label'] : $parentSlug.'_'.$_['label'];
- $response['slug'] = generateSlug($slug, Dictionary::class, 'slug', '', '_');
- });
- /* Composant tag list */
- Action::register('core_tag_list_autocomplete',function(&$response){
- global $myUser,$_;
- if(!$myUser->can('dictionary','read')) throw new Exception("Vous n'avez pas acces aux listes");
- $response['rows'] = array();
- 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){
- $response['rows'][] = array(
- 'name'=>$item->label,
- 'id'=>$item->id,
- 'slug'=>$item->slug
- );
- }
- });
- Action::register('core_tag_list_autocreate',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- $response = array();
- $parent = Dictionary::bySlug($_['slug']);
- $newtag = new Dictionary();
- $newtag->state = Dictionary::ACTIVE;
- $newtag->parent= $parent->id;
- $newtag->label= $_['label'];
- $newtag->slug= $parent->slug.'-'.slugify($_['label']);
- $newtag->save();
- $response = array(
- 'name'=>$newtag->label,
- 'id'=>$newtag->id,
- 'slug'=>$newtag->slug
- );
- });
- Action::register('core_tag_list_by_id',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- $response['tags'] = array();
- $ids = explode(',',$_['id']);
- foreach(Dictionary::loadAll(array('id:IN'=>$ids)) as $dictionary){
- $dictionaryMapping[$dictionary->id] = $dictionary;
- }
- foreach ($ids as $id) {
- if(!isset($dictionaryMapping[$id])) continue;
- $item = $dictionaryMapping[$id];
- $row = $item->toArray();
- $row['label'] = $item->label;
- $row['slug'] = $item->slug;
- $row['id'] = $item->id;
- $response['tags'][] = $row;
- }
- });
- /** Composant tableau de dictionary */
- Action::register('core_dictionary_table_search',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("permission denied");
- if(!is_numeric($_['id'])) throw new Exception("Aucun identifiant de liste spécifié");
- $dic = Dictionary::getById($_['id']);
- $response['dictionary'] = $dic->toArray(true);
- foreach (Dictionary::childs(array('slug'=>$dic->slug)) as $child)
- $response['rows'][] = $child->toArray(true);
- });
- Action::register('core_dictionary_table_save',function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Permission denied");
- if(!isset($_['label']) || empty($_['label'])) throw new Exception("Aucun libellé de liste renseigné");
- if(!isset($_['id']) && !isset($_['list'])) throw new Exception("Aucun identifiant de liste ou de parent de liste trouvé");
- $dic = isset($_['id']) && !empty($_['id'])? Dictionary::getById($_['id']) : new Dictionary();
- $dic->parent = $_['list'];
- $dic->label = $_['label'];
- if(isset($_['slug']) && !empty($_['slug'])) {
- $parameters = array('slug'=>$_['slug'], 'state'=>Dictionary::ACTIVE);
- if(isset($dic->id) && !empty($dic->id)) $parameters['id:!='] = $dic->id;
- if(Dictionary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé");
- $dic->slug = $_['slug'];
- }
- $dic->state = Dictionary::ACTIVE;
- $dic->save();
- });
- /* COMPOSANT LOCATION */
- Action::register('core_location_search',function(&$response){
- global $myUser,$_,$conf;
- if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- $appUrl = $conf->get('maps_api_suggest_url');
- $appId = $conf->get('maps_api_id');
- $appKey = $conf->get('maps_api_key');
- if(empty($appUrl) || empty($appId) || empty($appKey)) throw new Exception("Impossible d'initialiser le composant de localisation");
- if(!isset($_['keyword']) || empty($_['keyword'])) return;
- $default = array(
- 'query' => $_['keyword'],
- 'app_id' => $appId,
- 'app_code' => $appKey
- );
- $params = array_merge($default, $_['data']);
- $curlOpt = array(
- CURLOPT_URL => sprintf("%s?%s", $appUrl, http_build_query($params)),
- CURLOPT_HTTPHEADER => array(
- 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
- 'Content-Type: application/json',
- ),
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_HTTPAUTH => CURLAUTH_ANY,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- );
- $ch = curl_init();
- curl_setopt_array($ch, $curlOpt);
- $result = curl_exec($ch);
- if($result === false) throw new Exception("Erreur de récupération cURL : ".curl_error($curl));
- $result = json_decode($result);
- $infos = curl_getinfo($ch);
- curl_close($ch);
- $response['rows'] = $result->suggestions;
- });
- Action::register('core_location_detail_search',function(&$response){
- global $myUser,$_,$conf;
- if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- $appUrl = $conf->get('maps_api_geocode_url');
- $appId = $conf->get('maps_api_id');
- $appKey = $conf->get('maps_api_key');
- if(empty($appUrl) || empty($appId) || empty($appKey)) throw new Exception("Impossible de récupérer les détails de la localisation");
- if(!isset($_['locationId']) || empty($_['locationId'])) return;
- $params = array(
- 'locationid' => $_['locationId'],
- 'app_id' => $appId,
- 'app_code' => $appKey
- );
- $curlOpt = array(
- CURLOPT_URL => sprintf("%s?%s", $appUrl, http_build_query($params)),
- CURLOPT_HTTPHEADER => array(
- 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
- 'Content-Type: application/json',
- ),
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_HTTPAUTH => CURLAUTH_ANY,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- );
- $ch = curl_init();
- curl_setopt_array($ch, $curlOpt);
- $response = curl_exec($ch);
- if($response === false) throw new Exception("Erreur de récupération cURL : ".curl_error($curl));
- $response = json_decode($response);
- $infos = curl_getinfo($ch);
- curl_close($ch);
- });
- /** CRONTAB */
- Action::register('core_cron',function(&$response){
- try{
- if(php_sapi_name() !== 'cli') throw new Exception("Le cron ne peut être executé qu'en mode CLI depuis le serveur");
- Plugin::callHook('cron', array(time()));
- }catch(Exception $e){
- file_put_contents(__DIR__.SLASH.'cron.log',date('d-m-Y H:i').' | '.$e->getMessage().PHP_EOL,FILE_APPEND);
- }
- });
- /** FILES & UPLOADS */
- //Gestion de l'upload temporaire (avant soumission d'un form)
- Action::register('core_temporary_file_upload',function(&$response){
- global $myUser,$_;
- User::check_access('file','edit');
- $response['previews'] = array();
- $fileIndex = isset($_FILES[$_['index']]) ? $_FILES[$_['index']] : $_FILES['document'];
- File::clear_temp();
- for($i=0; $i<count($_FILES[$_['index']]['name']);$i++) {
- $tempPath = File::temp().basename($fileIndex['tmp_name'][$i]);
- move_uploaded_file($fileIndex['tmp_name'][$i], $tempPath);
- $ext = getExt($fileIndex['name'][$i]);
- $response['previews'][] = array(
- 'path' => basename($fileIndex['tmp_name'][$i]),
- 'name' => $fileIndex['name'][$i],
- 'temporary' => true,
- 'ext' => $ext,
- 'url' => 'action.php?action=core_temporary_file_download&name='.$fileIndex['name'][$i].'&path='.basename($fileIndex['tmp_name'][$i]),
- 'icon' => getExtIcon($ext)
- );
- }
- });
- Action::register('core_temporary_file_download',function(&$response){
- global $myUser,$_;
- User::check_access('file','read');
- File::downloadFile(File::temp().$_['path'],$_['name']);
- });
- /** GENERAL SETTINGS **/
- Action::register('core_general_settings_save',function(&$response){
- global $myUser, $_, $conf;
- User::check_access('setting_global','configure');
- $_FILES = normalize_php_files();
- if(isset($_FILES['fields'])) $_FILES = $_FILES['fields'];
- $coreFolder = __ROOT__.FILE_PATH.'core'.SLASH;
- if(!file_exists($coreFolder)) mkdir($coreFolder,0755,true);
- //Ajout logo
- if(!empty($_['logo-light'])){
- $logo = File::save_component('logo-light', 'core/public/logo.{{extension}}');
- Image::resize($logo[0]['absolute'], 200, 200);
- Image::toPng($logo[0]['absolute']);
- unset($_['logo-light']);
- }
- //Ajout logo dark
- if(!empty($_['logo-dark'])){
- $logo = File::save_component('logo-dark', 'core/public/logo.dark.{{extension}}');
- Image::resize($logo[0]['absolute'], 200, 200);
- Image::toPng($logo[0]['absolute']);
- unset($_['logo-dark']);
- }
- //Ajout favicon
- if(!empty($_['favicon'])){
- $logo = File::save_component('favicon', 'core/public/favicon.{{extension}}');
- Image::resize($logo[0]['absolute'], 16, 16);
- Image::toPng($logo[0]['absolute']);
- unset($_['favicon']);
- }
- //Durée de conservation des logs
- foreach(Log::staticQuery('SELECT DISTINCT category FROM {{table}}',array(),true) as $log):
- $slug = slugify($log->category);
- $key = 'log_retention_time_'.$slug;
- if(!isset($_[$key])) continue;
- if($_[$key] == 0 || !is_numeric($_[$key])) $_[$key] = '';
- $conf->put($key,$_[$key]);
- endforeach;
- //Gestion save des configuration générales
- foreach(Configuration::setting('configuration-global') as $key => $value){
- if(!is_array($value)) continue;
- $allowedSettings[] = $key;
- }
- 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");
- foreach($_ as $key => $value)
- if(in_array($key, $allowedSettings)) $conf->put($key, $value);
- //Politique de mot de passes
- if(isset($_['password_format'])) $conf->put('password_format',$_['password_format']);
- //Maintenance
- if(isset($_['maintenance'])){
- if($_['maintenance']){
- if(file_exists(File::dir().SLASH.'disabled.maintenance')) rename(File::dir().SLASH.'disabled.maintenance', File::dir().SLASH.'enabled.maintenance');
- file_put_contents(File::dir().SLASH.'enabled.maintenance', trim($_['maintenance-content']));
- } else {
- if(file_exists(File::dir().SLASH.'enabled.maintenance')) rename(File::dir().SLASH.'enabled.maintenance', File::dir().SLASH.'disabled.maintenance');
- file_put_contents(File::dir().SLASH.'disabled.maintenance', trim($_['maintenance-content']));
- }
- }
- });
- Action::register('core_general_password_reset_delay',function(&$response){
- global $myUser, $_, $conf;
- User::check_access('setting_global','configure');
- foreach(User::getAll(array('right'=>false)) as $user)
- $user->preference('passwordTime',strtotime('01/01/1990'));
- });
- //Récupération logo application générale
- Action::register('core_general_logo',function(&$response){
- global $myUser,$_;
- User::check_access('setting_global','configure');
- $variant = '';
- if(!empty($_['data']) && !empty($_['data']['variant'])){
- $variant = $_['data']['variant'];
- $variant = $variant == 'light' ? '' : '.'.$variant;
- }
- File::handle_component(array(
- 'namespace' => 'core', //stockés dans core/*.*
- 'access' => 'setting_global', // crud sur core,
- 'size' => '10000000', // taille max
- 'storage' => 'core/public/logo'.$variant.'.{png,jpg,jpeg,gif}' //chemin complet vers le fichier stocké
- ),$response);
- });
- //Récupération logo application générale
- Action::register('core_general_favicon',function(&$response){
- global $myUser,$_;
- User::check_access('setting_global','configure');
- File::handle_component(array(
- 'namespace' => 'core', //stockés dans core/*.*
- 'access' => 'setting_global', // crud sur core,
- 'size' => '1000000', // taille max
- 'extension' => 'png', // png uniquement
- 'storage' => 'core/public/favicon.png' //chemin complet vers le fichier stocké
- ),$response);
- });
- //Permet de se connecter "en tant que"
- Action::register('core_user_impersonation',function(&$response){
- try{
- global $myUser,$myFirm,$_,$conf;
- if(!$myUser->superadmin) throw new Exception("Seul le super administrateur peut exécuter cette fonctionnalité");
- if(!isset($_['login'])) throw new Exception("Identifiant non spécifié");
- if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
- if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
- $myUser = User::connectLogin($_['login']);
- Log::put("Impersonation de l'utilisateur : ".$myUser->login,"Utilisateur");
- $_SESSION['currentUser'] = serialize($myUser);
- $_SESSION['firm'] = serialize($myFirm);
- header('location: index.php?info='.rawurlencode('Connecté avec l\'utilisateur : '.$myUser->login));
- } catch(Exception $e){
- header('location: setting.php?section=user&error='.rawurlencode($e->getMessage()));
- }
- });
- /* HISTORY */
- Action::register('core_history_search',function(&$response){
- global $myUser,$_;
- User::check_access('history','read');
- $filters = array();
- $response['rows'] = array();
- //Récuperation du nombre de messages importants uniquement
- if(!empty($_['showImportant'])){
- $data = array(History::IMPORTANCE_IMPORTANT);
- $query = 'SELECT scope,uid,COUNT(id) thecount FROM {{table}} WHERE importance=? AND ( ';
- $i=0;
- foreach ($_['scopes'] as $scope=>$values) {
- $marks = array_fill(0, count($values), '?');
- $data[] = $scope;
- $data = array_merge($data,$values);
- $query .= ($i==0 ?'' :' OR ').' (scope = ? AND uid IN('.implode(',',$marks).')) ';
- $i++;
- }
- $query .= ' ) GROUP BY scope,uid ';
- $importants = History::staticQuery($query,$data)->fetchAll();
- //On renvoie 0 s'il n'y a pas de résultat afin d'afficher les notifications de l'historique
- if(empty($importants)){
- foreach($_['scopes'] as $scope=>$values){
- foreach($values as $uid){
- $importants[] = array('scope'=>$scope,'uid'=>$uid,'thecount'=>0);
- }
- }
- }
- foreach($importants as $line)
- $response['rows'][] = array('scope'=>$line['scope'],'uid'=>$line['uid'],'number'=>$line['thecount']);
- //Récuperation du detail ghistorique pour un item
- }else{
- $filters['scope'] = $_['scope'];
- if(isset($_['uid'])) $filters['uid'] = $_['uid'];
- if(!empty($_['keyword'])) $filters['comment:LIKE'] = '%'.$_['keyword'].'%';
- foreach(History::loadAll($filters,array('sort DESC')) as $history){
- $row = $history->toArray();
- $row['type'] = History::types($row['type']);
- $row['comment'] = html_entity_decode($row['comment'],ENT_QUOTES,'UTF-8');
- $row['created'] =array(
- 'fullname'=>complete_date($row['created']),
- 'time'=>date('H:i',$row['created'])
- );
- $user = User::byLogin($row['creator']);
- $row['creator'] = array('fullname'=>(!is_null($user->login) ? $user->fullName() : $row['creator']));
- $response['rows'][] = $row;
- }
- }
- });
- Action::register('core_history_importance_save',function(&$response){
- global $myUser,$_;
- User::check_access('history','edit');
- $item = History::provide();
- if(is_null($item->id)) return;
- $item->importance = $_['importance'];
- $item->save();
- $response = $item->toArray();
- });
- Action::register('core_history_save',function(&$response){
- global $myUser,$_,$myFirm;
- User::check_access('history','edit');
- $item = History::provide();
- if(!$item) return;
- if(isset($_['comment'])) $item->comment = $_['comment'];
- $item->uid = $_['uid'];
- //Si pas d'ordre défini on récupere l'ordre maximum
- if(empty($_['sort'])) {
- $query = History::staticQuery('SELECT MAX(sort) maxsort FROM {{table}} WHERE scope = ? AND uid= ? ',array($_['scope'],$item->uid));
- $row = $query->fetch();
- $_['sort'] = $row['maxsort']+1;
- }
- //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
- if(!empty($_['replaceSort'])) {
- $_['sort'] = $_['replaceSort'];
- History::staticQuery('UPDATE {{table}} SET sort = sort+1 WHERE sort >= ? AND scope = ? AND uid= ?',
- array($_['replaceSort'],$_['scope'],$item->uid)) ;
- }
- $item->sort = $_['sort'];
- $item->scope = $_['scope'];
- $item->importance = $_['importance'];
- $item->type = History::TYPE_COMMENT;
- $item->meta = json_encode(array('url'=>$_['meta']));
- $item->save();
- if(!is_null($item->comment) && $myFirm->has_plugin('fr.core.notification')){
- $mentionned = get_mention($item->comment);
- if(isset($mentionned['user']) && !empty($mentionned['user'])){
- $recipients = array();
- foreach($mentionned['user'] as $user)
- $recipients[] = $user->login;
- $url = array();
- if(!is_null($item->meta)){
- $data = json_decode($item->meta,true);
- foreach($data['url'] as $parameter=>$value)
- $url[] = $parameter."=".$value;
- }
- $url = empty($url) ? '' : '?'.implode('&',$url);
- // GESTION ENVOI NOTIFICATION
- Plugin::callHook('emit_notification',array(array(
- 'label' => 'Vous avez été mentionné dans un commentaire...',
- 'html' => 'Un utilisateur vous a mentionné '.$item->scope,
- 'type' => "notice",
- 'meta' => array('link' => ROOT_URL.'/index.php'.$url),
- 'recipients' => $recipients
- )
- ));
- }
- }
- $response = $item->toArray();
- });
- Action::register('core_history_delete',function(&$response){
- global $myUser,$_;
- User::check_access('history','delete');
- History::deleteById($_['id']);
- });
- /* CONTACT */
- Action::register('core_contact_autocomplete',function(&$response){
- global $myUser,$_;
- if(!$myUser->can('contact','read')) throw new Exception("Vous n'avez pas acces aux contacts");
- $response['rows'] = array();
- $query = 'SELECT * FROM {{table}} p WHERE 1 ';
- if(isset($_['keyword'])){
- $query .= ' AND (p.firstname LIKE ? OR p.name LIKE ?) ';
- $data = array('%'.$_['keyword'].'%','%'.$_['keyword'].'%');
- }
- if(isset($_['data']) && isset($_['data']['scope'])){
- $query .= ' AND p.scope= ? ';
- $data[]= $_['data']['scope'];
- }
- if(isset($_['data']) && isset($_['data']['uid'])){
- $uids = array();
- foreach($_['data']['uid'] as $uid){
- $uids[] = '?';
- $data[]= $uid;
- }
- $query .= ' AND p.uid IN ('.implode(',',$uids).') ';
- }
- $query .= ' ORDER BY name,firstname LIMIT 15';
- foreach(ContactPerson::staticQuery($query,$data,true) as $item){
- $response['rows'][] = array(
- 'label'=>html_decode_utf8($item->fullName()),
- 'id'=>$item->id,
- 'job'=>$item->job
- );
- }
- });
- Action::register('core_contact_by_uid',function(&$response){
- global $myUser,$_;
- if(!$myUser->can('contact','read')) throw new Exception("Vous n'avez pas acces aux contacts");
- $response['items'] = array();
- $items = $_['items'];
- foreach(ContactPerson::loadAll(array('id:IN'=>implode(',',$items))) as $item){
- $row = $item->toArray();
- $row['label'] = $item->fullname();
- $row['job'] = $item->job;
- $row['id'] = $item->id;
- $response['items'][$item->id] = $row;
- }
- });
- /** Gestion des fichiers **/
- Action::register('core_file_search',function(&$response){
- global $myUser, $_, $conf;
- User::check_access('file','read');
- $programRoot = rtrim(File::dir(),SLASH);
- $root = !empty($_['root']) ? $programRoot.SLASH.trim($_['root'],SLASH) : $programRoot;
- if(isset($_['folder']) && ($_['folder']=='.' || $_['folder']=='..')) $_['folder']=='';
- $target = (!empty($_['folder'])) ? $programRoot.SLASH.rtrim($_['folder'],SLASH) : $root;
- $path = explode(SLASH,str_replace($root,'',$target));
- $path = array_values(array_filter($path));
- $files = glob($root.SLASH.'*');
- $currentPath = '';
- for($i=0;$i<count($path);$i++){
- $currentPath.= $path[$i].SLASH;
- $files = array_merge($files,glob(File::dir().$currentPath.'*'));
- }
- $response['tree'] = array();
- foreach($files as $file){
- if(!is_dir($file)) continue;
- $relativePath = str_replace( $root.SLASH,'',$file);
- $response['tree'][] = $relativePath;
- }
- });
- /** CUSTOM REWRITE */
- Action::register('rewrite',function(&$response){
- try{
- $root = substr($_SERVER['SCRIPT_NAME'], 0,strrpos($_SERVER['SCRIPT_NAME'] , '/'));
- $requested = substr($_SERVER['REQUEST_URI'], strlen($root)+1);
- ob_start();
- Plugin::callHook('rewrite',array($requested));
- $stream = ob_get_clean();
- if($stream !='') echo $stream;
- }catch(Exception $e){
- exit('<div style="width:300px;margin:30px auto;padding:15px;background:#cecece;text-align:center;font-family:Arial">'.$e->getMessage().'</div>');
- }
- });
- /** ACTIONS DE PLUGINS */
- if(isset($GLOBALS['actions'][$_['action']])) Action::write($GLOBALS['actions'][$_['action']]);
- ?>
|