Subversion Repositories eFlore/Applications.cel

Rev

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

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