<?php
	/** MACHINE / MACHINE / ENVIRONNEMENT **/
	//Récuperation d'une liste de machine / environnement
	Action::register('host_machine_search',function(&$response){
		global $_,$myUser,$myFirm;
		User::check_access('host','read');
		Plugin::need('client/Client');
		require_once(__DIR__.SLASH.'Machine.class.php');

		// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
		$query = 'SELECT m.*,m.id as id,'.Client::joinString('cli').' FROM '.Machine::tableName().' m LEFT JOIN '.Client::tableName().' cli ON m.client = cli.id WHERE 1';
		$data = array();
		//Recherche simple
		if(!empty($_['filters']['keyword'])){
			$query .= ' AND m.label LIKE ?';
			$data[] = '%'.$_['filters']['keyword'].'%';
		}

		//Droits

		$allowedMachines = array();

		if(isset($myUser->rights['host_sheet'])){
			if(isset($myUser->rights['host_sheet'][0])){
				foreach($myUser->rights['host_sheet'][0] as $machine=>$rights){
					if(!$rights['read']) continue;
					$allowedMachines[]=$machine;
				}
			}
			if( isset($myUser->rights['host_sheet'][$myFirm->id])){
				foreach($myUser->rights['host_sheet'][$myFirm->id] as $machine=>$rights){
					if(!$rights['read']) continue;
					$allowedMachines[]=$machine;
				}
			}
		}

		if(!$myUser->can('host','configure')){
			$query .= ' AND (m.creator = ? ';
			$data[] = $myUser->login;

			if(count($allowedMachines)!=0){
				$query .= ' OR m.id IN ('.implode(',',array_fill(0, count($allowedMachines), '?')).')';
				foreach($allowedMachines as $id)
					$data[] = $id;
			}
			$query .= ')';
		}




		//Recherche avancée
		if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('m.label','m.manager','m.ip','m.client','m.os','m.mac','m.ram','m.cpu','m.comment','m.type'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('m.label','m.manager','m.ip','m.client','m.os','m.mac','m.ram','m.cpu','m.comment','m.type'),$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'] = Machine::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'m');

		$machines = Machine::staticQuery($query,$data,true,1);


		$osList = Dictionary::slugToArray('host_machine_os',true);
		$response['rows'] = array();
		foreach($machines as $machine){
			$row = $machine->toArray();
			$user = User::byLogin($row['manager']);
			$row['manager'] = $user->toArray();
			$row['manager']['fullname'] = $user->fullname();
			$row['manager']['avatar'] = $user->getAvatar();

			$row['client'] = $machine->join('client')->toArray();
			$row['client']['label'] = htmlspecialchars_decode($row['client']['label'], ENT_QUOTES);

			$row['class'] = '';
			if( !$machine->can('edit')) $row['class'] .= ' readonly ';
			if(!empty($row['os'])){
				$row['os'] = isset($osList[$row['os']]) ? $osList[$row['os']] : new Dictionary();
			}else{
				unset($row['os']);
			}
			$row['comment'] = html_entity_decode($row['comment']);
			$row['type'] = Machine::types($row['type']);

			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 (Machine::fields(false) as $key => $value)
				$fieldsMapping[$value['label']] = $key;

			$stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
			File::downloadStream($stream,'export-demandes-'.date('d-m-Y').'.xlsx');
			exit();
		}

	});

	Action::register('host_application_url_search',function(&$response){
		global $_,$myUser;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'Machine.class.php');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		Plugin::need('client/Client');
		$response['rows'] = array();
		foreach(MachineApplication::loadAll(array('url:!='=>''),  null,  null, array('*'),  2) as $application){
			$row =  $application->toArray();
			$machine =  $application->join('machine');
			if(!$machine || empty($machine->id)) continue;
			$row['machine'] = $machine->toArray();
			$client = $machine->join('client');


			if(!isset($response['rows'][$machine->id])){
				$response['rows'][$machine->id] = $machine->toArray();
				$response['rows'][$machine->id]['type'] = Machine::types($machine->type);
				$response['rows'][$machine->id]['client'] = $client->toArray();

				$response['rows'][$machine->id]['applications'] = array();
			}
			$response['rows'][$machine->id]['applications'][] = $row;

		}
	});

	Action::register('host_application_url_ping',function(&$response){
		global $_,$myUser;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'Machine.class.php');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');


		$application = MachineApplication::getById($_['application']);


		if(!empty($application->url) && filter_var($application->url, FILTER_VALIDATE_URL) !== FALSE){
			$ping = host_ping_url($application->url);
		}else{
			$ping = array('code' => 404,'message'=> 'Adresse vide ou malformée');
		}
		$response['ping'] = $ping;

	});

	Action::register('host_plan_search',function(&$response){
		global $_,$myUser;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'Machine.class.php');
		$response['rows'] = array();
		foreach(Machine::loadAll(array('ip:LIKE'=>$_['root'].'.%')) as $machine){
			$row =  $machine->toArray();
			$row['type'] = Machine::types($row['type']);
			$response['rows'][] = $row;
		}
	});

	//Ajout ou modification d'élément machine / environnement
	Action::register('host_machine_save',function(&$response){
		global $_,$myUser,$myFirm;
		User::check_access('host','edit');
		require_once(__DIR__.SLASH.'Machine.class.php');


		if(!$myUser->can('host','edit')) return;

		//Check champs dynamiques
		if($myFirm->has_plugin('fr.core.dynamicform')){
			Plugin::need('dynamicform/DynamicForm');
			$dynamicFields = Dynamicform::check_required('host-sheet',array(),$_);
		}

		$item = Machine::provide();

		if(!empty($item->id) && !$item->can('edit') ) return;




		$oldItem = clone $item;
		$item->label = $_['label'];
		$item->manager = $_['manager'];
		$item->ip = $_['ip'];
		if(!empty($_['os']) && is_numeric($_['os'])) $item->os = $_['os'];
		$item->mac = $_['mac'];
		if(is_numeric($_['ram'])) $item->ram = $_['ram'];
		if(is_numeric($_['cpu'])) $item->cpu = $_['cpu'];
		$item->comment = $_['comment'];
		$item->type = $_['type'];
		$item->save();
		History::entityChange('host_machine',$oldItem,$item);

		//save champs dynamiques
		if($myFirm->has_plugin('fr.core.dynamicform')){
			Plugin::need('dynamicform/DynamicForm');
			echo Dynamicform::record('host-sheet',array(
				'scope'=>'host',
				'uid'=>$item->id,
				'fields'=>$dynamicFields
			),$_);
		}


		$response = $item->toArray();

	});




	//Récuperation ou edition d'élément machine / environnement
	Action::register('host_machine_edit',function(&$response){
		global $_,$myUser,$myFirm;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'Machine.class.php');

		$machine = Machine::provide();
		if( !$machine->can('read')) throw new Exception("Vous n'avez pas la permission de voir cet hébergement");

		ob_start();
		require_once(__DIR__.SLASH.'page.sheet.machine.php');
		$response['html'] = ob_get_clean();
		$response['id'] = $machine->id;

		if(!$machine->can('edit')) $response['readonly'] = true;

	});


	//Suppression d'élement machine / environnement
	Action::register('host_machine_delete',function(&$response){
		global $_,$myUser;
		User::check_access('host','delete');
		require_once(__DIR__.SLASH.'Machine.class.php');
		$machine = Machine::getById($_['id']);
		if(!$machine->can('delete'))  throw new Exception("Vous n'avez pas la permission de supprimer cet hébergement");


		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		$machine = Machine::getById($_['id']);
		$machine->remove();
	});

	//Suppression d'élement machine / environnement
	Action::register('host_machine_open_with',function(&$response){
		global $_;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'Machine.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");

		$machine = Machine::provide();
		$tool = $_['tool'];

		$json = array(
			'action' =>$tool.'_open',
			'ip' => $machine->ip
		);
		$json = json_encode($json);
		header('location: dev://'.base64_encode($json));

	});

	/* permissions
	Action::register('host_permission_save',function(&$response){
		global $myUser,$_;
		if(!$myUser->can('host','edit')) throw new Exception("Permissions insuffisantes",403);
		if(!Right::can('host','edit')) throw new Exception("Permissions insuffisantes",403);
		$permission = Right::form();
		$permission->scope = 'host';
		$permission->save();
	});

	//Suppression d'élement permission
	Action::register('host_permission_delete',function(&$response){
		$permission = Right::getById($_['id']);
		if($permission->scope != 'host') throw new Exception("Erreur de routage des permissions");
		if(!Right::can('host','delete')) throw new Exception("Permissions insuffisantes",403);
		Right::deleteById($permission->id);
	});

*/

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


	/** MACHINEAPPLICATION / APPLICATION SUR LA MACHINE **/
	//Récuperation d'une liste de application sur la machine
	Action::register('host_machine_application_search',function(&$response){
		global $_,$myUser;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		require_once(__DIR__.SLASH.'Machine.class.php');

		if(isset($_['filters']['advanced'])){
			foreach ($_['filters']['advanced'] as $key => $value) {
				if($value['column']!='main.machine') continue;

				$machine = Machine::getById($value['value'][0]);

				if( !$machine->can('read')) throw new Exception("Vous n'avez pas la permission de visualiser cet hébergement");
			}
		}


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

		if(!empty($_['machine'])){
			$query .= ' AND main.machine = ?';
			$data[] = $_['machine'];
		}

		//Recherche avancée
		if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('main.label','main.version','main.url','main.monitored','main.machine'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.label','main.version','main.url','main.monitored','main.machine'),$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'] = MachineApplication::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');

		$machineapplications = MachineApplication::staticQuery($query,$data,true,1);




		$response['rows'] = array();
		foreach($machineapplications as $machineapplication){
			$row = $machineapplication->toArray();
			$row['machine'] = $machineapplication->join('machine')->toArray();

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

	});


	//Ajout ou modification d'élément application sur la machine
	Action::register('host_machine_application_save',function(&$response){
		global $_,$myUser;
		User::check_access('host','edit');

		require_once(__DIR__.SLASH.'Machine.class.php');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');

		$machine = Machine::getById($_['machine']);
		if( !$machine->can('edit')) throw new Exception("Vous n'avez pas la permission de modifier cet hébergement");


		$item = MachineApplication::provide();
		$oldItem = clone $item;
		$item->label = $_['label'];
		if(is_numeric($_['version'])) $item->version = $_['version'];
		$item->url = $_['url'];
		$item->monitored = $_['monitored'];
		$item->machine = $_['machine'];
		$item->save();
		History::entityChange('host_application',$oldItem,$item);
		$response = $item->toArray();
	});



	//Suppression d'élement application sur la machine
	Action::register('host_machine_application_delete',function(&$response){
		global $_,$myUser;
		User::check_access('host','delete');

		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		require_once(__DIR__.SLASH.'Machine.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		$application = MachineApplication::getById($_['id'],1);

		$machine = $application->join('machine');
		if(!$machine->can('delete')) throw new Exception("Vous n'avez pas la permission de modifier cet hébergement");
		$application = MachineApplication::getById($_['id']);
		$application->remove();
	});


	//Récuperation ou edition d'élément application
	Action::register('host_machine_application_edit',function(&$response){
		global $_,$myUser;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'Machine.class.php');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		$application = MachineApplication::provide('id',1);
		$machine = !empty($_['machine']) && $application->id==0 ? Machine::getById($_['machine']) : $application->join('machine');

		if( !$machine->can('read') ) throw new Exception("Vous n'avez pas la permission de visualiser cet hébergement");

		ob_start();
		require_once(__DIR__.SLASH.'page.sheet.machine.application.php');
		$response['html'] = ob_get_clean();
	});




	//MachineApplication : Gestion upload Certificat SSL
	Action::register('host_machine_application_certificate',function(&$response){
			File::handle_component(array(
				'namespace' => 'host', //stockés dans file/host/*.*
				'access' => 'host', // crud sur host,
				'size' => '1000000000', // taille max
				'storage' => 'host/machineapplication/{{data.id}}/certificate/*' //chemin complet vers le fichier stocké
			),$response);
	});

	/** APPLICATIONACCESS / ACCèS à L'APPLICATION  **/

	Action::register('host_application_access_search_page',function(&$response){
		global $_,$myUser;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		$application = MachineApplication::getById($_['application']);
		ob_start();
		require_once(__DIR__.SLASH.'page.list.application.access.php');
		$response['html'] = ob_get_clean();
	});


	Action::register('host_application_access_search',function(&$response){
		global $_,$myUser;
		User::check_access('host','read');
		require_once(__DIR__.SLASH.'ApplicationAccess.class.php');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		require_once(__DIR__.SLASH.'Machine.class.php');

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

		if(isset($_['filters']['advanced'])){
			foreach ($_['filters']['advanced'] as $key => $value) {
				if($value['column']!='main.application') continue;

				$application = MachineApplication::getById($value['value'][0],1);
				$machine = $application->join('machine');

				if( !$machine->can('read')) throw new Exception("Vous n'avez pas la permission de visualiser cet hébergement");
			}
		}
		if(!isset($application)) return $response;

		// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
		$query = 'SELECT main.* FROM '.ApplicationAccess::tableName().' main 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('main.label','main.login','main.password','main.application'),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.label','main.login','main.password','main.application'),$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'] = ApplicationAccess::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');

		$applicationaccesss = ApplicationAccess::staticQuery($query,$data,true,0);

		foreach($applicationaccesss as $applicationaccess){
			$row = $applicationaccess->toArray();

			$row['password'] = htmlspecialchars_decode(decrypt($row['password']));
			$row['login'] = htmlspecialchars_decode(decrypt($row['login']));

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

	});


	//Ajout ou modification d'élément accès à l'application
	Action::register('host_application_access_save',function(&$response){
		global $_,$myUser;
		User::check_access('host','edit');
		require_once(__DIR__.SLASH.'ApplicationAccess.class.php');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		require_once(__DIR__.SLASH.'Machine.class.php');
		$item = ApplicationAccess::provide('id',1);


		$application = MachineApplication::getById($_['application'],1);
		$machine = $application->join('machine');
		if( !$machine->can('edit')) throw new Exception("Vous n'avez pas la permission de modifier cet hébergement");


		$item->label = $_['label'];
		$item->login = encrypt($_['login']);
		$item->password = encrypt($_['password']);
		$item->application = $_['application'];
		$item->save();
		$response = $item->toArray();
	});

	//Récuperation ou edition d'élément accès à l'application
	Action::register('host_application_access_edit',function(&$response){
		global $_,$myUser;
		User::check_access('host','edit');
		require_once(__DIR__.SLASH.'ApplicationAccess.class.php');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		require_once(__DIR__.SLASH.'Machine.class.php');
		$access = ApplicationAccess::getById($_['id'],2);
		$application = $access->join('application');
		$machine = $application->join('machine');

		if( !$machine->can('read')) throw new Exception("Vous n'avez pas la permission de visualiser cet hébergement");
		$response = $access->toArray();


		$response['login'] = decrypt($response['login']);
		$response['password'] = decrypt($response['password']);
	});


	//Suppression d'élement accès à l'application
	Action::register('host_application_access_delete',function(&$response){
		global $_,$myUser;
		require_once(__DIR__.SLASH.'ApplicationAccess.class.php');
		require_once(__DIR__.SLASH.'MachineApplication.class.php');
		require_once(__DIR__.SLASH.'Machine.class.php');
		User::check_access('host','delete');
		$access = ApplicationAccess::getById($_['id'],2);
		$application = $access->join('application');
		$machine = $application->join('machine');
		if( !$machine->can('edit')) throw new Exception("Vous n'avez pas la permission de supprimer des élements de cet hébergement");

		require_once(__DIR__.SLASH.'ApplicationAccess.class.php');
		if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		ApplicationAccess::deleteById($_['id']);
	});



?>