Subversion Repositories eFlore/Projets.eflore-projets

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
449 mathilde 1
<?php
2
 
3
/**
4
* Classe CommunGraphiques.php regroupement de fonctions pour les graphiques
5
*  graphiques/#typegraphique/#bdnt.nn:#num_nomen --> renvoie un graphique avec les données connues
6
*
916 jpm 7
*
449 mathilde 8
* @package eflore-projets
9
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
10
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org>
11
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
12
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
13
* @version 1.0
14
* @copyright 1999-2011 Tela Botanica (accueil@tela-botanica.org)
15
*/
16
 
17
abstract class CommunGraphiques extends Commun{
916 jpm 18
 
449 mathilde 19
	protected $parametres = array();
20
	protected $ressources = array();
916 jpm 21
 
449 mathilde 22
	protected $Bdd;
23
	protected $config;
24
	protected $cache;
25
	protected $metadonnees;
26
	protected $version;
27
	protected $serviceNom = 'Graphiques';
916 jpm 28
 
449 mathilde 29
	protected $graduations_id = array();
30
	protected  $champs_ontologiques =  array();
31
	protected $nomGraphique = array();
916 jpm 32
 
449 mathilde 33
	protected $table = '';
34
	protected $requete_condition = "";
35
	protected $requete_champs;
916 jpm 36
 
449 mathilde 37
	protected $convertisseur;
38
	protected $cheminGraphBase;
39
	protected $valeurs_en_pourcentage = array();
40
	protected $dom;
41
	protected $largeurSVG = "500";
512 mathilde 42
	protected $hauteurSVG;
449 mathilde 43
	protected $valeurs_champs;
916 jpm 44
 
45
 
46
 
449 mathilde 47
	public function consulter($ressources, $parametres) {
48
		$this->ressources = $ressources;
49
		$this->parametres = $parametres;
506 mathilde 50
		$this->verifierParametres();
449 mathilde 51
		$this->initialiserConfiguration();
52
		$resultats = '';
53
		$this->traiterRessources();
968 raphael 54
 
988 mathias 55
		$req = $this->assemblerLaRequete();
56
		$resultat = $this->resultat = $this->Bdd->recupererTous($req);
449 mathilde 57
		$versionResultat = $this->obtenirResultat($resultat);
58
		return $versionResultat;
59
	}
60
 
916 jpm 61
 
449 mathilde 62
	//+--------------------------initialisation de paramètres  -------------------------------------------+
916 jpm 63
 
449 mathilde 64
	private function initialiserConfiguration() {
65
		$conteneur = new Conteneur();
66
		$this->Bdd = $conteneur->getBdd();
67
		$this->config = $conteneur->getParametre('Graphiques');
68
		$this->convertisseur = $this->config['convertisseur'];
968 raphael 69
		$this->graduations_id = $this->getParametreTableau('Paramètres.graduations_id');
958 raphael 70
		$this->champs_ontologiques = $this->getParametreTableau('Paramètres.champs_ontologiques');
449 mathilde 71
		$this->cheminGraphBase = $this->config['chemin'];
797 raphael 72
		$cacheOptions = array('mise_en_cache' => $this->config['cache_miseEnCache'],
916 jpm 73
			'stockage_chemin' => $this->config['cache_stockageChemin'],
74
			'duree_de_vie' => $this->config['cache_dureeDeVie']);
449 mathilde 75
		$this->cache = $conteneur->getCacheSimple($cacheOptions);
76
		$this->definirVersion();
77
		$this->definirFormat();
78
		$this->definirTable($this->version);
79
	}
916 jpm 80
 
81
 
82
 
449 mathilde 83
	abstract function definirTable($version);
916 jpm 84
 
85
 
449 mathilde 86
	private function getParametreTableau($cle) {
87
		$tableau = array();
88
		$parametre = Config::get($cle);
89
		if (empty($parametre) === false) {
90
			$tableauPartiel = explode(',', $parametre);
91
			$tableauPartiel = array_map('trim', $tableauPartiel);
92
			foreach ($tableauPartiel as $champ) {
93
				if (strpos($champ, '=') !== false && strlen($champ) >= 3) {
94
					list($cle, $val) = explode('=', $champ);
95
					$tableau[trim($cle)] = trim($val);
96
				} else {
97
					$tableau[] = trim($champ);
98
				}
99
			}
100
		}
101
		return $tableau;
102
	}
506 mathilde 103
 
449 mathilde 104
	//+--------------------------traitement ressources ou paramètres  -------------------------------------------+
916 jpm 105
 
449 mathilde 106
	//+---- paramètres ----+
916 jpm 107
 
506 mathilde 108
	private function verifierParametres() {
109
		if (isset($this->parametres)) {
110
			$parametres_dispo = array('retour', 'retour.format', 'version.projet');
111
			$parametres = array_keys($this->parametres);
112
			foreach ($parametres as $param) {
113
				if (!in_array($param, $parametres_dispo)) {
114
					$erreur = "Erreur : Le paramètre $param est inconnu.";
115
					$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
116
					throw new Exception($erreur, $code);
117
				}
118
			}
119
		}
916 jpm 120
 
506 mathilde 121
	}
916 jpm 122
 
449 mathilde 123
	//on n'affiche qu'une version de graphique à la fois ( la dernière ou celle demandée )
916 jpm 124
	private function definirVersion() {
449 mathilde 125
		$this->chargerVersions();
506 mathilde 126
		if (!isset($this->parametres['version.projet']) ) {
449 mathilde 127
			$this->version = $this->metadonnees[0]['version'];
506 mathilde 128
		} elseif ($this->parametres['version.projet'] == '+') {
129
				 $this->version = $this->metadonnees[0]['version'];
449 mathilde 130
		} else {
506 mathilde 131
			if($this->verifierVersion($this->parametres['version.projet'])) {
132
				$this->version = $this->parametres['version.projet'];
133
			}else {
134
				$erreur = "Erreur : La version est inconnue.";
135
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
136
				throw new Exception($erreur, $code);
137
			}
449 mathilde 138
		}
139
	}
916 jpm 140
 
506 mathilde 141
	private function verifierVersion($version){
142
		$retour = false;
143
		foreach ($this->metadonnees as $vers) {
144
			if ($vers['version'] == $version ) {
145
				$retour = true;
146
			}
147
		}
148
		return $retour;
149
	}
449 mathilde 150
	private function definirFormat() {
151
		if (isset($this->parametres['retour.format']) ){
152
			if (preg_match("/^[0-9]+$/", $this->parametres['retour.format'])){
512 mathilde 153
				if ($this->parametres['retour.format'] > 0) {
154
					$this->largeurSVG = $this->parametres['retour.format'];
155
				} else {
156
					$erreur = "Erreur : valeur pour retour.format négative ou égale à 0.";
157
					$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
158
					throw new Exception($erreur, $code);
159
				}
449 mathilde 160
			}else {
506 mathilde 161
				$erreur = "Erreur : valeur inconnue. Entrez la largeur voulue (en pixels) pour le paramètre retour.format.";
449 mathilde 162
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
163
				throw new Exception($erreur, $code);
164
			}
165
		}
166
		if (!isset($this->parametres['retour']) ){
167
			$this->parametres['retour'] = 'image/svg+xml';
916 jpm 168
 
449 mathilde 169
		}else {
170
			if (( $this->parametres['retour'] != 'image/svg+xml')&& ( $this->parametres['retour'] != 'image/png')){
506 mathilde 171
				$erreur = "Erreur : valeur inconnue. Choisissez le format de retour pour le paramètre retour : image/svg%2Bxml ou image/png.";
449 mathilde 172
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
173
				throw new Exception($erreur, $code);
174
			}
175
		}
176
	}
916 jpm 177
 
178
 
179
 
449 mathilde 180
	private function chargerVersions() {
181
		$requete = "SELECT version ".
182
							"FROM ".Config::get('bdd_table_meta')." ".
183
							"ORDER BY date_creation DESC ";
184
		$resultats = $this->Bdd->recupererTous($requete);
185
		if (!is_array($resultats) || count($resultats) <= 0) {
186
			$message = "Les méta-données n'ont pu être chargée pour la ressource demandée";
187
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
188
			throw new Exception($message, $code);
189
		}
916 jpm 190
 
449 mathilde 191
		$this->metadonnees = $resultats;
192
	}
916 jpm 193
 
449 mathilde 194
	//+----- ressources -----+
916 jpm 195
 
196
 
449 mathilde 197
	public function traiterRessources() {
501 mathilde 198
		if(isset($this->ressources)) {
199
			$this->traiterTypeGraphique();
200
			$this->traiterReferentielEtNum();
201
		} else {
202
			$e = 'Erreur dans l\'url de votre requête : </br> ressources insuffisantes.';
203
			throw new Exception( $e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
204
		}
449 mathilde 205
	}
916 jpm 206
 
449 mathilde 207
	abstract function traiterReferentielEtNum();
208
	abstract function traiterTypeGraphique();
916 jpm 209
 
449 mathilde 210
	//+--------------------------FONCTIONS D'ASSEMBLAGE DE LA REQUETE-------------------------------------------+
916 jpm 211
 
449 mathilde 212
	public function assemblerLaRequete() {
968 raphael 213
		return ' SELECT '.$this->requete_champs.'  FROM '.$this->table.' '.Informations::retournerRequeteCondition($this->requete_condition);
449 mathilde 214
	}
916 jpm 215
 
449 mathilde 216
	public  function retournerRequeteCondition() {
217
		$condition = '';
218
		if ($this->requete_condition !== "") {
219
			$condition = ' WHERE '.implode(' AND ', $this->requete_condition);
220
		}
221
		return $condition;
222
	}
916 jpm 223
 
449 mathilde 224
	//+-------------------------- formatage du résultat  -------------------------------------------+
225
 
226
	public function obtenirResultat($resultat) {
968 raphael 227
		if ($resultat == '') {
228
			throw new Exception(
229
                'La requête SQL formée comporte une erreur!',
230
                RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
231
		} elseif ($resultat) {
449 mathilde 232
			if ((count($this->ressources)) != 0) {
458 delphine 233
				//$Atraiter = array_filter($resultat[0],function($var){return ($var != '');});
234
				foreach ($resultat[0] as $champs => $valeur) {
1016 delphine 235
					if ($valeur !== null && $valeur !== '') {
458 delphine 236
						$Atraiter[$champs] = $valeur;
237
					}
238
				}
449 mathilde 239
				if (!empty($Atraiter)) {
240
					$this->traiterValeursEcologiques($Atraiter);
968 raphael 241
					$svg = $this->genererSVG($this->cheminGraphBase.$this->nomGraphique.".svg");
449 mathilde 242
					$resultat = new ResultatService();
243
					$resultat->corps = ($this->parametres['retour'] == 'image/png') ? $this->convertirEnPNG($svg) : $svg;
244
					$resultat->mime = $this->parametres['retour'];
245
				} else {
916 jpm 246
					$resultat = null;
449 mathilde 247
				}
248
			}
249
		} else {
250
			$resultat = null;
251
		}
252
		return $resultat;
253
	}
916 jpm 254
 
255
 
256
 
257
 
449 mathilde 258
	//+----- modification svg -----+
259
 
916 jpm 260
 
261
 
988 mathias 262
	public function traiterValeursEcologiques($valeur) {
916 jpm 263
		$this->valeurs_champs = $valeur;
264
 
449 mathilde 265
		foreach($this->valeurs_champs as $cle => $val){
988 mathias 266
			if ($val === null) {
267
				$this->valeurs_en_pourcentage[$cle] = null;
268
			} else {
449 mathilde 269
				if (preg_match("/ve_humidite_edaph/", $cle)) {
270
					$this->valeurs_en_pourcentage[$cle] = round($val/13,1);
271
				} elseif (preg_match("/ve_salinite/", $cle)) {
272
					$this->valeurs_en_pourcentage[$cle] = round(($val+1)/11,1);
273
				} else {
274
					$this->valeurs_en_pourcentage[$cle] = round($val/10,1);
275
				}
988 mathias 276
			}
449 mathilde 277
		}
278
	}
916 jpm 279
 
512 mathilde 280
	public function donnerHauteur($ancienne_largeur, $ancienne_hauteur) {
281
		$nouvelle_largeur = $this->largeurSVG;
282
		$ancienne_largeur = str_replace('px','',$ancienne_largeur);
283
		$ancienne_hauteur = str_replace('px','',$ancienne_hauteur);
284
		$rapport =   $nouvelle_largeur / $ancienne_largeur ;
285
		$nouvelle_hauteur = $ancienne_hauteur * $rapport;
286
		$this->hauteurSVG = $nouvelle_hauteur;
287
	}
916 jpm 288
 
512 mathilde 289
	public function ajusterFormatSVG(){
290
		$svg = $this->dom->getElementsByTagName("svg")->item(0);
291
		$largeur = $svg->getAttribute('width');
292
		$hauteur = $svg->getAttribute('height');
293
		$this->donnerHauteur($largeur , $hauteur);
560 aurelien 294
		$svg->setAttribute('width',round($this->largeurSVG).'px');
295
		$svg->setAttribute('height',round($this->hauteurSVG).'px');
916 jpm 296
 
512 mathilde 297
	}
916 jpm 298
 
968 raphael 299
	public function genererSVG($fichierSvg){
449 mathilde 300
		$svg = null;
301
		$this->dom = new DOMDocument('1.0', 'UTF-8');
302
		$this->dom->validateOnParse = true;
303
		$this->dom->load($fichierSvg);
304
		$this->changerValeursSVG();
968 raphael 305
		return $this->dom->saveXML();
449 mathilde 306
	}
916 jpm 307
 
449 mathilde 308
	abstract function changerValeursSVG();
916 jpm 309
 
449 mathilde 310
	public function recupererOntologies($valeur, $champs){
311
		$url = $this->ajouterHref('ontologies',$this->champs_ontologiques[$champs].':'.urlencode(urlencode($valeur)));
712 aurelien 312
		try {
763 raphael 313
			$val = $this->getBdd()->recuperer(sprintf(
314
				"SELECT a.nom FROM baseflor_ontologies a LEFT JOIN baseflor_ontologies b ON a.id = b.id LEFT JOIN baseflor_ontologies c ON b.classe_id = c.id WHERE".
315
				" b.code = BINARY '%s' AND c.code = BINARY '%s' LIMIT 0, 100",
316
				$valeur,
317
				$this->champs_ontologiques[$champs]),
318
				Bdd::MODE_OBJET);
712 aurelien 319
		} catch (Exception $e) {
988 mathias 320
			$val = false;
712 aurelien 321
		}
449 mathilde 322
		return $val;
323
	}
916 jpm 324
 
465 mathilde 325
	public function traiterIntermediaires($valeurTexte,$champsOntologie, $champsTable){
473 mathilde 326
		if (preg_match("/(?:I|i)nterm(?:é|e)diaire(?:s)*/", $valeurTexte )) {
465 mathilde 327
			$prec = $this->recupererOntologies(($this->valeurs_champs[$champsTable]-1), $champsOntologie );
328
			$suiv = $this->recupererOntologies(($this->valeurs_champs[$champsTable]+1), $champsOntologie );
329
			$valeurTexte = "Intermédiaires entre $prec->nom et $suiv->nom ";
330
		}
331
		return $valeurTexte;
332
	}
916 jpm 333
 
449 mathilde 334
	/// +---- convertir png ----+
916 jpm 335
 
449 mathilde 336
	public function convertirEnPNG($svg) {
337
		$png = null;
916 jpm 338
 
449 mathilde 339
		if (isset($this->convertisseur)) {
340
			if ($this->convertisseur == 'imagick') {
341
				if (extension_loaded('imagick')) {
342
					$png = $this->convertirEnPNGAvecImageMagick($svg);
343
				} else {
344
					$message = "Impossible de générer l'image sur le serveur. Extension ImageMagick absente.";
345
					$code = RestServeur::HTTP_CODE_ERREUR;
346
					throw new Exception($message, $code);
347
				}
348
			} else if ($this->convertisseur == 'rsvg') {
808 raphael 349
				$png = $this->convertirGraphiqueEnPNGAvecRsvg($svg);
449 mathilde 350
			} else {
351
				$message = "Le convertisseur indiqué '{$this->convertisseur}' ne fait pas partie de la liste ".
352
								"des convertisseurs disponibles : imagick, rsvg.";
353
				$code = RestServeur::HTTP_CODE_ERREUR;
354
				throw new Exception($message, $code);
355
			}
356
		} else {
357
			$message = "Veuillez indiquer le convertisseur de svg à utiliser pour le service.";
358
			$code = RestServeur::HTTP_CODE_ERREUR;
359
			throw new Exception($message, $code);
360
		}
361
		return $png;
362
	}
916 jpm 363
 
449 mathilde 364
	public function convertirEnPNGAvecImageMagick($svg) {
365
		$convertisseur = new Imagick();
366
		$convertisseur->setBackgroundColor(new ImagickPixel('#F8F8F8'));
367
		$convertisseur->readImageBlob($svg);
368
		$convertisseur->setImageFormat('png32');
512 mathilde 369
		$convertisseur->resizeImage($this->largeurSVG,$this->hauteurSVG, imagick::FILTER_LANCZOS, 0, true);
449 mathilde 370
		$png = $convertisseur->getImageBlob();
371
		$convertisseur->clear();
372
		$convertisseur->destroy();
373
		return $png;
374
	}
916 jpm 375
 
808 raphael 376
	public function convertirGraphiqueEnPNGAvecRsvg($svg) {
449 mathilde 377
		$idFichier = $this->getIdFichier();
808 raphael 378
		$fichierPng = $this->config['cache_stockageChemin'].$idFichier.'.png';
379
		$fichierSvg = $this->config['cache_stockageChemin'].$idFichier.'.svg';
449 mathilde 380
		file_put_contents($fichierSvg, $svg);
512 mathilde 381
		$commande = "rsvg-convert  $fichierSvg -w ".$this->largeurSVG ." -h ".$this->hauteurSVG ." -o $fichierPng";
382
		//echo $commande; exit;
449 mathilde 383
		$rsvg = exec($commande);
808 raphael 384
		$this->indexerGraphiqueFichierPng($fichierPng);
449 mathilde 385
		$png = file_get_contents($fichierPng);
386
		return $png;
387
	}
916 jpm 388
 
808 raphael 389
	public function indexerGraphiqueFichierPng($fichierPng) {
449 mathilde 390
		$img = imagecreatefrompng($fichierPng);
391
		imagetruecolortopalette($img, false, 32);
392
		imagepng($img, $fichierPng, 9, PNG_ALL_FILTERS);
393
	}
916 jpm 394
 
449 mathilde 395
	public function getIdFichier(){
396
		$idfichier = str_replace(".","-",$this->ressources[1]);
397
		$idfichier = str_replace(':','-',$idfichier);
398
		$idfichier .= "-".$this->ressources[0];
399
		return $idfichier;
400
	}
401
}
402
?>