Subversion Repositories eFlore/Applications.cel

Rev

Rev 1711 | Rev 1715 | 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;
1714 raphael 99
		$colonnes = @FormateurGroupeColonne::colGroupsValidation($criteres['colonnes']);
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;
1714 raphael 157
		$groupes = @FormateurGroupeColonne::colGroupsValidation($criteres['colonnes']);
158
		if(!$groupes) die('erreur: Ne peut identifier les groupes de champs demandés.');
1679 raphael 159
 
1714 raphael 160
 
1679 raphael 161
		if($criteres['obsids']) $criteres['sql_brut'] = sprintf('id_observation IN (%s)',
162
																implode(',', $criteres['obsids']));
1625 aurelien 163
 
164
		unset($criteres['limite']);
165
		unset($criteres['debut']);
166
		unset($criteres['format']);
1654 aurelien 167
		unset($criteres['colonnes']);
1679 raphael 168
		unset($criteres['obsids']);
169
 
170
		$observations = $chercheur_observations->rechercherObservations(null, $criteres, $debut, $limite, TRUE)->get();
1659 aurelien 171
		$ids = array();
172
		foreach($observations as &$obs) {
173
			$ids[] = $obs['id_observation'];
174
		}
175
 
1703 raphael 176
		if($this->format == 'pdf') {
177
			$pdf = $this->convertirEnPdf($observations);
178
			$pdf->pdf->Output('etiquettes.pdf', 'I');
179
			exit;
1662 aurelien 180
		}
181
 
1703 raphael 182
		// cas XLS et CSV: on peut avoir besoin des champs étendus, des noms communs et des champs baseflor:
1714 raphael 183
		// 0) obtention des colonnes correspondantes aux groupes de champs
184
		$colonnes = FormateurGroupeColonne::nomEnsembleVersListeColonnes($groupes);
1703 raphael 185
 
1714 raphael 186
		// 1) champs étendus, si demandés
187
		$colonnes_champs_supp_par_obs = $champs_supp_par_obs = array();
188
		if(isset($colonnes['etendu'])) {
189
			$gestion_champs_etendus = new GestionChampsEtendus($this->config, 'obs');
190
			$champs_supp_par_obs = $gestion_champs_etendus->consulterParLots($ids);
191
			$colonnes_champs_supp_par_obs = $gestion_champs_etendus->consulterClesParLots($ids);
192
		}
1703 raphael 193
 
194
		// 2) nom communs
195
		// $cache pourrait être utilisé par les fonctions de colonnes
196
		// * Pour "nom commun", "preload" retourne NULL, car c'est le cache statique de FormateurGroupeColonne
197
		// qu'il initialise et utilise en interne sans qu'un passage par paramètre ne soit nécessaire
1711 raphael 198
		$cache = FormateurGroupeColonne::preload($colonnes, $this, $ids);
1703 raphael 199
 
1659 aurelien 200
    	// TODO: tous les champs étendus et les paramètres supplémentaires devraient être passés en un seul
201
    	// tableau (et chaque formateur csv, xls etc... pourrait également être dans une classe à part)
1625 aurelien 202
		switch($this->format) {
1660 raphael 203
		case 'csv':
204
			$csv = $this->convertirEnCsv($observations, $colonnes, $colonnes_champs_supp_par_obs, $champs_supp_par_obs);
205
			$this->envoyerCsv($csv);
206
			break;
207
		case 'xls':
208
			$xls = $this->convertirEnXls($observations, $colonnes, $colonnes_champs_supp_par_obs, $champs_supp_par_obs);
209
			$this->envoyerXls($xls);
210
			break;
211
		default:
1402 aurelien 212
		}
1374 aurelien 213
	}
214
 
1611 raphael 215
	protected function traiterParametresAutorises(Array $parametres) {
1376 aurelien 216
		$parametres_traites = array();
1402 aurelien 217
		$this->format = (isset($parametres['format']) && $parametres['format'] != '') ? $parametres['format'] : $this->format;
1376 aurelien 218
		foreach($parametres as $cle => $valeur) {
1711 raphael 219
			if(is_string($valeur) && !trim($valeur)) continue;
220
			if(isset($this->parametres_autorises[$cle])) {
1376 aurelien 221
				$parametres_traites[$this->parametres_autorises[$cle]] = $valeur;
222
			}
223
		}
1679 raphael 224
		$parametres_traites['obsids'] = @self::traiterObsIds($parametres['obsids']);
1376 aurelien 225
		return $parametres_traites;
226
	}
227
 
1374 aurelien 228
	private function envoyerCsv($csv) {
229
		header('Content-Type: text/csv; charset=UTF-8');
1408 aurelien 230
		header('Content-Disposition: attachment;filename='.$this->nom_fichier_export.'.csv');
1374 aurelien 231
		echo $csv;
1376 aurelien 232
		exit;
1374 aurelien 233
	}
234
 
1402 aurelien 235
	private function envoyerXls($workbook) {
236
		$workbook->close();
237
		exit;
238
	}
239
 
1711 raphael 240
	private function convertirEnCsv(&$data, $colonnes, &$colonnes_supplementaires, &$champs_supplementaires = array()) {
1374 aurelien 241
		$chemin_temp = "php://temp";
242
		$outstream = fopen($chemin_temp, 'r+');
1690 raphael 243
 
1711 raphael 244
		$intitule_champs = array_merge(FormateurGroupeColonne::getIntitulesColonnes($colonnes));
1703 raphael 245
		// en premier car utilisé génériquement dans getLigneObservation()
1711 raphael 246
		if(isset($colonnes['baseflor'])) {
1703 raphael 247
			$intitule_champs = array_merge($intitule_champs, FormateurGroupeColonne::$baseflor_col);
248
		}
249
		// en second car manuellement appellé plus bas, TODO: utiliser l'API du FormateurGroupeColonne
250
		$intitule_champs = array_merge($intitule_champs, array_values($colonnes_supplementaires));
1690 raphael 251
 
252
		// header
253
		fputcsv($outstream, $intitule_champs, ',', '"');
254
		// lignes
1617 aurelien 255
		foreach($data as &$ligne) {
1659 aurelien 256
			$id_obs = $ligne['id_observation'];
1692 raphael 257
			$ligne = self::filtrerDonneesSensibles($ligne);
1711 raphael 258
			$ligne = FormateurGroupeColonne::getLigneObservation($ligne, $colonnes, $this);
1690 raphael 259
			$ligne_etendue_aplatie = self::aplatirChampsEtendus($champs_supplementaires[$id_obs]);
260
			self::traiterLigneEtendue($ligne, $colonnes_supplementaires, $ligne_etendue_aplatie);
1374 aurelien 261
			fputcsv($outstream, $ligne, ',', '"');
262
		}
263
		rewind($outstream);
264
		$csv = stream_get_contents($outstream);
265
		fclose($outstream);
266
		return $csv;
267
	}
268
 
1711 raphael 269
	private function convertirEnXls(&$data, $colonnes, &$colonnes_supplementaires, &$champs_supplementaires = array()) {
1402 aurelien 270
		$this->extendSpreadsheetProductor = new SpreadsheetProductor();
271
		$this->extendSpreadsheetProductor->initSpreadsheet();
272
 
273
		$workbook = new Spreadsheet_Excel_Writer();
1625 aurelien 274
		$worksheet = $workbook->addWorksheet('Liste');
275
		$workbook->setTempDir($this->config['cel']['chemin_stockage_temp']);
1612 raphael 276
		$workbook->setVersion(8);
1402 aurelien 277
 
1612 raphael 278
		$worksheet->setInputEncoding('utf-8');
1408 aurelien 279
		$workbook->send($this->nom_fichier_export.'.xls');
1402 aurelien 280
 
281
		$nb_lignes = 1;
1690 raphael 282
 
1711 raphael 283
		$intitule_champs = array_merge(FormateurGroupeColonne::getIntitulesColonnes($colonnes));
1703 raphael 284
		// en premier car utilisé génériquement dans getLigneObservation()
1711 raphael 285
		if(isset($colonnes['baseflor'])) {
1703 raphael 286
			$intitule_champs = array_merge($intitule_champs, FormateurGroupeColonne::$baseflor_col);
287
		}
288
		// en second car manuellement appellé plus bas, TODO: utiliser l'API du FormateurGroupeColonne
289
		$intitule_champs = array_merge($intitule_champs, array_values($colonnes_supplementaires));
290
 
1690 raphael 291
		// header
292
		$indice = 0;
293
		foreach ($intitule_champs as &$intitule) {
1692 raphael 294
			$worksheet->write(0,$indice++,$intitule);
1690 raphael 295
		}
296
 
1617 aurelien 297
		foreach($data as &$ligne) {
1659 aurelien 298
			$id_obs = $ligne['id_observation'];
1692 raphael 299
			$ligne = self::filtrerDonneesSensibles($ligne);
1711 raphael 300
			$ligne = FormateurGroupeColonne::getLigneObservation($ligne, $colonnes, $this);
1690 raphael 301
 
302
			$ligne_etendue_aplatie = self::aplatirChampsEtendus($champs_supplementaires[$id_obs]);
303
			$ligne_supp = self::traiterLigneEtendue($ligne, $colonnes_supplementaires, $ligne_etendue_aplatie);
1402 aurelien 304
			$indice = 0;
1617 aurelien 305
			foreach($ligne as &$champ) {
1692 raphael 306
				$worksheet->write($nb_lignes,$indice++,$champ);
1402 aurelien 307
			}
308
			$nb_lignes++;
309
		}
310
		return $workbook;
311
	}
312
 
1662 aurelien 313
	private function convertirEnPdf(&$observations) {
314
		if(count($observations) > 300) die('trop de données');
315
		//require_once('GenerateurPDF.php');
316
		$pdf = new GenerateurPDF();
317
		$pdf->export($observations);
318
		return $pdf;
319
	}
320
 
1690 raphael 321
	static function traiterLigneEtendue(&$ligne, &$colonnes_etendues, $ligne_etendue_aplatie) {
322
		if(! $colonnes_etendues) return;
323
		if(! $ligne_etendue_aplatie) return;
324
		$nb_colonnes_supp = count($colonnes_etendues);
325
 
326
		$ligne_supp = array_fill(0, $nb_colonnes_supp, '');
1659 aurelien 327
		$ligne_etendue_fmt = array();
1690 raphael 328
 
1659 aurelien 329
		foreach($colonnes_etendues as $colonne) {
330
			if(!isset($ligne_etendue_aplatie[$colonne])) {
331
				$ligne_etendue_fmt[$colonne] = '';
332
			} else {
333
				$ligne_etendue_fmt[$colonne] = $ligne_etendue_aplatie[$colonne];
334
			}
335
		}
1690 raphael 336
 
337
		$ligne += $ligne_etendue_fmt;
1659 aurelien 338
	}
1703 raphael 339
 
1690 raphael 340
	static function aplatirChampsEtendus(&$ligne_champs_etendus) {
1659 aurelien 341
		$champs_etendus_fmt = array();
1695 raphael 342
		if(!$ligne_champs_etendus) return $champs_etendus_fmt;
1659 aurelien 343
		foreach($ligne_champs_etendus as $champ) {
344
			$champs_etendus_fmt[$champ->cle] = $champ->valeur;
345
		}
346
		return $champs_etendus_fmt;
347
	}
348
 
1692 raphael 349
	static function filtrerDonneesSensibles($ligne) {
1429 aurelien 350
		if(stripos($ligne['mots_cles_texte'], 'sensible') !== false) {
351
			$ligne['latitude'] = '';
352
			$ligne['longitude'] = '';
353
		}
354
		return $ligne;
355
	}
356
 
1654 aurelien 357
	private function doitEtPeutExporterObsPrivees($criteres) {
358
		return isset($criteres['ce_utilisateur']) &&
359
					$this->peutExporterObsPrivees($criteres['ce_utilisateur']);
360
	}
361
 
362
	private function peutExporterObsPrivees($id_utilisateur) {
363
		$gestion_utilisateur = new User($this->config);
364
		$utilisateur = $gestion_utilisateur->obtenirIdentiteConnectee();
1703 raphael 365
		return ! empty($utilisateur['id_utilisateur']) && $id_utilisateur == $utilisateur['id_utilisateur'];
1654 aurelien 366
	}
1679 raphael 367
 
368
	static function traiterObsIds($range_param) {
369
		if (!isset($range_param)) return NULL;
370
		// trim() car: `POST http://url<<<"range=*"`
371
		if (trim($range_param) == '*') return NULL;
372
		return self::rangeToList(trim($range_param));
373
	}
374
 
375
	/*
376
	 * @param $fieldSets: un range, eg: 1-5,8,32,58-101
377
	 * @return un tableau trié, eg: 1,2,3,4,5,8,32,58,...,101
378
	 * http://stackoverflow.com/questions/7698664/converting-a-range-or-partial-array-in-the-form-3-6-or-3-6-12-into-an-arra
379
	 */
380
	static function rangeToList($in = '') {
381
		$inSets = explode(',', trim($in, ','));
382
		$outSets = array();
383
 
384
		foreach($inSets as $inSet) {
385
			list($start,$end) = explode('-', $inSet . '-' . $inSet);
386
			// ignore les ranges trop importants
387
			if($start > 10000000 || $end > 10000000 || abs($start-$end) > 10000) continue;
388
			$outSets = array_merge($outSets,range($start,$end));
389
		}
390
		$outSets = array_unique($outSets);
391
		$outSets = array_filter($outSets, 'is_numeric');
392
		sort($outSets);
393
		return $outSets;
394
	}
1374 aurelien 395
}
396
?>