Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 951 | Rev 1235 | 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'];
797 raphael 58
		$cacheOptions = array('mise_en_cache' => $this->config['cache_miseEnCache'],
916 jpm 59
			'stockage_chemin' => $this->config['cache_stockageChemin'],
60
			'duree_de_vie' => $this->config['cache_dureeDeVie']);
255 jpm 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) {
951 raphael 223
			$this->ontologies[$ontologie['id']] = Commun::extraireComplementsOntologies($ontologie);
255 jpm 224
		}
225
	}
226
 
227
	private function chargerLegende() {
228
		foreach ($this->ontologies as $ontologie) {
229
			if ($ontologie['classe_id'] == self::PRESENCE_CHOROLOGIE) {
230
				$this->legende[$ontologie['code']] = $ontologie['legende'];
231
			}
232
		}
233
	}
234
 
235
	private function chargerPrioritesLegende() {
236
		foreach ($this->ontologies as $ontologie) {
237
			if ($ontologie['classe_id'] == self::PRESENCE_CHOROLOGIE && isset($ontologie['priorite'])) {
238
				$this->priorites[$ontologie['code']] = $ontologie['priorite'];
239
			}
240
		}
241
	}
242
 
243
	private function chargerDonnees() {
244
		$conditions = $this->getConditions();
245
		$requete = 'SELECT * '.
246
					"FROM {$this->tableChorodep} ".
247
		(isset($conditions) ? 'WHERE '.implode(' AND ', $conditions) : '');
248
		$resultat = $this->Bdd->recupererTous($requete);
249
		$this->donnees = $resultat;
250
	}
251
 
252
	private function getConditions() {
253
		$conditions = null;
254
		if ($nnListe = $this->getListeNumNom()) {
255
			$conditions[] = "num_nom IN ($nnListe) ";
256
		}
257
		if ($ntListe = $this->getListeNumTax()) {
258
			$conditions[] = "num_tax IN ($ntListe) ";
259
		}
260
		return $conditions;
261
	}
262
 
263
	private function getListeNumNom() {
264
		$nnListe = null;
265
		$refTax = self::CODE_REFTAX_DEFAUT;
266
		if (isset($this->taxonsDemandes[$refTax])) {
267
			$nnProteges = array();
268
			if (isset($this->taxonsDemandes[$refTax]['nn'])) {
269
				foreach ($this->taxonsDemandes[$refTax]['nn'] as $nn) {
270
					$nnProteges[] = $this->Bdd->proteger($nn);
271
				}
272
				$nnListe = implode(',', $nnProteges);
273
			}
274
		}
275
		return $nnListe;
276
	}
277
 
278
	private function getListeNumTax() {
279
		$ntListe = null;
280
		$refTax = self::CODE_REFTAX_DEFAUT;
281
		if (isset($this->taxonsDemandes[$refTax])) {
282
			$ntProteges = array();
283
			if (isset($this->taxonsDemandes[$refTax]['nt'])) {
284
				foreach ($this->taxonsDemandes[$refTax]['nt'] as $nt) {
285
					$ntProteges[] = $this->Bdd->proteger($nt);
286
				}
287
				$ntListe = implode(',', $ntProteges);
288
			}
289
		}
290
		return $ntListe;
291
	}
292
 
293
	private function genererSVG() {
1073 jpm 294
		$fichierCarteSvg = $this->cheminCartesBase.self::CARTE_DEFAUT.'.svg';
295
		if (file_exists($fichierCarteSvg) === false) {
296
			$message = "Le fichier SVG servant de base à la carte est introuvable : $fichierCarteSvg";
297
			$code = RestServeur::HTTP_CODE_ERREUR;
298
			throw new Exception($message, $code);
299
		}
300
 
255 jpm 301
		$dom = new DOMDocument('1.0', 'UTF-8');
302
		$dom->validateOnParse = true;
303
		$dom->load($fichierCarteSvg);
304
 
305
		$racineElement = $dom->documentElement;
306
		$racineElement->setAttribute('width', $this->imgLargeur);
273 jpm 307
		if ($this->imgHauteur != 0) {
308
			$racineElement->setAttribute('height', $this->imgHauteur);
309
		}
255 jpm 310
 
311
		$css = $this->creerCssCarte();
312
		$styleElement = $dom->getElementsByTagName('style')->item(0);
313
		$css = $styleElement->nodeValue.$css;
314
		$txtCss = $dom->createCDATASection($css);
315
		$styleElement->nodeValue = '';
316
		$styleElement->appendChild($txtCss);
317
 
318
		$titre = $this->creerTitre();
319
		$titreCdata = $dom->createCDATASection($titre);
320
		$titreElement = $dom->getElementsByTagName('title')->item(0);
321
		$titreElement->nodeValue = '';
322
		$titreElement->appendChild($titreCdata);
323
 
324
		$taxonTitre = $this->creerTitreTaxon();
325
		$taxonCdata = $dom->createCDATASection($taxonTitre);
326
		$xpath = new DOMXPath($dom);
327
		$taxonTitreEl = $xpath->query("//*[@id='titre-taxon']")->item(0);
328
		$taxonTitreEl->nodeValue = '';
329
		$taxonTitreEl->setAttribute('title', $taxonTitre);
330
		$taxonTitreEl->appendChild($taxonCdata);
331
 
332
		$svg = $dom->saveXML();
333
		return $svg;
334
	}
335
 
336
	private function creerCssCarte() {
337
		$css = '';
338
		$this->getZonesPriorites();
339
		$zonesCouleurs = $this->getZonesCouleurs();
340
		foreach ($zonesCouleurs as $couleur => $zonesClasses) {
341
			$classes = implode(', ', $zonesClasses);
342
			$css .= "$classes{\nfill:$couleur;\n}\n";
343
		}
344
		return $css;
345
	}
346
 
347
	private function getZonesPriorites() {
348
		$this->zones = array();
349
		$zonesPrioritaires = array();
350
		foreach ($this->donnees as $donnee) {
351
			foreach ($donnee as $zoneId => $codeLegende) {
352
				if (preg_match('/^[0-9][0-9ab]$/i', $zoneId)) {
353
					if (array_key_exists($codeLegende, $this->priorites)) {
354
						$priorite = $this->priorites[$codeLegende];
355
						if (array_key_exists($zoneId, $zonesPrioritaires) == false) {
356
							$zonesPrioritaires[$zoneId] = 0;
357
						}
358
						if ($priorite > $zonesPrioritaires[$zoneId]) {
359
							$zonesPrioritaires[$zoneId] = $priorite;
360
							$this->zones[$zoneId] = $codeLegende;
361
						}
362
					}
363
				}
364
			}
365
		}
366
	}
367
 
368
	private function getZonesCouleurs() {
369
		$zones = array();
260 jpm 370
		ksort($this->zones);
255 jpm 371
		foreach ($this->zones as $zoneId => $codeLegende) {
372
			if (array_key_exists($codeLegende, $this->legende)) {
373
				$couleur = $this->legende[$codeLegende];
260 jpm 374
				$zones[$couleur][] = strtolower('.departement'.sprintf('%02s', $zoneId));
255 jpm 375
			}
376
		}
377
		return $zones;
378
	}
379
 
380
	private function creerTitre() {
355 delphine 381
		$titre = "Carte en cours d'élaboration";
382
		if ($this->donnees != array()) {
383
			$titre .= ' pour '.$this->creerTitreTaxon();
384
		}
255 jpm 385
		return $titre;
386
	}
387
 
388
	private function creerTitreTaxon() {
355 delphine 389
		$titre = '';
255 jpm 390
		$noms = array();
391
		foreach ($this->donnees as $donnee) {
392
			$noms[] = $donnee['nom_sci'];
393
		}
394
		$titre = implode(', ', $noms);
395
		return $titre;
396
	}
397
 
398
	private function convertirEnPNG($svg) {
399
		$png = null;
268 jpm 400
		if (isset($this->convertisseur)) {
401
			if ($this->convertisseur == 'imagick') {
402
				if (extension_loaded('imagick')) {
403
					$png = $this->convertirEnPNGAvecImageMagick($svg);
404
				} else {
677 isa 405
					$message = "Impossible de générer l'image sur le serveur. Extension ImageMagick abscente.";
268 jpm 406
					$code = RestServeur::HTTP_CODE_ERREUR;
407
					throw new Exception($message, $code);
408
				}
409
			} else if ($this->convertisseur == 'rsvg') {
807 raphael 410
				$png = Commun::convertirEnPNGAvecRsvg($this->getIdFichier(), $this->config['cache_stockageChemin'], $svg);
268 jpm 411
			} else {
412
				$message = "Le convertisseur indiqué '{$this->convertisseur}' ne fait pas parti de la liste ".
413
					"des convertisseurs disponibles : imagick, rsvg.";
414
				$code = RestServeur::HTTP_CODE_ERREUR;
415
				throw new Exception($message, $code);
416
			}
255 jpm 417
		} else {
268 jpm 418
			$message = "Veuillez indiquer le convertisseur de svg à utiliser pour le service.";
255 jpm 419
			$code = RestServeur::HTTP_CODE_ERREUR;
420
			throw new Exception($message, $code);
421
		}
268 jpm 422
		return $png;
255 jpm 423
	}
424
 
425
	private function convertirEnPNGAvecImageMagick($svg) {
426
		$convertisseur = new Imagick();
268 jpm 427
		$convertisseur->setBackgroundColor(new ImagickPixel('transparent'));
255 jpm 428
		$convertisseur->readImageBlob($svg);
268 jpm 429
		$convertisseur->setImageFormat('png32');
430
		$convertisseur->resizeImage($this->imgLargeur, $this->imgHauteur, imagick::FILTER_LANCZOS, 0, true);
255 jpm 431
		$png = $convertisseur->getImageBlob();
432
		$convertisseur->clear();
433
		$convertisseur->destroy();
434
		return $png;
435
	}
436
 
273 jpm 437
	private function getIdFichier() {
438
		$id = '';
439
		foreach ($this->taxonsDemandes as $reftax => $ids) {
440
			$id[] = $reftax;
441
			foreach ($ids as $type => $vals) {
442
				$id[] = $type;
443
				$id[] = implode('-', $vals);
444
			}
445
		}
446
		$id = implode('-', $id);
447
		return $id;
448
	}
449
 
255 jpm 450
	public function getParametreTableau($cle) {
451
		$tableau = array();
452
		$parametre = $this->config[$cle];
453
		if (empty($parametre) === false) {
454
			$tableauPartiel = explode(',', $parametre);
455
			$tableauPartiel = array_map('trim', $tableauPartiel);
456
			foreach ($tableauPartiel as $champ) {
457
				if (strpos($champ, '=') === false) {
458
					$tableau[] = trim($champ);
459
				} else {
460
					list($cle, $val) = explode('=', $champ);
461
					$tableau[trim($cle)] = trim($val);
462
				}
463
			}
464
		}
465
		return $tableau;
466
	}
467
}
468
?>