Subversion Repositories eFlore/Applications.cel

Rev

Rev 1633 | Rev 1635 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 1633 Rev 1634
1
<?php
1
<?php
2
 
2
 
3
/**
3
/**
4
* @category  PHP
4
* @category  PHP
5
* @package   jrest
5
* @package   jrest
6
* @author    Raphaël Droz <raphael@tela-botania.org>
6
* @author    Raphaël Droz <raphael@tela-botania.org>
7
* @copyright 2013 Tela-Botanica
7
* @copyright 2013 Tela-Botanica
8
* @license   http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
8
* @license   http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
9
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
9
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
10
*/
10
*/
11
 
11
 
12
/**
12
/**
13
 * Service d'export de données d'observation du CEL au format XLS
13
 * Service d'export de données d'observation du CEL au format XLS
14
 *
14
 *
15
 * Format du service :
15
 * Format du service :
16
 * POST /ExportXLS
16
 * POST /ExportXLS
17
 * POST /ExportXLS/<Utilisateur>
17
 * POST /ExportXLS/<Utilisateur>
18
 * TODO: GET /ExportXLS/<Utilisateur> [ sans "range" ? ]
18
 * TODO: GET /ExportXLS/<Utilisateur> [ sans "range" ? ]
19
 *
19
 *
20
 * Les données POST acceptées sont:
20
 * Les données POST acceptées sont:
21
 * range (obligatoire): un range d'id_observation sous la forme d'entier ou d'intervalles d'entiers
21
 * range (obligatoire): un range d'id_observation sous la forme d'entier ou d'intervalles d'entiers
22
 *						séparés par des virgules ou bien '*' (pour toutes)
22
 *						séparés par des virgules ou bien '*' (pour toutes)
23
 * TODO: limit
23
 * TODO: limit
24
 * TODO: départ
24
 * TODO: départ
25
 * TODO: sets (ou colonnes, ou extended)
25
 * TODO: sets (ou colonnes, ou extended)
26
 * TODO: + les critères supportés par fabriquerSousRequeteRecherche()
26
 * TODO: + les critères supportés par fabriquerSousRequeteRecherche()
27
 *
27
 *
28
 * Si <Utilisateur> est fourni, celui-ci doit être authentifié
28
 * Si <Utilisateur> est fourni, celui-ci doit être authentifié
29
 * TODO: export des données public et non-sensible d'un utilisateur
29
 * TODO: export des données public et non-sensible d'un utilisateur
30
 *
30
 *
31
 * Si <Utilisateur> est fourni, le observations seront le résultat de l'intersection des 2 contraintes
31
 * Si <Utilisateur> est fourni, le observations seront le résultat de l'intersection des 2 contraintes
32
 *
32
 *
33
 */
33
 */
34
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(dirname(realpath(__FILE__))) . '/lib');
34
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(dirname(realpath(__FILE__))) . '/lib');
-
 
35
// TERM
-
 
36
ini_set('html_errors', 0);
-
 
37
ini_set('xdebug.cli_color', 2);
-
 
38
require_once('lib/PHPExcel/Classes/PHPExcel.php');
35
 
39
 
36
// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
40
// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
37
/*require_once('/home/raphael/eflore/framework/framework/Framework.php');
41
/*require_once('/home/raphael/eflore/framework/framework/Framework.php');
38
Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
42
Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
39
Framework::setInfoAppli(Config::get('info'));
43
Framework::setInfoAppli(Config::get('info'));
40
require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
44
require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
41
 
45
 
42
class ExportXLS extends Cel  {
46
class ExportXLS extends Cel  {
43
 
47
 
44
	private $cache = Array();
48
	private $cache = Array();
45
 
49
 
46
	function ExportXLS($config) {
50
	function ExportXLS($config) {
47
		parent::__construct($config);
51
		parent::__construct($config);
48
	}
52
	}
49
 
53
 
50
	/*
54
	/*
51
	 * Process $_POST et $_GET
55
	 * Process $_POST et $_GET
52
	 * TODO: changer JRest pour pouvoir disposer d'un nom de méthode plus représentatif que "updateXXX"
56
	 * TODO: changer JRest pour pouvoir disposer d'un nom de méthode plus représentatif que "updateXXX"
53
	 * en POST
57
	 * en POST
54
	 */
58
	 */
55
	function updateElement($uid, $pairs) {
59
	function updateElement($uid, $pairs) {
56
		$params = Array('uid' => $uid[0]);
60
		$params = Array('uid' => $uid[0]);
57
		// TODO: pas de range mais un utilisateur: possible
61
		// TODO: pas de range mais un utilisateur: possible
58
		if(!isset($_POST['range'])) {
62
		if(!isset($_POST['range'])) {
59
			header('HTTP/1.0 204 No Content');
63
			header('HTTP/1.0 204 No Content');
60
			exit;
64
			exit;
61
		}
65
		}
62
		// trim() car: `POST http://url<<<"range=*"`
66
		// trim() car: `POST http://url<<<"range=*"`
63
		elseif(trim($_POST['range']) == '*') {
67
		elseif(trim($_POST['range']) == '*') {
64
			$records = Array('*');
68
			$records = Array('*');
65
		}
69
		}
66
		else {
70
		else {
67
			$records = self::rangeToList(trim($_POST['range']));
71
			$records = self::rangeToList(trim($_POST['range']));
68
		}
72
		}
69
		$this->export($records, NULL, $params);
73
		$this->export($records, NULL, $params);
70
		exit;
74
		exit;
71
	}
75
	}
72
 
76
 
73
	/*
77
	/*
74
	 * $param: Tableau associatif, indexes supportés:
78
	 * $param: Tableau associatif, indexes supportés:
75
	 * 		   - widget: le nom du widget d'origine (utilisé pour les méta-données du tableur)
79
	 * 		   - widget: le nom du widget d'origine (utilisé pour les méta-données du tableur)
76
	 *
80
	 *
77
	 */
81
	 */
78
	function export(Array $records, String $fieldSets = NULL, Array $params = Array()) {
82
	function export(Array $records, String $fieldSets = NULL, Array $params = Array()) {
79
		$colonnes = self::fieldSetsToColumns($fieldSets);
83
		$colonnes = self::fieldSetsToColumns($fieldSets);
80
		$columnSlugs = array_keys($colonnes);
84
		$columnSlugs = array_keys($colonnes);
81
		$chercheur_observations = new RechercheObservation($this->config);
85
		$chercheur_observations = new RechercheObservation($this->config);
82
 
86
 
83
		$objPHPExcel = new PHPExcel();
87
		$objPHPExcel = new PHPExcel();
84
 
88
 
85
		// TODO: $params['part'] pour le multi-part
89
		// TODO: $params['part'] pour le multi-part
86
		$params['widget'] = isset($params['widget']) ? $params['widget'] : 'CEL';
90
		$params['widget'] = isset($params['widget']) ? $params['widget'] : 'CEL';
87
		// TODO: controleUtilisateur()
91
		// TODO: controleUtilisateur()
88
		if(! $params['uid']) { // || ! $this->controleUtilisateur($params['uid'])) {
92
		if(! $params['uid']) { // || ! $this->controleUtilisateur($params['uid'])) {
89
			$params['uid'] = NULL;
93
			$params['uid'] = NULL;
90
		}
94
		}
91
 
95
 
92
		$criteres = Array();
96
		$criteres = Array();
93
		if(! $records || count($records) == 1 && $records[0] == '*') {
97
		if(! $records || count($records) == 1 && $records[0] == '*') {
94
			unset($criteres['raw']);
98
			unset($criteres['raw']);
95
		}
99
		}
96
		else {
100
		else {
97
			$criteres = Array('raw' =>
101
			$criteres = Array('raw' =>
98
							  sprintf('id_observation IN (%s)', implode(',', $records)));
102
							  sprintf('id_observation IN (%s)', implode(',', $records)));
99
		}
103
		}
100
 
104
 
101
		$criteres['debut'] = isset($_GET['debut']) ? intval($_GET['debut']) : 0;
105
		$criteres['debut'] = isset($_GET['debut']) ? intval($_GET['debut']) : 0;
102
		$criteres['limite'] = isset($_GET['limite']) ? intval($_GET['limite']) : 0;
106
		$criteres['limite'] = isset($_GET['limite']) ? intval($_GET['limite']) : 0;
103
		$observations = $chercheur_observations
107
		$observations = $chercheur_observations
104
			->rechercherObservations($params['uid'], $criteres, $criteres['debut'], $criteres['limite'])
108
			->rechercherObservations($params['uid'], $criteres, $criteres['debut'], $criteres['limite'], TRUE)
105
			->get();
109
			->get();
106
			
110
			
107
		// debug //echo ($chercheur_observations->requete_selection_observations);
111
		// debug //echo ($chercheur_observations->requete_selection_observations);
108
		// XXX: malheureusement l'instance de JRest n'est pas accessible ici
112
		// XXX: malheureusement l'instance de JRest n'est pas accessible ici
109
		if(!$observations) {
113
		if(!$observations) {
110
			header('HTTP/1.0 204 No Content');
114
			header('HTTP/1.0 204 No Content');
111
			exit;
115
			exit;
112
		}
116
		}
113
 
117
 
114
		$objPHPExcel->getProperties()->setCreator($params['widget']) // ou $uid ?
118
		$objPHPExcel->getProperties()->setCreator($params['widget']) // ou $uid ?
115
			->setLastModifiedBy("XX") // TODO: $uid
119
			->setLastModifiedBy("XX") // TODO: $uid
116
			->setTitle("YY") // TODO
120
			->setTitle("YY") // TODO
117
			->setSubject("ZZ") // TODO
121
			->setSubject("ZZ") // TODO
118
			->setDescription("Export blah");
122
			->setDescription("Export blah");
119
			//->setKeywords("office PHPExcel php")
123
			//->setKeywords("office PHPExcel php")
120
			//->setCategory("Test result file")
124
			//->setCategory("Test result file")
121
 
125
 
122
		$objPHPExcel->getActiveSheet()->setTitle("Observations");
126
		$objPHPExcel->getActiveSheet()->setTitle("Observations");
123
		$sheet = $objPHPExcel->setActiveSheetIndex(0);
127
		$sheet = $objPHPExcel->setActiveSheetIndex(0);
124
		$colid = 0;
128
		$colid = 0;
125
		foreach($colonnes as $colonne) {
129
		foreach($colonnes as $colonne) {
126
			$sheet->setCellValueByColumnAndRow($colid, 1, $colonne['nom']);
130
			$sheet->setCellValueByColumnAndRow($colid, 1, $colonne['nom']);
127
			if($colonne['extra']) {
131
			if($colonne['extra']) {
128
				$sheet->getStyleByColumnAndRow($colid, 1)->getBorders()->applyFromArray(
132
				$sheet->getStyleByColumnAndRow($colid, 1)->getBorders()->applyFromArray(
129
					array(
133
					array(
130
						'allborders' => array(
134
						'allborders' => array(
131
							'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
135
							'style' => PHPExcel_Style_Border::BORDER_DASHDOT,
132
							'color' => array('rgb' => PHPExcel_Style_Color::COLOR_BLUE)
136
							'color' => array('rgb' => PHPExcel_Style_Color::COLOR_BLUE)
133
						)
137
						)
134
					)
138
					)
135
				);
139
				);
136
			}
140
			}
137
			$colid++;
141
			$colid++;
138
		}
142
		}
139
 
143
 
140
		$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);
144
		$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);
141
 
145
 
142
		$row = 2;
146
		$row = 2;
143
		foreach ($observations as $obs) {
147
		foreach ($observations as $obs) {
144
			$colid = 0;
148
			$colid = 0;
145
			foreach($colonnes as $slug => $colonne) {
149
			foreach($colonnes as $slug => $colonne) {
146
				// valeur direct depuis cel_obs ?
150
				// valeur direct depuis cel_obs ?
147
				if(isset($obs[$slug])) $valeur = $obs[$slug];
151
				if(isset($obs[$slug])) $valeur = $obs[$slug];
148
 
152
 
149
				// pré-processeur de la champs
153
				// pré-processeur de la champs
150
				if(function_exists($colonne['fonction'])) {
154
				if(function_exists($colonne['fonction'])) {
151
					$valeur = $colonne['fonction']($valeur);
155
					$valeur = $colonne['fonction']($valeur);
152
				} elseif(method_exists(__CLASS__, $colonne['fonction'])) {
156
				} elseif(method_exists(__CLASS__, $colonne['fonction'])) {
153
					$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
157
					$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
154
				} elseif($colonne['fonction']) {
158
				} elseif($colonne['fonction']) {
155
					die("méthode {$colonne['fonction']} introuvable");
159
					die("méthode {$colonne['fonction']} introuvable");
156
				}
160
				}
157
				// fonction pour obtenir des champs (étendus)
161
				// fonction pour obtenir des champs (étendus)
158
				elseif(function_exists($colonne['fonction_data'])) {
162
				elseif(function_exists($colonne['fonction_data'])) {
159
					$valeur = $colonne['fonction_data']($obs);
163
					$valeur = $colonne['fonction_data']($obs);
160
				}
164
				}
161
				elseif(method_exists(__CLASS__, $colonne['fonction_data'])) {
165
				elseif(method_exists(__CLASS__, $colonne['fonction_data'])) {
162
					$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
166
					$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
163
				}
167
				}
164
 
168
 
165
 
169
 
166
				// // cette section devrait être vide:
170
				// // cette section devrait être vide:
167
				// // cas particuliers ingérable avec l'architecture actuelle:
171
				// // cas particuliers ingérable avec l'architecture actuelle:
168
				if(false && $slug == 'date_observation' && $valeur == "0000-00-00") { /* blah */ }
172
				if(false && $slug == 'date_observation' && $valeur == "0000-00-00") { /* blah */ }
169
				// // fin de section "cas particuliers"
173
				// // fin de section "cas particuliers"
170
 
174
 
171
				$sheet->setCellValueByColumnAndRow($colid, $row, $valeur);
175
				$sheet->setCellValueByColumnAndRow($colid, $row, $valeur);
172
				$colid++;
176
				$colid++;
173
			}
177
			}
174
			$row++;
178
			$row++;
175
		}
179
		}
176
 
180
 
177
		header("Content-Type: application/vnd.ms-excel");
181
		header("Content-Type: application/vnd.ms-excel");
178
		header("Content-Disposition: attachment; filename=\"liste.xls\"; charset=utf-8");
182
		header("Content-Disposition: attachment; filename=\"liste.xls\"; charset=utf-8");
179
		header("Cache-Control: max-age=0");
183
		header("Cache-Control: max-age=0");
180
		// Le format Excel2007 utilise un fichier temporaire
184
		// Le format Excel2007 utilise un fichier temporaire
181
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
185
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
182
		// $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
186
		// $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
183
		$objWriter->save('php://output');
187
		$objWriter->save('php://output');
184
		exit;
188
		exit;
185
	}
189
	}
186
 
190
 
187
	/*
191
	/*
188
	 * @param $fieldSets: un range, eg: 1-5,8,32,58-101
192
	 * @param $fieldSets: un range, eg: 1-5,8,32,58-101
189
	 * @return un tableau trié, eg: 1,2,3,4,5,8,32,58,...,101
193
	 * @return un tableau trié, eg: 1,2,3,4,5,8,32,58,...,101
190
	 */
194
	 */
191
	static function rangeToList($in = '') {
195
	static function rangeToList($in = '') {
192
		$inSets = explode(',', $in);
196
		$inSets = explode(',', $in);
193
		$outSets = array();
197
		$outSets = array();
194
 
198
 
195
		foreach($inSets as $inSet) {
199
		foreach($inSets as $inSet) {
196
			list($start,$end) = explode('-', $inSet . '-' . $inSet);
200
			list($start,$end) = explode('-', $inSet . '-' . $inSet);
-
 
201
			// ignore les ranges trop importants
-
 
202
			if($start > 10000000 || $end > 10000000 || abs($start-$end) > 10000) continue;
197
			$outSets = array_merge($outSets,range($start,$end));
203
			$outSets = array_merge($outSets,range($start,$end));
198
		}
204
		}
199
		$outSets = array_unique($outSets);
205
		$outSets = array_unique($outSets);
200
		$outSets = array_filter($outSets, 'is_numeric');
206
		$outSets = array_filter($outSets, 'is_numeric');
201
		sort($outSets);
207
		sort($outSets);
202
		return $outSets;
208
		return $outSets;
203
	}
209
	}
204
 
210
 
205
	/*
211
	/*
206
	 * @param $fieldSets: un liste de noms de colonnes ou de sets de colonnes
212
	 * @param $fieldSets: un liste de noms de colonnes ou de sets de colonnes
207
	 *		séparés par des virgules
213
	 *		séparés par des virgules
208
	 * 		eg: "espece" ou "champs-etendus", ...
214
	 * 		eg: "espece" ou "champs-etendus", ...
209
	 *
215
	 *
210
	 * @return: un tableau associatif déjà ordonné
216
	 * @return: un tableau associatif déjà ordonné
211
	 * 		clé: slug [machine-name] de la colonne (eg: "espece" ou "mot-clef")
217
	 * 		clé: slug [machine-name] de la colonne (eg: "espece" ou "mot-clef")
212
	 * 		valeur: des données relative à cette colonne, cf GenColInfo
218
	 * 		valeur: des données relative à cette colonne, cf GenColInfo
213
	 *
219
	 *
214
	 * @TODO: fonction commune à la génération en CSV
220
	 * @TODO: fonction commune à la génération en CSV
215
	 */
221
	 */
216
	static function fieldSetsToColumns($fieldSets = 'standard') {
222
	static function fieldSetsToColumns($fieldSets = 'standard') {
217
		if(! $fieldSets) $fieldSets = 'standard';
223
		if(! $fieldSets) $fieldSets = 'standard';
218
		$fieldSets = array_flip(explode(',', $fieldSets));
224
		$fieldSets = array_flip(explode(',', $fieldSets));
219
		$colonnes = Array();
225
		$colonnes = Array();
220
 
226
 
221
		if(isset($fieldSets['standard'])) {
227
		if(isset($fieldSets['standard'])) {
222
		   $colonnes += Array(
228
		   $colonnes += Array(
223
			   'nom_sel'			=> self::GenColInfo('nom_sel', 'Espèce'),
229
			   'nom_sel'			=> self::GenColInfo('nom_sel', 'Espèce'),
224
			   'nom_sel_nn'			=> self::GenColInfo('nom_sel_nn', 'Numéro nomenclatural'),
230
			   'nom_sel_nn'			=> self::GenColInfo('nom_sel_nn', 'Numéro nomenclatural'),
225
			   'nom_ret'			=> self::GenColInfo('nom_ret', 'Nom retenu'),
231
			   'nom_ret'			=> self::GenColInfo('nom_ret', 'Nom retenu'),
226
			   'nom_ret_nn'			=> self::GenColInfo('nom_ret_nn', 'Numéro nomenclatural nom retenu'),
232
			   'nom_ret_nn'			=> self::GenColInfo('nom_ret_nn', 'Numéro nomenclatural nom retenu'),
227
			   'nt'					=> self::GenColInfo('nt', 'Numéro taxonomique'),
233
			   'nt'					=> self::GenColInfo('nt', 'Numéro taxonomique'),
228
			   'famille'			=> self::GenColInfo('famille', 'Famille'),
234
			   'famille'			=> self::GenColInfo('famille', 'Famille'),
229
			   'nom_referentiel'	=> self::GenColInfo('nom_referentiel', 'Referentiel taxonomique'),
235
			   'nom_referentiel'	=> self::GenColInfo('nom_referentiel', 'Referentiel taxonomique'),
230
			   'zone_geo'			=> self::GenColInfo('zone_geo', 'Commune'),
236
			   'zone_geo'			=> self::GenColInfo('zone_geo', 'Commune'),
231
			   'ce_zone_geo'		=> self::GenColInfo('ce_zone_geo', 'Identifiant Commune', 0, 'convertirCodeZoneGeoVersDepartement'),
237
			   'ce_zone_geo'		=> self::GenColInfo('ce_zone_geo', 'Identifiant Commune', 0, 'convertirCodeZoneGeoVersDepartement'),
232
			   'date_observation'	=> self::GenColInfo('date_observation', 'Date', 0, 'formaterDate'),
238
			   'date_observation'	=> self::GenColInfo('date_observation', 'Date', 0, 'formaterDate'),
233
			   'lieudit'			=> self::GenColInfo('lieudit', 'Lieu-dit'),
239
			   'lieudit'			=> self::GenColInfo('lieudit', 'Lieu-dit'),
234
			   'station'			=> self::GenColInfo('station', 'Station'),
240
			   'station'			=> self::GenColInfo('station', 'Station'),
235
			   'milieu'				=> self::GenColInfo('milieu', 'Milieu'),
241
			   'milieu'				=> self::GenColInfo('milieu', 'Milieu'),
236
			   'commentaire'		=> self::GenColInfo('commentaire', 'Notes'),
242
			   'commentaire'		=> self::GenColInfo('commentaire', 'Notes'),
237
			   'latitude'			=> self::GenColInfo('latitude', 'Latitude', 1),
243
			   'latitude'			=> self::GenColInfo('latitude', 'Latitude', 1),
238
			   'longitude'			=> self::GenColInfo('longitude', 'Longitude', 1),
244
			   'longitude'			=> self::GenColInfo('longitude', 'Longitude', 1),
239
			   'geodatum'			=> self::GenColInfo('geodatum', 'Référentiel Géographique', 1),
245
			   'geodatum'			=> self::GenColInfo('geodatum', 'Référentiel Géographique', 1),
240
 
246
 
241
			   'ordre'				=> self::GenColInfo('ordre', 'Ordre', 1),
247
			   'ordre'				=> self::GenColInfo('ordre', 'Ordre', 1),
242
			   'id_observation'		=> self::GenColInfo('id_observation', 'Identifiant', 1),
248
			   'id_observation'		=> self::GenColInfo('id_observation', 'Identifiant', 1),
243
 
249
 
244
			   'mots_cles_texte'	=> self::GenColInfo('mots_cles_texte', 'Mots Clés', 1),
250
			   'mots_cles_texte'	=> self::GenColInfo('mots_cles_texte', 'Mots Clés', 1),
245
			   'commentaire'		=> self::GenColInfo('commentaire', 'Commentaires', 1),
251
			   'commentaire'		=> self::GenColInfo('commentaire', 'Commentaires', 1),
246
			   'date_creation'		=> self::GenColInfo('date_creation', 'Date Création', 1),
252
			   'date_creation'		=> self::GenColInfo('date_creation', 'Date Création', 1),
247
			   'date_modification'	=> self::GenColInfo('date_modification', 'Date Modification', 1),
253
			   'date_modification'	=> self::GenColInfo('date_modification', 'Date Modification', 1),
248
			   'date_transmission'	=> self::GenColInfo('date_transmission', 'Date Transmission', 1),
254
			   'date_transmission'	=> self::GenColInfo('date_transmission', 'Date Transmission', 1),
249
			   'abondance'			=> self::GenColInfo('abondance', 'Abondance', 1),
255
			   'abondance'			=> self::GenColInfo('abondance', 'Abondance', 1),
250
			   'certitude'			=> self::GenColInfo('certitude', 'Certitude', 1),
256
			   'certitude'			=> self::GenColInfo('certitude', 'Certitude', 1),
251
			   'phenologie'			=> self::GenColInfo('phenologie', 'Phénologie', 1),
257
			   'phenologie'			=> self::GenColInfo('phenologie', 'Phénologie', 1),
252
 
258
 
253
			   'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun')
259
			   'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun')
254
			   //'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun_v2')
260
			   //'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun_v2')
255
			   //'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun_v3')
261
			   //'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun_v3')
256
		   );
262
		   );
257
		}
263
		}
258
 
264
 
259
		return $colonnes;
265
		return $colonnes;
260
	}
266
	}
261
 
267
 
262
	/*
268
	/*
263
	 * Wrapper générant un tableau associatif:
269
	 * Wrapper générant un tableau associatif:
264
	 * @param $is_extra: défini si la colonne est extra (auquelle une bordure bleue entoure son nom dans la première ligne
270
	 * @param $is_extra: défini si la colonne est extra (auquelle une bordure bleue entoure son nom dans la première ligne
265
	 * @param $fonction (optionnel): un nom d'un fonction de préprocessing
271
	 * @param $fonction (optionnel): un nom d'un fonction de préprocessing
266
	 * 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
272
	 * 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
267
	 * @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
273
	 * @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
268
	 * 		  $fonction_data doit prendre comme premier argument les champs de l'enregistrement existant
274
	 * 		  $fonction_data doit prendre comme premier argument les champs de l'enregistrement existant
269
	 *		  $fonction_data doit retourner une valeur
275
	 *		  $fonction_data doit retourner une valeur
270
 
276
 
271
	 */
277
	 */
272
	static function GenColInfo($slug, $nom, $is_extra = 0, $fonction = NULL, $fonction_data = NULL) {
278
	static function GenColInfo($slug, $nom, $is_extra = 0, $fonction = NULL, $fonction_data = NULL) {
273
		return Array('slug' => $slug,
279
		return Array('slug' => $slug,
274
					 'nom' => $nom,
280
					 'nom' => $nom,
275
					 'extra' => $is_extra ? 1 : 0,
281
					 'extra' => $is_extra ? 1 : 0,
276
					 'fonction' => $fonction,
282
					 'fonction' => $fonction,
277
					 'fonction_data' => $fonction_data
283
					 'fonction_data' => $fonction_data
278
		);
284
		);
279
	}
285
	}
280
 
286
 
281
	protected function formaterDate($date_heure_mysql, $format = NULL) {
287
	protected function formaterDate($date_heure_mysql, $format = NULL) {
282
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") return "00/00/0000";
288
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") return "00/00/0000";
283
		$timestamp = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql)->getTimestamp();
289
		$timestamp = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql)->getTimestamp();
284
		if(!$timestamp) return "00/00/0000";
290
		if(!$timestamp) return "00/00/0000";
285
		// TODO: les widget ne font malheureusement pas usage de l'heure dans le CEL
291
		// TODO: les widget ne font malheureusement pas usage de l'heure dans le CEL
286
		$date_formatee = strftime('%A %d %B %Y', $timestamp);
292
		$date_formatee = strftime('%A %d %B %Y', $timestamp);
287
		if(!$date_formatee) return "00/00/0000";
293
		if(!$date_formatee) return "00/00/0000";
288
		return $date_formatee;
294
		return $date_formatee;
289
	}
295
	}
290
 
296
 
291
 
297
 
292
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
298
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
293
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
299
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
294
	// Par exemple, la variable pour "nva" ?
300
	// Par exemple, la variable pour "nva" ?
295
	function getNomCommun($obs) {
301
	function getNomCommun($obs) {
296
		$langue = 'fra';
302
		$langue = 'fra';
297
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
303
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
298
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
304
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
299
		else return '';
305
		else return '';
300
 
306
 
301
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
307
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
302
		if(isset($this->cache['getNomCommun'][$cache_id])) {
308
		if(isset($this->cache['getNomCommun'][$cache_id])) {
303
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
309
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
304
			return $this->cache['getNomCommun'][$cache_id];
310
			return $this->cache['getNomCommun'][$cache_id];
305
		}
311
		}
306
		// pas de cache:
312
		// pas de cache:
307
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
313
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
308
 
314
 
309
		// pour bdtfx:
315
		// pour bdtfx:
310
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
316
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
311
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
317
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
312
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
318
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
313
						   Array($referentiel, $obs['nt'], $langue),
319
						   Array($referentiel, $obs['nt'], $langue),
314
						   $this->config['eflore']['url_service_nom_attribution']) .
320
						   $this->config['eflore']['url_service_nom_attribution']) .
315
			"&retour.champs=num_statut";
321
			"&retour.champs=num_statut";
316
		$noms = @json_decode(file_get_contents($url));
322
		$noms = @json_decode(file_get_contents($url));
317
		if(! $noms) return '';
323
		if(! $noms) return '';
318
		$noms = array_filter((array)($noms->resultat), function($item) { return ($item->num_statut == 1); });
324
		$noms = array_filter((array)($noms->resultat), function($item) { return ($item->num_statut == 1); });
319
		$nom = array_pop($noms)->nom_vernaculaire;
325
		$nom = array_pop($noms)->nom_vernaculaire;
320
 
326
 
321
		// cache
327
		// cache
322
		$this->cache['getNomCommun'][$cache_id] = $nom;
328
		$this->cache['getNomCommun'][$cache_id] = $nom;
323
		return $nom;
329
		return $nom;
324
	}
330
	}
325
 
331
 
326
 
332
 
327
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
333
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
328
	   NomsVernaculaires pour obtenir le nom commun */
334
	   NomsVernaculaires pour obtenir le nom commun */
329
	function getNomCommun_v2($obs) {
335
	function getNomCommun_v2($obs) {
330
		static $service;
336
		static $service;
331
		$service = new Projets();
337
		$service = new Projets();
332
 
338
 
333
		$langue = 'fra';
339
		$langue = 'fra';
334
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
340
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
335
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
341
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
336
		else return '';
342
		else return '';
337
 
343
 
338
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
344
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
339
		if(isset($this->cache['getNomCommun'][$cache_id])) {
345
		if(isset($this->cache['getNomCommun'][$cache_id])) {
340
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
346
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
341
			return $this->cache['getNomCommun'][$cache_id];
347
			return $this->cache['getNomCommun'][$cache_id];
342
		}
348
		}
343
		// pas de cache:
349
		// pas de cache:
344
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
350
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
345
 
351
 
346
		$data = Array('masque.nt' => $obs['nt'],
352
		$data = Array('masque.nt' => $obs['nt'],
347
							 'masque.lg' => $langue,
353
							 'masque.lg' => $langue,
348
							 'retour.champs' => 'num_statut');
354
							 'retour.champs' => 'num_statut');
349
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $data);
355
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $data);
350
 
356
 
351
		if(! $noms) return '';
357
		if(! $noms) return '';
352
		$noms = array_filter((array)($noms->resultat), function($item) { return ($item->num_statut == 1); });
358
		$noms = array_filter((array)($noms->resultat), function($item) { return ($item->num_statut == 1); });
353
		$nom = array_pop($noms)->nom_vernaculaire;
359
		$nom = array_pop($noms)->nom_vernaculaire;
354
 
360
 
355
		// cache
361
		// cache
356
		$this->cache['getNomCommun'][$cache_id] = $nom;
362
		$this->cache['getNomCommun'][$cache_id] = $nom;
357
		return $nom;
363
		return $nom;
358
	}
364
	}
359
 
365
 
360
 
366
 
361
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
367
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
362
	   n'est pas aussi retentissant qu'espéré */
368
	   n'est pas aussi retentissant qu'espéré */
363
	static $service;
369
	static $service;
364
	function getNomCommun_v3($obs) {
370
	function getNomCommun_v3($obs) {
365
		if(! $this->service) $this->service = new Projets();
371
		if(! $this->service) $this->service = new Projets();
366
 
372
 
367
		$langue = 'fra';
373
		$langue = 'fra';
368
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
374
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
369
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
375
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
370
		else return '';
376
		else return '';
371
 
377
 
372
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
378
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
373
		if(isset($this->cache['getNomCommun'][$cache_id])) {
379
		if(isset($this->cache['getNomCommun'][$cache_id])) {
374
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
380
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
375
			return $this->cache['getNomCommun'][$cache_id];
381
			return $this->cache['getNomCommun'][$cache_id];
376
		}
382
		}
377
		// pas de cache:
383
		// pas de cache:
378
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
384
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
379
 
385
 
380
		$data = Array('masque.nt' => $obs['nt'],
386
		$data = Array('masque.nt' => $obs['nt'],
381
					  'masque.lg' => $langue,
387
					  'masque.lg' => $langue,
382
					  'retour.champs' => 'conseil_emploi');
388
					  'retour.champs' => 'conseil_emploi');
383
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $data);
389
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $data);
384
		try {
390
		try {
385
			$noms = $this->service->traiterRessources();
391
			$noms = $this->service->traiterRessources();
386
		} catch(Exception $e) { return ''; }
392
		} catch(Exception $e) { return ''; }
387
		if(! $noms) return '';
393
		if(! $noms) return '';
388
		$noms = array_filter($noms['resultat'], function($item) { return ($item['num_statut'] == 1); });
394
		$noms = array_filter($noms['resultat'], function($item) { return ($item['num_statut'] == 1); });
389
		$nom = array_pop($noms)['nom_vernaculaire'];
395
		$nom = array_pop($noms)['nom_vernaculaire'];
390
 
396
 
391
		// cache
397
		// cache
392
		$this->cache['getNomCommun'][$cache_id] = $nom;
398
		$this->cache['getNomCommun'][$cache_id] = $nom;
393
		return $nom;
399
		return $nom;
394
	}
400
	}
395
 
401
 
396
}
402
}