Subversion Repositories eFlore/Applications.cel

Rev

Rev 1634 | Rev 1638 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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