Subversion Repositories eFlore/Applications.cel

Rev

Rev 2296 | Rev 2449 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 2296 Rev 2446
1
<?php
1
<?php
2
// declare(encoding='UTF-8');
2
// declare(encoding='UTF-8');
3
/**
3
/**
4
 * Service fournissant une carte dynamique des obsertions publiques du CEL.
4
 * Service fournissant une carte dynamique des obsertions publiques du CEL.
5
 * Encodage en entrée : utf8
5
 * Encodage en entrée : utf8
6
 * Encodage en sortie : utf8
6
 * Encodage en sortie : utf8
7
 *
7
 *
8
 * Cas d'utilisation :
8
 * Cas d'utilisation :
9
 * /CelWidgetMap/Carte/Utilisateur : carte des observations publiques d'un utilisateur.
9
 * /CelWidgetMap/Carte/Utilisateur : carte des observations publiques d'un utilisateur.
10
 * /CelWidgetMap/Carte/Utilisateur/Projet : carte des observations publiques d'un utilisateur pour un projet.
10
 * /CelWidgetMap/Carte/Utilisateur/Projet : carte des observations publiques d'un utilisateur pour un projet.
11
 * /CelWidgetMap/Carte/Utilisateur/Projet/dept : carte des observations publiques d'un utilisateur pour un projet sur un département.
11
 * /CelWidgetMap/Carte/Utilisateur/Projet/dept : carte des observations publiques d'un utilisateur pour un projet sur un département.
12
 * /CelWidgetMap/Carte/Utilisateur/Projet/dept/nt : carte des observations publiques d'un utilisateur pour un projet sur un département pour un taxon.
12
 * /CelWidgetMap/Carte/Utilisateur/Projet/dept/nt : carte des observations publiques d'un utilisateur pour un projet sur un département pour un taxon.
13
 *
13
 *
14
 * Carte = Type de carte. Valeurs possible : defaut,
14
 * Carte = Type de carte. Valeurs possible : defaut,
15
 * Utilisateur = identifiant (= courriel) de l'utilisateur ou * pour tous les utilisateurs.
15
 * Utilisateur = identifiant (= courriel) de l'utilisateur ou * pour tous les utilisateurs.
16
 * Projet = mot-clé du projet
16
 * Projet = mot-clé du projet
17
 * 		Plusieurs mots-clés peuvent être spécifiés:
17
 * 		Plusieurs mots-clés peuvent être spécifiés:
18
 * 			machin ET bidule ET chose => observations ayant tous les mots-clés (intersection) 
18
 * 			machin ET bidule ET chose => observations ayant tous les mots-clés (intersection)
19
 * 			machin OU bildule OU chose => observations ayant au moins un des mots-clés (union)
19
 * 			machin OU bildule OU chose => observations ayant au moins un des mots-clés (union)
20
 * 		ATTENTION
20
 * 		ATTENTION
21
 * 			machin ET bidule OU chose donne un résultat indéterminé pour l'instant
21
 * 			machin ET bidule OU chose donne un résultat indéterminé pour l'instant
22
 *
22
 *
23
 * @author Jean-Pascal MILCENT <jpm@clapas.org>
23
 * @author Jean-Pascal MILCENT <jpm@clapas.org>
24
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
24
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
25
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
25
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
26
 * @version $Id$
26
 * @version $Id$
27
 * @copyright © 2010, Jean-Pascal MILCENT
27
 * @copyright © 2010, Jean-Pascal MILCENT
28
 */
28
 */
29
// TODO : supprimer le TRIM quand les obs seront reliées correctements aux localisations (sur le code INSEE par exemple)
29
// TODO : supprimer le TRIM quand les obs seront reliées correctements aux localisations (sur le code INSEE par exemple)
30
class CelWidgetMapPoint extends Cel {
30
class CelWidgetMapPoint extends Cel {
31
	const MARQUEUR_GROUPE = 'GROUPE';
31
	const MARQUEUR_GROUPE = 'GROUPE';
32
	const MARQUEUR_COMMUNE = 'COMMUNE';
32
	const MARQUEUR_COMMUNE = 'COMMUNE';
33
	const MARQUEUR_STATION = 'STATION';
33
	const MARQUEUR_STATION = 'STATION';
34
	/**
34
	/**
35
	 * Méthode appelée avec une requête de type GET.
35
	 * Méthode appelée avec une requête de type GET.
36
	 */
36
	 */
37
	public function getElement($ressources) {
37
	public function getElement($ressources) {
38
		$retour = null;
38
		$retour = null;
39
		if($this->parametres == null) {
39
		if($this->parametres == null) {
40
			$this->parametres = array();
40
			$this->parametres = array();
41
		}
41
		}
42
		extract($this->parametres);
42
		extract($this->parametres);
43
		//Chronometre::chrono("Avant groupage");
43
		//Chronometre::chrono("Avant groupage");
44
 
44
 
45
		$action = array_shift($ressources);
45
		$action = array_shift($ressources);
46
		if (isset($action)) {
46
		if (isset($action)) {
47
			$methode = $this->traiterNomMethodeGet($action);
47
			$methode = $this->traiterNomMethodeGet($action);
48
			if (method_exists($this, $methode)) {
48
			if (method_exists($this, $methode)) {
49
				$retour = $this->$methode($ressources);
49
				$retour = $this->$methode($ressources);
50
			} else {
50
			} else {
51
				$this->messages[] = "Ce type de ressource '$methode' n'est pas disponible.";
51
				$this->messages[] = "Ce type de ressource '$methode' n'est pas disponible.";
52
			}
52
			}
53
		} else {
53
		} else {
54
			$this->messages[] = "Vous devez indiquer le type de ressource.";
54
			$this->messages[] = "Vous devez indiquer le type de ressource.";
55
		}
55
		}
56
 
56
 
57
		//Chronometre::chrono("Apres traitement");
57
		//Chronometre::chrono("Apres traitement");
58
		//echo Chronometre::afficherChrono();
58
		//echo Chronometre::afficherChrono();
59
		if (is_null($retour)) {
59
		if (is_null($retour)) {
60
			$info = 'Un problème est survenu : '.print_r($this->messages, true);
60
			$info = 'Un problème est survenu : '.print_r($this->messages, true);
61
			$this->envoyer($info);
61
			$this->envoyer($info);
62
		} else if (isset($retour['type']) && $retour['type'] == 'jsonVar') {
62
		} else if (isset($retour['type']) && $retour['type'] == 'jsonVar') {
63
			$this->envoyerJsonVar($retour['variable_js'], $retour['donnees']);
63
			$this->envoyerJsonVar($retour['variable_js'], $retour['donnees']);
64
		} else if (isset($retour['type']) && $retour['type'] == 'jsonP') {
64
		} else if (isset($retour['type']) && $retour['type'] == 'jsonP') {
65
			$this->envoyerJsonp($retour['donnees']);
65
			$this->envoyerJsonp($retour['donnees']);
66
		} else if (isset($retour['type']) && $retour['type'] == 'png') {
66
		} else if (isset($retour['type']) && $retour['type'] == 'png') {
67
			header("Content-type: image/png");
67
			header("Content-type: image/png");
68
			imagepng($retour['img']);
68
			imagepng($retour['img']);
69
			imagedestroy($retour['img']);
69
			imagedestroy($retour['img']);
70
		} else {
70
		} else {
71
			$this->envoyerJson($retour);
71
			$this->envoyerJson($retour);
72
		}
72
		}
73
	}
73
	}
74
 
74
 
75
	/**
75
	/**
76
	 * Les icones des groupes de stations
76
	 * Les icones des groupes de stations
77
	 */
77
	 */
78
	public function getIconeGroupe($params) {
78
	public function getIconeGroupe($params) {
79
		extract($this->parametres);
79
		extract($this->parametres);
80
 
80
 
81
		$chemin_marqueur = sprintf($this->config['settings']['cheminCelMarkerObsTpl'], $type);
81
		$chemin_marqueur = sprintf($this->config['settings']['cheminCelMarkerObsTpl'], $type);
82
		$img = imagecreatefrompng($chemin_marqueur);
82
		$img = imagecreatefrompng($chemin_marqueur);
83
 
83
 
84
		$noir = imagecolorallocate($img, 0, 0, 0);
84
		$noir = imagecolorallocate($img, 0, 0, 0);
85
		$texte = (String) $nbre;
85
		$texte = (String) $nbre;
86
		$x = (imagesx($img) - 6.0 * strlen($texte)) / 2;
86
		$x = (imagesx($img) - 6.0 * strlen($texte)) / 2;
87
		$y = (imagesy($img) - 16) / 2;
87
		$y = (imagesy($img) - 16) / 2;
88
 
88
 
89
		imagestring($img, 3, $x, $y, $texte, $noir);
89
		imagestring($img, 3, $x, $y, $texte, $noir);
90
 
90
 
91
		imagealphablending($img, false);
91
		imagealphablending($img, false);
92
		imagesavealpha($img, true);
92
		imagesavealpha($img, true);
93
 
93
 
94
		return array('type' => 'png', 'img' => $img);
94
		return array('type' => 'png', 'img' => $img);
95
	}
95
	}
96
 
96
 
97
	public function getTout($params) {
97
	public function getTout($params) {
98
 
98
 
99
		$emplacements = null;
99
		$emplacements = null;
100
		$concatenation_id = "CONCAT(IFNULL(latitude,''),IFNULL(longitude,''), IFNULL(wgs84_latitude,''),IFNULL(wgs84_longitude,'')) ";
100
		$concatenation_id = "CONCAT(IFNULL(latitude,''),IFNULL(longitude,''), IFNULL(wgs84_latitude,''),IFNULL(wgs84_longitude,'')) ";
101
 
101
 
102
		$requete =  'SELECT ce_zone_geo, zone_geo, station, '.
102
		$requete =  'SELECT ce_zone_geo, zone_geo, station, '.
103
								"mots_cles_texte, ".
103
								"mots_cles_texte, ".
104
								"latitude, ".
104
								"latitude, ".
105
								"wgs84_latitude, ".
105
								"wgs84_latitude, ".
106
								"longitude, ".
106
								"longitude, ".
107
								"wgs84_longitude, ".
107
								"wgs84_longitude, ".
108
								$concatenation_id." as id_coord ".
108
								$concatenation_id." as id_coord ".
109
					'FROM cel_obs AS co '.
109
					'FROM cel_obs AS co '.
110
                    '   LEFT JOIN cel_zones_geo AS l '.
110
                    '   LEFT JOIN cel_zones_geo AS l '.
111
                    '       ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) '.
111
                    '       ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) '.
112
                    "WHERE transmission = '1' ".
112
                    "WHERE transmission = '1' ".
113
					" AND (".
113
					" AND (".
114
					$this->construireWhereRectangleStationOR()." OR ".
114
					$this->construireWhereRectangleStationOR()." OR ".
115
					$this->construireWhereRectangleCommuneOR().") ".
115
					$this->construireWhereRectangleCommuneOR().") ".
116
					$this->construireWhereDept().
116
					$this->construireWhereDept().
117
                    $this->construireWhereCommune().
117
                    $this->construireWhereCommune().
118
                    $this->construireWhereUtilisateur().
118
                    $this->construireWhereUtilisateur().
119
					$this->construireWhereNumTaxonAvecSousTaxons().
119
					$this->construireWhereNumTaxonAvecSousTaxons().
120
					$this->construireWhereNomTaxon().
120
					$this->construireWhereNomTaxon().
121
					$this->construireWhereReferentiel().
121
					$this->construireWhereReferentiel().
122
					$this->construireWhereDate().
122
					$this->construireWhereDate().
123
					$this->construireWhereCommentaire().
123
					$this->construireWhereCommentaire().
124
					$this->construireWherePhotosSeulement().
124
					$this->construireWherePhotosSeulement().
125
					$this->construireWhereProjet().
125
					$this->construireWhereProjet().
126
					$this->construireWhereTag().
126
					$this->construireWhereTag().
127
					$this->construireWhereNombreDeJours().
127
					$this->construireWhereNombreDeJours().
128
					$this->construireWhereAnnee().
128
					$this->construireWhereAnnee().
129
					' GROUP BY id_coord';
129
					' GROUP BY id_coord';
130
 
130
 
131
		$resultats_emplacements = Cel::db()->requeter($requete);
131
		$resultats_emplacements = Cel::db()->requeter($requete);
132
		$emplacements = $this->traiterEmplacements($resultats_emplacements, $this->compterObservations($params));
132
		$emplacements = $this->traiterEmplacements($resultats_emplacements, $this->compterObservations($params));
133
		return $emplacements;
133
		return $emplacements;
134
	}
134
	}
135
 
135
 
136
	private function afficherRequeteFormatee($requete) {
136
	private function afficherRequeteFormatee($requete) {
137
		$requete = str_replace(')',')<br />',$requete);
137
		$requete = str_replace(')',')<br />',$requete);
138
		$requete = str_replace('(','	<br />	(',$requete);
138
		$requete = str_replace('(','	<br />	(',$requete);
139
		echo '<pre>'.$requete.'</pre>';
139
		echo '<pre>'.$requete.'</pre>';
140
		exit;
140
		exit;
141
	}
141
	}
142
 
142
 
143
	private $nb_obs = 0;
143
	private $nb_obs = 0;
144
 
144
 
145
	private function compterObservations($params) {
145
	private function compterObservations($params) {
146
		$requete =  'SELECT COUNT(*) as nb '.
146
		$requete =  'SELECT COUNT(*) as nb '.
147
					'FROM cel_obs AS co '.
147
					'FROM cel_obs AS co '.
148
                    '   LEFT JOIN cel_zones_geo AS l '.
148
                    '   LEFT JOIN cel_zones_geo AS l '.
149
                    '       ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) '.
149
                    '       ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) '.
150
                    "WHERE transmission = '1' ".
150
                    "WHERE transmission = '1' ".
151
					" AND (".
151
					" AND (".
152
					$this->construireWhereRectangleStationOR()." OR ".
152
					$this->construireWhereRectangleStationOR()." OR ".
153
					$this->construireWhereRectangleCommuneOR().") ".
153
					$this->construireWhereRectangleCommuneOR().") ".
154
					$this->construireWhereDept().
154
					$this->construireWhereDept().
155
                    $this->construireWhereCommune().
155
                    $this->construireWhereCommune().
156
                    $this->construireWhereUtilisateur().
156
                    $this->construireWhereUtilisateur().
157
					$this->construireWhereNumTaxonAvecSousTaxons().
157
					$this->construireWhereNumTaxonAvecSousTaxons().
158
					$this->construireWhereNomTaxon().
158
					$this->construireWhereNomTaxon().
159
					$this->construireWhereReferentiel().
159
					$this->construireWhereReferentiel().
160
					$this->construireWhereDate().
160
					$this->construireWhereDate().
161
					$this->construireWhereCommentaire().
161
					$this->construireWhereCommentaire().
162
					$this->construireWherePhotosSeulement().
162
					$this->construireWherePhotosSeulement().
163
					$this->construireWhereProjet().
163
					$this->construireWhereProjet().
164
					$this->construireWhereTag().
164
					$this->construireWhereTag().
165
					$this->construireWhereNombreDeJours().
165
					$this->construireWhereNombreDeJours().
166
					$this->construireWhereAnnee();
166
					$this->construireWhereAnnee();
167
 
167
 
168
		$resultats_nb_obs = Cel::db()->requeter($requete);
168
		$resultats_nb_obs = Cel::db()->requeter($requete);
169
		return $resultats_nb_obs[0]['nb'];
169
		return $resultats_nb_obs[0]['nb'];
170
	}
170
	}
171
 
171
 
172
	private function traiterEmplacements(&$emplacements, $nb_total_observation) {
172
	private function traiterEmplacements(&$emplacements, $nb_total_observation) {
173
		$zoom = (int) array_key_exists('zoom', $this->parametres) ? $this->parametres['zoom'] : 11;
173
		$zoom = (int) array_key_exists('zoom', $this->parametres) ? $this->parametres['zoom'] : 11;
174
		$distance = (int) array_key_exists('distance', $this->parametres) ? $this->parametres['distance'] : 20;
174
		$distance = (int) array_key_exists('distance', $this->parametres) ? $this->parametres['distance'] : 20;
175
 
175
 
176
		$marqueurs = array(
176
		$marqueurs = array(
177
			'stats' => array('stations' => 0, 'communes' => 0, 'observations' => 0),
177
			'stats' => array('stations' => 0, 'communes' => 0, 'observations' => 0),
178
			'points' => null
178
			'points' => null
179
		);
179
		);
180
 
180
 
181
		if (isset($this->parametres['ne']) && $this->parametres['sw'] && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
181
		if (isset($this->parametres['ne']) && $this->parametres['sw'] && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
182
			$ne = $this->decomposerLatLng($this->parametres['ne']);
182
			$ne = $this->decomposerLatLng($this->parametres['ne']);
183
			$sw = $this->decomposerLatLng($this->parametres['sw']);
183
			$sw = $this->decomposerLatLng($this->parametres['sw']);
184
			$marqueurs['points'] = CartoGroupage::creerGroupesQuadtree($emplacements, $ne['lat'], $ne['lng'], $sw['lat'], $sw['lng'], $zoom);
184
			$marqueurs['points'] = CartoGroupage::creerGroupesQuadtree($emplacements, $ne['lat'], $ne['lng'], $sw['lat'], $sw['lng'], $zoom);
185
 
185
 
186
			// laisser la classe cartoGroupage compter les élements simplifie le comptage
186
			// laisser la classe cartoGroupage compter les élements simplifie le comptage
187
			// et permet de ne pas reparser le tableau pour compter les différents éléments
187
			// et permet de ne pas reparser le tableau pour compter les différents éléments
188
			$nb_elements = CartoGroupage::getNbElements();
188
			$nb_elements = CartoGroupage::getNbElements();
189
			// les bornes servent à centrer la carte dans le cas ou l'on demande des paramètres précis
189
			// les bornes servent à centrer la carte dans le cas ou l'on demande des paramètres précis
190
			$marqueurs['stats']['coordmax'] = CartoGroupage::getBornes();
190
			$marqueurs['stats']['coordmax'] = CartoGroupage::getBornes();
191
			$marqueurs['stats']['stations'] = $nb_elements['stations'];
191
			$marqueurs['stats']['stations'] = $nb_elements['stations'];
192
			$marqueurs['stats']['communes'] = $nb_elements['communes'];
192
			$marqueurs['stats']['communes'] = $nb_elements['communes'];
193
			$marqueurs['stats']['observations'] = (int)$nb_total_observation;
193
			$marqueurs['stats']['observations'] = (int)$nb_total_observation;
194
		} else {
194
		} else {
195
			$marqueurs['points'] = $emplacements;
195
			$marqueurs['points'] = $emplacements;
196
		}
196
		}
197
 
197
 
198
		return $marqueurs;
198
		return $marqueurs;
199
	}
199
	}
200
 
200
 
201
	private function traiterStations($communes, $stations) {
201
	private function traiterStations($communes, $stations) {
202
		$zoom = (int) array_key_exists('zoom', $this->parametres) ? $this->parametres['zoom'] : 11;
202
		$zoom = (int) array_key_exists('zoom', $this->parametres) ? $this->parametres['zoom'] : 11;
203
		$distance = (int) array_key_exists('distance', $this->parametres) ? $this->parametres['distance'] : 20;
203
		$distance = (int) array_key_exists('distance', $this->parametres) ? $this->parametres['distance'] : 20;
204
 
204
 
205
		$marqueurs = array(
205
		$marqueurs = array(
206
			'stats' => array('stations' => 0, 'communes' => 0, 'observations' => 0),
206
			'stats' => array('stations' => 0, 'communes' => 0, 'observations' => 0),
207
			'points' => null
207
			'points' => null
208
		);
208
		);
209
		$marqueurs['stats']['observations'] = $this->traiterNbreObs($communes) + $this->traiterNbreObs($stations);
209
		$marqueurs['stats']['observations'] = $this->traiterNbreObs($communes) + $this->traiterNbreObs($stations);
210
 
210
 
211
		$points = array();
211
		$points = array();
212
		if ($communes !== false) {
212
		if ($communes !== false) {
213
			foreach ($communes as $commune) {
213
			foreach ($communes as $commune) {
214
				if (is_numeric($commune['lat']) && is_numeric($commune['lng'])) {
214
				if (is_numeric($commune['lat']) && is_numeric($commune['lng'])) {
215
					extract($commune);
215
					extract($commune);
216
					$id = self::MARQUEUR_COMMUNE.':'.$lat.'|'.$lng;
216
					$id = self::MARQUEUR_COMMUNE.':'.$lat.'|'.$lng;
217
					$lata = round($lat, 5);
217
					$lata = round($lat, 5);
218
					$lnga = round($lng, 5);
218
					$lnga = round($lng, 5);
219
 
219
 
220
					if (!isset($points[$id])) {
220
					if (!isset($points[$id])) {
221
						$points[$id]['id'] = $id;
221
						$points[$id]['id'] = $id;
222
						$points[$id]['nom'] = $nom;
222
						$points[$id]['nom'] = $nom;
223
						$points[$id]['lat'] = $lata;
223
						$points[$id]['lat'] = $lata;
224
						$points[$id]['lng'] = $lnga;
224
						$points[$id]['lng'] = $lnga;
225
						$points[$id]['nbre'] = 1;
225
						$points[$id]['nbre'] = 1;
226
						$marqueurs['stats']['communes']++;
226
						$marqueurs['stats']['communes']++;
227
					} else {
227
					} else {
228
						$points[$id]['nbre']++;
228
						$points[$id]['nbre']++;
229
					}
229
					}
230
				}
230
				}
231
			}
231
			}
232
		}
232
		}
233
		if ($stations !== false) {
233
		if ($stations !== false) {
234
			foreach ($stations as $station) {
234
			foreach ($stations as $station) {
235
				if (is_numeric($station['lat']) && is_numeric($station['lng'])) {
235
				if (is_numeric($station['lat']) && is_numeric($station['lng'])) {
236
					extract($station);
236
					extract($station);
237
					$id = self::MARQUEUR_STATION.':'.$lat.'|'.$lng;
237
					$id = self::MARQUEUR_STATION.':'.$lat.'|'.$lng;
238
					$lata = round($lat, 5);
238
					$lata = round($lat, 5);
239
					$lnga = round($lng, 5);
239
					$lnga = round($lng, 5);
240
					$nom = $this->etreNull($nom) ? $lata.','.$lnga : $nom;
240
					$nom = $this->etreNull($nom) ? $lata.','.$lnga : $nom;
241
 
241
 
242
					if (!isset($points[$id])) {
242
					if (!isset($points[$id])) {
243
						$points[$id]['id'] = $id;
243
						$points[$id]['id'] = $id;
244
						$points[$id]['nom'] = $nom;
244
						$points[$id]['nom'] = $nom;
245
						$points[$id]['lat'] = $lata;
245
						$points[$id]['lat'] = $lata;
246
						$points[$id]['lng'] = $lnga;
246
						$points[$id]['lng'] = $lnga;
247
						$points[$id]['nbre'] = 1;
247
						$points[$id]['nbre'] = 1;
248
						$marqueurs['stats']['stations']++;
248
						$marqueurs['stats']['stations']++;
249
					} else {
249
					} else {
250
						$points[$id]['nbre']++;
250
						$points[$id]['nbre']++;
251
					}
251
					}
252
				}
252
				}
253
			}
253
			}
254
		}
254
		}
255
 
255
 
256
		if (isset($this->parametres['ne']) && $this->parametres['sw'] && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
256
		if (isset($this->parametres['ne']) && $this->parametres['sw'] && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
257
			$ne = $this->decomposerLatLng($this->parametres['ne']);
257
			$ne = $this->decomposerLatLng($this->parametres['ne']);
258
			$sw = $this->decomposerLatLng($this->parametres['sw']);
258
			$sw = $this->decomposerLatLng($this->parametres['sw']);
259
			$marqueurs['points'] = CartoGroupage::creerGroupesQuadtree($points, $ne['lat'], $ne['lng'], $sw['lat'], $sw['lng'], $zoom);
259
			$marqueurs['points'] = CartoGroupage::creerGroupesQuadtree($points, $ne['lat'], $ne['lng'], $sw['lat'], $sw['lng'], $zoom);
260
		} else {
260
		} else {
261
			$marqueurs['points'] = $points;
261
			$marqueurs['points'] = $points;
262
		}
262
		}
263
		//$marqueurs['stats']['latDiff'] = abs($marqueurs['stats']['latMin'] - $marqueurs['stats']['latMax']);
263
		//$marqueurs['stats']['latDiff'] = abs($marqueurs['stats']['latMin'] - $marqueurs['stats']['latMax']);
264
		//$marqueurs['stats']['lngDiff'] = abs($marqueurs['stats']['lngMin'] - $marqueurs['stats']['lngMax']);
264
		//$marqueurs['stats']['lngDiff'] = abs($marqueurs['stats']['lngMin'] - $marqueurs['stats']['lngMax']);
265
 
265
 
266
		return $marqueurs;
266
		return $marqueurs;
267
	}
267
	}
268
 
268
 
269
	private function definirLatLngMaxMin(&$marqueurs, $lat, $lng) {
269
	private function definirLatLngMaxMin(&$marqueurs, $lat, $lng) {
270
		if ($lat != null && $lng != null) {
270
		if ($lat != null && $lng != null) {
271
			$marqueurs['stats']['latMin'] = $marqueurs['stats']['latMin'] > $lat ? $lat : $marqueurs['stats']['latMin'];
271
			$marqueurs['stats']['latMin'] = $marqueurs['stats']['latMin'] > $lat ? $lat : $marqueurs['stats']['latMin'];
272
			$marqueurs['stats']['lngMin'] = $marqueurs['stats']['lngMin'] > $lng ? $lng : $marqueurs['stats']['lngMin'];
272
			$marqueurs['stats']['lngMin'] = $marqueurs['stats']['lngMin'] > $lng ? $lng : $marqueurs['stats']['lngMin'];
273
			$marqueurs['stats']['latMax'] = $marqueurs['stats']['latMax'] < $lat ? $lat : $marqueurs['stats']['latMax'];
273
			$marqueurs['stats']['latMax'] = $marqueurs['stats']['latMax'] < $lat ? $lat : $marqueurs['stats']['latMax'];
274
			$marqueurs['stats']['lngMax'] = $marqueurs['stats']['lngMax'] < $lng ? $lng : $marqueurs['stats']['lngMax'];
274
			$marqueurs['stats']['lngMax'] = $marqueurs['stats']['lngMax'] < $lng ? $lng : $marqueurs['stats']['lngMax'];
275
		}
275
		}
276
	}
276
	}
277
 
277
 
278
	private function traiterNbreObs($resultats) {
278
	private function traiterNbreObs($resultats) {
279
		$obs_nbre = 0;
279
		$obs_nbre = 0;
280
		if ($resultats !== false) {
280
		if ($resultats !== false) {
281
			$obs_nbre = count($resultats);
281
			$obs_nbre = count($resultats);
282
		}
282
		}
283
		return $obs_nbre;
283
		return $obs_nbre;
284
	}
284
	}
285
 
285
 
286
	private function verifierLatLng($lat, $lng) {
286
	private function verifierLatLng($lat, $lng) {
287
		$ok_lat = $this->etreLatitude($lat) ? true : false;
287
		$ok_lat = $this->etreLatitude($lat) ? true : false;
288
		$ok_lng = $this->etreLongitude($lng) ? true : false;
288
		$ok_lng = $this->etreLongitude($lng) ? true : false;
289
		$ok = $ok_lat && $ok_lng;
289
		$ok = $ok_lat && $ok_lng;
290
		return $ok;
290
		return $ok;
291
	}
291
	}
292
 
292
 
293
	private function etreLatitude($lat) {
293
	private function etreLatitude($lat) {
294
		$ok = false;
294
		$ok = false;
295
		//$format =  preg_match('/^[-]?[0-9]+(?:[.][0-9]+|)$/', $lat) ? true : false;
295
		//$format =  preg_match('/^[-]?[0-9]+(?:[.][0-9]+|)$/', $lat) ? true : false;
296
		$ok = ($lat >= -90 && $lat <= 90) ? true : false;
296
		$ok = ($lat >= -90 && $lat <= 90) ? true : false;
297
		return $ok;
297
		return $ok;
298
	}
298
	}
299
 
299
 
300
	private function etreLongitude($lng) {
300
	private function etreLongitude($lng) {
301
		$ok = false;
301
		$ok = false;
302
		//$format =  preg_match('/^[-]?[0-9]+(?:[.][0-9]+|)$/', $lng) ? true : false;
302
		//$format =  preg_match('/^[-]?[0-9]+(?:[.][0-9]+|)$/', $lng) ? true : false;
303
		$ok = ($lng >= -180 && $lng <= 180) ? true : false;
303
		$ok = ($lng >= -180 && $lng <= 180) ? true : false;
304
		return $ok;
304
		return $ok;
305
	}
305
	}
306
 
306
 
307
	private function etreObsSensible($tags) {
307
	private function etreObsSensible($tags) {
308
		$sensible = true;
308
		$sensible = true;
309
		if (stristr($tags, 'sensible') === FALSE) {
309
		if (stristr($tags, 'sensible') === FALSE) {
310
			$sensible = false;
310
			$sensible = false;
311
		}
311
		}
312
		return $sensible;
312
		return $sensible;
313
	}
313
	}
314
 
314
 
315
	private function communeEstDemandee() {
315
	private function communeEstDemandee() {
316
	    $station_infos = $this->decomposerParametreStation();
316
	    $station_infos = $this->decomposerParametreStation();
317
	    $commune_demandee = true;
317
	    $commune_demandee = true;
318
	    if($station_infos['type'] == self::MARQUEUR_STATION) {
318
	    if($station_infos['type'] == self::MARQUEUR_STATION) {
319
			$commune_demandee = false;
319
			$commune_demandee = false;
320
	    }
320
	    }
321
	    return $commune_demandee;
321
	    return $commune_demandee;
322
	}
322
	}
323
 
323
 
324
	/**
324
	/**
325
	 * Données pour l'affichage des obs d'une station
325
	 * Données pour l'affichage des obs d'une station
326
	 */
326
	 */
327
	public function getObservations($params) {
327
	public function getObservations($params) {
328
		$resultats = array();
328
		$resultats = array();
329
		$total = 0;
329
		$total = 0;
330
		if (isset($this->parametres['station']) && !$this->etreNull($this->parametres['station'])) {
330
		if (isset($this->parametres['station']) && !$this->etreNull($this->parametres['station'])) {
331
			$requete = 	'SELECT SQL_CALC_FOUND_ROWS id_observation, ce_utilisateur, courriel_utilisateur, nom_utilisateur, prenom_utilisateur, '.
331
			$requete = 	'SELECT SQL_CALC_FOUND_ROWS id_observation, ce_utilisateur, courriel_utilisateur, nom_utilisateur, prenom_utilisateur, '.
332
						'	nom_sel, nom_ret, nom_sel_nn, nom_ret_nn, nt, famille, '.
332
						'	nom_sel, nom_ret, nom_sel_nn, nom_ret_nn, nt, famille, '.
333
						'	lieudit, zone_geo, date_observation, milieu, commentaire, '.
333
						'	lieudit, zone_geo, date_observation, milieu, commentaire, '.
334
						'	utm_secteur, utm_x, utm_y, code, date_transmission, nom_referentiel '.
334
						'	utm_secteur, utm_x, utm_y, code, date_transmission, nom_referentiel '.
335
						'FROM cel_obs AS co '.
335
						'FROM cel_obs AS co '.
336
						'	LEFT JOIN cel_zones_geo AS l '.
336
						'	LEFT JOIN cel_zones_geo AS l '.
337
						"		ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) ".
337
						"		ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) ".
338
						"WHERE transmission = '1' ".
338
						"WHERE transmission = '1' ".
339
						(($this->communeEstDemandee()) ? $this->construireWhereCommuneSansCoordonneesAvecSensibles() : $this->construireWhereCoordonneesSansSensibles()).
339
						(($this->communeEstDemandee()) ? $this->construireWhereCommuneSansCoordonneesAvecSensibles() : $this->construireWhereCoordonneesSansSensibles()).
340
						$this->construireWhereDept().
340
						$this->construireWhereDept().
341
						$this->construireWhereUtilisateur().
341
						$this->construireWhereUtilisateur().
342
						$this->construireWhereNumTaxonAvecSousTaxons().
342
						$this->construireWhereNumTaxonAvecSousTaxons().
343
						$this->construireWhereNomTaxon().
343
						$this->construireWhereNomTaxon().
344
						$this->construireWhereReferentiel().
344
						$this->construireWhereReferentiel().
345
						$this->construireWhereDate().
345
						$this->construireWhereDate().
346
						$this->construireWhereCommentaire().
346
						$this->construireWhereCommentaire().
347
						$this->construireWherePhotosSeulement().
347
						$this->construireWherePhotosSeulement().
348
						$this->construireWhereProjet().
348
						$this->construireWhereProjet().
349
						$this->construireWhereTag().
349
						$this->construireWhereTag().
350
						$this->construireWhereNombreDeJours().
350
						$this->construireWhereNombreDeJours().
351
					$this->construireWhereAnnee().
351
					$this->construireWhereAnnee().
352
	                    'ORDER BY nom_sel ASC '.
352
	                    'ORDER BY nom_sel ASC '.
353
	                    "LIMIT {$this->start},{$this->limit} ";
353
	                    "LIMIT {$this->start},{$this->limit} ";
354
			//echo $requete;exit;
354
			//echo $requete;exit;
355
			$resultats = Cel::db()->requeter($requete, self::SQL_RETOUR_COMPLET, self::SQL_MODE_OBJET);
355
			$resultats = Cel::db()->requeter($requete, self::SQL_RETOUR_COMPLET, self::SQL_MODE_OBJET);
356
			$requete = 'SELECT FOUND_ROWS()';
356
			$requete = 'SELECT FOUND_ROWS()';
357
			$total = (int) Cel::db()->requeter($requete, self::SQL_RETOUR_COLONNE);
357
			$total = (int) Cel::db()->requeter($requete, self::SQL_RETOUR_COLONNE);
358
		}
358
		}
359
 
359
 
360
		// Post-traitement
360
		// Post-traitement
361
		$observations = $this->traiterObservations($resultats, $total);
361
		$observations = $this->traiterObservations($resultats, $total);
362
		$observations = $this->ajouterImagesAuxObs($observations);
362
		$observations = $this->ajouterImagesAuxObs($observations);
363
		$observations = $this->ajouterAuteursAuxObs($observations);
363
		$observations = $this->ajouterAuteursAuxObs($observations);
364
		$observations = $this->supprimerIdDesObs($observations);
364
		$observations = $this->supprimerIdDesObs($observations);
365
 
365
 
366
		return $observations;
366
		return $observations;
367
	}
367
	}
368
 
368
 
369
	private function traiterObservations($donnees, $total) {
369
	private function traiterObservations($donnees, $total) {
370
		$observations = array('commune' => '', 'observations' => array(), 'observateurs' => array());
370
		$observations = array('commune' => '', 'observations' => array(), 'observateurs' => array());
371
		$observations['total'] = (isset($total)) ? $total : 0;
371
		$observations['total'] = (isset($total)) ? $total : 0;
372
		if (is_array($donnees) && count($donnees) > 0) {
372
		if (is_array($donnees) && count($donnees) > 0) {
373
			foreach ($donnees as $donnee) {
373
			foreach ($donnees as $donnee) {
374
				//echo '<pre>'.print_r($donnee,true).'</pre>';exit;
374
				//echo '<pre>'.print_r($donnee,true).'</pre>';exit;
375
				$observation = array();
375
				$observation = array();
376
				$observation['idObs'] = $donnee->id_observation;
376
				$observation['idObs'] = $donnee->id_observation;
377
				$observation['nn'] = $this->etreNull($donnee->nom_sel_nn) ? null : $donnee->nom_sel_nn;
377
				$observation['nn'] = $this->etreNull($donnee->nom_sel_nn) ? null : $donnee->nom_sel_nn;
378
				$observation['nomSci'] = $this->nettoyerTexte($donnee->nom_sel);
378
				$observation['nomSci'] = $this->nettoyerTexte($donnee->nom_sel);
379
				$observation['date'] = ($donnee->date_observation != '0000-00-00 00:00:00') ? $this->formaterDate($donnee->date_observation, '%d/%m/%Y') : '';
379
				$observation['date'] = ($donnee->date_observation != '0000-00-00 00:00:00') ? $this->formaterDate($donnee->date_observation, '%d/%m/%Y') : '';
380
				$observation['datePubli'] = $this->formaterDate($donnee->date_transmission);
380
				$observation['datePubli'] = $this->formaterDate($donnee->date_transmission);
381
				$observation['lieu'] = $this->traiterLieu($donnee);
381
				$observation['lieu'] = $this->traiterLieu($donnee);
382
				$observation['observateur'] = $donnee->courriel_utilisateur;
382
				$observation['observateur'] = $donnee->courriel_utilisateur;
383
				$observation['observateurId'] = $donnee->ce_utilisateur;
383
				$observation['observateurId'] = $donnee->ce_utilisateur;
384
				$observation['urlEflore'] = $this->getUrlEflore($donnee->nom_referentiel, $donnee->nom_sel_nn);
384
				$observation['urlEflore'] = $this->getUrlEflore($donnee->nom_referentiel, $donnee->nom_sel_nn);
385
 
385
 
386
				if (isset($donnee->zone_geo)) {
386
				if (isset($donnee->zone_geo)) {
387
					$observations['commune'] = $this->nettoyerTexte($donnee->zone_geo);
387
					$observations['commune'] = $this->nettoyerTexte($donnee->zone_geo);
388
				}
388
				}
389
				$observations['observations'][$donnee->id_observation] = $observation;
389
				$observations['observations'][$donnee->id_observation] = $observation;
390
 
390
 
391
				if (! array_key_exists($donnee->ce_utilisateur, $observations['observateurs'])) {
391
				if (! array_key_exists($donnee->ce_utilisateur, $observations['observateurs'])) {
392
					$observations['observateurs'][$donnee->courriel_utilisateur] = $donnee->courriel_utilisateur;
392
					$observations['observateurs'][$donnee->courriel_utilisateur] = $donnee->courriel_utilisateur;
393
				}
393
				}
394
			}
394
			}
395
		}
395
		}
396
		return $observations;
396
		return $observations;
397
	}
397
	}
398
 
398
 
399
	private function traiterLieu($donnee) {
399
	private function traiterLieu($donnee) {
400
		$lieu = array();
400
		$lieu = array();
401
		if (!$this->etreNull($donnee->lieudit)) {
401
		if (!$this->etreNull($donnee->lieudit)) {
402
			$lieu[] = $donnee->lieudit;
402
			$lieu[] = $donnee->lieudit;
403
		}
403
		}
404
		if (!$this->etreNull($donnee->milieu)) {
404
		if (!$this->etreNull($donnee->milieu)) {
405
			$lieu[] = $donnee->milieu;
405
			$lieu[] = $donnee->milieu;
406
		}
406
		}
407
		return implode(', ', $lieu);
407
		return implode(', ', $lieu);
408
	}
408
	}
409
 
409
 
410
	private function chargerImages(Array $obs_ids) {
410
	private function chargerImages(Array $obs_ids) {
411
		// Récupération des données au format Json
411
		// Récupération des données au format Json
412
		$service = 'CelImage/liste-ids?obsId='.implode(',', $obs_ids);
412
		$service = 'CelImage/liste-ids?obsId='.implode(',', $obs_ids);
413
		$url = sprintf($this->config['settings']['baseURLServicesCelTpl'], $service);
413
		$url = sprintf($this->config['settings']['baseURLServicesCelTpl'], $service);
414
		$json = $this->getRestClient()->consulter($url);
414
		$json = $this->getRestClient()->consulter($url);
415
		$donnees = json_decode($json);
415
		$donnees = json_decode($json);
416
 
416
 
417
		// Post-traitement des données
417
		// Post-traitement des données
418
		$images = $this->traiterImages($donnees);
418
		$images = $this->traiterImages($donnees);
419
 
419
 
420
		return $images;
420
		return $images;
421
	}
421
	}
422
 
422
 
423
	private function traiterImages($donnees) {
423
	private function traiterImages($donnees) {
424
		$images = array();
424
		$images = array();
425
		if (count($donnees) > 0) {
425
		if (count($donnees) > 0) {
426
			foreach ($donnees as $id_obs => $id_images) {
426
			foreach ($donnees as $id_obs => $id_images) {
427
				foreach ($id_images as $id_img) {
427
				foreach ($id_images as $id_img) {
428
					$urls['idImg'] = $id_img;
428
					$urls['idImg'] = $id_img;
429
					$urls['guid'] = sprintf($this->config['settings']['guidImgTpl'], $id_img);
429
					$urls['guid'] = sprintf($this->config['settings']['guidImgTpl'], $id_img);
430
					$urls['miniature'] = $this->getUrlImage($id_img, 'CXS');
430
					$urls['miniature'] = $this->getUrlImage($id_img, 'CXS');
431
					$urls['normale'] = $this->getUrlImage($id_img, 'XL');
431
					$urls['normale'] = $this->getUrlImage($id_img, 'XL');
432
					$images[$id_obs][] = $urls;
432
					$images[$id_obs][] = $urls;
433
				}
433
				}
434
			}
434
			}
435
		}
435
		}
436
		return $images;
436
		return $images;
437
	}
437
	}
438
 
438
 
439
	private function ajouterImagesAuxObs($observations) {
439
	private function ajouterImagesAuxObs($observations) {
440
		$images = $this->chargerImages(array_keys($observations['observations']));
440
		$images = $this->chargerImages(array_keys($observations['observations']));
441
		foreach ($observations['observations'] as $id => $infos) {
441
		foreach ($observations['observations'] as $id => $infos) {
442
			if(isset($images[$id])) {
442
			if(isset($images[$id])) {
443
				$infos['images'] = $images[$id];
443
				$infos['images'] = $images[$id];
444
				$observations['observations'][$id] = $infos;
444
				$observations['observations'][$id] = $infos;
445
			}
445
			}
446
		}
446
		}
447
		return $observations;
447
		return $observations;
448
	}
448
	}
449
 
449
 
450
	private function ajouterAuteursAuxObs($observations) {
450
	private function ajouterAuteursAuxObs($observations) {
451
		$observateurs = $this->recupererUtilisateursIdentite(array_keys($observations['observateurs']));
451
		$observateurs = $this->recupererUtilisateursIdentite(array_keys($observations['observateurs']));
452
		unset($observations['observateurs']);
452
		unset($observations['observateurs']);
453
		foreach ($observations['observations'] as $id => $infos) {
453
		foreach ($observations['observations'] as $id => $infos) {
454
			$courriel = strtolower($infos['observateur']);
454
			$courriel = strtolower($infos['observateur']);
455
			if(isset($observateurs[$courriel])) {
455
			if(isset($observateurs[$courriel])) {
456
				$infos['observateur'] = $observateurs[$courriel]['intitule'];
456
				$infos['observateur'] = $observateurs[$courriel]['intitule'];
457
				$infos['observateurId'] = $observateurs[$courriel]['id'];
457
				$infos['observateurId'] = $observateurs[$courriel]['id'];
458
			}
458
			}
459
			$observations['observations'][$id] = $infos;
459
			$observations['observations'][$id] = $infos;
460
		}
460
		}
461
		return $observations;
461
		return $observations;
462
	}
462
	}
463
 
463
 
464
	private function supprimerIdDesObs($observations) {
464
	private function supprimerIdDesObs($observations) {
465
		// Le tableau de sortie ne doit pas avoir les id des obs en clé car sinon Jquery Template ne fonctionne pas
465
		// Le tableau de sortie ne doit pas avoir les id des obs en clé car sinon Jquery Template ne fonctionne pas
466
		$observationSansId = $observations;
466
		$observationSansId = $observations;
467
		unset($observationSansId['observations']);
467
		unset($observationSansId['observations']);
468
		foreach ($observations['observations'] as $id => $infos) {
468
		foreach ($observations['observations'] as $id => $infos) {
469
			$observationSansId['observations'][] = $infos;
469
			$observationSansId['observations'][] = $infos;
470
		}
470
		}
471
		return $observationSansId;
471
		return $observationSansId;
472
	}
472
	}
473
 
473
 
474
	/**
474
	/**
475
	 * Liste des taxons présents sur la carte
475
	 * Liste des taxons présents sur la carte
476
	 */
476
	 */
477
	public function getTaxons($params) {
477
	public function getTaxons($params) {
478
		$json = null;
478
		$json = null;
479
 
479
 
480
		$requete = 	'SELECT SQL_CALC_FOUND_ROWS DISTINCT nom_ret, nom_ret_nn, nt, famille '.
480
		$requete = 	'SELECT SQL_CALC_FOUND_ROWS DISTINCT nom_ret, nom_ret_nn, nt, famille '.
481
					'FROM cel_obs AS co '.
481
					'FROM cel_obs AS co '.
482
					'	LEFT JOIN cel_zones_geo AS l '.
482
					'	LEFT JOIN cel_zones_geo AS l '.
483
					'		ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) '.
483
					'		ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) '.
484
					"WHERE transmission = '1' ".
484
					"WHERE transmission = '1' ".
485
					"	AND nom_ret != '' ".
485
					"	AND nom_ret != '' ".
486
					$this->construireWhereDept().
486
					$this->construireWhereDept().
487
                    $this->construireWhereCommune().
487
                    $this->construireWhereCommune().
488
                    $this->construireWhereUtilisateur().
488
                    $this->construireWhereUtilisateur().
489
					$this->construireWhereNumTaxon().
489
					$this->construireWhereNumTaxon().
490
					$this->construireWhereNomTaxon().
490
					$this->construireWhereNomTaxon().
491
					$this->construireWhereReferentiel().
491
					$this->construireWhereReferentiel().
492
					$this->construireWhereDate().
492
					$this->construireWhereDate().
493
					$this->construireWhereCommentaire().
493
					$this->construireWhereCommentaire().
494
					$this->construireWherePhotosSeulement().
494
					$this->construireWherePhotosSeulement().
495
					$this->construireWhereProjet().
495
					$this->construireWhereProjet().
496
					$this->construireWhereTag().
496
					$this->construireWhereTag().
497
					$this->construireWhereNombreDeJours().
497
					$this->construireWhereNombreDeJours().
498
					$this->construireWhereAnnee().
498
					$this->construireWhereAnnee().
499
					'ORDER BY nom_ret ASC '.
499
					'ORDER BY nom_ret ASC '.
500
                    "LIMIT {$this->start},{$this->limit} ";
500
                    "LIMIT {$this->start},{$this->limit} ";
501
		//$this->debug[] = $requete;
501
		//$this->debug[] = $requete;
502
		$resultats = Cel::db()->requeter($requete, self::SQL_RETOUR_COMPLET, self::SQL_MODE_OBJET);
502
		$resultats = Cel::db()->requeter($requete, self::SQL_RETOUR_COMPLET, self::SQL_MODE_OBJET);
503
		//echo $requete;exit;
503
		//echo $requete;exit;
504
		$requete = 'SELECT FOUND_ROWS()';
504
		$requete = 'SELECT FOUND_ROWS()';
505
		$taxons['total'] = (int) Cel::db()->requeter($requete, self::SQL_RETOUR_COLONNE);
505
		$taxons['total'] = (int) Cel::db()->requeter($requete, self::SQL_RETOUR_COLONNE);
506
 
506
 
507
		// Post-traitement
507
		// Post-traitement
508
		$taxons['taxons'] = $this->traiterTaxons($resultats);
508
		$taxons['taxons'] = $this->traiterTaxons($resultats);
509
 
509
 
510
		return $taxons;
510
		return $taxons;
511
	}
511
	}
512
 
512
 
513
	private function traiterTaxons($donnees) {
513
	private function traiterTaxons($donnees) {
514
		$taxons = array();
514
		$taxons = array();
515
		if (is_array($donnees) && count($donnees) > 0) {
515
		if (is_array($donnees) && count($donnees) > 0) {
516
			foreach ($donnees as $donnee) {
516
			foreach ($donnees as $donnee) {
517
				if (!isset($taxons[$donnee->nt]) && ! $this->etreNull($donnee->nom_ret)) {
517
				if (!isset($taxons[$donnee->nt]) && ! $this->etreNull($donnee->nom_ret)) {
518
					$taxon = array();
518
					$taxon = array();
519
					$taxon['nn'] = $donnee->nom_ret_nn;
519
					$taxon['nn'] = $donnee->nom_ret_nn;
520
					$taxon['nt'] = $donnee->nt;
520
					$taxon['nt'] = $donnee->nt;
521
					$taxon['nom'] = $this->nettoyerTexte($donnee->nom_ret);
521
					$taxon['nom'] = $this->nettoyerTexte($donnee->nom_ret);
522
					$taxon['famille'] = $this->nettoyerTexte($donnee->famille);
522
					$taxon['famille'] = $this->nettoyerTexte($donnee->famille);
523
					$taxons[$donnee->nt] = $taxon;
523
					$taxons[$donnee->nt] = $taxon;
524
				}
524
				}
525
			}
525
			}
526
		}
526
		}
527
		$taxons = array_values($taxons);
527
		$taxons = array_values($taxons);
528
		return $taxons;
528
		return $taxons;
529
	}
529
	}
530
 
530
 
531
	private function construireWhereCoordonnees() {
531
	private function construireWhereCoordonnees() {
532
		$sql = '';
532
		$sql = '';
533
		// Récupération des coordonnées depuis l'id station
533
		// Récupération des coordonnées depuis l'id station
534
		extract($this->decomposerParametreStation());
534
		extract($this->decomposerParametreStation());
535
		if (isset($type)) {
535
		if (isset($type)) {
536
			if ($type == self::MARQUEUR_COMMUNE) {
536
			if ($type == self::MARQUEUR_COMMUNE) {
537
				$lat = Cel::db()->proteger($lat.'%');
537
				$lat = Cel::db()->proteger($lat.'%');
538
				$lng = Cel::db()->proteger($lng.'%');
538
				$lng = Cel::db()->proteger($lng.'%');
539
				$sql = " AND wgs84_latitude LIKE $lat AND wgs84_longitude LIKE $lng ";
539
				$sql = " AND wgs84_latitude LIKE $lat AND wgs84_longitude LIKE $lng ";
540
			}  else if ($type == self::MARQUEUR_STATION) {
540
			}  else if ($type == self::MARQUEUR_STATION) {
541
				$lat = Cel::db()->proteger($lat.'%');
541
				$lat = Cel::db()->proteger($lat.'%');
542
				$lng = Cel::db()->proteger($lng.'%');
542
				$lng = Cel::db()->proteger($lng.'%');
543
				$sql = " AND (latitude LIKE $lat AND longitude LIKE $lng) ";
543
				$sql = " AND (latitude LIKE $lat AND longitude LIKE $lng) ";
544
			}
544
			}
545
		}
545
		}
546
		return $sql;
546
		return $sql;
547
	}
547
	}
548
 
548
 
549
	private function construireWhereCoordonneesSansSensibles() {
549
	private function construireWhereCoordonneesSansSensibles() {
550
		$sql = '(';
550
		$sql = '(';
551
		// Récupération des coordonnées depuis l'id station
551
		// Récupération des coordonnées depuis l'id station
552
		extract($this->decomposerParametreStation());
552
		extract($this->decomposerParametreStation());
553
		if (isset($type)) {
553
		if (isset($type)) {
554
			if ($type == self::MARQUEUR_COMMUNE) {
554
			if ($type == self::MARQUEUR_COMMUNE) {
555
				$lat = Cel::db()->proteger($lat);
555
				$lat = Cel::db()->proteger($lat);
556
				$lng = Cel::db()->proteger($lng);
556
				$lng = Cel::db()->proteger($lng);
557
				$sql = " AND wgs84_latitude LIKE $lat AND wgs84_longitude LIKE $lng ";
557
				$sql = " AND wgs84_latitude LIKE $lat AND wgs84_longitude LIKE $lng ";
558
			}  else if ($type == self::MARQUEUR_STATION) {
558
			}  else if ($type == self::MARQUEUR_STATION) {
559
				$lat = Cel::db()->proteger($lat.'%');
559
				$lat = Cel::db()->proteger($lat.'%');
560
				$lng = Cel::db()->proteger($lng.'%');
560
				$lng = Cel::db()->proteger($lng.'%');
561
				$sql = " AND (latitude LIKE $lat AND longitude LIKE $lng) ";
561
				$sql = " AND (latitude LIKE $lat AND longitude LIKE $lng) ";
562
			}
562
			}
563
		}
563
		}
564
		$sql .= ' AND (mots_cles_texte IS NULL OR mots_cles_texte NOT LIKE "%sensible%" ) ';
564
		$sql .= ' AND (mots_cles_texte IS NULL OR mots_cles_texte NOT LIKE "%sensible%" ) ';
565
		return $sql;
565
		return $sql;
566
	}
566
	}
567
 
567
 
568
	private function construireWhereCommentaire() {
568
	private function construireWhereCommentaire() {
569
		$sql = '';
569
		$sql = '';
570
		list($type, $commentaire) = $this->decomposerParametreCommentaire();
570
		list($type, $commentaire) = $this->decomposerParametreCommentaire();
571
		if (!$this->etreNull($commentaire)) {
571
		if (!$this->etreNull($commentaire)) {
572
			$commentaire = Cel::db()->proteger('%'.$commentaire.'%');
572
			$commentaire = Cel::db()->proteger('%'.$commentaire.'%');
573
			switch ($type) {
573
			switch ($type) {
574
				case '*' :
574
				case '*' :
575
					$sql = $this->obtenirConditionPourCommentaires($commentaire);
575
					$sql = $this->obtenirConditionPourCommentaires($commentaire);
576
					$sql = " AND (commentaire LIKE $commentaire OR ($sql)) ";
576
					$sql = " AND (commentaire LIKE $commentaire OR ($sql)) ";
577
					break;
577
					break;
578
				case 'observation' :
578
				case 'observation' :
579
					$sql = " AND commentaire LIKE $commentaire ";
579
					$sql = " AND commentaire LIKE $commentaire ";
580
					break;
580
					break;
581
				case 'photo' :
581
				case 'photo' :
582
					$sql = ' AND '.$this->obtenirConditionPourCommentaires($commentaire).' ';
582
					$sql = ' AND '.$this->obtenirConditionPourCommentaires($commentaire).' ';
583
					break;
583
					break;
584
				case 'photo.meta' :
584
				case 'photo.meta' :
585
					$sql = ' AND '.$this->obtenirConditionPourCommentaireMeta($commentaire).' ';
585
					$sql = ' AND '.$this->obtenirConditionPourCommentaireMeta($commentaire).' ';
586
					break;
586
					break;
587
				case 'photo.utilisateur' :
587
				case 'photo.utilisateur' :
588
					$sql = ' AND '.$this->obtenirConditionPourCommentaireUtilisateur($commentaire).' ';
588
					$sql = ' AND '.$this->obtenirConditionPourCommentaireUtilisateur($commentaire).' ';
589
					break;
589
					break;
590
				default:
590
				default:
591
					$sql = " AND commentaire LIKE $commentaire ";
591
					$sql = " AND commentaire LIKE $commentaire ";
592
			}
592
			}
593
		}
593
		}
594
		return $sql;
594
		return $sql;
595
	}
595
	}
596
 
596
 
597
 
597
 
598
	private function construireWhereNomTaxon() {
598
	private function construireWhereNomTaxon() {
599
		$sql = '';
599
		$sql = '';
600
		list($type, $nom) = $this->decomposerParametreTaxon();
600
		list($type, $nom) = $this->decomposerParametreTaxon();
601
		if (!$this->etreNull($nom)) {
601
		if (!$this->etreNull($nom)) {
602
			$nom = Cel::db()->proteger($nom.'%');
602
			$nom = Cel::db()->proteger($nom.'%');
603
			switch ($type) {
603
			switch ($type) {
604
				case '*' :
604
				case '*' :
605
					$sql = " AND (nom_ret LIKE $nom OR nom_sel LIKE $nom OR famille LIKE $nom) ";
605
					$sql = " AND (nom_ret LIKE $nom OR nom_sel LIKE $nom OR famille LIKE $nom) ";
606
					break;
606
					break;
607
				case 'retenu' :
607
				case 'retenu' :
608
					$sql = " AND nom_ret LIKE $nom ";
608
					$sql = " AND nom_ret LIKE $nom ";
609
					break;
609
					break;
610
				case 'selectionne' :
610
				case 'selectionne' :
611
					$sql = " AND nom_sel LIKE $nom ";
611
					$sql = " AND nom_sel LIKE $nom ";
612
					break;
612
					break;
613
				case 'famille' :
613
				case 'famille' :
614
					$sql = " AND famille LIKE $nom ";
614
					$sql = " AND famille LIKE $nom ";
615
					break;
615
					break;
616
				default:
616
				default:
617
					$sql = " AND nom_ret LIKE $nom ";
617
					$sql = " AND nom_ret LIKE $nom ";
618
			}
618
			}
619
		}
619
		}
620
		return $sql;
620
		return $sql;
621
	}
621
	}
622
 
622
 
623
	private function construireWhereReferentiel() {
623
	private function construireWhereReferentiel() {
624
		$sql = '';
624
		$sql = '';
625
		extract($this->parametres);
625
		extract($this->parametres);
626
		if (isset($referentiel) && !$this->etreNull($referentiel)) {
626
		if (isset($referentiel) && !$this->etreNull($referentiel)) {
627
			$referentiel = Cel::db()->proteger($referentiel.'%');
627
			$referentiel = Cel::db()->proteger($referentiel.'%');
628
			$sql = ' AND co.nom_referentiel LIKE '.$referentiel.' ';
628
			$sql = ' AND co.nom_referentiel LIKE '.$referentiel.' ';
629
		}
629
		}
630
		return $sql;
630
		return $sql;
631
	}
631
	}
632
 
632
 
633
	private function construireWhereDate() {
633
	private function construireWhereDate() {
634
		$sql = '';
634
		$sql = '';
635
		// Récupération des coordonnées depuis l'id station
635
		// Récupération des coordonnées depuis l'id station
636
		list($type, $date) = $this->decomposerParametreDate();
636
		list($type, $date) = $this->decomposerParametreDate();
637
 
637
 
638
		if (!$this->etreNull($date)) {
638
		if (!$this->etreNull($date)) {
639
			$date = Cel::db()->proteger($date.'%');
639
			$date = Cel::db()->proteger($date.'%');
640
			switch ($type) {
640
			switch ($type) {
641
				case '*' :
641
				case '*' :
642
					$sql = " AND (
642
					$sql = " AND (
643
						date_observation LIKE $date
643
						date_observation LIKE $date
644
						OR date_creation LIKE $date
644
						OR date_creation LIKE $date
645
						OR date_modification LIKE $date
645
						OR date_modification LIKE $date
646
						OR date_transmission LIKE $date) ";
646
						OR date_transmission LIKE $date) ";
647
					break;
647
					break;
648
				case 'observation' :
648
				case 'observation' :
649
					$sql = " AND date_observation LIKE $date ";
649
					$sql = " AND date_observation LIKE $date ";
650
					break;
650
					break;
651
				case 'creation' :
651
				case 'creation' :
652
					$sql = " AND date_creation LIKE $date ";
652
					$sql = " AND date_creation LIKE $date ";
653
					break;
653
					break;
654
				case 'modification' :
654
				case 'modification' :
655
					$sql = " AND date_modification LIKE $date ";
655
					$sql = " AND date_modification LIKE $date ";
656
					break;
656
					break;
657
				case 'transmission' :
657
				case 'transmission' :
658
					$sql = " AND date_transmission LIKE $date ";
658
					$sql = " AND date_transmission LIKE $date ";
659
					break;
659
					break;
660
				case 'photo' :
660
				case 'photo' :
661
					$sql = $this->obtenirConditionPourDatePhoto($date);
661
					$sql = $this->obtenirConditionPourDatePhoto($date);
662
					break;
662
					break;
663
				case 'ajout' :
663
				case 'ajout' :
664
					$sql = $this->obtenirConditionPourDateAjout($date);
664
					$sql = $this->obtenirConditionPourDateAjout($date);
665
					break;
665
					break;
666
				case 'liaison' :
666
				case 'liaison' :
667
					$sql = $this->obtenirConditionPourDateLiaison($date);
667
					$sql = $this->obtenirConditionPourDateLiaison($date);
668
					break;
668
					break;
669
				default:
669
				default:
670
					$sql = " AND date_observation LIKE $date ";
670
					$sql = " AND date_observation LIKE $date ";
671
			}
671
			}
672
		}
672
		}
673
		return $sql;
673
		return $sql;
674
	}
674
	}
675
 
675
 
676
	private function obtenirConditionPourDatePhoto($date) {
676
	private function obtenirConditionPourDatePhoto($date) {
677
		$observations = $this->obtenirObsLieesImg('date.photo', $date);
677
		$observations = $this->obtenirObsLieesImg('date.photo', $date);
678
		if (is_null($observations)) {
678
		if (is_null($observations)) {
679
			$this->debug[] = "Aucune observation n'est liée à une photo prise à la date : $date";
679
			$this->debug[] = "Aucune observation n'est liée à une photo prise à la date : $date";
680
		}
680
		}
681
		$sql = $this->assemblerObsEnConditionSql($observations);
681
		$sql = $this->assemblerObsEnConditionSql($observations);
682
		return $sql;
682
		return $sql;
683
	}
683
	}
684
 
684
 
685
	private function obtenirConditionPourDateLiaison($date) {
685
	private function obtenirConditionPourDateLiaison($date) {
686
		$observations = $this->obtenirObsLieesImg('date.liaison', $date);
686
		$observations = $this->obtenirObsLieesImg('date.liaison', $date);
687
		if (is_null($observations)) {
687
		if (is_null($observations)) {
688
			$this->debug[] = "Aucune observation n'a été liée à une image à à la date : $date";
688
			$this->debug[] = "Aucune observation n'a été liée à une image à à la date : $date";
689
		}
689
		}
690
		$sql = $this->assemblerObsEnConditionSql($observations);
690
		$sql = $this->assemblerObsEnConditionSql($observations);
691
		return $sql;
691
		return $sql;
692
	}
692
	}
693
 
693
 
694
	private function obtenirConditionPourDateAjout($date) {
694
	private function obtenirConditionPourDateAjout($date) {
695
		$observations = $this->obtenirObsLieesImg('date.ajout', $date);
695
		$observations = $this->obtenirObsLieesImg('date.ajout', $date);
696
		if (is_null($observations)) {
696
		if (is_null($observations)) {
697
			$this->debug[] = "Aucune observation n'est liée à une image ajoutée à la date : $date";
697
			$this->debug[] = "Aucune observation n'est liée à une image ajoutée à la date : $date";
698
		}
698
		}
699
		$sql = $this->assemblerObsEnConditionSql($observations);
699
		$sql = $this->assemblerObsEnConditionSql($observations);
700
		return $sql;
700
		return $sql;
701
	}
701
	}
702
 
702
 
703
	private function obtenirConditionPourCommentaireMeta($commentaire) {
703
	private function obtenirConditionPourCommentaireMeta($commentaire) {
704
		$observations = $this->obtenirObsLieesImg('commentaire.meta', $commentaire);
704
		$observations = $this->obtenirObsLieesImg('commentaire.meta', $commentaire);
705
		if (is_null($observations)) {
705
		if (is_null($observations)) {
706
			$this->debug[] = "Aucune observation n'est liée à une image dont le commentaire des méta-données correspond à : $commmentaire";
706
			$this->debug[] = "Aucune observation n'est liée à une image dont le commentaire des méta-données correspond à : $commmentaire";
707
		}
707
		}
708
		$operateur = '';
708
		$operateur = '';
709
		$sql = $this->assemblerObsEnConditionSql($observations, $operateur);
709
		$sql = $this->assemblerObsEnConditionSql($observations, $operateur);
710
		return $sql;
710
		return $sql;
711
	}
711
	}
712
 
712
 
713
	private function obtenirConditionPourCommentaireUtilisateur($commentaire) {
713
	private function obtenirConditionPourCommentaireUtilisateur($commentaire) {
714
		$observations = $this->obtenirObsLieesImg('commentaire.utilisateur', $commentaire);
714
		$observations = $this->obtenirObsLieesImg('commentaire.utilisateur', $commentaire);
715
		if (is_null($observations)) {
715
		if (is_null($observations)) {
716
			$this->debug[] = "Aucune observation n'est liée à une image dont le commentaire des utilisateur correspond à : $commmentaire";
716
			$this->debug[] = "Aucune observation n'est liée à une image dont le commentaire des utilisateur correspond à : $commmentaire";
717
		}
717
		}
718
		$operateur = '';
718
		$operateur = '';
719
		$sql = $this->assemblerObsEnConditionSql($observations, $operateur);
719
		$sql = $this->assemblerObsEnConditionSql($observations, $operateur);
720
		return $sql;
720
		return $sql;
721
	}
721
	}
722
 
722
 
723
	private function obtenirConditionPourCommentaires($commentaire) {
723
	private function obtenirConditionPourCommentaires($commentaire) {
724
		$observations = $this->obtenirObsLieesImg('commentaire.*', $commentaire);
724
		$observations = $this->obtenirObsLieesImg('commentaire.*', $commentaire);
725
		if (is_null($observations)) {
725
		if (is_null($observations)) {
726
			$this->debug[] = "Aucune observation n'est liée à une image dont un des commentaires correspond à : $commmentaire";
726
			$this->debug[] = "Aucune observation n'est liée à une image dont un des commentaires correspond à : $commmentaire";
727
		}
727
		}
728
		$operateur = '';
728
		$operateur = '';
729
		$sql = $this->assemblerObsEnConditionSql($observations, $operateur);
729
		$sql = $this->assemblerObsEnConditionSql($observations, $operateur);
730
		return $sql;
730
		return $sql;
731
	}
731
	}
732
 
732
 
733
	/**
733
	/**
734
	 * Récupération des identifiant d'utilisateur et des ordres des observations correspondant à une date.
734
	 * Récupération des identifiant d'utilisateur et des ordres des observations correspondant à une date.
735
	 * Retour sous forme de tableau : array[identifiant] = array(ordre, ordre...);
735
	 * Retour sous forme de tableau : array[identifiant] = array(ordre, ordre...);
736
	 */
736
	 */
737
	private function obtenirObsLieesImg($type, $param) {
737
	private function obtenirObsLieesImg($type, $param) {
738
		// Construction de la requête
738
		// Construction de la requête
739
		$requete = 	'SELECT DISTINCT co.id_obs,  ci.ce_utilisateur AS utilisateur '.
739
		$requete = 	'SELECT DISTINCT co.id_obs, ci.ce_utilisateur AS utilisateur '.
740
			'FROM  cel_images '.
740
			'FROM cel_images '.
741
			'	LEFT JOIN cel_obs_images coi '.
-
 
742
			'		ON (ci.id_image = coi.id_image) '.
-
 
743
			'	LEFT JOIN cel_obs AS co '.
741
			'	LEFT JOIN cel_obs AS co '.
744
			'		ON (coi.id_observation = co.id_observation) '.
742
			'		ON (ci.ce_observation = co.id_observation) '.
745
			'	LEFT JOIN cel_zones_geo AS l '.
743
			'	LEFT JOIN cel_zones_geo AS l '.
746
			'		ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) '.
744
			'		ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) '.
747
			"WHERE  transmission = '1' ".
745
			"WHERE co.transmission = '1' ".
748
			($type == 'date.photo' ? " AND (ci_meta_date_time LIKE ".str_replace('-', ':', $param)." OR ci_meta_date LIKE $param) " : '').
746
			($type == 'date.photo' ? " AND (ci.date_prise_de_vue LIKE ".str_replace('-', ':', $param).' ' : '').
749
			($type == 'date.ajout' ? " AND ci_meta_date_ajout LIKE $param " : '').
747
			($type == 'date.creation' ? " AND ci.date_creation LIKE $param " : '').
750
			($type == 'date.liaison' ? " AND coi_date_liaison LIKE $param " : '').
748
			($type == 'date.liaison' ? " AND ci.date_liaison LIKE $param " : '').
751
			($type == 'commentaire.meta' ? " AND ci_meta_comment LIKE $param " : '').
749
			($type == 'commentaire.img' ? " AND ci.commentaire LIKE $param " : '').
752
			($type == 'commentaire.utilisateur' ? "	AND ci_meta_user_comment LIKE $param " : '').
750
			($type == 'commentaire.obs' ? "	AND co.commentaire LIKE $param " : '').
753
			($type == 'commentaire.*' ? " AND (ci_meta_comment LIKE $param OR ci_meta_user_comment LIKE $param) " : '').
751
			($type == 'commentaire.*' ? " AND (co.commentaire LIKE $param OR ci.commentaire LIKE $param) " : '').
754
			$this->construireWhereCoordonnees().
752
			$this->construireWhereCoordonnees().
755
			$this->construireWhereDept().
753
			$this->construireWhereDept().
756
			$this->construireWhereCommune().
754
			$this->construireWhereCommune().
757
			$this->construireWhereUtilisateur().
755
			$this->construireWhereUtilisateur().
758
			$this->construireWhereNumTaxon().
756
			$this->construireWhereNumTaxon().
759
			$this->construireWhereNomTaxon().
757
			$this->construireWhereNomTaxon().
760
			$this->construireWhereReferentiel().
758
			$this->construireWhereReferentiel().
761
			$this->construireWhereProjet().
759
			$this->construireWhereProjet().
762
			$this->construireWhereTag().
760
			$this->construireWhereTag().
763
			'ORDER BY utilisateur ASC, ordre ASC';
761
			'ORDER BY utilisateur ASC, ordre ASC';
764
		//$this->debug[] = $requete;
762
		//$this->debug[] = $requete;
765
		//die($requete);
763
		//die($requete);
766
		$resultats = Cel::db()->requeter($requete);
764
		$resultats = Cel::db()->requeter($requete);
767
 
765
 
768
		$observations = null;
766
		$observations = null;
769
		if ($resultats != false) {
767
		if ($resultats != false) {
770
			$observations = array();
768
			$observations = array();
771
			foreach ($resultats as $occurence) {
769
			foreach ($resultats as $occurence) {
772
				$utilisateur = $occurence['utilisateur'];
770
				$utilisateur = $occurence['utilisateur'];
773
				$ordre = $occurence['ordre'];
771
				$ordre = $occurence['ordre'];
774
				if (!array_key_exists($utilisateur, $observations)) {
772
				if (!array_key_exists($utilisateur, $observations)) {
775
					$observations[$utilisateur] = array();
773
					$observations[$utilisateur] = array();
776
				}
774
				}
777
				if (!array_key_exists($ordre, $observations[$utilisateur])) {
775
				if (!array_key_exists($ordre, $observations[$utilisateur])) {
778
					$observations[$utilisateur][$ordre] = $ordre;
776
					$observations[$utilisateur][$ordre] = $ordre;
779
				}
777
				}
780
			}
778
			}
781
		}
779
		}
782
		return $observations;
780
		return $observations;
783
	}
781
	}
784
 
782
 
785
	private function assemblerObsEnConditionSql($observations, $operateur = 'AND') {
783
	private function assemblerObsEnConditionSql($observations, $operateur = 'AND') {
786
		$sql = '';
784
		$sql = '';
787
		if ($observations != null) {
785
		if ($observations != null) {
788
			// Pré-construction du where de la requête
786
			// Pré-construction du where de la requête
789
			$tpl_where = "(identifiant = '%s' AND ordre IN (%s))";
787
			$tpl_where = "(identifiant = '%s' AND ordre IN (%s))";
790
			foreach ($observations as $utilisateur => $ordres) {
788
			foreach ($observations as $utilisateur => $ordres) {
791
				$morceaux_requete[] = sprintf($tpl_where, $utilisateur, implode(',', $ordres));
789
				$morceaux_requete[] = sprintf($tpl_where, $utilisateur, implode(',', $ordres));
792
			}
790
			}
793
			if (count($morceaux_requete) > 0) {
791
			if (count($morceaux_requete) > 0) {
794
				$sql = implode(" \nOR ", $morceaux_requete);
792
				$sql = implode(" \nOR ", $morceaux_requete);
795
			}
793
			}
796
		} else {
794
		} else {
797
			// Nous voulons que la requête ne retourne rien
795
			// Nous voulons que la requête ne retourne rien
798
			$sql = "identifiant = '' AND ordre = ''";
796
			$sql = "identifiant = '' AND ordre = ''";
799
		}
797
		}
800
		$sql = " $operateur ($sql) ";
798
		$sql = " $operateur ($sql) ";
801
		return $sql;
799
		return $sql;
802
	}
800
	}
803
 
801
 
804
	private function construireWhereRectangleStation() {
802
	private function construireWhereRectangleStation() {
805
		$sql = '';
803
		$sql = '';
806
		if (isset($this->parametres['ne']) && isset($this->parametres['sw']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
804
		if (isset($this->parametres['ne']) && isset($this->parametres['sw']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
807
			$ne = $this->decomposerLatLng($this->parametres['ne']);
805
			$ne = $this->decomposerLatLng($this->parametres['ne']);
808
			$sw = $this->decomposerLatLng($this->parametres['sw']);
806
			$sw = $this->decomposerLatLng($this->parametres['sw']);
809
 
807
 
810
			$latMin = $sw['lat'];
808
			$latMin = $sw['lat'];
811
			$lngMin = $sw['lng'];
809
			$lngMin = $sw['lng'];
812
 
810
 
813
			$latMax = $ne['lat'];
811
			$latMax = $ne['lat'];
814
			$lngMax = $ne['lng'];
812
			$lngMax = $ne['lng'];
815
 
813
 
816
			// ATTENTION : latitude correspond bien à la LATITUDE!
814
			// ATTENTION : latitude correspond bien à la LATITUDE!
817
			$sql = " AND (latitude != 0 AND longitude != 0) ".
815
			$sql = " AND (latitude != 0 AND longitude != 0) ".
818
				" AND latitude > $latMin ".
816
				" AND latitude > $latMin ".
819
				" AND latitude < $latMax ".
817
				" AND latitude < $latMax ".
820
				" AND longitude > $lngMin ".
818
				" AND longitude > $lngMin ".
821
				" AND longitude < $lngMax ";
819
				" AND longitude < $lngMax ";
822
		}
820
		}
823
		return $sql;
821
		return $sql;
824
	}
822
	}
825
 
823
 
826
	private function construireWhereRectangleStationOR() {
824
	private function construireWhereRectangleStationOR() {
827
		$sql = '';
825
		$sql = '';
828
		if (isset($this->parametres['ne']) && isset($this->parametres['sw']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
826
		if (isset($this->parametres['ne']) && isset($this->parametres['sw']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
829
			$ne = $this->decomposerLatLng($this->parametres['ne']);
827
			$ne = $this->decomposerLatLng($this->parametres['ne']);
830
			$sw = $this->decomposerLatLng($this->parametres['sw']);
828
			$sw = $this->decomposerLatLng($this->parametres['sw']);
831
 
829
 
832
			$latMin = $sw['lat'];
830
			$latMin = $sw['lat'];
833
			$lngMin = $sw['lng'];
831
			$lngMin = $sw['lng'];
834
 
832
 
835
			$latMax = $ne['lat'];
833
			$latMax = $ne['lat'];
836
			$lngMax = $ne['lng'];
834
			$lngMax = $ne['lng'];
837
 
835
 
838
			$sql = "( (latitude != 0 AND longitude != 0) ".
836
			$sql = "( (latitude != 0 AND longitude != 0) ".
839
				" AND latitude BETWEEN $latMin AND $latMax ".
837
				" AND latitude BETWEEN $latMin AND $latMax ".
840
				" AND longitude BETWEEN $lngMin AND $lngMax )";
838
				" AND longitude BETWEEN $lngMin AND $lngMax )";
841
 
839
 
842
			/*$sql = " MBRWithin(mon_point, GeomFromText('POLYGON((".$latMin.' '.$lngMin.','.
840
			/*$sql = " MBRWithin(mon_point, GeomFromText('POLYGON((".$latMin.' '.$lngMin.','.
843
			$latMax.' '.$lngMin.','.
841
			$latMax.' '.$lngMin.','.
844
			$latMax.' '.$lngMax.','.
842
			$latMax.' '.$lngMax.','.
845
			$latMax.' '.$lngMin.','.
843
			$latMax.' '.$lngMin.','.
846
			$latMin.' '.$lngMin."))')) ";		*/
844
			$latMin.' '.$lngMin."))')) ";		*/
847
		}
845
		}
848
		return $sql;
846
		return $sql;
849
	}
847
	}
850
 
848
 
851
	private function construireWhereRectangleCommune() {
849
	private function construireWhereRectangleCommune() {
852
		$sql = '';
850
		$sql = '';
853
		if (isset($this->parametres['ne']) && isset($this->parametres['sw']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
851
		if (isset($this->parametres['ne']) && isset($this->parametres['sw']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
854
			$ne = $this->decomposerLatLng($this->parametres['ne']);
852
			$ne = $this->decomposerLatLng($this->parametres['ne']);
855
			$sw = $this->decomposerLatLng($this->parametres['sw']);
853
			$sw = $this->decomposerLatLng($this->parametres['sw']);
856
 
854
 
857
			$latMin = $sw['lat'];
855
			$latMin = $sw['lat'];
858
			$lngMin = $sw['lng'];
856
			$lngMin = $sw['lng'];
859
 
857
 
860
			$latMax = $ne['lat'];
858
			$latMax = $ne['lat'];
861
			$lngMax = $ne['lng'];
859
			$lngMax = $ne['lng'];
862
 
860
 
863
			$sql = "AND wgs84_longitude != 0 AND wgs84_latitude != 0 ".
861
			$sql = "AND wgs84_longitude != 0 AND wgs84_latitude != 0 ".
864
				" AND wgs84_latitude BETWEEN $latMin AND $latMax ".
862
				" AND wgs84_latitude BETWEEN $latMin AND $latMax ".
865
				" AND wgs84_longitude BETWEEN $lngMin AND $lngMax ";
863
				" AND wgs84_longitude BETWEEN $lngMin AND $lngMax ";
866
		}
864
		}
867
		return $sql;
865
		return $sql;
868
	}
866
	}
869
 
867
 
870
	private function construireWhereRectangleCommuneOR() {
868
	private function construireWhereRectangleCommuneOR() {
871
		$sql = '';
869
		$sql = '';
872
		if (isset($this->parametres['ne']) && isset($this->parametres['sw']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
870
		if (isset($this->parametres['ne']) && isset($this->parametres['sw']) && ! $this->etreNull($this->parametres['ne']) && ! $this->etreNull($this->parametres['sw'])) {
873
			$ne = $this->decomposerLatLng($this->parametres['ne']);
871
			$ne = $this->decomposerLatLng($this->parametres['ne']);
874
			$sw = $this->decomposerLatLng($this->parametres['sw']);
872
			$sw = $this->decomposerLatLng($this->parametres['sw']);
875
 
873
 
876
			$latMin = $sw['lat'];
874
			$latMin = $sw['lat'];
877
			$lngMin = $sw['lng'];
875
			$lngMin = $sw['lng'];
878
 
876
 
879
			$latMax = $ne['lat'];
877
			$latMax = $ne['lat'];
880
			$lngMax = $ne['lng'];
878
			$lngMax = $ne['lng'];
881
 
879
 
882
			$sql = "( wgs84_longitude != 0 AND wgs84_latitude != 0 ".
880
			$sql = "( wgs84_longitude != 0 AND wgs84_latitude != 0 ".
883
				" AND wgs84_latitude BETWEEN $latMin AND $latMax ".
881
				" AND wgs84_latitude BETWEEN $latMin AND $latMax ".
884
				" AND wgs84_longitude BETWEEN $lngMin AND $lngMax )";
882
				" AND wgs84_longitude BETWEEN $lngMin AND $lngMax )";
885
 
883
 
886
			/*$sql = " MBRWithin(point_commune, GeomFromText('POLYGON((".$latMin.' '.$lngMin.','.
884
			/*$sql = " MBRWithin(point_commune, GeomFromText('POLYGON((".$latMin.' '.$lngMin.','.
887
			$latMax.' '.$lngMin.','.
885
			$latMax.' '.$lngMin.','.
888
			$latMax.' '.$lngMax.','.
886
			$latMax.' '.$lngMax.','.
889
			$latMax.' '.$lngMin.','.
887
			$latMax.' '.$lngMin.','.
890
			$latMin.' '.$lngMin."))')) ";*/
888
			$latMin.' '.$lngMin."))')) ";*/
891
		}
889
		}
892
		return $sql;
890
		return $sql;
893
	}
891
	}
894
 
892
 
895
	private function construireWhereDept() {
893
	private function construireWhereDept() {
896
		$sql = '';
894
		$sql = '';
897
		// Récupération des coordonnées depuis l'id station
895
		// Récupération des coordonnées depuis l'id station
898
		extract($this->parametres);
896
		extract($this->parametres);
899
		if (isset($dept) && !$this->etreNull($dept)) {
897
		if (isset($dept) && !$this->etreNull($dept)) {
900
			$valeurs_a_proteger = explode(',',trim($dept));
898
			$valeurs_a_proteger = explode(',',trim($dept));
901
			foreach ($valeurs_a_proteger as $valeur) {
899
			foreach ($valeurs_a_proteger as $valeur) {
902
				$valeurs_protegees[] = '(ce_zone_geo LIKE '.Cel::db()->quote('INSEE-C:'.$valeur.'%').') ';
900
				$valeurs_protegees[] = '(ce_zone_geo LIKE '.Cel::db()->quote('INSEE-C:'.$valeur.'%').') ';
903
			}
901
			}
904
			$valeurs = implode(' OR ', $valeurs_protegees);
902
			$valeurs = implode(' OR ', $valeurs_protegees);
905
			$sql = " AND ($valeurs) ";
903
			$sql = " AND ($valeurs) ";
906
		}
904
		}
907
		return $sql;
905
		return $sql;
908
	}
906
	}
909
 
907
 
910
	private function construireWhereCommune() {
908
	private function construireWhereCommune() {
911
		$sql = '';
909
		$sql = '';
912
		// Récupération des coordonnées depuis l'id station
910
		// Récupération des coordonnées depuis l'id station
913
		extract($this->parametres);
911
		extract($this->parametres);
914
		if (isset($this->parametres['commune']) && !$this->etreNull($commune)) {
912
		if (isset($this->parametres['commune']) && !$this->etreNull($commune)) {
915
			$commune = Cel::db()->proteger($commune);
913
			$commune = Cel::db()->proteger($commune);
916
			$sql = " AND zone_geo LIKE $commune";
914
			$sql = " AND zone_geo LIKE $commune";
917
		}
915
		}
918
		if (isset($this->parametres['zonegeo']) && !$this->etreNull($zonegeo)) {
916
		if (isset($this->parametres['zonegeo']) && !$this->etreNull($zonegeo)) {
919
			$zonegeo = Cel::db()->proteger($zonegeo);
917
			$zonegeo = Cel::db()->proteger($zonegeo);
920
			$sql = " AND ce_zone_geo = $zonegeo";
918
			$sql = " AND ce_zone_geo = $zonegeo";
921
		}
919
		}
922
		return $sql;
920
		return $sql;
923
	}
921
	}
924
 
922
 
925
	private function construireWhereCommuneSansCoordonneesAvecSensibles() {
923
	private function construireWhereCommuneSansCoordonneesAvecSensibles() {
926
		$sql = '';
924
		$sql = '';
927
		// Récupération des coordonnées depuis l'id station
925
		// Récupération des coordonnées depuis l'id station
928
		extract($this->parametres);
926
		extract($this->parametres);
929
		if (isset($this->parametres['commune']) && !$this->etreNull($commune)) {
927
		if (isset($this->parametres['commune']) && !$this->etreNull($commune)) {
930
			$commune = Cel::db()->proteger($commune);
928
			$commune = Cel::db()->proteger($commune);
931
			$sql = " AND zone_geo LIKE $commune";
929
			$sql = " AND zone_geo LIKE $commune";
932
			$sql .= " AND (
930
			$sql .= " AND (
933
			           		(
931
			           		(
934
			           			(latitude = '000null' OR latitude = '' OR latitude = 0 OR latitude IS NULL) ".
932
			           			(latitude = '000null' OR latitude = '' OR latitude = 0 OR latitude IS NULL) ".
935
								" AND (longitude = '000null' OR longitude = '' OR longitude = 0 OR longitude IS NULL)".
933
								" AND (longitude = '000null' OR longitude = '' OR longitude = 0 OR longitude IS NULL)".
936
							')'.
934
							')'.
937
							' OR mots_cles_texte LIKE "%sensible%"'.
935
							' OR mots_cles_texte LIKE "%sensible%"'.
938
						') ';
936
						') ';
939
 
937
 
940
		}
938
		}
941
		if (isset($this->parametres['zonegeo']) && !$this->etreNull($zonegeo)) {
939
		if (isset($this->parametres['zonegeo']) && !$this->etreNull($zonegeo)) {
942
			$zonegeo = Cel::db()->proteger($zonegeo);
940
			$zonegeo = Cel::db()->proteger($zonegeo);
943
			$sql = " AND ce_zone_geo = $zonegeo";
941
			$sql = " AND ce_zone_geo = $zonegeo";
944
		}
942
		}
945
		return $sql;
943
		return $sql;
946
	}
944
	}
947
 
945
 
948
 
946
 
949
	private function construireWherePhotosSeulement() {
947
	private function construireWherePhotosSeulement() {
950
		$sql = '';
948
		$sql = '';
951
		if (isset($this->parametres['photos']) && $this->parametres['photos'] == 1) {
949
		if (isset($this->parametres['photos']) && $this->parametres['photos'] == 1) {
952
			$sql = 'AND co.id_observation IN (SELECT DISTINCT id_observation FROM cel_obs_images) ';
950
			$sql = 'AND co.id_observation IN (SELECT DISTINCT ce_observation FROM cel_images) ';
953
		}
951
		}
954
		return $sql;
952
		return $sql;
955
	}
953
	}
956
 
954
 
957
	private function construireWhereUtilisateur() {
955
	private function construireWhereUtilisateur() {
958
		$sql = '';
956
		$sql = '';
959
		// TODO tester si l'on recoit un id, un mail ou bien un nom ou prenom
957
		// TODO tester si l'on recoit un id, un mail ou bien un nom ou prenom
960
		// pour en faire une fonction polyvalente
958
		// pour en faire une fonction polyvalente
961
		extract($this->parametres);
959
		extract($this->parametres);
962
		if (isset($this->parametres['utilisateur']) && !$this->etreNull($utilisateur)) {
960
		if (isset($this->parametres['utilisateur']) && !$this->etreNull($utilisateur)) {
963
			$utilisateur = Cel::db()->proteger($utilisateur);
961
			$utilisateur = Cel::db()->proteger($utilisateur);
964
			$sql = " AND co.courriel_utilisateur = $utilisateur ";
962
			$sql = " AND co.courriel_utilisateur = $utilisateur ";
965
		}
963
		}
966
		return $sql;
964
		return $sql;
967
	}
965
	}
968
 
966
 
969
 
967
 
970
	private function construireWhereNumTaxon() {
968
	private function construireWhereNumTaxon() {
971
		$sql = '';
969
		$sql = '';
972
		// Récupération des coordonnées depuis l'id station
970
		// Récupération des coordonnées depuis l'id station
973
		extract($this->parametres);
971
		extract($this->parametres);
974
		if (isset($this->parametres['num_taxon']) && !$this->etreNull($num_taxon)) {
972
		if (isset($this->parametres['num_taxon']) && !$this->etreNull($num_taxon)) {
975
		$num_taxon = Cel::db()->proteger($num_taxon);
973
		$num_taxon = Cel::db()->proteger($num_taxon);
976
		$sql = " AND nt = $num_taxon ";
974
		$sql = " AND nt = $num_taxon ";
977
		}
975
		}
978
		return $sql;
976
		return $sql;
979
	}
977
	}
980
 
978
 
981
	private function construireWhereNumTaxonAvecSousTaxons() {
979
	private function construireWhereNumTaxonAvecSousTaxons() {
982
		$sql = '';
980
		$sql = '';
983
		// Récupération des coordonnées depuis l'id station
981
		// Récupération des coordonnées depuis l'id station
984
		extract($this->parametres);
982
		extract($this->parametres);
985
		if (isset($this->parametres['num_taxon']) && !$this->etreNull($num_taxon)) {
983
		if (isset($this->parametres['num_taxon']) && !$this->etreNull($num_taxon)) {
986
			$sous_taxons = $this->obtenirSousTaxons($this->parametres['num_taxon']);
984
			$sous_taxons = $this->obtenirSousTaxons($this->parametres['num_taxon']);
987
			$num_taxon = Cel::db()->proteger($num_taxon);
985
			$num_taxon = Cel::db()->proteger($num_taxon);
988
			if(!empty($sous_taxons)) {
986
			if(!empty($sous_taxons)) {
989
				$sql_in_sous_tax = implode(',', $sous_taxons);
987
				$sql_in_sous_tax = implode(',', $sous_taxons);
990
				$sql = " AND (nt = $num_taxon OR ".
988
				$sql = " AND (nt = $num_taxon OR ".
991
							"nom_sel_nn IN (".$sql_in_sous_tax.") OR ".
989
							"nom_sel_nn IN (".$sql_in_sous_tax.") OR ".
992
							"nom_ret_nn IN (".$sql_in_sous_tax.") ".
990
							"nom_ret_nn IN (".$sql_in_sous_tax.") ".
993
							") ";
991
							") ";
994
			}
992
			}
995
			else {
993
			else {
996
				$sql = " AND nt = $num_taxon ";
994
				$sql = " AND nt = $num_taxon ";
997
			}
995
			}
998
		}
996
		}
999
		return $sql;
997
		return $sql;
1000
	}
998
	}
1001
 
999
 
1002
	private function obtenirSousTaxons($nt) {
1000
	private function obtenirSousTaxons($nt) {
1003
		$referentiel = 'bdtfx';
1001
		$referentiel = 'bdtfx';
1004
		if(isset($this->parametres['referentiel']) && $this->parametres['referentiel'] != "" && $this->parametres['referentiel'] != '*') {
1002
		if(isset($this->parametres['referentiel']) && $this->parametres['referentiel'] != "" && $this->parametres['referentiel'] != '*') {
1005
			$referentiel = $this->parametres['referentiel'];
1003
			$referentiel = $this->parametres['referentiel'];
1006
		}
1004
		}
1007
		$nn_sous_taxons = array();
1005
		$nn_sous_taxons = array();
1008
		$sous_taxons = $this->obtenirSousTaxonsPourNt($referentiel, $nt);
1006
		$sous_taxons = $this->obtenirSousTaxonsPourNt($referentiel, $nt);
1009
		foreach($sous_taxons as $sous_tax) {
1007
		foreach($sous_taxons as $sous_tax) {
1010
			$nn_sous_taxons[] = $sous_tax['num_nom'];
1008
			$nn_sous_taxons[] = $sous_tax['num_nom'];
1011
		}
1009
		}
1012
		return $nn_sous_taxons;
1010
		return $nn_sous_taxons;
1013
	}
1011
	}
1014
 
1012
 
1015
	private function construireWhereProjet() {
1013
	private function construireWhereProjet() {
1016
		$sql = '';
1014
		$sql = '';
1017
		extract($this->parametres);
1015
		extract($this->parametres);
1018
		$projet_sql = isset($projet) ? $this->getSqlWhereProjet($projet) : null;
1016
		$projet_sql = isset($projet) ? $this->getSqlWhereProjet($projet) : null;
1019
		if (!$this->etreNull($projet_sql)) {
1017
		if (!$this->etreNull($projet_sql)) {
1020
			$sql = " AND ($projet_sql) ";
1018
			$sql = " AND ($projet_sql) ";
1021
		}
1019
		}
1022
		return $sql;
1020
		return $sql;
1023
	}
1021
	}
1024
 
1022
 
1025
	/**
1023
	/**
1026
	 * Traitement de $projet pour construction du filtre dans la requête
1024
	 * Traitement de $projet pour construction du filtre dans la requête
1027
	 * 
1025
	 *
1028
	 * projet1 ET projet2 ET projet3 => intersection
1026
	 * projet1 ET projet2 ET projet3 => intersection
1029
	 * projet1 OU projet2 OU projet3 => union
1027
	 * projet1 OU projet2 OU projet3 => union
1030
	 * projet1 ET projet2 OU projet3 => ATTENTION indéfini 
1028
	 * projet1 ET projet2 OU projet3 => ATTENTION indéfini
1031
	 */
1029
	 */
1032
	private function getSqlWhereProjet($projet) {
1030
	private function getSqlWhereProjet($projet) {
1033
		$sql = null;
1031
		$sql = null;
1034
		if (isset($projet) && !$this->etreNull($projet)) {			
1032
		if (isset($projet) && !$this->etreNull($projet)) {
1035
			if (strpos($projet, ' ET ')) {
1033
			if (strpos($projet, ' ET ')) {
1036
				// intersection
1034
				// intersection
1037
				$projets = explode(' ET ', $projet);
1035
				$projets = explode(' ET ', $projet);
1038
				$clauses = array();
1036
				$clauses = array();
1039
				foreach ($projets as $proj) {
1037
				foreach ($projets as $proj) {
1040
					if ($proj != '') {
1038
					if ($proj != '') {
1041
						$clauses[] = 'co.mots_cles_texte LIKE '.Cel::db()->proteger('%'.$proj.'%');
1039
						$clauses[] = 'co.mots_cles_texte LIKE '.Cel::db()->proteger('%'.$proj.'%');
1042
					}
1040
					}
1043
				}
1041
				}
1044
				$sql = implode($clauses, ' AND ');
1042
				$sql = implode($clauses, ' AND ');
1045
			} else if (strpos($projet, ' OU ')) {
1043
			} else if (strpos($projet, ' OU ')) {
1046
				// union
1044
				// union
1047
				$projets = explode(' OU ', $projet);
1045
				$projets = explode(' OU ', $projet);
1048
				$clauses = array();
1046
				$clauses = array();
1049
				foreach ($projets as $proj) {
1047
				foreach ($projets as $proj) {
1050
					if ($proj != '') {
1048
					if ($proj != '') {
1051
						$clauses[] = 'co.mots_cles_texte LIKE '.Cel::db()->proteger('%'.$proj.'%');
1049
						$clauses[] = 'co.mots_cles_texte LIKE '.Cel::db()->proteger('%'.$proj.'%');
1052
					}
1050
					}
1053
				}
1051
				}
1054
				$sql = implode($clauses, ' OR ');
1052
				$sql = implode($clauses, ' OR ');
1055
			} else {
1053
			} else {
1056
				// simple
1054
				// simple
1057
				$sql = 'co.mots_cles_texte LIKE '.Cel::db()->proteger('%'.$projet.'%');
1055
				$sql = 'co.mots_cles_texte LIKE '.Cel::db()->proteger('%'.$projet.'%');
1058
			}
1056
			}
1059
		}
1057
		}
1060
		return $sql;
1058
		return $sql;
1061
	}
1059
	}
1062
 
1060
 
1063
	private function construireWhereTag() {
1061
	private function construireWhereTag() {
1064
		$sql = '';
1062
		$sql = '';
1065
		extract($this->parametres);
1063
		extract($this->parametres);
1066
		$tag_sql = isset($tag) ? $this->getSqlWhereObsAvecImagesTaguees($tag) : null;
1064
		$tag_sql = isset($tag) ? $this->getSqlWhereObsAvecImagesTaguees($tag) : null;
1067
		if (!$this->etreNull($tag_sql)) {
1065
		if (!$this->etreNull($tag_sql)) {
1068
			$sql = " AND ($tag_sql) ";
1066
			$sql = " AND ($tag_sql) ";
1069
		}
1067
		}
1070
		return $sql;
1068
		return $sql;
1071
	}
1069
	}
1072
 
1070
 
1073
	private function construireWhereNombreDeJours() {
1071
	private function construireWhereNombreDeJours() {
1074
		$sql = null;
1072
		$sql = null;
1075
		extract($this->parametres);
1073
		extract($this->parametres);
1076
		if (isset($nbjours) && !$this->etreNull($nbjours)) {
1074
		if (isset($nbjours) && !$this->etreNull($nbjours)) {
1077
			$sql = ' AND DATEDIFF(CURDATE(),co.date_creation) <= '.Cel::db()->proteger($nbjours).' ';
1075
			$sql = ' AND DATEDIFF(CURDATE(),co.date_creation) <= '.Cel::db()->proteger($nbjours).' ';
1078
		}
1076
		}
1079
		return $sql;
1077
		return $sql;
1080
	}
1078
	}
1081
 
1079
 
1082
	private function construireWhereAnnee() {
1080
	private function construireWhereAnnee() {
1083
		$sql = null;
1081
		$sql = null;
1084
		extract($this->parametres);
1082
		extract($this->parametres);
1085
		if (isset($annee) && !$this->etreNull($annee)) {
1083
		if (isset($annee) && !$this->etreNull($annee)) {
1086
			$sql = ' AND YEAR(co.date_creation) = ' . Cel::db()->proteger($annee) . ' ';
1084
			$sql = ' AND YEAR(co.date_creation) = ' . Cel::db()->proteger($annee) . ' ';
1087
		}
1085
		}
1088
		return $sql;
1086
		return $sql;
1089
	}
1087
	}
1090
 
1088
 
1091
	/**
1089
	/**
1092
	 * Traitement de $tag pour construction du filtre dans la requête
1090
	 * Traitement de $tag pour construction du filtre dans la requête
1093
	 */
1091
	 */
1094
	private function getSqlWhereObsAvecImagesTaguees($tag) {
1092
	private function getSqlWhereObsAvecImagesTaguees($tag) {
1095
		$sql = null;
1093
		$sql = null;
1096
		if (isset($tag) && !$this->etreNull($tag)) {
1094
		if (isset($tag) && !$this->etreNull($tag)) {
1097
			$tag_sql = $this->getSqlWhereMotsCles($tag);
1095
			$tag_sql = $this->getSqlWhereMotsCles($tag);
1098
			// Construction de la requête
1096
			// Construction de la requête
1099
			$requete = 	'SELECT DISTINCT coi.id_observation AS id_obs,  ci.ce_utilisateur AS utilisateur '.
1097
			$requete = 	'SELECT DISTINCT co.id_observation AS id_obs, ci.ce_utilisateur AS utilisateur '.
1100
						'FROM cel_images ci'.
1098
						'FROM cel_images ci'.
1101
						'	LEFT JOIN cel_obs_images coi'.
-
 
1102
						'		ON (ci.id_image = coi.id_image) '.
-
 
1103
						'	LEFT JOIN cel_obs AS co '.
1099
						'	INNER JOIN cel_obs AS co '.
1104
						'		ON (coi.id_observation = co.id_observation) '.
1100
						'		ON (ci.ce_observation = co.id_observation) '.
1105
						'	LEFT JOIN cel_zones_geo AS l '.
1101
						'	LEFT JOIN cel_zones_geo AS l '.
1106
						"		ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) ".
1102
						"		ON (l.nom = co.zone_geo AND l.id_zone_geo = co.ce_zone_geo) ".
1107
						"WHERE transmission = '1' ".
1103
						"WHERE co.transmission = '1' ".
1108
						$this->construireWhereCoordonnees().
1104
						$this->construireWhereCoordonnees().
1109
						$this->construireWhereUtilisateur().
1105
						$this->construireWhereUtilisateur().
1110
						$this->construireWhereNumTaxon().
1106
						$this->construireWhereNumTaxon().
1111
						$this->construireWhereNomTaxon().
1107
						$this->construireWhereNomTaxon().
1112
						$this->construireWhereReferentiel().
1108
						$this->construireWhereReferentiel().
1113
						$this->construireWhereProjet().
1109
						$this->construireWhereProjet().
1114
						(!$this->etreNull($tag_sql) ? "AND ($tag_sql) " : '').
1110
						(!$this->etreNull($tag_sql) ? "AND ($tag_sql) " : '').
1115
						'ORDER BY utilisateur ASC, ci.ordre ASC';
1111
						'ORDER BY utilisateur ASC, ci.ordre ASC';
1116
			//$this->debug[] = $requete;
1112
			//$this->debug[] = $requete;
1117
			//die($requete);
1113
			//die($requete);
1118
			$elements_tag = Cel::db()->requeter($requete);
1114
			$elements_tag = Cel::db()->requeter($requete);
1119
 
1115
 
1120
			$requete_tag = array();
1116
			$requete_tag = array();
1121
			if ($elements_tag != false && count($elements_tag) > 0) {
1117
			if ($elements_tag != false && count($elements_tag) > 0) {
1122
 
1118
 
1123
				$filtres = array();
1119
				$filtres = array();
1124
				foreach ($elements_tag as $occurence) {
1120
				foreach ($elements_tag as $occurence) {
1125
					$utilisateur = $occurence['utilisateur'];
1121
					$utilisateur = $occurence['utilisateur'];
1126
					$id_obs = $occurence['id_obs'];
1122
					$id_obs = $occurence['id_obs'];
1127
					if (!array_key_exists($utilisateur, $filtres)) {
1123
					if (!array_key_exists($utilisateur, $filtres)) {
1128
						$filtres[$utilisateur] = array();
1124
						$filtres[$utilisateur] = array();
1129
					}
1125
					}
1130
					if (!array_key_exists($id_obs, $filtres[$utilisateur])) {
1126
					if (!array_key_exists($id_obs, $filtres[$utilisateur])) {
1131
						$filtres[$utilisateur][$id_obs] = $id_obs;
1127
						$filtres[$utilisateur][$id_obs] = $id_obs;
1132
					}
1128
					}
1133
				}
1129
				}
1134
 
1130
 
1135
				// Pré-construction du where de la requête
1131
				// Pré-construction du where de la requête
1136
				$tpl_where = "(id_observation IN (%s))";
1132
				$tpl_where = "(id_observation IN (%s))";
1137
				foreach ($filtres as $utilisateur => $id_obs) {
1133
				foreach ($filtres as $utilisateur => $id_obs) {
1138
					$requete_tag[] = sprintf($tpl_where, implode(',', $id_obs));
1134
					$requete_tag[] = sprintf($tpl_where, implode(',', $id_obs));
1139
				}
1135
				}
1140
 
1136
 
1141
			} else {
1137
			} else {
1142
				$this->messages[] = "Aucune observation ne possède d'images avec ce mot-clé.";
1138
				$this->messages[] = "Aucune observation ne possède d'images avec ce mot-clé.";
1143
			}
1139
			}
1144
			if (count($requete_tag) > 0) {
1140
			if (count($requete_tag) > 0) {
1145
				$sql = implode(" \nOR ", $requete_tag);
1141
				$sql = implode(" \nOR ", $requete_tag);
1146
			}
1142
			}
1147
		}
1143
		}
1148
		return $sql;
1144
		return $sql;
1149
	}
1145
	}
1150
 
1146
 
1151
	/**
1147
	/**
1152
	 * Traitement de $tag pour construction du filtre dans la requête
1148
	 * Traitement de $tag pour construction du filtre dans la requête
1153
	 */
1149
	 */
1154
	private function getSqlWhereMotsCles($tag) {
1150
	private function getSqlWhereMotsCles($tag) {
1155
		$sql = null;
1151
		$sql = null;
1156
		$mots_cles = $this->decomposerParametreTag($tag);
1152
		$mots_cles = $this->decomposerParametreTag($tag);
1157
		$requete_projet = $this->getSqlWhereMotsClesImages($mots_cles);
1153
		$requete_projet = $this->getSqlWhereMotsClesImages($mots_cles);
1158
		$sql = $requete_projet;
1154
		$sql = $requete_projet;
1159
		//$this->debug[] = $sql;
1155
		//$this->debug[] = $sql;
1160
		return $sql;
1156
		return $sql;
1161
	}
1157
	}
1162
 
1158
 
1163
	/**
1159
	/**
1164
	 * Traitement de $tag pour construction du filtre dans la requête
1160
	 * Traitement de $tag pour construction du filtre dans la requête
1165
	 */
1161
	 */
1166
	private function getSqlWhereMotsClesImages($mots_cles_encodes) {
1162
	private function getSqlWhereMotsClesImages($mots_cles_encodes) {
1167
		$where_mots_cles_images = array();
1163
		$where_mots_cles_images = array();
1168
		foreach ($mots_cles_encodes['motsClesEncodesProteges'] as $mot_cle_encode) {
1164
		foreach ($mots_cles_encodes['motsClesEncodesProteges'] as $mot_cle_encode) {
1169
			$where_mots_cles_images[] = "ci.mots_cles_texte LIKE $mot_cle_encode";
1165
			$where_mots_cles_images[] = "ci.mots_cles_texte LIKE $mot_cle_encode";
1170
		}
1166
		}
1171
		$where_mots_cles_images = implode(' '.$mots_cles_encodes['type'].' ', $where_mots_cles_images);
1167
		$where_mots_cles_images = implode(' '.$mots_cles_encodes['type'].' ', $where_mots_cles_images);
1172
		return $where_mots_cles_images;
1168
		return $where_mots_cles_images;
1173
	}
1169
	}
1174
 
1170
 
1175
	private function decomposerParametreTag($tags) {
1171
	private function decomposerParametreTag($tags) {
1176
 
1172
 
1177
		$mots_cles = array('type' => null, 'motsCles' => null, 'motsClesEncodesProteges' => null);
1173
		$mots_cles = array('type' => null, 'motsCles' => null, 'motsClesEncodesProteges' => null);
1178
		if (preg_match('/.+OU.+/', $tags)) {
1174
		if (preg_match('/.+OU.+/', $tags)) {
1179
			$mots_cles['type'] = 'OR';
1175
			$mots_cles['type'] = 'OR';
1180
			$mots_cles['motsCles'] = explode('OU', $tags);
1176
			$mots_cles['motsCles'] = explode('OU', $tags);
1181
		} else if (preg_match('/.+ET.+/', $tags)) {
1177
		} else if (preg_match('/.+ET.+/', $tags)) {
1182
			$mots_cles['type'] = 'AND';
1178
			$mots_cles['type'] = 'AND';
1183
			$mots_cles['motsCles'] = explode('ET', $tags);
1179
			$mots_cles['motsCles'] = explode('ET', $tags);
1184
		} else {
1180
		} else {
1185
			$mots_cles['motsCles'][] = $tags;
1181
			$mots_cles['motsCles'][] = $tags;
1186
		}
1182
		}
1187
 
1183
 
1188
		foreach ($mots_cles['motsCles'] as $mot) {
1184
		foreach ($mots_cles['motsCles'] as $mot) {
1189
			$mots_cles['motsClesEncodesProteges'][] = Cel::db()->quote('%'.$mot.'%');
1185
			$mots_cles['motsClesEncodesProteges'][] = Cel::db()->quote('%'.$mot.'%');
1190
		}
1186
		}
1191
		$this->debug[] = $mots_cles;
1187
		$this->debug[] = $mots_cles;
1192
		return $mots_cles;
1188
		return $mots_cles;
1193
	}
1189
	}
1194
 
1190
 
1195
	private function decomposerLatLng($coord) {
1191
	private function decomposerLatLng($coord) {
1196
		$lat_lng = array();
1192
		$lat_lng = array();
1197
		if (isset($coord)) {
1193
		if (isset($coord)) {
1198
			list($lat, $lng) = explode('|', $coord);
1194
			list($lat, $lng) = explode('|', $coord);
1199
			$lat_lng = array('lat' => $lat, 'lng' => $lng);
1195
			$lat_lng = array('lat' => $lat, 'lng' => $lng);
1200
		}
1196
		}
1201
		return $lat_lng;
1197
		return $lat_lng;
1202
	}
1198
	}
1203
 
1199
 
1204
	private function decomposerParametreStation() {
1200
	private function decomposerParametreStation() {
1205
		$station_infos = array();
1201
		$station_infos = array();
1206
		if (isset($this->parametres['station'])) {
1202
		if (isset($this->parametres['station'])) {
1207
			$station = $this->parametres['station'];
1203
			$station = $this->parametres['station'];
1208
			$this->debug[] = $station;
1204
			$this->debug[] = $station;
1209
			@list($type, $coord) = explode(':', $station);
1205
			@list($type, $coord) = explode(':', $station);
1210
			@list($lat, $lng) = explode('|', $coord);
1206
			@list($lat, $lng) = explode('|', $coord);
1211
 
1207
 
1212
			$station_infos = array('type' => $type, 'lat' => $lat, 'lng' => $lng);
1208
			$station_infos = array('type' => $type, 'lat' => $lat, 'lng' => $lng);
1213
		}
1209
		}
1214
		return $station_infos;
1210
		return $station_infos;
1215
	}
1211
	}
1216
 
1212
 
1217
	private function decomposerParametreDate() {
1213
	private function decomposerParametreDate() {
1218
		$date_infos = array(null,null);
1214
		$date_infos = array(null,null);
1219
		if (isset($this->parametres['date'])) {
1215
		if (isset($this->parametres['date'])) {
1220
			$date = $this->parametres['date'];
1216
			$date = $this->parametres['date'];
1221
			if (strpos($date, ':')) {
1217
			if (strpos($date, ':')) {
1222
				list($type, $date) = explode(':', $date);
1218
				list($type, $date) = explode(':', $date);
1223
			} else {
1219
			} else {
1224
				$type = 'observation';
1220
				$type = 'observation';
1225
			}
1221
			}
1226
 
1222
 
1227
			$date = str_replace('/', '-', $date);
1223
			$date = str_replace('/', '-', $date);
1228
			if (preg_match('/(^[0-9]{2})-([0-9]{2})-([0-9]{4}$)/', $date, $matches)) {
1224
			if (preg_match('/(^[0-9]{2})-([0-9]{2})-([0-9]{4}$)/', $date, $matches)) {
1229
				$date = $matches[3].'-'.$matches[2].'-'.$matches[1];
1225
				$date = $matches[3].'-'.$matches[2].'-'.$matches[1];
1230
			}
1226
			}
1231
 
1227
 
1232
			$date_infos = array($type, $date);
1228
			$date_infos = array($type, $date);
1233
		}
1229
		}
1234
		return $date_infos;
1230
		return $date_infos;
1235
	}
1231
	}
1236
 
1232
 
1237
	private function decomposerParametreTaxon() {
1233
	private function decomposerParametreTaxon() {
1238
		$nom_infos = array(null,null);
1234
		$nom_infos = array(null,null);
1239
		if (isset($this->parametres['taxon'])) {
1235
		if (isset($this->parametres['taxon'])) {
1240
			$taxon = $this->parametres['taxon'];
1236
			$taxon = $this->parametres['taxon'];
1241
			if (strpos($taxon, ':')) {
1237
			if (strpos($taxon, ':')) {
1242
				$nom_infos = explode(':', $taxon);
1238
				$nom_infos = explode(':', $taxon);
1243
			} else {
1239
			} else {
1244
				$nom_infos = array('retenu', $taxon);
1240
				$nom_infos = array('retenu', $taxon);
1245
			}
1241
			}
1246
		}
1242
		}
1247
		return $nom_infos;
1243
		return $nom_infos;
1248
	}
1244
	}
1249
 
1245
 
1250
	private function decomposerParametreCommentaire() {
1246
	private function decomposerParametreCommentaire() {
1251
		$commentaire_infos = array(null,null);
1247
		$commentaire_infos = array(null,null);
1252
		if (isset($this->parametres['commentaire'])) {
1248
		if (isset($this->parametres['commentaire'])) {
1253
			$commentaire = $this->parametres['commentaire'];
1249
			$commentaire = $this->parametres['commentaire'];
1254
			if (strpos($commentaire, ':')) {
1250
			if (strpos($commentaire, ':')) {
1255
				$commentaire_infos = explode(':', $commentaire);
1251
				$commentaire_infos = explode(':', $commentaire);
1256
			} else {
1252
			} else {
1257
				$commentaire_infos = array('observation', $commentaire);
1253
				$commentaire_infos = array('observation', $commentaire);
1258
			}
1254
			}
1259
		}
1255
		}
1260
		return $commentaire_infos;
1256
		return $commentaire_infos;
1261
	}
1257
	}
1262
}
1258
}
1263
?>
1259
?>