<?php

if(!ini_get('safe_mode')) @set_time_limit(0);
require_once __DIR__.DIRECTORY_SEPARATOR."common.php";

if(php_sapi_name() == 'cli') $_['action'] = $_SERVER['argv'][1];	

if(!isset($_['action'])) throw new Exception('Action inexistante');

//Execution du code en fonction de l'action
switch ($_['action']){
	
	case 'login': 
		global $myUser,$myFirm,$_,$conf;
	
		try {
			// ETAPE 1
			Log::put("CONNEXION avec le login \"".$_['login']."\" - ETAPE 1 => Entrée dans l'action",'Utilisateur');

			// ETAPE 2
			if($_['login'] == '')
				throw new Exception("Login vide");
			
			if($_['password'] == '')	
				throw new Exception("Mot de passe vide");
			

			if($conf->get('account_block')==1){
				$try = is_numeric($conf->get('account_block_try')) ?$conf->get('account_block_try') : 5;
				$delay = is_numeric($conf->get('account_block_delay')) ?$conf->get('account_block_delay') : 10;
				
				$trying = Log::staticQuery('SELECT * FROM {{table}} WHERE category=? AND label=? AND created>?',array(
					'auth_fail',
					$_['login'],
					( time() - ($delay*60) )
				),true);


				if(count($trying)>=$try) throw new Exception("Suite à un trop grand nombre de tentatives, votre compte est bloqué pour un delais 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','');
            }

			Log::put("Identification de l'utilisateur ".$myUser->toText(),'Utilisateur');
			

			$redirect = isset($_['url']) ? base64_decode($_['url']) : 'index.php';
			if(isset($_SESSION['last_request']) &&  !isset($_['url'])){
			    $redirect = $_SESSION['last_request'];
			    unset($_SESSION['last_request']);
			}
			header('location: '.$redirect);


			// ETAPE 11
			Log::put("CONNEXION avec le login \"".$_['login']."\" - ETAPE 11 => Sortie de l'action, myUser : ".$myUser->toText()." / l'utilisateur est redirigé vers \"".$redirect."\"",'Utilisateur');
		} catch(Exception $e){
			Log::put("CONNEXION erreur : \"".$_['login']." : ".$e->getMessage(),'Utilisateur');
			//LA vérification sur le code 509 permet d'éviter d'allonger le temps de ban a chaque tentative
			if($e->getCode()!=509) Log::put($_['login'],'auth_fail');
			header('location: index.php?error='.rawurlencode($e->getMessage()));
		}
	break;
	
	case 'logout':
		global $myUser;
		if(isset($myUser->login)) $myUser->preference('cookie','');
		unset($_SESSION['currentUser']);
		unset($_SESSION['firm']);
		session_destroy();
		unset($_COOKIE[COOKIE_NAME]);
		setcookie(COOKIE_NAME, null, -1, '/');
		$redirect = isset($_['url']) ? base64_decode($_['url']) : 'index.php';
		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,$_;

			if(!$myUser->can('log','read')) throw new Exception("Permissions insuffisantes",403);
			$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 ';

			//Pagination
			$response['pagination'] = Log::paginate(100,(!empty($_['page'])?$_['page']:0),$query,$data);

			foreach(Log::staticQuery($query,$data,true) as $log){
				$log->created = date('d/m/Y H:i:s',$log->created);
				if(!empty($_['keyword'])){
					$log->label = preg_replace_callback('|(.*)('.$_['keyword'].')(.*)|i', function($matches){
						return $matches[1].'<mark>'.$matches[2].'</mark>'.$matches[3];
					}, $log->label);
				}
				//evite les json encode crash lorsque la chaine contient des caractères spéciaux non utf-8
				$log->label = htmlentities($log->label);
				$response['rows'][] = $log;
			}
		});
	break;
	
	/** PLUGINS **/
	case 'search_plugin':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('plugin','read')) throw new Exception("Permissions insuffisantes",403);
			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,$_;
			if(!$myUser->can('plugin','configure')) throw new Exception("Permissions insuffisantes",403);
			
			$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,$_;
			if(!$myUser->can('plugin','configure')) throw new Exception("Permissions insuffisantes",403);
			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,$_;
			if(!$myUser->can('plugin','configure')) throw new Exception("Permissions insuffisantes",403);
			
			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,$_;
			if(!$myUser->can('firm','read')) throw new Exception("Permissions insuffisantes",403);
			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,$_;
	    	if(!$myUser->can('firm','edit')) throw new Exception("Permissions insuffisantes",403);
	    	$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{
			if(!$myUser->can('firm','edit')) throw new Exception("Permissions insuffisantes",403);
			$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,$_;
			if(!$myUser->can('firm','delete')) throw new Exception("Permissions insuffisantes",403);
			$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,$_;
			if(!$myUser->can('firm','read')) throw new Exception("Permissions insuffisantes",403);
			
			if($_['firm'] == 0)
				foreach(Firm::loadAll() as $firm)
					$firms[] = $firm->id;
			else
				$firms[] = $_['firm'];	

			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 = User::byLogin($userFirmRank['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,$_;
			if(!$myUser->can('firm','edit')) throw new Exception("Permissions insuffisantes",403);
			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,$_;
			if(!$myUser->can('firm','edit')) throw new Exception("Permissions insuffisantes",403);

			$userFirmRank = UserFirmRank::getById($_['id']);
			$response = $userFirmRank;
		});
	break;
	
	case 'delete_userfirmrank':
		Action::write(function(&$response){
			global $myUser,$_,$conf;
			if(!$myUser->can('firm','delete')) throw new Exception("Permissions insuffisantes",403);
			$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,$_;
			if(!$myUser->can('user','read')) throw new Exception("Permissions insuffisantes",403);
			foreach(User::getAll() as $user){
				$user->avatar = $user->getAvatar();
				$response['rows'][] = $user;
			}
		});
	break;

	case 'user_autocomplete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->connected()) throw new Exception("Permissions insuffisantes",403);
			$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())))
						$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("Permissions insuffisantes",403);
			$response['users'] = array();

			foreach (explode(',',$_['login']) as $login) {
				if(is_numeric($login)){
					//rank
					$item = Rank::getById($login);
					$item = !$item ? new Rank(): $item;
					$row = $item->toArray();
					$row['fullname'] = $item->label;
					$row['type'] = 'rank';
					$row['uid'] = $item->id;
				}else{
					//user
					$item = User::byLogin($login);
					$item = !$item ? new User(): $item;
					$row = $item->toArray();
					$row['fullname'] = $item->fullName();
					$row['type'] = 'user';
					$row['uid'] =  $item->login;
					unset($row['password']);
					unset($row['token']);
				}
				$response['users'][] = $row;
			}
		});
	break;

	case 'account_lost_password':
		Action::write(function(&$response){
			global $myUser,$myFirm,$_,$conf;
			if(!isset($_['mail']) || empty($_['mail']) || !check_mail($_['mail'])) throw new Exception("Adresse e-mail non spécifiée ou incorrecte");
			
			foreach(User::getAll() as $user){
				if(strtolower($user->mail) == strtolower($_['mail'])){
					
					$token = sha1(time().mt_rand(0,1000));
					$linkToken = base64_encode($user->login.'::'.$token);
					
					UserPreference::delete(array('user'=>$user->login,'key'=>'lost_password'));
					$saved = new UserPreference();
					$saved->user = $user->login;
					$saved->key = 'lost_password';
					$saved->value = $token;
					$saved->save();

					$mail = new Mail();
					$mail->title="Mot de passe perdu";
					$link = ROOT_URL.'/account.lost.php?token='.$linkToken;
					$mail->message = "
					Vous recevez cet e-mail parce que quelqu'un a fait une demande de changement de mot de passe pour votre compte sur ".ROOT_URL.".
					<br/>Si il s'agit bien de vous, <a href='".$link."'>Cliquez ici pour changer votre mot de passe</a> ou copiez collez le lien suivant dans votre navigateur préféré.
					<br/>Si vous n'êtes pas à l'origine de ce mail, aucune action n'est requise.";
					
					$mail->recipients['to'][] = $user->mail;

					$mail->send();
					return;
				}
			}
			throw new Exception("Aucun compte ne correspond à l'e-mail spécifié dans notre base, veuillez contacter un administrateur pour modifier votre mot de passe.");
			
		});
	break;

	case 'account_save':

		Action::write(function(&$response){
			global $myUser,$myFirm,$_;



			$userForm = new User();
			$userForm->fromArray($_);
			
			//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'));


			$hashedPassword = sha1(md5('$a1u7'.$_['password'].'$y$1'));
			if(in_array($hashedPassword, $chain)) 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::checkPasswordFormat($_['password']);
					if(count($passwordErrors)!=0) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : ".implode(',',$passwordErrors));

					if($_['password']==$myUser->login || $_['password']==$myUser->mail) 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->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}}',1048576,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();
		 
			$_SESSION['currentUser'] = serialize($myUser);
		});
	
	break;

	case 'account_avatar_download':
		global $myUser,$_;
		try {
			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,$_;
			if(!$myUser->can('user','edit')) throw new Exception("Permissions insuffisantes",403);
			if($_['password']!=$_['password2']) throw new Exception("Mot de passe et confimration non similaires");
			
			$user = User::byLogin($_['login']);
			$user = $user ? $user : new User();

			if($user->id == 0){
				if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
				if(!isset($_['password']) || empty($_['password'])) throw new Exception("Mot de passe obligatoire");
				if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Le champ "Mail"est obligatoire');
			}

			if(!empty(trim($_['password']))){


				$passwordErrors = User::checkPasswordFormat(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->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();
			$user->password = '';
			Log::put("Création/Modification de l'utilisateur ".$user->toText(),'Utilisateur');
		});
	break;
	
	case 'edit_user':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('user','edit')) throw new Exception("Permissions insuffisantes",403);
			$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,$_;
			if(!$myUser->can('user','delete')) throw new Exception("Permissions insuffisantes",403);
			$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,$_;
			if(!$myUser->can('rank','edit')) throw new Exception("Permissions insuffisantes",403);
			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
				);
			}
		});
	break;	
	
	case 'toggle_right':
	Action::write(function(&$response){
		global $myUser,$_,$myFirm;
		if(!$myUser->can('rank','edit')) throw new Exception("Permissions insuffisantes",403);
		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,$_;
			if(!$myUser->can('rank','read')) throw new Exception("Permissions insuffisantes",403);
			foreach(Rank::loadAll() as $rank){
				$row = $rank->toArray(true);
				$response['rows'][] = $row;
			}
		});
	break;
	
	case 'save_rank':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('rank','edit')) throw new Exception("Permissions insuffisantes",403);
			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,$_;
			if(!$myUser->can('rank','edit')) throw new Exception("Permissions insuffisantes",403);
			$response = Rank::getById($_['id']);
		});
	break;

	case 'delete_rank':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('rank','delete')) throw new Exception("Permissions insuffisantes",403);
			$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,$_;
			if(!$myUser->can('dictionnary','read')) throw new Exception("Permissions insuffisantes",403);
			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,$_;
			if(!$myUser->can('dictionnary','edit')) throw new Exception("Permissions insuffisantes",403);
			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,$_;
			if(!$myUser->can('dictionnary','edit')) throw new Exception("Permissions insuffisantes",403);
			$dictionnary = Dictionnary::getById($_['id']);
			$response = $dictionnary->toArray(true);
		});
	break;

	case 'delete_dictionnary':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->can('dictionnary','delete')) throw new Exception("Permissions insuffisantes",403);
			
			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
				);
			}
		},array());
	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;
		},array());
	break;


	/* Composant tag list */ 
	case 'tag_list_autocomplete':
		Action::write(function(&$response){
			global $myUser,$_;
			if(!$myUser->connected()) throw new Exception("Permissions insuffisantes",403);
			$response['rows'] = array();
			if($_['keyword'] == '') return;

			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("Permissions insuffisantes",403);
			$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,$_;
			if(!$myUser->can('file','edit')) throw new Exception("Permissions insuffisantes",403);
			$response['previews'] = array();
			File::clear_temp();
			for ($i=0; $i<count($_FILES['document']['name']);$i++) {

				$tempPath = File::temp().basename($_FILES['document']['tmp_name'][$i]);

				move_uploaded_file($_FILES['document']['tmp_name'][$i], $tempPath);
				$response['previews'][] = array(
					'path' => basename($_FILES['document']['tmp_name'][$i]),
					'name' => $_FILES['document']['name'][$i],
					'temporary' => true,
					'url' => 'action.php?action=download_temporary_file&name='.$_FILES['document']['name'][$i].'&path='.basename($_FILES['document']['tmp_name'][$i]),
					'icon' => getExtIcon(getExt($_FILES['document']['name'][$i]))
				);
			}
		});
	break;
	
	case 'download_temporary_file':
		global $myUser,$_;
		if(!$myUser->can('file','read')) throw new Exception("Permissions insuffisantes",403);
		File::downloadFile(File::temp().$_['path'],$_['name']);
	break;

	/** GENERAL SETTINGS **/
	case 'general_settings_save':
		Action::write(function(&$response){
			global $myUser, $_, $conf;
			if(!$myUser->can('setting_global','configure')) throw new Exception("Permissions insuffisantes",403);

			//Affichage ou non du nom de l'application
			$conf->put('show_application_name',$_['show_application_name']);

			//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']);
			if(isset($_['password-delay'])) $conf->put('password_delay',$_['password-delay']);

			//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;
			if(!$myUser->can('setting_global','configure')) throw new Exception("Permissions insuffisantes",403);
			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,$_;
	        if(!$myUser->can('setting_global', 'configure')) throw new Exception("Permissions insuffisantes",403);

	        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,$_;
	        if(!$myUser->can('setting_global', 'configure')) throw new Exception("Permissions insuffisantes",403);

	        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']));
	       
	        if($user!=false){
	            $user->ranks = array();
	            $user->firms = array();
	            $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");
	        }
	       
	        Plugin::callHook("user_login", array(&$user,$_['login'],null,true,true,true));
	        $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 */
	case 'api':
		global $myUser,$_;
        $response = array();

        try{
			$command = explode('/',$_['command']);
			if(count($command)<1) throw new Exception("Unspecified API");

			 if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
                $user = User::check($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']);
                if(!$user) throw new Exception('Le compte spécifié est inexistant');
                $myUser = $user;
            }
			$module = array_shift($command);
			
			Plugin::callHook('api',array($module,$command,&$response));
		}catch(Exception $e){
         $response['error'] = $e->getMessage();
        }
        header('Content-Type: application/json');
        echo json_encode($response);
	break;

	/** CUSTOM REWRITE */
	case 'rewrite':
		$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;
		} 
	break;

	/** ACTIONS DE PLUGINS */
	default:
		Plugin::callHook('action');
	break;
}


?>