Subversion Repositories eFlore/Projets.eflore-projets

Rev

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