Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 91 | Rev 112 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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