Subversion Repositories eFlore/Applications.cel

Rev

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

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