Subversion Repositories eFlore/Applications.cel

Rev

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

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