Subversion Repositories eFlore/Projets.eflore-projets

Rev

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

Rev Author Line No. Line
396 mathilde 1
<?php
2
/**
402 mathilde 3
* Classe Graphiques.php permet d'afficher des graphiques en svg remplis avec des données écologiques
396 mathilde 4
*  fin d'url possibles :
402 mathilde 5
*  graphiques/#typegraphique/#bdnt.nn:#num_nomen --> renvoie une graphique avec les données connues
396 mathilde 6
*
7
* Encodage en entrée : utf8
8
* Encodage en sortie : utf8
9
* @package eflore-projets
10
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
11
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org>
12
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
13
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
14
* @version 1.0
15
* @copyright 1999-2011 Tela Botanica (accueil@tela-botanica.org)
16
*/
17
 
421 mathilde 18
class Graphiques extends Commun{
402 mathilde 19
 
421 mathilde 20
	protected $parametres = array();
21
	protected $ressources = array();
402 mathilde 22
	private $metadonnees;
23
	private $version;
24
	private $Bdd;
25
	private $nomGraphique = array();
421 mathilde 26
	protected $table = "";
402 mathilde 27
	private $requete_condition = "";
28
	private $requete_champs;
29
	private $config;
30
	private $convertisseur;
31
	private $cheminGraphBase;
421 mathilde 32
	protected $serviceNom = 'Graphiques';
402 mathilde 33
	private $valeurs_en_pourcentage ;
34
	private $dom;
410 mathilde 35
	private $largeurSVG="500";
421 mathilde 36
	private $valeurs_champs;
402 mathilde 37
	private $graduations_id = array ("zero" => 0 ,"un"=> 0.1, "deux" => 0.2 , "trois" => 0.3, "quatre" => 0.4,
38
									"cinq" => 0.5, "six" => 0.6 ,"sept" => 0.7, "huit" => 0.8, "neuf" => 0.9,
39
									"dix" => 1 );
421 mathilde 40
	private $champs_ontologiques =  array ('ve_lumiere' => 'VEL', 've_temperature' => 'VET',
41
												've_continentalite' => 'VEC', 've_humidite_atmos' => 'VEHA',
42
												've_humidite_edaph' => 'VEHE', 've_reaction_sol' => 'VER' ,
43
												've_nutriments_sol' => 'VEN', 've_salinite'=> 'VES' ,
44
												've_texture_sol' => 'VETX', 've_mat_org_sol' => 'VEMO');
396 mathilde 45
 
46
	public function consulter($ressources, $parametres) {
402 mathilde 47
		$this->ressources = $ressources;
396 mathilde 48
		$this->parametres = $parametres;
402 mathilde 49
		$this->initialiserConfiguration();
50
		$resultats = '';
51
		$this->table = Config::get('bdd_table')."_v".$this->version;
396 mathilde 52
		$this->traiterRessources();
402 mathilde 53
		$requete = $this->assemblerLaRequete();
421 mathilde 54
		$resultat = $this->resultat = $this->Bdd->recupererTous($requete);
402 mathilde 55
		$versionResultat = $this->obtenirResultat($resultat);
56
		return $versionResultat;
57
	}
396 mathilde 58
 
402 mathilde 59
//+--------------------------initialisation de paramètres  -------------------------------------------+
60
 
61
	public function initialiserConfiguration() {
62
		$conteneur = new Conteneur();
63
		$this->Bdd = $conteneur->getBdd();
64
		$this->config = $conteneur->getParametre('Graphiques');
65
		$this->convertisseur = $this->config['convertisseur'];
66
		$this->cheminGraphBase = $this->config['chemin'];
410 mathilde 67
		$cacheOptions = array('mise_en_cache' => $this->config['cache']['miseEnCache'],
68
							'stockage_chemin' => $this->config['cache']['stockageChemin'],
69
							'duree_de_vie' => $this->config['cache']['dureeDeVie']);
70
		$this->cache = $conteneur->getCacheSimple($cacheOptions);
402 mathilde 71
		$this->chargerVersions();
72
		$this->definirVersion();
410 mathilde 73
		$this->definirFormat();
396 mathilde 74
	}
75
 
402 mathilde 76
	//on n'affiche qu'une version de graphique à la fois ( la dernière ou celle demandée )
77
	private function definirVersion() {
78
		if( (!isset($this->parametres['version.projet']) ) || ((isset($this->parametres['version.projet']) )&&
79
		(($this->parametres['version.projet'] == '+') || ($this->parametres['version.projet'] == '')))){
80
			$this->version = $this->metadonnees[0]['version'];
81
		} else {
82
			$this->version = $this->parametres['version.projet'];
83
		}
84
	}
85
 
410 mathilde 86
	private function definirFormat() {
87
		if (isset($this->parametres['retour.format']) ){
88
			if (preg_match("/^[0-9]+$/", $this->parametres['retour.format'])){
89
				$this->largeurSVG= $this->parametres['retour.format'];
90
			}else {
91
				$erreur = "Erreur : Entrez la largeur voulue (en pixels) pour le paramètre retour.format.";
92
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
93
				throw new Exception($erreur, $code);
94
			}
402 mathilde 95
		}
410 mathilde 96
		if (!isset($this->parametres['retour']) ){
97
			$this->parametres['retour'] = 'image/svg+xml';
98
		}else {
99
			if (( $this->parametres['retour'] != 'image/svg+xml')&& ( $this->parametres['retour'] != 'image/png')){
100
				$erreur = "Erreur : choisissez le format de retour pour le paramètre retour : image/svg%2Bxml ou image/png.";
101
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
102
				throw new Exception($erreur, $code);
103
			}
104
		}
402 mathilde 105
	}
106
 
410 mathilde 107
 
108
 
402 mathilde 109
	private function chargerVersions() {
110
		$requete = "SELECT version ".
111
				"FROM ".Config::get('bdd_table_meta')." ".
112
				"ORDER BY date_creation DESC ";
113
		$resultats = $this->Bdd->recupererTous($requete);
114
		if (!is_array($resultats) || count($resultats) <= 0) {
115
			$message = "Les méta-données n'ont pu être chargée pour la ressource demandée";
116
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
117
			throw new Exception($message, $code);
118
		}
119
 
120
		$this->metadonnees = $resultats;
121
	}
122
 
123
	//+--------------------------traitement ressources ou paramètres  -------------------------------------------+
124
 
396 mathilde 125
	public function traiterRessources() {
402 mathilde 126
		$this->traiterRessources_NomService();
127
		$this->traiterRessources_TypeGraphique();
128
	}
129
 
130
	public function traiterRessources_TypeGraphique(){
131
		if (isset($this->ressources) && !empty($this->ressources[1])) {
132
			if(preg_match('/^(.+)\.nn:([0-9]+)$/', $this->ressources[1], $retour)==1){
133
				switch ($retour[1]) {
134
					case 'bdtfx' :
135
						$this->requete_condition[]= "num_nomen = ".$retour[2]." AND BDNT = 'BDTFX' ";
136
						break;
137
					case  'bdafx' :
138
						$this->requete_condition[] = "num_nomen = ".$retour[2]." AND BDNT = 'BDAFX' ";
139
						break;
140
					case  'bdbfx' :
141
						$this->requete_condition[] = "num_nomen = ".$retour[2]." AND BDNT = 'BDBFX' ";
142
						break;
143
					default :
144
						$e = 'Erreur dans l\'url de votre requête : </br> La ressource " '
145
					.$retour[1].' " n\'existe pas.';
146
					throw new Exception( $e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
147
					break;
148
				}
149
 
150
			}else {
151
				$e = 'Erreur dans l\'url de votre requête : </br> La ressource  n\'existe pas.';
152
				throw new Exception( $e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
153
			}
154
		} else {
155
			throw new Exception( "Erreur dans l\'url de votre requête :".
156
					"preciser le référentiel et le numéro nomenclatural sous la forme {bdnt}.nn:{nn}.",
157
			RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
396 mathilde 158
		}
159
 
160
	}
161
 
402 mathilde 162
	public function traiterRessources_NomService(){
163
		if (isset($this->ressources) && !empty($this->ressources[0])) {
164
			switch ($this->ressources[0]) {
165
				case  'climat' :
166
					$this->requete_champs = ' ve_lumiere , ve_temperature, ve_continentalite, ve_humidite_atmos' ;
167
					$this->nomGraphique= 'climat';
168
					break;
169
				case 'sol' :
170
					$this->requete_champs = ' ve_humidite_edaph , ve_reaction_sol, ve_nutriments_sol, ve_salinite,'
171
					.'ve_texture_sol, ve_mat_org_sol' ;
172
					$this->nomGraphique = 'sol';
173
					break;
174
				default :
175
					$e = 'Erreur dans l\'url de votre requête : </br> La ressource " '
176
				.$retour[1].' " n\'existe pas.';
177
				throw new Exception($e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
178
				break;
179
			}
180
		}else {
181
			throw new Exception("Erreur dans l\'url de votre requête :".
182
			"</br> precisez le graphique -> \"sol\" ou \"climat\".", RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
183
		}
184
	}
185
 
186
 
187
 
188
 
189
	//+-------------------------- formatage du résultat  -------------------------------------------+
190
 
191
 
192
	public function obtenirResultat($resultat) {
193
		if ($resultat == ""){
194
			$message = 'La requête SQL formée comporte une erreur!';
195
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
196
			throw new Exception($message, $code);
197
		}elseif ($resultat) {
198
			if ((count($this->ressources)) != 0) {
199
				$this->traiterValeursEcologiques($resultat[0]);
200
				$svg = $this->genererSVG();
201
				$resultat = new ResultatService();
410 mathilde 202
				$resultat->corps = ($this->parametres['retour'] == 'image/png') ? $this->convertirEnPNG($svg) : $svg;
203
				$resultat->mime = $this->parametres['retour'];
204
				}
396 mathilde 205
		} else {
402 mathilde 206
			$message = 'Les données recherchées sont introuvables.';
396 mathilde 207
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
208
			throw new Exception($message, $code);
209
		}
210
		return $resultat;
211
	}
212
 
402 mathilde 213
 
421 mathilde 214
	public function traiterValeursEcologiques($valeur){
215
		$this->valeurs_champs = $valeur;
402 mathilde 216
		//humidite edaphique sur echelle de 12
421 mathilde 217
		foreach($this->valeurs_champs as $cle => $val){
402 mathilde 218
			if ($cle == 've_humidite_edaph'){
219
				$this->valeurs_en_pourcentage[$cle] = round($val/12,1);
220
			}else{
221
				//salinite commence à 0
222
				if($val == 0){
223
					$this->valeurs_en_pourcentage[$cle] = 0;
224
				}else{
225
					$this->valeurs_en_pourcentage[$cle] = round($val/9,1);
226
				}
227
			}
228
		}
229
	}
230
 
231
	public function genererSVG(){
232
		$this->dom = new DOMDocument('1.0', 'UTF-8');
233
		//verifie que le xml est bien formé
234
		$this->dom->validateOnParse = true;
235
		$fichierSvg = $this->cheminGraphBase."".$this->nomGraphique.".svg";
421 mathilde 236
		$this->dom->load($fichierSvg);
402 mathilde 237
		$this->changerValeursSVG();
238
		$svg = $this->dom->saveXML();
239
		return $svg;
240
	}
241
 
242
 
243
 
244
	public function changerValeursSVG(){
245
		foreach ($this->valeurs_en_pourcentage as $cle => $val){
246
			$grad_id = array_search($val,$this->graduations_id);
247
			$Dompath = new DOMXPath($this->dom);
248
 			$element = $Dompath->query("//*[@id='".$grad_id."']")->item(0);
249
			$pos_x = $element->getAttribute('x1');
250
 			$curseur = $Dompath->query("//*[@id='".$cle."']")->item(0);
251
 			$curseur->setAttribute('cx', $pos_x);
421 mathilde 252
 			$this->ajouterInfoAuSurvol($curseur);
402 mathilde 253
 			$svg = $this->dom->getElementsByTagName("svg")->item(0);
254
 			$svg->setAttribute('width',$this->largeurSVG);
255
		}
256
	}
257
 
421 mathilde 258
	public function ajouterInfoAuSurvol($curseur){
259
		$champs = $curseur->getAttribute('id');
260
		$valeurTexte = $this->recupererOntologies($this->valeurs_champs[$champs], $champs );
261
		$curseur->setAttribute('title',$this->valeurs_champs[$champs].":".$valeurTexte->nom );
262
	}
263
 
264
	public function recupererOntologies($valeur, $champs){
265
		$url = $this->ajouterHref('ontologies',$this->champs_ontologiques[$champs].':'.urlencode(urlencode($valeur)));
266
		$val = $this->consulterHref($url);
267
		return $val;
268
	}
269
 
270
	public function convertirEnPNG($svg) {
410 mathilde 271
		$png = null;
272
 
273
		if (isset($this->convertisseur)) {
274
			if ($this->convertisseur == 'imagick') {
275
				if (extension_loaded('imagick')) {
276
					$png = $this->convertirEnPNGAvecImageMagick($svg);
277
				} else {
278
					$message = "Impossible de générer l'image sur le serveur. Extension ImageMagick absente.";
279
					$code = RestServeur::HTTP_CODE_ERREUR;
280
					throw new Exception($message, $code);
281
				}
282
			} else if ($this->convertisseur == 'rsvg') {
283
			$png = $this->convertirEnPNGAvecRsvg($svg);
284
			} else {
285
				$message = "Le convertisseur indiqué '{$this->convertisseur}' ne fait pas partie de la liste ".
286
						"des convertisseurs disponibles : imagick, rsvg.";
287
				$code = RestServeur::HTTP_CODE_ERREUR;
288
				throw new Exception($message, $code);
289
			}
290
		} else {
291
			$message = "Veuillez indiquer le convertisseur de svg à utiliser pour le service.";
292
			$code = RestServeur::HTTP_CODE_ERREUR;
293
			throw new Exception($message, $code);
294
		}
295
		return $png;
296
	}
297
 
421 mathilde 298
	public function convertirEnPNGAvecImageMagick($svg) {
410 mathilde 299
		$convertisseur = new Imagick();
418 mathilde 300
		$convertisseur->setBackgroundColor(new ImagickPixel('#F8F8F8'));
410 mathilde 301
		$convertisseur->readImageBlob($svg);
302
		$convertisseur->setImageFormat('png32');
303
		$convertisseur->resizeImage($this->largeurSVG, 0 , imagick::FILTER_LANCZOS, 0, true);
304
		$png = $convertisseur->getImageBlob();
305
		$convertisseur->clear();
306
		$convertisseur->destroy();
307
		return $png;
308
	}
309
 
421 mathilde 310
	public function convertirEnPNGAvecRsvg($svg) {
410 mathilde 311
		$idFichier = $this->getIdFichier();
312
		$fichierPng = $this->config['cache']['stockageChemin']."".$idFichier.'.png';
313
		$fichierSvg = $this->config['cache']['stockageChemin']."".$idFichier.'.svg';
314
		file_put_contents($fichierSvg, $svg);
421 mathilde 315
		$commande = "rsvg-convert  $fichierSvg -b #F8F8F8 -w $this->largeurSVG -a -o $fichierPng";
410 mathilde 316
		$rsvg = exec($commande);
317
		$this->indexerFichierPng($fichierPng);
318
		$png = file_get_contents($fichierPng);
319
		return $png;
320
	}
321
 
421 mathilde 322
	public function indexerFichierPng($fichierPng) {
410 mathilde 323
		$img = imagecreatefrompng($fichierPng);
324
		imagetruecolortopalette($img, false, 32);
325
		imagepng($img, $fichierPng, 9, PNG_ALL_FILTERS);
326
	}
327
 
421 mathilde 328
	public function getIdFichier(){
410 mathilde 329
		$idfichier = str_replace(".","-",$this->ressources[1]);
330
		$idfichier = str_replace(':','-',$idfichier);
418 mathilde 331
		$idfichier .= "-".$this->ressources[0];
410 mathilde 332
		return $idfichier;
333
	}
402 mathilde 334
	//+--------------------------FONCTIONS D'ASSEMBLAGE DE LA REQUETE-------------------------------------------+
335
 
336
	public function assemblerLaRequete() {
337
		$requete = 	' SELECT '.$this->requete_champs.'  FROM '.$this->table.' '.$this->retournerRequeteCondition();
338
		return $requete;
339
	}
340
 
341
	public  function retournerRequeteCondition() {
342
		$condition = '';
343
		if ($this->requete_condition !== "") {
344
			$condition = ' WHERE '.implode(' AND ', $this->requete_condition);
345
		}
346
		return $condition;
347
	}
348
 
349
 
350
 
396 mathilde 351
}
352
?>