Subversion Repositories eFlore/Projets.eflore-projets

Rev

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