Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 358 | Rev 562 | 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;
363 delphine 388
			$champs_complementaire = array('nom_retenu_complet', 'basionyme_complet');
3 jpm 389
			// on verifie si le nom du champ existe bien
390
			if (!$this->estChampApi($radical) && !$this->estChampComplementaire($radical)) {
363 delphine 391
				if (!in_array($radical, $champs_complementaire)) {
392
					$validite_ressource = false;
393
					$e = 'Le champ "'.$radical.'" n\'existe pas dans la base. <br/><br/>';
394
					$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
395
				}
3 jpm 396
			} elseif ($this->estUnPoint($champ)) {
397
				$validite_ressource = $this->verifierValiditeSuffixe($suffixe, $radical);
398
			}
399
		}
400
		return $validite_ressource;
401
	}
402
 
403
	public function estChampApi($radical_champ) {
404
		$champ_api_ok = false;
405
		if (in_array($radical_champ, $this->champs_api) || in_array($radical_champ, $this->correspondance_champs)) {
406
			$champ_api_ok = true;
407
		}
408
		return $champ_api_ok;
409
	}
410
 
411
	public function estChampComplementaire($radical_champ) {
412
		$champ_complementaire_ok = in_array($radical_champ, $this->champs_comp) ? true : false;
413
		return	$champ_complementaire_ok;
414
	}
415
 
416
	public function verifierValiditeSuffixe($suffixe, $radical_champ) {
417
		$validite_ressource = true;
418
		if ($this->correspondAUnId($radical_champ) || $radical_champ == 'id') {
419
			$this->verificationSuffixesIdentifiant($suffixe, $radical_champ, $validite_ressource);
420
		} elseif ($this->correspondAUnCode($radical_champ)) {
421
			$this->verificationSuffixesCodes($suffixe, $radical_champ, $validite_ressource);
422
		} elseif ($radical_champ == 'nom_sci') {
423
			if ($suffixe != '*') {
424
				$validite_ressource = false;
425
				$m = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/>
426
					Les suffixes possibles sont les suivants : <li> * </li>';
427
				$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
428
			}
429
		} else {
430
			$validite_ressource = false;
431
			$m = 'Erreur : Le paramètre "'.$radical_champ.'" ne peut pas présenter de suffixe. <br/><br/>';
432
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
433
		}
434
		return $validite_ressource;
435
	}
436
 
437
	public function verificationSuffixesCodes(&$suffixe, &$radical_champ, &$validite_ressource ) {
438
		if (!in_array($suffixe, array('*', 'code', 'href', 'details'))) {
439
			$validite_ressource = false;
440
			$e = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'.<br/> Les suffixes '
441
				.'possibles sont les suivants : <li> .* </li><li> .code </li><li> .href </li><li> .details </li>';
442
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
443
		}
444
	}
445
 
446
	public function verificationSuffixesIdentifiant(&$suffixe, &$radical_champ, &$validite_ressource) {
447
		if ((strrpos($radical_champ, 'parent') !== false && !in_array($suffixe, array('*', 'id', 'href', 'details', 'notes')))
448
			|| !in_array($suffixe, array('*', 'id', 'href', 'details')) && strrpos($radical_champ, 'parent') === false) {
449
			$validite_ressource = false;
450
			$e = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/> Les suffixes '
451
				.'possibles sont les suivants : <li> .* </li><li> .id </li><li> .href </li><li> .details </li>'
452
				.'<li> .notes (seulement pour les hybride.parent)';
453
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
454
		}
455
	}
456
 
457
 
458
//------------------------------fonction de formatage pour les services /stats/-----------------------------------------
459
 
460
	public function formaterStatsAnnee($resultat) {
461
		foreach ($resultat as $cle_annee) {
462
			$annee = ($cle_annee['annee'] != '') ? $cle_annee['annee'] : 'ND';
463
			$nb = $cle_annee['nombre'];
464
			$retour_stats_annee[$annee] = $nb;
465
		}
466
		return $retour_stats_annee;
467
	}
468
 
469
	public function formaterStatsRang($resultat) {
470
		foreach ($resultat as $rangs) {
471
			if ($rangs['rang'] != 0) {
472
				$rang = $rangs['rang'];
473
				if ($this->parametres['retour.format'] == 'max') {
474
					$retour_rang[$rang]['rang'] = $this->ajouterSignificationCode('rang',$rang);
475
				}
476
				$nombre = $rangs['nombre'];
477
				$retour_rang[$rang]['nombre'] = $nombre;
478
			}
479
		}
480
		return $retour_rang;
481
	}
482
 
483
	public function formaterStatsInitiales($resultat) {
484
		$rang = null;
485
		$table_rang = array();
486
		foreach ($resultat as $tuple) {
487
			if ($tuple['rang'] != 0) {
488
				$this->memoriserRang($table_rang, $tuple, $rang);
489
				if ($tuple['lettre'] == 'x ') {
490
					$this->ajouterHybrideChimere('hybride', $rang, $tuple);
491
				} elseif ($tuple['lettre'] == '+ ') {
492
					$this->ajouterHybrideChimere('chimere', $rang, $tuple);
493
				} else {
494
					$l = substr($tuple['lettre'], 0, 1);
495
					if (isset($this->table_retour[$rang][$l])) {
496
						$this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] += floatval($tuple['nb']);
497
					} else {
498
						$this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] = floatval($tuple['nb']);
499
					}
500
				}
501
			}
502
		}
503
		return $this->table_retour;
504
	}
505
 
506
	public function memoriserRang(&$table_rang, $tuple, &$rang) {
507
		if (is_array($table_rang)) {
508
			if (!in_array($tuple['rang'], $table_rang)) {
509
				$rang = $tuple['rang'];
510
				$table_rang[] = $rang;
511
				if ($this->parametres['retour.format'] == 'max') {
512
					$rang = $this->ajouterSignificationCode('rang', $rang);
513
				}
514
			}
515
		}
516
	}
517
 
518
	public function ajouterHybrideChimere($groupe, &$rang, &$tuple) {
519
		if (isset($this->table_retour[$rang][str_replace('hybride', 'hyb', $groupe)])) {
520
			$this->table_retour[$rang][$groupe] += floatval($tuple['nb']);
521
		} else {
522
			$this->table_retour[$rang][$groupe] = floatval($tuple['nb']);
523
		}
524
	}
525
 
526
	//-----------------------------Fonctions d'affichage utiliser dans les fonctions de formatage---------------------------
527
 
528
	public function afficherDonnees($champApi, $valeur) {
529
		$champBdd = $this->trouverChampBddCorrespondant($champApi);
530
		if ($this->parametres['retour.format'] == 'min') {
133 aurelien 531
			if ($champApi == 'nom_sci') {
3 jpm 532
				$valeur = $valeur.$this->ajouterCompositionNom($this->resultat_req);
533
			}
325 delphine 534
			if ($champApi == 'nom_sci_html') {
535
				$valeur = $valeur.$this->ajouterCompositionNom($this->resultat_req, 'htm');
536
			}
3 jpm 537
			$this->table_retour[$champBdd] = $valeur;
538
		} else {
539
			$this->afficherToutesLesInfos($champBdd, $valeur);
540
		}
541
	}
542
 
543
	public function trouverChampBddCorrespondant($champApi) {
544
		if (array_key_exists($champApi, $this->champs_api)) {
545
			$champBdd = $this->correspondance_champs[$champApi];
546
		} else {
547
			$champBdd = $champApi;
548
		}
549
		return $champBdd;
550
	}
551
 
552
	public function afficherToutesLesInfos($nom_champ_api, $valeur) {
553
		if ($this->presentePlusieursId($nom_champ_api, $valeur)) {
554
			preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
555
			$this->afficherInfosPrecises($match[1], 'details', $valeur);
556
			$this->table_retour[$nom_champ_api] = $valeur;
557
 
558
		} elseif (strrpos($nom_champ_api, 'parent') !== false && strrpos($nom_champ_api, 'notes') !== false) {
559
			$this->table_retour[$nom_champ_api] = $valeur;
560
 
561
		} elseif (($this->correspondAUnId($nom_champ_api) || $nom_champ_api == 'id' && $valeur != '0')) {
562
			preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
563
			$this->afficherInfosPrecises($match[1], 'id,signification,href', $valeur);
564
 
565
		} elseif ($this->correspondAUnCode($nom_champ_api)) {
566
			preg_match('/^([^.]+)(?:\.code)?$/', $nom_champ_api, $match);
567
			$this->afficherInfosPrecises($match[1], 'code,signification,href', $valeur);
568
 
325 delphine 569
		} elseif ($nom_champ_api == 'nom_sci_html') {
326 delphine 570
			$this->table_retour['nom_sci_html'] = $valeur;
571
			$this->table_retour['nom_sci_html_complet'] = $valeur.$this->ajouterCompositionNom($this->resultat_req, 'htm');
325 delphine 572
		}elseif ($nom_champ_api != 'nom_sci') {
3 jpm 573
			$this->table_retour[$nom_champ_api] = $valeur;
574
		}
575
	}
576
 
577
	public function presentePlusieursId($ressource, $valeur = null) {
578
		if ($valeur) {
579
			$presente = strrpos($ressource, 'proparte') !== false && strrpos($valeur, ',') !== false;
580
		} else { //pour la vérification du champ, on ignore alors la valeur de la ressource
581
			$presente = strrpos($ressource, 'proparte') !== false;
582
		}
583
		return $presente;
584
	}
585
 
586
	public function afficherInfosPrecises($champ, $suffixe, $valeur) {
587
		$suffixes = explode(',', $suffixe);
588
		//on initialise au service appelé. Sera potentiellement modifié dans la fonction afficherSignification()
589
		$this->service_href = $this->service;
590
		foreach ($suffixes  as $suffixe) {
591
			switch ($suffixe) {
592
				case 'id' 			 :
593
					$this->table_retour[str_replace('id.id', 'id', $champ.'.id')] = $valeur;
594
					break;
595
				case 'details' 		 :
596
					$this->afficherTableDetails($champ, $valeur);
597
					break;
598
				case 'signification' :
599
					$this->afficherSignification($champ, $valeur);
600
					break;
601
				case 'href' 		 :
602
					$url = $this->creerUrl($champ, $valeur);
603
					$this->table_retour[str_replace('id.href', 'href', $champ.'.href')] = $url;
604
					break;
605
				case 'code' 		 :
606
					$this->table_retour[$champ.'.code'] = $this->obtenirCode($champ, $valeur);
607
					break;
608
				case 'notes' 		 :
609
					$this->table_retour[$champ.'.notes'] = $this->resultat_req[str_replace('.', '_', $champ).'_notes'];
610
					break;
611
				default : break;
612
			}
613
		}
614
	}
615
 
616
	public function afficherTableDetails($nom_champ_api, $valeur) {
617
		$tab_id = explode(',', $valeur);
618
		$tab_res = $this->table_retour;
619
		$this->table_retour = array();
620
		foreach ($tab_id as $id) {
621
			$this->afficherInfosPrecises($nom_champ_api, 'id,signification,href', $id);
622
			$tab_res[$nom_champ_api.'.details'][] = $this->table_retour;
623
			$this->table_retour = array();
624
		}
625
		$this->table_retour = $tab_res;
626
	}
627
 
628
	private function obtenirCode($champ, $valeur) {
629
		$code = $this->transformerChampEnCode($champ);
630
		return "bdnt.$code:$valeur";
631
	}
632
 
633
	private function transformerChampEnCode($champ) {
634
		if (is_null($this->relationsChampsCodesOntologie)) {
635
			$this->relationsChampsCodesOntologie = Outils::recupererTableauConfig('ChampsCodesOntologie');
636
		}
637
 
638
		$code = $champ;
639
		if (array_key_exists($champ, $this->relationsChampsCodesOntologie)) {
640
			$code = $this->relationsChampsCodesOntologie[$champ];
641
		}
642
		return $code;
643
	}
644
 
645
	public function creerUrl($champ, $valeur) {
646
		if ($this->correspondAUnId($champ) || $champ == 'id') {
647
			$service = $this->service_href;
648
			$url = $this->ajouterHref($service, $valeur);
649
		} else {
650
			$code = $this->transformerChampEnCode($champ);
651
			$url = $this->ajouterHrefAutreProjet('ontologies', "$code:", $valeur, 'bdnt');
652
		}
653
		return $url;
654
	}
655
 
656
	public function afficherSignification($champ, $valeur) {
657
		if ($champ == 'id' && isset($this->resultat_req['nom_sci']) && $this->resultat_req['num_nom'] == $valeur) {
658
			//si le nom_sci du num_nom que l'on veut afficher est déjà dans la table de résultat :
326 delphine 659
			$this->table_retour['nom_sci'] = $this->resultat_req['nom_sci'];
660
			$this->table_retour['nom_sci_complet'] = $this->resultat_req['nom_sci'].
3 jpm 661
				$this->ajouterCompositionNom($this->resultat_req);
662
		} elseif ($this->correspondAUnId($champ) || $champ == 'id') {
663
			$nom = $this->recupererNomSci($valeur);
664
			if ($nom != array()) {
357 delphine 665
				$this->table_retour[$champ.'.libelle'] = $nom['nom_sci'];
326 delphine 666
				$this->table_retour[$champ.'_html'] = $nom['nom_sci_html'];
667
				$this->table_retour[$champ.'_complet'] = $nom['nom_sci_complet'];
668
				$this->table_retour[$champ.'_html_complet'] = $nom['nom_sci_complet_html'];
3 jpm 669
				$this->service_href = $nom['service'];
670
			}
671
		} elseif ($this->correspondAUnCode($champ)) {
357 delphine 672
			$this->table_retour[$champ.'.libelle'] = $this->ajouterSignificationCode($champ, $valeur);
3 jpm 673
		}
674
	}
675
 
676
	/** Permet d'afficher les élements nomenclatural du nom_sci lors de l'appel dans le service noms/id/champ du champ^nom_sci.*/
677
	public function afficherNomSciPointEpithete($resultat) {
678
		$tab_nom_sci   = array('nom_supra_generique', 'genre', 'epithete_infra_generique', 'epithete_sp',
679
		'type_epithete', 'epithete_infra_sp', 'cultivar_groupe', 'cultivar', 'nom_commercial');
680
		foreach ($tab_nom_sci as $compo_nom) {
681
			if (isset($resultat[$compo_nom]) && !empty($resultat[$compo_nom])) {
682
				$this->table_retour['nom_sci.'.$compo_nom] = $resultat[$compo_nom];
683
			}
684
		}
685
	}
686
 
687
	public function ajouterSignificationCode($champ, $valeur) {
688
		$champ = ($champ == 'rang') ? 'rangTaxo' : rtrim($champ, '_Co,_Ga');
689
		if (preg_match('/^([^_-]+)(?:_|-)([^_-]+)$/', $champ, $match)) {
690
			$champ = $match[1].ucfirst($match[2]);
691
		}
692
		$url = Config::get('url_ontologie').$champ.':'.$valeur.'/nom';
693
		$res = $this->consulterHref($url); //dans commun.php
694
		$nom_code = $valeur;
695
		if (is_object($res)) {
696
			$nom_code = $res->nom;
697
		}
698
		return $nom_code;
699
	}
700
 
701
	public function recupererNomSci($id) {
702
		$nom = array();
703
		if ($id != 0) {
704
			if ($this->compo_nom == null) {
326 delphine 705
				$req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html FROM '.$this->table.' WHERE num_nom = '.$id;
3 jpm 706
			} else { //on ajoute à la requete sql, les champs de ns.structure
707
				//print_r($this->compo_nom);
326 delphine 708
				$req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html, '.implode(', ', $this->compo_nom)
3 jpm 709
						.' FROM '.$this->table
710
						.' WHERE num_nom = '.$id;
711
			}
712
			if ($this->parametres['ns.format'] == 'htm') {
713
				$req = str_replace('nom_sci', 'nom_sci_html as nom_sci', $req);
714
			}
715
			$res = $this->getBdd()->recuperer($req);
716
			if ($res) {
326 delphine 717
				$nom['nom_sci']	= $res['nom_sci'];
718
				$nom['nom_sci_html']	= $res['nom_sci_html'];
719
				$nom['nom_sci_complet']	= $res['nom_sci'].$this->ajouterCompositionNom($res);
720
				$nom['nom_sci_complet_html']	= $res['nom_sci_html'].$this->ajouterCompositionNom($res, 'htm');
3 jpm 721
				$nom['service'] = ($res['num_nom_retenu'] == $id && $this->service == 'taxons') ? 'taxons' : 'noms';
722
			}
723
		}
724
		return $nom;
725
	}
726
 
727
	/** Permet de retourner une chaine de caractère composée des parametres du nom (ns.structure : annnée, auteur,
728
	 * bibilio et addendum). A ajouter au nom scientifique */
325 delphine 729
	public function ajouterCompositionNom($tab_res, $format = '') {
730
		$format = ($format == '') ? $this->parametres['ns.format'] : $format;
3 jpm 731
		$nom = '';
732
		if (isset($this->compo_nom)) {
325 delphine 733
			if ($format == 'htm') {
3 jpm 734
				$format = array(
735
					'au' => '<span class="auteur">%s</span>',
736
					'an' => '[<span class="annee">%s</span>]',
737
					'an_bib' => '[<span class="annee">%s</span>, <span class="biblio">%s</span>]',
738
					'bib' => '[<span class="biblio">%s</span>]',
739
					'ad' => '[<span class="adendum">%s</span>]');
740
			} else {
741
				$format = array(
742
					'au' => '%s',
743
					'an' => '[%s]',
744
					'an_bib' => '[%s, %s]',
745
					'bib' => '[%s]',
746
					'ad' => '[%s]');
747
			}
112 jpm 748
			$compo_nom = array();
3 jpm 749
			foreach ($this->compo_nom as $key => $champ) {
750
				if (isset($tab_res[$champ]) && !empty($tab_res[$champ])) {
751
					$compo_nom[$key] = $tab_res[$champ];
752
				}
753
			}
112 jpm 754
			$nom_complet = $this->formerNomComplet($compo_nom, $format);
3 jpm 755
			$nom = ' '.implode(' ', $nom_complet);
756
		}
757
		return rtrim($nom, ' ');
758
	}
759
 
760
 
112 jpm 761
	public function formerNomComplet($compo_nom, $format) {
762
		$nom_complet = array();
3 jpm 763
		extract($compo_nom);
764
		if (isset($au)) $nom_complet[] = sprintf($format['au'], $au);
765
		if (isset($an)) {
766
			if (isset($bib)) {
767
				$nom_complet[] = sprintf($format['an_bib'], $an, $bib);
768
			} else {
769
				$nom_complet[] = sprintf($format['an'], $an);
770
			}
771
		} elseif (isset($bib)) {
772
			$nom_complet[] = sprintf($format['bib'], $bib);
773
		}
774
		if (isset($ad)) $nom_complet[] = sprintf($format['ad'], $ad);
775
		return $nom_complet;
776
	}
777
 
778
 
779
	public function correspondAUnCode($key) {
780
		return (strrpos($key, '.code') !== false) || (in_array($key.'.code', $this->correspondance_champs));
781
	}
782
 
783
	public function correspondAUnId($key) {
784
		return (strrpos($key, '.id') !== false) || (in_array($key.'.id', $this->correspondance_champs));
785
	}
786
 
787
	public function estUnPoint($key) {
788
		if (strrpos($key, 'hybride.parent') !== false) {
789
			$key = str_replace('hybride.parent', 'hybride_parent', $key);
790
		}
791
		return (strrpos($key, '.') !== false);
792
	}
793
 
794
	public function recupererMasquePrincipal() {
795
		$masque = null;
796
		$tab_masque   = array(
797
			'masque' => 'nom_sci',
798
			'masque_sg' => 'nom_supra_generique',
799
			'masque_gen' => 'genre',
800
			'masque_sp' => 'epithete_sp',
801
			'masque_ssp' => 'epithete_infra_sp',
802
			'masque_au' => 'auteur',
803
			'masque_an' => 'annee',
804
			'masque_bib' => 'biblio_origine',
805
			'masque_ad' => 'addendum',
806
			'masque_rg' => 'rang');
807
		$liste_masque = array();
808
 
809
		if (isset($this->masque['num_nom'])) {
810
			$liste_masque[] = $this->masque['num_nom'];
811
		}
812
 
813
		foreach ($tab_masque as $key => $filtre) {
814
            if (isset($this->masque[$filtre])) {
815
            	if (!isset($masque) && !in_array($filtre, array('rang', 'annee'))) {
816
            		$masque = array($key, $filtre);
817
            	}
818
                $liste_masque[] = $this->masque[$filtre];
819
            }
820
        }
821
        $this->masque = $liste_masque;
822
        return $masque;
823
	}
824
}
825
?>