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].''.$matches[2].''.$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.".
Si il s'agit bien de vous, Cliquez ici pour changer votre mot de passe ou copiez collez le lien suivant dans votre navigateur préféré.
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 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('
'.$e->getMessage().'
'); } break; /** ACTIONS DE PLUGINS */ default: Plugin::callHook('action'); break; } ?>