Subversion Repositories eFlore/Applications.del

Rev

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

Rev Author Line No. Line
720 gduche 1
<?php
2
// declare(encoding='UTF-8');
3
/**
737 gduche 4
	* Le web service observations récupère toutes les observations et, pour chacune d'elle, les
5
	* images qui lui sont associées.
720 gduche 6
 *
7
 * @category	php 5.2
8
 * @package	del
9
 * @subpackage images
10
 * @author		Jean-Pascal MILCENT <jpm@tela-botanica.org>
11
 * @copyright	Copyright (c) 2012, Tela Botanica (accueil@tela-botanica.org)
12
 * @license	http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
13
 * @license	http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
14
 * @version	$Id: Bdd.php 403 2012-02-22 14:35:20Z gduche $
737 gduche 15
 * @see http://www.tela-botanica.org/wikini/eflore/wakka.php?wiki=ApiIdentiplante01Observations
720 gduche 16
 */
17
 
755 gduche 18
class ListeObservations {
720 gduche 19
 
755 gduche 20
 
720 gduche 21
	private $conteneur;
726 gduche 22
	private $navigation;
23
	private $masque;
737 gduche 24
	private $gestionBdd;
25
	private $bdd;
720 gduche 26
 
27
	public function __construct(Conteneur $conteneur = null) {
28
		$this->conteneur = $conteneur == null ? new Conteneur() : $conteneur;
737 gduche 29
		$this->conteneur->chargerConfiguration('config_departements.ini');
776 aurelien 30
		$this->conteneur->chargerConfiguration('config_observations.ini');
787 delphine 31
		$this->conteneur->chargerConfiguration('config_votes.ini');
726 gduche 32
		$this->navigation = $conteneur->getNavigation();
33
		$this->masque = $conteneur->getMasque();
737 gduche 34
		$this->gestionBdd = $conteneur->getGestionBdd();
35
		$this->bdd = $this->gestionBdd->getBdd();
720 gduche 36
	}
37
 
38
	/**
39
	 * Méthode principale de la classe.
40
	 * Lance la récupération des images dans la base et les place dans un objet ResultatService
41
	 * pour l'afficher.
42
	 * @param array $ressources les ressources situées après l'url de base (ex : http://url/ressource1/ressource2)
43
	 * @param array $parametres les paramètres situés après le ? dans l'url
44
	 * */
45
	public function consulter($ressources, $parametres) {
46
 
47
		// Gestion des configuration du script
48
		$this->configurer();
49
		$this->verifierConfiguration();
50
 
51
		// Lancement du service
52
		$liaisons = $this->chargerLiaisons();
737 gduche 53
		$total = $this->compterObservations();
726 gduche 54
		$this->navigation->setTotal($total);
755 gduche 55
		$observations = $this->chargerObservations($liaisons);
56
		$observations = $this->chargerImages($observations);
57
		$observations = $this->chargerDeterminations($observations);
720 gduche 58
 
59
		// Mettre en forme le résultat et l'envoyer pour affichage
60
		$resultat = new ResultatService();
755 gduche 61
		$resultat->corps = array('entete' => $this->conteneur->getEntete(), 'resultats' => $observations);
720 gduche 62
		return $resultat;
63
	}
64
 
65
	/*-------------------------------------------------------------------------------
66
	 							CONFIGURATION DU SERVICE
67
	 --------------------------------------------------------------------------------*/
68
	/**
69
	 * Configuration du service en fonction du fichier de config config_del.ini
70
	 * */
755 gduche 71
	private function configurer() {
720 gduche 72
		$this->mappingFiltre = $this->conteneur->getParametre('mapping_masque');
73
		$this->mappingObservation = $this->conteneur->getParametre('mapping_observation');
787 delphine 74
		$this->mappingVotes = $this->conteneur->getParametre('mapping_votes');
720 gduche 75
	}
76
 
77
	/**
78
	 * Vérifier que le service est bien configuré
79
	 * */
755 gduche 80
	private function verifierConfiguration() {
737 gduche 81
 
720 gduche 82
		$erreurs = array();
755 gduche 83
		$tableauObservations = $this->conteneur->getParametre('observations');
84
		if (empty($tableauObservations)) {
720 gduche 85
			$erreurs[] = '- le fichier de configuration ne contient pas le tableau [images] ou celui-ci est vide ;';
86
		} else {
737 gduche 87
			if ($this->conteneur->getParametre('url_service') == null) {
720 gduche 88
				$erreurs[] = '- paramètre "url_service" manquant ;';
89
			}
90
 
737 gduche 91
			if ($this->conteneur->getParametre('url_images') == null) {
720 gduche 92
				$erreurs[] = '- paramètre "url_images" manquant ;';
93
			}
94
 
95
		}
96
 
97
		if (empty($this->mappingObservation)) {
98
			$erreurs[] = '- le fichier de configuration ne contient pas le tableau [mapping_observation] ou celui-ci est vide ;';
99
		} else {
100
			$champsMappingObs = array('id_observation', 'date_observation', 'date_transmission', 'famille', 'nom_sel', 'nom_sel_nn', 'nt',
737 gduche 101
								'ce_zone_geo', 'zone_geo', 'lieudit', 'station', 'courriel', 'ce_utilisateur', 'nom', 'prenom');
102
 
720 gduche 103
			foreach ($champsMappingObs as $champ) {
104
				if (!isset($this->mappingObservation[$champ])) {
105
					$erreurs[] = '- le mapping du champ "'.$champ.'" pour l\'observation est manquant ;';
106
				}
107
			}
108
		}
109
 
110
		if (empty($this->mappingFiltre)) {
111
			$erreurs[] = '- le fichier de configuration ne contient pas le tableau [mapping_masque] ou celui-ci est vide ;';
112
		} else {
113
			$champsMappingFiltre = array('famille', 'ns', 'nn', 'date', 'tag', 'commune');
114
			foreach ($champsMappingFiltre as $champ) {
115
				if (!isset($this->mappingFiltre[$champ])) {
116
					$erreurs[] = '- le mapping du champ "'.$champ.'" pour l\'observation est manquant ;';
117
				}
118
			}
119
		}
120
 
121
		if (!empty($erreurs)) {
122
			$e = 'Erreur lors de la configuration : '."\n";
123
			$e .= implode("\n", $erreurs);
124
			throw new Exception($e, RestServeur::HTTP_CODE_ERREUR);
737 gduche 125
		}
720 gduche 126
	}
127
 
128
 
129
 
130
	/**
131
	 * Obtenir une chaine de caractère concaténant nom et prénom séparé par une virgule
132
	 * @param String $auteurId l'identifiant de l'auteur
133
	 * @return String la chaine de concaténation
134
	 * */
135
	private function getChaineNomPrenom($auteurId) {
136
		$nomPrenom = explode(' ', $auteurId);
137
		$nomPrenom = $this->proteger($nomPrenom);
138
		$chaineNomPrenom = implode(', ', $nomPrenom);
139
		return $chaineNomPrenom;
140
	}
141
 
142
	/**
143
	* Charger la clause WHERE en fonction des paramètres de masque
144
	* */
145
	private function chargerClauseWhere() {
146
		$where = array();
737 gduche 147
		$tableauMasque = $this->masque->getMasque();
148
		// FIXME : Les communes avec une apostrophe (ex: saint michel d'euzet) arrivent dans les paramètres sans l'apostrophe
149
		if (!empty($tableauMasque)) {
150
			foreach($tableauMasque as $idMasque => $valeurMasque) {
151
 
152
				$idMasque = str_replace('masque.', '', $idMasque);
153
				switch ($idMasque) {
154
					// nom du masque => nom BDD
155
					case 'auteur' :
156
						$auteurId = $this->masque->getMasque('auteur');
157
						if (is_numeric($auteurId)) {
158
							$where[] = ' ce_utilisateur = '.$auteurId;
159
						} else {
160
							if (strpos($auteurId, '@') === false) {
161
								$chaineNomPrenom = $this->getChaineNomPrenom($auteurId);
162
								$where[] = '((nom IN ('.$chaineNomPrenom.')) OR (prenom IN ('.$chaineNomPrenom.')))';
163
							} else {
164
								$where[] = " courriel LIKE ".$this->proteger($this->masque->getMasque('auteur').'%')." ";
165
							}
166
						}
167
						break;
720 gduche 168
 
737 gduche 169
						//TODO : gérer le format de la date ?
170
						// rechercher sur LIKE DATE % ?
171
						// TODO : recherche sur JOUR MOIS ou ANNEE
172
					case 'departement' :
173
						$dept = $valeurMasque;
174
						if (is_numeric($dept)) {
744 gduche 175
							$dept = sprintf('%02s', $dept);
176
							$dept = sprintf("%-'_5s", $dept);
177
							$where[] = " ce_zone_geo LIKE ".$this->proteger('INSEE-C:'.$dept);
720 gduche 178
						} else {
737 gduche 179
 
180
							//FIXME : et les apostrophes dans les départements ?
181
 
182
							$deptId = $this->conteneur->getParametre($dept);
183
							if ($deptId != null) {
184
								$where[] = " ce_zone_geo LIKE ".$this->proteger('INSEE-C:'.$deptId.'%');
185
							}
720 gduche 186
						}
737 gduche 187
						break;
188
					case 'genre' :
744 gduche 189
						$where[] = ' '.$this->mappingFiltre['ns'].' LIKE '.$this->proteger('%'.$valeurMasque.'% %');
737 gduche 190
						break;
191
					case 'tag' :
744 gduche 192
						$where[] = " mots_cles_texte LIKE ".$this->proteger($valeurMasque);
737 gduche 193
						break;
744 gduche 194
					case 'nn' :
195
						$where[] = ' '.$this->mappingFiltre['nn'].'  = '.$this->proteger($valeurMasque);
740 gduche 196
						break;
776 aurelien 197
					case 'ns' :
198
							$where[] = " nom_sel LIKE ".$this->proteger($valeurMasque.'%');
199
						break;
737 gduche 200
					default:
744 gduche 201
						$where[] = ' '.$this->mappingFiltre[$idMasque].' LIKE '.$this->proteger('%'.$valeurMasque.'%');
737 gduche 202
				}
203
			}
720 gduche 204
		}
205
 
206
		if (!empty($where)) {
207
			return ' WHERE '.implode('AND', $where);
208
		} else {
209
			return;
210
		}
211
	}
212
 
213
	/*-------------------------------------------------------------------------------
745 gduche 214
								CHARGEMENT DES OBSERVATIONS
720 gduche 215
	--------------------------------------------------------------------------------*/
216
	/**
217
	* Chargement depuis la bdd de toutes les liaisons entre images et observations
218
	* */
219
	private function chargerLiaisons() {
220
 
221
		$requeteLiaisons = 'SELECT SQL_CALC_FOUND_ROWS * '.
737 gduche 222
						   'FROM '.$this->gestionBdd->formaterTable('del_observation', 'dob').
766 aurelien 223
						   'INNER JOIN '.$this->gestionBdd->formaterTable('del_obs_image', 'doi').
737 gduche 224
						   'ON doi.id_observation = dob.id_observation '.
720 gduche 225
						   'INNER JOIN del_utilisateur du '.
737 gduche 226
						   'ON du.id_utilisateur = doi.id_utilisateur ';
720 gduche 227
		$requeteLiaisons .= $this->chargerClauseWhere();
737 gduche 228
		$requeteLiaisons .=  ' GROUP BY doi.id_observation';
229
		$requeteLiaisons .= ' ORDER BY date_transmission DESC ';
230
		$requeteLiaisons .= $this->gestionBdd->getLimitSql();
231
 
720 gduche 232
		return $this->bdd->recupererTous($requeteLiaisons);
233
	}
234
 
235
	/**
236
	* Compter le nombre total d'images dans la base pour affichage dans entete.
237
	* */
737 gduche 238
	private function compterObservations() {
720 gduche 239
		$requete = 'SELECT FOUND_ROWS() AS nbre ';
240
		$resultats = $this->bdd->recuperer($requete);
766 aurelien 241
		return (int) $resultats['nbre'];
720 gduche 242
	}
243
 
244
	/**
245
	* Retourner un tableau d'images formaté en fonction des liaisons trouvées
246
	* @param $liaisons les liaisons de la table del_obs_images
247
	* */
737 gduche 248
	private function chargerObservations($liaisons) {
720 gduche 249
 
737 gduche 250
		$observations = array();
720 gduche 251
		foreach ($liaisons as $liaison) {
737 gduche 252
			$idObs = $liaison[$this->mappingObservation['id_observation']];
720 gduche 253
 
745 gduche 254
			$observation = $this->formaterObservation($liaison);
737 gduche 255
			$observations[$idObs] = $observation;
720 gduche 256
		}
737 gduche 257
		return $observations;
720 gduche 258
	}
259
 
260
	/**
737 gduche 261
	 * Sélectionner toutes les images de chaque observation
262
	 * @param array $observations la liste des observations
263
	 * */
755 gduche 264
	private function chargerImages($observations) {
720 gduche 265
 
737 gduche 266
		foreach ($observations as $id => $observation) {
720 gduche 267
 
766 aurelien 268
			$requeteImages = 'SELECT * FROM '. $this->gestionBdd->formaterTable('del_obs_image', 'doi').
737 gduche 269
							 'INNER JOIN '.$this->gestionBdd->formaterTable('del_image', 'di').
270
							 'ON doi.id_image = di.id_image '.
271
							 'WHERE doi.id_observation = '.$observation['id_observation'];
720 gduche 272
 
737 gduche 273
			$images = $this->bdd->recupererTous($requeteImages);
274
			$images = $this->formaterImages($images);
275
			$observations[$id]['images'] = $images;
720 gduche 276
		}
277
 
737 gduche 278
		return $observations;
720 gduche 279
	}
280
 
755 gduche 281
	/**
282
	* Récupérer toutes les déterminations et le nombre de commentaire au total
283
	* @param array $observations la liste des observations à mettre à jour
284
	* */
285
	private function chargerDeterminations($observations) {
286
		foreach ($observations as $id => $observation) {
287
			$requetePropositions = 'SELECT * FROM '.$this->gestionBdd->formaterTable('del_commentaire', 'dc').
288
									   'WHERE dc.nom_sel IS NOT NULL AND ce_observation = '.$observation['id_observation'];
289
			$propositions = $this->bdd->recupererTous($requetePropositions);
781 delphine 290
			$observations[$id]['propositions'] = $this->formaterDeterminations($propositions);
755 gduche 291
		}
292
		return $observations;
293
	}
737 gduche 294
 
781 delphine 295
	private function formaterDeterminations($propositions) {
296
		$propositions_format = array();
297
		if ($propositions != array()) {
298
			foreach ($propositions as $id => $proposition) {
299
				$propositions_format[$proposition['id_commentaire']] = $proposition;
300
				$ids_proposition[] = $proposition['id_commentaire'];
301
			}
302
			$propositions_format = $this->chargerVotes($ids_proposition, $propositions_format);
303
			$propositions_format = $this->chargerNombreCommentaire($ids_proposition, $propositions_format);
304
		}
305
		return $propositions_format;
306
	}
755 gduche 307
	/**
781 delphine 308
	 * Charger les votes sur les déterminations
309
	 * @param Array $observations le tableau des observatins à mettre à jour
310
	* */
311
	private function chargerVotes($ids_proposition, $propositions) {
312
		$requeteVotes = 'SELECT * FROM '.
313
			$this->gestionBdd->formaterTable('del_commentaire_vote').
314
			'WHERE ce_proposition IN ('.implode(', ', $ids_proposition).')';
315
 
316
		$resultatsVotes = $this->bdd->recupererTous($requeteVotes);
317
		foreach ($resultatsVotes as $vote) {
787 delphine 318
			$propositions[$vote['ce_proposition']]['votes'][] = $this->formaterVotes($vote);
781 delphine 319
		}
320
		return $propositions;
321
	}
322
 
323
	/**
755 gduche 324
	 * Charger le nombre de commentaires (sans détermination) associé à l'observation
325
	 * @param Array $observations le tableau des observatins à mettre à jour
326
	 * */
781 delphine 327
	private function chargerNombreCommentaire($ids_proposition, $propositions) {
328
		$requeteNbCommentaires = 'SELECT ce_proposition, COUNT('.$this->proteger('id_commentaire').') as nb '.
329
									'FROM '.$this->gestionBdd->formaterTable('del_commentaire').
330
									'WHERE ce_proposition IN ('.implode(', ', $ids_proposition).')';
331
		$nbCommentaires = $this->bdd->recuperer($requeteNbCommentaires);
332
		foreach ($nbCommentaires as $vote) {
333
			$propositions[$vote['ce_proposition']]['commentaires']= $vote;
755 gduche 334
		}
781 delphine 335
		return $propositions;
755 gduche 336
	}
737 gduche 337
 
720 gduche 338
	/*-------------------------------------------------------------------------------
339
								FORMATER ET METTRE EN FORME
340
	--------------------------------------------------------------------------------*/
341
 
342
	/**
737 gduche 343
	 * Formater les images d'une observation
344
	 * @param array $images les images de l'observation
345
	 * */
346
	private function formaterImages($images) {
347
		$imagesRetour = array();
348
		foreach ($images as $image) {
349
			$imageCourante = array();
350
			$imageCourante['id_image'] = $image['id_image'];
351
			$imageCourante['date'] = $image['date_prise_de_vue'];
352
			$imageCourante['binaire.href'] = $this->formaterLienImage($image['id_image']);
353
			$imageCourante['hauteur'] = $image['hauteur'];
354
			$imageRetour['largeur'] = $image['largeur'];
355
 
356
			$imagesRetour[] = $imageCourante;
357
		}
358
 
359
		return $imagesRetour;
360
	}
361
 
362
	/**
720 gduche 363
	*  Formater une observation depuis une ligne liaison
364
	*  @param $liaison liaison issue de la recherche
365
	*  @return $observation l'observation mise en forme
366
	* */
367
	private function formaterObservation($liaison) {
368
		$observation = array();
369
 
370
		foreach ($this->mappingObservation as $nomOriginal => $nomFinal) {
371
			$observation[$nomFinal] = $liaison[$nomOriginal];
372
		}
745 gduche 373
 
374
		$observation['images'] = array();
720 gduche 375
 
376
		return $observation;
377
	}
378
 
379
 
380
	/**
381
	 * Formater le lien de l'image en fonction du fichier de config et de l'identifiant de l'image
382
	 * */
383
	private function formaterLienImage($idImage) {
384
		$idImage = sprintf('%09s', $idImage);
385
		$url = $this->conteneur->getParametre('url_images');
386
		$urlImage = str_replace('%s', $idImage, $url);
387
		return $urlImage;
388
	}
389
 
787 delphine 390
	/**
391
	*  Formater un vote en fonction du fichier de configuration config_votes.ini
392
	*  @param $votes array()
393
	* */
394
	private function formaterVotes($vote) {
395
		$retour = array();
396
		foreach ($vote as $param=>$valeur) {
397
			$retour[$vote['id_vote']][$this->mappingVotes[$param]] = $valeur;
398
		}
399
		return $retour;
400
	}
401
 
720 gduche 402
	private function proteger($valeur) {
403
		if (is_array($valeur)) {
404
			return $this->bdd->protegerTableau($valeur);
405
		} else {
406
			return $this->bdd->proteger($valeur);
407
		}
408
	}
409
}
410
?>