Subversion Repositories eFlore/Projets.eflore-projets

Rev

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