Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
1374 aurelien 1
<?php
2
/**
3
* Service fournissant des informations concernant le CEL au format RSS1, RSS2 ou ATOM.
4
* Encodage en entrée : utf8
5
* Encodage en sortie : utf8
6
* Format du service :
7
* /CelWidgetExport/format
8
* /CelWidgetExport/csv
9
*
10
* Les paramêtres :
11
*  - "start" indique le numéro du premier item à afficher
12
*  - "limit" nombre d'items à afficher
13
*
14
* @author Aurélien Peronnet <aurelien@tela-botanica.org>
15
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
16
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
17
* @version $Id$
18
* @copyright 2012
19
*/
1610 raphael 20
 
21
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(dirname(realpath(__FILE__))) . '/lib');
22
// la sortie est binaire (xls), mais OLE n'est pas compatible E_ALL en PHP-5.4
1700 raphael 23
error_reporting(error_reporting() & ~E_STRICT);
1610 raphael 24
require_once("lib/OLE.php");
25
require_once("lib/Spreadsheet/Excel/Writer.php");
26
 
1374 aurelien 27
class CelWidgetExport extends Cel {
28
 
1408 aurelien 29
	private $nom_fichier_export = 'cel_export';
1671 aurelien 30
	// certains paramètres apparaissent plusieurs fois car ils ont des alias
31
	// dans certains widgets
1376 aurelien 32
	private $parametres_autorises = array(
1654 aurelien 33
		'id_utilisateur' => 'ce_utilisateur',
1376 aurelien 34
		'utilisateur' => 'courriel_utilisateur',
35
		'commune' => 'zone_geo',
1671 aurelien 36
		'zone_geo' => 'zone_geo',
1376 aurelien 37
		'dept' => 'departement',
1654 aurelien 38
		'departement' => 'departement',
39
		'lieudit' => 'lieudit',
40
		'station' => 'station',
1376 aurelien 41
		'projet' => 'mots_cles',
1379 aurelien 42
		'num_taxon' => 'nt',
1378 aurelien 43
		'date_debut' => 'date_debut',
1387 aurelien 44
		'date_fin' => 'date_fin',
1625 aurelien 45
		'taxon' => 'taxon',
1654 aurelien 46
		'annee' => 'annee',
47
		'mois' => 'mois',
48
		'jour' => 'jour',
49
		'recherche' => 'recherche',
50
		'id_mots_cles' => 'id_mots_cles',
1662 aurelien 51
		'mots_cles' => 'mots_cles',
1625 aurelien 52
		'debut' => 'debut',
53
		'limite' => 'limite',
1654 aurelien 54
		'format' => 'format',
55
		'colonnes' => 'colonnes',
1679 raphael 56
		'transmission' => 'transmission',
57
		'obsids' => 'obsids',
1376 aurelien 58
	);
1402 aurelien 59
 
1625 aurelien 60
	private $limite_decoupage_defaut = 9000;
61
 
1402 aurelien 62
	private $format = 'csv';
1579 aurelien 63
 
1659 aurelien 64
	public $id_utilisateur = null;
65
 
1579 aurelien 66
	public function getRessource() {
67
		return $this->getElement(array());
68
	}
1374 aurelien 69
 
70
	/**
71
	 * Méthode appelée avec une requête de type GET.
72
	 */
1709 raphael 73
	public function getElement($params = array()) {
1711 raphael 74
		switch(@strtolower($params[0])) {
1709 raphael 75
		case 'calcul':
76
			$this->getCalcul();
77
			break;
1625 aurelien 78
 
1709 raphael 79
		case 'export':
80
			$this->getExport();
81
			break;
82
		default:
1625 aurelien 83
			$this->getExport();
84
		}
85
	}
86
 
87
	private function getCalcul() {
1611 raphael 88
		$criteres = $this->traiterParametresAutorises($_GET);
1654 aurelien 89
 
1374 aurelien 90
		$criteres['transmission'] = 1;
1654 aurelien 91
		if($this->doitEtPeutExporterObsPrivees($criteres)) {
92
			unset($criteres['transmission']);
1659 aurelien 93
			$this->id_utilisateur = $criteres['id_utilisateur'];
1654 aurelien 94
		}
1374 aurelien 95
		$chercheur_observations = new RechercheObservation($this->config);
96
 
1379 aurelien 97
		$numero_page = isset($criteres['debut']) ? $criteres['debut'] : 0;
98
		$limite = isset($criteres['limite']) ? $criteres['limite'] : 0;
1654 aurelien 99
		$colonnes = isset($criteres['colonnes']) ? $criteres['colonnes'] : 'standard,avance';
1374 aurelien 100
 
101
		unset($criteres['limite']);
102
		unset($criteres['debut']);
1625 aurelien 103
		unset($criteres['format']);
1654 aurelien 104
		unset($criteres['colonnes']);
1625 aurelien 105
 
106
		$nb_observations = $chercheur_observations->compterObservations(null, $criteres);
107
		$limite_decoupage = $this->calculerNbLignesMaxParFichier();
108
 
109
		$url_telechargements = array();
110
		$intervalle = 0;
111
 
112
		$params_url = $criteres;
113
		unset($params_url['transmission']);
114
		do {
115
			$base_url = $this->config['settings']['baseURLAbsolu'].'CelWidgetExport/export';
116
			$params_url['debut'] = $intervalle;
117
			$params_url['limite'] = $limite_decoupage;
118
			$url_telechargement_fichier = $base_url;
1654 aurelien 119
			$url_telechargements[] = $base_url.'?'.http_build_query($params_url).'&format='.$this->format.'&colonnes='.$colonnes;
1625 aurelien 120
			$intervalle += $limite_decoupage;
121
			$nb_observations -= $limite_decoupage;
122
		} while($nb_observations >= $limite_decoupage);
123
 
124
		$this->envoyerJson($url_telechargements);
125
	}
1374 aurelien 126
 
1625 aurelien 127
	private function calculerNbLignesMaxParFichier() {
128
		$limite = $this->limite_decoupage_defaut;
1402 aurelien 129
		switch($this->format) {
130
			case 'csv':
1625 aurelien 131
				$limite = 20000;
132
				break;
133
			case 'xls':
134
				$limite = 8000;
135
				break;
1660 raphael 136
			case 'pdf':
137
				$limite = 300;
138
				break;
1625 aurelien 139
		}
140
		return $limite;
141
	}
142
 
143
	private function getExport() {
144
		$criteres = $this->traiterParametresAutorises($_GET);
1711 raphael 145
		// ne pas faire de super-requête en cas d'absence de paramètres
146
		// par exemple "format", au minimum, devrait être défini
147
		if(!$criteres) die('pas de paramètre reçu');
148
 
1625 aurelien 149
		$criteres['transmission'] = 1;
1654 aurelien 150
		if($this->doitEtPeutExporterObsPrivees($criteres)) {
151
			unset($criteres['transmission']);
152
		}
1625 aurelien 153
		$chercheur_observations = new RechercheObservation($this->config);
154
 
1679 raphael 155
		$debut = isset($criteres['debut']) ? intval($criteres['debut']) : 0;
156
		$limite = isset($criteres['limite']) ? intval($criteres['limite']) : 0;
1711 raphael 157
		$groupes = isset($criteres['colonnes']) ? $criteres['colonnes'] : 'standard,avance';
1679 raphael 158
 
159
		if($criteres['obsids']) $criteres['sql_brut'] = sprintf('id_observation IN (%s)',
160
																implode(',', $criteres['obsids']));
1625 aurelien 161
 
162
		unset($criteres['limite']);
163
		unset($criteres['debut']);
164
		unset($criteres['format']);
1654 aurelien 165
		unset($criteres['colonnes']);
1679 raphael 166
		unset($criteres['obsids']);
167
 
168
		$observations = $chercheur_observations->rechercherObservations(null, $criteres, $debut, $limite, TRUE)->get();
1659 aurelien 169
		$ids = array();
170
		foreach($observations as &$obs) {
171
			$ids[] = $obs['id_observation'];
172
		}
173
 
1703 raphael 174
		if($this->format == 'pdf') {
175
			$pdf = $this->convertirEnPdf($observations);
176
			$pdf->pdf->Output('etiquettes.pdf', 'I');
177
			exit;
1662 aurelien 178
		}
179
 
1703 raphael 180
		// cas XLS et CSV: on peut avoir besoin des champs étendus, des noms communs et des champs baseflor:
181
 
182
		// 1) champs étendus
183
		$gestion_champs_etendus = new GestionChampsEtendus($this->config, 'obs');
184
		$champs_supp_par_obs = $gestion_champs_etendus->consulterParLots($ids);
185
		$colonnes_champs_supp_par_obs = $gestion_champs_etendus->consulterClesParLots($ids);
186
 
187
		// 2) nom communs
188
		// $cache pourrait être utilisé par les fonctions de colonnes
189
		// * Pour "nom commun", "preload" retourne NULL, car c'est le cache statique de FormateurGroupeColonne
190
		// qu'il initialise et utilise en interne sans qu'un passage par paramètre ne soit nécessaire
1711 raphael 191
		$colonnes = FormateurGroupeColonne::nomEnsembleVersListeColonnes($groupes);
192
		if(!$colonnes) die('ne peut identifier les groupes de champs demandés');
193
		$cache = FormateurGroupeColonne::preload($colonnes, $this, $ids);
1703 raphael 194
 
1659 aurelien 195
    	// TODO: tous les champs étendus et les paramètres supplémentaires devraient être passés en un seul
196
    	// tableau (et chaque formateur csv, xls etc... pourrait également être dans une classe à part)
1625 aurelien 197
		switch($this->format) {
1660 raphael 198
		case 'csv':
199
			$csv = $this->convertirEnCsv($observations, $colonnes, $colonnes_champs_supp_par_obs, $champs_supp_par_obs);
200
			$this->envoyerCsv($csv);
201
			break;
202
		case 'xls':
203
			$xls = $this->convertirEnXls($observations, $colonnes, $colonnes_champs_supp_par_obs, $champs_supp_par_obs);
204
			$this->envoyerXls($xls);
205
			break;
206
		default:
1402 aurelien 207
		}
1374 aurelien 208
	}
209
 
1611 raphael 210
	protected function traiterParametresAutorises(Array $parametres) {
1376 aurelien 211
		$parametres_traites = array();
1402 aurelien 212
		$this->format = (isset($parametres['format']) && $parametres['format'] != '') ? $parametres['format'] : $this->format;
1376 aurelien 213
		foreach($parametres as $cle => $valeur) {
1711 raphael 214
			if(is_string($valeur) && !trim($valeur)) continue;
215
			if(isset($this->parametres_autorises[$cle])) {
1376 aurelien 216
				$parametres_traites[$this->parametres_autorises[$cle]] = $valeur;
217
			}
218
		}
1679 raphael 219
		$parametres_traites['obsids'] = @self::traiterObsIds($parametres['obsids']);
1376 aurelien 220
		return $parametres_traites;
221
	}
222
 
1374 aurelien 223
	private function envoyerCsv($csv) {
224
		header('Content-Type: text/csv; charset=UTF-8');
1408 aurelien 225
		header('Content-Disposition: attachment;filename='.$this->nom_fichier_export.'.csv');
1374 aurelien 226
		echo $csv;
1376 aurelien 227
		exit;
1374 aurelien 228
	}
229
 
1402 aurelien 230
	private function envoyerXls($workbook) {
231
		$workbook->close();
232
		exit;
233
	}
234
 
1711 raphael 235
	private function convertirEnCsv(&$data, $colonnes, &$colonnes_supplementaires, &$champs_supplementaires = array()) {
1374 aurelien 236
		$chemin_temp = "php://temp";
237
		$outstream = fopen($chemin_temp, 'r+');
1690 raphael 238
 
1711 raphael 239
		$intitule_champs = array_merge(FormateurGroupeColonne::getIntitulesColonnes($colonnes));
1703 raphael 240
		// en premier car utilisé génériquement dans getLigneObservation()
1711 raphael 241
		if(isset($colonnes['baseflor'])) {
1703 raphael 242
			$intitule_champs = array_merge($intitule_champs, FormateurGroupeColonne::$baseflor_col);
243
		}
244
		// en second car manuellement appellé plus bas, TODO: utiliser l'API du FormateurGroupeColonne
245
		$intitule_champs = array_merge($intitule_champs, array_values($colonnes_supplementaires));
1690 raphael 246
 
247
		// header
248
		fputcsv($outstream, $intitule_champs, ',', '"');
249
		// lignes
1617 aurelien 250
		foreach($data as &$ligne) {
1659 aurelien 251
			$id_obs = $ligne['id_observation'];
1692 raphael 252
			$ligne = self::filtrerDonneesSensibles($ligne);
1711 raphael 253
			$ligne = FormateurGroupeColonne::getLigneObservation($ligne, $colonnes, $this);
1690 raphael 254
			$ligne_etendue_aplatie = self::aplatirChampsEtendus($champs_supplementaires[$id_obs]);
255
			self::traiterLigneEtendue($ligne, $colonnes_supplementaires, $ligne_etendue_aplatie);
1374 aurelien 256
			fputcsv($outstream, $ligne, ',', '"');
257
		}
258
		rewind($outstream);
259
		$csv = stream_get_contents($outstream);
260
		fclose($outstream);
261
		return $csv;
262
	}
263
 
1711 raphael 264
	private function convertirEnXls(&$data, $colonnes, &$colonnes_supplementaires, &$champs_supplementaires = array()) {
1402 aurelien 265
		$this->extendSpreadsheetProductor = new SpreadsheetProductor();
266
		$this->extendSpreadsheetProductor->initSpreadsheet();
267
 
268
		$workbook = new Spreadsheet_Excel_Writer();
1625 aurelien 269
		$worksheet = $workbook->addWorksheet('Liste');
270
		$workbook->setTempDir($this->config['cel']['chemin_stockage_temp']);
1612 raphael 271
		$workbook->setVersion(8);
1402 aurelien 272
 
1612 raphael 273
		$worksheet->setInputEncoding('utf-8');
1408 aurelien 274
		$workbook->send($this->nom_fichier_export.'.xls');
1402 aurelien 275
 
276
		$nb_lignes = 1;
1690 raphael 277
 
1711 raphael 278
		$intitule_champs = array_merge(FormateurGroupeColonne::getIntitulesColonnes($colonnes));
1703 raphael 279
		// en premier car utilisé génériquement dans getLigneObservation()
1711 raphael 280
		if(isset($colonnes['baseflor'])) {
1703 raphael 281
			$intitule_champs = array_merge($intitule_champs, FormateurGroupeColonne::$baseflor_col);
282
		}
283
		// en second car manuellement appellé plus bas, TODO: utiliser l'API du FormateurGroupeColonne
284
		$intitule_champs = array_merge($intitule_champs, array_values($colonnes_supplementaires));
285
 
1690 raphael 286
		// header
287
		$indice = 0;
288
		foreach ($intitule_champs as &$intitule) {
1692 raphael 289
			$worksheet->write(0,$indice++,$intitule);
1690 raphael 290
		}
291
 
1617 aurelien 292
		foreach($data as &$ligne) {
1659 aurelien 293
			$id_obs = $ligne['id_observation'];
1692 raphael 294
			$ligne = self::filtrerDonneesSensibles($ligne);
1711 raphael 295
			$ligne = FormateurGroupeColonne::getLigneObservation($ligne, $colonnes, $this);
1690 raphael 296
 
297
			$ligne_etendue_aplatie = self::aplatirChampsEtendus($champs_supplementaires[$id_obs]);
298
			$ligne_supp = self::traiterLigneEtendue($ligne, $colonnes_supplementaires, $ligne_etendue_aplatie);
1402 aurelien 299
			$indice = 0;
1617 aurelien 300
			foreach($ligne as &$champ) {
1692 raphael 301
				$worksheet->write($nb_lignes,$indice++,$champ);
1402 aurelien 302
			}
303
			$nb_lignes++;
304
		}
305
		return $workbook;
306
	}
307
 
1662 aurelien 308
	private function convertirEnPdf(&$observations) {
309
		if(count($observations) > 300) die('trop de données');
310
		//require_once('GenerateurPDF.php');
311
		$pdf = new GenerateurPDF();
312
		$pdf->export($observations);
313
		return $pdf;
314
	}
315
 
1690 raphael 316
	static function traiterLigneEtendue(&$ligne, &$colonnes_etendues, $ligne_etendue_aplatie) {
317
		if(! $colonnes_etendues) return;
318
		if(! $ligne_etendue_aplatie) return;
319
		$nb_colonnes_supp = count($colonnes_etendues);
320
 
321
		$ligne_supp = array_fill(0, $nb_colonnes_supp, '');
1659 aurelien 322
		$ligne_etendue_fmt = array();
1690 raphael 323
 
1659 aurelien 324
		foreach($colonnes_etendues as $colonne) {
325
			if(!isset($ligne_etendue_aplatie[$colonne])) {
326
				$ligne_etendue_fmt[$colonne] = '';
327
			} else {
328
				$ligne_etendue_fmt[$colonne] = $ligne_etendue_aplatie[$colonne];
329
			}
330
		}
1690 raphael 331
 
332
		$ligne += $ligne_etendue_fmt;
1659 aurelien 333
	}
1703 raphael 334
 
1690 raphael 335
	static function aplatirChampsEtendus(&$ligne_champs_etendus) {
1659 aurelien 336
		$champs_etendus_fmt = array();
1695 raphael 337
		if(!$ligne_champs_etendus) return $champs_etendus_fmt;
1659 aurelien 338
		foreach($ligne_champs_etendus as $champ) {
339
			$champs_etendus_fmt[$champ->cle] = $champ->valeur;
340
		}
341
		return $champs_etendus_fmt;
342
	}
343
 
1692 raphael 344
	static function filtrerDonneesSensibles($ligne) {
1429 aurelien 345
		if(stripos($ligne['mots_cles_texte'], 'sensible') !== false) {
346
			$ligne['latitude'] = '';
347
			$ligne['longitude'] = '';
348
		}
349
		return $ligne;
350
	}
351
 
1654 aurelien 352
	private function doitEtPeutExporterObsPrivees($criteres) {
353
		return isset($criteres['ce_utilisateur']) &&
354
					$this->peutExporterObsPrivees($criteres['ce_utilisateur']);
355
	}
356
 
357
	private function peutExporterObsPrivees($id_utilisateur) {
358
		$gestion_utilisateur = new User($this->config);
359
		$utilisateur = $gestion_utilisateur->obtenirIdentiteConnectee();
1703 raphael 360
		return ! empty($utilisateur['id_utilisateur']) && $id_utilisateur == $utilisateur['id_utilisateur'];
1654 aurelien 361
	}
1679 raphael 362
 
363
	static function traiterObsIds($range_param) {
364
		if (!isset($range_param)) return NULL;
365
		// trim() car: `POST http://url<<<"range=*"`
366
		if (trim($range_param) == '*') return NULL;
367
		return self::rangeToList(trim($range_param));
368
	}
369
 
370
	/*
371
	 * @param $fieldSets: un range, eg: 1-5,8,32,58-101
372
	 * @return un tableau trié, eg: 1,2,3,4,5,8,32,58,...,101
373
	 * http://stackoverflow.com/questions/7698664/converting-a-range-or-partial-array-in-the-form-3-6-or-3-6-12-into-an-arra
374
	 */
375
	static function rangeToList($in = '') {
376
		$inSets = explode(',', trim($in, ','));
377
		$outSets = array();
378
 
379
		foreach($inSets as $inSet) {
380
			list($start,$end) = explode('-', $inSet . '-' . $inSet);
381
			// ignore les ranges trop importants
382
			if($start > 10000000 || $end > 10000000 || abs($start-$end) > 10000) continue;
383
			$outSets = array_merge($outSets,range($start,$end));
384
		}
385
		$outSets = array_unique($outSets);
386
		$outSets = array_filter($outSets, 'is_numeric');
387
		sort($outSets);
388
		return $outSets;
389
	}
1374 aurelien 390
}
391
?>