Subversion Repositories eFlore/Projets.eflore-projets

Rev

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