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']){ $cookie = sha1(bin2hex(random_bytes(20))); $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($_['login'],'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($_['slug'])) return $response; function filter_recursive_save($filters){ foreach($filters as $i=>$advanced){ if(isset($filters[$i]['operator'])) $filters[$i]['operator'] = html_entity_decode($filters[$i]['operator']); if(isset($filters[$i]['group'])) $filters[$i]['group'] = filter_recursive_save($filters[$i]['group']); } return $filters; } if(isset($_['filters']['advanced'])) $_['filters']['advanced'] = filter_recursive_save($_['filters']['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,$_; if(empty($_['slug'])) return $response; $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('label','category','creator','created','ip'),$query,$data); //Tri des colonnes if(isset($_['sort'])) sort_secure_query($_['sort'],array('label','ip','created','category','creator'),$query,$data); else $query .= ' ORDER BY created DESC, id DESC '; //Pagination $response['pagination'] = Log::paginate(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); } $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()); foreach($plugin->require as $id=>$version) $plugin->required[] = array('id'=>$id, 'version'=>$version); $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); unset($_SESSION['users']); 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(); $row['logo'] = $firm->logo(); $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); } if($firm->id == $myFirm->id){ unset($_SESSION['firm']); $_SESSION['firm'] = serialize($firm); $myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']) : new Firm(); } 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'] = ''; $user->name = $user->lastname(); $user->firstname = $user->firstname(); $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; $user = User::byLogin(stripslashes($_['user'])); $rank = Rank::getById($_['rank']); if($user->origin == 'active_directory' && (!array_key_exists($firm->id, $user->firms) || !$firm->has_plugin('fr.sys1.activedirectory'))) continue; $userFirmRank = UserFirmRank::provide(); $exist = is_null($userFirmRank->id) || $_['firm'] == 0 ? UserFirmRank::rowCount(array('user'=>$user->login,'firm'=>$firm->id,'rank'=>$_['rank'])) : UserFirmRank::rowCount(array('id:!='=>$userFirmRank->id,'user'=>$user->login,'firm'=>$firm->id,'rank'=>$_['rank'])); if($exist > 0){ $response['warning'][] = "Le rang ".$rank->label." est déja défini pour ".$user->fullName()." sur l'établissement ".$firm->label; continue; } $userFirmRank->fromArray($_); $userFirmRank->firm = $firm->id; $userFirmRank->user = $user->login; $userFirmRank->save(); $response['success'][] = "Rang ".$rank->label." ajouté pour ".$user->fullName()." sur l'établissement ".$firm->label; } }); 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(false) as $user){ if($user->state == User::INACTIVE || (!$myUser->superadmin && $user->superadmin)) continue; $user->login = htmlspecialchars_decode($user->login); $user->name = $user->lastname(); $user->firstname = $user->firstname(); $user->avatar = $user->getAvatar(); $user->formatedLogin = urlencode($user->login); $response['rows'][] = $user; } }); 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(false) as $user){ if(preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->fullName())) || preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->login))){ $response['rows'][] = array( 'fullname'=>html_decode_utf8($user->fullName()), 'name'=>$user->fullName(), 'uid'=>html_decode_utf8(addslashes($user->login)), 'id'=>$user->login, 'mail'=>$user->mail, 'type'=>'user', 'avatar'=>$user->getAvatar(), 'function'=>$user->function ); } } } if(in_array('rank', $_['data']['types'])){ foreach(Rank::staticQuery('SELECT * FROM {{table}} WHERE label LIKE ?',array('%'.$_['keyword'].'%'),true) as $rank){ $response['rows'][] = array( 'fullname'=>html_decode_utf8($rank->label), 'name'=>$rank->label, 'uid'=>$rank->id, 'id'=>$rank->id, 'type'=>'rank', 'description'=>$rank->description, ); } } }); 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'] = html_decode_utf8($item->fullName()); $row['name'] = $item->fullName(); $row['uid'] = html_decode_utf8(addslashes($item->login)); $row['id'] = $item->login; $row['type'] = 'user'; unset($row['password']); unset($row['token']); $response['users'][$item->login] = $row; } //rank foreach(Rank::loadAll(array('id:IN'=>implode(',',$ranks))) as $item){ $row = $item->toArray(); $row['fullname'] = $item->label; $row['name'] = $item->label; $row['uid'] = $item->id; $row['id'] = $item->id; $row['type'] = 'rank'; $response['users'][$item->id] = $row; } }); 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(false) as $user){ if(strtolower($user->mail) != strtolower($_['mail'])) continue; $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 = "Récupération de mot de passe oublié"; $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.".
S'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é (".$link.").
Si vous n'êtes pas à l'origine de ce mail, aucune action n'est requise."; $mail->recipients['to'][] = $user->mail; $mail->send(); Log::put("Demande de récupération de mot de passe : ".$user->toText(),'Utilisateur'); return; } throw new Exception("Aucun compte ne correspond à 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,$_,$conf; User::check_access('account','edit'); if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire"); if(preg_match('|[,'.preg_quote(htmlspecialchars_decode($conf->get('login_forbidden_char'))).']|i', htmlspecialchars_decode($_['login']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans l'identifiant"); if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Adresse mail obligatoire'); $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(preg_match('|[,'.preg_quote(htmlspecialchars_decode($conf->get('password_forbidden_char'))).']|i', htmlspecialchars_decode($_['password']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans le mot de passe"); if($_['password'] != $_['password2']) throw new Exception("Mot de passe et confirmation non similaires"); //Recuperation des hash des precedents passwords $chain = explode('-',$myUser->preference('account_chain')); if(!empty(trim($_['password']))) { $hashedPassword = 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->preference('passwordTime',time()); } $myUser->firstname = $userForm->firstname; $myUser->name = $userForm->name; $myUser->mail = $userForm->mail; $myUser->function = $userForm->function; $myUser->phone = $userForm->phone; $myUser->mobile = $userForm->mobile; $myUser->manager = is_object($myUser->manager) ? $myUser->manager->login : $myUser->manager; $myUser->save(); if($myUser->superadmin == 1){ foreach(Firm::loadAll() as $firm) $firms[$firm->id] = $firm; $myUser->setFirms($firms); } } //Save de l'avatar if(!empty($_FILES['avatar']) && $_FILES['avatar']['size']!=0 ){ $login = User::format_avatar_name($myUser->login); foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.$login.".*") as $filename) unlink($filename); $avatar = File::upload('avatar',AVATAR_PATH.$login.'.{{ext}}',104857060,array('jpg','png','jpeg','gif')); Image::resize($avatar['absolute'],150,150); } //save des comptes types plugin Plugin::callHook("user_save",array(&$myUser,$userForm,&$response)); $myUser->loadRights(); 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::format_avatar_name($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::format_avatar_name($user->login).".*") as $filename) unlink($filename); if(!file_exists(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails')) return; foreach(glob(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails'.SLASH.User::format_avatar_name($user->login).".*") as $filename) unlink($filename); }); break; case 'save_user': Action::write(function(&$response){ global $myUser,$_,$conf; User::check_access('user','edit'); if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire"); if(preg_match('|[,'.preg_quote(htmlspecialchars_decode($conf->get('login_forbidden_char'))).']|i', htmlspecialchars_decode($_['login']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans l'identifiant"); //Calcule de la taille max du login en focntion du chemin absolu pour avatar + extension (5) $osElementMaxLength = OS_path_max_length() - strlen(__ROOT__.FILE_PATH.AVATAR_PATH) - strlen(User::get_avatar_extension_brace()); if(strlen($_['login']) > $osElementMaxLength) throw new Exception("Identifiant trop long : maximum ".$osElementMaxLength." caractères"); $osElementMaxLength = OS_element_max_length(); if(strlen($_['login']) > $osElementMaxLength) throw new Exception("Identifiant trop long : maximum ".$osElementMaxLength." caractères"); if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Le champ "Mail" est obligatoire'); if(!check_mail($_['mail'])) throw new Exception('Le format du champ "Mail" est invalide'); if(preg_match('|[,'.preg_quote(htmlspecialchars_decode($conf->get('password_forbidden_char'))).']|i', htmlspecialchars_decode($_['password']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans le mot de passe"); if($_['password'] != $_['password2']) throw new Exception("Mot de passe et confirmation non similaires"); $user = User::byLogin($_['login']); $user = $user && empty($user->origin) ? $user : new User(); //Check si un user n'existe pas déjà avec ce login (on récupère tous les users car user peut être supprimé logiquement / désactivé uniquement) if(empty($user->id) && User::load(array('login'=>$_['login']))) throw new Exception("Un utilisateur existe déjà avec cet identifiant"); if(!$user->login) $user->login = $_['login']; foreach(User::getAll(false) as $existingUser) if($existingUser->mail == trim($_['mail']) && $existingUser->login != $user->login) throw new Exception("Un utilisateur existe déjà avec cette adresse e-mail"); if($user->id == 0 && (!isset($_['password']) || empty($_['password']))) throw new Exception("Mot de passe obligatoire"); if(!empty(trim($_['password']))){ $passwordErrors = User::check_password_format(html_entity_decode($_['password'])); if(count($passwordErrors)!=0) 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 = trim($_['mail']); $user->state = User::ACTIVE; if(isset($_['manager'])) $user->manager = $_['manager']; $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']); $user->login = htmlspecialchars_decode($user->login); $user->name = $user->lastname(); $user->firstname = $user->firstname(); if(!$user) throw new Exception("Utilisateur non identifié"); $user->password = ''; $response = $user; }); 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"); if(!$user = User::getById($user->id)) throw new Exception("Impossible de supprimer un compte en dehors de de la base de données"); $user->state = User::INACTIVE; $user->save(); foreach(UserFirmRank::loadAll(array('user'=>$user->login)) as $ufrLink) UserFirmRank::deleteById($ufrLink->id); 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("Établissement 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'); $rankQry = 'SELECT *,(SELECT GROUP_CONCAT(CONCAT(f.label,":",`section`,":",`read`,":",`edit`,":",`delete`,":",`configure`)) FROM `'.Right::tableName().'` r LEFT JOIN firm f ON f.id = r.firm WHERE (r.read=1 OR r.edit=1 OR r.delete=1 OR r.configure=1) AND r.rank={{table}}.id) as rights FROM {{table}}'; $ranks = Rank::staticQuery($rankQry,array(),true); foreach($ranks as $rank){ $row = $rank->toArray(true); $row['rights'] = array(); foreach (explode(',', $rank->foreign('rights')) as $right) { $infos = explode(':', $right); $row['rights'][] = array( 'configure' => !empty(array_pop($infos)), 'delete' => !empty(array_pop($infos)), 'edit' => !empty(array_pop($infos)), 'read' => !empty(array_pop($infos)), 'section' => array_pop($infos), 'firm' => array_pop($infos) ); usort($row['rights'], function($a, $b){ return strcmp($a['firm'], $b['firm']); }); } $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(!empty($_['slug'])){ $parameters = array('slug'=>$_['slug'], 'state'=>Dictionnary::ACTIVE); if(isset($item->id) && !empty($item->id)) $parameters['id:!='] = $item->id; if(Dictionnary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé"); $item->slug = $_['slug']; } if(empty($item->slug)){ $parentSlug = $_['parent'] == 0 ? '' : Dictionnary::getById($_['parent'])->slug; $slug = empty($parentSlug) ? $_['label'] : $parentSlug.'-'.$_['label']; $item->slug = Dictionnary::generateSlug($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; case 'dictionnary_slug_proposal': Action::write(function(&$response){ global $myUser,$_; if(!isset($_['label']) || empty($_['label'])) return; //Check si l'item n'a pas déjà un slug if(isset($_['id']) && !empty($_['id']) && is_numeric($_['id'])){ $item = Dictionnary::provide(); if(!empty($item->slug)) return; } $parentSlug = empty($_['parent']) ? '' : Dictionnary::getById($_['parent'])->slug; $slug = empty($parentSlug) ? $_['label'] : $parentSlug.'-'.$_['label']; $response['slug'] = Dictionnary::generateSlug($slug, 'slug'); }); 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 ? AND state = "'.Dictionnary::ACTIVE.'"',array($_['data']['parent'],'%'.$_['keyword'].'%'),true) as $item){ $response['rows'][] = array( 'name'=>$item->label, 'id'=>$item->id, 'slug'=>$item->slug ); } }); break; case 'tag_list_autocreate': Action::write(function(&$response){ global $myUser,$_; if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401); $response = array(); $parent = Dictionnary::bySlug($_['slug']); $newtag = new Dictionnary(); $newtag->state = Dictionnary::ACTIVE; $newtag->parent= $parent->id; $newtag->label= $_['label']; $newtag->slug= $parent->slug.'-'.slugify($_['label']); $newtag->save(); $response = array( 'name'=>$newtag->label, 'id'=>$newtag->id, 'slug'=>$newtag->slug ); }); 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; /* COMPOSANT LOCATION */ case 'location_search': Action::write(function(&$response){ global $myUser,$_,$conf; if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401); $appUrl = $conf->get('maps_api_suggest_url'); $appId = $conf->get('maps_api_id'); $appKey = $conf->get('maps_api_key'); if(empty($appUrl) || empty($appId) || empty($appKey)) throw new Exception("Impossible d'initialiser le composant de localisation"); if(!isset($_['keyword']) || empty($_['keyword'])) return; $default = array( 'query' => $_['keyword'], 'app_id' => $appId, 'app_code' => $appKey ); $params = array_merge($default, $_['data']); $curlOpt = array( CURLOPT_URL => sprintf("%s?%s", $appUrl, http_build_query($params)), CURLOPT_HTTPHEADER => array( 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0', 'Content-Type: application/json', ), CURLOPT_RETURNTRANSFER => 1, CURLOPT_HTTPAUTH => CURLAUTH_ANY, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, ); $ch = curl_init(); curl_setopt_array($ch, $curlOpt); $result = curl_exec($ch); if($result === false) throw new Exception("Erreur de récupération cURL : ".curl_error($curl)); $result = json_decode($result); $infos = curl_getinfo($ch); curl_close($ch); $response['rows'] = $result->suggestions; }); break; case 'location_detail_search': Action::write(function(&$response){ global $myUser,$_,$conf; if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401); $appUrl = $conf->get('maps_api_geocode_url'); $appId = $conf->get('maps_api_id'); $appKey = $conf->get('maps_api_key'); if(empty($appUrl) || empty($appId) || empty($appKey)) throw new Exception("Impossible de récupérer les détails de la localisation"); if(!isset($_['locationId']) || empty($_['locationId'])) return; $params = array( 'locationid' => $_['locationId'], 'app_id' => $appId, 'app_code' => $appKey ); $curlOpt = array( CURLOPT_URL => sprintf("%s?%s", $appUrl, http_build_query($params)), CURLOPT_HTTPHEADER => array( 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0', 'Content-Type: application/json', ), CURLOPT_RETURNTRANSFER => 1, CURLOPT_HTTPAUTH => CURLAUTH_ANY, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, ); $ch = curl_init(); curl_setopt_array($ch, $curlOpt); $response = curl_exec($ch); if($response === false) throw new Exception("Erreur de récupération cURL : ".curl_error($curl)); $response = json_decode($response); $infos = curl_getinfo($ch); curl_close($ch); }); 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(); $fileIndex = isset($_FILES[$_['index']]) ? $_FILES[$_['index']] : $_FILES['document']; File::clear_temp(); for($i=0; $i basename($fileIndex['tmp_name'][$i]), 'name' => $fileIndex['name'][$i], 'temporary' => true, 'ext' => $ext, 'url' => 'action.php?action=download_temporary_file&name='.$fileIndex['name'][$i].'&path='.basename($fileIndex['tmp_name'][$i]), 'icon' => getExtIcon($ext) ); } }); 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 authentification 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(false) 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; //Permet de se connecter "en tant que" 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'],'state'=>User::ACTIVE)); 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(); $firms = $user->firms; $firmValues = array_values($firms); $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : (!is_null(key($firms)) ? key($firms) : array_shift($firmValues)); $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"); } if($user == false || empty($user->login)) throw new Exception("Utilisateur inexistant"); $user->loadRights(); $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; /** PERMISSION **/ //Récuperation d'une liste de permission case 'core_permission_search': Action::write(function(&$response){ global $myUser,$_; User::check_access('core','read'); $permissions = Permission::loadAll(array('entity'=>$_['entity'],'uid'=>$_['uid'])); foreach($permissions as $permission){ $row = $permission->toArray(); if( !$permission->read ) unset($row['read']); if( !$permission->edit ) unset($row['edit']); if( !$permission->delete ) unset($row['delete']); if( !$permission->configure ) unset($row['configure']); if( !$permission->recursive ) unset($row['recursive']); if($permission->targetEntity == 'rank'){ $row['target'] = ' '.Rank::getById($permission->targetUid)->label; }else{ $user = User::byLogin($permission->targetUid); $row['target'] = ' '.$user->fullName(); } $response['rows'][] = $row; } }); break; //Récuperation ou edition d'élément permission case 'core_permission_edit': Action::write(function(&$response){ global $myUser,$_; User::check_access('core','edit'); $permissions = Permission::loadAll(array('uid'=>$_['uid'],'entity'=>$_['entity'])); $response['rows']= $permissions; }); 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(); }); //right api $api->route('rights','retourne la liste des droits du logiciel','GET',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['rights'] = array(); if(isset($request['parameters']['sort'])) throw new Exception("Sort is not implemented for firms",501); if(isset($request['parameters']['filter'])) throw new Exception("Filter is not implemented for firms",501); $limit = isset($request['parameters']['limit']) ? array($request['parameters']['limit']) : array(); foreach (Right::loadAll(array(),array(),$limit) as $right) { $row = $right->toArray(); $response['rights'][] = $row; } }); $api->route('rights/[rightid]','ajoute/modifie un droit du logiciel','PUT',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['right'] = array(); //Création $_ = $request['parameters']; $form = json_decode($request['body'],true); if(!$form) throw new Exception("Invalid JSON body",400); User::check_access('right','edit'); if(!empty($request['pathes'])){ $right = Right::getById($request['pathes'][0]); if(empty($right->id)) throw new Exception("Right not found", 404); $response['code'] = 200; //Modifié }else{ $right = new right(); if(!isset($form['rank']) || empty($form['rank'])) throw new Exception("L'id du rang est obligatoire",400); if(!isset($form['section']) || empty($form['section'])) throw new Exception("Le nom de la section est obligatoire",400); if(!isset($form['firm']) || empty($form['firm'])) throw new Exception("L'id de l'établissement est obligatoire",400); $response['code'] = 201; //Créé } //Check si le rang existe $rank = Rank::getById($form['rank']); if(empty($rank->id)) throw new Exception("Rank not found", 400); //Check si la firm existe $firm = Firm::getById($form['firm']); if(empty($firm->id)) throw new Exception("Firm not found", 400); //Check si la section existe $sections = array(); Plugin::callHook('section',array(&$sections)); $find = false; foreach($sections as $section=>$description){ if ($section==$form['section']){ $find = true; break; } } if (!$find) throw new Exception("Section not found", 400); if(isset($form['rank'])) $right->rank = $form['rank']; if(isset($form['section'])) $right->section = $form['section']; if(isset($form['firm'])) $right->firm = $form['firm']; if(isset($form['read'])) $right->read = $form['read']; if(isset($form['edit'])) $right->edit = $form['edit']; if(isset($form['delete'])) $right->delete = $form['delete']; if(isset($form['configure'])) $right->configure = $form['configure']; $right->save(); Log::put("Création/Modification de droit ".$right->toText(),'Droit'); $response['right'] = array('id'=>$right->id,'section'=>$right->section); }); $api->route('rights/rightid','Supprime un rang du logiciel','DELETE',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); if(empty($request['pathes'])) throw new Exception("You must specify right id", 400); User::check_access('right','delete'); $right = Right::getById($request['pathes'][0]); if(!$right) throw new Exception("Right not found",404); $right->deleteById($right->id); Log::put("Suppression du rang ".$right->toText(),'Rang'); $response['code'] = 204; }); //rank api $api->route('ranks','retourne la liste des rangs du logiciel','GET',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['ranks'] = array(); if(isset($request['parameters']['sort'])) throw new Exception("Sort is not implemented for firms",501); if(isset($request['parameters']['filter'])) throw new Exception("Filter is not implemented for firms",501); $limit = isset($request['parameters']['limit']) ? array($request['parameters']['limit']) : array(); foreach (Rank::loadAll(array(),array(),$limit) as $rank) { $row = $rank->toArray(); $response['ranks'][] = $row; } }); $api->route('ranks/[rankid]','ajoute/modifie un rang du logiciel','PUT',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['rank'] = array(); //Création $_ = $request['parameters']; $form = json_decode($request['body'],true); if(!$form) throw new Exception("Invalid JSON body",400); User::check_access('rank','edit'); if(!empty($request['pathes'])){ $rank = Rank::getById($request['pathes'][0]); if(empty($rank->id)) throw new Exception("Rank not found", 404); $response['code'] = 200; //Modifié }else{ $rank = new rank(); if(!isset($form['label']) || empty($form['label'])) throw new Exception("Le libellé est obligatoire",400); //Check si un rang n'existe pas déjà avec ce label if(Rank::load(array('label'=>$form['label']))) throw new Exception("Un rang existe déjà avec ce nom",400); $rank->label = $form['label']; $response['code'] = 201; //Créé } if(isset($form['label'])) $rank->label = $form['label']; if(isset($form['description'])) $rank->description = $form['description']; $rank->save(); Log::put("Création/Modification de rang ".$rank->toText(),'Rang'); $response['rank'] = array('id'=>$rank->id,'label'=>$rank->label); }); $api->route('ranks/rankid','Supprime un rang du logiciel','DELETE',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); if(empty($request['pathes'])) throw new Exception("You must specify rank id", 400); User::check_access('rank','delete'); $rank = Rank::getById($request['pathes'][0]); if(!$rank) throw new Exception("Rank not found",404); foreach(UserFirmRank::loadAll(array('rank'=>$rank->id)) as $ufrLink) UserFirmRank::deleteById($ufrLink->id); $rank->deleteById($rank->id); Log::put("Suppression du rang ".$rank->toText(),'Rang'); $response['code'] = 204; }); //firm api $api->route('firms','retourne la liste des établissements du logiciel','GET',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['firms'] = array(); if(isset($request['parameters']['sort'])) throw new Exception("Sort is not implemented for firms",501); if(isset($request['parameters']['filter'])) throw new Exception("Filter is not implemented for firms",501); $limit = isset($request['parameters']['limit']) ? array($request['parameters']['limit']) : array(); foreach (Firm::loadAll(array(),array(),$limit) as $i=>$firm) { $row = $firm->toArray(); $response['firms'][] = $row; } }); $api->route('firms/[firmid]','ajoute/modifie un établissement du logiciel','PUT',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['firm'] = array(); //Création $_ = $request['parameters']; $form = json_decode($request['body'],true); if(!$form) throw new Exception("Invalid JSON body",400); User::check_access('firm','edit'); if(!empty($request['pathes'])){ $firm = Firm::getById($request['pathes'][0]); if(empty($firm->id)) throw new Exception("Firm not found", 404); $response['code'] = 200; //Modifié }else{ $firm = new Firm(); if(!isset($form['label']) || empty($form['label'])) throw new Exception("Le libellé est obligatoire",400); if(!isset($form['mail']) || empty($form['mail'])) throw new Exception('Le champ "Mail"est obligatoire',400); //Check si une firm n'existe pas déjà avec ce label if(Firm::load(array('label'=>$form['label']))) throw new Exception("Un établissement existe déjà avec ce nom",400); $firm->label = $form['label']; $response['code'] = 201; //Créé } if(isset($form['label'])) $firm->label = $form['label']; if(isset($form['description'])) $firm->description = $form['description']; if(isset($form['mail'])) $firm->mail = $form['mail']; if(isset($form['phone'])) $firm->phone = $form['phone']; if(isset($form['fax'])) $firm->fax = $form['fax']; if(isset($form['street'])) $firm->street = $form['street']; if(isset($form['street2'])) $firm->street2 = $form['street2']; if(isset($form['city'])) $firm->city = $form['city']; if(isset($form['zipcode'])) $firm->zipcode = $form['zipcode']; if(isset($form['siret'])) $firm->siret = $form['siret']; if(isset($form['iban'])) $firm->iban = $form['iban']; $firm->save(); Log::put("Création/Modification de l'établissement ".$firm->toText(),'Etablissement'); $response['firm'] = array('id'=>$firm->id,'label'=>$firm->label); }); $api->route('firms/firmid','Supprime un établissement du logiciel','DELETE',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); if(empty($request['pathes'])) throw new Exception("You must specify firm id", 400); User::check_access('firm','delete'); $firm = Firm::getById($request['pathes'][0]); if(!$firm) throw new Exception("Firm not found",404); foreach(UserFirmRank::loadAll(array('firm'=>$firm->id)) as $ufrLink) UserFirmRank::deleteById($ufrLink->id); $firm->deleteById($firm->id); Log::put("Suppression de l'établissement ".$firm->toText(),'Etablissement'); $response['code'] = 204; }); //user api $api->route('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(false) as $i=>$user) { if(isset($request['parameters']['limit']) && $request['parameters']['limit']==$i) break; $row = $user->toArray(); unset($row['password']); unset($row['manager']); $row['origin'] = !isset($row['id']) ? 'plugin': 'database'; $response['users'][] = $row; } }); $api->route('users/[userid]','ajoute/modifie un utilisateur du logiciel','PUT',function($request,&$response){ global $myUser; if(!$myUser->connected()) throw new Exception("Credentials are missing",401); $response['user'] = array(); //Création $_ = $request['parameters']; $form = json_decode($request['body'],true); if(!$form) throw new Exception("Invalid JSON body",400); User::check_access('user','edit'); if(!empty($request['pathes'])){ $user = User::byLogin($request['pathes'][0]); if(empty($user->login)) throw new Exception("User not found", 404); $response['code'] = 200; //Modifié }else{ $user = new User(); if(!isset($form['login']) || empty($form['login'])) throw new Exception("Identifiant obligatoire",400); if(!isset($form['password']) || empty($form['password'])) throw new Exception("Mot de passe obligatoire",400); if(!isset($form['mail']) || empty($form['mail'])) throw new Exception('Le champ "Mail"est obligatoire',400); foreach(User::getAll(false) as $existingUser) if($existingUser->mail == trim($_['mail'])) throw new Exception("Un utilisateur existe déjà avec cette adresse e-mail"); //Check si un user n'existe pas déjà avec ce login (on récupère tous les users car user peut être supprimé logiquement / désactivé uniquement) if(User::load(array('login'=>$form['login']))) throw new Exception("Un utilisateur existe déjà avec cet identifiant",400); $user->login = $form['login']; $response['code'] = 201; //Créé } if(!empty($form['password']) && 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(); User::getAll(true,true); 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; } ?>