Subversion Repositories eFlore/Projets.eflore-projets

Rev

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