Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 854 | Rev 858 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
854 raphael 1
<?php
2
/*
3
 * @copyright 2013 Tela Botanica (accueil@tela-botanica.org)
4
 * @author Raphaël Droz <raphael@tela-botanica.org>
5
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
6
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
7
 *
856 raphael 8
 * pattern: /service:eflore:0.1/coste/textes/bdtfx.nn:182
854 raphael 9
 * params: txt.format=(htm|txt) ,  retour.champs=(titre,texte,...) , retour.format=(min|max), ...
10
 *
11
 * Ce webservice est censé pouvoir:
12
 * 1) retourner des informations (choisies) à propos d'un taxon donné (à partir de son numéro nomenclatural
13
 * 2) retourner des informations (choisies) à propos de taxons recherchés (à partir de divers critères)
14
 *
15
 * TODO: masque.titre => masque.tag
16
 *
17
 */
18
 
19
/*restore_error_handler();
20
  error_reporting(E_ALL);*/
856 raphael 21
class Textes {
854 raphael 22
	// paramètres autorisés
23
	static $allow_params = array(
24
		'txt.format', 'retour.format', 'retour.champs',
25
		'recherche',
26
		'masque.ns', 'masque.txt', 'masque.page', 'masque.tome', 'masque.famille',
27
		'masque.titre', // masque sur titre de la page wiki correspondante (page "clef" OR page "description")
28
		'navigation.depart', 'navigation.limite');
29
	// et valeurs par défaut
30
	static $default_params = array('txt.format' => 'txt', 'retour.format' => 'max', 'recherche' => 'stricte',
31
								   'retour.champs' => 'titre,texte,determination,tag',
32
								   'navigation.depart' => 0, 'navigation.limite' => 50);
33
 
34
	// les champs de base de coste_v2_00
35
	// mysql -N tb_eflore<<<"SHOW FIELDS FROM coste_v2_00"|egrep -v 'page_'|awk '{print $1}'|xargs -i -n1 printf "'%s' => 'c.%s',\n" {} {}
36
	static $allow_champs = array(
37
		'num_nom' => 'c.num_nom',
38
		'num_nom_retenu' => 'c.num_nom_retenu',
39
		'num_tax_sup' => 'c.num_tax_sup',
40
		'rang' => 'c.rang',
41
		'nom_sci' => 'c.nom_sci',
42
		'nom_supra_generique' => 'c.nom_supra_generique',
43
		'genre' => 'c.genre',
44
		'epithete_infra_generique' => 'c.epithete_infra_generique',
45
		'epithete_sp' => 'c.epithete_sp',
46
		'type_epithete' => 'c.type_epithete',
47
		'epithete_infra_sp' => 'c.epithete_infra_sp',
48
		'cultivar_groupe' => 'c.cultivar_groupe',
49
		'cultivar' => 'c.cultivar',
50
		'nom_commercial' => 'c.nom_commercial',
51
		'auteur' => 'c.auteur',
52
		'annee' => 'c.annee',
53
		'biblio_origine' => 'c.biblio_origine',
54
		'notes' => 'c.notes',
55
		'nom_addendum' => 'c.nom_addendum',
56
		'nom_francais' => 'c.nom_francais',
57
		'nom_coste' => 'c.nom_coste',
58
		'auteur_coste' => 'c.auteur_coste',
59
		'biblio_coste' => 'c.biblio_coste',
60
		'num_nom_coste' => 'c.num_nom_coste',
61
		'num_nom_retenu_coste' => 'c.num_nom_retenu_coste',
62
		'num_tax_sup_coste' => 'c.num_tax_sup_coste',
63
		'synonymie_coste' => 'c.synonymie_coste',
64
		'tome' => 'c.tome',
65
		'page' => 'c.page',
66
		'nbre_taxons' => 'c.nbre_taxons',
67
		'flore_bdtfx_nn' => 'c.flore_bdtfx_nn',
68
		'flore_bdtfx_nt' => 'c.flore_bdtfx_nt',
69
		'image' => 'c.image',
70
		'image_auteur' => 'c.image_auteur',
71
		'nom_sci_html' => 'c.nom_sci_html',
72
 
73
		// handly duplicate (redirigé vers nom_sci ou nom_sci_html selon que txt.format vaut "txt" ou "htm"
74
		'titre' => 'c.nom_sci',
75
 
76
		// champs spécifiques (et étrangères)
77
		'texte' => 'dsc.body',
78
		'determination' => 'cle.body',
79
		'tag' => 'dsc.tag',
80
		'famille' => 'b.famille', // cf sqlAddJoins()
81
		'*' => 'XXX' // spécial
82
	);
83
 
84
	// les champs suivants disparaissent de la liste utilisée pour former la requête SQL
85
	static $special_champs = array('nom_sci_html', 'nom_sci', '*');
86
	// le pattern utilisé pour la recherche dite "floue"
87
	static $soundex_scheme = '(%1$s LIKE %2$s OR SOUNDEX(%1$s) = SOUNDEX(%2$s) OR SOUNDEX(REVERSE(%1$s)) = SOUNDEX(REVERSE(%2$s)))';
88
 
89
	// contrainte du point d'entrée d'API webservice Tela lors d'un GET
90
	public function consulter($ressources, $parametres, $db = NULL) {
91
		if(!$db) {
92
			// http_response_code(500);
93
			throw new Exception('no DB', 500);
94
		}
95
 
96
		// parser la requête et filtrer les paramètres valides
97
		// en cas d'accès HTTP
98
		if(array_key_exists('QUERY_STRING', $_SERVER)) {
99
			self::requestParse($uri, $params);
100
		}
101
		// en cas d'accès phpunit
102
		else {
103
			$uri = $ressources;
104
		}
105
 
106
		if(is_null($parametres)) $parametres = Array();
107
		$params = self::requestFilterParams($parametres);
108
 
109
		// renvoie du plain/text d'aide (cf fin de programme)
110
		if(count($uri) == 1 && $uri[0] == 'aide') return self::aide();
111
 
112
		$id = 0;
113
		// getNN renvoie le num_nom passé comme segment d'URI
114
		// ou bien l'extrait du pattern bdtfx.nn:#id
115
		if(count($uri) == 1) $id = self::getNN($uri[0]);
116
 
117
 
118
		// en cas d'échec (id invalide), bail-out
119
		// note: NULL is ok, mais FALSE est le retour de getNN()
120
		if($id === FALSE || count($uri) > 1) {
121
			// http_response_code(500);
122
			throw new Exception('not supported', 500);
123
		}
124
 
125
		// XXX: temporaires, pour chopper $db dans l'instance
126
		// (non disponibles dans nos helpers statics)
127
		$GLOBALS[__FILE__] = $db;
128
		$req = self::getCosteInfo($params, $id);
129
		unset($GLOBALS[__FILE__]);
130
		$res = $db->recupererTous($req);
131
		$err = mysql_error();
132
		if(!$res && $err) {
133
			// http_response_code(400);
134
			// if(defined('DEBUG') && DEBUG) header("X-Debug: $req");
135
			throw new Exception('not found', 400);
136
		}
137
 
138
		// rapide formatage des résultats:
139
		$matches = 0;
140
 
141
		if($res) {
142
			// nombre de matches (sans LIMIT) utilisé pour l'en-tête
143
			$matches = $db->recuperer('SELECT FOUND_ROWS() AS total');
144
			$matches = intval($matches['total']);
145
		}
146
 
147
		// reformate les résultats pour les indexer par num_nom
148
		$res2 = array();
149
		foreach($res as $v) {
150
			$res2[$v['num_nom']] = $v;
151
		}
152
 
153
		// l'appelant s'occupera du json_encode()
154
		// même si ça démange d'exit'er ici
155
		header("Content-Type: application/json; charset=utf-8");
156
		return array('entete' => array('depart' => $params['navigation.depart'],
157
									   'limite' => $params['navigation.limite'],
158
									   'total' => count($res2),
159
									   'match' => $matches),
160
					 'resultats' => $res2);
161
 
162
	}
163
 
164
 
165
	// la fonction central: récupère les infos à partir de paramètres
166
	// et une optionnel contrainte de num_nom
167
	static function getCosteInfo(array $params, $id = NULL) {
168
		assert('is_int($id)');
169
 
170
		// contraintes (WHERE):
171
		$constraints = self::sqlAddConstraint($params);
172
		// ajout de la contrainte sur num_nom si un composant d'URL supplémentaire
173
		// comportant un #id existe
174
		if($id) array_unshift($constraints, "c.num_nom = $id");
175
 
176
 
177
		// champs:
178
		$champs_valides_non_formattes = NULL;
179
		$champs_valides = self::sqlSelectFields($params, $champs_valides_non_formattes);
180
 
181
		// joins:
182
		$other_join = self::sqlAddJoins($params, $champs_valides_non_formattes);
183
 
184
		$req = sprintf(<<<EOF
185
SELECT SQL_CALC_FOUND_ROWS c.num_nom, %s
186
FROM tb_eflore.coste_v2_00 c
187
LEFT JOIN tela_prod_wikini.florecoste_pages dsc ON c.page_wiki_dsc = dsc.tag AND dsc.latest = 'Y'
188
LEFT JOIN tela_prod_wikini.florecoste_pages cle ON c.page_wiki_cle = cle.tag AND cle.latest = 'Y'
189
%s
190
WHERE %s ORDER BY c.num_nom LIMIT %u, %u -- %s
191
EOF
192
					   ,
193
					   $champs_valides, // dans le SELECT (parmi champs coste_v2_00)
194
					   // autre join, si nécessaire
195
					   $other_join ? $other_join : '',
196
					   // where
197
					   $constraints ? implode(' AND ', $constraints) : '1',
198
 
199
					   // limit
200
					   $params['navigation.depart'],
201
					   $params['navigation.limite'],
202
					   __FILE__ . ':' . __LINE__);
203
 
204
		return $req;
205
	}
206
 
207
 
208
 
209
 
210
	// SQL helpers
211
	// le préfix de coste_v2_00 est "c"
212
	// le préfix de florecoste_pages sur la description est est "dsc"
213
	// le préfix de florecoste_pages sur la clef de détermination est est "cle"
214
	static function sqlAddConstraint($params) {
215
		$q = $GLOBALS[__FILE__];
216
 
217
		$stack = array();
218
		if(!empty($params['masque.ns'])) {
219
			if($params['recherche'] == 'etendue')
220
				$stack[] = 'c.nom_sci LIKE ' . $q->proteger('%' . trim($params['masque.ns']) . '%');
221
			elseif($params['recherche'] == 'floue')
222
				$stack[] = sprintf(self::$soundex_scheme,
223
								   'c.nom_sci',
224
								   $q->proteger('%' . trim($params['masque.ns']) . '%'));
225
			else
226
				$stack[] = 'c.nom_sci = ' . $q->proteger(trim($params['masque.ns']));
227
		}
228
 
229
		// le masque sur texte est toujours un LIKE() "étendue", sauf si "floue" spécifié
230
		if(!empty($params['masque.txt'])) {
231
			if($params['recherche'] == 'floue') {
232
				$stack[] = sprintf(self::$soundex_scheme,
233
								   'dsc.body',
234
								   $q->proteger('%' . trim($params['masque.txt']) . '%'));
235
			}
236
			else {
237
				$stack[] = 'dsc.body LIKE ' . $q->proteger('%' . trim($params['masque.txt']) . '%');
238
			}
239
		}
240
 
241
		if(!empty($params['masque.titre'])) {
242
			if($params['recherche'] == 'stricte') {
243
				$stack[] = sprintf('(dsc.tag = %1$s OR cle.tag = %1$s)',
244
								   $q->proteger(trim($params['masque.titre'])));
245
			}
246
			else {
247
				$stack[] = sprintf('(dsc.tag LIKE %1$s OR cle.tag LIKE %1$s)',
248
								   $q->proteger('%' .  trim($params['masque.titre']) . '%'));
249
			}
250
		}
251
 
252
		if(array_key_exists('masque.famille', $params)) {
253
			$stack[] = 'b.famille LIKE ' . $q->proteger(trim($params['masque.famille']));
254
		}
255
 
256
		if(array_key_exists('masque.page', $params)) {
257
			$stack[] = 'c.page = ' . intval($params['masque.page']);
258
		}
259
 
260
		if(array_key_exists('masque.tome', $params)) {
261
			$stack[] = 'c.tome = ' . intval($params['masque.tome']);
262
		}
263
 
264
		return $stack;
265
	}
266
 
267
 
268
	// $unmerged contient la même liste de champs que celle renvoyée
269
	// à la différence que celle-ci n'est pas reformatée et s'avère donc
270
	// utilisable plus aisément dans sqlAddJoins() qui peut en avoir besoin
271
	static function sqlSelectFields($params, &$unmerged) {
272
		$champs = $params['retour.champs'];
273
		// champs coste_v2_00
274
		$c = array_intersect_key(self::$allow_champs, array_flip(explode(',', $champs)));
275
		if(isset($c['*'])) {
276
			$t = array_diff_key(self::$allow_champs, array_flip(self::$special_champs));
277
		}
278
		else {
279
			// just loop below
280
			$t = $c;
281
		}
282
 
283
		// si aucun des champs fournis n'est valide
284
		// on se rappelle nous-même après avoir réinitialisé retour.champs
285
		// avec les champs par défaut
286
		if(!$t) {
287
			$params['retour.champs'] = self::$default_params['retour.champs'];
288
			return self::sqlSelectFields($params);
289
		}
290
 
291
		if(array_key_exists('titre', $t))
292
			$t['titre'] = $params['txt.format'] == 'txt' ? 'c.nom_sci' : 'c.nom_sci_html';
293
 
294
		$unmerged = $t;
295
 
296
		// XXX: PHP-5.3
297
		$ret = array();
298
		foreach($t as $k => $v) {
299
			$ret[] = "$v AS $k";
300
		}
301
		return implode(',',$ret);
302
	}
303
 
304
	static function sqlAddJoins($params, $champs) {
305
		$j = '';
306
		// ces tests doivent correspondre aux champs générés par sqlSelectFields()
307
		// ou contraintes générées par sqlAddConstraint()
308
		if(array_key_exists('masque.famille', $params) ||
309
		   array_key_exists('famille', $champs)) {
310
			$j .= 'LEFT JOIN tb_eflore.bdtfx_v1_02 b ON c.num_nom = b.num_nom';
311
		}
312
 
313
		return $j;
314
	}
315
 
316
	// request handler
317
	static function requestParse(&$ressource, &$params) {
318
		$uri = explode('/', $_SERVER['REDIRECT_URL']);
319
		if(!empty($_SERVER['QUERY_STRING']))
320
			parse_str($_SERVER['REDIRECT_QUERY_STRING'], $params);
856 raphael 321
		$ressource = array_slice($uri, array_search('textes', $uri) + 1, 3);
854 raphael 322
	}
323
 
324
	// supprime l'index du tableau des paramètres si sa valeur ne correspond pas
325
	// au spectre passé par $values.
326
	static function unsetIfInvalid(&$var, $index, $values) {
327
		if(array_key_exists($index, $var) && !in_array($var[$index], $values))
328
			unset($var[$index]);
329
	}
330
 
331
	static function requestFilterParams(Array $params) {
332
		$p = array_intersect_key($params, array_flip(self::$allow_params));
333
		self::unsetIfInvalid($p, 'txt.format', array('txt', 'htm'));
334
		self::unsetIfInvalid($p, 'retour.format', array('min','max'));
335
		self::unsetIfInvalid($p, 'recherche', array('stricte','etendue','floue'));
336
 
337
		if(isset($params['masque.ns'])) $p['masque.ns'] = trim($params['masque.ns']);
338
		if(isset($params['masque.texte'])) $p['masque.texte'] = trim($params['masque.texte']);
339
 
340
		if(isset($params['masque.famille'])) {
341
			// mysql -N<<<"SELECT DISTINCT famille FROM bdtfx_v1_02;"|sed -r "s/(.)/\1\n/g"|sort -u|tr -d "\n"
342
			$p['masque.famille'] = preg_replace('/[^a-zA-Z %_]/', '', iconv("UTF-8",
343
																			"ASCII//TRANSLIT",
344
																			$params['masque.famille']));
345
		}
346
 
347
		// TODO: use filter_input(INPUT_GET);
348
		// renvoie FALSE ou NULL si absent ou invalide
349
		$p['navigation.limite'] = filter_var(@$params['navigation.limite'],
350
												  FILTER_VALIDATE_INT,
351
												  array('options' => array('default' => NULL,
352
																		   'min_range' => 1,
353
																		   'max_range' => 500)));
354
		$p['navigation.depart'] = filter_var(@$params['navigation.depart'],
355
												  FILTER_VALIDATE_INT,
356
												  array('options' => array('default' => NULL,
357
																		   'min_range' => 0,
358
																		   'max_range' => 10000))); // count(1) from coste_v2_00
359
 
360
		// on filtre les NULL, FALSE et '', mais pas les 0, d'où le callback()
361
		// TODO: PHP-5.3
362
		$p = array_filter($p, create_function('$a','return !in_array($a, array("",false,null),true);'));
363
		$p = array_merge(self::$default_params, $p);
364
 
365
		return $p;
366
	}
367
 
368
	static function aide() {
369
		header("Content-Type: text/plain; charset=utf-8");
370
		return sprintf("
371
Service coste/textes:
372
Retourne des informations (choisies) à propos d'un taxon donné (à partir de son numéro nomenclatural
373
Retourne des informations (choisies) à propos de taxons recherchés (à partir de divers critères)
374
 
375
Usage:
376
			coste/textes/bdtfx.nn:#id?<params>
377
			coste/textes/#id?<params>
378
			coste/textes?<params>
379
* #id étant un numéro nomenclatural d'un taxon bdtfx
380
* retour.champs une liste de champs séparés par des virgules parmi *,%s
381
* les paramètres acceptés sont les suivants: %s
382
* les champs retournés par défaut sont les suivants: %s
383
* le paramètre \"recherche\" affecte les masques \"ns\" et \"texte\"
384
* le paramètre \"famille\" est traité via LIKE et accepte les caractères '_' et '%'
385
* le paramètre \"retour.format\" est inutilisé pour l'instant",
386
					   implode(',', array_keys(self::$allow_champs)),
387
					   implode(',', self::$allow_params),
388
					   self::$default_params['retour.champs']
389
		);
390
	}
391
 
392
	static function getNN($refnn) {
393
		if(is_numeric($refnn) && intval($refnn) >= 1) return intval($refnn);
394
		if(strpos($refnn, 'bdtfx.nn:') !== 0) return FALSE;
395
		return intval(str_replace('bdtfx.nn:', '', $refnn));
396
	}
397
}