1375 |
raphael |
1 |
<?php
|
|
|
2 |
/**
|
|
|
3 |
* Le web service observations récupère toutes les observations et, pour chacune d'elle, les
|
|
|
4 |
* images qui lui sont associées.
|
|
|
5 |
* Basée sur la classe antérieure dans ListeObservations.php de
|
|
|
6 |
* Grégoire Duché et Aurélien Peronnet
|
|
|
7 |
* (formaterVote, formaterDeterminations, chargerNombreCommentaire, chargerVotes, chargerDeterminations)
|
|
|
8 |
*
|
|
|
9 |
* @category php 5.2
|
|
|
10 |
* @package del
|
|
|
11 |
* @author Raphaël Droz <raphael@tela-botanica.org>
|
|
|
12 |
* @copyright Copyright (c) 2013 Tela Botanica (accueil@tela-botanica.org)
|
|
|
13 |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
|
|
|
14 |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
|
|
|
15 |
* @see http://www.tela-botanica.org/wikini/eflore/wakka.php?wiki=ApiIdentiplante01Observations
|
|
|
16 |
*
|
|
|
17 |
* TODO:
|
|
|
18 |
* PDO::prepare()
|
|
|
19 |
* Sphinx pour auteur, genre, ns, commune, tag et masque-général
|
|
|
20 |
*/
|
|
|
21 |
|
|
|
22 |
define('_LISTE_OBS_MAX_RESULT_LIMIT', 1000);
|
|
|
23 |
define('_LISTE_OBS_MAX_ID_OBS', 10e7);
|
|
|
24 |
// SELECT MAX(num_taxonomique) FROM bdtfx_v2_00;
|
|
|
25 |
define('_LISTE_OBS_MAX_BDTFX_NT', 44378 + 1000);
|
|
|
26 |
// SELECT MAX(num_nom) FROM bdtfx_v2_00;
|
|
|
27 |
define('_LISTE_OBS_MAX_BDTFX_NN', 103386 + 10000);
|
|
|
28 |
|
1488 |
raphael |
29 |
require_once(dirname(__FILE__) . '/../images/ListeImages2.php');
|
|
|
30 |
/*
|
|
|
31 |
restore_error_handler();
|
|
|
32 |
restore_exception_handler();
|
|
|
33 |
error_reporting(E_ALL);
|
|
|
34 |
*/
|
1375 |
raphael |
35 |
|
1451 |
raphael |
36 |
class ListeObservations {
|
1375 |
raphael |
37 |
|
|
|
38 |
private $conteneur;
|
|
|
39 |
private $gestionBdd;
|
|
|
40 |
private $bdd;
|
|
|
41 |
private $parametres = array();
|
|
|
42 |
private $ressources = array();
|
|
|
43 |
|
|
|
44 |
static $tris_possibles = array('date_observation');
|
|
|
45 |
// paramètres autorisés
|
|
|
46 |
static $parametres_autorises = array('masque', 'masque.famille', 'masque.nn', 'masque.referentiel', // taxon
|
1488 |
raphael |
47 |
'masque.genre', 'masque.espece', 'masque.ns', // nom_sel
|
|
|
48 |
'masque.commune', 'masque.departement', 'masque.id_zone_geo', // loc
|
|
|
49 |
'masque.auteur', 'masque.date', 'masque.tag', 'masque.type', // autres
|
|
|
50 |
// tri, offset
|
|
|
51 |
'navigation.depart', 'navigation.limite',
|
|
|
52 |
'tri', 'ordre', // TODO: 'total=[yes]', 'fields=[x,y,...]'
|
|
|
53 |
// TODO: masque.annee, masque.insee (!= departement)
|
1375 |
raphael |
54 |
);
|
|
|
55 |
|
|
|
56 |
static $default_params = array('navigation.depart' => 0, 'navigation.limite' => 10,
|
1488 |
raphael |
57 |
'tri' => 'date_transmission', 'ordre' => 'desc');
|
1375 |
raphael |
58 |
|
|
|
59 |
static $sql_fields_liaisons = array(
|
|
|
60 |
'dob' => array('id_observation', 'nom_sel AS `determination.ns`', 'nt AS `determination.nt`',
|
1488 |
raphael |
61 |
'nom_sel_nn AS `determination.nn`', 'famille AS `determination.famille`',
|
|
|
62 |
'nom_referentiel AS `determination.referentiel`',
|
|
|
63 |
'ce_zone_geo AS id_zone_geo', 'zone_geo', 'lieudit',
|
|
|
64 |
'station', 'milieu', 'date_observation', 'mots_cles_texte', 'date_transmission',
|
|
|
65 |
'ce_utilisateur AS `auteur.id`', 'prenom_utilisateur AS `auteur.prenom`',
|
|
|
66 |
'nom_utilisateur AS `auteur.nom`', 'courriel_utilisateur AS observateur',
|
|
|
67 |
'commentaire'),
|
1386 |
raphael |
68 |
'di' => array('id_image', 'date_prise_de_vue AS `date`', 'hauteur',/* 'largeur','nom_original' // apparemment inutilisés */),
|
1375 |
raphael |
69 |
'du' => array('prenom', 'nom', 'courriel'),
|
|
|
70 |
'dc' => array('commentaire')
|
|
|
71 |
);
|
|
|
72 |
|
|
|
73 |
|
|
|
74 |
public function __construct(Conteneur $conteneur = null) {
|
|
|
75 |
$this->conteneur = $conteneur == null ? new Conteneur() : $conteneur;
|
|
|
76 |
$this->conteneur->chargerConfiguration('config_departements_bruts.ini');
|
|
|
77 |
$this->conteneur->chargerConfiguration('config_observations.ini');
|
|
|
78 |
$this->conteneur->chargerConfiguration('config_mapping_votes.ini');
|
|
|
79 |
$this->conteneur->chargerConfiguration('config_mapping_commentaires.ini');
|
|
|
80 |
$this->navigation = $conteneur->getNavigation();
|
|
|
81 |
$this->masque = $conteneur->getMasque();
|
|
|
82 |
$this->gestionBdd = $conteneur->getGestionBdd();
|
|
|
83 |
$this->bdd = $this->gestionBdd->getBdd();
|
|
|
84 |
}
|
|
|
85 |
|
1383 |
raphael |
86 |
static function reformateObservation($obs, $url_pattern = '') {
|
1375 |
raphael |
87 |
$obs = array_map('array_filter', $obs);
|
|
|
88 |
$obs_merged = array();
|
|
|
89 |
foreach($obs as $o) {
|
|
|
90 |
$id = $o['id_observation'];
|
1386 |
raphael |
91 |
|
|
|
92 |
// car auteur.id peut être un email, un hash, ou un annuaire_tela.U_ID
|
|
|
93 |
// mais dans les deux premiers cas SELECT courriel AS observateur fait déjà l'affaire
|
|
|
94 |
if(!is_numeric($o['auteur.id'])) $o['auteur.id'] = "0";
|
|
|
95 |
if(!isset($o['auteur.nom'])) $o['auteur.nom'] = '[inconnu]';
|
|
|
96 |
|
1375 |
raphael |
97 |
$image = array_intersect_key($o, array_flip(array('id_image', 'date', 'hauteur' , 'largeur', 'nom_original')));
|
1383 |
raphael |
98 |
$image['binaire.href'] = sprintf($url_pattern, $image['id_image']);
|
1375 |
raphael |
99 |
unset($o['id_image'], $o['date'], $o['hauteur'], $o['largeur'], $o['nom_original']);
|
|
|
100 |
if(!isset($obs_merged['"' . $id . '"'])) $obs_merged['"' . $id . '"'] = $o;
|
|
|
101 |
$obs_merged['"' . $id . '"']['images'][] = $image;
|
|
|
102 |
}
|
|
|
103 |
return $obs_merged;
|
|
|
104 |
}
|
|
|
105 |
|
1386 |
raphael |
106 |
// utilisée uniquement par Observation.php
|
1383 |
raphael |
107 |
static function reformateObservationSimpleIndex($obs, $url_pattern = '') {
|
1386 |
raphael |
108 |
// XXX: cf Observation.php::consulter(), nous pourriouns ici
|
|
|
109 |
// conserver les valeurs vides (pour les phptests notamment, ou non)
|
1383 |
raphael |
110 |
$obs = array_map('array_filter', $obs);
|
|
|
111 |
$obs_merged = array();
|
|
|
112 |
foreach($obs as $o) {
|
|
|
113 |
$id = $o['id_observation'];
|
|
|
114 |
$image = array_intersect_key($o, array_flip(array('id_image', 'date', 'hauteur' , 'largeur', 'nom_original')));
|
|
|
115 |
$image['binaire.href'] = sprintf($url_pattern, $image['id_image']);
|
|
|
116 |
unset($o['id_image'], $o['date'], $o['hauteur'], $o['largeur'], $o['nom_original']);
|
|
|
117 |
if(!isset($obs_merged[$id])) $obs_merged[$id] = $o;
|
|
|
118 |
$obs_merged[$id]['images'][$image['id_image']] = $image;
|
|
|
119 |
}
|
|
|
120 |
return $obs_merged;
|
|
|
121 |
}
|
|
|
122 |
|
1396 |
raphael |
123 |
|
|
|
124 |
// utilisée uniquement par ListeImages.php
|
1398 |
raphael |
125 |
static function reformateImagesDoubleIndex($obs, $url_pattern = '', $image_format = 'XL') {
|
1396 |
raphael |
126 |
// XXX: cf Observation.php::consulter(), nous pourriouns ici
|
|
|
127 |
// conserver les valeurs vides (pour les phptests notamment, ou non)
|
1398 |
raphael |
128 |
// $obs = array_map('array_filter', $obs);
|
|
|
129 |
$obs_merged = $obs_keyed_by_id_image = array();
|
1396 |
raphael |
130 |
foreach($obs as $o) {
|
1398 |
raphael |
131 |
// ceci nous complique la tâche pour le reste du processing...
|
|
|
132 |
$id = $o['jsonindex'];
|
|
|
133 |
// ainsi nous utilisons deux tableaux: le final, indexé par couple d'id(image-obs)
|
|
|
134 |
// et celui indexé par simple id_image qui est fort utile pour mapVotesToImages()
|
|
|
135 |
// mais tout deux partage leur référence à "protocole"
|
1396 |
raphael |
136 |
$image = array(
|
|
|
137 |
'id_image' => $o['id_image'],
|
1398 |
raphael |
138 |
'binaire.href' => sprintf($url_pattern, $o['id_image'], $image_format),
|
|
|
139 |
'mots_cles_texte' => @$o['i_mots_cles_texte'], // @, peut avoir été filtré par array_map() ci-dessus
|
1396 |
raphael |
140 |
);
|
|
|
141 |
unset($o['id_image'], $o['i_mots_cles_texte'], $o['jsonindex']);
|
|
|
142 |
if(!isset($obs_merged[$id])) $obs_merged[$id] = $image;
|
|
|
143 |
$obs_merged[$id]['observation'] = $o;
|
1398 |
raphael |
144 |
$obs_merged[$id]['protocoles_votes'] = array();
|
|
|
145 |
|
|
|
146 |
$obs_keyed_by_id_image[$image['id_image']]['protocoles_votes'] = &$obs_merged[$id]['protocoles_votes'];
|
1396 |
raphael |
147 |
}
|
1398 |
raphael |
148 |
|
|
|
149 |
return array($obs_merged,$obs_keyed_by_id_image);
|
1396 |
raphael |
150 |
}
|
|
|
151 |
|
1375 |
raphael |
152 |
/**
|
|
|
153 |
* Méthode principale de la classe.
|
|
|
154 |
* Lance la récupération des images dans la base et les place dans un objet ResultatService
|
|
|
155 |
* pour l'afficher.
|
|
|
156 |
* @param array $ressources les ressources situées après l'url de base (ex : http://url/ressource1/ressource2)
|
|
|
157 |
* @param array $parametres les paramètres situés après le ? dans l'url
|
|
|
158 |
**/
|
|
|
159 |
public function consulter($ressources, $parametres) {
|
1416 |
raphael |
160 |
// SELECT, à terme, pourrait affecter getInfos(), mais en aucune manière getIdObs()
|
1375 |
raphael |
161 |
$req = array('select' => array(), 'join' => array(), 'where' => array(), 'groupby' => array(), 'having' => array());
|
1416 |
raphael |
162 |
|
1380 |
raphael |
163 |
// toujours nécessaire puisque nous tapons sur v_del_image qui INNER JOIN cel_images, or nous voulons certes
|
1375 |
raphael |
164 |
// toutes les images, mais nous voulons $limite observations uniques.
|
1416 |
raphael |
165 |
$req['groupby'][] = 'vdi.id_observation';
|
1375 |
raphael |
166 |
|
|
|
167 |
$db = $this->bdd;
|
|
|
168 |
|
|
|
169 |
// filtrage de l'INPUT
|
1389 |
raphael |
170 |
$params = self::requestFilterParams($parametres, self::$parametres_autorises, $this->conteneur);
|
1488 |
raphael |
171 |
|
|
|
172 |
$params['masque.tag'] = ListeImages2::buildTagsAST(@$parametres['masque.tag'], 'OR', ',');
|
|
|
173 |
|
1421 |
raphael |
174 |
// ... et paramètres par défaut
|
|
|
175 |
$params = array_merge(self::$default_params, $params);
|
|
|
176 |
|
1375 |
raphael |
177 |
// création des contraintes (masques)
|
|
|
178 |
self::sqlAddConstraint($params, $db, $req, $this->conteneur);
|
1416 |
raphael |
179 |
self::sqlAddMasqueConstraint($params, $db, $req, $this->conteneur);
|
1375 |
raphael |
180 |
|
|
|
181 |
// 1) grunt-work: *la* requête de récupération des id valides (+ SQL_CALC_FOUND_ROWS)
|
|
|
182 |
$idobs_tab = self::getIdObs($params, $req, $db);
|
|
|
183 |
// idobs est une liste (toujours ordonnée) des id d'observations recherchées
|
|
|
184 |
$idobs = array_values(array_map(create_function('$a', 'return $a["id_observation"];'), $idobs_tab));
|
|
|
185 |
|
1379 |
raphael |
186 |
if($idobs) {
|
|
|
187 |
$total = $db->recuperer('SELECT FOUND_ROWS() AS c'); $total = intval($total['c']);
|
1375 |
raphael |
188 |
|
1379 |
raphael |
189 |
// 2) récupération des données nécessaires pour ces observations (obs + images)
|
1416 |
raphael |
190 |
// ici les champs récupérés sont issus de self::$sql_fields_liaisons mais sans préfixes
|
|
|
191 |
// car tout provient de v_del_image
|
1379 |
raphael |
192 |
$obs_unfmt = self::getInfos($idobs, $db);
|
1375 |
raphael |
193 |
|
1379 |
raphael |
194 |
// 3) suppression, merge des données en tableau assez représentatif du futur JSON en output
|
1383 |
raphael |
195 |
$observations = self::reformateObservation($obs_unfmt, $this->conteneur->getParametre('url_images'));
|
1375 |
raphael |
196 |
|
1379 |
raphael |
197 |
// 4) récupération des données nécessaires pour ces observations (commentaires + votes)
|
|
|
198 |
// modifie $observations
|
|
|
199 |
$this->configurer();
|
|
|
200 |
$this->chargerDeterminations($observations);
|
1375 |
raphael |
201 |
|
1379 |
raphael |
202 |
// 5) restauration de l'ordre souhaité initialement
|
|
|
203 |
$observations = self::sortArrayByArray($observations, $idobs);
|
|
|
204 |
} else {
|
|
|
205 |
$observations = array();
|
|
|
206 |
$total = 0;
|
|
|
207 |
}
|
|
|
208 |
|
1375 |
raphael |
209 |
// 6) JSON output
|
|
|
210 |
$resultat = new ResultatService();
|
1389 |
raphael |
211 |
$resultat->corps = array('entete' => self::makeJSONHeader($total, $params, Config::get('url_service')),
|
1488 |
raphael |
212 |
'resultats' => $observations);
|
1375 |
raphael |
213 |
|
|
|
214 |
return $resultat;
|
|
|
215 |
}
|
|
|
216 |
|
|
|
217 |
static function sortArrayByArray($array, $orderArray) {
|
|
|
218 |
$ordered = array();
|
|
|
219 |
foreach($orderArray as $key) {
|
|
|
220 |
if(array_key_exists('"' . $key . '"', $array)) {
|
|
|
221 |
$ordered['"' . $key . '"'] = $array['"' . $key . '"'];
|
|
|
222 |
unset($array['"' . $key . '"']);
|
|
|
223 |
}
|
|
|
224 |
}
|
|
|
225 |
return $ordered + $array;
|
|
|
226 |
}
|
|
|
227 |
|
|
|
228 |
// SQL helpers
|
|
|
229 |
/*
|
|
|
230 |
* Retourne une liste ordonnée d'id d'observation correspondant aux critères
|
|
|
231 |
* passés dans p et aux clauses where/join présentes dans le tableau $req
|
|
|
232 |
*
|
|
|
233 |
* @param p: $params (filtrés sauf escape-string)
|
|
|
234 |
* @param req: le tableau représentant les composants de la requete SQL
|
|
|
235 |
* @param db: l'instance de db
|
|
|
236 |
*/
|
|
|
237 |
static function getIdObs($p, $req, $db) {
|
|
|
238 |
$req_s = sprintf('SELECT SQL_CALC_FOUND_ROWS id_observation' .
|
1488 |
raphael |
239 |
' FROM v_del_image vdi'.
|
|
|
240 |
' %s' . // LEFT JOIN if any
|
|
|
241 |
' WHERE %s'. // where-clause ou TRUE
|
|
|
242 |
' %s'. // group-by
|
|
|
243 |
' %s'. // having (si commentaires)
|
|
|
244 |
' ORDER BY %s %s %s'.
|
|
|
245 |
' LIMIT %d, %d -- %s',
|
1375 |
raphael |
246 |
|
1488 |
raphael |
247 |
$req['join'] ? implode(' ', $req['join']) : '',
|
|
|
248 |
$req['where'] ? implode(' AND ', $req['where']) : 'TRUE',
|
1375 |
raphael |
249 |
|
1488 |
raphael |
250 |
$req['groupby'] ? ('GROUP BY ' . implode(', ', array_unique($req['groupby']))) : '',
|
|
|
251 |
$req['having'] ? ('HAVING ' . implode(' AND ', $req['having'])) : '',
|
1375 |
raphael |
252 |
|
1488 |
raphael |
253 |
$p['tri'], strtoupper($p['ordre']),
|
|
|
254 |
// date_transmission peut-être NULL et nous voulons de la consistence
|
|
|
255 |
// (sauf après r1860 de Cel)
|
|
|
256 |
$p['tri'] == 'date_transmission' ? ', id_observation' : '',
|
1375 |
raphael |
257 |
|
1488 |
raphael |
258 |
$p['navigation.depart'], $p['navigation.limite'], __FILE__ . ':' . __LINE__);
|
1379 |
raphael |
259 |
|
1375 |
raphael |
260 |
$res = $db->recupererTous($req_s);
|
|
|
261 |
$err = mysql_error();
|
|
|
262 |
if(!$res && $err) {
|
|
|
263 |
// http_response_code(400);
|
|
|
264 |
// if(defined('DEBUG') && DEBUG) header("X-Debug: $req_s");
|
|
|
265 |
throw new Exception('not found', 400);
|
|
|
266 |
}
|
|
|
267 |
// ordre préservé, à partir d'ici c'est important.
|
|
|
268 |
return $res;
|
|
|
269 |
}
|
|
|
270 |
|
|
|
271 |
/*
|
|
|
272 |
Champs récupérés:
|
|
|
273 |
Pour del_images, la vue retourne déjà ce que nous recherchons de cel_obs et cel_images
|
1416 |
raphael |
274 |
(cel_obs.* et cel_[obs_]images.{id_observation, id_image, date_prise_de_vue AS date, hauteur, largeur})
|
1375 |
raphael |
275 |
Pour del_commentaires: nous voulons *
|
1416 |
raphael |
276 |
Reste ensuite à formatter.
|
|
|
277 |
Note: le préfixe de table utilisé ici (vdi) n'impacte *aucune* autre partie du code car rien
|
|
|
278 |
n'en dépend pour l'heure. (inutilisation de $req['select'])
|
1375 |
raphael |
279 |
*/
|
|
|
280 |
static function getInfos($idobs, $db) {
|
|
|
281 |
/*$select_fields = implode(',', array_merge(
|
1488 |
raphael |
282 |
array_map(create_function('$a', 'return "vdi.".$a;'), self::$sql_fields_liaisons['dob']),
|
|
|
283 |
array_map(create_function('$a', 'return "vdi.".$a;'), self::$sql_fields_liaisons['di']),
|
|
|
284 |
array_map(create_function('$a', 'return "du.".$a;'), self::$sql_fields_liaisons['du'])));*/
|
1375 |
raphael |
285 |
$select_fields = array_merge(self::$sql_fields_liaisons['dob'],
|
1488 |
raphael |
286 |
self::$sql_fields_liaisons['di']);
|
1416 |
raphael |
287 |
$req_s = sprintf('SELECT %s FROM v_del_image vdi'.
|
1488 |
raphael |
288 |
// ' LEFT JOIN del_commentaire AS dc ON di.id_observation = dc.ce_observation AND dc.nom_sel IS NOT NULL'.
|
|
|
289 |
' WHERE id_observation IN (%s)',
|
|
|
290 |
implode(',', $select_fields),
|
|
|
291 |
implode(',', $idobs));
|
1375 |
raphael |
292 |
return $db->recupererTous($req_s);
|
|
|
293 |
}
|
|
|
294 |
|
|
|
295 |
|
|
|
296 |
/**
|
|
|
297 |
* - Rempli le tableau des contraintes "where" et "join" nécessaire
|
1416 |
raphael |
298 |
* à la *recherche* des observations demandées ($req) utilisées par self::getIdObs()
|
|
|
299 |
*
|
1375 |
raphael |
300 |
* Attention, cela signifie que toutes les tables ne sont pas *forcément*
|
|
|
301 |
* join'ées, par exemple si aucune contrainte ne le nécessite.
|
|
|
302 |
* $req tel qu'il est rempli ici est utile pour récupéré la seule liste des
|
|
|
303 |
* id d'observation qui match.
|
|
|
304 |
* Pour la récupération effective de "toutes" les données correspondante, il faut
|
|
|
305 |
* réinitialiser $req["join"] afin d'y ajouter toutes les autres tables.
|
|
|
306 |
*
|
1416 |
raphael |
307 |
* Note: toujours rajouter les préfixes de table (vdi,du,doi ou di), en fonction de ce que défini
|
|
|
308 |
* les JOIN qui sont utilisés.
|
|
|
309 |
* le préfix de v_del_image est "vdi" (cf: "FROM" de self::getIdObs())
|
|
|
310 |
* le préfix de del_utilisateur sur id_utilisateur = vdi.ce_utilisateur est "du"
|
1375 |
raphael |
311 |
*
|
|
|
312 |
* @param $p les paramètres (notamment de masque) passés par l'URL et déjà traités/filtrés (sauf quotes)
|
1416 |
raphael |
313 |
* @param $req le tableau, passé par référence représentant les composants de la requête à bâtir
|
1375 |
raphael |
314 |
* @param $c conteneur, utilisé soit pour l'appel récursif à requestFilterParams() en cas de param "masque"
|
|
|
315 |
* soit pour la définition du type (qui utilise la variable nb_commentaires_discussion)
|
|
|
316 |
*/
|
|
|
317 |
static function sqlAddConstraint($p, $db, &$req, Conteneur $c = NULL) {
|
|
|
318 |
if(!empty($p['masque.auteur'])) {
|
|
|
319 |
// id du poster de l'obs
|
1416 |
raphael |
320 |
$req['join'][] = 'LEFT JOIN del_utilisateur AS du ON du.id_utilisateur = vdi.ce_utilisateur';
|
1375 |
raphael |
321 |
// id du poster de l'image... NON, c'est le même que le posteur de l'obs
|
|
|
322 |
// Cette jointure de table est ignoré ci-dessous pour les recherches d'auteurs
|
1416 |
raphael |
323 |
// $req['join'][] = 'LEFT JOIN del_utilisateur AS dui ON dui.id_utilisateur = vdi.i_ce_utilisateur';
|
1375 |
raphael |
324 |
|
|
|
325 |
if(is_numeric($p['masque.auteur'])) {
|
1416 |
raphael |
326 |
$req['where'][] = sprintf('(du.id_utilisateur = %1$d OR vdi.id_utilisateur = %1$d )', $p['masque.auteur']);
|
1375 |
raphael |
327 |
}
|
|
|
328 |
elseif(preg_match(';^.{5,}@[a-z0-9-.]{5,}$;i', $p['masque.auteur'])) {
|
1416 |
raphael |
329 |
$req['where'][] = sprintf('(du.courriel LIKE %1$s OR vdi.courriel LIKE %1$s )',
|
1488 |
raphael |
330 |
$db->proteger($p['masque.auteur'] . '%'));
|
1375 |
raphael |
331 |
}
|
|
|
332 |
else {
|
|
|
333 |
self::addAuteursConstraint($p['masque.auteur'], $db, $req['where']);
|
|
|
334 |
}
|
|
|
335 |
}
|
|
|
336 |
|
|
|
337 |
if(!empty($p['masque.date'])) {
|
1379 |
raphael |
338 |
if(is_integer($p['masque.date']) && $p['masque.date'] < 2030 && $p['masque.date'] > 1600) {
|
1416 |
raphael |
339 |
$req['where'][] = sprintf("YEAR(vdi.date_observation) = %d", $p['masque.date']);
|
1379 |
raphael |
340 |
}
|
|
|
341 |
else {
|
1416 |
raphael |
342 |
$req['where'][] = sprintf("DATE_FORMAT(vdi.date_observation, '%%Y-%%m-%%d') = %s",
|
1488 |
raphael |
343 |
$db->proteger(strftime('%Y-%m-%d', $p['masque.date'])));
|
1379 |
raphael |
344 |
}
|
1375 |
raphael |
345 |
}
|
|
|
346 |
|
|
|
347 |
// TODO: avoir des champs d'entrée distinct
|
|
|
348 |
if(!empty($p['masque.departement'])) {
|
1416 |
raphael |
349 |
$req['where'][] = sprintf("vdi.ce_zone_geo = %s", $db->proteger('INSEE-C:'.$p['masque.departement']));
|
1375 |
raphael |
350 |
}
|
|
|
351 |
if(!empty($p['masque.id_zone_geo'])) {
|
1416 |
raphael |
352 |
$req['where'][] = sprintf("vdi.ce_zone_geo = %s", $db->proteger($p['masque.id_zone_geo']));
|
1375 |
raphael |
353 |
}
|
|
|
354 |
if(!empty($p['masque.genre'])) {
|
1416 |
raphael |
355 |
$req['where'][] = 'vdi.nom_sel LIKE '.$db->proteger('%' . $p['masque.genre'].'% %');
|
1375 |
raphael |
356 |
}
|
|
|
357 |
if(!empty($p['masque.famille'])) {
|
1416 |
raphael |
358 |
$req['where'][] = 'vdi.famille = '.$db->proteger($p['masque.famille']);
|
1375 |
raphael |
359 |
}
|
|
|
360 |
if(!empty($p['masque.ns'])) {
|
1416 |
raphael |
361 |
$req['where'][] = 'vdi.nom_sel LIKE '.$db->proteger($p['masque.ns'].'%');
|
1375 |
raphael |
362 |
}
|
|
|
363 |
if(!empty($p['masque.nn'])) {
|
1416 |
raphael |
364 |
$req['where'][] = sprintf('vdi.nom_sel_nn = %1$d OR vdi.nom_ret_nn = %1$d', $p['masque.nn']);
|
1375 |
raphael |
365 |
}
|
|
|
366 |
if(!empty($p['masque.referentiel'])) {
|
1416 |
raphael |
367 |
$req['where'][] = sprintf('vdi.nom_referentiel LIKE %s', $db->proteger($p['masque.referentiel'].'%'));
|
1375 |
raphael |
368 |
}
|
|
|
369 |
if(!empty($p['masque.commune'])) {
|
1416 |
raphael |
370 |
$req['where'][] = 'vdi.zone_geo LIKE '.$db->proteger($p['masque.commune'].'%');
|
1375 |
raphael |
371 |
}
|
|
|
372 |
if(!empty($p['masque.tag'])) {
|
1488 |
raphael |
373 |
// TODO: remove LOWER() lorsqu'on est sur que les tags sont uniformés en minuscule
|
1380 |
raphael |
374 |
// i_mots_cles_texte provient de la VIEW v_del_image
|
1488 |
raphael |
375 |
if(isset($p['masque.tag']['AND'])) {
|
|
|
376 |
/* Lorsque nous interprêtons la chaîne provenant du masque général (cf: buildTagsAST($p['masque'], 'OR', ' ') dans sqlAddMasqueConstraint()),
|
|
|
377 |
nous sommes splittés par espace. Cependant, assurons que si une virgule à été saisie, nous n'aurons pas le motif
|
|
|
378 |
" AND CONCAT(mots_cles_texte, i_mots_cles_texte) REGEXP ',' " dans notre requête.
|
|
|
379 |
XXX: Au 12/11/2013, une recherche sur tag depuis le masque général implique un OU, donc le problème ne se pose pas ici */
|
|
|
380 |
$subwhere = array();
|
|
|
381 |
foreach($p['masque.tag']['AND'] as $tag) {
|
|
|
382 |
if(trim($tag) == ',') continue;
|
|
|
383 |
|
|
|
384 |
$subwhere[] = sprintf(
|
|
|
385 |
'LOWER(CONCAT(%s)) REGEXP %s',
|
|
|
386 |
self::sqlAddIfNullPourConcat(array('vdi.mots_cles_texte', 'vdi.i_mots_cles_texte')),
|
|
|
387 |
$db->proteger(strtolower($tag)));
|
|
|
388 |
}
|
|
|
389 |
$req['where'][] = '(' . implode(' AND ', $subwhere) . ')';
|
|
|
390 |
}
|
|
|
391 |
else {
|
|
|
392 |
$req['where'][] = sprintf(
|
|
|
393 |
'LOWER(CONCAT(%s)) REGEXP %s',
|
|
|
394 |
self::sqlAddIfNullPourConcat(array('vdi.mots_cles_texte', 'vdi.i_mots_cles_texte')),
|
|
|
395 |
$db->proteger(strtolower(implode('|', $p['masque.tag']['OR']))));
|
|
|
396 |
}
|
1375 |
raphael |
397 |
}
|
|
|
398 |
|
|
|
399 |
if(!empty($p['masque.type'])) {
|
|
|
400 |
self::addTypeConstraints($p['masque.type'], $db, $req, $c);
|
|
|
401 |
}
|
1416 |
raphael |
402 |
}
|
1375 |
raphael |
403 |
|
1416 |
raphael |
404 |
/* Le masque fait une recherche générique parmi de nombreux champs ci-dessus.
|
|
|
405 |
Nous initialisons donc ces paramètres (excepté masque biensur), et nous rappelons
|
|
|
406 |
récursivement. À la seule différence que nous n'utiliserons que $or_req['where']
|
|
|
407 |
imploded par des " OR ". */
|
|
|
408 |
static function sqlAddMasqueConstraint($p, $db, &$req, Conteneur $c = NULL) {
|
1375 |
raphael |
409 |
if(!empty($p['masque'])) {
|
|
|
410 |
$or_params = array('masque.auteur' => $p['masque'],
|
1488 |
raphael |
411 |
'masque.departement' => $p['masque'],
|
|
|
412 |
'masque.id_zone_geo' => $p['masque'],
|
|
|
413 |
'masque.tag' => $p['masque'],
|
|
|
414 |
'masque.ns' => $p['masque'],
|
|
|
415 |
'masque.famille' => $p['masque'],
|
|
|
416 |
'masque.date' => $p['masque'],
|
|
|
417 |
'masque.genre' => $p['masque'],
|
|
|
418 |
/* milieu: TODO ? */ );
|
1389 |
raphael |
419 |
$or_masque = self::requestFilterParams($or_params, array_keys($or_params), $c);
|
1488 |
raphael |
420 |
$or_masque['masque.tag'] = ListeImages2::buildTagsAST($p['masque'], 'OR', ' ');
|
1375 |
raphael |
421 |
// $or_req = array('select' => array(), 'join' => array(), 'where' => array(), 'groupby' => array(), 'having' => array());
|
|
|
422 |
$or_req = array('join' => array(), 'where' => array());
|
|
|
423 |
self::sqlAddConstraint($or_masque, $db, $or_req);
|
|
|
424 |
|
|
|
425 |
if($or_req['where']) {
|
|
|
426 |
$req['where'][] = '(' . implode(' OR ', $or_req['where']) . ')';
|
|
|
427 |
// utile au cas ou des jointures seraient rajoutées
|
|
|
428 |
$req['join'] = array_unique(array_merge($req['join'], $or_req['join']));
|
|
|
429 |
}
|
|
|
430 |
}
|
|
|
431 |
}
|
|
|
432 |
|
|
|
433 |
|
|
|
434 |
private function configurer() {
|
|
|
435 |
$this->mappingVotes = $this->conteneur->getParametre('mapping_votes');
|
|
|
436 |
$this->mappingCommentaire = $this->conteneur->getParametre('mapping_commentaire');
|
|
|
437 |
}
|
|
|
438 |
|
|
|
439 |
|
|
|
440 |
|
|
|
441 |
/* Lorsque l'on concatène des champs, un seul NULL prend le dessus,
|
1379 |
raphael |
442 |
Il faut donc utiliser la syntaxe IFNULL(%s, "").
|
1375 |
raphael |
443 |
(Cette fonction effectue aussi l'implode() "final" */
|
|
|
444 |
static function sqlAddIfNullPourConcat($tab) {
|
|
|
445 |
// XXX: PHP-5.3
|
1379 |
raphael |
446 |
return implode(',',array_map(create_function('$a', 'return "IFNULL($a, \"\")";'), $tab));
|
1375 |
raphael |
447 |
}
|
|
|
448 |
|
|
|
449 |
/*
|
|
|
450 |
Retourne une clausse where du style:
|
1416 |
raphael |
451 |
CONCAT(IF(du.prenom IS NULL, "", du.prenom), [...] vdi.i_nomutilisateur) REGEXP 'xxx'
|
1375 |
raphael |
452 |
Note; i_(nom|prenom_utilisateur), alias pour cel_images.(nom|prenom), n'est pas traité
|
|
|
453 |
car cette information est redondante dans cel_image et devrait être supprimée.
|
|
|
454 |
*/
|
|
|
455 |
static function addAuteursConstraint($val, $db, &$where) {
|
|
|
456 |
@list($a, $b) = explode(' ', $val, 2);
|
|
|
457 |
// un seul terme
|
|
|
458 |
$champs_n = array('du.prenom', // info user authentifié de l'obs depuis l'annuaire
|
1488 |
raphael |
459 |
'vdi.prenom_utilisateur', // info user anonyme de l'obs
|
|
|
460 |
/* 'vdi.i_prenom_utilisateur' */ ); // info user anonyme de l'image
|
1375 |
raphael |
461 |
$champs_p = array('du.nom', // idem pour le nom
|
1488 |
raphael |
462 |
'vdi.nom_utilisateur',
|
|
|
463 |
/* 'vdi.i_nom_utilisateur' */ );
|
1442 |
raphael |
464 |
|
|
|
465 |
/*
|
|
|
466 |
Note: pour l'heure, étant donnés:
|
|
|
467 |
- les CONVERT() de la VIEW del_utilisateur
|
|
|
468 |
- DEFAULT CHARSET=latin1 pour tela_prod_v4.annuaire_tela
|
|
|
469 |
- DEFAULT CHARSET=utf8 pour tb_cel.cel_obs
|
|
|
470 |
et l'âge du capitaine...
|
|
|
471 |
- REGEXP est case-sensitive, et collate les caractères accentués
|
|
|
472 |
- LIKE est case-insensitive, et collate les caractères accentués
|
1488 |
raphael |
473 |
*/
|
1375 |
raphael |
474 |
if(! $b) {
|
1442 |
raphael |
475 |
$where[] = sprintf('CONCAT(%s,%s) LIKE %s',
|
1488 |
raphael |
476 |
self::sqlAddIfNullPourConcat($champs_n),
|
|
|
477 |
self::sqlAddIfNullPourConcat($champs_p),
|
|
|
478 |
$db->proteger("%".$val."%"));
|
1375 |
raphael |
479 |
}
|
|
|
480 |
else {
|
1487 |
raphael |
481 |
$where[] = sprintf('(CONCAT(%1$s,%2$s) LIKE %3$s AND CONCAT(%1$s,%2$s) LIKE %4$s)',
|
1488 |
raphael |
482 |
self::sqlAddIfNullPourConcat($champs_n),
|
|
|
483 |
self::sqlAddIfNullPourConcat($champs_p),
|
|
|
484 |
$db->proteger("%" . $a . "%"), $db->proteger("%" . $b . "%"));
|
1375 |
raphael |
485 |
}
|
|
|
486 |
}
|
|
|
487 |
|
|
|
488 |
/*
|
|
|
489 |
* @param $req: la représentation de la requête MySQL complète, à amender.
|
|
|
490 |
*/
|
|
|
491 |
static function addTypeConstraints($val, $db, &$req, Conteneur $c) {
|
|
|
492 |
if(array_key_exists('adeterminer', $val)) {
|
|
|
493 |
//On récupère toutes les observations qui on le tag "aDeterminer" *ou* qui n'ont pas de nom d'espèce
|
|
|
494 |
$req['where'][] = '(' . implode(' OR ', array(
|
1416 |
raphael |
495 |
'vdi.certitude = "aDeterminer"',
|
|
|
496 |
'vdi.mots_cles_texte LIKE "%aDeterminer%"',
|
|
|
497 |
'vdi.nom_sel_nn IS NULL', // TODO: ensure pas d'entrée à 0
|
1375 |
raphael |
498 |
)) . ')';
|
|
|
499 |
}
|
|
|
500 |
if(array_key_exists('aconfirmer', $val)) {
|
|
|
501 |
//On récupère toutes les observations qui ne sont pas "aDeterminer" *et* qui ont un nom d'espèce
|
|
|
502 |
$req['where'][] = '(' . implode(' AND ', array(
|
1416 |
raphael |
503 |
'vdi.nom_sel IS NOT NULL',
|
|
|
504 |
'vdi.certitude != "aDeterminer"',
|
|
|
505 |
'(vdi.mots_cles_texte IS NULL OR vdi.mots_cles_texte NOT LIKE "%aDeterminer%"',
|
1375 |
raphael |
506 |
)) . ')';
|
|
|
507 |
}
|
1444 |
raphael |
508 |
if(array_key_exists('validees', $val)) {
|
|
|
509 |
//On récupère toutes les observations ayant un commentaire doté de proposition_retenue = 1
|
|
|
510 |
$req['join'][] = 'INNER JOIN del_commentaire AS dc ON vdi.id_observation = dc.ce_observation AND dc.proposition_retenue = 1';
|
|
|
511 |
}
|
1375 |
raphael |
512 |
|
|
|
513 |
// solution n°1: impraticable
|
|
|
514 |
if(false && array_key_exists('endiscussion', $val)) {
|
|
|
515 |
//Si on veut les observations en discussion,
|
|
|
516 |
// on va récupérer les ids des observations dont le nombre de commentaire est supérieur à N
|
|
|
517 |
$req['select'][] = 'COUNT(dc.id_commentaire) AS comm_count';
|
1416 |
raphael |
518 |
$req['join'][] = 'INNER JOIN del_commentaire AS dc ON vdi.id_observation = dc.ce_observation';
|
|
|
519 |
$req['groupby'][] = 'vdi.id_observation';
|
1375 |
raphael |
520 |
$req['having'][] = "COUNT(id_commentaire) > " . $c->getParametre('nb_commentaires_discussion');
|
|
|
521 |
}
|
|
|
522 |
|
|
|
523 |
if(array_key_exists('endiscussion', $val)) {
|
|
|
524 |
$req['where'][] = '(SELECT COUNT(id_commentaire) FROM del_commentaire AS dc'.
|
|
|
525 |
' WHERE ce_observation = id_observation) > ' . intval($c->getParametre('nb_commentaires_discussion'));
|
|
|
526 |
}
|
|
|
527 |
}
|
|
|
528 |
|
|
|
529 |
|
|
|
530 |
/**
|
1488 |
raphael |
531 |
* Récupérer toutes les déterminations et le nombre de commentaire au total
|
|
|
532 |
* @param array $observations la liste des observations à mettre à jour
|
|
|
533 |
* */
|
1375 |
raphael |
534 |
private function chargerDeterminations(&$observations) {
|
|
|
535 |
$idObs = array_values(array_map(create_function('$a', 'return $a["id_observation"];'),
|
1488 |
raphael |
536 |
$observations));
|
1375 |
raphael |
537 |
$r = sprintf('SELECT * FROM del_commentaire AS dc WHERE dc.nom_sel IS NOT NULL AND ce_observation IN (%s) -- %s',
|
1488 |
raphael |
538 |
implode(',',$idObs),
|
|
|
539 |
__FILE__ . ':' . __LINE__);
|
1375 |
raphael |
540 |
$propositions = $this->bdd->recupererTous($r);
|
|
|
541 |
if(!$propositions) return;
|
|
|
542 |
foreach ($propositions as $proposition) {
|
|
|
543 |
$idObs = $proposition['ce_observation'];
|
1386 |
raphael |
544 |
$idComment = $proposition['id_commentaire'];
|
|
|
545 |
$comment = $this->formaterDetermination($idComment, $proposition);
|
|
|
546 |
if($comment) $observations['"' . $idObs . '"']['commentaires'][$idComment] = $comment;
|
|
|
547 |
|
1375 |
raphael |
548 |
}
|
|
|
549 |
}
|
|
|
550 |
|
1386 |
raphael |
551 |
private function formaterDetermination($commentId, $proposition) {
|
|
|
552 |
if(!$proposition) return NULL;
|
|
|
553 |
|
|
|
554 |
$proposition_formatee = array('nb_commentaires' => '0');
|
|
|
555 |
foreach ($this->mappingCommentaire as $nomOriginal => $nomFinal) {
|
|
|
556 |
if (isset($proposition[$nomOriginal])) {
|
|
|
557 |
$proposition_formatee[$nomFinal] = $proposition[$nomOriginal];
|
|
|
558 |
}
|
|
|
559 |
}
|
|
|
560 |
|
|
|
561 |
// Charger les votes sur les déterminations
|
|
|
562 |
$resultatsVotes = $this->bdd->recupererTous(
|
|
|
563 |
sprintf('SELECT * FROM del_commentaire_vote WHERE ce_proposition = %d', $commentId));
|
|
|
564 |
|
1375 |
raphael |
565 |
foreach ($resultatsVotes as $vote) {
|
1386 |
raphael |
566 |
$proposition_formatee['votes'][$vote['id_vote']] = $this->formaterVote($vote);
|
1375 |
raphael |
567 |
}
|
|
|
568 |
|
1386 |
raphael |
569 |
|
|
|
570 |
// chargerNombreCommentaire()
|
|
|
571 |
// Charger le nombre de commentaires (sans détermination) associé à l'observation
|
|
|
572 |
$listeCommentaires = $this->bdd->recupererTous(sprintf(
|
|
|
573 |
'SELECT ce_commentaire_parent, ce_proposition, COUNT( id_commentaire ) AS nb '.
|
|
|
574 |
'FROM del_commentaire WHERE ce_proposition = %d GROUP BY ce_proposition -- %s',
|
|
|
575 |
$commentId, __FILE__ . ':' . __LINE__));
|
1375 |
raphael |
576 |
foreach ($listeCommentaires as $ligneProposition) {
|
|
|
577 |
// ce test sert à exclure les proposition de 1er niveau qui sont elles aussi des commentaires
|
1386 |
raphael |
578 |
if($ligneProposition['ce_commentaire_parent']) {
|
|
|
579 |
// TODO/debug: id_commentaire_parent != $commentId ??
|
|
|
580 |
// reprendre la "logique" du code... moins de boucles, moins de requêtes, ...
|
|
|
581 |
if($ligneProposition['ce_commentaire_parent'] != $commentId) {
|
|
|
582 |
// restore_error_handler();
|
|
|
583 |
error_log(sprintf("possible error: nb_commentaires = %s: comment = %d, parent = %d, %s",
|
1488 |
raphael |
584 |
$ligneProposition['nb'], $commentId, $ligneProposition['ce_commentaire_parent'], __FILE__));
|
1386 |
raphael |
585 |
}
|
|
|
586 |
$proposition_formatee['nb_commentaires'] = $ligneProposition['nb'];
|
1375 |
raphael |
587 |
} else {
|
1386 |
raphael |
588 |
$proposition_formatee['observation']['nb_commentaires'] = $ligneProposition['nb'];
|
1375 |
raphael |
589 |
}
|
|
|
590 |
}
|
|
|
591 |
|
1386 |
raphael |
592 |
return $proposition_formatee;
|
1375 |
raphael |
593 |
}
|
|
|
594 |
|
|
|
595 |
/**
|
1488 |
raphael |
596 |
* Formater un vote en fonction du fichier de configuration config_votes.ini
|
|
|
597 |
* @param $votes array()
|
|
|
598 |
* */
|
1375 |
raphael |
599 |
private function formaterVote($vote) {
|
|
|
600 |
$retour = array();
|
|
|
601 |
foreach ($vote as $param=>$valeur) {
|
|
|
602 |
$retour[$this->mappingVotes[$param]] = $valeur;
|
|
|
603 |
}
|
|
|
604 |
return $retour;
|
|
|
605 |
}
|
|
|
606 |
|
|
|
607 |
|
|
|
608 |
// supprime l'index du tableau des paramètres si sa valeur ne correspond pas
|
|
|
609 |
// au spectre passé par $values.
|
|
|
610 |
static function unsetIfInvalid(&$var, $index, $values) {
|
|
|
611 |
if(array_key_exists($index, $var)) {
|
|
|
612 |
if(!in_array($var[$index], $values)) unset($var[$index]);
|
|
|
613 |
else return $var[$index];
|
|
|
614 |
}
|
|
|
615 |
return NULL;
|
|
|
616 |
}
|
|
|
617 |
|
|
|
618 |
|
1429 |
raphael |
619 |
/* Filtre et valide les paramètres reconnus. Effectue *toute* la sanitization *sauf* l'escape-string
|
|
|
620 |
Cette fonction est appelée:
|
|
|
621 |
- une fois sur les champs de recherche avancées
|
|
|
622 |
- une fois sur le masque général si celui-ci à été spécifié. Dans ce cas,
|
|
|
623 |
la chaîne générale saisie est utilisée comme valeur pour chacun des champs particuliers
|
|
|
624 |
avec les traitements particuliers qui s'imposent
|
|
|
625 |
Par exemple: si l'on cherche "Languedoc", cela impliquera:
|
|
|
626 |
WHERE (nom_sel like "Languedoc" OR nom_ret ... OR ...) mais pas masque.date ou masque.departement
|
|
|
627 |
qui s'assure d'un pattern particulier */
|
1421 |
raphael |
628 |
static function requestFilterParams(Array $params, $parametres_autorises = NULL, Conteneur $c = NULL /* pour la récup des départements */ ) {
|
|
|
629 |
if($parametres_autorises) { // filtrage de toute clef inconnue
|
|
|
630 |
$params = array_intersect_key($params, array_flip($parametres_autorises));
|
|
|
631 |
}
|
1375 |
raphael |
632 |
|
|
|
633 |
$p['tri'] = self::unsetIfInvalid($params, 'tri', array('date_observation'));
|
|
|
634 |
$p['ordre'] = self::unsetIfInvalid($params, 'ordre', array('asc','desc'));
|
1394 |
aurelien |
635 |
$p['masque.referentiel'] = self::unsetIfInvalid($params, 'masque.referentiel', array('bdtfx','bdtxa','isfan'));
|
1375 |
raphael |
636 |
|
|
|
637 |
// TODO: use filter_input(INPUT_GET);
|
|
|
638 |
// renvoie FALSE ou NULL si absent ou invalide
|
|
|
639 |
$p['navigation.limite'] = filter_var(@$params['navigation.limite'],
|
1488 |
raphael |
640 |
FILTER_VALIDATE_INT,
|
|
|
641 |
array('options' => array('default' => NULL,
|
|
|
642 |
'min_range' => 1,
|
|
|
643 |
'max_range' => _LISTE_OBS_MAX_RESULT_LIMIT)));
|
1375 |
raphael |
644 |
$p['navigation.depart'] = filter_var(@$params['navigation.depart'],
|
1488 |
raphael |
645 |
FILTER_VALIDATE_INT,
|
|
|
646 |
array('options' => array('default' => NULL,
|
|
|
647 |
'min_range' => 0,
|
|
|
648 |
'max_range' => _LISTE_OBS_MAX_ID_OBS)));
|
1375 |
raphael |
649 |
if(isset($params['masque.departement'])) {
|
|
|
650 |
// STRING: 0 -> 95, 971 -> 976, 2A + 2B (./services/configurations/config_departements_bruts.ini)
|
|
|
651 |
// accept leading 0 ?
|
|
|
652 |
// TODO; filter patterns like 555.
|
|
|
653 |
if(preg_match(';^(\d{2}|\d{3}|2a|2b)$;i', $params['masque.departement'])) {
|
|
|
654 |
$p['masque.departement'] = $params['masque.departement'];
|
|
|
655 |
}
|
|
|
656 |
// cf configurations/config_departements_bruts.ini
|
|
|
657 |
elseif( !is_null($c) && ( $x = $c->getParametre(
|
|
|
658 |
strtolower(str_replace(' ','-',iconv("UTF-8", "ASCII//TRANSLIT", $params['masque.departement'])))
|
|
|
659 |
))) {
|
|
|
660 |
$p['masque.departement'] = sprintf("INSEE-C:%02d___", $x);
|
|
|
661 |
}
|
|
|
662 |
}
|
|
|
663 |
|
|
|
664 |
if(isset($params['masque.date'])) {
|
|
|
665 |
// une année, TODO: masque.annee
|
|
|
666 |
if(is_numeric($params['masque.date'])) {
|
1379 |
raphael |
667 |
$p['masque.date'] = $params['masque.date'];
|
1375 |
raphael |
668 |
}
|
|
|
669 |
elseif(strpos($params['masque.date'], '/' !== false) &&
|
1488 |
raphael |
670 |
($x = strtotime(str_replace('/','-',$params['masque.date'])))) {
|
1375 |
raphael |
671 |
$p['masque.date'] = $x;
|
|
|
672 |
}
|
|
|
673 |
elseif(strpos($params['masque.date'], '-' !== false) &&
|
1488 |
raphael |
674 |
($x = strtotime($params['masque.date'])) ) {
|
1375 |
raphael |
675 |
$p['masque.date'] = $x;
|
|
|
676 |
}
|
|
|
677 |
}
|
|
|
678 |
|
|
|
679 |
$p['masque.nn'] = filter_var(@$params['masque.nn'],
|
1488 |
raphael |
680 |
FILTER_VALIDATE_INT,
|
|
|
681 |
array('options' => array('default' => NULL,
|
|
|
682 |
'min_range' => 0,
|
|
|
683 |
'max_range' => _LISTE_OBS_MAX_BDTFX_NN)));
|
1375 |
raphael |
684 |
|
|
|
685 |
$p['masque.nt'] = filter_var(@$params['masque.nt'],
|
1488 |
raphael |
686 |
FILTER_VALIDATE_INT,
|
|
|
687 |
array('options' => array('default' => NULL,
|
|
|
688 |
'min_range' => 0,
|
|
|
689 |
'max_range' => _LISTE_OBS_MAX_BDTFX_NT)));
|
1375 |
raphael |
690 |
|
|
|
691 |
|
|
|
692 |
// TODO: should we really trim() ?
|
|
|
693 |
|
|
|
694 |
if(isset($params['masque.ns'])) $p['masque.ns'] = trim($params['masque.ns']);
|
|
|
695 |
// if(isset($params['masque.texte'])) $p['masque.texte'] = trim($params['masque.texte']);
|
|
|
696 |
|
|
|
697 |
if(isset($params['masque.famille'])) {
|
|
|
698 |
// mysql -N<<<"SELECT DISTINCT famille FROM bdtfx_v1_02;"|sed -r "s/(.)/\1\n/g"|sort -u|tr -d "\n"
|
|
|
699 |
$p['masque.famille'] = preg_replace('/[^a-zA-Z %_]/', '', iconv("UTF-8",
|
1488 |
raphael |
700 |
"ASCII//TRANSLIT",
|
|
|
701 |
$params['masque.famille']));
|
1375 |
raphael |
702 |
}
|
|
|
703 |
|
|
|
704 |
// masque.genre est un alias pour masque.ns (nom_sel), mais permet de rajouter une clause supplémentaire
|
|
|
705 |
// sur nom_sel. Précédemment: WHERE nom_sel LIKE '%<masque.genre>% %'.
|
|
|
706 |
// Désormais masque.genre doit être intégralement spécifié, les caractères '%' et '_' seront interprétés.
|
|
|
707 |
// Attention toutefois car la table del_observation intègre des nom_sel contenant '_'
|
|
|
708 |
if(isset($params['masque.genre'])) $p['masque.genre'] = trim($params['masque.genre']);
|
|
|
709 |
if(isset($params['masque.ns'])) $p['masque.ns'] = trim($params['masque.ns']);
|
|
|
710 |
// masque.espece n'était pas déclaré dans la "where" mais utilisé via config + switch//default
|
|
|
711 |
if(isset($params['masque.espece'])) $p['masque.espece'] = trim($params['masque.espece']);
|
|
|
712 |
|
|
|
713 |
// idem pour id_zone_geo qui mappait à ce_zone_geo:
|
|
|
714 |
if(isset($params['masque.id_zone_geo']) && preg_match(';^(INSEE-C:\d{5}|\d{2})$;', $params['masque.id_zone_geo'])) {
|
|
|
715 |
$p['masque.id_zone_geo'] = $params['masque.id_zone_geo'];
|
|
|
716 |
}
|
|
|
717 |
|
|
|
718 |
// masque.commune (zone_geo)
|
|
|
719 |
// TODO: que faire avec des '%' en INPUT ?
|
|
|
720 |
// Le masque doit *permettre* une regexp et non l'imposer. Charge au client de faire son travail
|
|
|
721 |
if(isset($params['masque.commune'])) $p['masque.commune'] = str_replace(array('-',' '), '_', $params['masque.commune']);
|
|
|
722 |
|
|
|
723 |
// masque.auteur: peut-être un id, un courriel, ou un nom ou prénom, ...
|
|
|
724 |
if(isset($params['masque.auteur'])) $p['masque.auteur'] = trim($params['masque.auteur']);
|
|
|
725 |
// sera trimmé plus tard, cf sqlAddConstraint
|
|
|
726 |
if(isset($params['masque'])) $p['masque'] = trim($params['masque']);
|
|
|
727 |
|
|
|
728 |
// masque.tag, idem que pour masque.genre et masque.commune
|
|
|
729 |
if(isset($params['masque.tag'])) {
|
|
|
730 |
$x = explode(',',$params['masque.tag']);
|
|
|
731 |
$x = array_map('trim', $x);
|
|
|
732 |
$p['masque.tag'] = implode('|', array_filter($x));
|
|
|
733 |
}
|
|
|
734 |
|
1444 |
raphael |
735 |
// masque.type: ['adeterminer', 'aconfirmer', 'endiscussion', 'validees']
|
1375 |
raphael |
736 |
if(isset($params['masque.type'])) {
|
|
|
737 |
$p['masque.type'] = array_flip(array_intersect(array_filter(explode(';', $params['masque.type'])),
|
1488 |
raphael |
738 |
array('adeterminer', 'aconfirmer', 'endiscussion', 'validees')));
|
1375 |
raphael |
739 |
}
|
|
|
740 |
|
|
|
741 |
|
|
|
742 |
// TODO: masque (général)
|
|
|
743 |
|
|
|
744 |
|
|
|
745 |
// on filtre les NULL, FALSE et '', mais pas les 0, d'où le callback()
|
|
|
746 |
// TODO: PHP-5.3
|
1421 |
raphael |
747 |
return array_filter($p, create_function('$a','return !in_array($a, array("",false,null),true);'));
|
1375 |
raphael |
748 |
}
|
|
|
749 |
|
1389 |
raphael |
750 |
static function makeJSONHeader($total, $params, $url_service) {
|
1480 |
mathias |
751 |
|
1389 |
raphael |
752 |
$prev_url = $next_url = NULL;
|
1480 |
mathias |
753 |
$url_service_sans_slash = substr($url_service, 0, -1);
|
1389 |
raphael |
754 |
|
1480 |
mathias |
755 |
// aplatissons les params! - une seule couche cela dit, après débrouillez-vous
|
|
|
756 |
$params_a_plat = $params;
|
|
|
757 |
foreach ($params_a_plat as $cle_plate => $pap) {
|
|
|
758 |
if (is_array($pap)) {
|
|
|
759 |
$params_a_plat[$cle_plate] = implode(array_keys($pap), ',');
|
|
|
760 |
}
|
|
|
761 |
}
|
|
|
762 |
|
1389 |
raphael |
763 |
$next_offset = $params['navigation.depart'] + $params['navigation.limite'];
|
|
|
764 |
if($next_offset < $total) {
|
1480 |
mathias |
765 |
$next_url = $url_service_sans_slash . '?' . http_build_query(array_merge($params_a_plat, array('navigation.depart' => $next_offset)));
|
1389 |
raphael |
766 |
}
|
|
|
767 |
|
|
|
768 |
$prev_offset = $params['navigation.depart'] - $params['navigation.limite'];
|
1481 |
mathias |
769 |
if($prev_offset >= 0) {
|
1480 |
mathias |
770 |
$prev_url = $url_service_sans_slash . '?' . http_build_query(array_merge($params_a_plat, array('navigation.depart' => $prev_offset)));
|
1389 |
raphael |
771 |
}
|
|
|
772 |
|
|
|
773 |
return array(
|
1417 |
raphael |
774 |
'masque' => http_build_query(array_diff_key($params, array_flip(array('navigation.depart', 'navigation.limite')))),
|
1389 |
raphael |
775 |
'total' => $total,
|
|
|
776 |
'depart' => $params['navigation.depart'],
|
|
|
777 |
'limite' => $params['navigation.limite'],
|
|
|
778 |
'href.precedent' => $prev_url,
|
|
|
779 |
'href.suivant' => $next_url
|
|
|
780 |
);
|
|
|
781 |
}
|
1375 |
raphael |
782 |
}
|