Subversion Repositories eFlore/Projets.eflore-projets

Rev

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

Rev Author Line No. Line
255 jpm 1
<?php
2
// declare(encoding='UTF-8');
3
/**
4
* Gère le sous-service Taxons de Cartes.
5
*
6
* @see http://www.tela-botanica.org/wikini/eflore/wakka.php?wiki=EfloreApi01Cartes
7
*
8
* @package eFlore/services
9
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
10
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
11
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
12
* @version 1.0
13
* @copyright 1999-2012 Tela Botanica (accueil@tela-botanica.org)
14
*/
15
// TODO : Config et Outils sont des classes statiques qui doivent poser des pb pour les tests...
16
class TaxonsCartes {
17
 
18
	private $parametres = array();
19
	private $ressources = array();
20
 
260 jpm 21
	const CODE_REFTAX_DEFAUT = 'bdtfx';
255 jpm 22
	const TYPE_ID_DEFAUT = 'nn';
23
	const CARTE_DEFAUT = 'france_02';
268 jpm 24
	const FORMAT_DEFAUT = '587x550';
260 jpm 25
	const VERSION_DEFAUT = '+';
255 jpm 26
	const MIME_SVG = 'image/svg+xml';
27
	const MIME_PNG = 'image/png';
28
	const PRESENCE_CHOROLOGIE = '1';
29
 
30
	private $config = array();
268 jpm 31
	private $convertisseur = '';
255 jpm 32
	private $cheminCartesBase = '';
260 jpm 33
	private $formatsSupportes = array(self::MIME_SVG, self::MIME_PNG);
34
	private $reftaxSupportes = array(self::CODE_REFTAX_DEFAUT);
255 jpm 35
	private $UrlNavigation = null;
36
	private $taxonsDemandes = array();
37
	private $imgLargeur = 0;
38
	private $imgHauteur = 0;
39
	private $tableMeta = '';
40
	private $tableOntologie = '';
41
	private $tableChorodep = '';
42
	private $metadonnees = '';
43
	private $ontologies = '';
44
	private $priorites = '';
45
	private $version = '';
46
	private $legende = array();
47
	private $donnees = array();
48
 
49
 
50
	public function __construct(Conteneur $conteneur) {
51
		$this->Bdd = $conteneur->getBdd();
52
		$this->tableOntologie = $conteneur->getParametre('bdd_table_ontologies');
53
		$this->config = $conteneur->getParametre('Cartes');
268 jpm 54
		$this->convertisseur = $this->config['convertisseur'];
255 jpm 55
		$this->tableMeta = $conteneur->getParametre('bdd_table_meta');
56
		$this->tableOntologie = $conteneur->getParametre('bdd_table_ontologies');
57
		$this->cheminCartesBase = $this->config['chemin'];
58
		$cacheOptions = array('mise_en_cache' => $this->config['cache']['miseEnCache'],
59
					'stockage_chemin' => $this->config['cache']['stockageChemin'],
60
					'duree_de_vie' => $this->config['cache']['dureeDeVie']);
61
		$this->cache = $conteneur->getCacheSimple($cacheOptions);
62
	}
63
 
64
	public function consulter($ressources, $parametres) {
65
		$this->parametres = $parametres;
66
		$this->ressources = $ressources;
67
 
68
		$this->definirValeurParDefautDesParametres();
69
		$this->verifierParametres();
70
 
71
		$resultat = $this->obtenirResultat();
72
 
73
		return $resultat;
74
	}
75
 
76
	private function definirValeurParDefautDesParametres() {
77
		if (isset($this->parametres['retour']) == false) {
78
			$this->parametres['retour'] = self::MIME_SVG;
79
		}
80
		if (isset($this->parametres['retour.format']) == false) {
81
			$this->parametres['retour.format'] = self::FORMAT_DEFAUT;
82
		}
260 jpm 83
		if (isset($this->parametres['version.projet']) == false) {
84
			$this->parametres['version.projet'] = self::VERSION_DEFAUT;
85
		}
255 jpm 86
	}
87
 
88
	private function verifierParametres() {
89
		$erreurs = array();
90
 
91
		if (isset($this->parametres['retour']) == false) {
92
			$erreurs[] = "Le paramètre type de retour 'retour' est obligatoire.";
93
		}
94
		if ($this->verifierValeurParametreRetour() == false) {
95
			$erreurs[] = "Le type de retour '{$this->parametres['retour']}' n'est pas supporté.";
96
		}
97
		if (isset($this->parametres['retour.format']) == false) {
98
			$erreurs[] = "Le paramètre de format de retour 'retour.format' est obligatoire.";
99
		}
100
		if ($this->verifierValeurParametreFormat() == false) {
101
			$erreurs[] = "Le type de format '{$this->parametres['retour.format']}' n'est pas supporté.".
260 jpm 102
				"Veuillez indiquer un nombre entier correspondant à la largeur désirée pour la carte.";
255 jpm 103
		}
260 jpm 104
		if ($this->verifierValeurParametreVersionProjet() == false) {
105
			$erreurs[] = "Le format de version.projet '{$this->parametres['version.projet']}' n'est pas supporté.".
106
				"Veuillez indiquer le code '+' (=dernière version) ou une année sur 4 chiffres séparé d'un mois ".
107
				"sur deux chiffres par un point. Ex. : 2012.01";
108
		}
255 jpm 109
 
110
		if (count($erreurs) > 0) {
111
			$message = implode('<br />', $erreurs);
112
			$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
113
			throw new Exception($message, $code);
114
		}
115
	}
116
 
117
	private function verifierValeurParametreRetour() {
260 jpm 118
		return in_array($this->parametres['retour'], $this->formatsSupportes);
255 jpm 119
	}
120
 
121
	private function verifierValeurParametreFormat() {
122
		if ($ok = preg_match('/^([0-9]+)$/', $this->parametres['retour.format'], $match)) {
123
			$this->imgLargeur = $match[1];
124
		} else if ($ok = preg_match('/^([0-9]+)x([0-9]+)$/', $this->parametres['retour.format'], $match)) {
125
			$this->imgLargeur = $match[1];
126
			$this->imgHauteur = $match[2];
127
		}
128
		return $ok;
129
	}
260 jpm 130
	private function verifierValeurParametreVersionProjet() {
131
		$ok = (preg_match('/^(?:[+]|[0-9]{4}\.[0-9]{2})$/', $this->parametres['version.projet']) == 0) ? false : true;
132
		return $ok;
133
	}
255 jpm 134
 
135
	private function obtenirResultat() {
136
		$this->analyserIdentifiants();
260 jpm 137
		$this->verifierIdentifiants();
255 jpm 138
 
260 jpm 139
		$this->chargerMetadonnees();
140
		$this->definirVersion();
141
		$this->tableChorodep = 'chorodep_v'.str_replace('.', '_', $this->version);
142
		$this->chargerOntologies();
143
		$this->chargerLegende();
144
		$this->chargerPrioritesLegende();
255 jpm 145
		$this->chargerDonnees();
146
		$svg = $this->genererSVG();
147
		$img = ($this->parametres['retour'] == self::MIME_PNG) ? $this->convertirEnPNG($svg) : $svg;
148
 
149
		$resultat = new ResultatService();
150
		$resultat->corps = $img;
151
		$resultat->mime = $this->parametres['retour'];
152
 
153
		return $resultat;
154
	}
155
 
156
	private function analyserIdentifiants() {
157
		$ids = $this->ressources[0];
158
		if (preg_match('/^[0-9]+$/', $ids)) {
159
			$this->taxonsDemandes[self::CODE_REFTAX_DEFAUT]['nn'][] = $ids;
160
		} else {
161
			// ceci contient potentiellement des formes ref_tax1.nn:1,2;ref_tax2.nt:3,4
162
			$projetsListeEtNumNoms = explode(';', $ids);
163
			if (count($projetsListeEtNumNoms) > 0) {
164
				foreach ($projetsListeEtNumNoms as $projetEtNumNoms) {
165
					$projetEtNumNoms = (strpos($projetEtNumNoms, ':')) ? $projetEtNumNoms : self::CODE_REFTAX_DEFAUT.'.nn:'.$projetEtNumNoms;
166
					list($projetEtType, $numNoms) = explode(':', $projetEtNumNoms);
260 jpm 167
 
168
					$projetEtType = (strpos($projetEtType, '.')) ? $projetEtType : self::CODE_REFTAX_DEFAUT.'.'.$projetEtType;
255 jpm 169
					list($projet, $type) = explode('.', $projetEtType);
260 jpm 170
 
255 jpm 171
					$this->taxonsDemandes[$projet][$type] = explode(',', $numNoms);
172
				}
173
			}
174
		}
175
	}
176
 
260 jpm 177
	private function verifierIdentifiants() {
178
		foreach (array_keys($this->taxonsDemandes) as $reftax) {
179
			$ok = in_array($reftax, $this->reftaxSupportes);
180
			if ($ok == false) {
181
				$message = "Le reférentiel taxonomique '$reftax' n'est pas pris en compte par ce projet.";
182
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
183
				throw new Exception($message, $code);
184
			}
185
		}
186
	}
187
 
188
	private function chargerMetadonnees() {
255 jpm 189
		$requete = 'SELECT * '.
260 jpm 190
			"FROM {$this->tableMeta} ".
191
			"ORDER BY date_creation DESC ";
192
		$resultats = $this->Bdd->recupererTous($requete);
255 jpm 193
 
194
		if (!is_array($resultats) || count($resultats) <= 0) {
260 jpm 195
			$message = "Les méta-données n'ont pu être chargée pour la ressource demandée";
255 jpm 196
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
197
			throw new Exception($message, $code);
198
		}
199
 
200
		$this->metadonnees = $resultats;
260 jpm 201
	}
255 jpm 202
 
260 jpm 203
	private function definirVersion() {
204
		if ($this->parametres['version.projet'] == '+') {
205
			$this->version = $this->metadonnees[0]['version'];
206
		} else {
207
			$this->version = $this->parametres['version.projet'];
208
		}
255 jpm 209
	}
210
 
211
	private function chargerOntologies() {
212
		$requete = 'SELECT * '.
260 jpm 213
			"FROM {$this->tableOntologie} ";
255 jpm 214
		$resultats = $this->Bdd->recupererTous($requete);
215
 
216
		if (!is_array($resultats) || count($resultats) <= 0) {
217
			$message = "Les données de légende n'ont pu être chargées pour la ressource demandée";
218
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
219
			throw new Exception($message, $code);
220
		}
221
 
222
		foreach ($resultats as $ontologie) {
223
			$this->ontologies[$ontologie['id']] = $this->extraireComplementsOntologies($ontologie);
224
		}
225
	}
226
 
227
 
228
	private function extraireComplementsOntologies($ontologie) {
229
		if ($ontologie['complements'] != '') {
230
			$complements = explode(',', trim($ontologie['complements']));
231
			foreach ($complements as $complement) {
232
				list($cle, $val) = explode('=', trim($complement));
233
				$ontologie[trim($cle)] = trim($val);
234
			}
235
		}
236
		return $ontologie;
237
	}
238
 
239
	private function chargerLegende() {
240
		foreach ($this->ontologies as $ontologie) {
241
			if ($ontologie['classe_id'] == self::PRESENCE_CHOROLOGIE) {
242
				$this->legende[$ontologie['code']] = $ontologie['legende'];
243
			}
244
		}
245
	}
246
 
247
	private function chargerPrioritesLegende() {
248
		foreach ($this->ontologies as $ontologie) {
249
			if ($ontologie['classe_id'] == self::PRESENCE_CHOROLOGIE && isset($ontologie['priorite'])) {
250
				$this->priorites[$ontologie['code']] = $ontologie['priorite'];
251
			}
252
		}
253
	}
254
 
255
	private function chargerDonnees() {
256
		$conditions = $this->getConditions();
257
		$requete = 'SELECT * '.
258
					"FROM {$this->tableChorodep} ".
259
		(isset($conditions) ? 'WHERE '.implode(' AND ', $conditions) : '');
260
		$resultat = $this->Bdd->recupererTous($requete);
261
 
262
		if (!is_array($resultat) || count($resultat) <= 0) {
263
			$message = "Aucune donnée ne correspond à la ressource demandée";
264
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
265
			throw new Exception($message, $code);
266
		}
267
		$this->donnees = $resultat;
268
	}
269
 
270
	private function getConditions() {
271
		$conditions = null;
272
		if ($nnListe = $this->getListeNumNom()) {
273
			$conditions[] = "num_nom IN ($nnListe) ";
274
		}
275
		if ($ntListe = $this->getListeNumTax()) {
276
			$conditions[] = "num_tax IN ($ntListe) ";
277
		}
278
		return $conditions;
279
	}
280
 
281
	private function getListeNumNom() {
282
		$nnListe = null;
283
		$refTax = self::CODE_REFTAX_DEFAUT;
284
		if (isset($this->taxonsDemandes[$refTax])) {
285
			$nnProteges = array();
286
			if (isset($this->taxonsDemandes[$refTax]['nn'])) {
287
				foreach ($this->taxonsDemandes[$refTax]['nn'] as $nn) {
288
					$nnProteges[] = $this->Bdd->proteger($nn);
289
				}
290
				$nnListe = implode(',', $nnProteges);
291
			}
292
		}
293
		return $nnListe;
294
	}
295
 
296
	private function getListeNumTax() {
297
		$ntListe = null;
298
		$refTax = self::CODE_REFTAX_DEFAUT;
299
		if (isset($this->taxonsDemandes[$refTax])) {
300
			$ntProteges = array();
301
			if (isset($this->taxonsDemandes[$refTax]['nt'])) {
302
				foreach ($this->taxonsDemandes[$refTax]['nt'] as $nt) {
303
					$ntProteges[] = $this->Bdd->proteger($nt);
304
				}
305
				$ntListe = implode(',', $ntProteges);
306
			}
307
		}
308
		return $ntListe;
309
	}
310
 
311
	private function genererSVG() {
312
		$dom = new DOMDocument('1.0', 'UTF-8');
313
		$dom->validateOnParse = true;
314
 
315
		$fichierCarteSvg = $this->cheminCartesBase.self::CARTE_DEFAUT.'.svg';
316
		$dom->load($fichierCarteSvg);
317
 
318
		$racineElement = $dom->documentElement;
319
		$racineElement->setAttribute('width', $this->imgLargeur);
273 jpm 320
		if ($this->imgHauteur != 0) {
321
			$racineElement->setAttribute('height', $this->imgHauteur);
322
		}
255 jpm 323
 
324
		$css = $this->creerCssCarte();
325
		$styleElement = $dom->getElementsByTagName('style')->item(0);
326
		$css = $styleElement->nodeValue.$css;
327
		$txtCss = $dom->createCDATASection($css);
328
		$styleElement->nodeValue = '';
329
		$styleElement->appendChild($txtCss);
330
 
331
		$titre = $this->creerTitre();
332
		$titreCdata = $dom->createCDATASection($titre);
333
		$titreElement = $dom->getElementsByTagName('title')->item(0);
334
		$titreElement->nodeValue = '';
335
		$titreElement->appendChild($titreCdata);
336
 
337
		$taxonTitre = $this->creerTitreTaxon();
338
		$taxonCdata = $dom->createCDATASection($taxonTitre);
339
		$xpath = new DOMXPath($dom);
340
		$taxonTitreEl = $xpath->query("//*[@id='titre-taxon']")->item(0);
341
		$taxonTitreEl->nodeValue = '';
342
		$taxonTitreEl->setAttribute('title', $taxonTitre);
343
		$taxonTitreEl->appendChild($taxonCdata);
344
 
345
		$svg = $dom->saveXML();
346
		return $svg;
347
	}
348
 
349
	private function creerCssCarte() {
350
		$css = '';
351
		$this->getZonesPriorites();
352
		$zonesCouleurs = $this->getZonesCouleurs();
353
		foreach ($zonesCouleurs as $couleur => $zonesClasses) {
354
			$classes = implode(', ', $zonesClasses);
355
			$css .= "$classes{\nfill:$couleur;\n}\n";
356
		}
357
		return $css;
358
	}
359
 
360
	private function getZonesPriorites() {
361
		$this->zones = array();
362
		$zonesPrioritaires = array();
363
		foreach ($this->donnees as $donnee) {
364
			foreach ($donnee as $zoneId => $codeLegende) {
365
				if (preg_match('/^[0-9][0-9ab]$/i', $zoneId)) {
366
					if (array_key_exists($codeLegende, $this->priorites)) {
367
						$priorite = $this->priorites[$codeLegende];
368
						if (array_key_exists($zoneId, $zonesPrioritaires) == false) {
369
							$zonesPrioritaires[$zoneId] = 0;
370
						}
371
						if ($priorite > $zonesPrioritaires[$zoneId]) {
372
							$zonesPrioritaires[$zoneId] = $priorite;
373
							$this->zones[$zoneId] = $codeLegende;
374
						}
375
					}
376
				}
377
			}
378
		}
379
	}
380
 
381
	private function getZonesCouleurs() {
382
		$zones = array();
260 jpm 383
		ksort($this->zones);
255 jpm 384
		foreach ($this->zones as $zoneId => $codeLegende) {
385
			if (array_key_exists($codeLegende, $this->legende)) {
386
				$couleur = $this->legende[$codeLegende];
260 jpm 387
				$zones[$couleur][] = strtolower('.departement'.sprintf('%02s', $zoneId));
255 jpm 388
			}
389
		}
390
		return $zones;
391
	}
392
 
393
	private function creerTitre() {
394
		$titre = "Carte en cours d'élaboration pour ".$this->creerTitreTaxon();
395
		return $titre;
396
	}
397
 
398
	private function creerTitreTaxon() {
399
		$noms = array();
400
		foreach ($this->donnees as $donnee) {
401
			$noms[] = $donnee['nom_sci'];
402
		}
403
		$titre = implode(', ', $noms);
404
		return $titre;
405
	}
406
 
407
	private function convertirEnPNG($svg) {
408
		$png = null;
268 jpm 409
		if (isset($this->convertisseur)) {
410
			if ($this->convertisseur == 'imagick') {
411
				if (extension_loaded('imagick')) {
412
					$png = $this->convertirEnPNGAvecImageMagick($svg);
413
				} else {
414
					$message = "Impossible de générer l'image sur le serveur. Extenssion ImageMagick abscente.";
415
					$code = RestServeur::HTTP_CODE_ERREUR;
416
					throw new Exception($message, $code);
417
				}
418
			} else if ($this->convertisseur == 'rsvg') {
419
				$png = $this->convertirEnPNGAvecRsvg($svg);
420
			} else {
421
				$message = "Le convertisseur indiqué '{$this->convertisseur}' ne fait pas parti de la liste ".
422
					"des convertisseurs disponibles : imagick, rsvg.";
423
				$code = RestServeur::HTTP_CODE_ERREUR;
424
				throw new Exception($message, $code);
425
			}
255 jpm 426
		} else {
268 jpm 427
			$message = "Veuillez indiquer le convertisseur de svg à utiliser pour le service.";
255 jpm 428
			$code = RestServeur::HTTP_CODE_ERREUR;
429
			throw new Exception($message, $code);
430
		}
268 jpm 431
		return $png;
255 jpm 432
	}
433
 
434
	private function convertirEnPNGAvecImageMagick($svg) {
435
		$convertisseur = new Imagick();
268 jpm 436
		$convertisseur->setBackgroundColor(new ImagickPixel('transparent'));
255 jpm 437
		$convertisseur->readImageBlob($svg);
268 jpm 438
		$convertisseur->setImageFormat('png32');
439
		$convertisseur->resizeImage($this->imgLargeur, $this->imgHauteur, imagick::FILTER_LANCZOS, 0, true);
255 jpm 440
		$png = $convertisseur->getImageBlob();
441
		$convertisseur->clear();
442
		$convertisseur->destroy();
443
		return $png;
444
	}
445
 
268 jpm 446
	private function convertirEnPNGAvecRsvg($svg) {
273 jpm 447
		$idFichier = $this->getIdFichier();
268 jpm 448
		$fichierPng = $this->config['cache']['stockageChemin'].$idFichier.'.png';
449
		$fichierSvg = $this->config['cache']['stockageChemin'].$idFichier.'.svg';
450
		file_put_contents($fichierSvg, $svg);
273 jpm 451
		$commande = "rsvg-convert $fichierSvg -d 75 -p 75 -o $fichierPng";
452
		$rsvg = exec($commande);
453
 
268 jpm 454
		$this->indexerFichierPng($fichierPng);
455
		$png = file_get_contents($fichierPng);
456
		return $png;
457
	}
458
 
459
	private function indexerFichierPng($fichierPng) {
460
		$img = imagecreatefrompng($fichierPng);
461
		imagetruecolortopalette($img, false, 32);
462
		imagepng($img, $fichierPng, 9, PNG_ALL_FILTERS);
463
	}
464
 
273 jpm 465
	private function getIdFichier() {
466
		$id = '';
467
		foreach ($this->taxonsDemandes as $reftax => $ids) {
468
			$id[] = $reftax;
469
			foreach ($ids as $type => $vals) {
470
				$id[] = $type;
471
				$id[] = implode('-', $vals);
472
			}
473
		}
474
		$id = implode('-', $id);
475
		return $id;
476
	}
477
 
255 jpm 478
	public function getParametreTableau($cle) {
479
		$tableau = array();
480
		$parametre = $this->config[$cle];
481
		if (empty($parametre) === false) {
482
			$tableauPartiel = explode(',', $parametre);
483
			$tableauPartiel = array_map('trim', $tableauPartiel);
484
			foreach ($tableauPartiel as $champ) {
485
				if (strpos($champ, '=') === false) {
486
					$tableau[] = trim($champ);
487
				} else {
488
					list($cle, $val) = explode('=', $champ);
489
					$tableau[trim($cle)] = trim($val);
490
				}
491
			}
492
		}
493
		return $tableau;
494
	}
495
}
496
?>