Subversion Repositories eFlore/Projets.eflore-projets

Rev

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