Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 975 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
631 delphine 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
 
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
	protected $sans_nom_sci = array('gen','sp','ssp','fam','au_ss','bib_ss');
31
	private $bib_traitees = array();
32
	private $ontologie = array();
33
 
34
//+------------------------------- PARAMÈTRES ---------------------------------------------------------------+
35
 
36
	public function traiterParametres() {
37
		$this->definirParametresParDefaut();
38
		$this->verifierParametres();
39
 
40
		if (isset($this->parametres) && count($this->parametres) > 0) {
41
			foreach ($this->parametres as $param => $val) {
42
				switch ($param) {
43
					case 'ns.structure' :
44
						$this->remplirTableCompositionNom($val);
45
						if (in_array($val,$this->sans_nom_sci)){
46
							$this->requete_champ = implode(', ',$this->compo_nom);
657 jpm 47
						}else {
631 delphine 48
							$this->requete_champ .= ' ,'.implode(', ',$this->compo_nom);
49
						}
50
						break;
51
					case 'navigation.depart' :
52
							$this->limite_requete['depart'] = $val;
53
						break;
54
					case 'navigation.limite' :
55
							$this->limite_requete['limite'] = $val;
56
						break;
57
				}
58
			}
59
			$this->traiterParametresSpecifiques();
60
		}
61
	}
62
 
63
	protected function definirParametresParDefaut() {
64
		if (empty($this->parametres['recherche'])) {
65
			$this->parametres['recherche'] = 'stricte';
66
		}
67
		if (empty($this->parametres['ns.format'])) {
68
			$this->parametres['ns.format'] =  'txt';
69
		}
70
		if (empty($this->parametres['retour.format'])) {
71
			$this->parametres['retour.format'] = 'max';
72
		}
73
		if (empty($this->parametres['ns.structure']) &&
74
			$this->parametres['retour.format'] != 'oss') {
75
			$this->parametres['ns.structure'] = 'au,an,bib';
76
		}
77
	}
657 jpm 78
 
79
 
631 delphine 80
	public function verifierParametres() {
81
		//$this->verifierParametresAPI();
82
 
83
		$this->verifierParametre('recherche', 'stricte|floue|etendue|complete');
84
		$this->verifierParametre('ns.format', 'htm|txt');
85
		$this->verifierParametre('retour.format', 'min|max|oss|perso');
86
		$this->verifierParametreAvecValeurMultipe('ns.structure', 'an|au|bib|ad|gen|sp|ssp|fam|au_ss|bib_ss');
87
 
88
		/*if (count($this->erreursParametres) > 0) {
89
			$m = 'Erreur dans votre requête : '.implode('<br/>', $this->erreursParametres);
90
			$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
91
		}*/
92
	}
93
 
94
	public function verifierParametresAPI() {
95
		$parametresApi = $this->recupererTableauConfig('parametresAPI');
96
		while (!is_null($parametre = key($this->parametres))) {
97
			if (!in_array($parametre, $parametresApi)) {
98
				$this->erreursParametres[] = "Le paramètre '$parametre' n'est pas pris en compte par cette version de l'API.";
99
			}
100
			next($this->parametres);
101
		}
102
	}
103
 
104
	public function verifierParametre($parametre, $valeursPermises) {
105
		if (isset($this->parametres[$parametre]) && !empty($this->parametres[$parametre])) {
106
			$valeur = $this->parametres[$parametre];
107
			$this->verifierValeursPermises($parametre, $valeur, $valeursPermises);
108
		}
109
	}
110
 
111
	public function verifierParametreAvecValeurMultipe($parametre, $valeursPermises) {
112
		if (isset($this->parametres[$parametre]) && !empty($this->parametres[$parametre])) {
113
			$valeursConcatenees = $this->parametres[$parametre];
114
			$valeurs = explode(',', $valeursConcatenees);
115
			foreach ($valeurs as $valeur) {
116
				$this->verifierValeursPermises($parametre, $valeur, $valeursPermises);
117
			}
118
		}
119
	}
120
 
121
	private function verifierValeursPermises($parametre, $valeur, $valeursPermises) {
122
		if (!in_array($valeur, explode('|', $valeursPermises))) {
123
			$this->erreursParametres[] = "Le paramètre '$parametre' ne peut pas prendre la valeur '$valeur'. Valeurs permises : $valeursPermises";
124
		}
125
	}
126
 
127
	public function traiterParametresCommuns() {
128
 
129
	}
130
 
131
	public function ajouterFiltreMasque($nom_champ, $valeur) {
132
		$valeur = explode(',',$valeur);
133
		$conditions = array();
134
		if ($nom_champ == 'annee' || $nom_champ == 'rang') {
135
			foreach ($valeur as $val) {
136
				 $conditions[] = "$nom_champ = ".$this->getBdd()->proteger($val);
137
			}
138
		} else {
139
			if ($this->parametres['recherche'] == 'etendue') {
140
				foreach ($valeur as $val) {
141
					$val = $this->modifierValeur($val);
142
					$conditions[] = "$nom_champ LIKE ".$this->getBdd()->proteger($val);
143
				}
657 jpm 144
 
631 delphine 145
			} elseif ($this->parametres['recherche'] == 'floue') {
146
				foreach ($valeur as $val) {
147
					$val = $this->getBdd()->proteger($val);
148
					$conditions[] = "( SOUNDEX($nom_champ) = SOUNDEX($val))".
149
											" OR ( SOUNDEX(REVERSE($nom_champ)) = SOUNDEX(REVERSE($val)))";
150
				}
151
			} else {
152
				foreach ($valeur as $val) {
153
					$conditions[] = "$nom_champ LIKE ".$this->getBdd()->proteger($val);
154
				}
155
			}
156
		}
157
		$this->requete_condition[]= '('.implode(' OR ', $conditions ).')';
158
		$this->masque[$nom_champ] = $nom_champ.'='.implode(',',$valeur);
159
	}
160
 
161
	private function modifierValeur($valeur) {
162
		$valeur = $this->remplacerCaractereHybrideEtChimere($valeur);
163
		$valeur = $this->preparerChainePourRechercheEtendue($valeur);
164
		return $valeur;
165
	}
166
 
167
	private function remplacerCaractereHybrideEtChimere($valeur) {
168
		$caracteres = array('×', '%D7', '+', '%2B');
169
		$remplacements = array('x ','x ', '+', '+');
170
		$valeur = str_replace($caracteres, $remplacements, $valeur);
171
		return $valeur;
172
	}
173
 
174
	private function preparerChainePourRechercheEtendue($valeur) {
175
		$valeur = str_replace(' ', '% ', trim($valeur));
176
		$valeur = $valeur.'%';
177
		return $valeur;
178
	}
179
 
180
	//+-------------------------------Fonctions d'analyse des ressources-------------------------------------+
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') {
994 mathias 193
				$this->traiterRessourceIdRelations();
631 delphine 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
	//+------------------------------------------------------------------------------------------------------+
240
	// Fonction d'analyse des parametres
241
 
242
	/** Permet de remplir le tableau compo_nom. Il comprendra en fct du paramètre ns.structure les éléments à rajouter
243
	 * au nom_sci (annee, auteur, biblio ou addendum). */
244
	public function remplirTableCompositionNom($valeur) {
245
		$structure_nom = explode(',', $valeur);
246
		foreach ($structure_nom as $structure) {
657 jpm 247
			$structure = trim($structure);
248
			$patterns = array('/^an$/', '/^au$/', '/^bib$/', '/^ad$/', '/^sp$/', '/^gen$/', '/^ssp$/','/^fam$/',
249
					'/^au_ss$/','/^bib_ss$/');
250
			$champs = array('annee', 'auteur', 'biblio_origine', 'nom_addendum', 'epithete_sp', 'genre',
251
					'epithete_infra_sp','famille','auteur', 'biblio_origine');
252
 
253
			// avec str_replace() 'sp' est inclu dans 'ssp', et la conversion pour 'ssp' est mauvaise
254
			$this->compo_nom[$structure] = preg_replace($patterns, $champs, $structure);
255
		}
631 delphine 256
	}
257
 
258
	public function mettreAuFormat() {
259
		if ($this->parametres['ns.format'] == 'htm') {
260
			if (strrpos($this->requete_champ, 'nom_sci_html as nom_sci') === false) {
261
				$this->requete_champ = str_replace('nom_sci', 'nom_sci_html as nom_sci', $this->requete_champ);
262
			}
263
		}
264
	}
265
 
266
	//+------------------------------------------------------------------------------------------------------+
267
	// Fonctions de formatage
268
 
269
	/** Fonction permettant de creer la table dont le nom est passé en paramètre (champs_api, champs_bdtfx,
270
	 * correspondance_champs...). Les données de chaque table sont présentes dans le fichier de configuration config.ini
271
	 * @param String $table : Peut contenir plusieurs nom de table dont on souhaite récupérer les données : table,table,table. */
272
	public function recupererTableSignification($table) {
273
		$tables = explode(',', $table);
274
		foreach ($tables as $tab) {
275
			if ($tab == 'champs_comp') {
276
				$champ_bdnff_api = array_keys($this->champs_api); //on recupère le nom des champ ds la bdd
277
				$this->champs_comp = array_diff($this->champs_table, $champ_bdnff_api);
278
			} elseif ($tab == 'champs_api') {
279
				foreach ($this->correspondance_champs as $key => $val) {
280
					preg_match('/(hybride[.]parent_0[12](?:[.]notes)?|nom_sci[.][^.]+|[^.]+)(?:[.](id|code))?/', $val, $match);
281
					$val = $match[1];
282
					$this->champs_api[$key] = $val;
283
				}
284
			} else {
285
				$this->$tab = $this->recupererTableauConfig($tab);
286
			}
287
		}
288
	}
289
 
290
	public function formaterEnOss($resultat) {
291
		$table_nom = array();
292
		$oss = '';
293
		foreach ($resultat as $tab) {
294
			if (isset($tab['nom_sci']) ) {
295
				if (!in_array($tab['nom_sci'], $table_nom)) {
296
					$table_nom[] = $tab['nom_sci'];
297
					$oss[] = $tab['nom_sci'].' '.$this->ajouterCompositionNom($tab);
298
				}
299
			}else {
300
				$res = $this->ajouterCompositionNom($tab);
301
				if($res) {
302
					$oss[] = $res;
303
				}
304
			}
657 jpm 305
 
631 delphine 306
		}
657 jpm 307
 
631 delphine 308
		if (isset($this->masque)) $masque = implode('&', $this->masque);
309
		else $masque = 'Pas de masque';
310
		$table_retour_oss = array($masque, $oss);
311
		return $table_retour_oss;
312
	}
313
 
314
	public function afficherEnteteResultat($url_service) {
315
		$this->table_retour['depart'] = $this->limite_requete['depart'];
316
		$this->table_retour['limite'] = $this->limite_requete['limite'];
317
		$this->table_retour['total']  = $this->total_resultat;
318
		$url = $this->formulerUrl($this->total_resultat, $url_service);
319
		if (isset($url['precedent']) && $url['precedent'] != '') {
320
			$this->table_retour['href.precedent'] = $url['precedent'];
321
		}
322
		if (isset($url['suivant']) && $url['suivant']   != '') {
323
			$this->table_retour['href.suivant']   = $url['suivant'];
324
		}
325
	}
326
 
327
	public function afficherNomHrefRetenu($tab, $num) {
328
		$this->resultat_req = $tab;
329
		$this->afficherDonnees('num_nom', $num);
330
		if ($this->parametres['retour.format'] == 'min') { // sinon est affiché ds afficherDonnees(num_nom, $val) ci-dessus
331
			 $this->table_retour['nom_sci'] = $tab['nom_sci'];
332
			 $this->table_retour['nom_sci_complet'] = $tab['nom_sci'].' '.$this->ajouterCompositionNom($tab);
333
		}
334
		if ($tab['num_nom_retenu'] != '') {
335
			$retenu = ($tab['num_nom_retenu'] == $num) ? 'true' : 'false';
336
		} else {
337
			$retenu = 'absent';
338
		}
339
		$this->table_retour['retenu'] = $retenu;
340
		unset($this->table_retour['id']);
341
	}
342
 
343
 
344
	//+------------------------------------------------------------------------------------------------------+
345
	// Fonction de formatage pour les services /#id/
346
 
347
	public function formaterId($resultat) {
348
		$this->recupererTableSignification('correspondance_champs,champs_api,champs_comp');
349
		$this->resultat_req = $resultat;
350
 
351
		foreach ($resultat as $cle => $valeur) {
352
			if ($valeur != '') {
353
				$this->afficherDonnees($cle, $valeur);
354
			}
355
		}
356
		if (isset($this->parametres['retour.champs']) && $this->format_reponse == 'noms/id') {
357
			$retour = $this->table_retour;
358
			$this->table_retour = array();
359
			$champs = explode(',', $this->parametres['retour.champs']);
360
			$this->ajouterChampsPersonnalises($champs, $retour);
361
		}
362
		unset($this->table_retour['href']);
363
		return $this->table_retour;
364
	}
365
 
366
	public function formaterIdChamp($resultat) {
367
		$this->recupererTableSignification('correspondance_champs,champs_api,champs_comp');
368
		$reponse_id = $this->formaterId($resultat);
369
		$this->table_retour = array();
370
		$champs = explode(' ', $this->ressources[1]);
371
		$this->ajouterChampsPersonnalises($champs, $reponse_id);
372
		return $this->table_retour;
373
	}
374
 
375
	protected function ajouterChampsPersonnalises($champs, $reponse_id) {
376
		$champs_a_libeller = array('nom_retenu', 'rang', 'basionyme', 'hybride', 'hybride.parent_01',
377
			 'hybride.parent_02', 'presence', 'tax_sup', 'statut_origine', 'statut_culture', 'statut_introduction');
378
		if (! is_null($champs) && is_array($champs) && count($champs) > 0) {
379
			foreach ($champs as $champ) {
380
				if ($this->verifierValiditeChamp($champ)) {
381
					if (strrpos($champ, '.*') !== false) {
382
						$this->afficherPointEtoile($champ, $reponse_id);
383
					} elseif (in_array($champ, $champs_a_libeller)) {
657 jpm 384
						$this->table_retour[$champ.'.libelle'] =
631 delphine 385
							(isset($reponse_id[$champ.'.libelle'])) ? $reponse_id[$champ.'.libelle'] : null;
386
					} else {
387
						$champ = $this->trouverChampBddCorrespondant($champ);
388
						$this->table_retour[$champ] = (isset($reponse_id[$champ])) ? $reponse_id[$champ] : null;
389
					}
390
				}
391
			}
392
		}
393
	}
394
 
395
	public function afficherPointEtoile($champ, $reponse) {
396
		preg_match('/^([^.]+\.)\*$/', $champ, $match);
397
		if ($match[1] == 'nom_sci') {
398
			$this->afficherNomSciPointEpithete($this->resultat_req);
399
		} else {
400
			foreach ($reponse as $chp => $valeur) {
401
				if (strrpos($chp, $match[1]) !== false) {
402
					if ($valeur != '') {
403
						$this->table_retour[$chp] = $valeur;
404
					} else {
405
						$this->table_retour[$chp] = null;
406
					}
407
				}
408
			}
409
		}
410
	}
411
 
412
	public function decomposerNomChamp($champ) {
413
		$decomposition = false;
414
		if (preg_match('/^(?:([^.]+\.parent_0[12]|[^.]+))(?:\.(.+))?$/', $champ, $match)) {
415
			$radical_champ = $match[1];
416
			$suffixe = (isset($match[2])) ? $match[2] : "";
417
			$decomposition = array($radical_champ, $suffixe);
418
		}
419
		return $decomposition;
420
	}
421
 
422
	public function verifierValiditeChamp($champ) {
423
		$decomposition = $this->decomposerNomChamp($champ);
424
		$validite_ressource = true;
425
		if ($decomposition) {
426
			list($radical, $suffixe) = $decomposition;
427
			$champs_complementaire = array('nom_retenu_complet', 'basionyme_complet');
428
			// on verifie si le nom du champ existe bien
429
			if (!$this->estChampApi($radical) && !$this->estChampComplementaire($radical)) {
430
				if (!in_array($radical, $champs_complementaire)) {
431
					$validite_ressource = false;
432
					$e = 'Le champ "'.$radical.'" n\'existe pas dans la base. <br/><br/>';
433
					$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
434
				}
435
			} elseif ($this->estUnPoint($champ)) {
436
				$validite_ressource = $this->verifierValiditeSuffixe($suffixe, $radical);
437
			}
438
		}
439
		return $validite_ressource;
440
	}
441
 
442
	public function estChampApi($radical_champ) {
443
		$champ_api_ok = false;
444
		if (in_array($radical_champ, $this->champs_api) || in_array($radical_champ, $this->correspondance_champs)) {
445
			$champ_api_ok = true;
446
		}
447
		return $champ_api_ok;
448
	}
449
 
450
	public function estChampComplementaire($radical_champ) {
451
		$champ_complementaire_ok = in_array($radical_champ, $this->champs_comp) ? true : false;
452
		return	$champ_complementaire_ok;
453
	}
454
 
455
	public function verifierValiditeSuffixe($suffixe, $radical_champ) {
456
		$validite_ressource = true;
457
		if ($this->correspondAUnId($radical_champ) || $radical_champ == 'id') {
458
			$this->verificationSuffixesIdentifiant($suffixe, $radical_champ, $validite_ressource);
459
		} elseif ($this->correspondAUnCode($radical_champ)) {
460
			$this->verificationSuffixesCodes($suffixe, $radical_champ, $validite_ressource);
461
		} elseif ($radical_champ == 'nom_sci') {
462
			if ($suffixe != '*') {
463
				$validite_ressource = false;
464
				$m = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/>
465
					Les suffixes possibles sont les suivants : <li> * </li>';
466
				$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
467
			}
468
		} else {
469
			$validite_ressource = false;
470
			$m = 'Erreur : Le paramètre "'.$radical_champ.'" ne peut pas présenter de suffixe. <br/><br/>';
471
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
472
		}
473
		return $validite_ressource;
474
	}
475
 
476
	public function verificationSuffixesCodes(&$suffixe, &$radical_champ, &$validite_ressource ) {
477
		if (!in_array($suffixe, array('*', 'code', 'href', 'details'))) {
478
			$validite_ressource = false;
479
			$e = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'.<br/> Les suffixes '
480
				.'possibles sont les suivants : <li> .* </li><li> .code </li><li> .href </li><li> .details </li>';
481
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
482
		}
483
	}
484
 
485
	public function verificationSuffixesIdentifiant(&$suffixe, &$radical_champ, &$validite_ressource) {
486
		if ((strrpos($radical_champ, 'parent') !== false && !in_array($suffixe, array('*', 'id', 'href', 'details', 'notes')))
487
			|| !in_array($suffixe, array('*', 'id', 'href', 'details')) && strrpos($radical_champ, 'parent') === false) {
488
			$validite_ressource = false;
489
			$e = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/> Les suffixes '
490
				.'possibles sont les suivants : <li> .* </li><li> .id </li><li> .href </li><li> .details </li>'
491
				.'<li> .notes (seulement pour les hybride.parent)';
492
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
493
		}
494
	}
495
 
496
 
497
//------------------------------fonction de formatage pour les services /stats/-----------------------------------------
498
 
499
	public function formaterStatsAnnee($resultat) {
500
		foreach ($resultat as $cle_annee) {
501
			$annee = ($cle_annee['annee'] != '') ? $cle_annee['annee'] : 'ND';
502
			$nb = $cle_annee['nombre'];
503
			$retour_stats_annee[$annee] = $nb;
504
		}
505
		return $retour_stats_annee;
506
	}
507
 
508
	public function formaterStatsRang($resultat) {
509
		foreach ($resultat as $rangs) {
510
			if ($rangs['rang'] != 0) {
511
				$rang = $rangs['rang'];
512
				if ($this->parametres['retour.format'] == 'max') {
513
					$retour_rang[$rang]['rang'] = $this->ajouterSignificationCode('rang',$rang);
514
				}
515
				$nombre = $rangs['nombre'];
516
				$retour_rang[$rang]['nombre'] = $nombre;
517
			}
518
		}
519
		return $retour_rang;
520
	}
521
 
522
	public function formaterStatsInitiales($resultat) {
523
		$rang = null;
524
		$table_rang = array();
525
		foreach ($resultat as $tuple) {
526
			if ($tuple['rang'] != 0) {
527
				$this->memoriserRang($table_rang, $tuple, $rang);
528
				if ($tuple['lettre'] == 'x ') {
529
					$this->ajouterHybrideChimere('hybride', $rang, $tuple);
530
				} elseif ($tuple['lettre'] == '+ ') {
531
					$this->ajouterHybrideChimere('chimere', $rang, $tuple);
532
				} else {
533
					$l = substr($tuple['lettre'], 0, 1);
534
					if (isset($this->table_retour[$rang][$l])) {
535
						$this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] += floatval($tuple['nb']);
536
					} else {
537
						$this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] = floatval($tuple['nb']);
538
					}
539
				}
540
			}
541
		}
542
		return $this->table_retour;
543
	}
544
 
545
	public function memoriserRang(&$table_rang, $tuple, &$rang) {
546
		if (is_array($table_rang)) {
547
			if (!in_array($tuple['rang'], $table_rang)) {
548
				$rang = $tuple['rang'];
549
				$table_rang[] = $rang;
550
				if ($this->parametres['retour.format'] == 'max') {
551
					$rang = $this->ajouterSignificationCode('rang', $rang);
552
				}
553
			}
554
		}
555
	}
556
 
557
	public function ajouterHybrideChimere($groupe, &$rang, &$tuple) {
558
		if (isset($this->table_retour[$rang][str_replace('hybride', 'hyb', $groupe)])) {
559
			$this->table_retour[$rang][$groupe] += floatval($tuple['nb']);
560
		} else {
561
			$this->table_retour[$rang][$groupe] = floatval($tuple['nb']);
562
		}
563
	}
564
 
565
	//-----------------------------Fonctions d'affichage utiliser dans les fonctions de formatage---------------------------
566
 
567
	public function afficherDonnees($champApi, $valeur) {
568
		$champBdd = $this->trouverChampBddCorrespondant($champApi);
569
		if ($this->parametres['retour.format'] == 'min') {
570
			if ($champApi == 'nom_sci') {
571
				$valeur = $valeur.' '.$this->ajouterCompositionNom($this->resultat_req);
572
			}
573
			if ($champApi == 'nom_sci_html') {
574
				$valeur = $valeur.' '.$this->ajouterCompositionNom($this->resultat_req, 'htm');
575
			}
576
			$this->table_retour[$champBdd] = $valeur;
577
		} else {
578
			$this->afficherToutesLesInfos($champBdd, $valeur);
579
		}
580
	}
581
 
582
	public function trouverChampBddCorrespondant($champApi) {
583
		if (array_key_exists($champApi, $this->champs_api)) {
584
			$champBdd = $this->correspondance_champs[$champApi];
585
		} else {
586
			$champBdd = $champApi;
587
		}
588
		return $champBdd;
589
	}
590
 
591
	public function afficherToutesLesInfos($nom_champ_api, $valeur) {
592
		if ($this->presentePlusieursId($nom_champ_api, $valeur)) {
593
			preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
594
			$this->afficherInfosPrecises($match[1], 'details', $valeur);
595
			$this->table_retour[$nom_champ_api] = $valeur;
596
 
597
		} elseif (strrpos($nom_champ_api, 'parent') !== false && strrpos($nom_champ_api, 'notes') !== false) {
598
			$this->table_retour[$nom_champ_api] = $valeur;
599
 
600
		} elseif (($this->correspondAUnId($nom_champ_api) || $nom_champ_api == 'id' && $valeur != '0')) {
601
			preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
602
			$this->afficherInfosPrecises($match[1], 'id,signification,href', $valeur);
603
 
604
		} elseif ($this->correspondAUnCode($nom_champ_api)) {
605
			preg_match('/^([^.]+)(?:\.code)?$/', $nom_champ_api, $match);
606
			$this->afficherInfosPrecises($match[1], 'code,signification,href', $valeur);
607
 
608
		} elseif ($nom_champ_api == 'nom_sci_html') {
609
			$this->table_retour['nom_sci_html'] = $valeur;
610
			$this->table_retour['nom_sci_html_complet'] = $valeur.' '.$this->ajouterCompositionNom($this->resultat_req, 'htm');
611
		}elseif ($nom_champ_api != 'nom_sci') {
612
			$this->table_retour[$nom_champ_api] = $valeur;
613
		}
614
	}
615
 
616
	public function presentePlusieursId($ressource, $valeur = null) {
617
		if ($valeur) {
618
			$presente = strrpos($ressource, 'proparte') !== false && strrpos($valeur, ',') !== false;
619
		} else { //pour la vérification du champ, on ignore alors la valeur de la ressource
620
			$presente = strrpos($ressource, 'proparte') !== false;
621
		}
622
		return $presente;
623
	}
624
 
625
	public function afficherInfosPrecises($champ, $suffixe, $valeur) {
626
		$suffixes = explode(',', $suffixe);
627
		//on initialise au service appelé. Sera potentiellement modifié dans la fonction afficherSignification()
628
		$this->service_href = $this->service;
629
		foreach ($suffixes  as $suffixe) {
630
			switch ($suffixe) {
631
				case 'id' 			 :
632
					$this->table_retour[str_replace('id.id', 'id', $champ.'.id')] = $valeur;
633
					break;
634
				case 'details' 		 :
635
					$this->afficherTableDetails($champ, $valeur);
636
					break;
637
				case 'signification' :
662 delphine 638
					$this->afficherSignification($champ, $valeur);
631 delphine 639
					break;
640
				case 'href' 		 :
641
					$url = $this->creerUrl($champ, $valeur);
642
					$this->table_retour[str_replace('id.href', 'href', $champ.'.href')] = $url;
643
					break;
644
				case 'code' 		 :
645
					$this->table_retour[$champ.'.code'] = $this->obtenirCode($champ, $valeur);
646
					break;
647
				case 'notes' 		 :
648
					$this->table_retour[$champ.'.notes'] = $this->resultat_req[str_replace('.', '_', $champ).'_notes'];
649
					break;
650
				default : break;
651
			}
652
		}
653
	}
654
 
655
	public function afficherTableDetails($nom_champ_api, $valeur) {
656
		$tab_id = explode(',', $valeur);
657
		$tab_res = $this->table_retour;
658
		$this->table_retour = array();
659
		foreach ($tab_id as $id) {
660
			$this->afficherInfosPrecises($nom_champ_api, 'id,signification,href', $id);
661
			$tab_res[$nom_champ_api.'.details'][] = $this->table_retour;
662
			$this->table_retour = array();
663
		}
664
		$this->table_retour = $tab_res;
665
	}
666
 
667
	private function obtenirCode($champ, $valeur) {
668
		$code = $this->transformerChampEnCode($champ);
669
		return "bdnt.$code:$valeur";
670
	}
671
 
672
	private function transformerChampEnCode($champ) {
673
		if (is_null($this->relationsChampsCodesOntologie)) {
674
			$this->relationsChampsCodesOntologie = Outils::recupererTableauConfig('ChampsCodesOntologie');
675
		}
676
 
677
		$code = $champ;
678
		if (array_key_exists($champ, $this->relationsChampsCodesOntologie)) {
679
			$code = $this->relationsChampsCodesOntologie[$champ];
680
		}
681
		return $code;
682
	}
683
 
684
	public function creerUrl($champ, $valeur) {
685
		if ($this->correspondAUnId($champ) || $champ == 'id') {
686
			$service = $this->service_href;
687
			$url = $this->ajouterHref($service, $valeur);
688
		} else {
689
			$code = $this->transformerChampEnCode($champ);
690
			$url = $this->ajouterHrefAutreProjet('ontologies', "$code:", $valeur, 'bdnt');
691
		}
692
		return $url;
693
	}
694
 
695
	public function afficherSignification($champ, $valeur) {
696
		if ($champ == 'id' && isset($this->resultat_req['nom_sci']) && $this->resultat_req['num_nom'] == $valeur) {
697
			//si le nom_sci du num_nom que l'on veut afficher est déjà dans la table de résultat :
698
			$this->table_retour['nom_sci'] = $this->resultat_req['nom_sci'];
699
			$this->table_retour['nom_sci_complet'] = $this->resultat_req['nom_sci'].' '.
700
				$this->ajouterCompositionNom($this->resultat_req);
701
		} elseif ($this->correspondAUnId($champ) || $champ == 'id') {
702
			$nom = $this->recupererNomSci($valeur);
703
			if ($nom != array()) {
704
				$this->table_retour[$champ.'.libelle'] = $nom['nom_sci'];
705
				$this->table_retour[$champ.'_html'] = $nom['nom_sci_html'];
706
				$this->table_retour[$champ.'_complet'] = $nom['nom_sci_complet'];
707
				$this->table_retour[$champ.'_html_complet'] = $nom['nom_sci_complet_html'];
708
				$this->service_href = $nom['service'];
709
			}
710
		} elseif ($this->correspondAUnCode($champ)) {
711
			$this->table_retour[$champ.'.libelle'] = $this->ajouterSignificationCode($champ, $valeur);
712
		}
713
	}
714
 
715
	/** Permet d'afficher les élements nomenclatural du nom_sci lors de l'appel dans le service noms/id/champ du champ^nom_sci.*/
716
	public function afficherNomSciPointEpithete($resultat) {
717
		$tab_nom_sci   = array('nom_supra_generique', 'genre', 'epithete_infra_generique', 'epithete_sp',
718
		'type_epithete', 'epithete_infra_sp', 'cultivar_groupe', 'cultivar', 'nom_commercial');
719
		foreach ($tab_nom_sci as $compo_nom) {
720
			if (isset($resultat[$compo_nom]) && !empty($resultat[$compo_nom])) {
721
				$this->table_retour['nom_sci.'.$compo_nom] = $resultat[$compo_nom];
722
			}
723
		}
724
	}
725
 
726
	public function ajouterSignificationCode($champ, $valeur) {
662 delphine 727
		if($this->termeOntologieEstEnCache($champ, $valeur)) {
728
			$nom_code = $this->obtenirTermeOntologieParCache($champ, $valeur);
657 jpm 729
		} else {
662 delphine 730
			$code = $this->transformerChampEnCode($champ);
731
			if (preg_match('/^([^_-]+)(?:_|-)([^_-]+)$/', $code, $match)) {
732
				$code = $match[1].ucfirst($match[2]);
631 delphine 733
			}
662 delphine 734
			$url = Config::get('url_ontologie').$code.':'.$valeur.'/nom';
720 aurelien 735
			try {
736
				$res = $this->consulterHref($url); //dans commun.php
737
				$nom_code = $valeur;
738
				if (is_object($res)) {
739
					$nom_code = $res->nom;
740
				}
741
				$this->mettreEnCacheOntologie($champ, $valeur, $nom_code);
742
			} catch (Exception $e) {
743
				$nom_code = '';
631 delphine 744
			}
745
		}
746
		return $nom_code;
747
	}
748
 
749
	public function recupererNomSci($id) {
750
		$nom = array();
751
		if ($id != 0) {
752
			if ($this->compo_nom == null) {
753
				$req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html FROM '.$this->table.' WHERE num_nom = '.$id;
754
			} else { //on ajoute à la requete sql, les champs de ns.structure
755
				//print_r($this->compo_nom);
756
				$req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html, '.implode(', ', $this->compo_nom)
757
						.' FROM '.$this->table
758
						.' WHERE num_nom = '.$id;
759
			}
760
			if ($this->parametres['ns.format'] == 'htm') {
761
				$req = str_replace('nom_sci', 'nom_sci_html as nom_sci', $req);
762
			}
763
			$res = $this->getBdd()->recuperer($req);
764
			if ($res) {
765
				$nom['nom_sci']	= $res['nom_sci'];
766
				$nom['nom_sci_html']	= $res['nom_sci_html'];
767
				$nom['nom_sci_complet']	= $res['nom_sci'].' '.$this->ajouterCompositionNom($res);
768
				$nom['nom_sci_complet_html']	= $res['nom_sci_html'].' '.$this->ajouterCompositionNom($res, 'htm');
769
				$nom['service'] = ($res['num_nom_retenu'] == $id && $this->service == 'taxons') ? 'taxons' : 'noms';
770
			}
771
		}
772
		return $nom;
773
	}
774
 
775
	/** Permet de retourner une chaine de caractère composée des parametres du nom (ns.structure : annnée, auteur,
776
	 * bibilio et addendum). A ajouter au nom scientifique */
777
	public function ajouterCompositionNom($tab_res, $format = '') {
778
		$format = ($format == '') ? $this->parametres['ns.format'] : $format;
779
 
780
		$nom = '';
781
		if (isset($this->compo_nom)) {
782
			if ($format == 'htm') {
783
				$format = array(
784
					'au' => '<span class="auteur">%s</span>',
785
					'an' => '[<span class="annee">%s</span>]',
786
					'an_bib' => '[<span class="annee">%s</span>, <span class="biblio">%s</span>]',
787
					'bib' => '[<span class="biblio">%s</span>]',
788
					'ad' => '[<span class="adendum">%s</span>]');
789
			} else {
790
				$format = array(
791
					'au' => '%s',
792
					'an' => '[%s]',
793
					'an_bib' => '[%s, %s]',
794
					'bib' => '[%s]',
795
					'ad' => '[%s]',
796
					'gen' => '%s',
797
					'sp' => '%s',
798
					'ssp' => '%s',
799
					'fam' => '%s',
800
					'au_ss' => '%s',
801
					'bib_ss' => '%s');
802
			}
803
			$compo_nom = array();
804
 
805
			foreach ($this->compo_nom as $key => $champ) {
806
				if (isset($tab_res[$champ]) && !empty($tab_res[$champ])) {
807
					$compo_nom[$key] = $tab_res[$champ];
808
				}
809
			}
810
			$nom_complet = $this->formerNomComplet($compo_nom, $format);
811
			$nom = implode(' ', $nom_complet);
812
		}
813
		return rtrim($nom, ' ');
814
	}
815
 
816
 
817
	public function formerNomComplet($compo_nom, $format) {
818
		$nom_complet = array();
819
		extract($compo_nom);
820
		if (isset($au)) $nom_complet[] = sprintf($format['au'], $au);
821
		if (isset($an)) {
822
			if (isset($bib)) {
823
				$nom_complet[] = sprintf($format['an_bib'], $an, $bib);
824
			} else {
825
				$nom_complet[] = sprintf($format['an'], $an);
826
			}
827
		} elseif (isset($bib)) {
828
			$nom_complet[] = sprintf($format['bib'], $bib);
829
		}
830
		if (isset($ad)) $nom_complet[] = sprintf($format['ad'], $ad);
831
		if (isset($gen)) $nom_complet[] = sprintf($format['gen'], $gen);
832
		if (isset($ssp)) $nom_complet[] = sprintf($format['ssp'], $ssp);
833
		if (isset($sp)) $nom_complet[] = sprintf($format['sp'], $sp);
834
		if (isset($fam)) $nom_complet[] = sprintf($format['fam'], $fam);
835
		if (isset($au_ss)) $nom_complet[] = sprintf($format['au_ss'], $au_ss);
836
		if (isset($bib_ss)) {
837
			$bibl = $this->tronquerBiblio($bib_ss);
838
			//simule un 'select distinct' sur les biblio tronquées
657 jpm 839
			if (!isset($this->bib_traitees[$bibl])) {
631 delphine 840
				$nom_complet[] = sprintf($format['bib_ss'],$bibl );
841
				$this->bib_traitees[$bibl] = 1;
842
			}
843
		}
844
		return $nom_complet;
845
	}
846
 
847
	public function tronquerBiblio($valeur){
848
		$bib = '';
849
		if(strpos($valeur,',') !== false) {
850
			$bib = explode(',',$valeur);
851
		}
852
		if(strpos($bib[0],';') !== false) {
657 jpm 853
 
631 delphine 854
			$bib[0] = strstr($bib[0],';');
855
			$bib[0] = str_replace('; ','',$bib[0]);
856
		}
857
		return $bib[0];
858
	}
859
 
860
 
657 jpm 861
 
631 delphine 862
	public function correspondAUnCode($key) {
863
		return (strrpos($key, '.code') !== false) || (in_array($key.'.code', $this->correspondance_champs));
864
	}
865
 
866
	public function correspondAUnId($key) {
867
		return (strrpos($key, '.id') !== false) || (in_array($key.'.id', $this->correspondance_champs));
868
	}
869
 
870
	public function estUnPoint($key) {
871
		if (strrpos($key, 'hybride.parent') !== false) {
872
			$key = str_replace('hybride.parent', 'hybride_parent', $key);
873
		}
874
		return (strrpos($key, '.') !== false);
875
	}
876
 
877
	public function recupererMasquePrincipal() {
878
		$masque = null;
879
		$tab_masque   = array(
880
			'masque' => 'nom_sci',
881
			'masque_sg' => 'nom_supra_generique',
882
			'masque_gen' => 'genre',
883
			'masque_sp' => 'epithete_sp',
884
			'masque_ssp' => 'epithete_infra_sp',
885
			'masque_au' => 'auteur',
886
			'masque_an' => 'annee',
887
			'masque_bib' => 'biblio_origine',
888
			'masque_ad' => 'addendum',
889
			'masque_rg' => 'rang');
890
		$liste_masque = array();
891
 
892
		if (isset($this->masque['num_nom'])) {
893
			$liste_masque[] = $this->masque['num_nom'];
894
		}
895
 
896
		foreach ($tab_masque as $key => $filtre) {
897
            if (isset($this->masque[$filtre])) {
898
            	if (!isset($masque) && !in_array($filtre, array('rang', 'annee'))) {
899
            		$masque = array($key, $filtre);
900
            	}
901
                $liste_masque[] = $this->masque[$filtre];
902
            }
903
        }
904
        $this->masque = $liste_masque;
905
        return $masque;
906
	}
657 jpm 907
 
631 delphine 908
	private function mettreEnCacheOntologie($categorie, $valeur, $correspondance) {
909
		if(!isset($this->ontologie[$categorie])) {
910
			$this->ontologie[$categorie] = array();
911
		}
912
		if(!isset($this->ontologie[$categorie][$valeur])) {
913
			$this->ontologie[$categorie][$valeur] = array();
914
		}
915
		$this->ontologie[$categorie][$valeur] = $correspondance;
916
	}
657 jpm 917
 
631 delphine 918
	private function termeOntologieEstEnCache($categorie, $valeur) {
919
		return array_key_exists($categorie, $this->ontologie) && array_key_exists($valeur, $this->ontologie[$categorie]);
920
	}
657 jpm 921
 
631 delphine 922
	private function obtenirTermeOntologieParCache($categorie, $valeur) {
923
		return $this->ontologie[$categorie][$valeur];
924
	}
925
}
926
?>