Subversion Repositories eFlore/Applications.cel

Rev

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

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