Subversion Repositories eFlore/Projets.eflore-projets

Rev

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