Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 458 | 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
*
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) {
187
				$Atraiter = array_filter($resultat[0],function($var){return ($var != '');});
188
				if (!empty($Atraiter)) {
189
					$this->traiterValeursEcologiques($Atraiter);
190
					$svg = $this->genererSVG();
191
					$resultat = new ResultatService();
192
					$resultat->corps = ($this->parametres['retour'] == 'image/png') ? $this->convertirEnPNG($svg) : $svg;
193
					$resultat->mime = $this->parametres['retour'];
194
				} else {
195
					$resultat = null;
196
				}
197
			}
198
		} else {
199
			$resultat = null;
200
		}
201
		return $resultat;
202
	}
203
 
204
 
205
 
206
 
207
	//+----- modification svg -----+
208
 
209
 
210
 
211
	public function traiterValeursEcologiques($valeur){
212
		$this->valeurs_champs = $valeur;
213
 
214
		foreach($this->valeurs_champs as $cle => $val){
215
				if (preg_match("/ve_humidite_edaph/", $cle)) {
216
					$this->valeurs_en_pourcentage[$cle] = round($val/13,1);
217
				} elseif (preg_match("/ve_salinite/", $cle)) {
218
					$this->valeurs_en_pourcentage[$cle] = round(($val+1)/11,1);
219
				} else {
220
					$this->valeurs_en_pourcentage[$cle] = round($val/10,1);
221
				}
222
		}
223
	}
224
 
225
 
226
 
227
	public function genererSVG(){
228
		$svg = null;
229
		$this->dom = new DOMDocument('1.0', 'UTF-8');
230
		$this->dom->validateOnParse = true;
231
		$fichierSvg = $this->cheminGraphBase."".$this->nomGraphique.".svg";
232
		$this->dom->load($fichierSvg);
233
		$this->changerValeursSVG();
234
			$svg = $this->dom->saveXML();
235
		return $svg;
236
	}
237
 
238
	abstract function changerValeursSVG();
239
 
240
	public function recupererOntologies($valeur, $champs){
241
		$url = $this->ajouterHref('ontologies',$this->champs_ontologiques[$champs].':'.urlencode(urlencode($valeur)));
242
		$val = $this->consulterHref($url);
243
		return $val;
244
	}
245
 
246
	/// +---- convertir png ----+
247
 
248
	public function convertirEnPNG($svg) {
249
		$png = null;
250
 
251
		if (isset($this->convertisseur)) {
252
			if ($this->convertisseur == 'imagick') {
253
				if (extension_loaded('imagick')) {
254
					$png = $this->convertirEnPNGAvecImageMagick($svg);
255
				} else {
256
					$message = "Impossible de générer l'image sur le serveur. Extension ImageMagick absente.";
257
					$code = RestServeur::HTTP_CODE_ERREUR;
258
					throw new Exception($message, $code);
259
				}
260
			} else if ($this->convertisseur == 'rsvg') {
261
				$png = $this->convertirEnPNGAvecRsvg($svg);
262
			} else {
263
				$message = "Le convertisseur indiqué '{$this->convertisseur}' ne fait pas partie de la liste ".
264
								"des convertisseurs disponibles : imagick, rsvg.";
265
				$code = RestServeur::HTTP_CODE_ERREUR;
266
				throw new Exception($message, $code);
267
			}
268
		} else {
269
			$message = "Veuillez indiquer le convertisseur de svg à utiliser pour le service.";
270
			$code = RestServeur::HTTP_CODE_ERREUR;
271
			throw new Exception($message, $code);
272
		}
273
		return $png;
274
	}
275
 
276
	public function convertirEnPNGAvecImageMagick($svg) {
277
		$convertisseur = new Imagick();
278
		$convertisseur->setBackgroundColor(new ImagickPixel('#F8F8F8'));
279
		$convertisseur->readImageBlob($svg);
280
		$convertisseur->setImageFormat('png32');
281
		$convertisseur->resizeImage($this->largeurSVG, 0 , imagick::FILTER_LANCZOS, 0, true);
282
		$png = $convertisseur->getImageBlob();
283
		$convertisseur->clear();
284
		$convertisseur->destroy();
285
		return $png;
286
	}
287
 
288
	public function convertirEnPNGAvecRsvg($svg) {
289
		$idFichier = $this->getIdFichier();
290
		$fichierPng = $this->config['cache']['stockageChemin']."".$idFichier.'.png';
291
		$fichierSvg = $this->config['cache']['stockageChemin']."".$idFichier.'.svg';
292
		file_put_contents($fichierSvg, $svg);
293
		$commande = "rsvg-convert  $fichierSvg -b #F8F8F8 -w $this->largeurSVG -a -o $fichierPng";
294
		$rsvg = exec($commande);
295
		$this->indexerFichierPng($fichierPng);
296
		$png = file_get_contents($fichierPng);
297
		return $png;
298
	}
299
 
300
	public function indexerFichierPng($fichierPng) {
301
		$img = imagecreatefrompng($fichierPng);
302
		imagetruecolortopalette($img, false, 32);
303
		imagepng($img, $fichierPng, 9, PNG_ALL_FILTERS);
304
	}
305
 
306
	public function getIdFichier(){
307
		$idfichier = str_replace(".","-",$this->ressources[1]);
308
		$idfichier = str_replace(':','-',$idfichier);
309
		$idfichier .= "-".$this->ressources[0];
310
		return $idfichier;
311
	}
312
}
313
?>