Subversion Repositories eFlore/Projets.eflore-projets

Rev

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