Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 948 | Rev 984 | 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);
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)',
59
		'bdtfx:nt' => '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()
112
	static $champs_obligatoires = array('coste:nn', 'bdtfx:nn');
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);
149
 
854 raphael 150
		$res = $db->recupererTous($req);
151
		$err = mysql_error();
918 jpm 152
		if (!$res && $err) {
854 raphael 153
			// http_response_code(400);
154
			// if(defined('DEBUG') && DEBUG) header("X-Debug: $req");
155
			throw new Exception('not found', 400);
156
		}
157
 
158
		// rapide formatage des résultats:
159
		$matches = 0;
160
 
918 jpm 161
		if ($res) {
854 raphael 162
			// nombre de matches (sans LIMIT) utilisé pour l'en-tête
163
			$matches = $db->recuperer('SELECT FOUND_ROWS() AS total');
164
			$matches = intval($matches['total']);
165
		}
166
 
863 raphael 167
		// reformate les résultats pour les indexer par coste:nn par défaut
168
		// cependant le paramètre retour.indexBy permet de choisir une indexation par num_nom de bdtfx
169
		$clef_index = $params['retour.indexBy'] == 'coste' ? 'coste:nn' : 'bdtfx:nn';
854 raphael 170
		$res2 = array();
918 jpm 171
		foreach ($res as $v) {
172
			if (!$v[$clef_index]) {
173
				throw new Exception('format error: index NULL, use retour.indexBy=coste', 409);
174
			}
863 raphael 175
			$res2[$v[$clef_index]] = $v;
854 raphael 176
		}
177
 
178
		// l'appelant s'occupera du json_encode()
179
		// même si ça démange d'exit'er ici
948 raphael 180
		if(strpos($_SERVER['SCRIPT_NAME'], 'phpunit') === FALSE) header("Content-Type: application/json; charset=utf-8");
918 jpm 181
		return array('entete' => array(
182
			'depart' => $params['navigation.depart'],
183
			'limite' => $params['navigation.limite'],
184
			'total' => count($res2),
185
			'match' => $matches),
933 raphael 186
					 'resultats' => $res2);
854 raphael 187
	}
188
 
189
 
861 raphael 190
	// la fonction centrale: récupère les infos à partir de paramètres
191
	// et une optionnelle contrainte sur coste:nn ou bdtfx:nn
858 raphael 192
	static function getCosteInfo(array $params, $db) {
854 raphael 193
		// contraintes (WHERE):
858 raphael 194
		$constraints = self::sqlAddConstraint($params, $db);
195
		// XXX: que faire en l'absence de contrainte ? pour l'instant : "WHERE 1"
854 raphael 196
 
197
		// champs:
198
		$champs_valides_non_formattes = NULL;
199
		$champs_valides = self::sqlSelectFields($params, $champs_valides_non_formattes);
200
 
201
		// joins:
202
		$other_join = self::sqlAddJoins($params, $champs_valides_non_formattes);
918 jpm 203
		$requete_tpl = "SELECT SQL_CALC_FOUND_ROWS  %s".
204
			"FROM tb_eflore.coste_v2_00 c ".
205
			"	LEFT JOIN tela_prod_wikini.florecoste_pages dsc ON c.page_wiki_dsc = dsc.tag AND dsc.latest = 'Y' ".
206
			"	LEFT JOIN tela_prod_wikini.florecoste_pages cle ON c.page_wiki_cle = cle.tag AND cle.latest = 'Y' ".
207
			" %s ".
208
			"WHERE %s ORDER BY c.num_nom LIMIT %u, %u -- %s ";
209
		$req = sprintf($requete_tpl,
210
			$champs_valides, // dans le SELECT (parmi champs coste_v2_00)
211
			// autre join, si nécessaire
212
			$other_join ? $other_join : '',
854 raphael 213
 
918 jpm 214
			// where
215
			$constraints ? implode(' AND ', $constraints) : '1',
216
 
217
			// limit
218
			$params['navigation.depart'],
219
			$params['navigation.limite'],
220
			__FILE__ . ':' . __LINE__);
221
 
854 raphael 222
		return $req;
223
	}
224
 
225
	// SQL helpers
226
	// le préfix de coste_v2_00 est "c"
227
	// le préfix de florecoste_pages sur la description est est "dsc"
228
	// le préfix de florecoste_pages sur la clef de détermination est est "cle"
858 raphael 229
	static function sqlAddConstraint($params, $db) {
854 raphael 230
		$stack = array();
918 jpm 231
		if (!empty($params['masque.ns'])) {
232
			if ($params['recherche'] == 'etendue') {
233
				$stack[] = 'c.nom_sci LIKE '.$db->proteger('%' . trim($params['masque.ns']).'%');
234
			} elseif($params['recherche'] == 'floue') {
854 raphael 235
				$stack[] = sprintf(self::$soundex_scheme,
918 jpm 236
					'c.nom_sci',
237
					$db->proteger('%'.trim($params['masque.ns']).'%'));
238
			} else {
239
				$stack[] = 'c.nom_sci = '.$db->proteger(trim($params['masque.ns']));
240
			}
854 raphael 241
		}
242
 
243
		// le masque sur texte est toujours un LIKE() "étendue", sauf si "floue" spécifié
244
		if(!empty($params['masque.txt'])) {
245
			if($params['recherche'] == 'floue') {
246
				$stack[] = sprintf(self::$soundex_scheme,
918 jpm 247
					'dsc.body',
248
					$db->proteger('%'.trim($params['masque.txt']).'%'));
854 raphael 249
			}
250
			else {
918 jpm 251
				$stack[] = 'dsc.body LIKE '.$db->proteger('%'.trim($params['masque.txt']).'%');
854 raphael 252
			}
253
		}
254
 
255
		if(!empty($params['masque.titre'])) {
256
			if($params['recherche'] == 'stricte') {
257
				$stack[] = sprintf('(dsc.tag = %1$s OR cle.tag = %1$s)',
918 jpm 258
					$db->proteger(trim($params['masque.titre'])));
854 raphael 259
			}
260
			else {
261
				$stack[] = sprintf('(dsc.tag LIKE %1$s OR cle.tag LIKE %1$s)',
918 jpm 262
					$db->proteger('%'.trim($params['masque.titre']).'%'));
854 raphael 263
			}
264
		}
265
 
266
		if(array_key_exists('masque.famille', $params)) {
918 jpm 267
			$stack[] = 'b.famille LIKE '.$db->proteger(trim($params['masque.famille']));
854 raphael 268
		}
269
 
270
		if(array_key_exists('masque.page', $params)) {
918 jpm 271
			$stack[] = 'c.page = '.intval($params['masque.page']);
854 raphael 272
		}
273
 
274
		if(array_key_exists('masque.tome', $params)) {
918 jpm 275
			$stack[] = 'c.tome = '.intval($params['masque.tome']);
854 raphael 276
		}
277
 
862 raphael 278
		if(array_key_exists('masque.nt', $params)) {
918 jpm 279
			$stack[] = 'c.flore_bdtfx_nt = '.intval($params['masque.nt']);
862 raphael 280
		}
281
 
861 raphael 282
		// ajout de la contrainte sur coste:nn ou bdtfx:nn si un composant d'URL supplémentaire
858 raphael 283
		// comportant un #id existe, cf self::requestFilterIds()
861 raphael 284
		$o_stack = array();
918 jpm 285
		if (array_key_exists('_ids', $params) && $params['_ids']) {
286
			if ($params['_ids']['coste']) {
861 raphael 287
				$o_stack[] = sprintf("c.num_nom IN (%s)", implode(',', $params['_ids']['coste']));
288
			}
918 jpm 289
			if ($params['_ids']['bdtfx']) {
861 raphael 290
				$o_stack[] = sprintf("c.flore_bdtfx_nn IN (%s)", implode(',', $params['_ids']['bdtfx']));
291
			}
858 raphael 292
		}
918 jpm 293
		if ($o_stack) {
294
			$stack[] = '(' . implode(' OR ', $o_stack) . ')';
295
		}
858 raphael 296
 
854 raphael 297
		return $stack;
298
	}
299
 
300
 
301
	// $unmerged contient la même liste de champs que celle renvoyée
302
	// à la différence que celle-ci n'est pas reformatée et s'avère donc
303
	// utilisable plus aisément dans sqlAddJoins() qui peut en avoir besoin
304
	static function sqlSelectFields($params, &$unmerged) {
305
		$champs = $params['retour.champs'];
306
		// champs coste_v2_00
861 raphael 307
		$c = self::addSQLToFieldSynonym(explode(',', $champs));
918 jpm 308
		if (isset($c['*'])) {
854 raphael 309
			$t = array_diff_key(self::$allow_champs, array_flip(self::$special_champs));
918 jpm 310
		} else {
854 raphael 311
			// just loop below
312
			$t = $c;
313
		}
314
 
315
		// si aucun des champs fournis n'est valide
316
		// on se rappelle nous-même après avoir réinitialisé retour.champs
317
		// avec les champs par défaut
318
		if(!$t) {
319
			$params['retour.champs'] = self::$default_params['retour.champs'];
320
			return self::sqlSelectFields($params);
321
		}
322
 
323
		if(array_key_exists('titre', $t))
324
			$t['titre'] = $params['txt.format'] == 'txt' ? 'c.nom_sci' : 'c.nom_sci_html';
325
 
861 raphael 326
		// champs obligatoires:
327
		$t = array_merge($t, self::addSQLToFieldSynonym(self::$champs_obligatoires));
854 raphael 328
		$unmerged = $t;
329
 
330
		// XXX: PHP-5.3
331
		$ret = array();
332
		foreach($t as $k => $v) {
918 jpm 333
			if (strpos($k, ':') !== FALSE) {
861 raphael 334
				$ret[] = "$v AS \"$k\"";
335
			} else {
336
				$ret[] = "$v AS $k";
337
			}
854 raphael 338
		}
339
		return implode(',',$ret);
340
	}
341
 
342
	static function sqlAddJoins($params, $champs) {
343
		$j = '';
344
		// ces tests doivent correspondre aux champs générés par sqlSelectFields()
345
		// ou contraintes générées par sqlAddConstraint()
346
		if(array_key_exists('masque.famille', $params) ||
347
		   array_key_exists('famille', $champs)) {
948 raphael 348
			$j .= 'LEFT JOIN tb_eflore.bdtfx_v2_00 b ON c.flore_bdtfx_nn = b.num_nom';
854 raphael 349
		}
350
 
351
		return $j;
352
	}
353
 
861 raphael 354
	// d'un tableau de type array("coste:nn", "type_epithete")
355
	// retourne
356
	// un tableau de type array("coste:nn" => "c.num_nom", "type_epithete" => "c.type_epithete")
357
	// basé sur self::$allow_champs
358
	static function addSQLToFieldSynonym(Array $syno) {
359
		return array_intersect_key(self::$allow_champs, array_flip($syno));
360
	}
361
 
854 raphael 362
	// request handler
363
	static function requestParse(&$ressource, &$params) {
982 mathias 364
		if (isset($_SERVER['REDIRECT_URL'])) {
365
            $uri = explode('/', $_SERVER['REDIRECT_URL']);
366
        } else {
367
            $uri = explode('/', $_SERVER['REQUEST_URI']);
368
        }
854 raphael 369
		if(!empty($_SERVER['QUERY_STRING']))
370
			parse_str($_SERVER['REDIRECT_QUERY_STRING'], $params);
856 raphael 371
		$ressource = array_slice($uri, array_search('textes', $uri) + 1, 3);
854 raphael 372
	}
373
 
374
	// supprime l'index du tableau des paramètres si sa valeur ne correspond pas
375
	// au spectre passé par $values.
376
	static function unsetIfInvalid(&$var, $index, $values) {
377
		if(array_key_exists($index, $var) && !in_array($var[$index], $values))
378
			unset($var[$index]);
379
	}
380
 
381
	static function requestFilterParams(Array $params) {
382
		$p = array_intersect_key($params, array_flip(self::$allow_params));
383
		self::unsetIfInvalid($p, 'txt.format', array('txt', 'htm'));
384
		self::unsetIfInvalid($p, 'retour.format', array('min','max'));
863 raphael 385
		self::unsetIfInvalid($p, 'retour.indexBy', array('coste', 'bdtfx'));
854 raphael 386
		self::unsetIfInvalid($p, 'recherche', array('stricte','etendue','floue'));
387
 
388
		if(isset($params['masque.ns'])) $p['masque.ns'] = trim($params['masque.ns']);
389
		if(isset($params['masque.texte'])) $p['masque.texte'] = trim($params['masque.texte']);
390
 
391
		if(isset($params['masque.famille'])) {
948 raphael 392
			// mysql -N<<<"SELECT DISTINCT famille FROM bdtfx_v2_00;"|sed -r "s/(.)/\1\n/g"|sort -u|tr -d "\n"
854 raphael 393
			$p['masque.famille'] = preg_replace('/[^a-zA-Z %_]/', '', iconv("UTF-8",
394
																			"ASCII//TRANSLIT",
395
																			$params['masque.famille']));
396
		}
397
 
398
		// TODO: use filter_input(INPUT_GET);
399
		// renvoie FALSE ou NULL si absent ou invalide
400
		$p['navigation.limite'] = filter_var(@$params['navigation.limite'],
918 jpm 401
			FILTER_VALIDATE_INT,
402
			array('options' => array(
403
				'default' => NULL,
404
				'min_range' => 1,
405
				'max_range' => _COSTE_TEXTE_MAX_RESULT_LIMIT)));
854 raphael 406
		$p['navigation.depart'] = filter_var(@$params['navigation.depart'],
918 jpm 407
			FILTER_VALIDATE_INT,
408
			array('options' => array(
409
				'default' => NULL,
410
				'min_range' => 0,
411
				'max_range' => _COSTE_TEXTE_MAX_COSTE_NN)));
862 raphael 412
		$p['masque.page'] = filter_var(@$params['masque.page'],
918 jpm 413
			FILTER_VALIDATE_INT,
414
			array('options' => array(
415
				'default' => NULL,
416
				'min_range' => 0,
417
				'max_range' => _COSTE_TEXTE_MAX_COSTE_PAGE)));
862 raphael 418
		$p['masque.tome'] = filter_var(@$params['masque.tome'],
918 jpm 419
			FILTER_VALIDATE_INT,
420
			array('options' => array(
421
				'default' => NULL,
422
				'min_range' => 0,
423
				'max_range' => _COSTE_TEXTE_MAX_COSTE_TOME)));
862 raphael 424
		$p['masque.nt'] = filter_var(@$params['masque.nt'],
918 jpm 425
			FILTER_VALIDATE_INT,
426
			array('options' => array(
427
				'default' => NULL,
428
				'min_range' => 0,
429
				'max_range' => _COSTE_TEXTE_MAX_BDTFX_NT)));
854 raphael 430
 
431
		// on filtre les NULL, FALSE et '', mais pas les 0, d'où le callback()
432
		// TODO: PHP-5.3
433
		$p = array_filter($p, create_function('$a','return !in_array($a, array("",false,null),true);'));
434
		$p = array_merge(self::$default_params, $p);
435
 
436
		return $p;
437
	}
438
 
858 raphael 439
	static function requestFilterIds($uri) {
440
		if(count($uri) != 1) return NULL;
441
 
861 raphael 442
		// getNN* renvoient le num_nom passé comme segment d'URI:
443
		// - soit un id selon coste (num_nom dans coste_v2_00)
948 raphael 444
		// - soit un id selon bdtfx (num_nom dans bdtfx_v2_00)
858 raphael 445
		// ou bien l'extrait du pattern bdtfx.nn:(#id)
861 raphael 446
		$ids_coste = array_filter(array_map(array(__CLASS__, 'getNNCoste'), explode(',', $uri[0])));
447
		$ids_bdtfx = array_filter(array_map(array(__CLASS__, 'getNNBdtfx'), explode(',', $uri[0])));
858 raphael 448
 
449
		// en cas d'échec (tous les id sont invalides), bail-out
861 raphael 450
		if(!$ids_bdtfx && !$ids_coste) {
858 raphael 451
			// http_response_code(500);
452
			throw new Exception('not supported', 500);
453
		}
454
 
861 raphael 455
		return array(
918 jpm 456
			'coste' => array_slice($ids_coste, 0, intval(_COSTE_TEXTE_MAX_RESULT_LIMIT / 2) ),
457
			'bdtfx' => array_slice($ids_bdtfx, 0, intval(_COSTE_TEXTE_MAX_RESULT_LIMIT / 2) )
861 raphael 458
		);
858 raphael 459
	}
460
 
854 raphael 461
	static function aide() {
462
		header("Content-Type: text/plain; charset=utf-8");
934 raphael 463
		return sprintf("Service coste/textes:
464
 
854 raphael 465
Retourne des informations (choisies) à propos d'un taxon donné (à partir de son numéro nomenclatural
466
Retourne des informations (choisies) à propos de taxons recherchés (à partir de divers critères)
861 raphael 467
Les résultats sont indexés. La clef par défaut est le num_nom d'après coste (attribut \"coste:nn\")
934 raphael 468
Usage:  coste/textes[/<liste-num_nom>]?<params>
469
 
933 raphael 470
* le paramètre \"retour.indexBy\" affecte le mode d'indexation (\"bdtfx\" ou \"coste\" (defaut))
861 raphael 471
* <liste-num_nom> étant une liste de numéros nomenclaturaux de taxons séparés par des virgules au format:
472
 - <#id>: un numéro nomenclatural dans la base coste
473
 - <bdtfx.nn:#id>: un numéro nomenclatural dans la base bdtfx
854 raphael 474
* retour.champs une liste de champs séparés par des virgules parmi *,%s
475
* les paramètres acceptés sont les suivants: %s
476
* les champs retournés par défaut sont les suivants: %s
477
* le paramètre \"recherche\" affecte les masques \"ns\" et \"texte\"
934 raphael 478
* le paramètre \"famille\" est traité via LIKE et accepte les caractères '_' et '%%'
479
* le paramètre \"retour.format\" est inutilisé pour l'instant.
480
 
481
Exemples:
482
/service:eflore:0.1/coste/textes/bdtfx.nn:182?retour.champs=titre
483
	# retourne l'Acer monspessulanum
484
/service:eflore:0.1/coste/textes/182?retour.champs=titre
485
	# retourne la Roemeria violacea (bdtfx:nn = 56272)
486
/service:eflore:0.1/coste/textes/182,bdtfx.nn:182?retour.champs=titre
487
	# retourne les deux précédents
488
/service:eflore:0.1/coste/textes?masque.titre=Cla001Thalamiflores&retour.champs=titre
489
	# retourne la section de Coste relatives aux Thalamiflores
490
/service:eflore:0.1/coste/textes?masque.titre=Thalamiflores&recherche=floue&retour.champs=titre
491
	# idem, en utilisant une recherche floue
492
/service:eflore:0.1/coste/textes?masque.titre=Cla001Thalamiflores&retour.champs=titre&retour.indexBy=bdtfx
493
	# retourne une erreur de format car cette section de coste n'est associée à aucun taxon de la BDTFX
494
",
918 jpm 495
			implode(',', array_keys(self::$allow_champs)),
496
			implode(',', self::$allow_params),
497
			self::$default_params['retour.champs']
854 raphael 498
		);
499
	}
500
 
861 raphael 501
	static function getNNCoste($refnn) {
918 jpm 502
		if (is_numeric($refnn)) {
859 raphael 503
			$t = intval($refnn);
918 jpm 504
			if ($t >= 1 && $t < _COSTE_TEXTE_MAX_COSTE_NN) return $t;
859 raphael 505
		}
861 raphael 506
		return FALSE;
507
	}
508
 
509
	static function getNNBdtfx($refnn) {
854 raphael 510
		if(strpos($refnn, 'bdtfx.nn:') !== 0) return FALSE;
861 raphael 511
		$t = intval(str_replace('bdtfx.nn:', '', $refnn));
512
		if($t >= 1 && $t < _COSTE_TEXTE_MAX_BDTFX_NN) return $t;
513
		return FALSE;
854 raphael 514
	}
515
}