<?php

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

if(php_sapi_name() == 'cli'){
	 array_shift($_SERVER['argv']);
	$_['action'] = array_shift($_SERVER['argv']);
	foreach ($_SERVER['argv'] as $keyvalue) {
		$infos = explode('=',$keyvalue);
		$key = $infos[0];
		$value = count($infos)<2 ? '' : $infos[1];
		$_[$key] = $value;
	}
}

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


/*
	Authentification
*/
//Connexion
Action::register('core_login',function(&$response){
	global $myUser,$myFirm,$_,$conf;
	try {
		if(!isset($_['login'])) $_['login'] = 'anonymous';
		if(!isset($_['password'])) $_['password'] = '';

		Log::put("Tentative de connexion avec le login \"".$_['login']."\"",'Utilisateur');

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

			if(count($trying)>=$try) throw new Exception("Suite à un trop grand nombre de tentatives, votre compte est bloqué pour un délai de ".$delay." minutes",509);
		}

		$myUser = User::check($_['login'],html_entity_decode($_['password']));
		if(!$myUser) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");

		if(file_exists(File::dir().SLASH.'enabled.maintenance') && $myUser->superadmin != 1) throw new Exception('Seul un compte Super Admin peut se connecter en mode maintenance');

		if(!$myUser->connected()) throw new Exception('Identifiant ou mot de passe incorrect');

		//Suppression du token de reset de password s'il se reconnecte entre temps
		UserPreference::delete(array('user'=>$myUser->login,'key'=>'lost_password'));

		$myUser->loadPreferences();
		if(is_numeric($myUser->preference('default_firm')) && $myUser->haveFirm($myUser->preference('default_firm'))){
			$_SESSION['firm'] = serialize(Firm::getById($myUser->preference('default_firm')));
			if(!$_SESSION['firm']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
		} else if(count($myUser->firms)!=0) {
			$_SESSION['firm'] = serialize(reset($myUser->firms));
			if(!$_SESSION['firm']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");
		} else {
			throw new Exception('Ce compte n\'est actif sur aucun établissement');
		}

		$myFirm = isset($_SESSION['firm']) ? unserialize($_SESSION['firm']) : new Firm();
		if(!$myFirm) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");

		$_SESSION['currentUser'] = serialize($myUser);
		if(!$_SESSION['currentUser']) throw new Exception("Problème lors de la connexion, veuillez contacter l'administrateur");

		//Gestion de l'inactivité de l'utilisateur
		$inactivityDelay = $conf->get('logout_inactivity_delay');

		if(!empty($inactivityDelay) && is_numeric($inactivityDelay)){
			$response['inactivityDelay'] = $inactivityDelay;
			$myUser->meta['lastActivity'] = time();
		}

		if(isset($_['rememberMe']) && $_['rememberMe']){
			$cookie = password_hash(mt_rand(0,1000000000000).uniqid("", true).mt_rand(0,1000000000000), PASSWORD_DEFAULT);
			$myUser->preference('cookie',$cookie);
			make_cookie(COOKIE_NAME, $cookie);
		} else {
			$myUser->preference('cookie','');
		}

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

		Plugin::callHook('user_logged',array(&$myUser));
		//permet la redirection classic pour certains plugin d'authentification qui ne passent pas par le formulaire ajax
		if(isset($_['redirect']) && $_['redirect']=='classic'){
			header('location: '. $response['redirect']);
			exit();
		}

		Log::put("Connexion réussie avec \"".$myUser->login."\"",'Utilisateur');

	} catch(Exception $e){
		Log::put("Échec de la connexion avec ".$_['login']." : ".$e->getMessage(),'Utilisateur');
		//La vérification sur le code 509 permet d'éviter d'allonger le temps de ban à chaque tentative
		if($e->getCode()!=509) Log::put($_['login'],'auth_fail');
		throw new Exception($e->getMessage());
	}
});

//Déconnexion
Action::register('core_logout',function(&$response){
		global $myUser,$_;
		$url = $myUser->disconnect(isset($_['url'])?$_['url']:null);
		Plugin::callHook('logout',array($url,$myUser));
		$response['redirect'] = $url;
});

//Vérification de la présence
Action::register('initialize_activity',function(&$response){
    global $myUser;
    if(!$myUser->connected()) throw new Exception("Permission non accordée");
    $myUser->meta['lastActivity'] = time();
});

/** Tables de recherches **/

//Save des colonnes dynamiques
Action::register('core_table_colum_save',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) return;
	$preferences = json_decode($myUser->preference('search_columns'),true);
	if(!$preferences) $preferences = array();
	if(!isset($_['slug'])) return $response;
	if(empty($_['added'])) $_['added'] = array();
	$preferences[$_['slug']] = $_['added'];
	$myUser->preference('search_columns',json_encode($preferences));
	$_SESSION['currentUser'] = serialize($myUser);
});

//Load des colonnes dynamiques
Action::register('core_table_colum_search',function(&$response){
	global $myUser,$_;
	if(!isset($myUser)) throw new Exception("Utilisateur non définis");
	$response = json_decode($myUser->preference('search_columns'),true);
	if(!$response) $response = array();
	return $response;
});

//Save des fitlres de recherches en preference
Action::register('core_filter_save',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) throw new Exception("Permission non accordée");
	$preferences = json_decode($myUser->preference('search_filters'),true);
	if(!$preferences) $preferences = array();
	if(!isset($_['slug'])) return $response;
	if(empty($_['label'])) throw new Exception("Libellé obligatoire");

	function filter_recursive_save($filters){
		foreach($filters as $i=>$advanced){
			if(isset($filters[$i]['operator'])) $filters[$i]['operator'] = html_entity_decode($filters[$i]['operator']);
			if(isset($filters[$i]['group'])) $filters[$i]['group'] =  filter_recursive_save($filters[$i]['group']);

			if(!isset($filters[$i]['value'])) continue;
			foreach($filters[$i]['value'] as $j => $value)
				$filters[$i]['value'][$j] = html_entity_decode($value,ENT_QUOTES,'UTF-8');
		}
		return $filters;
	}

	if(isset($_['filters']['keyword'])) $_['filters']['keyword'] = html_entity_decode($_['filters']['keyword'],ENT_QUOTES,'UTF-8');
	if(isset($_['filters']['advanced'])) $_['filters']['advanced'] = filter_recursive_save($_['filters']['advanced']);
	if(!isset($preferences[$_['slug']])) $preferences[$_['slug']] = array();
	$_['label'] = html_entity_decode($_['label'],ENT_QUOTES,'UTF-8');

	$uid = base64_encode($_['label']);
	$preferences[$_['slug']][$uid] = array(
		'label' => $_['label'],
		'uid' => $uid,
		'filters'=> $_['filters']
	);

	$myUser->preference('search_filters',json_encode($preferences));
	$response['message'] = 'Recherche enregistrée';
	$_SESSION['currentUser'] = serialize($myUser);
});

/**
 * Suppression d'une recherche enregistrée
 *  @param boolean global Définit si la recherche est globale ou non
 *  @param string slug Représente le slug de la table de résultats associée
 *  @param
 * */
Action::register('core_filter_delete',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) throw new Exception("Permission denied");
	if(!$myUser->superadmin && isset($_['global']) && !empty($_['global'])) throw new Exception("Impossible de supprimer une recherche partagée");

	$preferences = json_decode($myUser->preference('search_filters'),true);
	unset($preferences[$_['slug']][$_['uid']]);
	$myUser->preference('search_filters',json_encode($preferences));
	$_SESSION['currentUser'] = serialize($myUser);
});

Action::register('core_filter_global_save',function(&$response){
	global $myUser,$_,$conf;
	if((empty($_['rightSection']) && !$myUser->superadmin) || (isset($_['rightSection']) && !$myUser->can($_['rightSection'], 'configure'))) throw new Exception("Permissions insuffisantes", 403);
	if(empty($_['slug']) || empty($_['uid'])) return $response;

	$globalPreferences = json_decode($conf->get('search_filters'),true);
	$preferences = json_decode($myUser->preference('search_filters'),true);

	if($_['state']==1){
		$globalPreferences[$_['slug']][$_['uid']] = $preferences[$_['slug']][$_['uid']];
		unset($preferences[$_['slug']][$_['uid']]);
	}else{
		$preferences[$_['slug']][$_['uid']] = $globalPreferences[$_['slug']][$_['uid']];
		unset($globalPreferences[$_['slug']][$_['uid']]);
	}

	$conf->put('search_filters',json_encode($globalPreferences));
	$myUser->preference('search_filters',json_encode($preferences));
	$_SESSION['currentUser'] = serialize($myUser);
});

Action::register('core_filter_search',function(&$response){
	global $myUser,$_,$conf;
	if(!isset($myUser)) throw new Exception("Utilisateur non définis");
	if(empty($_['slug'])) return $response;

	$searches = array();
	$globalPreferences = json_decode($conf->get('search_filters'),true);
	$preferences = json_decode($myUser->preference('search_filters'),true);

	if(is_array($preferences) && isset($preferences[$_['slug']])){
		foreach($preferences[$_['slug']] as $preference){
			if(!isset($preference['label'])) continue;
			$preference['global'] = 0;
			$searches[$preference['uid']] = $preference;
		}
	}

	if(is_array($globalPreferences )  && isset($globalPreferences[$_['slug']])){
		foreach($globalPreferences[$_['slug']] as $preference){
			if(!isset($preference['label'])) continue;
			$preference['global'] = 1;
			$searches[$preference['uid']] = $preference;
		}
	}
	$response['filters'] = $searches;
});

/** LOGS  */
Action::register('core_search_log',function(&$response){
	global $myUser,$_;
	User::check_access('log','read');
	$limit = isset($_['export']) && $_['export'] == 'true' ? 5000 : 150;

	$data = array();
	$query = 'SELECT * FROM {{table}} WHERE 1';

	//Recherche simple
	if(!empty($_['filters']['keyword'])){
	    $query .= ' AND label LIKE ?';
	    $data[] = '%'.$_['filters']['keyword'].'%';
	}

	//Recherche avancée
	if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('label','category','creator','created','ip'),$query,$data);

	//Tri des colonnes
	if(isset($_['sort']))
		sort_secure_query($_['sort'],array('label','ip','created','category','creator'),$query,$data);
	else
		$query .= ' ORDER BY created DESC, id DESC ';

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

	foreach(Log::staticQuery($query,$data,true) as $log){
		$row = $log->toArray(true);
		$row['created'] = date('d/m/Y H:i:s', $log->created);
		$row['created_full'] = date('Y-m-d', $log->created);
		if(!empty($_['filters']['keyword'])){
			$row['label'] = preg_replace_callback('|(.*)('.$_['filters']['keyword'].')(.*)|i', function($matches){
				return $matches[1].'<mark><strong>'.$matches[2].'</strong></mark>'.$matches[3];
			}, htmlentities($log->label, ENT_QUOTES));
		}
		$response['rows'][] = $row;
	}

	//Export des données
	if(isset($_['export']) && $_['export'] == 'true') {
		//Clear des marqueurs HTML
		foreach($response['rows'] as $i => $row) {
			$row['label'] = html_entity_decode(strip_tags($row['label']));
			$response['rows'][$i] = $row;
		}

		$mapping = array(
			'Date'				=> array('slug'=>'created_full', 'type'=>'DD/MM/YYYY'),
			'Catégorie'			=> 'category',
			'Libellé'			=> 'label',
			'Utilisateur'		=> 'creator',
			'Ip'				=> 'ip',
		);

		$export = Excel::exportArray($response['rows'], $mapping, 'Logs');
		File::downloadStream($export,'export-logs-'.date('ymd').'.xlsx');

		Log::put("Export logs : ".(isset($_['filters']) ? " Filtres: ".json_encode($_['filters']) : '').", Tri: ".(isset($_['sort'])?json_encode($_['sort']):'').", Page: ".$_['page'],'Produit');
		exit();
	}
});


/* Gestion des entitées */
//Récuperation d'une liste d'entitées en fonction du plugin ciblé
Action::register('core_entity_search',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) throw new Exception("Permission refusée");
	if(empty($_['plugin'])) throw new Exception('Plugin non spécifié');


	foreach(glob($_['plugin'].SLASH.'*.class.php') as $file){
		require_once($file);
		$class = str_replace('.class.php','',basename($file));
		if(!is_subclass_of($class, 'Entity')) continue;
		$instance = new $class();
		$label =  $class;
		$table =  strtolower($class);
		if(property_exists($instance,'entityLabel') && !empty($instance->entityLabel)) $label = $instance->entityLabel;
		if(method_exists($instance,'tableName') && !empty($instance->tableName())) $table = $instance->tableName();
		$response['rows'][] = array(
			'class'=> $class,
			'label'=>  $label,
			'table'=>  $table ,
			'path' => $file
		);
	}
});

//Récuperation des infos générales d'une entitée
Action::register('core_entity_edit',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) throw new Exception("Permission refusée");
	if(empty($_['path'])) throw new Exception('Chemin non spécifié');

	$file = $_['path'];
	require_once($file);
	$class = str_replace('.class.php','',basename($file));
	if(!is_subclass_of($class, 'Entity')) return;
	$instance = new $class();

	$label =  $class;
	$table =  strtolower($class);
	if(property_exists($instance,'entityLabel') && !empty($instance->entityLabel)) $label = $instance->entityLabel;
	if(method_exists($instance,'tableName') && !empty($instance->tableName())) $table = $instance->tableName();
	$response = array(
		'class'=> $class,
		'label'=>  $label,
		'table'=>  $table ,
		'path' => $file,
		'plugin' => Plugin::parseManifest(dirname($file).SLASH.'app.json')
	);
});

//Récuperation de la liste des attributs d'une entitée
Action::register('core_entity_attribute_search',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) throw new Exception("Permission refusée");
	if(empty($_['path'])) throw new Exception('Chemin non spécifié');

	$file = $_['path'];
	require_once($file);
	$class = str_replace('.class.php','',basename($file));
	if(!is_subclass_of($class, 'Entity')) return;
	$instance = new $class();

	$fields = $instance->fields(false);


	if(property_exists($instance,'links')){
		foreach($instance->links as $field=>$classFile){
			$classFile = __ROOT__.SLASH.$classFile;
			if(!file_exists($classFile)) continue;

			require_once($classFile);
			$subClass = str_replace('.class.php','',basename($classFile));
			if(!is_subclass_of($subClass, 'Entity')) continue;
			$subInstance = new $subClass();
			$fields[$field]['entity'] = $subClass;
			$fields[$field]['classFile'] = $classFile;
			$fields[$field]['childs'] = $subInstance->fields(false);
		}
	};
	$response['fields'] = $fields;

});

/* PLUGINS */

Action::register('core_plugin_search',function(&$response){
	global $myUser,$_;
	User::check_access('plugin','read');
	$includeCore = isset($_['includeCore']) && $_['includeCore']==true ;

	$firms = array();

	foreach(Firm::loadAll() as $firm)
		$firms[] =  $firm->toArray();

	foreach(Plugin::getAll(true) as $plugin)
		$firmPluginMapping[$plugin->id] = $plugin->firms;

	foreach(Plugin::getAll(false,$includeCore) as $plugin){

		$plugin->folder = array('name'=>$plugin->folder,'path'=>$plugin->path());
		foreach($plugin->require as $id=>$version)
			$plugin->required[] = array('id'=>$id, 'version'=>$version);

		$row = $plugin->toArray();
		$row['firms'] = array_values($firms);
		foreach($row['firms'] as $i=>$firm){
			$row['firms'][$i]['value'] = isset($firmPluginMapping[$plugin->id]) && in_array($firm['id'],$firmPluginMapping[$plugin->id]) ? 1 : 0;
		}
		$response['rows'][] = $row;
	}
});

Action::register('core_plugin_state_save',function(&$response){
	global $myUser,$_;
	User::check_access('plugin','configure');

	$plugin = Plugin::getById($_['plugin']);

	if($_['state']){
		$states = Plugin::states();
		$missingRequire = array();
		foreach($plugin->require as $require=>$version):
			$req = Plugin::getById($require);
			if($req == null || $req==false || !$req->state || $req->version!=$version)
				$missingRequire[]= $require.' - '.$version;
		endforeach;
		if(count($missingRequire)!=0) throw new Exception("Plugins pré-requis non installés : ".implode(',',$missingRequire));
	}
	Plugin::state($_['plugin'],$_['state']);

	Log::put(($_['state']?'Activation':'Désactivation')." du plugin ".$_['plugin'],'Plugin');
});

/** ETABLISSEMENT */

//Récuperation d'une liste de etablissement
Action::register('core_firm_search',function(&$response){
	global $_;
	User::check_access('firm','read');

	// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
	$query = 'SELECT main.* FROM '.Firm::tableName().' main  WHERE 1';
	$data = array();
	//Recherche simple
	if(!empty($_['filters']['keyword'])){
		$query .= ' AND main.label LIKE ?';
		$data[] = '%'.$_['filters']['keyword'].'%';
	}

	//Recherche avancée
	if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('main.label','main.description','main.logo','main.mail','main.phone','main.fax','main.street','main.street2','main.city','main.zipcode','main.siret','main.iban'),$query,$data);

	//Tri des colonnes
	if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.label','main.description','main.logo','main.mail','main.phone','main.fax','main.street','main.street2','main.city','main.zipcode','main.siret','main.iban'),$query,$data);

	//Pagination
	//Par défaut pour une recherche, 20 items, pour un export 5000 max
	$itemPerPage = !empty($_['itemPerPage']) ? $_['itemPerPage'] : 20;
	//force le nombre de page max a 50 coté serveur
	$itemPerPage = $itemPerPage>50 ? 50 : $itemPerPage;
	if($_['export'] == 'true') $itemPerPage = 5000;
	$response['pagination'] = Firm::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');

	$firms = Firm::staticQuery($query,$data,true,0);

	$response['rows'] = array();
	foreach($firms as $firm){
		$row = $firm->toArray();
		$row['description'] = html_entity_decode($row['description']);
		$row['logo'] = $firm->logo('url');

		if($_['export'] == 'true'){
			$row['created'] = date('d-m-Y',$row['created']);
			$row['updated'] = date('d-m-Y',$row['updated']);
		}

		$response['rows'][] = $row;
	}

	/* Mode export */
	if($_['export'] == 'true'){
		if(empty($response['rows'])) $response['rows'][] = array('Vide'=>'Aucune données');
		$fieldsMapping = array();
		foreach (Firm::fields(false) as $key => $value)
			$fieldsMapping[$value['label']] = $key;
		$stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
		File::downloadStream($stream,'export-etablissements-'.date('d-m-Y').'.xlsx');
		exit();
	}

});


//Ajout ou modification d'élément etablissement
Action::register('core_firm_save',function(&$response){
	global $_;
	User::check_access('firm','edit');

	$item = Firm::provide();
	$item->label = $_['label'];
	$item->description = $_['description'];
	$item->mail = $_['mail'];
	$item->phone = $_['phone'];
	$item->fax = $_['fax'];
	$item->street = $_['street'];
	$item->street2 = $_['street2'];
	$item->city = $_['city'];
	$item->zipcode = $_['zipcode'];
	$item->siret = $_['siret'];
	$item->iban = $_['iban'];
	$item->save();
	//Ajout upload Logo
	if(!empty($_['logo']))
		File::save_component('logo', 'core/public/firm/'.$item->id.'/logo.{{extension}}');
	$response = $item->toArray();
});



//Suppression d'élement etablissement
Action::register('core_firm_delete',function(&$response){
	global $_;
	User::check_access('firm','delete');

	if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
	$firm = Firm::getById($_['id']);
	Firm::deleteById($firm->id);

	//Suppression de l'établissmeent supprimé dans les plugins activés
	$states = Plugin::states();
	foreach ($states as $plugin => $firms) {
	    $key = array_search($_['id'], $firms);
	    if($key === false) continue;
	    unset($firms[$key]);
	    $states[$plugin] = array_values($firms);
	}
	Plugin::states($states);

	//Suppression des liens UFR et des droits associés
	UserFirmRank::delete(array('firm'=>$_['id']));
	Right::delete(array('firm'=>$_['id']));

	Log::put("Suppression de l'établissement ".$firm->toText(),'Etablissement');
});

//Firm : Gestion upload Logo
Action::register('core_firm_logo',function(&$response){
	File::handle_component(array(
		'namespace' => 'core', //stockés dans file/core/*.*
		'access' => 'core', // crud sur core,
		'size' => '1000000000', // taille max
		'limit' => '1', // nb max de fichiers
		'storage' => 'core/public/firm/{{data.id}}/logo.*' //chemin complet vers le fichier stocké
	),$response);
});

Action::register('core_firm_select',function(&$response){
	global $myUser,$_,$myFirm;
	try{
		if(!$myUser->connected()) throw new Exception("Permission denied");
		if(!$myUser->haveFirm( $_['firm'])) throw new Exception("Vous n'avez pas accès à cet établissement");
		$myFirm = Firm::getById($_['firm']);
		$_SESSION['firm'] = serialize($myFirm);

		$myUser->preference('default_firm',$myFirm->id);
		$myUser->loadRights();
		$_SESSION['currentUser'] = serialize($myUser);

		if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
		if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
		header('location: index.php');
	}catch(Exception $e){
		header('location: index.php?error='.urlencode($e->getMessage()));
	}
});

Action::register('core_firm_autocomplete',function(&$response){
	global $myUser,$_;
	if(!$myUser->can('firm','read')) throw new Exception("Vous n'avez pas acces aux établissements");
	$response['rows'] = array();
	if($_['keyword'] == '') return;

	foreach(Firm::loadAll(array('label:like'=> '%'.$_['keyword'].'%' ),array('label')) as $firm){
		$response['rows'][] = array(
			'label'=>$firm->label,
			'id'=>$firm->id,
			'description'=>$firm->description
		);
	}
});

Action::register('core_firm_by_uid',function(&$response){
	global $myUser,$_;
	if(!$myUser->can('firm','read')) throw new Exception("Vous n'avez pas acces aux établissements");
	$response['items'] = array();
	$firms = $_['items'];

	foreach(Firm::loadAll(array('id:IN'=>implode(',',$firms))) as $item){
		$row = $item->toArray();
		$row['label'] = $item->label;
		$row['id'] = $item->id;
		$response['items'][$item->id] = $row;
	}
});

/** LIEN ETABLISSEMENT / PLUGIN **/
Action::register('core_firm_plugin_search',function(&$response){
	global $myUser,$_;
	User::check_access('plugin','configure');
	if(!isset($_['firm'])) throw new Exception("Établissement non spécifié");

	$wholePlugins = array();

	if($_['firm'] == '0'){
		foreach(Firm::loadAll() as $firm){
			foreach(Plugin::getAll(true) as $plugin){
				$wholePlugins[$plugin->id][$firm->id] = in_array($firm->id, $plugin->firms) ? 1 : 0;
			}
		}
	}

	foreach(Plugin::getAll(true) as $plugin){
		if($_['firm'] == '0'){
			$plugin->state = count(array_unique($wholePlugins[$plugin->id])) === 1 ? end($wholePlugins[$plugin->id]) : 2;
		}else{
			$plugin->state = in_array($_['firm'], $plugin->firms) ? 1 : 0;
		}
		$response['rows'][] = $plugin;
	}
});

Action::register('core_firm_plugin_save',function(&$response){
	global $myUser,$_;
	User::check_access('plugin','configure');

	$firms = Firm::loadAll();
	$firms[] = Firm::anonymous_firm();

	foreach($firms as $firm){
		if($firm->id != $_['firm'] && $_['firm'] != '0') continue;

		$states = Plugin::states();
		$firms = $states[$_['plugin']];
		$key = array_search($firm->id, $firms);

		if($_['state']==0 && $key !== false){
			unset($firms[$key]);
		}else if($_['state']==1 && $key === false){
			$firms[] = $firm->id;
		}
		$states[$_['plugin']] = array_values($firms);
		Plugin::states($states);
	}
});

/** LIEN ETABLISSEMENT / UTILISATEUR / RANG **/
Action::register('core_userfirmrank_search',function(&$response){
	global $myUser,$_;
	User::check_access('rank','read');

	$firms = array($_['firm']);
	if($_['firm'] == 0){
		$firms = array();
		foreach(Firm::loadAll() as $firm)
			$firms[] = $firm->id;
	}

	$users = array();
	foreach(User::getAll(array('right'=>false)) as $user)
		$users[$user->login] = $user;

	foreach(UserFirmRank::staticQuery("SELECT *, ufr.id id, u.id uid, r.label rank, f.label firm
		FROM {{table}} ufr
		LEFT JOIN ".User::tableName()." u ON ufr.user=u.login
		LEFT JOIN ".Rank::tableName()." r ON r.id=ufr.rank
		LEFT JOIN ".Firm::tableName()." f ON f.id=ufr.firm
		WHERE ufr.firm IN (".str_repeat('?,', count($firms) - 1) . '?'.")",$firms,false) as $userFirmRank){

		if(empty($myUser->superadmin) && !empty($userFirmRank['superadmin'])) continue;
		$user = isset($users[$userFirmRank['user']]) ? $users[$userFirmRank['user']] : new User();

		// Petit trick pour l'affichage mustache
		$userFirmRank['superadmin'] = !empty($userFirmRank['superadmin']);
		$userFirmRank['avatar'] = $user->getAvatar();
		$userFirmRank['password'] = '';
		$user->name = $user->lastname();
		$user->firstname = $user->firstname();
		$userFirmRank['user'] = $user;

		$response['rows'][] = $userFirmRank;
	}
});

Action::register('core_userfirmrank_save',function(&$response){
	global $myUser,$_;
	User::check_access('rank','edit');
	if(!isset($_['firm'])) throw new Exception('Champ "Établissement" obligatoire');
	if(!isset($_['user']) || empty($_['user'])) throw new Exception('Champ "Utilisateur" obligatoire');
	if(!isset($_['rank']) || empty($_['rank'])) throw new Exception('Champ "Rang" obligatoire');

	foreach(Firm::loadAll() as $firm){
		if($_['firm'] != 0 && $_['firm'] != $firm->id) continue;
		$user = User::byLogin(stripslashes($_['user']));
		$rank = Rank::getById($_['rank']);

		if($user->origin == 'active_directory' && (!array_key_exists($firm->id, $user->firms) || !$firm->has_plugin('fr.core.activedirectory'))) continue;

		$userFirmRank = UserFirmRank::provide();

		$exist = is_null($userFirmRank->id) || $_['firm'] == 0 ? UserFirmRank::rowCount(array('user'=>$user->login,'firm'=>$firm->id,'rank'=>$_['rank'])) : UserFirmRank::rowCount(array('id:!='=>$userFirmRank->id,'user'=>$user->login,'firm'=>$firm->id,'rank'=>$_['rank']));

		if($exist > 0){
			$response['warning'][] = "Le rang ".$rank->label." est déja défini pour ".$user->fullName()." sur l'établissement ".$firm->label;
			continue;
		}

		$userFirmRank->fromArray($_);
		$userFirmRank->firm = $firm->id;
		$userFirmRank->user = $user->login;
		$userFirmRank->save();
		$response['success'][] = "Rang ".$rank->label." ajouté pour ".$user->fullName()." sur l'établissement ".$firm->label;
	}
});

Action::register('core_userfirmrank_edit',function(&$response){
	global $myUser,$_;
	User::check_access('rank','edit');

	$userFirmRank = UserFirmRank::getById($_['id']);
	$response = $userFirmRank;
});

Action::register('core_userfirmrank_delete',function(&$response){
	global $myUser,$_,$conf;
	User::check_access('rank','delete');
	$userFirmRank = UserFirmRank::provide();
	$user = User::byLogin($userFirmRank->user);

	if($user->preference('default_firm') == $userFirmRank->firm)
		UserPreference::delete(array('user'=>$user->login, 'key'=>'default_firm'));

	UserFirmRank::deleteById($_['id']);
});

/** UTILISATEURS **/
Action::register('core_user_search',function(&$response){
	global $myUser,$_;
	User::check_access('user','read');

	foreach(User::getAll(array('right'=>false,'force'=> true)) as $user){
		if($user->state == User::INACTIVE || (!$myUser->superadmin && $user->superadmin)) continue;

		$user->login = htmlspecialchars_decode($user->login);
		$user->name = $user->lastname();
		$user->firstname = $user->firstname();
		$user->avatar = $user->getAvatar();
		$user->formatedLogin = urlencode($user->login);
		$response['rows'][] = $user;
	}
});

Action::register('core_user_autocomplete',function(&$response){
	global $myUser,$_,$myFirm;
	if(!$myUser->can('user','read')) throw new Exception("Vous n'avez pas acces aux utilisateurs");
	$response['rows'] = array();
	$scope = isset($_['data']['scope']) ? $_['data']['scope'] : $myFirm->id;
	if($_['keyword'] == '') return;
	if(in_array('user', $_['data']['types'])){
		foreach(User::getAll(array('right'=>true) ) as $user){

			if($scope!= 0 && !isset($user->firms[$scope])) continue;

			if(preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->fullName())) || preg_match('|'.preg_quote(slugify($_['keyword'])).'|i', slugify($user->login))){
				$response['rows'][] = array(
					'fullname'=>html_decode_utf8($user->fullName()),
					'name'=>$user->fullName(),
					'uid'=>html_decode_utf8(addslashes($user->login)),
					'id'=>$user->login,
					'mail'=>$user->mail,
					'type'=>'user',
					'avatar'=>$user->getAvatar(),
					'function'=>$user->function
				);
			}
		}
	}
	if(in_array('rank', $_['data']['types'])){
		foreach(Rank::staticQuery('SELECT * FROM {{table}} WHERE label LIKE ?',array('%'.$_['keyword'].'%'),true) as $rank){
			$response['rows'][] = array(
				'fullname'=>html_decode_utf8($rank->label),
				'name'=>$rank->label,
				'uid'=>$rank->id,
				'id'=>$rank->id,
				'type'=>'rank',
				'description'=>$rank->description,
			);
		}
	}
});

Action::register('core_user_by_uid',function(&$response){
	global $myUser,$_;
	if(!$myUser->can('user','read')) throw new Exception("Vous n'avez pas acces aux utilisateurs");
	$response['users'] = array();

	$ranks = array();
	$users = array();

	foreach($_['uids'] as $uid){
		if(is_numeric($uid)){
			$ranks[] = $uid;
			continue;
		}

		//user
		$item = User::byLogin($uid);
		if(!$item->login) {
			$item->login = $uid;
			$item->fullName = $uid;
			$item->uid = $uid;
		}
		$row = $item->toArray();
		$row['fullname'] = html_decode_utf8($item->fullName());
		$row['name'] = $item->fullName();
		$row['uid'] = html_decode_utf8(addslashes($item->login));
		$row['id'] = $item->login;
		$row['type'] = 'user';
		unset($row['password']);
		unset($row['token']);
		$response['users'][$item->login] = $row;
	}

	//rank
	foreach(Rank::loadAll(array('id:IN'=>implode(',',$ranks))) as $item){
		$row = $item->toArray();
		$row['fullname'] = $item->label;
		$row['name'] = $item->label;
		$row['uid'] = $item->id;
		$row['id'] = $item->id;
		$row['type'] = 'rank';
		$response['users'][$item->id] = $row;
	}
});

/* Compte/Profil utilisateur */

Action::register('core_account_lost_password',function(&$response){
	global $myUser,$myFirm,$_,$conf;
	if(!isset($_['mail']) || empty($_['mail']) || !check_mail(trim($_['mail']))) throw new Exception("Adresse e-mail non spécifiée ou incorrecte");

	foreach(User::getAll(array('right'=>false) ) as $user){
		if(mb_strtolower($user->mail) != mb_strtolower(trim($_['mail']))) continue;

		$token = sha1(time().mt_rand(0,1000));
		$linkToken = base64_encode($user->login.'::'.$token.'::1');

		UserPreference::delete(array('user'=>$user->login,'key'=>'lost_password'));
		$saved = new UserPreference();
		$saved->user = $user->login;
		$saved->key = 'lost_password';
		$saved->value = $token;
		$saved->save();

		$mail = new Mail;
		$mail->expeditor = !empty($conf->get('password_lost_expeditor'))?$conf->get('password_lost_expeditor'):"";
        $mail->title = "Récupération de mot de passe oublié";

        $data = array(
			'link' => ROOT_URL.'/account.lost.php?token='.$linkToken,
			'url' => ROOT_URL,
			'firstname' => $user->firstname,
		);
		if(!empty($conf->get('password_lost_firm')) && $firm = Firm::getById($conf->get('password_lost_firm'))){
			$mail->firm = utf8_decode($firm->label);
			$data['firm'] = $firm->label;
			$data['logo'] = ROOT_URL.'/'.$firm->logo('url');
		}
		if(!empty($conf->get('password_lost_mail_expire'))){
			$expDays = intval($conf->get('password_lost_mail_expire'));
			$data['expDays'] = $expDays;
			$data['expDaysPlural'] = $expDays>1?"s":"";
			$data['expDate'] = !empty($expDays) ? date("d/m/Y à H:i", strtotime($expDays." days")) : '';
		}
		$mail->template(__DIR__.SLASH.'mail.reset.password.html',$data,true);

		$mail->recipients['to'][] = $user->mail;
		$mail->send();

		Log::put("Demande de récupération de mot de passe : ".$user->toText(),'Utilisateur');
		return;
	}
	throw new Exception("Aucun compte ne correspond, veuillez contacter un administrateur");
});

Action::register('core_account_api_save',function(&$response){
	global $myUser,$myFirm,$_,$conf;
	User::check_access('account','edit');
	$myUser->preference('api_enabled',$_['api-enabled']);
	$myUser->loadPreferences();
	$_SESSION['currentUser'] = serialize($myUser);
});

Action::register('core_account_save',function(&$response){
	global $myUser,$myFirm,$_,$conf;
	User::check_access('account','edit');

	if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
	if(preg_match('|[,'.preg_quote(htmlspecialchars_decode($conf->get('login_forbidden_char'))).']|i', htmlspecialchars_decode($_['login']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans l'identifiant");
	if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Adresse mail obligatoire');
	$_['mail'] = mb_strtolower(trim($_['mail']));
	$_['login'] = mb_strtolower(trim($_['login']));

	$userForm = new User();
	$userForm->fromArray($_);
	if(empty($userForm->login) && (!isset($_['password']) || empty($_['password']))) throw new Exception("Mot de passe obligatoire");

	//Vérifications & formattage des données
	$userForm->firstname = mb_ucfirst(mb_strtolower($userForm->firstname));
	$userForm->name = mb_strtoupper($userForm->name);

	if(!empty($userForm->mail) && !check_mail($userForm->mail)) throw new Exception('Le format du champ "Mail" est invalide');
	if(!empty($userForm->phone) && !check_phone_number($userForm->phone)) throw new Exception('Le format du champ "Téléphone fixe" est invalide');
	$userForm->phone = !empty($userForm->phone) ? normalize_phone_number($userForm->phone) : '';
	if(!empty($userForm->mobile) && !check_phone_number($userForm->mobile)) throw new Exception('Le format du champ "Téléphone mobile" est invalide');
	$userForm->mobile = !empty($userForm->mobile) ? normalize_phone_number($userForm->mobile) : '';
	if(!empty($conf->get('password_forbidden_char')) && preg_match('|['.preg_quote(htmlspecialchars_decode($conf->get('password_forbidden_char'))).']|i', htmlspecialchars_decode($_['password']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans le mot de passe");
	if($_['password'] != $_['password2']) throw new Exception("Mot de passe et confirmation non similaires");

	//Recuperation des hash des precedents passwords
	$chain = explode('-',$myUser->preference('account_chain'));

	if(!empty(trim($_['password']))) {
		$hashedPassword = User::password_encrypt('$a1u7'.$_['password'].'$y$1');
		if(in_array($hashedPassword, $chain) && !$myUser->superadmin) throw new Exception("Vous devez choisir un mot de passe différent des précédents");

		if(count($chain)==10) array_shift($chain);
		$chain[] = $hashedPassword;
		$myUser->preference('account_chain',implode('-',$chain));
	}

	//save des comptes type db
	if($myUser->origin == ''){
		if(!empty(trim($_['password']))){

			$passwordErrors = User::check_password_format($_['password']);
			if(count($passwordErrors)!=0 && !$myUser->superadmin) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : <br>".implode("<br>",$passwordErrors));

			if(($_['password']==$myUser->login || $_['password']==$myUser->mail) && !$myUser->superadmin) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant ou à l'e-mail");
			$myUser->password = User::password_encrypt($_['password']);
			$myUser->preference('passwordTime',time());
		}

		$myUser->firstname = $userForm->firstname;
		$myUser->name = $userForm->name;
		$myUser->mail = $userForm->mail;
		$myUser->function = $userForm->function;
		$myUser->phone = $userForm->phone;
		$myUser->mobile = $userForm->mobile;
		$myUser->manager = is_object($myUser->manager) ? $myUser->manager->login : $myUser->manager;
		if(is_array($myUser->meta)) $myUser->meta = json_encode($myUser->meta);
		$myUser->save();
		if($myUser->superadmin == 1){
			foreach(Firm::loadAll() as $firm)
				$firms[$firm->id] = $firm;
			$myUser->setFirms($firms);
		}
	}

	//Save de l'avatar
	if(!empty($_FILES['avatar']) && $_FILES['avatar']['size']!=0 ){

		$login = User::format_avatar_name($myUser->login);

		foreach (glob(__ROOT__.FILE_PATH.AVATAR_PATH.$login.".*") as $filename)
			unlink($filename);

		$avatar = File::upload('avatar',AVATAR_PATH.$login.'.{{ext}}',104857060,array('jpg','png','jpeg','gif'));
		Image::resize($avatar['absolute'],150,150);
	}
	//save des comptes types plugin
	Plugin::callHook("user_save",array(&$myUser,$userForm,&$response));

	$myUser->loadRights();
	if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
	if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
	$_SESSION['currentUser'] = serialize($myUser);
});

Action::register('core_account_avatar_download',function(&$response){
	global $myUser,$_;
	User::check_access('profile','read');
	try {
		$user = str_replace(array('..','/'),'',$_['user']);
		$extension = str_replace(array('..','/'),'',$_['extension']);
		File::downloadFile(File::dir().AVATAR_PATH.User::format_avatar_name($user).'.'.$extension,null, null, null, true,false);
	} catch(Exception $e) {
		File::downloadFile('img/default-avatar.png',null, null, null, true,false);
	}
});

Action::register('core_account_avatar_delete',function(&$response){
	global $myUser,$_;
	if(!$user = User::byLogin($_['login'])) throw new Exception("Utilisateur inconnu");
	if($myUser->login!=$user->login && !$myUser->can('user', 'edit')) throw new Exception("Permissions insuffisantes",403);

	foreach(glob(__ROOT__.FILE_PATH.AVATAR_PATH.User::format_avatar_name($user->login).".*") as $filename)
		unlink($filename);

	if(!file_exists(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails')) return;

	foreach(glob(__ROOT__.FILE_PATH.AVATAR_PATH.'.thumbnails'.SLASH.User::format_avatar_name($user->login).".*") as $filename)
		unlink($filename);
});

Action::register('core_user_save',function(&$response){
	global $myUser,$_,$conf;
	User::check_access('user','edit');
	if(!isset($_['login']) || empty($_['login'])) throw new Exception("Identifiant obligatoire");
	if(preg_match('|[,'.preg_quote(htmlspecialchars_decode($conf->get('login_forbidden_char'))).']|i', htmlspecialchars_decode($_['login']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans l'identifiant");

	//Calcule de la taille max du login en focntion du chemin absolu pour avatar + extension (5)
	$osElementMaxLength = OS_path_max_length() - strlen(__ROOT__.FILE_PATH.AVATAR_PATH) - strlen(User::get_avatar_extension_brace());
	if(strlen($_['login']) > $osElementMaxLength) throw new Exception("Identifiant trop long : maximum ".$osElementMaxLength." caractères");

	$osElementMaxLength = OS_element_max_length();
	if(strlen($_['login']) > $osElementMaxLength) throw new Exception("Identifiant trop long : maximum ".$osElementMaxLength." caractères");

	if(!isset($_['mail']) || empty($_['mail'])) throw new Exception('Le champ "Mail" est obligatoire');
	if(!check_mail($_['mail'])) throw new Exception('Le format du champ "Mail" est invalide');
	if(!empty($conf->get('password_forbidden_char')) && preg_match('|['.preg_quote(htmlspecialchars_decode($conf->get('password_forbidden_char'))).']|i', htmlspecialchars_decode($_['password']), $match)) throw new Exception("Caractère ".$match[0]." interdit dans le mot de passe");
	if($_['password'] != $_['password2']) throw new Exception("Mot de passe et confirmation non similaires");

	$_['mail'] = mb_strtolower(trim($_['mail']));
	$_['login'] = trim($_['login']);
	$user = User::byLogin($_['login']);
	$user = $user && empty($user->origin) ? $user : new User();

	//Check si un user n'existe pas déjà avec ce login (on récupère tous les users car user peut être supprimé logiquement / désactivé uniquement)
	if(empty($user->id)){
		$tryExisting = User::byLogin($_['login']);
		if($tryExisting && $tryExisting->state=='published')
			throw new Exception("Un utilisateur existe déjà avec cet identifiant");
	}
	if(!$user->login) $user->login = $_['login'];

	foreach(User::getAll(array('right'=>false)) as $existingUser)
		if($existingUser->mail == $_['mail'] && $existingUser->login != $user->login) throw new Exception("Un utilisateur existe déjà avec cette adresse e-mail");

	if($user->id == 0 && (!isset($_['password']) || empty($_['password']))) throw new Exception("Mot de passe obligatoire");
	if(!empty(trim($_['password']))){
		$passwordErrors = User::check_password_format(html_entity_decode($_['password']));
		if(count($passwordErrors)!=0 && !$myUser->superadmin) throw new Exception("Le format de mot de passe ne respecte pas les conditions suivantes : <br>".implode("<br>",$passwordErrors));

		if($_['password']==$_['login'] || $_['password']==$_['mail'] ) throw new Exception("Le mot de passe ne peut pas être identique à l'identifiant ou à l'e-mail");

		$user->password = User::password_encrypt(html_entity_decode($_['password']));
		$user->preference('passwordTime',time());
	}
	$user->firstname = mb_ucfirst(mb_strtolower($_['firstname']));
	$user->name = mb_strtoupper($_['name']);
	$user->mail = $_['mail'];
	$user->state = User::ACTIVE;
	if(isset($_['manager'])) $user->manager = $_['manager'];

	if(is_array($user->meta)) $user->meta = json_encode($user->meta);


	$user->save();
	if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
	if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
	$user->password = '';
	Log::put("Création/Modification de l'utilisateur ".$user->login,'Utilisateur');
});

Action::register('core_user_edit',function(&$response){
	global $myUser,$_;
	User::check_access('user','edit');

	$user = User::byLogin($_['login'], true, true);
	$user->login = htmlspecialchars_decode($user->login);
	$user->name = $user->lastname();
	$user->firstname = $user->firstname();
	if(!$user) throw new Exception("Utilisateur non identifié");
	$user->password = '';
	$response = $user;
});

Action::register('core_user_delete',function(&$response){
	global $myUser,$_;
	User::check_access('user','delete');
	$user = User::byLogin($_['login'], true, true);
	if(!$user) throw new Exception("Utilisateur non identifié");

	$user->loadRanks();
	if($user->superadmin == 1) throw new Exception("Vous ne pouvez pas supprimer le compte Super Admin");
	if($user->login == $myUser->login) throw new Exception("Vous ne pouvez pas supprimer votre propre compte");

	if(!$user = User::getById($user->id)) throw new Exception("Impossible de supprimer un compte en dehors de de la base de données");
	$user->state = User::INACTIVE;
	$user->save();

	foreach(UserFirmRank::loadAll(array('user'=>$user->login)) as $ufrLink)
	    UserFirmRank::deleteById($ufrLink->id);
	if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
	if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);
	Log::put("Suppression de l'utilisateur ".$user->toText(),'Utilisateur');
});

/** DROITS **/
Action::register('core_right_search',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) return $response;
	foreach(Right::loadAll(array('scope'=>$_['scope'],'uid'=>$_['uid'],'firm:IN'=>array($_['firm'],'NULL') )) as $right){
		$row = $right->toArray();
		if(!$right->read) unset($row['read']);
		if(!$right->edit) unset($row['edit']);
		if(!$right->delete) unset($row['delete']);
		if(!$right->configure) unset($row['configure']);
		if(!$right->recursive) unset($row['recursive']);

		if($row['firm']=='0') unset($row['firm']);
		if($right->targetScope == 'rank'){
			$row['target'] = '<i class="far fa-address-card"></i> '.Rank::getById($right->targetUid)->label;
		}else{
			$user = User::byLogin($right->targetUid);
			$row['target'] = '<img class="avatar avatar-mini avatar-rounded" src="'.$user->getAvatar().'"> '.$user->fullName();
		}
		$response['rows'][] = $row;
	}
});

//Récuperation ou edition d'élément right
Action::register('core_right_save',function(&$response){
	global $myUser,$_;

	$right = new Right();
	$right->fromArray($_);

	$scopes = Right::availables('scope');
	if(!isset($scopes[$right->scope]) ||!isset($scopes[$right->scope]['check'])) throw new Exception("Aucun control d'accès n'a été défini sur cette section");

	if(!$myUser->superadmin){ //todo décommenter
		$check = $scopes[$right->scope]['check'];
		$check('save',$right);
	}

	$right->save();
});

Action::register('core_right_delete',function(&$response){
	global $myUser,$_;

	$right = Right::getById($_['id']);

	$scopes = Right::availables('scope');
	if(!isset($scopes[$right->scope]) ||!isset($scopes[$right->scope]['check'])) throw new Exception("Aucun control d'accès n'a été défini sur cette section");

	if(!$myUser->superadmin){ //todo décommenter
		$check = $scopes[$right->scope]['check'];
		$check('delete',$right);
	}

	Right::deleteById($_['id']);
});


//////////////////////
Action::register('core_right_search',function(&$response){
	global $myUser,$_;
	User::check_access('rank','edit');
	if(!isset($_['firm'])) throw new Exception("Etablissement non spécifié");

	$wholeRights = array();
	$scopes = array();
	$scopes = Right::availables('scope');

	$firms = Firm::loadAll();
	$firms[] = Firm::anonymous_firm();

	foreach($firms as $firm){
		if($firm->id != $_['firm'] && $_['firm'] != '0') continue;

		$rights = Right::loadAll(array('targetUid'=>$_['targetUid'],'firm'=>$firm->id));
		$rightsTable = array();
		foreach($rights as $right)
			$rightsTable[$right->scope] = $right;

		if($_['firm'] == '0'){
			foreach($scopes as $scope=>$options) {
				$right = isset($rightsTable[$scope])? $rightsTable[$scope] : new Right();

				$wholeRights[$scope]['read'][$firm->id] = (int)$right->read;
				$wholeRights[$scope]['edit'][$firm->id] = (int)$right->edit;
				$wholeRights[$scope]['delete'][$firm->id] = (int)$right->delete;
				$wholeRights[$scope]['configure'][$firm->id] = (int)$right->configure;
			}
		}
	}

	foreach ($scopes as $scope=>$options) {
		if(!$options['global']) continue;
		if($_['firm'] == '0'){
			$read = count(array_unique($wholeRights[$scope]['read'])) === 1 ? end($wholeRights[$scope]['read']) : 2;
			$edit = count(array_unique($wholeRights[$scope]['edit'])) === 1 ? end($wholeRights[$scope]['edit']) : 2;
			$delete = count(array_unique($wholeRights[$scope]['delete'])) === 1 ? end($wholeRights[$scope]['delete']) : 2;
			$configure = count(array_unique($wholeRights[$scope]['configure'])) === 1 ? end($wholeRights[$scope]['configure']) : 2;
		}else{
			$right = isset($rightsTable[$scope])? $rightsTable[$scope] : new Right();
			$read = $right->read;
			$edit = $right->edit;
			$delete = $right->delete;
			$configure = $right->configure;
		}

		$response['rows'][] = array(
			'scope'=>$scope,
			'description'=>$options['label'],
			'read'=>(int)$read,
			'edit'=>(int)$edit,
			'delete'=>(int)$delete,
			'configure'=>(int)$configure
		);
		usort($response['rows'], function($a, $b){
			return strcmp($a['scope'], $b['scope']);
		});
	}
});

Action::register('core_right_toggle',function(&$response){
	global $myUser,$_,$myFirm;
	User::check_access('rank','edit');
	if(!isset($_['scope']) || empty($_['scope'])) throw new Exception("Scope non spécifié");
	if(!isset($_['targetUid']) || empty($_['targetUid'])) throw new Exception("target Uid non spécifié");
	if(!isset($_['right']) || empty($_['right'])) throw new Exception("Droit non spécifié");
	if(!isset($_['firm'])) throw new Exception("Établissement non spécifié");

	$firms = Firm::loadAll();
	$firms[] = Firm::anonymous_firm();

	foreach($firms as $firm){
		if($firm->id != $_['firm'] && $_['firm'] != '0') continue;

		$item = Right::load(array('targetUid'=>$_['targetUid'],'firm'=>$firm->id,'scope'=>$_['scope']));
		$item = !$item ? new Right() : $item ;
		$item->targetUid = $_['targetUid'];
		$item->firm = $firm->id;
		$item->targetScope = 'rank';
		$item->scope = $_['scope'];
		$item->{$_['right']} = $_['state'];
		$item->save();

		$myUser->loadRights();

		$_SESSION['currentUser'] = serialize($myUser);
	}
});


/** RANGS **/
Action::register('core_rank_search',function(&$response){
	global $myUser,$_;
	User::check_access('rank','read');

	$rankQry = 'SELECT *,(SELECT GROUP_CONCAT(CONCAT(f.label,":",`scope`,":",`read`,":",`edit`,":",`delete`,":",`configure`))
		FROM `'.Right::tableName().'` r LEFT JOIN firm f ON f.id = r.firm
		WHERE (r.read=? OR r.edit=? OR r.delete=? OR r.configure=?) AND r.targetUid={{table}}.id) as rights
		FROM {{table}}';

	$ranks = Rank::staticQuery($rankQry,array(1,1,1,1),true);
	foreach($ranks as $rank){
		$row = $rank->toArray(true);

		//Gestion des rights sur les rangs "coeur" ayant des perms
		$row['read'] = $row['edit'] = $row['delete'] = $row['configure'] = true;
		if($rights = Right::loadAll(array('scope'=>'rank', 'uid'=>$rank->id))){
			if(!$myUser->can('rank','read',$rank->id)) continue;
			$row['edit'] = $myUser->can('rank','edit',$rank->id);
			$row['delete'] = $myUser->can('rank','delete',$rank->id);
			$row['configure'] = $myUser->can('rank','configure',$rank->id);
		}

		$row['rights'] = array();
		foreach (explode(',', $rank->foreign('rights')) as $right) {
			$infos = explode(':', $right);

			$row['rights'][] = array(
				'configure' => !empty(array_pop($infos)),
				'delete' => !empty(array_pop($infos)),
				'edit' => !empty(array_pop($infos)),
				'read' => !empty(array_pop($infos)),
				'scope' => array_pop($infos),
				'firm' => array_pop($infos)
			);
			usort($row['rights'], function($a, $b){
				return strcmp($a['firm'], $b['firm']);
			});
		}
		$response['rows'][] = $row;
	}
});

Action::register('core_rank_save',function(&$response){
	global $myUser,$_;
	User::check_access('rank','edit');

	if(!isset($_['label']) || empty($_['label'])) throw new Exception("Libellé obligatoire");
	$item = isset($_['id']) && !empty($_['id']) ? Rank::getById($_['id']) : new Rank();
	$item->label = $_['label'];
	$item->description = $_['description'];
	$item->save();
	Log::put("Ajout/Modification du rang ".$item->toText(),'Rang');
});

Action::register('core_rank_edit',function(&$response){
	global $myUser,$_;
	User::check_access('rank','edit');
	$response = Rank::getById($_['id']);
});

Action::register('core_rank_delete',function(&$response){
	global $myUser,$_;
	User::check_access('rank','delete');
	$rank = Rank::getById($_['id']);
	Rank::deleteById($_['id']);
	Log::put("Suppression du rang ".$rank->toText(),'Rang');
});


/** LISTES **/
Action::register('core_dictionary_search',function(&$response){
	global $myUser,$_;
	User::check_access('dictionary','read');

	$parent = '';

	if(!empty($_['parent']) && is_numeric($_['parent']))
		$parent = $_['parent'];

	foreach(Dictionary::loadAll(array('parent'=>$parent, 'state'=>Dictionary::ACTIVE), array(' label ASC ')) as $item){
		$item->label = html_entity_decode($item->label);
		$response['rows'][] = $item->toArray();
	}
});

Action::register('core_dictionary_save',function(&$response){
	global $myUser,$_;
	User::check_access('dictionary','edit');
	if(!isset($_['label']) || empty(trim($_['label']))) throw new Exception("Libellé obligatoire");

	if(!is_numeric($_['parent'])){
		if($myUser->can('dictionary','configure'))
			$_['parent'] = 0;
		else
			throw new Exception("Veuillez sélectionner une liste");
	}
	$item = Dictionary::provide();
	$item->label = trim($_['label']);
	$item->parent = $_['parent'];
	$item->state = Dictionary::ACTIVE;

	if(!empty($_['slug'])){
		$parameters = array('slug'=>$_['slug'], 'state'=>Dictionary::ACTIVE);
		if(isset($item->id) && !empty($item->id)) $parameters['id:!='] = $item->id;
		if(Dictionary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé");
		$item->slug = $_['slug'];
	}
	if(empty($item->slug)){
		$parentSlug = $_['parent'] == 0 ? '' : Dictionary::getById($_['parent'])->slug;
		$slug = empty($parentSlug) ? $_['label'] : $parentSlug.'-'.$_['label'];
		$item->slug = generateSlug($slug, Dictionary::class, 'slug', '', '_');
	}

	if(isset($_['sublistlabel'])) $item->sublistlabel = $_['sublistlabel'];
	$item->save();
	Log::put("Création/Modification de l'item de liste ".$item->toText(),'Liste');
});

Action::register('core_dictionary_edit',function(&$response){
	global $myUser,$_;
	User::check_access('dictionary','edit');

	$dictionary = Dictionary::getById($_['id']);
	$response = $dictionary->toArray(true);
});

Action::register('core_dictionary_delete',function(&$response){
	global $myUser,$_;
	User::check_access('dictionary','delete');
	if(!isset($_['id']) || empty($_['id'])) throw new Exception("Aucun identifiant spécifié");

	$item = Dictionary::getById($_['id']);
	$item->state = Dictionary::INACTIVE;
	$item->save();

	Dictionary::change(array('state'=>Dictionary::INACTIVE), array('parent'=>$item->id));
	Log::put("Suppression de la liste et des sous-listes associées".$item->toText(), 'Liste');
});

Action::register('core_dictionary_get_parent',function(&$response){
	global $myUser,$_;

	if(!$myUser->connected()) throw new Exception("permission denied");

	$selected = Dictionary::loadAll(array("id"=>$_['selected']));

	foreach ($selected as $item) {
		if($item->parent == 0) {
			$parents = Dictionary::loadAll(array("parent"=>$item->parent), array(' label ASC '));
		} else {
			$tmpParent = Dictionary::loadAll(array("id"=>$item->parent), array(' label ASC '));
			$parents = Dictionary::loadAll(array("parent"=>$tmpParent[0]->parent), array(' label ASC '));
		}
		$parentId = !empty($tmpParent) ? $tmpParent[0]->id : '';

		$response['rows'][] = array(
			'parents'=> $parents,
			'currentId'=> $item->id,
			'parentId'=> $parentId,
			'label'=> $item->label
		);
	}
});


Action::register('core_dictionary_component_load',function(&$response){
	global $myUser,$_;
	//double check afin de laisse la possiubilité aux non connectés de voir les listes sur certains projets
	if(!$myUser->connected() && !$myUser->can('dictionary','read')){
		$response['content'] = array();
		return;
	}

	$dictionnaries = array();

	if(isset($_['slug']) && $_['slug'] != ""){
		$dictionnaries = Dictionary::load(array("slug"=>$_['slug']));
	}else{
		$dictionnaries = new Dictionary();
		$dictionnaries->id = 0;
	}

	if(isset($_['parentId']) && $_['parentId'] != ""){
		$dictionnaries = Dictionary::getById($_['parentId']);
		$dictionnaries->id = 0;
	}

	if($dictionnaries) {
		$dictionnaries = $dictionnaries->toArray();
		if(!isset($_['depth'])) $_['depth'] = 1;
		$dictionnaries['childs'] =  Dictionary::childs(array('id'=>$dictionnaries['id']),array('depth'=>$_['depth'],'format'=>'array'));
	}


	if(isset($_['value']) && $_['value'] != "" ){
		$output = is_numeric($_['value']) ? 'id' : 'slug';

		if($output == 'id' && $_['value'] == 0) return $dictionnaries;

		if(!$_['hierarchy'] || (isset($_['slug']) && $_['slug'] == "" )){

			foreach ($dictionnaries['childs'] as $i => $child) {

				if($child[$output] == $_['value']) $child['selected'] = true;
				$dictionnaries['childs'][$i] = $child;
			}
		} else {
			$dictionnaries = Dictionary::hierarchy($_['value'],$_['slug']);
		}

	}
	$response['content'] = $dictionnaries;
});


Action::register('core_dictionary_slug_proposal',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) throw new Exception("Permission denied");

	if(!isset($_['label']) || empty($_['label'])) return;
	//Check si l'item n'a pas déjà un slug
	if(isset($_['id']) && !empty($_['id']) && is_numeric($_['id'])){
		$item = Dictionary::provide();
		if(!empty($item->slug)) return;
	}
	$parentSlug = empty($_['parent']) ? '' : Dictionary::getById($_['parent'])->slug;
	$slug = empty($parentSlug) ? $_['label'] : $parentSlug.'_'.$_['label'];
	$response['slug'] = generateSlug($slug, Dictionary::class, 'slug', '', '_');
});


/* Composant tag list */
Action::register('core_tag_list_autocomplete',function(&$response){
	global $myUser,$_;
	if(!$myUser->can('dictionary','read')) throw new Exception("Vous n'avez pas acces aux listes");
	$response['rows'] = array();

	foreach(Dictionary::staticQuery('SELECT * FROM {{table}} WHERE parent=(SELECT id from {{table}} WHERE slug= ? LIMIT 1) AND label LIKE ? AND state = ? ',array($_['data']['parent'],'%'.$_['keyword'].'%',Dictionary::ACTIVE),true) as $item){
		$response['rows'][] = array(
			'name'=>$item->label,
			'id'=>$item->id,
			'slug'=>$item->slug
		);
	}
});

Action::register('core_tag_list_autocreate',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
	$response = array();

	$parent = Dictionary::bySlug($_['slug']);
	$newtag = new Dictionary();
	$newtag->state = Dictionary::ACTIVE;
	$newtag->parent= $parent->id;
	$newtag->label= $_['label'];
	$newtag->slug= $parent->slug.'-'.slugify($_['label']);
	$newtag->save();

	$response =  array(
		'name'=>$newtag->label,
		'id'=>$newtag->id,
		'slug'=>$newtag->slug
	);
});

Action::register('core_tag_list_by_id',function(&$response){
	global $myUser,$_;
	if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
	$response['tags'] = array();

	$ids = explode(',',$_['id']);

	foreach(Dictionary::loadAll(array('id:IN'=>$ids)) as $dictionary){
		$dictionaryMapping[$dictionary->id] = $dictionary;
	}

	foreach ($ids as $id) {

		if(!isset($dictionaryMapping[$id])) continue;
		$item = $dictionaryMapping[$id];
		$row = $item->toArray();
		$row['label'] = $item->label;
		$row['slug'] = $item->slug;
		$row['id'] = $item->id;

		$response['tags'][] = $row;
	}
});



/** Composant tableau de dictionary */
Action::register('core_dictionary_table_search',function(&$response){
	global $myUser,$_;

	if(!$myUser->connected()) throw new Exception("permission denied");

	if(!is_numeric($_['id'])) throw new Exception("Aucun identifiant de liste spécifié");

	$dic = Dictionary::getById($_['id']);
	$response['dictionary'] = $dic->toArray(true);

	foreach (Dictionary::childs(array('slug'=>$dic->slug)) as $child)
		$response['rows'][] = $child->toArray(true);
});

Action::register('core_dictionary_table_save',function(&$response){
	global $myUser,$_;

	if(!$myUser->connected()) throw new Exception("Permission denied");
	if(!isset($_['label']) || empty($_['label'])) throw new Exception("Aucun libellé de liste renseigné");
	if(!isset($_['id']) && !isset($_['list'])) throw new Exception("Aucun identifiant de liste ou de parent de liste trouvé");

	$dic = isset($_['id']) && !empty($_['id'])? Dictionary::getById($_['id']) : new Dictionary();
	$dic->parent = $_['list'];
	$dic->label = $_['label'];
	if(isset($_['slug']) && !empty($_['slug'])) {
		$parameters = array('slug'=>$_['slug'], 'state'=>Dictionary::ACTIVE);
		if(isset($dic->id) && !empty($dic->id)) $parameters['id:!='] = $dic->id;
		if(Dictionary::rowCount($parameters)>0) throw new Exception("Le slug renseigné est déjà utilisé");
			$dic->slug = $_['slug'];
	}
	$dic->state = Dictionary::ACTIVE;
	$dic->save();
});

/* COMPOSANT LOCATION */
Action::register('core_location_search',function(&$response){
	global $myUser,$_,$conf;
	if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);

	$appUrl = $conf->get('maps_api_suggest_url');
	$appId = $conf->get('maps_api_id');
	$appKey = $conf->get('maps_api_key');

	if(empty($appUrl) || empty($appId) || empty($appKey)) throw new Exception("Impossible d'initialiser le composant de localisation");
	if(!isset($_['keyword']) || empty($_['keyword'])) return;

	$default = array(
		'query' => $_['keyword'],
		'app_id' => $appId,
		'app_code' => $appKey
	);
	$params = array_merge($default, $_['data']);

	$curlOpt = array(
	  	CURLOPT_URL => sprintf("%s?%s", $appUrl, http_build_query($params)),
	  	CURLOPT_HTTPHEADER => array(
			'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
			'Content-Type: application/json',
		),
	  	CURLOPT_RETURNTRANSFER => 1,
		CURLOPT_HTTPAUTH => CURLAUTH_ANY,
	  	CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_SSL_VERIFYHOST => false,
	);
	$ch = curl_init();
	curl_setopt_array($ch, $curlOpt);

	$result = curl_exec($ch);
	if($result === false) throw new Exception("Erreur de récupération cURL : ".curl_error($curl));
	$result = json_decode($result);

	$infos = curl_getinfo($ch);
	curl_close($ch);

	$response['rows'] = $result->suggestions;
});

Action::register('core_location_detail_search',function(&$response){
	global $myUser,$_,$conf;
	if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);

	$appUrl = $conf->get('maps_api_geocode_url');
	$appId = $conf->get('maps_api_id');
	$appKey = $conf->get('maps_api_key');

	if(empty($appUrl) || empty($appId) || empty($appKey)) throw new Exception("Impossible de récupérer les détails de la localisation");
	if(!isset($_['locationId']) || empty($_['locationId'])) return;

	$params = array(
		'locationid' => $_['locationId'],
		'app_id' => $appId,
		'app_code' => $appKey
	);

	$curlOpt = array(
	  	CURLOPT_URL => sprintf("%s?%s", $appUrl, http_build_query($params)),
	  	CURLOPT_HTTPHEADER => array(
			'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
			'Content-Type: application/json',
		),
	  	CURLOPT_RETURNTRANSFER => 1,
		CURLOPT_HTTPAUTH => CURLAUTH_ANY,
	  	CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_SSL_VERIFYHOST => false,
	);
	$ch = curl_init();
	curl_setopt_array($ch, $curlOpt);

	$response = curl_exec($ch);
	if($response === false) throw new Exception("Erreur de récupération cURL : ".curl_error($curl));
	$response = json_decode($response);

	$infos = curl_getinfo($ch);
	curl_close($ch);
});

/** CRONTAB */
Action::register('core_cron',function(&$response){
	try{
		if(php_sapi_name() !== 'cli') throw new Exception("Le cron ne peut être executé qu'en mode CLI depuis le serveur");
		Plugin::callHook('cron', array(time()));
	}catch(Exception $e){
		file_put_contents(__DIR__.SLASH.'cron.log',date('d-m-Y H:i').' | '.$e->getMessage().PHP_EOL,FILE_APPEND);
	}
});

/** FILES & UPLOADS */
//Gestion de l'upload temporaire (avant soumission d'un form)
Action::register('core_temporary_file_upload',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<count($_FILES[$_['index']]['name']);$i++) {
		$tempPath = File::temp().basename($fileIndex['tmp_name'][$i]);

		move_uploaded_file($fileIndex['tmp_name'][$i], $tempPath);
		$ext  = getExt($fileIndex['name'][$i]);

		$response['previews'][] = array(
			'path' => basename($fileIndex['tmp_name'][$i]),
			'name' => $fileIndex['name'][$i],
			'temporary' => true,
			'ext' => $ext,
			'url' => 'action.php?action=core_temporary_file_download&name='.$fileIndex['name'][$i].'&path='.basename($fileIndex['tmp_name'][$i]),
			'icon' => getExtIcon($ext)
		);
	}
});

Action::register('core_temporary_file_download',function(&$response){
	global $myUser,$_;
	User::check_access('file','read');
	File::downloadFile(File::temp().$_['path'],$_['name']);
});

/** GENERAL SETTINGS **/
Action::register('core_general_settings_save',function(&$response){
	global $myUser, $_, $conf;
	User::check_access('setting_global','configure');

	$_FILES = normalize_php_files();
	if(isset($_FILES['fields'])) $_FILES = $_FILES['fields'];

	$coreFolder = __ROOT__.FILE_PATH.'core'.SLASH;
	if(!file_exists($coreFolder)) mkdir($coreFolder,0755,true);

	//Ajout logo
	if(!empty($_['logo-light'])){
		$logo = File::save_component('logo-light', 'core/public/logo.{{extension}}');
		Image::resize($logo[0]['absolute'], 200, 200);
		Image::toPng($logo[0]['absolute']);
		unset($_['logo-light']);
	}

	//Ajout logo dark
	if(!empty($_['logo-dark'])){
		$logo = File::save_component('logo-dark', 'core/public/logo.dark.{{extension}}');
		Image::resize($logo[0]['absolute'], 200, 200);
		Image::toPng($logo[0]['absolute']);
		unset($_['logo-dark']);
	}

	//Ajout favicon
	if(!empty($_['favicon'])){
		$logo = File::save_component('favicon', 'core/public/favicon.{{extension}}');
		Image::resize($logo[0]['absolute'], 16, 16);
		Image::toPng($logo[0]['absolute']);
		unset($_['favicon']);
	}

	//Durée de conservation des logs
	foreach(Log::staticQuery('SELECT DISTINCT category FROM {{table}}',array(),true) as $log):
		$slug = slugify($log->category);
		$key = 'log_retention_time_'.$slug;

		if(!isset($_[$key])) continue;
		if($_[$key] == 0 || !is_numeric($_[$key])) $_[$key] = '';
		$conf->put($key,$_[$key]);
	endforeach;

	//Gestion save des configuration générales
	foreach(Configuration::setting('configuration-global') as $key => $value){
		if(!is_array($value)) continue;
		$allowedSettings[] = $key;
	}


	if(isset($_['logout_inactivity_delay']) && !empty($_['logout_inactivity_delay']) && $_['logout_inactivity_delay'] < 60) throw new Exception("Le délai d'inactivité doit être supérieur ou égal à 60");


	foreach($_ as $key => $value)
		if(in_array($key, $allowedSettings)) $conf->put($key, $value);


	//Politique de mot de passes
	if(isset($_['password_format'])) $conf->put('password_format',$_['password_format']);

	//Maintenance
	if(isset($_['maintenance'])){
        if($_['maintenance']){
			if(file_exists(File::dir().SLASH.'disabled.maintenance')) rename(File::dir().SLASH.'disabled.maintenance', File::dir().SLASH.'enabled.maintenance');
			file_put_contents(File::dir().SLASH.'enabled.maintenance', trim($_['maintenance-content']));
		} else {
			if(file_exists(File::dir().SLASH.'enabled.maintenance')) rename(File::dir().SLASH.'enabled.maintenance', File::dir().SLASH.'disabled.maintenance');
			file_put_contents(File::dir().SLASH.'disabled.maintenance', trim($_['maintenance-content']));
		}
	}
});

Action::register('core_general_password_reset_delay',function(&$response){
	global $myUser, $_, $conf;
	User::check_access('setting_global','configure');

	foreach(User::getAll(array('right'=>false)) as $user)
		$user->preference('passwordTime',strtotime('01/01/1990'));
});

//Récupération logo application générale
Action::register('core_general_logo',function(&$response){
    global $myUser,$_;
    User::check_access('setting_global','configure');

    $variant = '';
    if(!empty($_['data']) && !empty($_['data']['variant'])){
    	$variant = $_['data']['variant'];
    	$variant = $variant == 'light' ? '' : '.'.$variant;
    }

    File::handle_component(array(
		'namespace' => 'core', //stockés dans core/*.*
		'access' => 'setting_global', // crud sur core,
		'size' => '10000000', // taille max
		'storage' => 'core/public/logo'.$variant.'.{png,jpg,jpeg,gif}' //chemin complet vers le fichier stocké
	),$response);
});

//Récupération logo application générale
Action::register('core_general_favicon',function(&$response){
    global $myUser,$_;
    User::check_access('setting_global','configure');

    File::handle_component(array(
		'namespace' => 'core', //stockés dans core/*.*
		'access' => 'setting_global', // crud sur core,
		'size' => '1000000', // taille max
		'extension' => 'png', // png uniquement
		'storage' => 'core/public/favicon.png' //chemin complet vers le fichier stocké
	),$response);
});


//Permet de se connecter "en tant que"
Action::register('core_user_impersonation',function(&$response){
	try{
		global $myUser,$myFirm,$_,$conf;
		if(!$myUser->superadmin) throw new Exception("Seul le super administrateur peut exécuter cette fonctionnalité");
		if(!isset($_['login'])) throw new Exception("Identifiant non spécifié");

		if(isset($_SESSION['users_rights'])) unset($_SESSION['users_rights']);
		if(isset($_SESSION['users_norights'])) unset($_SESSION['users_norights']);

		$myUser = User::connectLogin($_['login']);

		Log::put("Impersonation de l'utilisateur : ".$myUser->login,"Utilisateur");
		$_SESSION['currentUser'] = serialize($myUser);
		$_SESSION['firm'] = serialize($myFirm);

		header('location: index.php?info='.rawurlencode('Connecté avec l\'utilisateur : '.$myUser->login));
	} catch(Exception $e){
		header('location: setting.php?section=user&error='.rawurlencode($e->getMessage()));
	}
});



/* HISTORY */
Action::register('core_history_search',function(&$response){
	global $myUser,$_;
	User::check_access('history','read');

	$filters = array();
	$response['rows'] = array();

	//Récuperation du nombre de messages importants uniquement
	if(!empty($_['showImportant'])){
		$data = array(History::IMPORTANCE_IMPORTANT);
		$query = 'SELECT scope,uid,COUNT(id) thecount FROM {{table}} WHERE importance=? AND ( ';
		$i=0;
		foreach ($_['scopes'] as $scope=>$values) {
			$marks = array_fill(0, count($values), '?');
			$data[] = $scope;
			$data = array_merge($data,$values);
			$query .= ($i==0 ?'' :' OR ').' (scope = ? AND uid IN('.implode(',',$marks).')) ';
			$i++;
		}
		$query .= ' ) GROUP BY scope,uid ';

		$importants = History::staticQuery($query,$data)->fetchAll();

		//On renvoie 0 s'il n'y a pas  de résultat afin d'afficher les notifications de l'historique
		if(empty($importants)){
			foreach($_['scopes'] as $scope=>$values){
				foreach($values as $uid){
					$importants[] = array('scope'=>$scope,'uid'=>$uid,'thecount'=>0);
				}
			}
		}

		foreach($importants as $line)
			$response['rows'][] = array('scope'=>$line['scope'],'uid'=>$line['uid'],'number'=>$line['thecount']);


	//Récuperation du detail ghistorique pour un item
	}else{
		$filters['scope'] = $_['scope'];
		if(isset($_['uid'])) $filters['uid'] = $_['uid'];

		if(!empty($_['keyword'])) $filters['comment:LIKE'] = '%'.$_['keyword'].'%';
		foreach(History::loadAll($filters,array('sort DESC')) as $history){
			$row = $history->toArray();
			$row['type'] = History::types($row['type']);
			$row['comment'] = html_entity_decode($row['comment'],ENT_QUOTES,'UTF-8');
			$row['created'] =array(
				'fullname'=>complete_date($row['created']),
				'time'=>date('H:i',$row['created'])
			);
			$user = User::byLogin($row['creator']);
			$row['creator'] = array('fullname'=>(!is_null($user->login) ? $user->fullName() : $row['creator']));
			$response['rows'][] = $row;
		}
	}
});

Action::register('core_history_importance_save',function(&$response){
	global $myUser,$_;
	User::check_access('history','edit');

	$item = History::provide();
	if(is_null($item->id)) return;

	$item->importance = $_['importance'];
	$item->save();
	$response = $item->toArray();
});

Action::register('core_history_save',function(&$response){
	global $myUser,$_,$myFirm;
	User::check_access('history','edit');

	$item = History::provide();
	if(!$item) return;

	if(isset($_['comment'])) $item->comment = $_['comment'];
	$item->uid = $_['uid'];

	//Si pas d'ordre défini on récupere l'ordre maximum
	if(empty($_['sort'])) {
		$query = History::staticQuery('SELECT MAX(sort) maxsort FROM {{table}} WHERE scope = ? AND uid= ? ',array($_['scope'],$item->uid));
		$row = $query->fetch();
		$_['sort'] = $row['maxsort']+1;
	}

	//Si l'ordre est intercalé a la place de l'ordre "replaceSort", on décale la rangée de "replaceSort" à n et on attribute "replaceSort" à l'élement
	if(!empty($_['replaceSort'])) {
		$_['sort'] = $_['replaceSort'];
		History::staticQuery('UPDATE {{table}} SET sort = sort+1 WHERE sort >= ? AND scope = ? AND uid= ?',
			array($_['replaceSort'],$_['scope'],$item->uid)) ;
	}

	$item->sort = $_['sort'];
	$item->scope = $_['scope'];
	$item->importance = $_['importance'];
	$item->type = History::TYPE_COMMENT;
	$item->meta = json_encode(array('url'=>$_['meta']));
	$item->save();

	if(!is_null($item->comment) && $myFirm->has_plugin('fr.core.notification')){

		$mentionned = get_mention($item->comment);
		if(isset($mentionned['user']) && !empty($mentionned['user'])){
			$recipients = array();

			foreach($mentionned['user'] as $user)
				$recipients[] = $user->login;

			$url = array();
			if(!is_null($item->meta)){
				$data = json_decode($item->meta,true);
				foreach($data['url'] as $parameter=>$value)
					$url[] = $parameter."=".$value;
			}
			$url = empty($url) ? '' : '?'.implode('&',$url);
			// GESTION ENVOI NOTIFICATION
			Plugin::callHook('emit_notification',array(array(
					'label' => 'Vous avez été mentionné dans un commentaire...',
					'html' => 'Un utilisateur vous a mentionné '.$item->scope,
					'type' => "notice",
					'meta' => array('link' => ROOT_URL.'/index.php'.$url),
					'recipients' => $recipients
				)
			));
		}
	}
	$response = $item->toArray();
});

Action::register('core_history_delete',function(&$response){
	global $myUser,$_;
	User::check_access('history','delete');

	History::deleteById($_['id']);
});

/* CONTACT */
Action::register('core_contact_autocomplete',function(&$response){
	global $myUser,$_;
	if(!$myUser->can('contact','read')) throw new Exception("Vous n'avez pas acces aux contacts");
	$response['rows'] = array();

	$query = 'SELECT * FROM {{table}} p WHERE 1 ';

	if(isset($_['keyword'])){
		$query .= ' AND (p.firstname LIKE ? OR p.name LIKE ?) ';
		$data = array('%'.$_['keyword'].'%','%'.$_['keyword'].'%');
	}

	if(isset($_['data']) && isset($_['data']['scope'])){
		$query .= ' AND p.scope= ? ';
		$data[]= $_['data']['scope'];
	}
	if(isset($_['data']) && isset($_['data']['uid'])){
		$uids = array();
		foreach($_['data']['uid'] as $uid){
			$uids[] = '?';
			$data[]= $uid;
		}
		$query .= ' AND p.uid IN ('.implode(',',$uids).') ';
	}
	$query .= ' ORDER BY name,firstname LIMIT 15';

	foreach(ContactPerson::staticQuery($query,$data,true) as $item){
		$response['rows'][] = array(
			'label'=>html_decode_utf8($item->fullName()),
			'id'=>$item->id,
			'job'=>$item->job
		);
	}
});

Action::register('core_contact_by_uid',function(&$response){
	global $myUser,$_;
	if(!$myUser->can('contact','read')) throw new Exception("Vous n'avez pas acces aux contacts");
	$response['items'] = array();
	$items = $_['items'];

	foreach(ContactPerson::loadAll(array('id:IN'=>implode(',',$items))) as $item){
		$row = $item->toArray();
		$row['label'] = $item->fullname();
		$row['job'] = $item->job;
		$row['id'] = $item->id;
		$response['items'][$item->id] = $row;
	}
});

/** Gestion des fichiers **/
Action::register('core_file_search',function(&$response){
	global $myUser, $_, $conf;
	User::check_access('file','read');

	$programRoot = rtrim(File::dir(),SLASH);
	$root = !empty($_['root']) ? $programRoot.SLASH.trim($_['root'],SLASH) : $programRoot;

	if(isset($_['folder']) && ($_['folder']=='.' || $_['folder']=='..')) $_['folder']=='';
	$target = (!empty($_['folder'])) ? $programRoot.SLASH.rtrim($_['folder'],SLASH) : $root;

	$path = explode(SLASH,str_replace($root,'',$target));
	$path = array_values(array_filter($path));
	$files = glob($root.SLASH.'*');

	$currentPath = '';
	for($i=0;$i<count($path);$i++){
		$currentPath.= $path[$i].SLASH;
		$files = array_merge($files,glob(File::dir().$currentPath.'*'));
	}

	$response['tree'] = array();
	foreach($files as $file){
		if(!is_dir($file)) continue;
		$relativePath =  str_replace( $root.SLASH,'',$file);
		$response['tree'][] = $relativePath;
	}
});

/** CUSTOM REWRITE */
Action::register('rewrite',function(&$response){
	try{
		$root = substr($_SERVER['SCRIPT_NAME'], 0,strrpos($_SERVER['SCRIPT_NAME'] , '/'));
		$requested = substr($_SERVER['REQUEST_URI'], strlen($root)+1);
		ob_start();
		Plugin::callHook('rewrite',array($requested));
		$stream = ob_get_clean();
		if($stream !='') echo $stream;
	}catch(Exception $e){
		exit('<div style="width:300px;margin:30px auto;padding:15px;background:#cecece;text-align:center;font-family:Arial">'.$e->getMessage().'</div>');
	}
});

/** ACTIONS DE PLUGINS */
if(isset($GLOBALS['actions'][$_['action']])) Action::write($GLOBALS['actions'][$_['action']]);

?>
