Subversion Repositories eFlore/Projets.eflore-projets

Rev

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