Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 501 | Rev 512 | Go to most recent revision | Details | Compare with Previous | 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
*
7
*
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{
18
 
19
	protected $parametres = array();
20
	protected $ressources = array();
21
 
22
	protected $Bdd;
23
	protected $config;
24
	protected $cache;
25
	protected $metadonnees;
26
	protected $version;
27
	protected $serviceNom = 'Graphiques';
28
 
29
	protected $graduations_id = array();
30
	protected  $champs_ontologiques =  array();
31
	protected $nomGraphique = array();
32
 
33
	protected $table = '';
34
	protected $requete_condition = "";
35
	protected $requete_champs;
36
 
37
	protected $convertisseur;
38
	protected $cheminGraphBase;
39
	protected $valeurs_en_pourcentage = array();
40
	protected $dom;
41
	protected $largeurSVG = "500";
42
	protected $valeurs_champs;
43
 
44
 
45
	public function consulter($ressources, $parametres) {
46
		$this->ressources = $ressources;
47
		$this->parametres = $parametres;
506 mathilde 48
		$this->verifierParametres();
449 mathilde 49
		$this->initialiserConfiguration();
50
		$resultats = '';
51
		$this->traiterRessources();
52
		$requete = $this->assemblerLaRequete();
53
		$resultat = $this->resultat = $this->Bdd->recupererTous($requete);
54
		$versionResultat = $this->obtenirResultat($resultat);
55
		return $versionResultat;
56
	}
57
 
58
 
59
	//+--------------------------initialisation de paramètres  -------------------------------------------+
60
 
61
	private 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->graduations_id = $this->getParametreTableau('graduations_id');
67
		$this->champs_ontologiques = $this->getParametreTableau('champs_ontologiques');
68
		$this->cheminGraphBase = $this->config['chemin'];
69
		$cacheOptions = array('mise_en_cache' => $this->config['cache']['miseEnCache'],
70
								'stockage_chemin' => $this->config['cache']['stockageChemin'],
71
								'duree_de_vie' => $this->config['cache']['dureeDeVie']);
72
		$this->cache = $conteneur->getCacheSimple($cacheOptions);
73
		$this->definirVersion();
74
		$this->definirFormat();
75
		$this->definirTable($this->version);
76
	}
77
 
506 mathilde 78
 
79
 
449 mathilde 80
	abstract function definirTable($version);
81
 
82
 
83
	private function getParametreTableau($cle) {
84
		$tableau = array();
85
		$parametre = Config::get($cle);
86
		if (empty($parametre) === false) {
87
			$tableauPartiel = explode(',', $parametre);
88
			$tableauPartiel = array_map('trim', $tableauPartiel);
89
			foreach ($tableauPartiel as $champ) {
90
				if (strpos($champ, '=') !== false && strlen($champ) >= 3) {
91
					list($cle, $val) = explode('=', $champ);
92
					$tableau[trim($cle)] = trim($val);
93
				} else {
94
					$tableau[] = trim($champ);
95
				}
96
			}
97
		}
98
		return $tableau;
99
	}
506 mathilde 100
 
449 mathilde 101
	//+--------------------------traitement ressources ou paramètres  -------------------------------------------+
102
 
103
	//+---- paramètres ----+
104
 
506 mathilde 105
	private function verifierParametres() {
106
		if (isset($this->parametres)) {
107
			$parametres_dispo = array('retour', 'retour.format', 'version.projet');
108
			$parametres = array_keys($this->parametres);
109
			foreach ($parametres as $param) {
110
				if (!in_array($param, $parametres_dispo)) {
111
					$erreur = "Erreur : Le paramètre $param est inconnu.";
112
					$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
113
					throw new Exception($erreur, $code);
114
				}
115
			}
116
		}
117
 
118
	}
119
 
449 mathilde 120
	//on n'affiche qu'une version de graphique à la fois ( la dernière ou celle demandée )
121
	private function definirVersion() {
122
		$this->chargerVersions();
506 mathilde 123
		if (!isset($this->parametres['version.projet']) ) {
449 mathilde 124
			$this->version = $this->metadonnees[0]['version'];
506 mathilde 125
		} elseif ($this->parametres['version.projet'] == '+') {
126
				 $this->version = $this->metadonnees[0]['version'];
449 mathilde 127
		} else {
506 mathilde 128
			if($this->verifierVersion($this->parametres['version.projet'])) {
129
				$this->version = $this->parametres['version.projet'];
130
			}else {
131
				$erreur = "Erreur : La version est inconnue.";
132
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
133
				throw new Exception($erreur, $code);
134
			}
449 mathilde 135
		}
136
	}
137
 
506 mathilde 138
	private function verifierVersion($version){
139
		$retour = false;
140
		foreach ($this->metadonnees as $vers) {
141
			if ($vers['version'] == $version ) {
142
				$retour = true;
143
			}
144
		}
145
		return $retour;
146
	}
449 mathilde 147
	private function definirFormat() {
148
		if (isset($this->parametres['retour.format']) ){
149
			if (preg_match("/^[0-9]+$/", $this->parametres['retour.format'])){
150
				$this->largeurSVG = $this->parametres['retour.format'];
151
			}else {
506 mathilde 152
				$erreur = "Erreur : valeur inconnue. Entrez la largeur voulue (en pixels) pour le paramètre retour.format.";
449 mathilde 153
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
154
				throw new Exception($erreur, $code);
155
			}
156
		}
157
		if (!isset($this->parametres['retour']) ){
158
			$this->parametres['retour'] = 'image/svg+xml';
159
 
160
		}else {
161
			if (( $this->parametres['retour'] != 'image/svg+xml')&& ( $this->parametres['retour'] != 'image/png')){
506 mathilde 162
				$erreur = "Erreur : valeur inconnue. Choisissez le format de retour pour le paramètre retour : image/svg%2Bxml ou image/png.";
449 mathilde 163
				$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
164
				throw new Exception($erreur, $code);
165
			}
166
		}
167
	}
168
 
169
 
170
 
171
	private function chargerVersions() {
172
		$requete = "SELECT version ".
173
							"FROM ".Config::get('bdd_table_meta')." ".
174
							"ORDER BY date_creation DESC ";
175
		$resultats = $this->Bdd->recupererTous($requete);
176
		if (!is_array($resultats) || count($resultats) <= 0) {
177
			$message = "Les méta-données n'ont pu être chargée pour la ressource demandée";
178
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
179
			throw new Exception($message, $code);
180
		}
181
 
182
		$this->metadonnees = $resultats;
183
	}
184
 
185
	//+----- ressources -----+
186
 
187
 
188
	public function traiterRessources() {
501 mathilde 189
		if(isset($this->ressources)) {
190
			$this->traiterTypeGraphique();
191
			$this->traiterReferentielEtNum();
192
		} else {
193
			$e = 'Erreur dans l\'url de votre requête : </br> ressources insuffisantes.';
194
			throw new Exception( $e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
195
		}
449 mathilde 196
	}
197
 
198
	abstract function traiterReferentielEtNum();
199
	abstract function traiterTypeGraphique();
200
 
201
	//+--------------------------FONCTIONS D'ASSEMBLAGE DE LA REQUETE-------------------------------------------+
202
 
203
	public function assemblerLaRequete() {
204
		$requete = 	' SELECT '.$this->requete_champs.'  FROM '.$this->table.' '.$this->retournerRequeteCondition();
205
		return $requete;
206
	}
207
 
208
	public  function retournerRequeteCondition() {
209
		$condition = '';
210
		if ($this->requete_condition !== "") {
211
			$condition = ' WHERE '.implode(' AND ', $this->requete_condition);
212
		}
213
		return $condition;
214
	}
215
 
216
	//+-------------------------- formatage du résultat  -------------------------------------------+
217
 
218
	public function obtenirResultat($resultat) {
219
		if ($resultat == ""){
220
			$message = 'La requête SQL formée comporte une erreur!';
221
			$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
222
			throw new Exception($message, $code);
223
		}elseif ($resultat) {
224
			if ((count($this->ressources)) != 0) {
458 delphine 225
				//$Atraiter = array_filter($resultat[0],function($var){return ($var != '');});
226
				foreach ($resultat[0] as $champs => $valeur) {
227
					if ($valeur !== '') {
228
						$Atraiter[$champs] = $valeur;
229
					}
230
				}
449 mathilde 231
				if (!empty($Atraiter)) {
232
					$this->traiterValeursEcologiques($Atraiter);
233
					$svg = $this->genererSVG();
234
					$resultat = new ResultatService();
235
					$resultat->corps = ($this->parametres['retour'] == 'image/png') ? $this->convertirEnPNG($svg) : $svg;
236
					$resultat->mime = $this->parametres['retour'];
237
				} else {
238
					$resultat = null;
239
				}
240
			}
241
		} else {
242
			$resultat = null;
243
		}
244
		return $resultat;
245
	}
246
 
247
 
248
 
249
 
250
	//+----- modification svg -----+
251
 
252
 
253
 
254
	public function traiterValeursEcologiques($valeur){
255
		$this->valeurs_champs = $valeur;
256
 
257
		foreach($this->valeurs_champs as $cle => $val){
258
				if (preg_match("/ve_humidite_edaph/", $cle)) {
259
					$this->valeurs_en_pourcentage[$cle] = round($val/13,1);
260
				} elseif (preg_match("/ve_salinite/", $cle)) {
261
					$this->valeurs_en_pourcentage[$cle] = round(($val+1)/11,1);
262
				} else {
263
					$this->valeurs_en_pourcentage[$cle] = round($val/10,1);
264
				}
265
		}
266
	}
267
 
268
 
269
 
270
	public function genererSVG(){
271
		$svg = null;
272
		$this->dom = new DOMDocument('1.0', 'UTF-8');
273
		$this->dom->validateOnParse = true;
274
		$fichierSvg = $this->cheminGraphBase."".$this->nomGraphique.".svg";
275
		$this->dom->load($fichierSvg);
276
		$this->changerValeursSVG();
277
			$svg = $this->dom->saveXML();
278
		return $svg;
279
	}
280
 
281
	abstract function changerValeursSVG();
282
 
283
	public function recupererOntologies($valeur, $champs){
284
		$url = $this->ajouterHref('ontologies',$this->champs_ontologiques[$champs].':'.urlencode(urlencode($valeur)));
285
		$val = $this->consulterHref($url);
286
		return $val;
287
	}
288
 
465 mathilde 289
	public function traiterIntermediaires($valeurTexte,$champsOntologie, $champsTable){
473 mathilde 290
		if (preg_match("/(?:I|i)nterm(?:é|e)diaire(?:s)*/", $valeurTexte )) {
465 mathilde 291
			$prec = $this->recupererOntologies(($this->valeurs_champs[$champsTable]-1), $champsOntologie );
292
			$suiv = $this->recupererOntologies(($this->valeurs_champs[$champsTable]+1), $champsOntologie );
293
			$valeurTexte = "Intermédiaires entre $prec->nom et $suiv->nom ";
294
		}
295
		return $valeurTexte;
296
	}
297
 
449 mathilde 298
	/// +---- convertir png ----+
299
 
300
	public function convertirEnPNG($svg) {
301
		$png = null;
302
 
303
		if (isset($this->convertisseur)) {
304
			if ($this->convertisseur == 'imagick') {
305
				if (extension_loaded('imagick')) {
306
					$png = $this->convertirEnPNGAvecImageMagick($svg);
307
				} else {
308
					$message = "Impossible de générer l'image sur le serveur. Extension ImageMagick absente.";
309
					$code = RestServeur::HTTP_CODE_ERREUR;
310
					throw new Exception($message, $code);
311
				}
312
			} else if ($this->convertisseur == 'rsvg') {
313
				$png = $this->convertirEnPNGAvecRsvg($svg);
314
			} else {
315
				$message = "Le convertisseur indiqué '{$this->convertisseur}' ne fait pas partie de la liste ".
316
								"des convertisseurs disponibles : imagick, rsvg.";
317
				$code = RestServeur::HTTP_CODE_ERREUR;
318
				throw new Exception($message, $code);
319
			}
320
		} else {
321
			$message = "Veuillez indiquer le convertisseur de svg à utiliser pour le service.";
322
			$code = RestServeur::HTTP_CODE_ERREUR;
323
			throw new Exception($message, $code);
324
		}
325
		return $png;
326
	}
327
 
328
	public function convertirEnPNGAvecImageMagick($svg) {
329
		$convertisseur = new Imagick();
330
		$convertisseur->setBackgroundColor(new ImagickPixel('#F8F8F8'));
331
		$convertisseur->readImageBlob($svg);
332
		$convertisseur->setImageFormat('png32');
333
		$convertisseur->resizeImage($this->largeurSVG, 0 , imagick::FILTER_LANCZOS, 0, true);
334
		$png = $convertisseur->getImageBlob();
335
		$convertisseur->clear();
336
		$convertisseur->destroy();
337
		return $png;
338
	}
339
 
340
	public function convertirEnPNGAvecRsvg($svg) {
341
		$idFichier = $this->getIdFichier();
342
		$fichierPng = $this->config['cache']['stockageChemin']."".$idFichier.'.png';
343
		$fichierSvg = $this->config['cache']['stockageChemin']."".$idFichier.'.svg';
344
		file_put_contents($fichierSvg, $svg);
345
		$commande = "rsvg-convert  $fichierSvg -b #F8F8F8 -w $this->largeurSVG -a -o $fichierPng";
346
		$rsvg = exec($commande);
347
		$this->indexerFichierPng($fichierPng);
348
		$png = file_get_contents($fichierPng);
349
		return $png;
350
	}
351
 
352
	public function indexerFichierPng($fichierPng) {
353
		$img = imagecreatefrompng($fichierPng);
354
		imagetruecolortopalette($img, false, 32);
355
		imagepng($img, $fichierPng, 9, PNG_ALL_FILTERS);
356
	}
357
 
358
	public function getIdFichier(){
359
		$idfichier = str_replace(".","-",$this->ressources[1]);
360
		$idfichier = str_replace(':','-',$idfichier);
361
		$idfichier .= "-".$this->ressources[0];
362
		return $idfichier;
363
	}
364
}
365
?>