Subversion Repositories eFlore/Applications.cel

Rev

Rev 1632 | Rev 1634 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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