Subversion Repositories eFlore/Applications.cel

Rev

Rev 3633 | Rev 3774 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

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