Subversion Repositories eFlore/Projets.eflore-projets

Rev

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