12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460 |
- <?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');
- //Execution du code en fonction de l'action
- switch ($_['action']){
-
- case 'login':
- Action::write(function(&$response){
- global $myUser,$myFirm,$_,$conf;
- try {
- if(!isset($_['login'])) $_['login'] = 'anonymous';
- if(!isset($_['password'])) $_['password'] = '';
- // ETAPE 1
- 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);
- }
-
- // ETAPE 3
- $myUser = User::check($_['login'],$_['password']);
- if(!$myUser)
- throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
- // ETAPE 4
- if(file_exists('enabled.maintenance') && $myUser->superadmin != 1)
- throw new Exception('Seul un compte Super Admin peut se connecter en mode maintenance');
-
- // ETAPE 5
- if(!$myUser->connected())
- throw new Exception('Identifiant ou mot de passe incorrect');
-
- $myUser->loadPreferences();
- // ETAPE 6
- 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');
- }
-
- // ETAPE 7
- $myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']) : new Firm();
- if(!$myFirm)
- throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
-
- // ETAPE 8
- $_SESSION['currentUser'] = serialize($myUser);
- if(!$_SESSION['currentUser'])
- throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
-
- // ETAPE 10
- if(isset($_['rememberMe']) && $_['rememberMe']=='on'){
- $cookie = sha1('$^é"'.mt_rand(0,100000).'=)àç_è');
- $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']);
- }
- //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();
- }
- // ETAPE 11
- Log::put("Connexion réussie avec \"".$myUser->login."\"",'Utilisateur');
- } catch(Exception $e){
- Log::put("Echec 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('anonymous','auth_fail');
- throw new Exception($e->getMessage());
- }
- });
- break;
-
- case 'logout':
- global $myUser;
- if(isset($myUser->login)) $myUser->preference('cookie','');
- $url = 'index.php';
- if(isset($_['url'])) $url = base64_decode($_['url']);
- //Permet la redirection vers une url spécifique lors de la déco
- if(isset($_SESSION['logout_redirect'])) $url = $_SESSION['logout_redirect'];
- unset($_SESSION['currentUser']);
- unset($_SESSION['firm']);
- session_destroy();
- unset($_COOKIE[COOKIE_NAME]);
- setcookie(COOKIE_NAME, null, -1, '/');
- $redirect = $url;
- Plugin::callHook('logout',array($url,$myUser));
- header('location: '.$redirect);
- break;
- /** FILTERS **/
- case 'filter_save':
- Action::write(function(&$response){
- global $myUser,$_;
- $preferences = json_decode($myUser->preference('search_filters'),true);
- if(!$preferences) $preferences = array();
- if(isset($_['filters']['advanced'])){
- foreach($_['filters']['advanced'] as $i=>$advanced){
- $advanced['operator'] = html_entity_decode($advanced['operator']);
- $_['filters']['advanced'][$i] = $advanced;
- }
- }
- $preferences[$_['slug']] = $_['filters'];
- $myUser->preference('search_filters',json_encode($preferences));
- $response['message'] = 'Recherche enregistrée';
- $_SESSION['currentUser'] = serialize($myUser);
- });
- break;
- case 'filter_load':
- Action::write(function(&$response){
- global $myUser,$_;
- $preferences = json_decode($myUser->preference('search_filters'),true);
- if(!$preferences) $preferences = array();
- $response['filters'] = array();
- if(isset($preferences[$_['slug']])) $response['filters'] = $preferences[$_['slug']];
- });
- break;
- /** LOGS */
- case 'search_log':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('log','read');
- $query = 'SELECT * FROM {{table}} WHERE 1';
- $data = array();
- //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('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(100,(!empty($_['page'])?$_['page']:0),$query,$data);
- foreach(Log::staticQuery($query,$data,true) as $log){
- $log->created = date('d/m/Y H:i:s',$log->created);
- if(!empty($_['keyword'])){
- $log->label = preg_replace_callback('|(.*)('.$_['keyword'].')(.*)|i', function($matches){
- return $matches[1].'<mark>'.$matches[2].'</mark>'.$matches[3];
- }, $log->label);
- }
- //evite les json encode crash lorsque la chaine contient des caractères spéciaux non utf-8
- $log->label = htmlentities($log->label);
- $response['rows'][] = $log;
- }
- });
- break;
-
- /** PLUGINS **/
- case 'search_plugin':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('plugin','read');
- foreach(Plugin::getAll() as $plugin){
- $plugin->folder = array('name'=>$plugin->folder,'path'=>$plugin->path());
- $response['rows'][] = $plugin;
- }
- });
- break;
-
- case 'change_plugin_state':
- Action::write(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']);
- //TODO - mettre en place un timeout - core_reference();
- Log::put(($_['state']?'Activation':'Désactivation')." du plugin ".$_['plugin'],'Plugin');
- });
- break;
-
- /** LIEN ETABLISSEMENT / PLUGIN **/
- case 'search_firm_plugin':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('plugin','configure');
- if(!isset($_['firm'])) throw new Exception("Etablissement 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;
- }
- });
- break;
- case 'toggle_firm_plugin':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('plugin','configure');
- foreach(Firm::loadAll() 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);
- }
- });
- break;
- /** ETABLISSEMENT */
- case 'select_firm':
- global $myUser,$_,$myFirm;
- try{
- 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);
- header('location: index.php');
- }catch(Exception $e){
- header('location: index.php?error='.urlencode($e->getMessage()));
- }
- break;
- case 'search_firm':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('firm','read');
- foreach(Firm::loadAll()as $firm){
- $row = $firm->toArray();
- $row['address'] = $firm->address();
- $response['rows'][] = $row;
- }
- });
- break;
-
- case 'firm_logo_download':
- global $myUser,$_;
- try {
- File::downloadFile(File::dir().Firm::logo_path().$_['firm'].'.'.$_['extension']);
- } catch(Exception $e) {
- File::downloadFile('img/default-image.png');
- }
- break;
- case 'firm_logo_delete':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('firm','edit');
- $firm = Firm::provide();
- if(!$firm) throw new Exception("Établissement non identifié");
- foreach (glob(__ROOT__.FILE_PATH.Firm::logo_path().$firm->id.".*") as $filename)
- unlink($filename);
- if(!file_exists(__ROOT__.FILE_PATH.Firm::logo_path().'.thumbnails')) return;
- foreach (glob(__ROOT__.FILE_PATH.Firm::logo_path().'.thumbnails'.SLASH.$firm->id.".*") as $filename) {
- unlink($filename);
- }
- });
- break;
- case 'save_firm':
- global $myUser,$_;
- try{
- User::check_access('firm','edit');
- $firm = Firm::provide();
- $firm->fromArray($_);
- if(empty($firm->label)) throw new Exception("Vous devez remplir au moins le libellé de l'entreprise");
- $firm->save();
- //Ajout de l'image à la base de media
- if(!empty($_FILES['logo']) && $_FILES['logo']['size']!=0 ){
- foreach (glob(Firm::logo_path().$firm->id.".*") as $filename) {
- unlink($filename);
- }
- $logo = File::upload('logo',Firm::logo_path().$firm->id.'.{{ext}}',1048576,array('jpg','png','jpeg'));
- Image::resize($logo['absolute'],200,200);
- }
- Log::put("Ajout/Modification de l'établissement ".$firm->toText(),'Etablissement');
- header('location: setting.php?section=firm&success=Établissement enregistré');
- }catch(Exception $e){
- header('location: firm.php?id='.$firm->id.'&error='.$e->getMessage());
- }
- break;
- case 'delete_firm':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('firm','delete');
- $firm =Firm::getById($_['id']);
- Firm::deleteById($_['id']);
- $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);
- UserFirmRank::delete(array('firm'=>$_['id']));
- Right::delete(array('firm'=>$_['id']));
- Log::put("Suppression de l'établissement ".$firm->toText(),'Etablissement');
- });
- break;
- /** LIEN ETABLISSEMENT / UTILISATEUR / RANG **/
- case 'search_userfirmrank':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('firm','read');
-
- if($_['firm'] == 0)
- foreach(Firm::loadAll() as $firm)
- $firms[] = $firm->id;
- else
- $firms[] = $_['firm'];
- $users = array();
- foreach(User::getAll(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 ('".implode("','",$firms)."')",array(),false) as $userFirmRank){
-
- $user = isset($users[$userFirmRank['user']]) ? $users[$userFirmRank['user']] : new User();
-
- // Petit trick pour l'affichage mustache
- if($user->superadmin != 1) $userFirmRank['superadmin'] = null;
- $userFirmRank['avatar'] = $user->getAvatar();
- $userFirmRank['password'] = '';
- $userFirmRank['user'] = $user;
- $response['rows'][] = $userFirmRank;
- }
- });
- break;
-
- case 'save_userfirmrank':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('firm','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;
- $userFirmRank = UserFirmRank::provide();
- $exist = is_null($userFirmRank->id) || $_['firm'] == 0 ? UserFirmRank::rowCount(array('user'=>$_['user'],'firm'=>$firm->id,'rank'=>$_['rank'])) : UserFirmRank::rowCount(array('id:!='=>$userFirmRank->id,'user'=>$_['user'],'firm'=>$firm->id,'rank'=>$_['rank']));
- if($exist > 0) throw new Exception("Ce rang est déja défini pour cet utilisateur et l'établissement ".$firm->label);
- $userFirmRank->fromArray($_);
- $userFirmRank->firm = $firm->id;
- $userFirmRank->save();
- $response['success'][] = $firm->label;
- }
- });
- break;
- case 'edit_userfirmrank':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('firm','edit');
- $userFirmRank = UserFirmRank::getById($_['id']);
- $response = $userFirmRank;
- });
- break;
-
- case 'delete_userfirmrank':
- Action::write(function(&$response){
- global $myUser,$_,$conf;
- User::check_access('firm','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']);
- });
- break;
-
- /** UTILISATEURS **/
- case 'search_user':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('user','read');
- foreach(User::getAll() as $user){
- if($user->state == User::INACTIVE) continue;
- $user->avatar = $user->getAvatar();
- $response['rows'][] = $user;
- }
- });
- break;
- case 'user_autocomplete':
- Action::write(function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- $response['rows'] = array();
- if($_['keyword'] == '') return;
- if(in_array('user', $_['data']['types'])){
- foreach(User::getAll() as $user){
- if(preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->fullName())) || preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', $user->login)){
- $response['rows'][] = array(
- 'name'=>$user->fullName(),
- '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(
- 'name'=>$rank->label,
- 'id'=>$rank->id,
- 'type'=>'rank',
- 'description'=>$rank->description,
- );
- }
- }
- });
- break;
- case 'user_by_uid':
- Action::write(function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- $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) continue;
- $row = $item->toArray();
- $row['fullname'] = $item->fullName();
- $row['type'] = 'user';
- $row['uid'] = $item->login;
- unset($row['password']);
- unset($row['token']);
-
- $response['users'][$row['uid']] = $row;
- }
- //rank
- foreach(Rank::loadAll(array('id:IN'=>implode(',',$ranks))) as $item){
- $row = $item->toArray();
- $row['fullname'] = $item->label;
- $row['type'] = 'rank';
- $row['uid'] = $item->id;
- $response['users'][$row['uid']] = $row;
- }
- });
- break;
- case 'account_lost_password':
- Action::write(function(&$response){
- global $myUser,$myFirm,$_,$conf;
- if(!isset($_['mail']) || empty($_['mail']) || !check_mail($_['mail'])) throw new Exception("Adresse e-mail non spécifiée ou incorrecte");
- foreach(User::getAll() as $user){
- if(strtolower($user->mail) == strtolower($_['mail'])){
- $token = sha1(time().mt_rand(0,1000));
- $linkToken = base64_encode($user->login.'::'.$token);
- 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->title="Mot de passe perdu";
- $link = ROOT_URL.'/account.lost.php?token='.$linkToken;
- $mail->message = "
- Vous recevez cet e-mail parce que quelqu'un a fait une demande de changement de mot de passe pour votre compte sur ".ROOT_URL.".
- <br/>Si il s'agit bien de vous, <a href='".$link."'>Cliquez ici pour changer votre mot de passe</a> ou copiez collez le lien suivant dans votre navigateur préféré.
- <br/>Si vous n'êtes pas à l'origine de ce mail, aucune action n'est requise.";
- $mail->recipients['to'][] = $user->mail;
- $mail->send();
- return;
- }
- }
- throw new Exception("Aucun compte ne correspond à l'e-mail spécifié dans notre base, veuillez contacter un administrateur pour modifier votre mot de passe.");
- });
- break;
- case 'account_save':
- Action::write(function(&$response){
- global $myUser,$myFirm,$_;
- User::check_access('account','edit');
- if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
- if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Adresse mail obligatoire');
- $userForm = new User();
- $userForm->fromArray($_);
- if(empty($userForm->login))
- if(!isset($_['password']) || empty($_['password'])) throw new Exception("Mot de passe obligatoire");
- //Vérifications & formattage des données
- $userForm->firstname = ucfirst($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($_['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 = sha1(md5('$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 = sha1(md5($_['password']));
- }
- $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;
- $myUser->save();
- if($myUser->superadmin == 1){
- foreach(Firm::loadAll() as $firm)
- $firms[$firm->id] = $firm;
- $myUser->setFirms($firms);
- }
- }
- $myUser->preference('passwordTime',time());
- //save de l'avatar
- if(!empty($_FILES['avatar']) && $_FILES['avatar']['size']!=0 ){
- foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.$myUser->login.".*") as $filename) {
- unlink($filename);
- }
- $logo = File::upload('avatar',AVATAR_PATH.$myUser->login.'.{{ext}}',104857060,array('jpg','png','jpeg','gif'));
- Image::resize($logo['absolute'],150,150);
- }
- //save des comptes types plugin
- Plugin::callHook("user_save",array(&$myUser,$userForm,&$response));
- $myUser->loadRights();
- unset($_SESSION['users']);
- $_SESSION['currentUser'] = serialize($myUser);
- });
- break;
- case 'account_avatar_download':
- global $myUser,$_;
- try {
- $user = str_replace(array('..','/'),'',$_['user']);
- $extension = str_replace(array('..','/'),'',$_['extension']);
- File::downloadFile(File::dir().AVATAR_PATH.$user.'.'.$extension);
- } catch(Exception $e) {
- File::downloadFile('img/default-avatar.png');
- }
- break;
- case 'account_avatar_delete':
- Action::write(function(&$response){
- global $myUser,$_;
- $user = User::byLogin($_['login']);
- if(!$user) throw new Exception("Utilisateur non identifié");
- if($myUser->login!=$user->login && !$myUser->can('user', 'edit')) throw new Exception("Permissions insuffisantes",403);
- foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.$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->login.".*") as $filename) {
- unlink($filename);
- }
- });
- break;
- case 'save_user':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('user','edit');
- if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
- 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($_['password']!=$_['password2']) throw new Exception("Mot de passe et confirmation non similaires");
- $user = User::byLogin($_['login']);
- $user = $user ? $user : new User();
- if($user->id == 0)
- if(!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) 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 = sha1(md5($_['password']));
- $user->preference('passwordTime',time());
- }
- $user->firstname = ucfirst($_['firstname']);
- $user->name = mb_strtoupper($_['name']);
- $user->mail = $_['mail'];
- $user->state = User::ACTIVE;
- if(isset($_['manager'])) $user->manager = $_['manager'];
- //Check si un user n'existe pas déjà avec ce login
- if(empty($user->id) && User::load(array('login'=>$_['login']))) throw new Exception("Un utilisateur existe déjà avec cet identifiant");
- if(!$user->login) $user->login = $_['login'];
- $user->save();
- unset($_SESSION['users']);
- $user->password = '';
- Log::put("Création/Modification de l'utilisateur ".$user->toText(),'Utilisateur');
- });
- break;
-
- case 'edit_user':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('user','edit');
- $user = User::byLogin($_['login']);
- if(!$user) throw new Exception("Utilisateur non identifié");
- $user->password = '';
- $response = $user;
- });
- break;
- case 'delete_user':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('user','delete');
- $user = User::byLogin($_['login']);
- if(!$user) throw new Exception("Utilisateur non identifié");
- 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");
- $user = User::getById($user->id);
- $user->state = User::INACTIVE;
- $user->save();
- foreach(UserFirmRank::loadAll(array('user'=>$user->login)) as $ufrLink)
- UserFirmRank::deleteById($ufrLink->id);
- unset($_SESSION['users']);
- Log::put("Suppression de l'utilisateur ".$user->toText(),'Utilisateur');
- });
- break;
- /** DROITS **/
-
- case 'search_right':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('rank','edit');
- if(!isset($_['firm'])) throw new Exception("Etablissement non spécifié");
- $wholeRights = array();
- $sections = array();
- Plugin::callHook('section',array(&$sections));
- foreach(Firm::loadAll() as $firm){
- if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
- $rights = Right::loadAll(array('rank'=>$_['rank'],'firm'=>$firm->id));
- $rightsTable = array();
- foreach($rights as $right)
- $rightsTable[$right->section] = $right;
- if($_['firm'] == '0'){
- foreach($sections as $section=>$description) {
- $right = isset($rightsTable[$section])? $rightsTable[$section] : new Right();
- $wholeRights[$section]['read'][$firm->id] = (int)$right->read;
- $wholeRights[$section]['edit'][$firm->id] = (int)$right->edit;
- $wholeRights[$section]['delete'][$firm->id] = (int)$right->delete;
- $wholeRights[$section]['configure'][$firm->id] = (int)$right->configure;
- }
- }
- }
- foreach ($sections as $section=>$description) {
- if($_['firm'] == '0'){
- $read = count(array_unique($wholeRights[$section]['read'])) === 1 ? end($wholeRights[$section]['read']) : 2;
- $edit = count(array_unique($wholeRights[$section]['edit'])) === 1 ? end($wholeRights[$section]['edit']) : 2;
- $delete = count(array_unique($wholeRights[$section]['delete'])) === 1 ? end($wholeRights[$section]['delete']) : 2;
- $configure = count(array_unique($wholeRights[$section]['configure'])) === 1 ? end($wholeRights[$section]['configure']) : 2;
- }else{
- $right = isset($rightsTable[$section])? $rightsTable[$section] : new Right();
- $read = $right->read;
- $edit = $right->edit;
- $delete = $right->delete;
- $configure = $right->configure;
- }
- $response['rows'][] = array(
- 'section'=>$section,
- 'description'=>$description,
- 'read'=>(int)$read,
- 'edit'=>(int)$edit,
- 'delete'=>(int)$delete,
- 'configure'=>(int)$configure
- );
- usort($response['rows'], function($a, $b){
- return strcmp($a['section'], $b['section']);
- });
- }
- });
- break;
-
- case 'toggle_right':
- Action::write(function(&$response){
- global $myUser,$_,$myFirm;
- User::check_access('rank','edit');
- if(!isset($_['section']) || empty($_['section'])) throw new Exception("Droit non spécifié");
- if(!isset($_['rank']) || empty($_['rank'])) throw new Exception("Rang non spécifié");
- if(!isset($_['right']) || empty($_['right'])) throw new Exception("Droit non spécifié");
- if(!isset($_['firm'])) throw new Exception("Etablissement non spécifié");
-
- foreach(Firm::loadAll() as $firm){
- if($firm->id != $_['firm'] && $_['firm'] != '0') continue;
- $item = Right::load(array('rank'=>$_['rank'],'firm'=>$firm->id,'section'=>$_['section']));
- $item = !$item ? new Right() : $item ;
- $item->rank = $_['rank'];
- $item->firm = $firm->id;
- $item->section = $_['section'];
- $item->{$_['right']} = $_['state'];
- $item->save();
-
- $myUser->loadRights();
-
- $_SESSION['currentUser'] = serialize($myUser);
- }
- });
- break;
-
- /** RANGS **/
- case 'search_rank':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('rank','read');
- foreach(Rank::loadAll() as $rank){
- $row = $rank->toArray(true);
- $response['rows'][] = $row;
- }
- });
- break;
-
- case 'save_rank':
- Action::write(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');
- });
- break;
-
- case 'edit_rank':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('rank','edit');
- $response = Rank::getById($_['id']);
- });
- break;
- case 'delete_rank':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('rank','delete');
- $rank = Rank::getById($_['id']);
- Rank::deleteById($_['id']);
- Log::put("Suppression du rang ".$rank->toText(),'Rang');
- });
- break;
- /** LISTES **/
- case 'search_dictionnary':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('dictionnary','read');
- foreach(Dictionnary::loadAll(array('parent'=>$_['parent'], 'state'=>Dictionnary::ACTIVE), array(' label ASC ')) as $item){
- $item->label = html_entity_decode($item->label);
- $response['rows'][] = $item;
- }
- });
- break;
-
- case 'save_dictionnary':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('dictionnary','edit');
- if(!isset($_['label']) || empty($_['label'])) throw new Exception("Libellé obligatoire");
- if(!is_numeric($_['parent'])){
- if($myUser->superadmin == 1)
- $_['parent'] = 0;
- else
- throw new Exception("Veuillez sélectionner une liste");
- }
- $item = Dictionnary::provide();
- $item->label = $_['label'];
- $item->parent = $_['parent'];
- $item->state = Dictionnary::ACTIVE;
- if(isset($_['slug']) && !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(isset($_['sublistlabel'])) $item->sublistlabel = $_['sublistlabel'];
- $item->save();
- Log::put("Création/Modification de l'item de liste ".$item->toText(),'Liste');
- });
- break;
-
- case 'edit_dictionnary':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('dictionnary','edit');
- $dictionnary = Dictionnary::getById($_['id']);
- $response = $dictionnary->toArray(true);
- });
- break;
- case 'delete_dictionnary':
- Action::write(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');
- });
- break;
- case 'get_parent_dictionnary':
- Action::write (function (&$response){
- global $myUser,$_;
- $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
- );
- }
- });
- break;
- case 'load_dictionnary_component':
- Action::write (function (&$response){
- global $myUser,$_;
- $dictionnaries = array();
- if(isset($_['slug']) && $_['slug'] != "")
- $dictionnaries = Dictionnary::load(array("slug"=>$_['slug']));
- if(isset($_['parentId']) && $_['parentId'] != "")
- $dictionnaries = Dictionnary::getById($_['parentId']);
- if($dictionnaries) {
- $children = Dictionnary::childs(array('id'=>$dictionnaries->id));
- $dictionnaries->childs = $children;
- }
- if(isset($_['value']) && $_['value'] != "" && $_['value'] != 0){
- if(!$_['hierarchy']){
- foreach ($dictionnaries->childs as $i => $child) {
- if($child->id == $_['value']) $child->selected = true;
- $dictionnaries->childs[$i] = $child;
- }
- } else {
- $dictionnaries = Dictionnary::hierarchy($_['value']);
- }
- }
- $response['content'] = $dictionnaries;
- });
- break;
- /* Composant tag list */
- case 'tag_list_autocomplete':
- Action::write(function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- $response['rows'] = array();
- foreach(Dictionnary::staticQuery('SELECT * FROM {{table}} WHERE parent=(SELECT id from {{table}} WHERE slug= ? LIMIT 1) AND label LIKE ?',array($_['data']['parent'],'%'.$_['keyword'].'%'),true) as $item){
- $response['rows'][] = array(
- 'name'=>$item->label,
- 'id'=>$item->id,
- 'slug'=>$item->slug
- );
- }
- });
- break;
- case 'tag_list_by_id':
- Action::write(function(&$response){
- global $myUser,$_;
- if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- $response['tags'] = array();
- foreach (explode(',',$_['id']) as $id) {
- $item = Dictionnary::getById($id);
- $item = !$item ? new Dictionnary(): $item;
- $row = $item->toArray();
- $row['name'] = $item->label;
- $row['slug'] = $item->slug;
- $row['id'] = $item->id;
- $response['tags'][] = $row;
- }
- });
- break;
- /** TABLEAU DE DICTIONNARY */
- case 'dictionnary_table_search':
- Action::write(function(&$response){
- global $myUser,$_;
- 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);
- }
- });
- break;
- case 'dictionnary_table_save':
- Action::write(function(&$response){
- global $myUser,$_;
- 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();
- });
- break;
- /** CRONTAB */
- case 'cron':
- 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');
- }catch(Exception $e){
- file_put_contents(__DIR__.SLASH.'cron.log',date('d-m-Y H:i').' | '.$e->getMessage().PHP_EOL,FILE_APPEND);
- }
- break;
- /** FILES & UPLOADS */
- //Gestion de l'upload temporaire (avant soumission d'un form)
- case 'upload_temporary_file':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('file','edit');
- $response['previews'] = array();
- File::clear_temp();
- for ($i=0; $i<count($_FILES['document']['name']);$i++) {
- $tempPath = File::temp().basename($_FILES['document']['tmp_name'][$i]);
- move_uploaded_file($_FILES['document']['tmp_name'][$i], $tempPath);
- $response['previews'][] = array(
- 'path' => basename($_FILES['document']['tmp_name'][$i]),
- 'name' => $_FILES['document']['name'][$i],
- 'temporary' => true,
- 'url' => 'action.php?action=download_temporary_file&name='.$_FILES['document']['name'][$i].'&path='.basename($_FILES['document']['tmp_name'][$i]),
- 'icon' => getExtIcon(getExt($_FILES['document']['name'][$i]))
- );
- }
- });
- break;
-
- case 'download_temporary_file':
- global $myUser,$_;
- User::check_access('file','read');
- File::downloadFile(File::temp().$_['path'],$_['name']);
- break;
- /** GENERAL SETTINGS **/
- case 'general_settings_save':
- Action::write(function(&$response){
- global $myUser, $_, $conf;
- User::check_access('setting_global','configure');
- //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;
- //Save du logo clair de l'application
- if(!empty($_FILES['logo']) && $_FILES['logo']['size']!=0 ){
- $logo = File::upload('logo','core'.SLASH.'logo.{{ext}}', 1048576, array('jpg','png','jpeg'));
- Image::resize($logo['absolute'], 200, 200);
- Image::toPng($logo['absolute']);
- }
- //Save du logo sombre de l'application
- if(!empty($_FILES['logo_dark']) && $_FILES['logo_dark']['size']!=0 ){
- $logo = File::upload('logo_dark','core'.SLASH.'logo.dark.{{ext}}', 1048576, array('jpg','png','jpeg'));
- Image::resize($logo['absolute'], 200, 200);
- Image::toPng($logo['absolute']);
- }
- if(!empty($_FILES['favicon']) && $_FILES['favicon']['size']!=0 ){
- $logo = File::upload('favicon','core'.SLASH.'favicon.{{ext}}', 1048576, array('png'));
- Image::resize($logo['absolute'], 64, 64);
- Image::toPng($logo['absolute']);
- }
- //Gestion save des configuration générales
- foreach(Configuration::setting('configuration-global') as $key => $value){
- if(!is_array($value)) continue;
- $allowedSettings[] = $key;
- }
- 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', $_['maintenance-content']);
- } else {
- if(file_exists('enabled.maintenance')) rename('enabled.maintenance', 'disabled.maintenance');
- file_put_contents('disabled.maintenance', $_['maintenance-content']);
- }
- }
- });
- break;
- case 'general_reset_password_delay':
- Action::write(function(&$response){
- global $myUser, $_, $conf;
- User::check_access('setting_global','configure');
- foreach(User::getAll() as $user){
- $user->preference('passwordTime',strtotime('01/01/1990'));
- }
- });
- break;
- //Récupération logo application générale
- case 'general_logo_download':
- global $_;
- $variant = isset($_['variant']) && in_array($_['variant'], array('dark')) ? '.'.$_['variant'] : '';
- $logoPath = File::dir().'core'.SLASH.'logo'.$variant.'.png';
- $path = file_exists($logoPath) ? $logoPath : __ROOT__.SLASH.'img'.SLASH.'logo'.SLASH.'default-logo'.$variant.'.png';
- File::downloadFile($path,'logo.png','image/png');
- break;
- //Suppression logo de l'application
- case 'general_logo_delete':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('setting_global','configure');
- foreach (glob(File::dir().'core'.SLASH."logo.*") as $filename)
- unlink($filename);
- });
- break;
- //Récupération favicon application générale
- case 'general_favicon_download':
- $faviconPath = File::dir().'core'.SLASH.'favicon.png';
- $path = file_exists($faviconPath) ? $faviconPath : __ROOT__.SLASH.'img'.SLASH.'logo'.SLASH.'default-favicon.png';
- File::downloadFile($path,'favicon.png','image/png');
- break;
- //Suppression favicon de l'application
- case 'general_favicon_delete':
- Action::write(function(&$response){
- global $myUser,$_;
- User::check_access('setting_global','configure');
- foreach (glob(File::dir().'core'.SLASH."favicon.*") as $filename)
- unlink($filename);
- });
- break;
- case 'user_impersonation':
- try{
- global $myUser,$myFirm,$_;
- 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é");
- unset($_SESSION['users']);
- $user = new User();
- $user = User::load(array('login' => $_['login']));
- Plugin::callHook("user_login", array(&$user,$_['login'],null,true,true,true));
- if($user!=false){
- $user->ranks = empty($user->ranks) ? array() : $user->ranks;
- $user->firms = empty($user->firms) ? array() : $user->firms;
- $user->loadRanks();
- $user->loadPreferences();
- $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : key($user->firms);
- $myFirm = isset($user->firms[$defaultFirm]) ? $user->firms[$defaultFirm]:reset($user->firms);
- if(!isset($defaultFirm) || empty($defaultFirm)) throw new Exception("Ce compte n'est actif sur aucun établissement");
- }
- $user->loadRights();
- if($user == false || empty($user->login)) throw new Exception("Utilisateur inexistant");
- $myUser = $user;
- $_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()));
- }
- break;
- /** CUSTOM API */
- // pour obtenir un schema de toutes les api actives : http://url.com/api/schema?pretty
- case 'api':
- /* CORE API */
- //Infos api
- $api = new Api("core", "Api du coeur applicatif");
- $api->route('infos','retourne les informations sur l\'environnement','GET',function($request,&$response){
- global $myUser;
- 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['database']['type'] = BASE_SGBD;
- $response['database']['version'] = Database::version();
- $response['database']['host'] = BASE_HOST;
- $response['os']['type'] = PHP_OS;
- $response['os']['time'] = time();
- });
- //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() 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);
- //Check si un user n'existe pas déjà avec ce login
- 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) 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 = sha1(md5($form['password']));
- $user->preference('passwordTime',time());
- }
- if(isset($form['firstname'])) $user->firstname = ucfirst($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();
- Log::put("Création/Modification de l'utilisateur ".$user->toText(),'Utilisateur');
- $response['user'] = array('id'=>$user->id,'login'=>$user->login);
-
- });
- //user api
- $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);
- unset($_SESSION['users']);
- Log::put("Suppression de l'utilisateur ".$user->toText(),'Utilisateur');
- $response['code'] = 204;
- });
- $api->register();
- /* FIN CORE API */
- Api::run();
- break;
- /** CUSTOM REWRITE */
- case 'rewrite':
- 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>');
- }
- break;
- /** ACTIONS DE PLUGINS */
- default:
- Plugin::callHook('action');
- break;
- }
- ?>
|