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('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()); } }); Action::register('logout',function(&$response){ global $myUser,$_; $url = $myUser->disconnect(isset($_['url'])?$_['url']:null); Plugin::callHook('logout',array($url,$myUser)); $response['redirect'] = $url; }); Action::register('initialize_activity',function(&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Permission non accordée"); $myUser->meta['lastActivity'] = time(); }); /** DYNAMIC COLUMNS **/ Action::register('fill_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); }); Action::register('fill_column_load',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; }); /** FILTERS **/ Action::register('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); }); Action::register('filter_remove',function(&$response){ global $myUser,$_; if(!$myUser->connected()) throw new Exception("Pemrission 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('filter_save_global',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('filter_load',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('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].''.$matches[2].''.$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(); } }); /** PLUGINS & ENTITEES **/ Action::register('search_plugin',function(&$response){ global $myUser,$_; User::check_access('plugin','read'); $includeCore = isset($_['includeCore']) && $_['includeCore']==true ; 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); $response['rows'][] = $plugin; } }); //Récuperation d'une liste d'entitées en fonction du plugin ciblé Action::register('search_entities',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('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('entity_attributes',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; }); Action::register('change_plugin_state',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'); }); /** LIEN ETABLISSEMENT / PLUGIN **/ Action::register('search_firm_plugin',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('toggle_firm_plugin',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); } }); /** 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('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('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 / UTILISATEUR / RANG **/ Action::register('search_userfirmrank',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('save_userfirmrank',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('edit_userfirmrank',function(&$response){ global $myUser,$_; User::check_access('rank','edit'); $userFirmRank = UserFirmRank::getById($_['id']); $response = $userFirmRank; }); Action::register('delete_userfirmrank',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('search_user',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('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('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; } }); Action::register('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('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('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 :
".implode("
",$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('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); } catch(Exception $e) { File::downloadFile('img/default-avatar.png'); } }); Action::register('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('save_user',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 :
".implode("
",$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('edit_user',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('delete_user',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'] = ' '.Rank::getById($right->targetUid)->label; }else{ $user = User::byLogin($right->targetUid); $row['target'] = ' '.$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('search_right',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('toggle_right',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('search_rank',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('save_rank',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('edit_rank',function(&$response){ global $myUser,$_; User::check_access('rank','edit'); $response = Rank::getById($_['id']); }); Action::register('delete_rank',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('search_dictionnary',function(&$response){ global $myUser,$_; User::check_access('dictionnary','read'); $parent = ''; if(!empty($_['parent']) && is_numeric($_['parent'])) $parent = $_['parent']; foreach(Dictionnary::loadAll(array('parent'=>$parent, 'state'=>Dictionnary::ACTIVE), array(' label ASC ')) as $item){ $item->label = html_entity_decode($item->label); $response['rows'][] = $item->toArray(); } }); Action::register('save_dictionnary',function(&$response){ global $myUser,$_; User::check_access('dictionnary','edit'); if(!isset($_['label']) || empty(trim($_['label']))) throw new Exception("Libellé obligatoire"); if(!is_numeric($_['parent'])){ if($myUser->can('dictionnary','configure')) $_['parent'] = 0; else throw new Exception("Veuillez sélectionner une liste"); } $item = Dictionnary::provide(); $item->label = trim($_['label']); $item->parent = $_['parent']; $item->state = Dictionnary::ACTIVE; if(!empty($_['slug'])){ $parameters = array('slug'=>$_['slug'], 'state'=>Dictionnary::ACTIVE); if(isset($item->id) && !empty($item->id)) $parameters['id:!='] = $item->id; if(Dictionnary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé"); $item->slug = $_['slug']; } if(empty($item->slug)){ $parentSlug = $_['parent'] == 0 ? '' : Dictionnary::getById($_['parent'])->slug; $slug = empty($parentSlug) ? $_['label'] : $parentSlug.'-'.$_['label']; $item->slug = generateSlug($slug, Dictionnary::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('edit_dictionnary',function(&$response){ global $myUser,$_; User::check_access('dictionnary','edit'); $dictionnary = Dictionnary::getById($_['id']); $response = $dictionnary->toArray(true); }); Action::register('delete_dictionnary',function(&$response){ global $myUser,$_; User::check_access('dictionnary','delete'); if(!isset($_['id']) || empty($_['id'])) throw new Exception("Aucun identifiant spécifié"); $item = Dictionnary::getById($_['id']); $item->state = Dictionnary::INACTIVE; $item->save(); Dictionnary::change(array('state'=>Dictionnary::INACTIVE), array('parent'=>$item->id)); Log::put("Suppression de la liste et des sous-listes associées".$item->toText(), 'Liste'); }); Action::register('get_parent_dictionnary',function(&$response){ global $myUser,$_; if(!$myUser->connected()) throw new Exception("permission denied"); $selected = Dictionnary::loadAll(array("id"=>$_['selected'])); foreach ($selected as $item) { if($item->parent == 0) { $parents = Dictionnary::loadAll(array("parent"=>$item->parent), array(' label ASC ')); } else { $tmpParent = Dictionnary::loadAll(array("id"=>$item->parent), array(' label ASC ')); $parents = Dictionnary::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('load_dictionnary_component',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('dictionnary','read')){ $response['content'] = array(); return; } $dictionnaries = array(); if(isset($_['slug']) && $_['slug'] != ""){ $dictionnaries = Dictionnary::load(array("slug"=>$_['slug'])); }else{ $dictionnaries = new Dictionnary(); $dictionnaries->id = 0; } if(isset($_['parentId']) && $_['parentId'] != ""){ $dictionnaries = Dictionnary::getById($_['parentId']); $dictionnaries->id = 0; } if($dictionnaries) { $dictionnaries = $dictionnaries->toArray(); if(!isset($_['depth'])) $_['depth'] = 1; $dictionnaries['childs'] = Dictionnary::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 = Dictionnary::hierarchy($_['value'],$_['slug']); } } $response['content'] = $dictionnaries; }); Action::register('dictionnary_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 = Dictionnary::provide(); if(!empty($item->slug)) return; } $parentSlug = empty($_['parent']) ? '' : Dictionnary::getById($_['parent'])->slug; $slug = empty($parentSlug) ? $_['label'] : $parentSlug.'_'.$_['label']; $response['slug'] = generateSlug($slug, Dictionnary::class, 'slug', '', '_'); }); /* Composant tag list */ Action::register('tag_list_autocomplete',function(&$response){ global $myUser,$_; if(!$myUser->can('dictionnary','read')) throw new Exception("Vous n'avez pas acces aux listes"); $response['rows'] = array(); foreach(Dictionnary::staticQuery('SELECT * FROM {{table}} WHERE parent=(SELECT id from {{table}} WHERE slug= ? LIMIT 1) AND label LIKE ? AND state = ? ',array($_['data']['parent'],'%'.$_['keyword'].'%',Dictionnary::ACTIVE),true) as $item){ $response['rows'][] = array( 'name'=>$item->label, 'id'=>$item->id, 'slug'=>$item->slug ); } }); Action::register('tag_list_autocreate',function(&$response){ global $myUser,$_; if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401); $response = array(); $parent = Dictionnary::bySlug($_['slug']); $newtag = new Dictionnary(); $newtag->state = Dictionnary::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('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(Dictionnary::loadAll(array('id:IN'=>$ids)) as $dictionnary){ $dictionnaryMapping[$dictionnary->id] = $dictionnary; } foreach ($ids as $id) { if(!isset($dictionnaryMapping[$id])) continue; $item = $dictionnaryMapping[$id]; $row = $item->toArray(); $row['label'] = $item->label; $row['slug'] = $item->slug; $row['id'] = $item->id; $response['tags'][] = $row; } }); /** TABLEAU DE DICTIONNARY */ Action::register('dictionnary_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 = Dictionnary::getById($_['id']); $response['dictionnary'] = $dic->toArray(true); foreach (Dictionnary::childs(array('slug'=>$dic->slug)) as $child) $response['rows'][] = $child->toArray(true); }); Action::register('dictionnary_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'])? Dictionnary::getById($_['id']) : new Dictionnary(); $dic->parent = $_['list']; $dic->label = $_['label']; if(isset($_['slug']) && !empty($_['slug'])) { $parameters = array('slug'=>$_['slug'], 'state'=>Dictionnary::ACTIVE); if(isset($dic->id) && !empty($dic->id)) $parameters['id:!='] = $dic->id; if(Dictionnary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé"); $dic->slug = $_['slug']; } $dic->state = Dictionnary::ACTIVE; $dic->save(); }); /* COMPOSANT LOCATION */ Action::register('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('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('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('upload_temporary_file',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 basename($fileIndex['tmp_name'][$i]), 'name' => $fileIndex['name'][$i], 'temporary' => true, 'ext' => $ext, 'url' => 'action.php?action=download_temporary_file&name='.$fileIndex['name'][$i].'&path='.basename($fileIndex['tmp_name'][$i]), 'icon' => getExtIcon($ext) ); } }); Action::register('download_temporary_file',function(&$response){ global $myUser,$_; User::check_access('file','read'); File::downloadFile(File::temp().$_['path'],$_['name']); }); /** GENERAL SETTINGS **/ Action::register('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('disabled.maintenance')) rename('disabled.maintenance', 'enabled.maintenance'); file_put_contents('enabled.maintenance', trim($_['maintenance-content'])); } else { if(file_exists('enabled.maintenance')) rename('enabled.maintenance', 'disabled.maintenance'); file_put_contents('disabled.maintenance', trim($_['maintenance-content'])); } } }); Action::register('general_reset_password_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_setting_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_setting_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('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 : '.$user->login)); } catch(Exception $e){ header('location: setting.php?section=user&error='.rawurlencode($e->getMessage())); } }); /* HISTORY */ Action::register('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('history_importance',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('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('history_delete',function(&$response){ global $myUser,$_; User::check_access('history','delete'); History::deleteById($_['id']); }); /* CONTACT */ Action::register('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('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('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;$iroute('infos','retourne les informations sur l\'environnement','GET',function($request,&$response){ global $myUser,$databases_credentials; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $repository = ''; if(file_exists(__DIR__.SLASH.'.git'.SLASH.'config')){ $stream = file_get_contents(__DIR__.SLASH.'.git'.SLASH.'config'); preg_match('|url = (.*\.fr)[:/]([^\n]*)|is', $stream,$match); $repository = $match[2]; $repositoryUrl = preg_replace('|[^@]*@|i','http://',$match[1]).'/'.$match[2]; } if(file_exists(__DIR__.SLASH.'.git'.SLASH.'refs'.SLASH.'heads'.SLASH.'master')) $commitVersion = str_replace(array("\n","\r"),"",file_get_contents(__DIR__.SLASH.'.git'.SLASH.'refs'.SLASH.'heads'.SLASH.'master')); $response['application']['label'] = PROGRAM_NAME; $response['application']['version'] = SOURCE_VERSION; $response['application']['versionning']['type'] = 'git'; $response['application']['versionning']['repository'] = $repository; $response['application']['versionning']['repository_url'] = $repositoryUrl; $response['application']['versionning']['commit_version'] = $commitVersion; $response['application']['timezone'] = TIME_ZONE; $response['php']['version'] = phpversion(); $response['apache']['version'] = apache_get_version(); $response['databases'] = array(); foreach ($databases_credentials as $key => $value) { unset($value['password']); $value['uid'] = $key; $response['databases'][] = $value; } $response['os']['type'] = PHP_OS; $response['os']['time'] = time(); }); $api->route('token','retourne un jwt token en fonction des identifiants fournis sur l\'environnement','POST',function($request,&$response){ $_ = json_decode($request['body'],true); if(!isset($_['api_id']) || !isset($_['api_secret'])) throw new Exception("Api Credentials are missing",401); global $conf; if(empty($conf->get('jwtauth_secret'))) throw new Exception('JWT secret is missing in core',501); if(session_status() == PHP_SESSION_ACTIVE) session_destroy(); session_start(); $apiKey = UserPreference::load(array('key'=>'api_id','value'=>encrypt($_['api_id']))); if(!$apiKey) throw new Exception('Api id not found',404); $apiSecret = UserPreference::load(array('key'=>'api_secret','user'=>$apiKey->user,'value'=>encrypt($_['api_secret']))); if(!$apiSecret) throw new Exception('Bad api secret',401); $apiEnabled = UserPreference::load(array('key'=>'api_enabled','user'=>$apiKey->user,'value'=>1)); if(!$apiEnabled) throw new Exception('Api is not enabled for this account',401); global $myUser,$myFirm; $myUser = User::connectLogin($apiSecret->user); if(!$myUser || !$myUser->connected()) throw new Exception('Bad credentials',401); if(file_exists('enabled.maintenance') && $myUser->superadmin != 1) throw new Exception('Maintenance is enabled, only super admin can connects',403); $_SESSION['currentUser'] = serialize($myUser); $_SESSION['firm'] = serialize($myFirm); $response['session'] = session_id(); $json = array(); $json['exp'] = strtotime('+8hours'); $json['attributes'] = array( 'session_id' => session_id(), 'user' => $myUser->login ); $response['token'] = JWToken::createFromJson($json,$conf->get('jwtauth_secret')); }); //right api $api->route('rights','retourne la liste des droits du logiciel','GET',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['rights'] = array(); if(isset($request['parameters']['sort'])) throw new Exception("Sort is not implemented for firms",501); if(isset($request['parameters']['filter'])) throw new Exception("Filter is not implemented for firms",501); $limit = isset($request['parameters']['limit']) ? array($request['parameters']['limit']) : array(); foreach (Right::loadAll(array(),array(),$limit) as $right) { $row = $right->toArray(); $response['rights'][] = $row; } }); $api->route('rights/[rightid]','ajoute/modifie un droit du logiciel','PUT',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['right'] = array(); //Création $_ = $request['parameters']; $form = json_decode($request['body'],true); if(!$form) throw new Exception("Invalid JSON body",400); User::check_access('right','edit'); if(!empty($request['pathes'])){ $right = Right::getById($request['pathes'][0]); if(empty($right->id)) throw new Exception("Right not found", 404); $response['code'] = 200; //Modifié }else{ $right = new right(); if(!isset($form['rank']) || empty($form['rank'])) throw new Exception("L'id du rang est obligatoire",400); if(!isset($form['scope']) || empty($form['scope'])) throw new Exception("Le nom de la scope est obligatoire",400); if(!isset($form['firm']) || empty($form['firm'])) throw new Exception("L'id de l'établissement est obligatoire",400); $response['code'] = 201; //Créé } //Check si le rang existe $rank = Rank::getById($form['rank']); if(empty($rank->id)) throw new Exception("Rank not found", 400); //Check si la firm existe $firm = Firm::getById($form['firm']); if(empty($firm->id)) throw new Exception("Firm not found", 400); //Check si la scope existe $scopes = array(); Plugin::callHook('section',array(&$scopes)); $find = false; foreach($scopes as $scope=>$description){ if ($scope==$form['scope']){ $find = true; break; } } if (!$find) throw new Exception("Section not found", 400); if(isset($form['targetUid'])) $right->targetUid = $form['targetUid']; if(isset($form['scope'])) $right->scope = $form['scope']; if(isset($form['firm'])) $right->firm = $form['firm']; if(isset($form['read'])) $right->read = $form['read']; if(isset($form['edit'])) $right->edit = $form['edit']; if(isset($form['delete'])) $right->delete = $form['delete']; if(isset($form['configure'])) $right->configure = $form['configure']; $right->save(); Log::put("Création/Modification de droit ".$right->toText(),'Droit'); $response['right'] = array('id'=>$right->id,'scope'=>$right->scope); }); $api->route('rights/rightid','Supprime un rang du logiciel','DELETE',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); if(empty($request['pathes'])) throw new Exception("You must specify right id", 400); User::check_access('right','delete'); $right = Right::getById($request['pathes'][0]); if(!$right) throw new Exception("Right not found",404); $right->deleteById($right->id); Log::put("Suppression du rang ".$right->toText(),'Rang'); $response['code'] = 204; }); //rank api $api->route('ranks','retourne la liste des rangs du logiciel','GET',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['ranks'] = array(); if(isset($request['parameters']['sort'])) throw new Exception("Sort is not implemented for firms",501); if(isset($request['parameters']['filter'])) throw new Exception("Filter is not implemented for firms",501); $limit = isset($request['parameters']['limit']) ? array($request['parameters']['limit']) : array(); foreach (Rank::loadAll(array(),array(),$limit) as $rank) { $row = $rank->toArray(); $response['ranks'][] = $row; } }); $api->route('ranks/[rankid]','ajoute/modifie un rang du logiciel','PUT',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['rank'] = array(); //Création $_ = $request['parameters']; $form = json_decode($request['body'],true); if(!$form) throw new Exception("Invalid JSON body",400); User::check_access('rank','edit'); if(!empty($request['pathes'])){ $rank = Rank::getById($request['pathes'][0]); if(empty($rank->id)) throw new Exception("Rank not found", 404); $response['code'] = 200; //Modifié }else{ $rank = new rank(); if(!isset($form['label']) || empty($form['label'])) throw new Exception("Le libellé est obligatoire",400); //Check si un rang n'existe pas déjà avec ce label if(Rank::load(array('label'=>$form['label']))) throw new Exception("Un rang existe déjà avec ce nom",400); $rank->label = $form['label']; $response['code'] = 201; //Créé } if(isset($form['label'])) $rank->label = $form['label']; if(isset($form['description'])) $rank->description = $form['description']; $rank->save(); Log::put("Création/Modification de rang ".$rank->toText(),'Rang'); $response['rank'] = array('id'=>$rank->id,'label'=>$rank->label); }); $api->route('ranks/rankid','Supprime un rang du logiciel','DELETE',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); if(empty($request['pathes'])) throw new Exception("You must specify rank id", 400); User::check_access('rank','delete'); $rank = Rank::getById($request['pathes'][0]); if(!$rank) throw new Exception("Rank not found",404); foreach(UserFirmRank::loadAll(array('rank'=>$rank->id)) as $ufrLink) UserFirmRank::deleteById($ufrLink->id); $rank->deleteById($rank->id); Log::put("Suppression du rang ".$rank->toText(),'Rang'); $response['code'] = 204; }); //firm api $api->route('firms','retourne la liste des établissements du logiciel','GET',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['firms'] = array(); if(isset($request['parameters']['sort'])) throw new Exception("Sort is not implemented for firms",501); if(isset($request['parameters']['filter'])) throw new Exception("Filter is not implemented for firms",501); $limit = isset($request['parameters']['limit']) ? array($request['parameters']['limit']) : array(); foreach (Firm::loadAll(array(),array(),$limit) as $i=>$firm) { $row = $firm->toArray(); $response['firms'][] = $row; } }); $api->route('firms/[firmid]','ajoute/modifie un établissement du logiciel','PUT',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['firm'] = array(); //Création $_ = $request['parameters']; $form = json_decode($request['body'],true); if(!$form) throw new Exception("Invalid JSON body",400); User::check_access('firm','edit'); if(!empty($request['pathes'])){ $firm = Firm::getById($request['pathes'][0]); if(empty($firm->id)) throw new Exception("Firm not found", 404); $response['code'] = 200; //Modifié }else{ $firm = new Firm(); if(!isset($form['label']) || empty($form['label'])) throw new Exception("Le libellé est obligatoire",400); if(!isset($form['mail']) || empty($form['mail'])) throw new Exception('Le champ "Mail"est obligatoire',400); //Check si une firm n'existe pas déjà avec ce label if(Firm::load(array('label'=>$form['label']))) throw new Exception("Un établissement existe déjà avec ce nom",400); $firm->label = $form['label']; $response['code'] = 201; //Créé } if(isset($form['label'])) $firm->label = $form['label']; if(isset($form['description'])) $firm->description = $form['description']; if(isset($form['mail'])) $firm->mail = $form['mail']; if(isset($form['phone'])) $firm->phone = $form['phone']; if(isset($form['fax'])) $firm->fax = $form['fax']; if(isset($form['street'])) $firm->street = $form['street']; if(isset($form['street2'])) $firm->street2 = $form['street2']; if(isset($form['city'])) $firm->city = $form['city']; if(isset($form['zipcode'])) $firm->zipcode = $form['zipcode']; if(isset($form['siret'])) $firm->siret = $form['siret']; if(isset($form['iban'])) $firm->iban = $form['iban']; $firm->save(); Log::put("Création/Modification de l'établissement ".$firm->toText(),'Etablissement'); $response['firm'] = array('id'=>$firm->id,'label'=>$firm->label); }); $api->route('firms/firmid','Supprime un établissement du logiciel','DELETE',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); if(empty($request['pathes'])) throw new Exception("You must specify firm id", 400); User::check_access('firm','delete'); $firm = Firm::getById($request['pathes'][0]); if(!$firm) throw new Exception("Firm not found",404); foreach(UserFirmRank::loadAll(array('firm'=>$firm->id)) as $ufrLink) UserFirmRank::deleteById($ufrLink->id); $firm->deleteById($firm->id); Log::put("Suppression de l'établissement ".$firm->toText(),'Etablissement'); $response['code'] = 204; }); //user api $api->route('account','retourne les informations du compte connecté','GET',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['account'] = $myUser->toArray(); unset($response['account']['password']); }); //user api $api->route('users','retourne la liste des utilisateurs du logiciel','GET',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['users'] = array(); if(isset($request['parameters']['sort'])) throw new Exception("Sort is not implemented for users",501); if(isset($request['parameters']['filter'])) throw new Exception("Filter is not implemented for users",501); foreach (User::getAll(array('right'=>false)) as $i=>$user) { if(isset($request['parameters']['limit']) && $request['parameters']['limit']==$i) break; $row = $user->toArray(); unset($row['password']); unset($row['manager']); $row['origin'] = !isset($row['id']) ? 'plugin': 'database'; $response['users'][] = $row; } }); $api->route('users/[userid]','ajoute/modifie un utilisateur du logiciel','PUT',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['user'] = array(); //Création $_ = $request['parameters']; $form = json_decode($request['body'],true); if(!$form) throw new Exception("Invalid JSON body",400); User::check_access('user','edit'); if(!empty($request['pathes'])){ $user = User::byLogin($request['pathes'][0]); if(empty($user->login)) throw new Exception("User not found", 404); $response['code'] = 200; //Modifié }else{ $user = new User(); if(!isset($form['login']) || empty($form['login'])) throw new Exception("Identifiant obligatoire",400); if(!isset($form['password']) || empty($form['password'])) throw new Exception("Mot de passe obligatoire",400); if(!isset($form['mail']) || empty($form['mail'])) throw new Exception('Le champ "Mail"est obligatoire',400); foreach(User::getAll(array('right'=>false)) as $existingUser) if($existingUser->mail == trim($_['mail'])) throw new Exception("Un utilisateur existe déjà avec cette adresse e-mail"); //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(User::load(array('login'=>$form['login']))) throw new Exception("Un utilisateur existe déjà avec cet identifiant",400); $user->login = $form['login']; $response['code'] = 201; //Créé } if(!empty(trim($form['password']))){ $passwordErrors = User::check_password_format(html_entity_decode($form['password'])); if(count($passwordErrors)!=0 && !$myUser->superadmin) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes :
".implode("
",$passwordErrors), 400); if($form['password']==$form['login'] || $form['password']==$form['mail'] ) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant ou à l'e-mail",400); $user->password = User::password_encrypt($form['password']); $user->preference('passwordTime',time()); } if(isset($form['firstname'])) $user->firstname = mb_ucfirst(mb_strtolower($form['firstname'])); if(isset($form['name'])) $user->name = mb_strtoupper($form['name']); if(isset($form['mail'])) $user->mail = $form['mail']; $user->state = User::ACTIVE; if(isset($form['manager'])) $user->manager = $form['manager']; $user->save(); User::getAll(array('right'=>true,'force'=>true)); Log::put("Création/Modification de l'utilisateur ".$user->toText(),'Utilisateur'); $response['user'] = array('id'=>$user->id,'login'=>$user->login); }); $api->route('users/userid','Supprime un utilisateur du logiciel','DELETE',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); if(empty($request['pathes'])) throw new Exception("You must spcify user login", 400); User::check_access('user','delete'); $user = User::byLogin($request['pathes'][0]); if(!$user) throw new Exception("User not found",404); if($user->superadmin == 1) throw new Exception("You can't delete superadmin account",403); if($user->login == $myUser->login) throw new Exception("You can't delete your own account",403); if(empty($user->id)) throw new Exception("You cant delete no db account", 400); $user = User::getById($user->id); $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'); $response['code'] = 204; }); $api->register(); /* FIN CORE API */ Api::run(); }); /** 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('
'.$e->getMessage().'
'); } }); /** ACTIONS DE PLUGINS */ //nouveau system d'action plugin if(isset($GLOBALS['actions'][$_['action']])){ Action::write($GLOBALS['actions'][$_['action']]); }else{ //compatibilité ancien système d'action plugin (deprecated) Plugin::callHook('action'); } ?>