Subversion Repositories eFlore/Applications.cel

Rev

Rev 3750 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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