{"label":"Action","syntax":"php"}
<?php
	/** {{ENTITY}} / {{ENTITYLABEL}} **/
	//Récuperation d'une liste de {{entityLabel}}
	Action::register('{{plugin_entity_deduplicate}}_search',function(&$response){
		global $_;
		User::check_access('{{plugin}}','read');
		require_once(__DIR__.SLASH.'{{Entity}}.class.php');{{#links}}
		require_once({{linkedRequirePath}});{{/links}}
		{{#advanced-search}}
		// OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
		$query = 'SELECT main.*{{#linksCount}},main.id as id,{{/linksCount}}{{#links}} '.{{linkedEntity}}::joinString('{{linkedEntity}}').'{{;}},{{/;}}{{/links}} FROM '.{{Entity}}::tableName().' main {{#links}} LEFT JOIN '.{{linkedEntity}}::tableName().' {{linkedEntity}} ON main.{{linkedKey}}={{linkedEntity}}.id {{/links}} 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({{#fields}}'main.{{key}}'{{;}},{{/;}}{{/fields}}),$query,$data);

		//Tri des colonnes
		if(isset($_['sort'])) sort_secure_query($_['sort'],array({{#fields}}'main.{{key}}'{{;}},{{/;}}{{/fields}}),$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'] = {{Entity}}::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');

		${{entity}}s = {{Entity}}::staticQuery($query,$data,true,{{linksCount}});{{/advanced-search}}
		{{^advanced-search}}${{entity}}s = {{Entity}}::loadAll();{{/advanced-search}}

		{{#fields}}{{#isDictionary}}${{key}}List = Dictionary::slugToArray('{{plugin}}_{{entity}}_{{key}}',true);{{/isDictionary}}{{/fields}}

		$response['rows'] = array();
		foreach(${{entity}}s as ${{entity}}){
			$row = ${{entity}}->toArray();{{#links}}
			$row['{{linkedKey}}'] = ${{entity}}->join('{{linkedKey}}')->toArray();{{/links}}{{#fields}}{{#isDate}}
			$row['{{key}}-readable'] = complete_date($row['{{key}}']).' à '.date('H:i',$row['{{key}}']); {{/isDate}}{{#isDictionary}}
			$row['{{key}}'] = isset(${{key}}List[$row['{{key}}']]) ? ${{key}}List[$row['{{key}}']] : new Dictionary(); {{/isDictionary}}{{#isList}}
			$row['{{key}}'] = {{Entity}}::{{key}}s($row['{{key}}']); {{/isList}}{{#isChoice}}
			$row['{{key}}'] = {{Entity}}::{{key}}s($row['{{key}}']); {{/isChoice}}{{#isWysiwyg}}
			$row['{{key}}'] = html_entity_decode($row['{{key}}']); {{/isWysiwyg}}{{#isUser}}
			$user = User::byLogin($row['{{key}}']);
			$row['{{key}}'] = $user->toArray();
			$row['{{key}}']['fullname'] = $user->fullname();
			$row['{{key}}']['avatar'] = $user->getAvatar();
			{{/isUser}}{{#isImage}}
			$row['{{key}}'] = 'action.php?action={{plugin}}_{{entity}}_{{key}}&type=download&path='.base64_encode('{{plugin}}/{{entity}}/'.$row['id'].'/{{key}}.*');
			{{/isImage}}{{#isFile}}
			$row['{{key}}'] = array();
			foreach (glob(File::dir().'{{plugin}}'.SLASH.'{{entity}}'.SLASH.$row['id'].'/{{key}}/*') as $file) {
				$row['{{key}}'][] = array(
					'label' => basename($file),
					'url' => 'action.php?action={{plugin}}_{{entity}}_{{key}}&type=download&path='.base64_encode('{{plugin}}/{{entity}}/'.$row['id'].'/{{key}}/'.basename($file)),
				);
			}

			{{/isFile}}{{/fields}}

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

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


	//Ajout ou modification d'élément {{entityLabel}}
	Action::register('{{plugin_entity_deduplicate}}_save',function(&$response){
		global $_;
		User::check_access('{{plugin}}','edit');
		require_once(__DIR__.SLASH.'{{Entity}}.class.php');
		$item = {{Entity}}::provide();{{#history-save}}
		$oldItem = clone $item;{{/history-save}}{{#fields}}{{^isFile}}{{^isImage}}
		{{#isFloat}}if(is_numeric($_['{{key}}'])) {{/isFloat}}{{#isDictionary}}if(!empty($_['{{key}}']) && is_numeric($_['{{key}}'])) {{/isDictionary}}{{#isChoice}}if(!empty($_['{{key}}']))  {{/isChoice}}$item->{{key}} = {{#isDate}}timestamp_date($_['{{key}}']);{{/isDate}}{{^isDate}}$_['{{key}}'];{{/isDate}}{{/isImage}}{{/isFile}}{{/fields}}
		$item->save();{{#fields}}{{#isImage}}
		//Ajout upload {{label}}
		if(!empty($_['{{key}}']))
			File::save_component('{{key}}', '{{plugin}}/{{entity}}/'.$item->id.'/{{key}}.[-[-extension-]-]');{{/isImage}}{{#isFile}}
		//Ajout upload {{label}}
		if(!empty($_['{{key}}']))
			File::save_component('{{key}}', '{{plugin}}/{{entity}}/'.$item->id.'/{{key}}/[-[-label-]-]');{{/isFile}}{{/fields}}{{#history-save}}

		History::entityChange('{{entity}}',$oldItem,$item);{{/history-save}}

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

	{{#edit-form}}//Récuperation ou edition d'élément {{entityLabel}}
	Action::register('{{plugin_entity_deduplicate}}_edit',function(&$response){
		global $_;
		User::check_access('{{plugin}}','edit');
		require_once(__DIR__.SLASH.'{{Entity}}.class.php');{{:links}}
		require_once(__DIR__.SLASH.'{{value.entity}}.class.php');{{/:links}}
		$response = {{Entity}}::getById($_['id'],{{linksCount}})->toArray();
	});
	{{/edit-form}}

	//Suppression d'élement {{entityLabel}}
	Action::register('{{plugin_entity_deduplicate}}_delete',function(&$response){
		global $_;
		User::check_access('{{plugin}}','delete');
		require_once(__DIR__.SLASH.'{{Entity}}.class.php');
		{{^logic-remove}}if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
		{{Entity}}::deleteById($_['id']);{{/logic-remove}}{{#logic-remove}}$item = {{Entity}}::getById($_['id']);
		$item->state = {{Entity}}::INACTIVE;
		$item->save();{{/logic-remove}}
	});

	{{#fields}}{{#isImage}}//{{Entity}} : Gestion upload {{label}}
	Action::register('{{plugin_entity_deduplicate}}_{{key}}',function(&$response){
			File::handle_component(array(
				'namespace' => '{{plugin}}', //stockés dans file/{{plugin}}/*.*
				'access' => '{{plugin}}', // crud sur {{plugin}},
				'size' => '1000000000', // taille max
				'limit' => '1', // nb max de fichiers
				'storage' => '{{plugin}}/{{entity}}/[-[-data.id-]-]/{{key}}.*' //chemin complet vers le fichier stocké
			),$response);
	});{{/isImage}}{{#isFile}}
	//{{Entity}} : Gestion upload {{label}}
	Action::register('{{plugin_entity_deduplicate}}_{{key}}',function(&$response){
			File::handle_component(array(
				'namespace' => '{{plugin}}', //stockés dans file/{{plugin}}/*.*
				'access' => '{{plugin}}', // crud sur {{plugin}},
				'size' => '1000000000', // taille max
				'storage' => '{{plugin}}/{{entity}}/[-[-data.id-]-]/{{key}}/*' //chemin complet vers le fichier stocké
			),$response);
	});{{/isFile}}{{/fields}}

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

	{{#component}}
		/* COMPOSANT*/
		//recherche autocomplete
		Action::register('{{entity}}_autocomplete',function(&$response){
        	global $myUser,$_;
    		require_once(__DIR__.SLASH.'{{Entity}}.class.php');
    		if (!$myUser->connected()) throw new Exception("Vous devez être connecté", 401);
    		$response['rows'] = array();
			$data = array("%".$_['keyword']."%");

			//retourne en priorité les matchs à 100%, pour les match keyword%, puis les autres
			$query = 'SELECT c.* FROM '.{{Entity}}::tableName().' c WHERE (c.label LIKE ?) ';
			$query .= ' LIMIT 10';


        	$devices = {{Entity}}::staticQuery($query,$data,true);
        	foreach($devices as $item){
                $response['rows'][] = array(
                	'label'=>html_entity_decode($item->label, ENT_QUOTES),
					'id'=>$item->id,
				);
        	}
        });


	//Récuperation valeur composant depuis l'uid
    Action::register('{{entity}}_by_uid',function(&$response){
        global $myUser,$_;
    	if (!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
    	require_once(__DIR__.SLASH.'{{Entity}}.class.php');

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

    	$query = 'SELECT main.* FROM '.{{Entity}}::tableName().' main WHERE main.id IN(';
    	$query .= implode(',', array_fill(0, count($_['items']), '?'));
    	$query .= ')';

	    foreach({{Entity}}::staticQuery($query,$_['items'],true) as  $item) {
	       $row = $item->toArray();
    	   $row['label'] =  html_entity_decode($row['label'], ENT_QUOTES);
    	   $response['items'][$row['id']] = $row;
	    }

    });{{/component}}

	{{#widget}}Action::register('{{plugin}}_widget_load',function(&$response){
		Plugin::need('dashboard/DashboardWidget');
		User::check_access('{{plugin}}','read');
		$widget = DashboardWidget::current();
		$widget->title = 'Widget {{Plugin}}';
		ob_start();
		//Décommenter après avoir créé widget.php
		//require_once(__DIR__.SLASH.'widget.php');
		//$widget->content = ob_get_clean();
		$widget->content = 'Widget non développé';
		$response = $widget->toArray();
	});
	{{/widget}}


?>