Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 937 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
937 raphael 1
<?php
2
/*
3
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
4
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
5
 * @copyright 2013 Tela Botanica (accueil@tela-botanica.org)
6
 */
7
 
8
abstract class CommunNomsTaxons extends Commun {
9
 
10
	/** Tableau de correspondance entre les noms des champs et les codes de l'ontologie.*/
11
	private $relationsChampsCodesOntologie = null;
12
	protected $table_retour; //Permet de stocker le tableau de résultat (non encodé en json)
13
	protected $resultat_req; // Permet de stocker le résultat de la requete principale.
14
	protected $table;// Nom de la table dans laquelle on récupèrera les données dans les requetes SQL
15
	protected $total_resultat = null;
16
	 /** Stocke le service appelé correspondant. Est utilisé principalement lors de l'affichage du href d'un synonyme
17
	  (ex id=12, basionyme num 25 est un synonyme) dans le service taxon */
18
	protected $service_href = null;
19
	protected $erreursParametres = null;
20
	protected $sans_nom_sci = array('gen','sp','ssp','fam','au_ss','bib_ss');
21
	private $bib_traitees = array();
22
 
23
	static $correspondance_champs = array();
24
	static $champs_api = array();
25
	static $compo_nom = null; //Stocke sous forme de tableau les composant du nom à ajouter au nom scientifique
26
	static $cache_ontologies = array(); // cache des ontologies
27
//+------------------------------- PARAMÈTRES ---------------------------------------------------------------+
28
 
29
	public function traiterParametres() {
30
		$this->definirParametresParDefaut();
31
		$this->verifierParametres();
32
		if (isset($this->parametres) && count($this->parametres) > 0) {
33
			foreach ($this->parametres as $param => $val) {
34
				switch ($param) {
35
					case 'ns.structure' :
36
						self::remplirTableCompositionNom($val);
37
						if (in_array($val,$this->sans_nom_sci)){
38
							$this->requete_champ = implode(', ',self::$compo_nom);
39
						}else {
40
							$this->requete_champ .= ' ,'.implode(', ',self::$compo_nom);
41
						}
42
						break;
43
					case 'navigation.depart' :
44
							$this->limite_requete['depart'] = $val;
45
						break;
46
					case 'navigation.limite' :
47
							$this->limite_requete['limite'] = $val;
48
						break;
49
				}
50
			}
51
			$this->traiterParametresSpecifiques();
52
		}
53
	}
54
 
55
	protected function definirParametresParDefaut() {
56
		if (empty($this->parametres['recherche'])) {
57
			$this->parametres['recherche'] = 'stricte';
58
		}
59
		if (empty($this->parametres['ns.format'])) {
60
			$this->parametres['ns.format'] =  'txt';
61
		}
62
		if (empty($this->parametres['retour.format'])) {
63
			$this->parametres['retour.format'] = 'max';
64
		}
65
		if (empty($this->parametres['ns.structure']) &&
66
			$this->parametres['retour.format'] != 'oss') {
67
			$this->parametres['ns.structure'] = 'au,an,bib';
68
		}
69
	}
70
 
71
 
72
	public function verifierParametres() {
73
		//$this->verifierParametresAPI();
74
 
75
		$this->verifierParametre('recherche', 'stricte|floue|etendue|complete');
76
		$this->verifierParametre('ns.format', 'htm|txt');
77
		$this->verifierParametre('retour.format', 'min|max|oss|perso');
78
		$this->verifierParametreAvecValeurMultipe('ns.structure', 'an|au|bib|ad|gen|sp|ssp|fam|au_ss|bib_ss');
79
 
80
		/*if (count($this->erreursParametres) > 0) {
81
			$m = 'Erreur dans votre requête : '.implode('<br/>', $this->erreursParametres);
82
			throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
83
		}*/
84
	}
85
 
86
	public function verifierParametresAPI() {
87
		$parametresApi = Commun::recupererTableauConfig('parametresAPI');
88
		while (!is_null($parametre = key($this->parametres))) {
89
			if (!in_array($parametre, $parametresApi)) {
90
				$this->erreursParametres[] = "Le paramètre '$parametre' n'est pas pris en compte par cette version de l'API.";
91
			}
92
			next($this->parametres);
93
		}
94
	}
95
 
96
	public function verifierParametre($parametre, $valeursPermises) {
97
		if (isset($this->parametres[$parametre]) && !empty($this->parametres[$parametre])) {
98
			$valeur = $this->parametres[$parametre];
99
			$this->verifierValeursPermises($parametre, $valeur, $valeursPermises);
100
		}
101
	}
102
 
103
	public function verifierParametreAvecValeurMultipe($parametre, $valeursPermises) {
104
		if (isset($this->parametres[$parametre]) && !empty($this->parametres[$parametre])) {
105
			$valeursConcatenees = $this->parametres[$parametre];
106
			$valeurs = explode(',', $valeursConcatenees);
107
			foreach ($valeurs as $valeur) {
108
				$this->verifierValeursPermises($parametre, $valeur, $valeursPermises);
109
			}
110
		}
111
	}
112
 
113
	private function verifierValeursPermises($parametre, $valeur, $valeursPermises) {
114
		if (!in_array($valeur, explode('|', $valeursPermises))) {
115
			$this->erreursParametres[] = "Le paramètre '$parametre' ne peut pas prendre la valeur '$valeur'. Valeurs permises : $valeursPermises";
116
		}
117
	}
118
 
119
	public function ajouterFiltreMasque($nom_champ, $valeur) {
120
		$orig_val = $valeur;
121
		$valeur = explode(',',$valeur);
122
		$conditions = array();
123
		if ($nom_champ == 'annee' || $nom_champ == 'rang') {
124
			foreach ($valeur as $val) {
125
				 $conditions[] = "$nom_champ = ".$this->getBdd()->proteger($val);
126
			}
127
		} else {
128
			if ($this->parametres['recherche'] == 'etendue') {
129
				foreach ($valeur as $val) {
130
					$val = self::preparerChainePourRechercheEtendue(self::remplacerCaractereHybrideEtChimere($val));
131
					$conditions[] = "$nom_champ LIKE ".$this->getBdd()->proteger($val);
132
				}
133
 
134
			} elseif ($this->parametres['recherche'] == 'floue') {
135
				foreach ($valeur as $val) {
136
					$val = $this->getBdd()->proteger($val);
137
					$conditions[] = "( SOUNDEX($nom_champ) = SOUNDEX($val))".
138
											" OR ( SOUNDEX(REVERSE($nom_champ)) = SOUNDEX(REVERSE($val)))";
139
				}
140
				// utile pour la détermination à partir d'un nom retenu (concat(nom_sci,auteur)) lors
141
				// d'un import depuis le CEL
142
			} elseif ($this->parametres['recherche'] == 'concat' && $nom_champ == 'nom_sci') {
143
				$conditions[] = "CONCAT(nom_sci, ' ', auteur) = " . $this->getBdd()->proteger($orig_val);
144
 
145
			} else {
146
				foreach ($valeur as $val) {
147
					$conditions[] = "$nom_champ LIKE ".$this->getBdd()->proteger($val);
148
				}
149
			}
150
		}
151
		$this->requete_condition[]= '('.implode(' OR ', $conditions ).')';
152
		$this->masque[$nom_champ] = $nom_champ.'='.implode(',',$valeur);
153
	}
154
 
155
	static function remplacerCaractereHybrideEtChimere($valeur) {
156
		return str_replace(array('×', '%D7', '+', '%2B'),
157
						   array('x ','x ', '+', '+'),
158
						   $valeur);
159
	}
160
 
161
	static function preparerChainePourRechercheEtendue($valeur) {
162
		return str_replace(' ', '% ', trim($valeur)) . '%';
163
	}
164
 
165
	//+-------------------------------Fonctions d'analyse des ressources-------------------------------------+
166
	public function traiterRessources() {
167
		if (isset($this->ressources) && count($this->ressources) > 0) {
168
			if ($this->ressources[0] == 'relations') {
169
				$this->traiterRessourceRelations();
170
			} elseif ($this->estUnIdentifiant($this->ressources[0])) { //l'identifiant peut etre de type /#id ou /nt:#id
171
				$this->traiterRessourcesIdentifiant(); // dans le service noms ou taxons
172
			} elseif ($this->ressources[0] == 'stats') { //ressource = noms/stats
173
				$this->traiterRessourcesStats();
174
			} else {
175
				$e = 'Erreur dans votre requete </br> Ressources disponibles : <br/>
176
					 <li> /'.$this->service.'/#id (id : L\'identifiant du nom rechercher)</li>
177
					 <li> /'.$this->service.'/nt:#id (id : Numero du taxon recherche)</li>
178
					 <li> /'.$this->service.'/stats </li>';
179
				throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
180
			}
181
		}
182
	}
183
 
184
	public function traiterRessourcesStats() {
185
		$this->format_reponse = $this->service.'/stats';
186
 
187
		$e = "Erreur dans votre requête </br> Ressources disponibles : $this->service/stats/[annees|rangs|initiales]";
188
		if (isset($this->ressources[1]) && !empty($this->ressources[1])) {
189
			switch ($this->ressources[1]) {
190
				case 'annees' :
191
					$this->traiterRessourceStatsAnnees();
192
					break;
193
				case 'rangs' :
194
					$this->traiterRessourceStatsRangs();
195
					break;
196
				case 'initiales' :
197
					$this->traiterRessourceStatsInitiales();
198
					break;
199
				default :
200
					throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
201
					break;
202
			}
203
		} else {
204
			throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
205
		}
206
	}
207
 
208
	/** Vérifie si la première valeur de la table de ressource est un identifiant :
209
	 * un numerique ou un numéro taxonomique sous la forme nt:xx */
210
	static function estUnIdentifiant($uripart) {
211
		return (is_numeric($uripart) || (strrpos($uripart,'nt:') !== false
212
				&& is_numeric(str_replace('nt:','',$uripart))));
213
	}
214
 
215
	//+------------------------------------------------------------------------------------------------------+
216
	// Fonction d'analyse des parametres
217
 
218
	/** Permet de remplir le tableau compo_nom. Il comprendra en fct du paramètre ns.structure les éléments à rajouter
219
	 * au nom_sci (annee, auteur, biblio ou addendum). */
220
	static function remplirTableCompositionNom($valeur) {
221
		$structure_nom = explode(',', $valeur);
222
 
223
		foreach ($structure_nom as $structure) {
224
			$structure = trim($structure);
225
			$patterns = array('/^an$/', '/^au$/', '/^bib$/', '/^ad$/', '/^sp$/', '/^gen$/', '/^ssp$/','/^fam$/',
226
							  '/^au_ss$/','/^bib_ss$/');
227
			$champs = array('annee', 'auteur', 'biblio_origine', 'nom_addendum', 'epithete_sp', 'genre',
228
							'epithete_infra_sp','famille','auteur', 'biblio_origine');
229
 
230
			// avec str_replace() 'sp' est inclu dans 'ssp', et la conversion pour 'ssp' est mauvaise
231
			self::$compo_nom[$structure] = preg_replace($patterns, $champs, $structure);
232
		}
233
	}
234
 
235
	public function mettreAuFormat() {
236
		if ($this->parametres['ns.format'] == 'htm') {
237
			if (strrpos($this->requete_champ, 'nom_sci_html as nom_sci') === false) {
238
				$this->requete_champ = str_replace('nom_sci', 'nom_sci_html as nom_sci', $this->requete_champ);
239
			}
240
		}
241
	}
242
 
243
	//+------------------------------------------------------------------------------------------------------+
244
	// Fonctions de formatage
245
	public function formaterEnOss($resultat) {
246
		$table_nom = array();
247
		$oss = '';
248
		foreach ($resultat as $tab) {
249
			if (isset($tab['nom_sci']) ) {
250
				if (!in_array($tab['nom_sci'], $table_nom)) {
251
					$table_nom[] = $tab['nom_sci'];
252
					$oss[] = $tab['nom_sci'].' '.self::ajouterCompositionNom($tab, $this->parametres['ns.format'], $this->bib_traitees);
253
				}
254
			}else {
255
				$res = self::ajouterCompositionNom($tab, $this->parametres['ns.format'], $this->bib_traitees);
256
				if($res) {
257
					$oss[] = $res;
258
				}
259
			}
260
 
261
		}
262
 
263
		if (isset($this->masque)) $masque = implode('&', $this->masque);
264
		else $masque = 'Pas de masque';
265
		$table_retour_oss = array($masque, $oss);
266
		return $table_retour_oss;
267
	}
268
 
269
	public function afficherEnteteResultat($url_service) {
270
		$this->table_retour['depart'] = $this->limite_requete['depart'];
271
		$this->table_retour['limite'] = $this->limite_requete['limite'];
272
		$this->table_retour['total']  = $this->total_resultat;
273
		$url = $this->formulerUrl($this->total_resultat, $url_service);
274
		if (isset($url['precedent']) && $url['precedent'] != '') {
275
			$this->table_retour['href.precedent'] = $url['precedent'];
276
		}
277
		if (isset($url['suivant']) && $url['suivant']   != '') {
278
			$this->table_retour['href.suivant']   = $url['suivant'];
279
		}
280
	}
281
 
282
	public function afficherNomHrefRetenu($tab, $num) {
283
		$this->resultat_req = $tab;
284
		$this->afficherDonnees('num_nom', $num);
285
		if ($this->parametres['retour.format'] == 'min') { // sinon est affiché ds afficherDonnees(num_nom, $val) ci-dessus
286
			 $this->table_retour['nom_sci'] = $tab['nom_sci'];
287
			 $this->table_retour['nom_sci_complet'] = $tab['nom_sci'].' '.self::ajouterCompositionNom($tab, $this->parametres['ns.format'], $this->bib_traitees);
288
		}
289
		if ($tab['num_nom_retenu'] != '') {
290
			$retenu = ($tab['num_nom_retenu'] == $num) ? 'true' : 'false';
291
		} else {
292
			$retenu = 'absent';
293
		}
294
		$this->table_retour['retenu'] = $retenu;
295
		// Pourquoi ce unset ? JPM - 28-03-2013
296
		unset($this->table_retour['id']);
297
	}
298
 
299
 
300
	//+------------------------------------------------------------------------------------------------------+
301
	// Fonction de formatage pour les services /#id/
302
 
303
	public function formaterId($resultat) {
304
		self::$correspondance_champs = Commun::recupererTableauConfig('correspondance_champs');
305
		foreach (self::$correspondance_champs as $key => $val) {
306
			preg_match('/(hybride[.]parent_0[12](?:[.]notes)?|nom_sci[.][^.]+|[^.]+)(?:[.](id|code))?/', $val, $match);
307
			self::$champs_api[$key] = $match[1];
308
		}
309
 
310
		$this->resultat_req = $resultat;
311
 
312
		foreach ($resultat as $cle => $valeur) {
313
			if ($valeur != '') {
314
				$this->afficherDonnees($cle, $valeur);
315
			}
316
		}
317
		if (isset($this->parametres['retour.champs']) && $this->format_reponse == 'noms/id') {
318
			$retour = $this->table_retour;
319
			$this->table_retour = array();
320
			$champs = explode(',', $this->parametres['retour.champs']);
321
			self::ajouterChampsPersonnalises($champs, $retour, $this->champs_table, $this->table_retour, $this->resultat_req);
322
		}
323
		unset($this->table_retour['href']);
324
		return $this->table_retour;
325
	}
326
 
327
	public function formaterIdChamp($resultat) {
328
		self::$correspondance_champs = Commun::recupererTableauConfig('correspondance_champs');
329
		foreach (self::$correspondance_champs as $key => $val) {
330
			preg_match('/(hybride[.]parent_0[12](?:[.]notes)?|nom_sci[.][^.]+|[^.]+)(?:[.](id|code))?/', $val, $match);
331
			self::$champs_api[$key] = $match[1];
332
		}
333
 
334
		$reponse_id = $this->formaterId($resultat);
335
		$this->table_retour = array();
336
		$champs = explode(' ', $this->ressources[1]);
337
		self::ajouterChampsPersonnalises($champs, $reponse_id, $this->champs_table, $this->table_retour, $this->resultat_req);
338
		return $this->table_retour;
339
	}
340
 
341
	static function ajouterChampsPersonnalises($champs, $reponse_id, $champs_table, &$retour, $resultat_req) {
342
		$champs_a_libeller = array('nom_retenu', 'rang', 'basionyme', 'hybride', 'hybride.parent_01',
343
			 'hybride.parent_02', 'presence', 'tax_sup', 'statut_origine', 'statut_culture', 'statut_introduction');
344
		if (! is_null($champs) && is_array($champs) && count($champs) > 0) {
345
			foreach ($champs as $champ) {
346
				if (! self::verifierValiditeChamp($champ, $champs_table)) continue;
347
 
348
				if (strrpos($champ, '.*') !== false) {
349
					self::afficherPointEtoile($champ, $reponse_id, $retour, $resultat_req);
350
				} elseif (in_array($champ, $champs_a_libeller)) {
351
					$retour[$champ.'.libelle'] =
352
						(isset($reponse_id[$champ.'.libelle'])) ? $reponse_id[$champ.'.libelle'] : null;
353
				} else {
354
					$champ_bdd = self::trouverChampBddCorrespondant($champ);
355
					$retour[$champ_bdd] = isset($reponse_id[$champ_bdd]) ? $reponse_id[$champ_bdd] : null;
356
				}
357
			}
358
		}
359
	}
360
 
361
	static function afficherPointEtoile($champ, $reponse, &$retour, $resultat_req) {
362
		preg_match('/^([^.]+\.)\*$/', $champ, $match);
363
		if ($match[1] == 'nom_sci') {
364
			self::afficherNomSciPointEpithete($resultat_req, $retour);
365
		} else {
366
			foreach ($reponse as $chp => $valeur) {
367
				if (strrpos($chp, $match[1]) !== false) {
368
					if ($valeur != '') {
369
						$retour[$chp] = $valeur;
370
					} else {
371
						$retour[$chp] = null;
372
					}
373
				}
374
			}
375
		}
376
	}
377
 
378
	static function verifierValiditeChamp($champ, $champs_table) {
379
		if (! preg_match('/^(?:([^.]+\.parent_0[12]|[^.]+))(?:\.(.+))?$/', $champ, $match)) {
380
			return true;
381
		}
382
		// decomposerNomChamp()
383
		$radical = $match[1];
384
		$suffixe = isset($match[2]) ? $match[2] : "";
385
 
386
		$champs_complementaire = array('nom_retenu_complet', 'basionyme_complet');
387
		// on verifie si le nom du champ existe bien
388
		$champs_complementaire2 = array_diff($champs_table, array_keys(self::$champs_api)); // XXX
389
		if (! self::estChampApi($radical) && ! in_array($radical_champ, $champs_complementaire2)) {
390
			if (!in_array($radical, $champs_complementaire)) {
391
				throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, 'Le champ "'.$radical.'" n\'existe pas dans la base. <br/><br/>');
392
				return FALSE;
393
			}
394
		} elseif (self::estUnPoint($champ)) {
395
			return self::verifierValiditeSuffixe($suffixe, $radical);
396
		}
397
 
398
		return TRUE;
399
	}
400
 
401
	static function estChampApi($radical_champ) {
402
		$champ_api_ok = false;
403
		if (in_array($radical_champ, self::$champs_api) || in_array($radical_champ, self::$correspondance_champs)) {
404
			$champ_api_ok = true;
405
		}
406
		return $champ_api_ok;
407
	}
408
 
409
	static function verifierValiditeSuffixe($suffixe, $radical_champ) {
410
		$validite_ressource = true;
411
		if (self::correspondAUnId($radical_champ) || $radical_champ == 'id') {
412
			self::verificationSuffixesIdentifiant($suffixe, $radical_champ, $validite_ressource);
413
		} elseif (self::correspondAUnCode($radical_champ)) {
414
			if (!in_array($suffixe, array('*', 'code', 'href', 'details'))) {
415
				throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'.<br/> Les suffixes possibles sont les suivants : <li> .* </li><li> .code </li><li> .href </li><li> .details </li>');
416
			}
417
		} elseif ($radical_champ == 'nom_sci') {
418
			if ($suffixe != '*') {
419
				$validite_ressource = false;
420
				$m = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/>
421
					Les suffixes possibles sont les suivants : <li> * </li>';
422
				throw new Exception( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
423
			}
424
		} else {
425
			$validite_ressource = false;
426
			$m = 'Erreur : Le paramètre "'.$radical_champ.'" ne peut pas présenter de suffixe. <br/><br/>';
427
			throw new Exception( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
428
		}
429
		return $validite_ressource;
430
	}
431
 
432
 
433
	static function verificationSuffixesIdentifiant(&$suffixe, &$radical_champ, &$validite_ressource) {
434
		if ((strrpos($radical_champ, 'parent') !== false && !in_array($suffixe, array('*', 'id', 'href', 'details', 'notes')))
435
			|| !in_array($suffixe, array('*', 'id', 'href', 'details')) && strrpos($radical_champ, 'parent') === false) {
436
			$validite_ressource = false;
437
			$e = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/> Les suffixes '
438
				.'possibles sont les suivants : <li> .* </li><li> .id </li><li> .href </li><li> .details </li>'
439
				.'<li> .notes (seulement pour les hybride.parent)';
440
			throw new Exception( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
441
		}
442
	}
443
 
444
 
445
//------------------------------fonction de formatage pour les services /stats/-----------------------------------------
446
	public function formaterStatsInitiales($resultat) {
447
		$rang = null;
448
		$table_rang = array();
449
		foreach ($resultat as $tuple) {
450
			if ($tuple['rang'] != 0) {
451
				$this->memoriserRang($table_rang, $tuple, $rang);
452
				if ($tuple['lettre'] == 'x ') {
453
					self::ajouterHybrideChimere('hybride', $this->retour[$rang], $tuple);
454
				} elseif ($tuple['lettre'] == '+ ') {
455
					self::ajouterHybrideChimere('chimere', $this->retour[$rang], $tuple);
456
				} else {
457
					$l = substr($tuple['lettre'], 0, 1);
458
					if (isset($this->table_retour[$rang][$l])) {
459
						$this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] += floatval($tuple['nb']);
460
					} else {
461
						$this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] = floatval($tuple['nb']);
462
					}
463
				}
464
			}
465
		}
466
		return $this->table_retour;
467
	}
468
 
469
	public function memoriserRang(&$table_rang, $tuple, &$rang) {
470
		if (is_array($table_rang)) {
471
			if (!in_array($tuple['rang'], $table_rang)) {
472
				$rang = $tuple['rang'];
473
				$table_rang[] = $rang;
474
				if ($this->parametres['retour.format'] == 'max') {
475
					$rang = self::ajouterSignificationCode('rang', $rang, $this->getBdd());
476
				}
477
			}
478
		}
479
	}
480
 
481
	static function ajouterHybrideChimere($groupe, &$tab, &$tuple) {
482
		if (isset($tab[str_replace('hybride', 'hyb', $groupe)])) {
483
			$tab[$groupe] += floatval($tuple['nb']);
484
		} else {
485
			$tab[$groupe] = floatval($tuple['nb']);
486
		}
487
	}
488
 
489
	//-----------------------------Fonctions d'affichage utiliser dans les fonctions de formatage---------------------------
490
 
491
	public function afficherDonnees($champApi, $valeur) {
492
		$champBdd = self::trouverChampBddCorrespondant($champApi);
493
 
494
		if ($this->parametres['retour.format'] == 'min') {
495
			if ($champApi == 'nom_sci') {
496
				$valeur = $valeur.' '.self::ajouterCompositionNom($this->resultat_req, $this->parametres['ns.format'], $this->bib_traitees);
497
			}
498
			if ($champApi == 'nom_sci_html') {
499
				$valeur = $valeur.' '.self::ajouterCompositionNom($this->resultat_req, 'htm', $this->bib_traitees);
500
			}
501
			$this->table_retour[$champBdd] = $valeur;
502
			// on essaye de permettre l'obtention du nom_sci_complet, y compris en retour.format == 'min',
503
			// tout en évitant les appels aux ontologies
504
			/*if ($this->correspondAUnId($champBdd) || $champBdd == 'id' && $valeur != '0') {
505
				preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $champBdd, $match);
506
				if(strpos($this->parametres['retour.format'], $match[1]) !== false) $this->afficherSignification($match[1], $valeur);
507
				}*/
508
		} else {
509
			$this->afficherToutesLesInfos($champBdd, $valeur);
510
		}
511
	}
512
 
513
	static function trouverChampBddCorrespondant($champApi) {
514
		if (array_key_exists($champApi, self::$champs_api)) {
515
			$champBdd = self::$correspondance_champs[$champApi];
516
		} else {
517
			$champBdd = $champApi;
518
		}
519
		return $champBdd;
520
	}
521
 
522
	public function afficherToutesLesInfos($nom_champ_api, $valeur) {
523
		if ($this->presentePlusieursId($nom_champ_api, $valeur)) {
524
			preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
525
			$this->afficherInfosPrecises($match[1], 'details', $valeur, $this->table_retour);
526
			$this->table_retour[$nom_champ_api] = $valeur;
527
 
528
		} elseif (strrpos($nom_champ_api, 'parent') !== false && strrpos($nom_champ_api, 'notes') !== false) {
529
			$this->table_retour[$nom_champ_api] = $valeur;
530
 
531
		} elseif ((self::correspondAUnId($nom_champ_api) || $nom_champ_api == 'id' && $valeur != '0')) {
532
			preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
533
			$this->afficherInfosPrecises($match[1], 'id,href', $valeur, $this->table_retour);
534
			self::afficherSignification($match[1], $valeur, $obj->resultat_req, $this->table_retour, $this->getBdd(), $this);
535
 
536
		} elseif (self::correspondAUnCode($nom_champ_api)) {
537
			preg_match('/^([^.]+)(?:\.code)?$/', $nom_champ_api, $match);
538
			$this->afficherInfosPrecises($match[1], 'code,href', $valeur, $this->table_retour);
539
			self::afficherSignification($match[1], $valeur, $obj->resultat_req, $this->table_retour, $this->getBdd(), $this);
540
 
541
		} elseif ($nom_champ_api == 'nom_sci_html') {
542
			$this->table_retour['nom_sci_html'] = $valeur;
543
			$this->table_retour['nom_sci_html_complet'] = $valeur.' '.self::ajouterCompositionNom($this->resultat_req, 'htm', $this->bib_traitees);
544
		} elseif ($nom_champ_api != 'nom_sci') {
545
			$this->table_retour[$nom_champ_api] = $valeur;
546
		}
547
	}
548
 
549
	public function presentePlusieursId($ressource, $valeur = null) {
550
		if ($valeur) {
551
			$presente = strrpos($ressource, 'proparte') !== false && strrpos($valeur, ',') !== false;
552
		} else { //pour la vérification du champ, on ignore alors la valeur de la ressource
553
			$presente = strrpos($ressource, 'proparte') !== false;
554
		}
555
		return $presente;
556
	}
557
 
558
	public function afficherInfosPrecises($champ, $suffixe, $valeur, &$retour) {
559
		$suffixes = explode(',', $suffixe);
560
		//on initialise au service appelé. Sera potentiellement modifié dans la fonction afficherSignification()
561
		$this->service_href = $this->service;
562
		foreach ($suffixes  as $suffixe) {
563
			switch ($suffixe) {
564
				case 'id' 			 :
565
					$retour[str_replace('id.id', 'id', $champ.'.id')] = $valeur;
566
					break;
567
				case 'details' 		 :
568
					$tab_id = explode(',', $valeur);
569
					$tab_res = $retour;
570
					$retour = array();
571
					foreach ($tab_id as $id) {
572
						$this->afficherInfosPrecises($champ, 'id,signification,href', $id, $retour);
573
						$tab_res[$champ.'.details'][] = $retour;
574
						$retour = array();
575
					}
576
					$retour = $tab_res;
577
					break;
578
				case 'href' 		 :
579
					$retour[str_replace('id.href', 'href', $champ.'.href')] = self::creerUrl($champ, $valeur, $this->version_projet);
580
					break;
581
				case 'code' 		 :
582
					$retour[$champ.'.code'] = "bdnt." . self::transformerChampEnCode($champ) . ":$valeur";
583
					break;
584
				case 'notes' 		 :
585
					$retour[$champ.'.notes'] = $this->resultat_req[str_replace('.', '_', $champ).'_notes'];
586
					break;
587
				default : break;
588
			}
589
		}
590
	}
591
 
592
	static function transformerChampEnCode($champ) {
593
		static $tab;
594
		$tab = Outils::recupererTableauConfig('ChampsCodesOntologie');
595
		if (!array_key_exists($champ, $tab)) return $champ;
596
		return $tab[$champ];
597
	}
598
 
599
	static function creerUrl($champ, $valeur, $version_projet) {
600
		if (self::correspondAUnId($champ) || $champ == 'id') {
601
			$service = $this->service_href;
602
			$url = self::s_ajouterHref($service, $valeur, $version_projet);
603
		} else {
604
			$code = self::transformerChampEnCode($champ);
605
			$url = self::ajouterHrefAutreProjet('ontologies', "$code:", $valeur, 'bdnt');
606
		}
607
		return $url;
608
	}
609
 
610
	static function afficherSignification($champ, $valeur, $resreq, &$retour, $db, $obj) {
611
		$fmt = $obj->parametres['ns.format'];
612
 
613
		if ($champ == 'id' && isset($resreq['nom_sci']) && $resreq['num_nom'] == $valeur) {
614
			//si le nom_sci du num_nom que l'on veut afficher est déjà dans la table de résultat :
615
			$retour['nom_sci'] = $resreq['nom_sci'];
616
			$retour['nom_sci_complet'] = $resreq['nom_sci'] . (($suff = self::ajouterCompositionNom($resreq, $fmt, $obj->bib_traitees)) ? ' ' . $suff : '');
617
			return ;
618
		}
619
 
620
		if (self::correspondAUnCode($champ)) {
621
			$retour[$champ.'.libelle'] = self::ajouterSignificationCode($champ, $valeur, $db);
622
			return ;
623
		}
624
 
625
		if (self::correspondAUnId($champ) || $champ == 'id') {
626
			// $nom = $obj->recupererNomSci($valeur);
627
			$id = $valeur;
628
 
629
			$nom = array();
630
			if ($id != 0) {
631
				if (self::$compo_nom == null) {
632
					$req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html FROM '.$obj->table.' WHERE num_nom = '.$id;
633
				} else { //on ajoute à la requete sql, les champs de ns.structure
634
					//print_r(self::$compo_nom);
635
					$req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html, '.implode(', ', self::$compo_nom)
636
						.' FROM '.$obj->table
637
						.' WHERE num_nom = '.$id;
638
				}
639
				if ($fmt == 'htm') {
640
					$req = str_replace('nom_sci', 'nom_sci_html as nom_sci', $req);
641
				}
642
				$res = $db->recuperer($req . ' -- ' . __FILE__ . ':' . __LINE__);
643
				if ($res) {
644
					$nom['nom_sci']	= $res['nom_sci'];
645
					$nom['nom_sci_html'] = $res['nom_sci_html'];
646
					$nom['nom_sci_complet'] = $res['nom_sci'].' '.self::ajouterCompositionNom($res, $fmt, $obj->bib_traitees);
647
					$nom['nom_sci_complet_html'] = $res['nom_sci_html'].' '.self::ajouterCompositionNom($res, 'htm', $obj->bib_traitees);
648
					$nom['service'] = ($res['num_nom_retenu'] == $id && $obj->service == 'taxons') ? 'taxons' : 'noms';
649
				}
650
			}
651
 
652
 
653
			if ($nom != array()) {
654
				$retour[$champ.'.libelle'] = $nom['nom_sci'];
655
				$retour[$champ.'_html'] = $nom['nom_sci_html'];
656
				$retour[$champ.'_complet'] = $nom['nom_sci_complet'];
657
				$retour[$champ.'_html_complet'] = $nom['nom_sci_complet_html'];
658
				$obj->service_href = $nom['service'];
659
			}
660
		}
661
	}
662
 
663
	/** Permet d'afficher les élements nomenclatural du nom_sci lors de l'appel dans le service noms/id/champ du champ^nom_sci.*/
664
	static function afficherNomSciPointEpithete($resultat, &$retour) {
665
		$tab_nom_sci   = array('nom_supra_generique', 'genre', 'epithete_infra_generique', 'epithete_sp',
666
							   'type_epithete', 'epithete_infra_sp', 'cultivar_groupe', 'cultivar', 'nom_commercial');
667
		foreach ($tab_nom_sci as $compo_nom) {
668
			if (isset($resultat[$compo_nom]) && !empty($resultat[$compo_nom])) {
669
				$table_retour['nom_sci.'.$compo_nom] = $resultat[$compo_nom];
670
			}
671
		}
672
	}
673
 
674
	static function ajouterSignificationCode($champ, $valeur, $db) {
675
		// ontologie/cache
676
		if(array_key_exists($champ, self::$cache_ontologies) && array_key_exists($valeur, self::$cache_ontologies[$champ])) {
677
			$nom_code = self::$cache_ontologies[$champ][$valeur];
678
		} else {
679
			$code = self::transformerChampEnCode($champ);
680
			if (preg_match('/^([^_-]+)(?:_|-)([^_-]+)$/', $code, $match)) {
681
				$code = $match[1].ucfirst($match[2]);
682
			}
683
			$requete = sprintf('SELECT * FROM %1$s WHERE id IN (SELECT id FROM %1$s WHERE code = "%2$s" AND classe_id = (SELECT id FROM %1$s WHERE code = "%3$s")) LIMIT 0, 100 -- %4$s:%5$s',
684
							   Config::get('bdd_table_ontologies'), $valeur, $code, __FILE__,  __LINE__);
685
			$res = $db->recuperer($requete);
686
			$nom_code = $valeur;
687
			if (is_array($res)) {
688
				$nom_code = $res['nom'];
689
			}
690
			// cache
691
			self::$cache_ontologies[$champ][$valeur] = $correspondance;
692
		}
693
		return $nom_code;
694
	}
695
 
696
	/** Permet de retourner une chaine de caractère composée des parametres du nom (ns.structure : annnée, auteur,
697
	 * bibilio et addendum). A ajouter au nom scientifique */
698
	static function ajouterCompositionNom($tab_res, $format, &$bib_traitees) {
699
		if(!self::$compo_nom) return '';
700
 
701
		if ($format == 'htm') {
702
			$format = array(
703
				'au' => '<span class="auteur">%s</span>',
704
				'an' => '[<span class="annee">%s</span>]',
705
				'an_bib' => '[<span class="annee">%s</span>, <span class="biblio">%s</span>]',
706
				'bib' => '[<span class="biblio">%s</span>]',
707
				'ad' => '[<span class="adendum">%s</span>]');
708
		} else {
709
			$format = array(
710
				'au' => '%s',
711
				'an' => '[%s]',
712
				'an_bib' => '[%s, %s]',
713
				'bib' => '[%s]',
714
				'ad' => '[%s]',
715
				'gen' => '%s',
716
				'sp' => '%s',
717
				'ssp' => '%s',
718
				'fam' => '%s',
719
				'au_ss' => '%s',
720
				'bib_ss' => '%s');
721
		}
722
		$compo_nom_arr = array();
723
		foreach (self::$compo_nom as $key => $champ) {
724
			if (isset($tab_res[$champ]) && !empty($tab_res[$champ])) {
725
				$compo_nom_arr[$key] = $tab_res[$champ];
726
			}
727
		}
728
		return rtrim(implode(' ', self::formerNomComplet($compo_nom_arr, $format, $bib_traitees)), ' ');
729
	}
730
 
731
 
732
	static function formerNomComplet($compo_nom_arr, $format, &$bib_traitees) {
733
		$nom_complet = array();
734
		extract($compo_nom_arr);
735
		if (isset($au)) $nom_complet[] = sprintf($format['au'], $au);
736
		if (isset($an)) {
737
			if (isset($bib)) {
738
				$nom_complet[] = sprintf($format['an_bib'], $an, $bib);
739
			} else {
740
				$nom_complet[] = sprintf($format['an'], $an);
741
			}
742
		} elseif (isset($bib)) {
743
			$nom_complet[] = sprintf($format['bib'], $bib);
744
		}
745
		if (isset($ad)) $nom_complet[] = sprintf($format['ad'], $ad);
746
		if (isset($gen)) $nom_complet[] = sprintf($format['gen'], $gen);
747
		if (isset($ssp)) $nom_complet[] = sprintf($format['ssp'], $ssp);
748
		if (isset($sp)) $nom_complet[] = sprintf($format['sp'], $sp);
749
		if (isset($fam)) $nom_complet[] = sprintf($format['fam'], $fam);
750
		if (isset($au_ss)) $nom_complet[] = sprintf($format['au_ss'], $au_ss);
751
		if (isset($bib_ss)) {
752
			$bibl = self::tronquerBiblio($bib_ss);
753
			//simule un 'select distinct' sur les biblio tronquées
754
			if (!isset($bib_traitees[$bibl])) {
755
				$nom_complet[] = sprintf($format['bib_ss'],$bibl );
756
				$bib_traitees[$bibl] = 1;
757
			}
758
		}
759
		return $nom_complet;
760
	}
761
 
762
	static function tronquerBiblio($valeur){
763
		$bib = '';
764
		if(strpos($valeur,',') !== false) {
765
			$bib = explode(',',$valeur);
766
		}
767
		if(strpos($bib[0],';') !== false) {
768
			$bib[0] = strstr($bib[0],';');
769
			$bib[0] = str_replace('; ','',$bib[0]);
770
		}
771
		return $bib[0];
772
	}
773
 
774
 
775
 
776
	static function correspondAUnCode($key) {
777
		return strrpos($key, '.code') !== false || in_array($key.'.code', self::$correspondance_champs);
778
	}
779
 
780
	static function correspondAUnId($key) {
781
		return strrpos($key, '.id') !== false || in_array($key.'.id', self::$correspondance_champs);
782
	}
783
 
784
	static function estUnPoint($key) {
785
		if (strrpos($key, 'hybride.parent') !== false) {
786
			$key = str_replace('hybride.parent', 'hybride_parent', $key);
787
		}
788
		return (strrpos($key, '.') !== false);
789
	}
790
 
791
	public function recupererMasquePrincipal() {
792
		$masque = null;
793
		$tab_masque   = array(
794
			'masque' => 'nom_sci',
795
			'masque_sg' => 'nom_supra_generique',
796
			'masque_gen' => 'genre',
797
			'masque_sp' => 'epithete_sp',
798
			'masque_ssp' => 'epithete_infra_sp',
799
			'masque_au' => 'auteur',
800
			'masque_an' => 'annee',
801
			'masque_bib' => 'biblio_origine',
802
			'masque_ad' => 'addendum',
803
			'masque_rg' => 'rang');
804
		$liste_masque = array();
805
 
806
		if (isset($this->masque['num_nom'])) {
807
			$liste_masque[] = $this->masque['num_nom'];
808
		}
809
 
810
		foreach ($tab_masque as $key => $filtre) {
811
            if (isset($this->masque[$filtre])) {
812
            	if (!isset($masque) && !in_array($filtre, array('rang', 'annee'))) {
813
            		$masque = array($key, $filtre);
814
            	}
815
                $liste_masque[] = $this->masque[$filtre];
816
            }
817
        }
818
        $this->masque = $liste_masque;
819
        return $masque;
820
	}
821
}