Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 858 | Rev 861 | 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;
28
define('_COSTE_TEXTE_MAX_NUM_NOM', 7015 + 1000);
29
 
854 raphael 30
/*restore_error_handler();
31
  error_reporting(E_ALL);*/
856 raphael 32
class Textes {
854 raphael 33
	// paramètres autorisés
34
	static $allow_params = array(
35
		'txt.format', 'retour.format', 'retour.champs',
36
		'recherche',
37
		'masque.ns', 'masque.txt', 'masque.page', 'masque.tome', 'masque.famille',
38
		'masque.titre', // masque sur titre de la page wiki correspondante (page "clef" OR page "description")
39
		'navigation.depart', 'navigation.limite');
40
	// et valeurs par défaut
41
	static $default_params = array('txt.format' => 'txt', 'retour.format' => 'max', 'recherche' => 'stricte',
42
								   'retour.champs' => 'titre,texte,determination,tag',
43
								   'navigation.depart' => 0, 'navigation.limite' => 50);
44
 
45
	// les champs de base de coste_v2_00
46
	// mysql -N tb_eflore<<<"SHOW FIELDS FROM coste_v2_00"|egrep -v 'page_'|awk '{print $1}'|xargs -i -n1 printf "'%s' => 'c.%s',\n" {} {}
47
	static $allow_champs = array(
48
		'num_nom' => 'c.num_nom',
49
		'num_nom_retenu' => 'c.num_nom_retenu',
50
		'num_tax_sup' => 'c.num_tax_sup',
51
		'rang' => 'c.rang',
52
		'nom_sci' => 'c.nom_sci',
53
		'nom_supra_generique' => 'c.nom_supra_generique',
54
		'genre' => 'c.genre',
55
		'epithete_infra_generique' => 'c.epithete_infra_generique',
56
		'epithete_sp' => 'c.epithete_sp',
57
		'type_epithete' => 'c.type_epithete',
58
		'epithete_infra_sp' => 'c.epithete_infra_sp',
59
		'cultivar_groupe' => 'c.cultivar_groupe',
60
		'cultivar' => 'c.cultivar',
61
		'nom_commercial' => 'c.nom_commercial',
62
		'auteur' => 'c.auteur',
63
		'annee' => 'c.annee',
64
		'biblio_origine' => 'c.biblio_origine',
65
		'notes' => 'c.notes',
66
		'nom_addendum' => 'c.nom_addendum',
67
		'nom_francais' => 'c.nom_francais',
68
		'nom_coste' => 'c.nom_coste',
69
		'auteur_coste' => 'c.auteur_coste',
70
		'biblio_coste' => 'c.biblio_coste',
71
		'num_nom_coste' => 'c.num_nom_coste',
72
		'num_nom_retenu_coste' => 'c.num_nom_retenu_coste',
73
		'num_tax_sup_coste' => 'c.num_tax_sup_coste',
74
		'synonymie_coste' => 'c.synonymie_coste',
75
		'tome' => 'c.tome',
76
		'page' => 'c.page',
77
		'nbre_taxons' => 'c.nbre_taxons',
78
		'flore_bdtfx_nn' => 'c.flore_bdtfx_nn',
79
		'flore_bdtfx_nt' => 'c.flore_bdtfx_nt',
80
		'image' => 'c.image',
81
		'image_auteur' => 'c.image_auteur',
82
		'nom_sci_html' => 'c.nom_sci_html',
83
 
84
		// handly duplicate (redirigé vers nom_sci ou nom_sci_html selon que txt.format vaut "txt" ou "htm"
85
		'titre' => 'c.nom_sci',
86
 
87
		// champs spécifiques (et étrangères)
88
		'texte' => 'dsc.body',
89
		'determination' => 'cle.body',
90
		'tag' => 'dsc.tag',
91
		'famille' => 'b.famille', // cf sqlAddJoins()
92
		'*' => 'XXX' // spécial
93
	);
94
 
95
	// les champs suivants disparaissent de la liste utilisée pour former la requête SQL
96
	static $special_champs = array('nom_sci_html', 'nom_sci', '*');
97
	// le pattern utilisé pour la recherche dite "floue"
98
	static $soundex_scheme = '(%1$s LIKE %2$s OR SOUNDEX(%1$s) = SOUNDEX(%2$s) OR SOUNDEX(REVERSE(%1$s)) = SOUNDEX(REVERSE(%2$s)))';
99
 
100
	// contrainte du point d'entrée d'API webservice Tela lors d'un GET
101
	public function consulter($ressources, $parametres, $db = NULL) {
102
		if(!$db) {
103
			// http_response_code(500);
104
			throw new Exception('no DB', 500);
105
		}
106
 
107
		// parser la requête et filtrer les paramètres valides
108
		// en cas d'accès HTTP
109
		if(array_key_exists('QUERY_STRING', $_SERVER)) {
110
			self::requestParse($uri, $params);
111
		}
112
		// en cas d'accès phpunit
113
		else {
114
			$uri = $ressources;
115
		}
116
 
117
		// renvoie du plain/text d'aide (cf fin de programme)
118
		if(count($uri) == 1 && $uri[0] == 'aide') return self::aide();
119
 
120
 
858 raphael 121
		if(is_null($parametres)) $parametres = Array();
122
		$params = self::requestFilterParams($parametres);
123
		// les contraintes liées aux ids (passés comme composants d'URL)
124
		// sont ajoutées aux params [sans être accepté comme paramètre d'URL]
125
		$params['_ids'] = self::requestFilterIds($uri);
854 raphael 126
 
858 raphael 127
		// XXX: temporaires, passage de $db aux fonctions
128
		// de toolkits
129
		$req = self::getCosteInfo($params, $db);
130
 
854 raphael 131
		$res = $db->recupererTous($req);
132
		$err = mysql_error();
133
		if(!$res && $err) {
134
			// http_response_code(400);
135
			// if(defined('DEBUG') && DEBUG) header("X-Debug: $req");
136
			throw new Exception('not found', 400);
137
		}
138
 
139
		// rapide formatage des résultats:
140
		$matches = 0;
141
 
142
		if($res) {
143
			// nombre de matches (sans LIMIT) utilisé pour l'en-tête
144
			$matches = $db->recuperer('SELECT FOUND_ROWS() AS total');
145
			$matches = intval($matches['total']);
146
		}
147
 
148
		// reformate les résultats pour les indexer par num_nom
149
		$res2 = array();
150
		foreach($res as $v) {
151
			$res2[$v['num_nom']] = $v;
152
		}
153
 
154
		// l'appelant s'occupera du json_encode()
155
		// même si ça démange d'exit'er ici
156
		header("Content-Type: application/json; charset=utf-8");
157
		return array('entete' => array('depart' => $params['navigation.depart'],
158
									   'limite' => $params['navigation.limite'],
159
									   'total' => count($res2),
160
									   'match' => $matches),
161
					 'resultats' => $res2);
162
 
163
	}
164
 
165
 
166
	// la fonction central: récupère les infos à partir de paramètres
167
	// et une optionnel contrainte de num_nom
858 raphael 168
	static function getCosteInfo(array $params, $db) {
854 raphael 169
		// contraintes (WHERE):
858 raphael 170
		$constraints = self::sqlAddConstraint($params, $db);
171
		// XXX: que faire en l'absence de contrainte ? pour l'instant : "WHERE 1"
854 raphael 172
 
173
		// champs:
174
		$champs_valides_non_formattes = NULL;
175
		$champs_valides = self::sqlSelectFields($params, $champs_valides_non_formattes);
176
 
177
		// joins:
178
		$other_join = self::sqlAddJoins($params, $champs_valides_non_formattes);
179
 
180
		$req = sprintf(<<<EOF
181
SELECT SQL_CALC_FOUND_ROWS c.num_nom, %s
182
FROM tb_eflore.coste_v2_00 c
183
LEFT JOIN tela_prod_wikini.florecoste_pages dsc ON c.page_wiki_dsc = dsc.tag AND dsc.latest = 'Y'
184
LEFT JOIN tela_prod_wikini.florecoste_pages cle ON c.page_wiki_cle = cle.tag AND cle.latest = 'Y'
185
%s
186
WHERE %s ORDER BY c.num_nom LIMIT %u, %u -- %s
187
EOF
188
					   ,
189
					   $champs_valides, // dans le SELECT (parmi champs coste_v2_00)
190
					   // autre join, si nécessaire
191
					   $other_join ? $other_join : '',
192
					   // where
193
					   $constraints ? implode(' AND ', $constraints) : '1',
194
 
195
					   // limit
196
					   $params['navigation.depart'],
197
					   $params['navigation.limite'],
198
					   __FILE__ . ':' . __LINE__);
199
 
200
		return $req;
201
	}
202
 
203
 
204
 
205
 
206
	// SQL helpers
207
	// le préfix de coste_v2_00 est "c"
208
	// le préfix de florecoste_pages sur la description est est "dsc"
209
	// le préfix de florecoste_pages sur la clef de détermination est est "cle"
858 raphael 210
	static function sqlAddConstraint($params, $db) {
854 raphael 211
		$stack = array();
212
		if(!empty($params['masque.ns'])) {
213
			if($params['recherche'] == 'etendue')
858 raphael 214
				$stack[] = 'c.nom_sci LIKE ' . $db->proteger('%' . trim($params['masque.ns']) . '%');
854 raphael 215
			elseif($params['recherche'] == 'floue')
216
				$stack[] = sprintf(self::$soundex_scheme,
217
								   'c.nom_sci',
858 raphael 218
								   $db->proteger('%' . trim($params['masque.ns']) . '%'));
854 raphael 219
			else
858 raphael 220
				$stack[] = 'c.nom_sci = ' . $db->proteger(trim($params['masque.ns']));
854 raphael 221
		}
222
 
223
		// le masque sur texte est toujours un LIKE() "étendue", sauf si "floue" spécifié
224
		if(!empty($params['masque.txt'])) {
225
			if($params['recherche'] == 'floue') {
226
				$stack[] = sprintf(self::$soundex_scheme,
227
								   'dsc.body',
858 raphael 228
								   $db->proteger('%' . trim($params['masque.txt']) . '%'));
854 raphael 229
			}
230
			else {
858 raphael 231
				$stack[] = 'dsc.body LIKE ' . $db->proteger('%' . trim($params['masque.txt']) . '%');
854 raphael 232
			}
233
		}
234
 
235
		if(!empty($params['masque.titre'])) {
236
			if($params['recherche'] == 'stricte') {
237
				$stack[] = sprintf('(dsc.tag = %1$s OR cle.tag = %1$s)',
858 raphael 238
								   $db->proteger(trim($params['masque.titre'])));
854 raphael 239
			}
240
			else {
241
				$stack[] = sprintf('(dsc.tag LIKE %1$s OR cle.tag LIKE %1$s)',
858 raphael 242
								   $db->proteger('%' .  trim($params['masque.titre']) . '%'));
854 raphael 243
			}
244
		}
245
 
246
		if(array_key_exists('masque.famille', $params)) {
858 raphael 247
			$stack[] = 'b.famille LIKE ' . $db->proteger(trim($params['masque.famille']));
854 raphael 248
		}
249
 
250
		if(array_key_exists('masque.page', $params)) {
251
			$stack[] = 'c.page = ' . intval($params['masque.page']);
252
		}
253
 
254
		if(array_key_exists('masque.tome', $params)) {
255
			$stack[] = 'c.tome = ' . intval($params['masque.tome']);
256
		}
257
 
858 raphael 258
		// ajout de la contrainte sur num_nom si un composant d'URL supplémentaire
259
		// comportant un #id existe, cf self::requestFilterIds()
260
		if(array_key_exists('_ids', $params) && $params['_ids']) {
261
			$stack[] = sprintf("c.num_nom IN (%s)", implode(',', $params['_ids']));
262
		}
263
 
854 raphael 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,
858 raphael 353
																		   'max_range' => _COSTE_TEXTE_MAX_RESULT_LIMIT)));
854 raphael 354
		$p['navigation.depart'] = filter_var(@$params['navigation.depart'],
355
												  FILTER_VALIDATE_INT,
356
												  array('options' => array('default' => NULL,
357
																		   'min_range' => 0,
859 raphael 358
																		   'max_range' => _COSTE_TEXTE_MAX_NUM_NOM)));
854 raphael 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
 
858 raphael 368
	static function requestFilterIds($uri) {
369
		if(count($uri) != 1) return NULL;
370
 
371
		// getNN renvoie le num_nom passé comme segment d'URI
372
		// ou bien l'extrait du pattern bdtfx.nn:(#id)
373
		$ids = array_filter(array_map(array(__CLASS__, 'getNN'), explode(',', $uri[0])));
374
 
375
		// en cas d'échec (tous les id sont invalides), bail-out
376
		if(!$ids) {
377
			// http_response_code(500);
378
			throw new Exception('not supported', 500);
379
		}
380
 
381
		return array_slice($ids, 0, _COSTE_TEXTE_MAX_RESULT_LIMIT);
382
	}
383
 
854 raphael 384
	static function aide() {
385
		header("Content-Type: text/plain; charset=utf-8");
386
		return sprintf("
387
Service coste/textes:
388
Retourne des informations (choisies) à propos d'un taxon donné (à partir de son numéro nomenclatural
389
Retourne des informations (choisies) à propos de taxons recherchés (à partir de divers critères)
390
 
391
Usage:
858 raphael 392
			coste/textes/<liste-num_nom>?<params>
393
* <liste-num_nom> étant une liste de numéros nomenclaturaux de taxons bdtfx séparés par des virgules
394
  au format <#id> ou <bdtfx.nn:#id>
854 raphael 395
* retour.champs une liste de champs séparés par des virgules parmi *,%s
396
* les paramètres acceptés sont les suivants: %s
397
* les champs retournés par défaut sont les suivants: %s
398
* le paramètre \"recherche\" affecte les masques \"ns\" et \"texte\"
399
* le paramètre \"famille\" est traité via LIKE et accepte les caractères '_' et '%'
400
* le paramètre \"retour.format\" est inutilisé pour l'instant",
401
					   implode(',', array_keys(self::$allow_champs)),
402
					   implode(',', self::$allow_params),
403
					   self::$default_params['retour.champs']
404
		);
405
	}
406
 
407
	static function getNN($refnn) {
859 raphael 408
		if(is_numeric($refnn)) {
409
			$t = intval($refnn);
410
			if($t >= 1 && $t < _COSTE_TEXTE_MAX_NUM_NOM) return $t;
411
			return FALSE;
412
		}
854 raphael 413
		if(strpos($refnn, 'bdtfx.nn:') !== 0) return FALSE;
414
		return intval(str_replace('bdtfx.nn:', '', $refnn));
415
	}
416
}