Subversion Repositories eFlore/Projets.eflore-projets

Rev

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