<?php
	/** ADSERVER / SERVEUR ACTIVE DIRECTORY **/
	//Récuperation d'une liste de serveur active directory
	Action::register('activedirectory_adserver_search',function(&$response){
		global $_;
		User::check_access('activedirectory','read');
		require_once(__DIR__.SLASH.'AdServer.class.php');

		// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
		$query = 'SELECT main.* FROM '.AdServer::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.ip','main.port','main.sslPort','main.protocolVersion','main.domain','main.userRoot','main.groupRoot','main.readonlyLogin','main.readonlyPassword','main.adminLogin','main.adminPassword','main.mapping','main.authenticationMode'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.ip','main.port','main.sslPort','main.protocolVersion','main.domain','main.userRoot','main.groupRoot','main.readonlyLogin','main.readonlyPassword','main.adminLogin','main.adminPassword','main.mapping','main.authenticationMode'),$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'] = AdServer::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');

		$adservers = AdServer::staticQuery($query,$data,true,0);




		$response['rows'] = array();
		foreach($adservers as $adserver){
			$row = $adserver->toArray();

			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 (AdServer::fields(false) as $key => $value)
				$fieldsMapping[$value['label']] = $key;
			$stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
			File::downloadStream($stream,'export-adserver-'.date('d-m-Y').'.xlsx');
			exit();
		}

	});


	//Ajout ou modification d'élément serveur active directory
	Action::register('activedirectory_adserver_save',function(&$response){
		global $_;
		User::check_access('activedirectory','edit');
		require_once(__DIR__.SLASH.'AdServer.class.php');
		$item = AdServer::provide();
		$item->ip = $_['ip'];
		$item->port = $_['port'];
		$item->sslPort = $_['sslPort'];
		$item->protocolVersion = $_['protocolVersion'];
		$item->domain = $_['domain'];
		$item->userRoot = $_['userRoot'];
		$item->groupRoot = $_['groupRoot'];
		$item->readonlyLogin = $_['readonlyLogin'];
		$item->readonlyPassword = encrypt($_['readonlyPassword']);
		$item->adminLogin = $_['adminLogin'];
		$item->adminPassword = encrypt($_['adminPassword']);
		$item->mapping = $_['mapping'];
		$item->authenticationMode = $_['authenticationMode'];

		$item->save();

		$response = $item->toArray();
	});




	//Suppression d'élement serveur active directory
	Action::register('activedirectory_fields_search',function(&$response){
		global $_;
		User::check_access('activedirectory','read');
		require_once(__DIR__.SLASH.'AdServer.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		$server = AdServer::getById($_['id']);
		$server->login();


		$response['groups'] = array();
		foreach($server->groups() as $group){
			$response['groups'][] = $group['label'];
		}

		$server->logout();

	});

	//Suppression d'élement serveur active directory
	Action::register('activedirectory_adserver_delete',function(&$response){
		global $_;
		User::check_access('activedirectory','delete');
		require_once(__DIR__.SLASH.'AdServer.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		AdServer::deleteById($_['id']);
	});

	//Test de connexion au serveur / OUs
	Action::register('activedirectory_adserver_test',function(&$response){
		global $_;
		User::check_access('activedirectory','delete');
		require_once(__DIR__.SLASH.'AdServer.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		$server = AdServer::getById($_['id']);



		try{
			$response['data_validity'] = true;
			$response['server_reachable'] = true;
			$response['authentication_readonly'] = true;
			$response['authentication_admin'] = true;
			$response['users'] = 0;
			$response['groups'] = 0;

			$server->login();

			$groups = $server->groups();
			$response['groups'] = count($groups);

			$users = $server->users();
			$response['users'] = count($users);

			$server->logout();
			try{
				$server->login(array('mode'=>'admin'));
				$server->logout();
			}catch(Exception $e){

				switch($e->getCode()){
					case 400 :
						$response['data_validity'] = false;
						$response['server_reachable'] = false;
						$response['authentication_admin'] = false;
						$response['authentication_readonly'] = false;
					break;
					case 404 :
						$response['server_reachable'] = false;
						$response['authentication_admin'] = false;
						$response['authentication_readonly'] = false;
					break;
					case 403 :  $response['authentication_readonly'] = false; break;
				}
				$response['error_detail'] = $e->getMessage();
			}

		}catch(Exception $e){
			switch($e->getCode()){
				case 400 :
					$response['data_validity'] = false;
					$response['server_reachable'] = false;
					$response['authentication_admin'] = false;
					$response['authentication_readonly'] = false;
				break;
				case 404 :
					$response['server_reachable'] = false;
					$response['authentication_admin'] = false;
					$response['authentication_readonly'] = false;
				break;
				case 403 :  $response['authentication_readonly'] = false; break;
			}
			$response['error_detail'] = $e->getMessage();
		}
	});


	//Sauvegarde des configurations de Active directory
	Action::register('activedirectory_setting_save',function(&$response){
		global $_,$conf;
		User::check_access('activedirectory','configure');
		//Si input file "multiple", possibilité de normaliser le
		//tableau $_FILES récupéré avec la fonction => normalize_php_files();
		foreach(Configuration::setting('activedirectory') as $key=>$value){
			if(!is_array($value)) continue;
			$allowed[] = $key;
		}
		foreach ($_['fields'] as $key => $value) {
			if(in_array($key, $allowed))
				$conf->put($key,$value);
		}
	});


	/** AdFirmRank / LIAISON GROUPE RANG **/
	//Récuperation d'une liste de liaison groupe rang
	Action::register('activedirectory_ad_firm_rank_search',function(&$response){
		global $_;
		User::check_access('activedirectory','read');
		require_once(__DIR__.SLASH.'AdFirmRank.class.php');
		require_once(__ROOT__.SLASH.'plugin/activedirectory/AdServer.class.php');

		// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
		$query = 'SELECT main.*,main.id as id, '.Firm::joinString('f').', '.Rank::joinString('r').' FROM '.AdFirmRank::tableName().' main
			LEFT JOIN '.Firm::tableName().' f ON f.id=main.firm
			LEFT JOIN '.Rank::tableName().' r ON r.id=main.rank
		  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.firm','main.rank','main.group','main.server'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.firm','main.rank','main.group','main.server'),$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'] = AdFirmRank::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');

		$adFirmRanks = AdFirmRank::staticQuery($query,$data,true,1);




		$response['rows'] = array();
		foreach($adFirmRanks as $adFirmRank){

			$row = $adFirmRank->toArray();
			$row['firm'] = $adFirmRank->join('firm');
			$row['rank'] = $adFirmRank->join('rank');

			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 (AdFirmRank::fields(false) as $key => $value)
				$fieldsMapping[$value['label']] = $key;
			$stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
			File::downloadStream($stream,'export-AdFirmRank-'.date('d-m-Y').'.xlsx');
			exit();
		}

	});


	//Ajout ou modification d'élément liaison groupe rang
	Action::register('activedirectory_ad_firm_rank_save',function(&$response){
		global $_;
		User::check_access('activedirectory','edit');
		require_once(__DIR__.SLASH.'AdFirmRank.class.php');
		$item = AdFirmRank::provide();
		$item->firm = $_['firm'];
		$item->rank = $_['rank'];
		$item->group = $_['group'];
		$item->server = $_['server'];
		$item->save();

		$response = $item->toArray();
	});

	//Récuperation ou edition d'élément liaison groupe rang
	Action::register('activedirectory_ad_firm_rank_edit',function(&$response){
		global $_;
		User::check_access('activedirectory','edit');
		require_once(__DIR__.SLASH.'AdServer.class.php');
		require_once(__DIR__.SLASH.'AdFirmRank.class.php');
		$response = AdFirmRank::getById($_['id'],1)->toArray();
	});


	//Suppression d'élement liaison groupe rang
	Action::register('activedirectory_ad_firm_rank_delete',function(&$response){
		global $_;
		User::check_access('activedirectory','delete');
		require_once(__DIR__.SLASH.'AdFirmRank.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		AdFirmRank::deleteById($_['id']);
	});




?>