Subversion Repositories eFlore/Projets.eflore-projets

Rev

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

Rev Author Line No. Line
707 aurelien 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);
47
						}else {
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
	}
78
 
79
 
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
				}
144
 
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') {
193
				$this->traiterRessourceRelations();
194
			} elseif ($this->estUnIdentifiant()) { //l'identifiant peut etre de type /#id ou /nt:#id
195
				$this->traiterRessourcesIdentifiant(); // dans le service noms ou taxons
196
			} elseif ($this->ressources[0] == 'stats') { //ressource = noms/stats
197
				$this->traiterRessourcesStats();
198
			} else {
199
				$e = 'Erreur dans votre requete </br> Ressources disponibles : <br/>
200
					 <li> /'.$this->service.'/#id (id : L\'identifiant du nom rechercher)</li>
201
					 <li> /'.$this->service.'/nt:#id (id : Numero du taxon recherche)</li>
202
					 <li> /'.$this->service.'/stats </li>';
203
				$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
204
			}
205
		}
206
	}
207
 
208
	public function traiterRessourcesStats() {
209
		$this->format_reponse = $this->service.'/stats';
210
 
211
		$e = "Erreur dans votre requête </br> Ressources disponibles : $this->service/stats/[annees|rangs|initiales]";
212
		if (isset($this->ressources[1]) && !empty($this->ressources[1])) {
213
			switch ($this->ressources[1]) {
214
				case 'annees' :
215
					$this->traiterRessourceStatsAnnees();
216
					break;
217
				case 'rangs' :
218
					$this->traiterRessourceStatsRangs();
219
					break;
220
				case 'initiales' :
221
					$this->traiterRessourceStatsInitiales();
222
					break;
223
				default :
224
					$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
225
					break;
226
			}
227
		} else {
228
			$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
229
		}
230
	}
231
 
232
	/** Vérifie si la première valeur de la table de ressource est un identifiant :
233
	 * un numerique ou un numéro taxonomique sous la forme nt:xx */
234
	public function estUnIdentifiant() {
235
		return (is_numeric($this->ressources[0]) || (strrpos($this->ressources[0],'nt:') !== false
236
				&& is_numeric(str_replace('nt:','',$this->ressources[0]))));
237
	}
238
 
239
	//+------------------------------------------------------------------------------------------------------+
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) {
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
		}
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
			}
305
 
306
		}
307
 
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');
1007 mathias 378
		$champs_forces = array('rang'); // même s'ils sont dans "à libeller", on les prend quand même en brut, en plus
707 aurelien 379
		if (! is_null($champs) && is_array($champs) && count($champs) > 0) {
380
			foreach ($champs as $champ) {
381
				if ($this->verifierValiditeChamp($champ)) {
382
					if (strrpos($champ, '.*') !== false) {
383
						$this->afficherPointEtoile($champ, $reponse_id);
384
					} elseif (in_array($champ, $champs_a_libeller)) {
385
						$this->table_retour[$champ.'.libelle'] =
386
							(isset($reponse_id[$champ.'.libelle'])) ? $reponse_id[$champ.'.libelle'] : null;
387
					} else {
388
						$champ = $this->trouverChampBddCorrespondant($champ);
389
						$this->table_retour[$champ] = (isset($reponse_id[$champ])) ? $reponse_id[$champ] : null;
390
					}
1007 mathias 391
					// champs bruts en plus, ajouté pour obtenir le rang, mais retourne rang.code avec du kk dedans :-/
392
					if (in_array($champ, $champs_forces)) {
393
						$champ = $this->trouverChampBddCorrespondant($champ);
394
						$this->table_retour[$champ] = (isset($reponse_id[$champ])) ? $reponse_id[$champ] : null;
395
					}
707 aurelien 396
				}
397
			}
398
		}
399
	}
400
 
401
	public function afficherPointEtoile($champ, $reponse) {
402
		preg_match('/^([^.]+\.)\*$/', $champ, $match);
403
		if ($match[1] == 'nom_sci') {
404
			$this->afficherNomSciPointEpithete($this->resultat_req);
405
		} else {
406
			foreach ($reponse as $chp => $valeur) {
407
				if (strrpos($chp, $match[1]) !== false) {
408
					if ($valeur != '') {
409
						$this->table_retour[$chp] = $valeur;
410
					} else {
411
						$this->table_retour[$chp] = null;
412
					}
413
				}
414
			}
415
		}
416
	}
417
 
418
	public function decomposerNomChamp($champ) {
419
		$decomposition = false;
420
		if (preg_match('/^(?:([^.]+\.parent_0[12]|[^.]+))(?:\.(.+))?$/', $champ, $match)) {
421
			$radical_champ = $match[1];
422
			$suffixe = (isset($match[2])) ? $match[2] : "";
423
			$decomposition = array($radical_champ, $suffixe);
424
		}
425
		return $decomposition;
426
	}
427
 
428
	public function verifierValiditeChamp($champ) {
429
		$decomposition = $this->decomposerNomChamp($champ);
430
		$validite_ressource = true;
431
		if ($decomposition) {
432
			list($radical, $suffixe) = $decomposition;
433
			$champs_complementaire = array('nom_retenu_complet', 'basionyme_complet');
434
			// on verifie si le nom du champ existe bien
435
			if (!$this->estChampApi($radical) && !$this->estChampComplementaire($radical)) {
436
				if (!in_array($radical, $champs_complementaire)) {
437
					$validite_ressource = false;
438
					$e = 'Le champ "'.$radical.'" n\'existe pas dans la base. <br/><br/>';
439
					$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
440
				}
441
			} elseif ($this->estUnPoint($champ)) {
442
				$validite_ressource = $this->verifierValiditeSuffixe($suffixe, $radical);
443
			}
444
		}
445
		return $validite_ressource;
446
	}
447
 
448
	public function estChampApi($radical_champ) {
449
		$champ_api_ok = false;
450
		if (in_array($radical_champ, $this->champs_api) || in_array($radical_champ, $this->correspondance_champs)) {
451
			$champ_api_ok = true;
452
		}
453
		return $champ_api_ok;
454
	}
455
 
456
	public function estChampComplementaire($radical_champ) {
457
		$champ_complementaire_ok = in_array($radical_champ, $this->champs_comp) ? true : false;
458
		return	$champ_complementaire_ok;
459
	}
460
 
461
	public function verifierValiditeSuffixe($suffixe, $radical_champ) {
462
		$validite_ressource = true;
463
		if ($this->correspondAUnId($radical_champ) || $radical_champ == 'id') {
464
			$this->verificationSuffixesIdentifiant($suffixe, $radical_champ, $validite_ressource);
465
		} elseif ($this->correspondAUnCode($radical_champ)) {
466
			$this->verificationSuffixesCodes($suffixe, $radical_champ, $validite_ressource);
467
		} elseif ($radical_champ == 'nom_sci') {
468
			if ($suffixe != '*') {
469
				$validite_ressource = false;
470
				$m = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/>
471
					Les suffixes possibles sont les suivants : <li> * </li>';
472
				$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
473
			}
474
		} else {
475
			$validite_ressource = false;
476
			$m = 'Erreur : Le paramètre "'.$radical_champ.'" ne peut pas présenter de suffixe. <br/><br/>';
477
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
478
		}
479
		return $validite_ressource;
480
	}
481
 
482
	public function verificationSuffixesCodes(&$suffixe, &$radical_champ, &$validite_ressource ) {
483
		if (!in_array($suffixe, array('*', 'code', 'href', 'details'))) {
484
			$validite_ressource = false;
485
			$e = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'.<br/> Les suffixes '
486
				.'possibles sont les suivants : <li> .* </li><li> .code </li><li> .href </li><li> .details </li>';
487
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
488
		}
489
	}
490
 
491
	public function verificationSuffixesIdentifiant(&$suffixe, &$radical_champ, &$validite_ressource) {
492
		if ((strrpos($radical_champ, 'parent') !== false && !in_array($suffixe, array('*', 'id', 'href', 'details', 'notes')))
493
			|| !in_array($suffixe, array('*', 'id', 'href', 'details')) && strrpos($radical_champ, 'parent') === false) {
494
			$validite_ressource = false;
495
			$e = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/> Les suffixes '
496
				.'possibles sont les suivants : <li> .* </li><li> .id </li><li> .href </li><li> .details </li>'
497
				.'<li> .notes (seulement pour les hybride.parent)';
498
			$this->renvoyerErreur( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
499
		}
500
	}
501
 
502
 
503
//------------------------------fonction de formatage pour les services /stats/-----------------------------------------
504
 
505
	public function formaterStatsAnnee($resultat) {
506
		foreach ($resultat as $cle_annee) {
507
			$annee = ($cle_annee['annee'] != '') ? $cle_annee['annee'] : 'ND';
508
			$nb = $cle_annee['nombre'];
509
			$retour_stats_annee[$annee] = $nb;
510
		}
511
		return $retour_stats_annee;
512
	}
513
 
514
	public function formaterStatsRang($resultat) {
515
		foreach ($resultat as $rangs) {
516
			if ($rangs['rang'] != 0) {
517
				$rang = $rangs['rang'];
518
				if ($this->parametres['retour.format'] == 'max') {
519
					$retour_rang[$rang]['rang'] = $this->ajouterSignificationCode('rang',$rang);
520
				}
521
				$nombre = $rangs['nombre'];
522
				$retour_rang[$rang]['nombre'] = $nombre;
523
			}
524
		}
525
		return $retour_rang;
526
	}
527
 
528
	public function formaterStatsInitiales($resultat) {
529
		$rang = null;
530
		$table_rang = array();
531
		foreach ($resultat as $tuple) {
532
			if ($tuple['rang'] != 0) {
533
				$this->memoriserRang($table_rang, $tuple, $rang);
534
				if ($tuple['lettre'] == 'x ') {
535
					$this->ajouterHybrideChimere('hybride', $rang, $tuple);
536
				} elseif ($tuple['lettre'] == '+ ') {
537
					$this->ajouterHybrideChimere('chimere', $rang, $tuple);
538
				} else {
539
					$l = substr($tuple['lettre'], 0, 1);
540
					if (isset($this->table_retour[$rang][$l])) {
541
						$this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] += floatval($tuple['nb']);
542
					} else {
543
						$this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] = floatval($tuple['nb']);
544
					}
545
				}
546
			}
547
		}
548
		return $this->table_retour;
549
	}
550
 
551
	public function memoriserRang(&$table_rang, $tuple, &$rang) {
552
		if (is_array($table_rang)) {
553
			if (!in_array($tuple['rang'], $table_rang)) {
554
				$rang = $tuple['rang'];
555
				$table_rang[] = $rang;
556
				if ($this->parametres['retour.format'] == 'max') {
557
					$rang = $this->ajouterSignificationCode('rang', $rang);
558
				}
559
			}
560
		}
561
	}
562
 
563
	public function ajouterHybrideChimere($groupe, &$rang, &$tuple) {
564
		if (isset($this->table_retour[$rang][str_replace('hybride', 'hyb', $groupe)])) {
565
			$this->table_retour[$rang][$groupe] += floatval($tuple['nb']);
566
		} else {
567
			$this->table_retour[$rang][$groupe] = floatval($tuple['nb']);
568
		}
569
	}
570
 
571
	//-----------------------------Fonctions d'affichage utiliser dans les fonctions de formatage---------------------------
572
 
573
	public function afficherDonnees($champApi, $valeur) {
574
		$champBdd = $this->trouverChampBddCorrespondant($champApi);
575
		if ($this->parametres['retour.format'] == 'min') {
576
			if ($champApi == 'nom_sci') {
577
				$valeur = $valeur.' '.$this->ajouterCompositionNom($this->resultat_req);
578
			}
579
			if ($champApi == 'nom_sci_html') {
580
				$valeur = $valeur.' '.$this->ajouterCompositionNom($this->resultat_req, 'htm');
581
			}
582
			$this->table_retour[$champBdd] = $valeur;
583
		} else {
584
			$this->afficherToutesLesInfos($champBdd, $valeur);
585
		}
586
	}
587
 
588
	public function trouverChampBddCorrespondant($champApi) {
589
		if (array_key_exists($champApi, $this->champs_api)) {
590
			$champBdd = $this->correspondance_champs[$champApi];
591
		} else {
592
			$champBdd = $champApi;
593
		}
594
		return $champBdd;
595
	}
596
 
597
	public function afficherToutesLesInfos($nom_champ_api, $valeur) {
598
		if ($this->presentePlusieursId($nom_champ_api, $valeur)) {
599
			preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
600
			$this->afficherInfosPrecises($match[1], 'details', $valeur);
601
			$this->table_retour[$nom_champ_api] = $valeur;
602
 
603
		} elseif (strrpos($nom_champ_api, 'parent') !== false && strrpos($nom_champ_api, 'notes') !== false) {
604
			$this->table_retour[$nom_champ_api] = $valeur;
605
 
606
		} elseif (($this->correspondAUnId($nom_champ_api) || $nom_champ_api == 'id' && $valeur != '0')) {
607
			preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
608
			$this->afficherInfosPrecises($match[1], 'id,signification,href', $valeur);
609
 
610
		} elseif ($this->correspondAUnCode($nom_champ_api)) {
611
			preg_match('/^([^.]+)(?:\.code)?$/', $nom_champ_api, $match);
612
			$this->afficherInfosPrecises($match[1], 'code,signification,href', $valeur);
613
 
614
		} elseif ($nom_champ_api == 'nom_sci_html') {
615
			$this->table_retour['nom_sci_html'] = $valeur;
616
			$this->table_retour['nom_sci_html_complet'] = $valeur.' '.$this->ajouterCompositionNom($this->resultat_req, 'htm');
617
		}elseif ($nom_champ_api != 'nom_sci') {
618
			$this->table_retour[$nom_champ_api] = $valeur;
619
		}
620
	}
621
 
622
	public function presentePlusieursId($ressource, $valeur = null) {
623
		if ($valeur) {
624
			$presente = strrpos($ressource, 'proparte') !== false && strrpos($valeur, ',') !== false;
625
		} else { //pour la vérification du champ, on ignore alors la valeur de la ressource
626
			$presente = strrpos($ressource, 'proparte') !== false;
627
		}
628
		return $presente;
629
	}
630
 
631
	public function afficherInfosPrecises($champ, $suffixe, $valeur) {
632
		$suffixes = explode(',', $suffixe);
633
		//on initialise au service appelé. Sera potentiellement modifié dans la fonction afficherSignification()
634
		$this->service_href = $this->service;
635
		foreach ($suffixes  as $suffixe) {
636
			switch ($suffixe) {
637
				case 'id' 			 :
638
					$this->table_retour[str_replace('id.id', 'id', $champ.'.id')] = $valeur;
639
					break;
640
				case 'details' 		 :
641
					$this->afficherTableDetails($champ, $valeur);
642
					break;
643
				case 'signification' :
644
					$this->afficherSignification($champ, $valeur);
645
					break;
646
				case 'href' 		 :
647
					$url = $this->creerUrl($champ, $valeur);
648
					$this->table_retour[str_replace('id.href', 'href', $champ.'.href')] = $url;
649
					break;
650
				case 'code' 		 :
651
					$this->table_retour[$champ.'.code'] = $this->obtenirCode($champ, $valeur);
652
					break;
653
				case 'notes' 		 :
654
					$this->table_retour[$champ.'.notes'] = $this->resultat_req[str_replace('.', '_', $champ).'_notes'];
655
					break;
656
				default : break;
657
			}
658
		}
659
	}
660
 
661
	public function afficherTableDetails($nom_champ_api, $valeur) {
662
		$tab_id = explode(',', $valeur);
663
		$tab_res = $this->table_retour;
664
		$this->table_retour = array();
665
		foreach ($tab_id as $id) {
666
			$this->afficherInfosPrecises($nom_champ_api, 'id,signification,href', $id);
667
			$tab_res[$nom_champ_api.'.details'][] = $this->table_retour;
668
			$this->table_retour = array();
669
		}
670
		$this->table_retour = $tab_res;
671
	}
672
 
673
	private function obtenirCode($champ, $valeur) {
674
		$code = $this->transformerChampEnCode($champ);
675
		return "bdnt.$code:$valeur";
676
	}
677
 
678
	private function transformerChampEnCode($champ) {
679
		if (is_null($this->relationsChampsCodesOntologie)) {
680
			$this->relationsChampsCodesOntologie = Outils::recupererTableauConfig('ChampsCodesOntologie');
681
		}
682
 
683
		$code = $champ;
684
		if (array_key_exists($champ, $this->relationsChampsCodesOntologie)) {
685
			$code = $this->relationsChampsCodesOntologie[$champ];
686
		}
687
		return $code;
688
	}
689
 
690
	public function creerUrl($champ, $valeur) {
691
		if ($this->correspondAUnId($champ) || $champ == 'id') {
692
			$service = $this->service_href;
693
			$url = $this->ajouterHref($service, $valeur);
694
		} else {
695
			$code = $this->transformerChampEnCode($champ);
696
			$url = $this->ajouterHrefAutreProjet('ontologies', "$code:", $valeur, 'bdnt');
697
		}
698
		return $url;
699
	}
700
 
701
	public function afficherSignification($champ, $valeur) {
702
		if ($champ == 'id' && isset($this->resultat_req['nom_sci']) && $this->resultat_req['num_nom'] == $valeur) {
703
			//si le nom_sci du num_nom que l'on veut afficher est déjà dans la table de résultat :
704
			$this->table_retour['nom_sci'] = $this->resultat_req['nom_sci'];
705
			$this->table_retour['nom_sci_complet'] = $this->resultat_req['nom_sci'].' '.
706
				$this->ajouterCompositionNom($this->resultat_req);
707
		} elseif ($this->correspondAUnId($champ) || $champ == 'id') {
708
			$nom = $this->recupererNomSci($valeur);
709
			if ($nom != array()) {
710
				$this->table_retour[$champ.'.libelle'] = $nom['nom_sci'];
711
				$this->table_retour[$champ.'_html'] = $nom['nom_sci_html'];
712
				$this->table_retour[$champ.'_complet'] = $nom['nom_sci_complet'];
713
				$this->table_retour[$champ.'_html_complet'] = $nom['nom_sci_complet_html'];
714
				$this->service_href = $nom['service'];
715
			}
716
		} elseif ($this->correspondAUnCode($champ)) {
717
			$this->table_retour[$champ.'.libelle'] = $this->ajouterSignificationCode($champ, $valeur);
718
		}
719
	}
720
 
721
	/** Permet d'afficher les élements nomenclatural du nom_sci lors de l'appel dans le service noms/id/champ du champ^nom_sci.*/
722
	public function afficherNomSciPointEpithete($resultat) {
723
		$tab_nom_sci   = array('nom_supra_generique', 'genre', 'epithete_infra_generique', 'epithete_sp',
724
		'type_epithete', 'epithete_infra_sp', 'cultivar_groupe', 'cultivar', 'nom_commercial');
725
		foreach ($tab_nom_sci as $compo_nom) {
726
			if (isset($resultat[$compo_nom]) && !empty($resultat[$compo_nom])) {
727
				$this->table_retour['nom_sci.'.$compo_nom] = $resultat[$compo_nom];
728
			}
729
		}
730
	}
731
 
732
	public function ajouterSignificationCode($champ, $valeur) {
733
		if($this->termeOntologieEstEnCache($champ, $valeur)) {
734
			$nom_code = $this->obtenirTermeOntologieParCache($champ, $valeur);
735
		} else {
736
			$code = $this->transformerChampEnCode($champ);
737
			if (preg_match('/^([^_-]+)(?:_|-)([^_-]+)$/', $code, $match)) {
738
				$code = $match[1].ucfirst($match[2]);
739
			}
740
			$url = Config::get('url_ontologie').$code.':'.$valeur.'/nom';
741
			$res = $this->consulterHref($url); //dans commun.php
742
			$nom_code = $valeur;
743
			if (is_object($res)) {
744
				$nom_code = $res->nom;
745
			}
746
			$this->mettreEnCacheOntologie($champ, $valeur, $nom_code);
747
		}
748
		return $nom_code;
749
	}
750
 
751
	public function recupererNomSci($id) {
752
		$nom = array();
753
		if ($id != 0) {
754
			if ($this->compo_nom == null) {
755
				$req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html FROM '.$this->table.' WHERE num_nom = '.$id;
756
			} else { //on ajoute à la requete sql, les champs de ns.structure
757
				//print_r($this->compo_nom);
758
				$req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html, '.implode(', ', $this->compo_nom)
759
						.' FROM '.$this->table
760
						.' WHERE num_nom = '.$id;
761
			}
762
			if ($this->parametres['ns.format'] == 'htm') {
763
				$req = str_replace('nom_sci', 'nom_sci_html as nom_sci', $req);
764
			}
765
			$res = $this->getBdd()->recuperer($req);
766
			if ($res) {
767
				$nom['nom_sci']	= $res['nom_sci'];
768
				$nom['nom_sci_html']	= $res['nom_sci_html'];
769
				$nom['nom_sci_complet']	= $res['nom_sci'].' '.$this->ajouterCompositionNom($res);
770
				$nom['nom_sci_complet_html']	= $res['nom_sci_html'].' '.$this->ajouterCompositionNom($res, 'htm');
771
				$nom['service'] = ($res['num_nom_retenu'] == $id && $this->service == 'taxons') ? 'taxons' : 'noms';
772
			}
773
		}
774
		return $nom;
775
	}
776
 
777
	/** Permet de retourner une chaine de caractère composée des parametres du nom (ns.structure : annnée, auteur,
778
	 * bibilio et addendum). A ajouter au nom scientifique */
779
	public function ajouterCompositionNom($tab_res, $format = '') {
780
		$format = ($format == '') ? $this->parametres['ns.format'] : $format;
781
 
782
		$nom = '';
783
		if (isset($this->compo_nom)) {
784
			if ($format == 'htm') {
785
				$format = array(
786
					'au' => '<span class="auteur">%s</span>',
787
					'an' => '[<span class="annee">%s</span>]',
788
					'an_bib' => '[<span class="annee">%s</span>, <span class="biblio">%s</span>]',
789
					'bib' => '[<span class="biblio">%s</span>]',
790
					'ad' => '[<span class="adendum">%s</span>]');
791
			} else {
792
				$format = array(
793
					'au' => '%s',
794
					'an' => '[%s]',
795
					'an_bib' => '[%s, %s]',
796
					'bib' => '[%s]',
797
					'ad' => '[%s]',
798
					'gen' => '%s',
799
					'sp' => '%s',
800
					'ssp' => '%s',
801
					'fam' => '%s',
802
					'au_ss' => '%s',
803
					'bib_ss' => '%s');
804
			}
805
			$compo_nom = array();
806
 
807
			foreach ($this->compo_nom as $key => $champ) {
808
				if (isset($tab_res[$champ]) && !empty($tab_res[$champ])) {
809
					$compo_nom[$key] = $tab_res[$champ];
810
				}
811
			}
812
			$nom_complet = $this->formerNomComplet($compo_nom, $format);
813
			$nom = implode(' ', $nom_complet);
814
		}
815
		return rtrim($nom, ' ');
816
	}
817
 
818
 
819
	public function formerNomComplet($compo_nom, $format) {
820
		$nom_complet = array();
821
		extract($compo_nom);
822
		if (isset($au)) $nom_complet[] = sprintf($format['au'], $au);
823
		if (isset($an)) {
824
			if (isset($bib)) {
825
				$nom_complet[] = sprintf($format['an_bib'], $an, $bib);
826
			} else {
827
				$nom_complet[] = sprintf($format['an'], $an);
828
			}
829
		} elseif (isset($bib)) {
830
			$nom_complet[] = sprintf($format['bib'], $bib);
831
		}
832
		if (isset($ad)) $nom_complet[] = sprintf($format['ad'], $ad);
833
		if (isset($gen)) $nom_complet[] = sprintf($format['gen'], $gen);
834
		if (isset($ssp)) $nom_complet[] = sprintf($format['ssp'], $ssp);
835
		if (isset($sp)) $nom_complet[] = sprintf($format['sp'], $sp);
836
		if (isset($fam)) $nom_complet[] = sprintf($format['fam'], $fam);
837
		if (isset($au_ss)) $nom_complet[] = sprintf($format['au_ss'], $au_ss);
838
		if (isset($bib_ss)) {
839
			$bibl = $this->tronquerBiblio($bib_ss);
840
			//simule un 'select distinct' sur les biblio tronquées
841
			if (!isset($this->bib_traitees[$bibl])) {
842
				$nom_complet[] = sprintf($format['bib_ss'],$bibl );
843
				$this->bib_traitees[$bibl] = 1;
844
			}
845
		}
846
		return $nom_complet;
847
	}
848
 
849
	public function tronquerBiblio($valeur){
850
		$bib = '';
851
		if(strpos($valeur,',') !== false) {
852
			$bib = explode(',',$valeur);
853
		}
854
		if(strpos($bib[0],';') !== false) {
855
 
856
			$bib[0] = strstr($bib[0],';');
857
			$bib[0] = str_replace('; ','',$bib[0]);
858
		}
859
		return $bib[0];
860
	}
861
 
862
 
863
 
864
	public function correspondAUnCode($key) {
865
		return (strrpos($key, '.code') !== false) || (in_array($key.'.code', $this->correspondance_champs));
866
	}
867
 
868
	public function correspondAUnId($key) {
869
		return (strrpos($key, '.id') !== false) || (in_array($key.'.id', $this->correspondance_champs));
870
	}
871
 
872
	public function estUnPoint($key) {
873
		if (strrpos($key, 'hybride.parent') !== false) {
874
			$key = str_replace('hybride.parent', 'hybride_parent', $key);
875
		}
876
		return (strrpos($key, '.') !== false);
877
	}
878
 
879
	public function recupererMasquePrincipal() {
880
		$masque = null;
881
		$tab_masque   = array(
882
			'masque' => 'nom_sci',
883
			'masque_sg' => 'nom_supra_generique',
884
			'masque_gen' => 'genre',
885
			'masque_sp' => 'epithete_sp',
886
			'masque_ssp' => 'epithete_infra_sp',
887
			'masque_au' => 'auteur',
888
			'masque_an' => 'annee',
889
			'masque_bib' => 'biblio_origine',
890
			'masque_ad' => 'addendum',
891
			'masque_rg' => 'rang');
892
		$liste_masque = array();
893
 
894
		if (isset($this->masque['num_nom'])) {
895
			$liste_masque[] = $this->masque['num_nom'];
896
		}
897
 
898
		foreach ($tab_masque as $key => $filtre) {
899
            if (isset($this->masque[$filtre])) {
900
            	if (!isset($masque) && !in_array($filtre, array('rang', 'annee'))) {
901
            		$masque = array($key, $filtre);
902
            	}
903
                $liste_masque[] = $this->masque[$filtre];
904
            }
905
        }
906
        $this->masque = $liste_masque;
907
        return $masque;
908
	}
909
 
910
	private function mettreEnCacheOntologie($categorie, $valeur, $correspondance) {
911
		if(!isset($this->ontologie[$categorie])) {
912
			$this->ontologie[$categorie] = array();
913
		}
914
		if(!isset($this->ontologie[$categorie][$valeur])) {
915
			$this->ontologie[$categorie][$valeur] = array();
916
		}
917
		$this->ontologie[$categorie][$valeur] = $correspondance;
918
	}
919
 
920
	private function termeOntologieEstEnCache($categorie, $valeur) {
921
		return array_key_exists($categorie, $this->ontologie) && array_key_exists($valeur, $this->ontologie[$categorie]);
922
	}
923
 
924
	private function obtenirTermeOntologieParCache($categorie, $valeur) {
925
		return $this->ontologie[$categorie][$valeur];
926
	}
927
}
928
?>