Subversion Repositories eFlore/Applications.del

Rev

Rev 787 | 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;
790 aurelien 29
		$this->conteneur->chargerConfiguration('config_departements_bruts.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
		if (!empty($tableauMasque)) {
149
			foreach($tableauMasque as $idMasque => $valeurMasque) {
150
 
151
				$idMasque = str_replace('masque.', '', $idMasque);
152
				switch ($idMasque) {
153
					// nom du masque => nom BDD
154
					case 'auteur' :
790 aurelien 155
						$where[] = $this->creerFiltreAuteur($this->masque->getMasque('auteur'));
737 gduche 156
						break;
790 aurelien 157
					case 'date' :
158
						$where[] = $this->creerFiltreDate($valeurMasque);
159
						break;
737 gduche 160
					case 'departement' :
790 aurelien 161
						$where[] = $this->creerFiltreIdZoneGeo($valeurMasque);
737 gduche 162
						break;
163
					case 'genre' :
744 gduche 164
						$where[] = ' '.$this->mappingFiltre['ns'].' LIKE '.$this->proteger('%'.$valeurMasque.'% %');
737 gduche 165
						break;
166
					case 'tag' :
790 aurelien 167
						$where[] = $this->creerFiltreMotsCles($valeurMasque);
737 gduche 168
						break;
744 gduche 169
					case 'nn' :
170
						$where[] = ' '.$this->mappingFiltre['nn'].'  = '.$this->proteger($valeurMasque);
740 gduche 171
						break;
776 aurelien 172
					case 'ns' :
790 aurelien 173
						$where[] = " nom_sel LIKE ".$this->proteger($valeurMasque.'%');
776 aurelien 174
						break;
790 aurelien 175
					case 'commune' :
176
						$where[] = ' '.$this->mappingFiltre[$idMasque].' LIKE '.$this->proteger($this->remplacerParJokerCaractere($valeurMasque).'%');
177
					break;
178
					case 'masque' :
179
						$where[] = $this->creerFiltreMasqueGeneral($valeurMasque);
180
						break;
737 gduche 181
					default:
744 gduche 182
						$where[] = ' '.$this->mappingFiltre[$idMasque].' LIKE '.$this->proteger('%'.$valeurMasque.'%');
737 gduche 183
				}
184
			}
720 gduche 185
		}
186
 
187
		if (!empty($where)) {
188
			return ' WHERE '.implode('AND', $where);
189
		} else {
190
			return;
191
		}
192
	}
193
 
790 aurelien 194
	private function creerFiltreMasqueGeneral($valeurMasque) {
195
 
196
		// créer filtre auteur et idzone géo peuvent renvoyer des valeurs vides
197
		$whereAuteur = $this->creerFiltreAuteur($valeurMasque);
198
		$whereIdZoneGeo = $this->creerFiltreIdZoneGeo($valeurMasque);
199
 
200
		$masqueGeneral = '( '.
201
                   	(($whereAuteur != '') ? $whereAuteur.' OR ' : '' ).
202
				   	(($whereIdZoneGeo != '') ? $whereIdZoneGeo.' OR ' : '' ).
203
					'zone_geo LIKE '.$this->proteger($this->remplacerParJokerCaractere($valeurMasque).'%').' OR '.
204
					$this->creerFiltreMotsCles($valeurMasque).' OR '.
205
					'nom_sel LIKE '.$this->proteger($valeurMasque.'%').' OR '.
206
					'famille LIKE '.$this->proteger($valeurMasque.'%').' OR '.
207
					'milieu LIKE '.$this->proteger($valeurMasque).' OR '.
208
					$this->mappingFiltre['ns'].' LIKE '.$this->proteger('%'.$valeurMasque.'% %').' OR '.
209
					$this->creerFiltreDate($valeurMasque).
210
					') ';
211
 
212
		return $masqueGeneral;
213
	}
214
 
215
	private function creerFiltreAuteur($valeurMasque) {
216
		$masque = '';
217
		$auteurId = $valeurMasque;
218
		if (is_numeric($auteurId)) {
219
			$masque = ' ce_utilisateur = '.$auteurId;
220
		} else {
221
			if (strpos($auteurId, '@') === false) {
222
				$tableauNomPrenom = explode(' ',$auteurId, 2);
223
				if(count($tableauNomPrenom) == 2) {
224
					// on teste potentiellement un nom prenom ou bien un prénom nom
225
					$masque = '('.
226
						          	'(nom LIKE '.$this->proteger($tableauNomPrenom[0].'%').' AND '.
227
								  	'prenom LIKE '.$this->proteger($tableauNomPrenom[1].'%').') OR '.
228
								 	'(nom LIKE '.$this->proteger($tableauNomPrenom[1].'%').' AND '.
229
								  	'prenom LIKE '.$this->proteger($tableauNomPrenom[0].'%').')'.
230
								  ')';
231
				} else {
232
					$masque = '(
233
						            (nom LIKE '.$this->proteger($auteurId.'%').' OR '.
234
									'prenom LIKE '.$this->proteger($auteurId.'%').')'.
235
								  ')';
236
				}
237
			} else {
238
				$masque = " courriel LIKE ".$this->proteger($valeurMasque.'%')." ";
239
			}
240
		}
241
		return $masque;
242
	}
243
 
244
	private function remplacerParJokerCaractere($valeurMasque) {
245
		return str_replace(array('-',' '), '_', $valeurMasque);
246
	}
247
	//TODO: déplacer les fonctions ci dessus et dessous dans une classe
248
	// utilitaire
249
	function supprimerAccents($str, $charset='utf-8')
250
	{
251
		$str = htmlentities($str, ENT_NOQUOTES, $charset);
252
 
253
		$str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
254
		$str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); // pour les ligatures e.g. '&oelig;'
255
		$str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères
256
 
257
		return $str;
258
	}
259
 
260
	private function obtenirIdDepartement($nomDpt) {
261
 
262
		$nomDpt = $this->supprimerAccents($nomDpt);
263
		$nomDpt = strtolower(str_replace(' ','-',$nomDpt));
264
 
265
		$idDpt = $this->conteneur->getParametre($nomDpt);
266
		if($idDpt == null || $idDpt == ' ') {
267
			$idDpt = ' ';
268
		}
269
		return $idDpt;
270
	}
271
 
272
	private function creerFiltreIdZoneGeo($valeurMasque) {
273
		$masque = '';
274
		$dept = $valeurMasque;
275
		if (is_numeric($dept)) {
276
			$dept = sprintf('%02s', $dept);
277
			$dept = sprintf("%-'_5s", $dept);
278
			$masque = " ce_zone_geo LIKE ".$this->proteger('INSEE-C:'.$dept);
279
		} else {
280
			$deptId = $this->conteneur->getParametre($dept);
281
			if ($deptId != null) {
282
				$masque = " ce_zone_geo LIKE ".$this->proteger('INSEE-C:'.$deptId.'%');
283
			} else {
284
				$id = $this->obtenirIdDepartement($valeurMasque);
285
				$masque = " ce_zone_geo LIKE ".$this->proteger('INSEE-C:'.$id.'%');
286
			}
287
		}
288
		return $masque;
289
	}
290
 
291
	private function creerFiltreDate($valeurMasque) {
292
		//TODO: définir dans le fichier de config un tableau contenant plusieurs format de date
293
		// autorisés pour la recherche, qui seraient ajoutés au OR
294
		$masque = '(';
295
		$masque .= (is_numeric($valeurMasque)) ? ' YEAR(date_observation) = '.$this->proteger($valeurMasque).' OR ' : '';
296
		$masque .= " DATE_FORMAT(date_observation, '%d/%m/%Y') = ".$this->proteger($valeurMasque).' '.
297
		           ')';
298
		return $masque;
299
	}
300
 
301
	private function creerFiltreMotsCles($valeurMasque) {
302
		$masque = '(di.mots_cles_texte LIKE '.$this->proteger('%'.$valeurMasque.'%').' OR '.
303
			                 ' dob.mots_cles_texte LIKE '.$this->proteger('%'.$valeurMasque.'%').') ';
304
		return $masque;
305
	}
306
 
720 gduche 307
	/*-------------------------------------------------------------------------------
745 gduche 308
								CHARGEMENT DES OBSERVATIONS
720 gduche 309
	--------------------------------------------------------------------------------*/
310
	/**
311
	* Chargement depuis la bdd de toutes les liaisons entre images et observations
312
	* */
313
	private function chargerLiaisons() {
790 aurelien 314
		// ajout seulement du champ mot clés de la table image liée, pour rechercher
315
		// sur les mots clés obs et images
316
		$requeteLiaisons = 'SELECT SQL_CALC_FOUND_ROWS *, di.mots_cles_texte '.
737 gduche 317
						   'FROM '.$this->gestionBdd->formaterTable('del_observation', 'dob').
766 aurelien 318
						   'INNER JOIN '.$this->gestionBdd->formaterTable('del_obs_image', 'doi').
737 gduche 319
						   'ON doi.id_observation = dob.id_observation '.
720 gduche 320
						   'INNER JOIN del_utilisateur du '.
790 aurelien 321
						   'ON du.id_utilisateur = doi.id_utilisateur '.
322
						   'INNER JOIN '.$this->gestionBdd->formaterTable('del_image', 'di').
323
						   'ON di.id_image = doi.id_image ';
720 gduche 324
		$requeteLiaisons .= $this->chargerClauseWhere();
737 gduche 325
		$requeteLiaisons .=  ' GROUP BY doi.id_observation';
326
		$requeteLiaisons .= ' ORDER BY date_transmission DESC ';
327
		$requeteLiaisons .= $this->gestionBdd->getLimitSql();
790 aurelien 328
 
720 gduche 329
		return $this->bdd->recupererTous($requeteLiaisons);
330
	}
331
 
332
	/**
333
	* Compter le nombre total d'images dans la base pour affichage dans entete.
334
	* */
737 gduche 335
	private function compterObservations() {
720 gduche 336
		$requete = 'SELECT FOUND_ROWS() AS nbre ';
337
		$resultats = $this->bdd->recuperer($requete);
766 aurelien 338
		return (int) $resultats['nbre'];
720 gduche 339
	}
340
 
341
	/**
342
	* Retourner un tableau d'images formaté en fonction des liaisons trouvées
343
	* @param $liaisons les liaisons de la table del_obs_images
344
	* */
737 gduche 345
	private function chargerObservations($liaisons) {
720 gduche 346
 
737 gduche 347
		$observations = array();
720 gduche 348
		foreach ($liaisons as $liaison) {
737 gduche 349
			$idObs = $liaison[$this->mappingObservation['id_observation']];
720 gduche 350
 
745 gduche 351
			$observation = $this->formaterObservation($liaison);
737 gduche 352
			$observations[$idObs] = $observation;
720 gduche 353
		}
737 gduche 354
		return $observations;
720 gduche 355
	}
356
 
357
	/**
737 gduche 358
	 * Sélectionner toutes les images de chaque observation
359
	 * @param array $observations la liste des observations
360
	 * */
755 gduche 361
	private function chargerImages($observations) {
720 gduche 362
 
737 gduche 363
		foreach ($observations as $id => $observation) {
720 gduche 364
 
766 aurelien 365
			$requeteImages = 'SELECT * FROM '. $this->gestionBdd->formaterTable('del_obs_image', 'doi').
737 gduche 366
							 'INNER JOIN '.$this->gestionBdd->formaterTable('del_image', 'di').
367
							 'ON doi.id_image = di.id_image '.
368
							 'WHERE doi.id_observation = '.$observation['id_observation'];
720 gduche 369
 
737 gduche 370
			$images = $this->bdd->recupererTous($requeteImages);
371
			$images = $this->formaterImages($images);
372
			$observations[$id]['images'] = $images;
720 gduche 373
		}
374
 
737 gduche 375
		return $observations;
720 gduche 376
	}
377
 
755 gduche 378
	/**
379
	* Récupérer toutes les déterminations et le nombre de commentaire au total
380
	* @param array $observations la liste des observations à mettre à jour
381
	* */
382
	private function chargerDeterminations($observations) {
383
		foreach ($observations as $id => $observation) {
384
			$requetePropositions = 'SELECT * FROM '.$this->gestionBdd->formaterTable('del_commentaire', 'dc').
385
									   'WHERE dc.nom_sel IS NOT NULL AND ce_observation = '.$observation['id_observation'];
386
			$propositions = $this->bdd->recupererTous($requetePropositions);
781 delphine 387
			$observations[$id]['propositions'] = $this->formaterDeterminations($propositions);
755 gduche 388
		}
389
		return $observations;
390
	}
737 gduche 391
 
781 delphine 392
	private function formaterDeterminations($propositions) {
393
		$propositions_format = array();
394
		if ($propositions != array()) {
395
			foreach ($propositions as $id => $proposition) {
396
				$propositions_format[$proposition['id_commentaire']] = $proposition;
397
				$ids_proposition[] = $proposition['id_commentaire'];
398
			}
399
			$propositions_format = $this->chargerVotes($ids_proposition, $propositions_format);
400
			$propositions_format = $this->chargerNombreCommentaire($ids_proposition, $propositions_format);
401
		}
402
		return $propositions_format;
403
	}
755 gduche 404
	/**
781 delphine 405
	 * Charger les votes sur les déterminations
406
	 * @param Array $observations le tableau des observatins à mettre à jour
407
	* */
408
	private function chargerVotes($ids_proposition, $propositions) {
409
		$requeteVotes = 'SELECT * FROM '.
410
			$this->gestionBdd->formaterTable('del_commentaire_vote').
411
			'WHERE ce_proposition IN ('.implode(', ', $ids_proposition).')';
412
 
413
		$resultatsVotes = $this->bdd->recupererTous($requeteVotes);
414
		foreach ($resultatsVotes as $vote) {
787 delphine 415
			$propositions[$vote['ce_proposition']]['votes'][] = $this->formaterVotes($vote);
781 delphine 416
		}
417
		return $propositions;
418
	}
419
 
420
	/**
755 gduche 421
	 * Charger le nombre de commentaires (sans détermination) associé à l'observation
422
	 * @param Array $observations le tableau des observatins à mettre à jour
423
	 * */
781 delphine 424
	private function chargerNombreCommentaire($ids_proposition, $propositions) {
425
		$requeteNbCommentaires = 'SELECT ce_proposition, COUNT('.$this->proteger('id_commentaire').') as nb '.
426
									'FROM '.$this->gestionBdd->formaterTable('del_commentaire').
427
									'WHERE ce_proposition IN ('.implode(', ', $ids_proposition).')';
428
		$nbCommentaires = $this->bdd->recuperer($requeteNbCommentaires);
429
		foreach ($nbCommentaires as $vote) {
430
			$propositions[$vote['ce_proposition']]['commentaires']= $vote;
755 gduche 431
		}
781 delphine 432
		return $propositions;
755 gduche 433
	}
737 gduche 434
 
720 gduche 435
	/*-------------------------------------------------------------------------------
436
								FORMATER ET METTRE EN FORME
437
	--------------------------------------------------------------------------------*/
438
 
439
	/**
737 gduche 440
	 * Formater les images d'une observation
441
	 * @param array $images les images de l'observation
442
	 * */
443
	private function formaterImages($images) {
444
		$imagesRetour = array();
445
		foreach ($images as $image) {
446
			$imageCourante = array();
447
			$imageCourante['id_image'] = $image['id_image'];
448
			$imageCourante['date'] = $image['date_prise_de_vue'];
449
			$imageCourante['binaire.href'] = $this->formaterLienImage($image['id_image']);
450
			$imageCourante['hauteur'] = $image['hauteur'];
451
			$imageRetour['largeur'] = $image['largeur'];
452
 
453
			$imagesRetour[] = $imageCourante;
454
		}
455
 
456
		return $imagesRetour;
457
	}
458
 
459
	/**
720 gduche 460
	*  Formater une observation depuis une ligne liaison
461
	*  @param $liaison liaison issue de la recherche
462
	*  @return $observation l'observation mise en forme
463
	* */
464
	private function formaterObservation($liaison) {
465
		$observation = array();
466
 
467
		foreach ($this->mappingObservation as $nomOriginal => $nomFinal) {
468
			$observation[$nomFinal] = $liaison[$nomOriginal];
469
		}
745 gduche 470
 
471
		$observation['images'] = array();
720 gduche 472
 
473
		return $observation;
474
	}
475
 
476
 
477
	/**
478
	 * Formater le lien de l'image en fonction du fichier de config et de l'identifiant de l'image
479
	 * */
480
	private function formaterLienImage($idImage) {
481
		$idImage = sprintf('%09s', $idImage);
482
		$url = $this->conteneur->getParametre('url_images');
483
		$urlImage = str_replace('%s', $idImage, $url);
484
		return $urlImage;
485
	}
486
 
787 delphine 487
	/**
488
	*  Formater un vote en fonction du fichier de configuration config_votes.ini
489
	*  @param $votes array()
490
	* */
491
	private function formaterVotes($vote) {
492
		$retour = array();
493
		foreach ($vote as $param=>$valeur) {
494
			$retour[$vote['id_vote']][$this->mappingVotes[$param]] = $valeur;
495
		}
496
		return $retour;
497
	}
498
 
720 gduche 499
	private function proteger($valeur) {
500
		if (is_array($valeur)) {
501
			return $this->bdd->protegerTableau($valeur);
502
		} else {
503
			return $this->bdd->proteger($valeur);
504
		}
505
	}
506
}
507
?>