Subversion Repositories eFlore/Applications.del

Rev

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

Rev Author Line No. Line
761 gduche 1
<?php
2
// declare(encoding='UTF-8');
3
/**
4
	* Le web service observations récupère toutes les observations et, pour chacune d'elle, les
5
	* images qui lui sont associées.
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 $
15
 * @see http://www.tela-botanica.org/wikini/eflore/wakka.php?wiki=ApiIdentiplante01Observations
16
 */
17
 
18
// http://localhost/del/services/0.1/observations/#id => une observation donnée et ses images, SANS LES propositions & nombre de commentaire
19
class Observation {
20
 
21
	private $conteneur;
22
	private $gestionBdd;
23
	private $bdd;
24
	private $id_observation;
841 aurelien 25
	private $imageIds;
761 gduche 26
 
27
	public function __construct(Conteneur $conteneur = null) {
28
		$this->conteneur = $conteneur == null ? new Conteneur() : $conteneur;
787 delphine 29
		$this->conteneur->chargerConfiguration('config_votes.ini');
841 aurelien 30
		$this->conteneur->chargerConfiguration('config_mapping_votes.ini');
950 aurelien 31
		$this->conteneur->chargerConfiguration('config_mapping_commentaires.ini');
761 gduche 32
		$this->gestionBdd = $conteneur->getGestionBdd();
33
		$this->bdd = $this->gestionBdd->getBdd();
34
	}
35
 
36
	/**
37
	 * Méthode principale de la classe.
38
	 * Lance la récupération des images dans la base et les place dans un objet ResultatService
39
	 * pour l'afficher.
40
	 * @param array $ressources les ressources situées après l'url de base (ex : http://url/ressource1/ressource2)
41
	 * @param array $parametres les paramètres situés après le ? dans l'url
42
	 * */
43
	public function consulter($ressources, $parametres) {
44
 
45
		// Gestion des configuration du script
46
		$this->configurer($ressources);
47
		$this->verifierConfiguration();
48
 
49
		// Lancement du service
50
		$liaisons = $this->chargerLiaisons();
1361 raphael 51
		$observation = array();
52
 
53
		if($liaisons) {
54
			$observation = $this->chargerObservation($liaisons);
55
			// modifie $observation
56
			$this->chargerImages($observation);
57
			// modifie $observation
58
			$this->chargerCommentaires($observation);
59
		}
1379 raphael 60
		else {
61
			header('HTTP/1.0 404 Not Found');
62
			// don't die (phpunit)
63
			throw(new Exception());
64
		}
1361 raphael 65
 
761 gduche 66
		// Mettre en forme le résultat et l'envoyer pour affichage
67
		$resultat = new ResultatService();
68
		$resultat->corps = $observation;
69
		return $resultat;
70
	}
71
 
72
	/*-------------------------------------------------------------------------------
73
	 							CONFIGURATION DU SERVICE
74
	 --------------------------------------------------------------------------------*/
75
	/**
76
	 * Configuration du service en fonction du fichier de config config_del.ini
77
	 * */
78
	private function configurer($ressources) {
79
		$this->mappingObservation = $this->conteneur->getParametre('mapping_observation');
787 delphine 80
		$this->mappingVotes = $this->conteneur->getParametre('mapping_votes');
950 aurelien 81
		$this->mappingCommentaire = $this->conteneur->getParametre('mapping_commentaire');
761 gduche 82
		if (empty($ressources) || sizeof($ressources) > 1 ) {
83
			$e = 'Le service observation accepete 1 et 1 seule ressource';
84
			throw new Exception($e, RestServeur::HTTP_CODE_ERREUR);
85
		} else {
86
			$this->id_observation = $ressources[0];
87
		}
88
	}
89
 
90
	/**
91
	 * Vérifier que le service est bien configuré
92
	 * */
93
	private function verifierConfiguration() {
94
 
95
		$erreurs = array();
96
		$tableauImages = $this->conteneur->getParametre('observations');
97
		if (empty($tableauImages)) {
98
			$erreurs[] = '- le fichier de configuration ne contient pas le tableau [images] ou celui-ci est vide ;';
99
		} else {
100
			if ($this->conteneur->getParametre('url_service') == null) {
101
				$erreurs[] = '- paramètre "url_service" manquant ;';
102
			}
103
 
104
			if ($this->conteneur->getParametre('url_images') == null) {
105
				$erreurs[] = '- paramètre "url_images" manquant ;';
106
			}
107
 
108
		}
109
 
110
		if (empty($this->mappingObservation)) {
111
			$erreurs[] = '- le fichier de configuration ne contient pas le tableau [mapping_observation] ou celui-ci est vide ;';
112
		} else {
113
			$champsMappingObs = array('id_observation', 'date_observation', 'date_transmission', 'famille', 'nom_sel', 'nom_sel_nn', 'nt',
114
								'ce_zone_geo', 'zone_geo', 'lieudit', 'station', 'courriel', 'ce_utilisateur', 'nom', 'prenom');
115
 
116
			foreach ($champsMappingObs as $champ) {
117
				if (!isset($this->mappingObservation[$champ])) {
118
					$erreurs[] = '- le mapping du champ "'.$champ.'" pour l\'observation est manquant ;';
119
				}
120
			}
121
		}
122
 
950 aurelien 123
		if (empty($this->mappingCommentaire)) {
124
			$erreurs[] = '- le fichier de configuration ne contient pas le tableau [mapping_commentaire] ou celui-ci est vide ;';
125
		} else {
126
			$champsMappingCom = array('id_commentaire', 'texte', 'ce_utilisateur', 'utilisateur_nom', 'utilisateur_prenom', 'utilisateur_courriel', 'date');
127
			foreach ($champsMappingCom as $champ) {
128
				if (!isset($this->mappingCommentaire[$champ])) {
129
					$erreurs[] = '- le mapping du champ "'.$champ.'" pour le commentaire est manquant ;';
130
				}
131
			}
132
		}
133
 
761 gduche 134
		if (!empty($erreurs)) {
135
			$e = 'Erreur lors de la configuration : '."\n";
136
			$e .= implode("\n", $erreurs);
137
			throw new Exception($e, RestServeur::HTTP_CODE_ERREUR);
138
		}
139
	}
140
 
141
	/*-------------------------------------------------------------------------------
142
								CHARGEMENT DES OBSERVATIONS
143
	--------------------------------------------------------------------------------*/
144
	/**
145
	* Chargement depuis la bdd de toutes les liaisons entre images et observations
146
	* */
147
	private function chargerLiaisons() {
148
 
1025 aurelien 149
		$requeteLiaisons = 'SELECT *, dob.commentaire as dob_commentaire '.
761 gduche 150
						   'FROM '.$this->gestionBdd->formaterTable('del_observation', 'dob').
151
						   'INNER JOIN '.$this->gestionBdd->formaterTable('del_obs_image', 'doi').
152
						   'ON doi.id_observation = dob.id_observation '.
1180 aurelien 153
						   'LEFT JOIN del_utilisateur du '.
820 gduche 154
						   'ON du.id_utilisateur = dob.ce_utilisateur '.
761 gduche 155
						   'WHERE doi.id_observation = '.$this->id_observation;
156
		$requeteLiaisons .=  ' GROUP BY doi.id_observation';
157
		$requeteLiaisons .= ' ORDER BY date_transmission DESC ';
158
		$requeteLiaisons .= $this->gestionBdd->getLimitSql();
159
 
160
		return $this->bdd->recuperer($requeteLiaisons);
161
	}
162
 
163
	/**
164
	* Retourner un tableau d'images formaté en fonction des liaisons trouvées
165
	* @param $liaisons les liaisons de la table del_obs_images
166
	* */
167
	private function chargerObservation($liaison) {
1361 raphael 168
 
1280 aurelien 169
		if($liaison['ce_utilisateur'] == 0) {
170
			$liaison['nom'] = $liaison['nom_utilisateur'];
171
			$liaison['prenom'] =$liaison['prenom_utilisateur'];
172
		}
173
 
761 gduche 174
		$observation = $this->formaterObservation($liaison);
175
		return $observation;
176
	}
177
 
178
	/**
179
	 * Sélectionner toutes les images de chaque observation
180
	 * @param array $observations la liste des observations
181
	 * */
1358 raphael 182
	private function chargerImages(&$observation) {
183
		$images = $this->bdd->recupererTous(sprintf(
184
			'SELECT * FROM %s INNER JOIN %s ON doi.id_image = di.id_image WHERE doi.id_observation = %d',
185
			$this->gestionBdd->formaterTable('del_obs_image', 'doi'),
186
			$this->gestionBdd->formaterTable('del_image', 'di'),
187
			$observation['id_observation']));
188
		if(!$images) return;
761 gduche 189
		$images = $this->formaterImages($images);
1358 raphael 190
		// modifie $images
191
		$this->chargerVotesImage($images);
761 gduche 192
		$observation['images'] = $images;
193
	}
194
 
195
	/**
841 aurelien 196
	* Charger les votes pour chaque image
197
	* */
1358 raphael 198
	private function chargerVotesImage(&$images) {
199
		$resultatsVotes = $this->bdd->recupererTous(sprintf(
200
			'SELECT v.*, p.* FROM %s INNER JOIN del_image_protocole p ON v.ce_protocole = p.id_protocole %s -- %s',
201
			$this->gestionBdd->formaterTable('del_image_vote', 'v'),
202
			$this->chargerClauseWhereVotesImage(),
203
			__FILE__ . ':' . __LINE__));
204
		if(!$resultatsVotes) return;
841 aurelien 205
 
206
		$votes = $this->formaterVotesImages($resultatsVotes);
207
		foreach ($images as $id => $image) {
208
			if (isset($votes[$image['id_image']])) {
209
				foreach($votes[$image['id_image']] as $id_vote => $vote_image) {
210
					$images[$id]['protocoles_votes'][$id_vote] = $vote_image;
211
				}
212
			}
213
		}
214
	}
215
 
216
	private function chargerClauseWhereVotesImage() {
217
		if (sizeof($this->imageIds) > 0) {
218
			$chaineImageIds = implode(',', $this->imageIds);
219
			$where[] = 'v.ce_image  IN ('.$chaineImageIds.')';
220
		}
221
		if (isset($this->parametres['protocole'])) {
222
			$where[] = 'v.ce_protocole = '.$this->proteger($this->parametres['protocole']);
223
		}
224
 
225
		$where = (!empty($where)) ? 'WHERE '.implode(' AND ', $where) : '';
226
		return $where;
227
	}
228
 
229
	/**
761 gduche 230
	* Récupérer tous les commentaires au total
231
	* @param array $observations la liste des observations à mettre à jour
232
	* */
1358 raphael 233
	private function chargerCommentaires(&$observation) {
761 gduche 234
		$requeteCommentaires = 'SELECT * FROM '.$this->gestionBdd->formaterTable('del_commentaire', 'dc').
235
							   'WHERE ce_observation = '.$observation['id_observation'];
236
		$commentaires = $this->bdd->recupererTous($requeteCommentaires);
1358 raphael 237
		if(!$commentaires) return;
238
 
841 aurelien 239
		$commentaires_formates = array();
240
		foreach ($commentaires as $commentaire) {
950 aurelien 241
			$commentaire = $this->formaterCommentaire($commentaire);
1000 delphine 242
			if (isset($commentaire['nom_sel']) && $commentaire['nom_sel'] != null) {
787 delphine 243
				$commentaire['votes'] = $this->chargerVotes($commentaire['id_commentaire']);
244
			}
841 aurelien 245
			$commentaires_formates[$commentaire['id_commentaire']] = $commentaire;
787 delphine 246
		}
841 aurelien 247
		$observation['commentaires'] = $commentaires_formates;
761 gduche 248
	}
249
 
787 delphine 250
	private function chargerVotes($id_commentaire) {
251
		$requeteVotes = 'SELECT * FROM '.
252
			$this->gestionBdd->formaterTable('del_commentaire_vote').
253
			'WHERE ce_proposition = '.$this->proteger($id_commentaire);
254
		$resultatsVotes = $this->bdd->recupererTous($requeteVotes);
841 aurelien 255
		$votes = array();
256
		foreach ($resultatsVotes as $vote) {
950 aurelien 257
			$id_vote = $vote['id_vote'];
258
			$votes[$id_vote] = $this->formaterVote($vote);
841 aurelien 259
		}
787 delphine 260
		return $votes;
261
	}
761 gduche 262
 
263
 
264
	/*-------------------------------------------------------------------------------
265
								FORMATER ET METTRE EN FORME
266
	--------------------------------------------------------------------------------*/
267
 
268
	/**
269
	 * Formater les images d'une observation
270
	 * @param array $images les images de l'observation
1358 raphael 271
	 * // TODO: en faire le maximum dans le SELECT
761 gduche 272
	 * */
273
	private function formaterImages($images) {
274
		$imagesRetour = array();
275
		foreach ($images as $image) {
841 aurelien 276
 
277
			$this->imageIds[] = $image['id_image'];
761 gduche 278
			$imageCourante = array();
279
			$imageCourante['id_image'] = $image['id_image'];
280
			$imageCourante['date'] = $image['date_prise_de_vue'];
281
			$imageCourante['binaire.href'] = $this->formaterLienImage($image['id_image']);
282
			$imageCourante['hauteur'] = $image['hauteur'];
283
			$imageRetour['largeur'] = $image['largeur'];
284
 
285
			$imagesRetour[] = $imageCourante;
286
		}
287
 
288
		return $imagesRetour;
289
	}
290
 
291
	/**
292
	*  Formater une observation depuis une ligne liaison
293
	*  @param $liaison liaison issue de la recherche
294
	*  @return $observation l'observation mise en forme
295
	* */
296
	private function formaterObservation($liaison) {
297
		$observation = array();
298
 
299
		foreach ($this->mappingObservation as $nomOriginal => $nomFinal) {
300
			$observation[$nomFinal] = $liaison[$nomOriginal];
301
		}
302
 
303
		$observation['images'] = array();
304
 
305
		return $observation;
306
	}
307
 
308
	/**
309
	 * Formater le lien de l'image en fonction du fichier de config et de l'identifiant de l'image
310
	 * */
311
	private function formaterLienImage($idImage) {
312
		$idImage = sprintf('%09s', $idImage);
313
		$url = $this->conteneur->getParametre('url_images');
314
		$urlImage = str_replace('%s', $idImage, $url);
315
		return $urlImage;
316
	}
317
 
318
	private function proteger($valeur) {
319
		if (is_array($valeur)) {
320
			return $this->bdd->protegerTableau($valeur);
321
		} else {
322
			return $this->bdd->proteger($valeur);
323
		}
324
	}
787 delphine 325
 
326
	/**
950 aurelien 327
	*
328
	* Formate un commentaire en fonction du fichier de configuration
329
	*/
330
	private function formaterCommentaire($commentaire) {
331
		$commentaire_formate = array();
332
		foreach ($this->mappingCommentaire as $nomOriginal => $nomFinal) {
1000 delphine 333
			if (isset($commentaire[$nomOriginal])) {
950 aurelien 334
			$commentaire_formate[$nomFinal] = $commentaire[$nomOriginal];
1000 delphine 335
			}
950 aurelien 336
		}
337
		return $commentaire_formate;
338
	}
339
 
340
	/**
787 delphine 341
	*  Formater un vote en fonction du fichier de configuration config_votes.ini
342
	*  @param $votes array()
343
	* */
950 aurelien 344
	private function formaterVote($vote) {
787 delphine 345
		$retour = array();
841 aurelien 346
		foreach ($vote as $param => $valeur) {
347
			$retour[$this->mappingVotes[$param]] = $valeur;
348
		}
349
		return $retour;
350
	}
351
 
352
	/**
353
	*  Formater une observation depuis une ligne liaison
354
	*  @param $liaison liaison issue de la recherche
355
	*  @return $observation l'observation mise en forme
356
	* */
357
	private function formaterVotesImages($votes) {
358
		$retour = array();
787 delphine 359
		foreach ($votes as $vote) {
841 aurelien 360
			$retour_vote = array();
361
			foreach ($vote as $param=>$valeur) {
362
				if (strpos($this->mappingVotes[$param], 'protocole.') === 0) {
363
					$retour_protocole[$this->mappingVotes[$param]] = $valeur;
364
				} else {
365
					$retour_vote[$this->mappingVotes[$param]] = $valeur;
366
				}
787 delphine 367
			}
841 aurelien 368
			if (!isset($retour[$vote['ce_image']][$vote['ce_protocole']])) {
369
				$retour[$vote['ce_image']][$vote['ce_protocole']] = $retour_protocole;
370
			}
371
			$retour[$vote['ce_image']][$vote['ce_protocole']]['votes'][$vote['id_vote']] = $retour_vote;
787 delphine 372
		}
841 aurelien 373
 
787 delphine 374
		return $retour;
375
	}
761 gduche 376
}
377
?>