Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 1108 | Rev 1195 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
6 jpm 1
<?php
966 raphael 2
 /**
3
 * Description :
4
 * Classe NomsVernaculaires.php fournit une liste de noms vernaculaires et leur liaison à la bdtfx
5
 * Le but étant de fournir un ensemble minimal d'information comprenant :
6
 * un identifiant (numérique ou alphanumérique sous forme de ChatMot si possible), un nom, une langue et
7
 * une relation avec un taxon de la bdtfx.
8
 * Si l'url finit par /noms-vernaculaires on retourne une liste de noms (seulement les 100 premières par défaut).
9
 * L'url peut contenir des paramètres optionnels passés après le ? : /observations?param1=val1&param2=val2&...
10
 *
1109 mathias 11
 * ATTENTION : /attributions groupe par taxon, le nombre de résultats est donc
12
  * inférieur ou égal au nombre demandé par navigation.limite
13
 *
966 raphael 14
 * Les paramètres de requête disponibles sont : masque, masque.code, masque.nom, masque.region , recherche,
15
 * distinct, retour.format, navigation.depart et navigation.limite.
16
 *
17
 * Encodage en entrée : utf8
18
 * Encodage en sortie : utf8
19
 * @package framework-v3
20
 * @author Delphine Cauquil <delphine@tela-botanica.org>
21
 * @author Jennifer Dhé <jennifer.dhe@tela-botanica.org>
22
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
23
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
24
 * @version 1.0
25
 * @copyright 1999-${year} Tela Botanica (accueil@tela-botanica.org)
26
 */
734 raphael 27
 
966 raphael 28
 // Un caractère de concaténation entre le projet et le service.
29
 // Ce caractère ne doit pas faire partie d'aucun des noms de service ou projet
30
 define('RES_VAL_SEP', '@');
31
 define('SPE_INDEX_NVJFL', '_result_ontologies' . RES_VAL_SEP . 'nvjfl');
734 raphael 32
 
966 raphael 33
 class NomsVernaculaires extends Commun {
832 raphael 34
 
966 raphael 35
     static $onto_multi_support = array('conseil_emploi', 'genre');
36
     static $champ_infos = array(
37
         'taxon' => array('service' => 'taxons', 'ressource' => 'nt:', 'projet' => 'bdtfx', 'nom' => 'nom_sci',
38
                          // utilisés par ajouterChampsOntologieLigneResultat()
39
                          'intitule' => 'taxon.code', // intitulé du champ tel qu'il sera renvoyé en JSON
40
                          'bdd_champ' => 'num_taxon'), // intitulé du champ tel qu'il est présent dans l'enregistrement MySQL
41
         'conseil_emploi' => array('service' => 'ontologies', 'ressource' => 'numStatut:', 'projet' => 'nvjfl', 'nom' => 'nom',
42
                                   'intitule' => 'conseil_emploi', 'bdd_champ' => 'num_statut'),
43
         'genre' => array('service' => 'ontologies', 'ressource' => 'genreNombre:', 'projet' => 'nvjfl', 'nom' => 'nom',
44
                          'intitule' => 'genre', 'bdd_champ' => 'num_genre'));
109 jpm 45
 
966 raphael 46
     protected $service = 'noms-vernaculaires';
109 jpm 47
 
966 raphael 48
     /**
49
      * Permet de stocker la requete formulée : /noms-vernaculaires | /noms-vernaculaires/#id |
50
      *  /noms-vernaculaires/#id/champ | /noms-vernaculaires/#id/relations
51
      * Est remplit au cours de l'analyse des ressources (traiterRessources()), par défaut, a la valeur du service.
52
      * Est utilisée principalement pr déterminer le format du tableau à retourner.	 */
53
     protected $format_reponse = 'noms-vernaculaires';
109 jpm 54
 
966 raphael 55
     /** Variables constituant les parametres de la requete SQL (champ, condition, limit) remplie
56
      * selon ressources et paramètres */
1109 mathias 57
     protected $requete_champ = array('*');
966 raphael 58
     protected $requete_condition = '';
59
     protected $limite_requete = array(
60
         'depart' => 0,
61
         'limite' => 100
62
     );
109 jpm 63
 
1107 mathias 64
	/**
65
	 * Vrai tri SQL
66
	 */
67
	protected $tri;
68
	protected $tri_ordre = 'asc';
109 jpm 69
 
1107 mathias 70
	// wtf ? on trie après avoir exécuté la requête ?
71
    protected $champ_tri = 'code_langue';
72
    protected $direction_tri = 'asc';
73
 
966 raphael 74
     /**
75
      * Indique les champs supplémentaires à retourner
76
      *  - conseil_emploi = conseil d'emploi du nom vernaculaire
77
      *  - genre = genre et nombre du nom
78
      *  - taxon = nom retenu associé à ce nom
79
      */
80
     protected $champs_supp = array();
109 jpm 81
 
966 raphael 82
     /**
83
      * Precise la contenance plus ou moins précise du tableau à retourner :
84
      *  - min = les données présentes dans la table
85
      *  - max = les données de la table + les informations complémentaires (pour les identifiants et les codes)
86
      *  - oss = la liste des nom_sci (uniquement pour noms et taxons) */
87
     protected $retour_format = 'max';
88
     /** Valeur du paramètre de requete recherche :
89
      *  - stricte : le masque est passé tel quel à l'opérateur LIKE.
90
      *  - etendue : ajout automatique du signe % à la place des espaces et en fin de masque avec utilisation de LIKE.
91
      *  - floue : recherche tolérante vis-à-vis d'approximations ou d'erreurs (fautes d'orthographe par exemple) */
92
     protected $recherche;
109 jpm 93
 
966 raphael 94
     /** Permet de stocker le tableau de résultat (non encodé en json) */
95
     protected $table_retour = array();
96
     /** Stocke le nombre total de résultats de la requete principale. Est calculée lors de l'assemblage de la requete */
97
     protected $total_resultat;
6 jpm 98
 
1107 mathias 99
     protected $config;
109 jpm 100
 
966 raphael 101
     public function __construct($config) {
102
         $this->config = is_null($config) ? Config::get('NomsVernaculaires') : $config;
103
     }
109 jpm 104
 
966 raphael 105
     //+------------------------------------------------------------------------------------------------------+
106
     // créer une condition en fonction du paramétre
107
     public function traiterParametres() {
108
         if (isset($this->parametres) && !empty($this->parametres)) {
109 jpm 109
 
966 raphael 110
             if (isset($this->parametres['recherche']) && $this->parametres['recherche'] != '') {
111
                 $this->recherche = $this->parametres['recherche'];
112
             }
113
             foreach ($this->parametres as $param => $valeur) {
114
                 switch ($param) {
115
                     case 'masque' :
116
                         $this->ajouterFiltreMasque('nom_vernaculaire', $valeur);
117
                         break;
118
                     case 'masque.nt' :
119
                         $this->ajouterFiltreMasque('num_taxon', $valeur);
120
                         break;
121
                     case 'masque.nv' :
122
                         $this->ajouterFiltreMasque('nom_vernaculaire', $valeur);
123
                         break;
124
                     case 'masque.lg' :
125
                         $this->ajouterFiltreMasque('code_langue', $valeur);
126
                         break;
127
                     case 'masque.cce' :
128
                         $this->ajouterFiltreMasque('num_statut', $valeur);
129
                         break;
130
                     case 'retour.format' :
131
                         $this->retour_format = $valeur;
132
                         break;
1107 mathias 133
                     case 'retour.tri' :
134
                         $this->tri = $valeur;
135
                         break;
136
                     case 'retour.ordre' :
137
						 if (in_array(strtolower($valeur), aray('asc', 'desc'))) {
138
							$this->tri_ordre = $valeur;
139
						 }
140
                         break;
966 raphael 141
                     case 'navigation.depart' :
142
                         $this->limite_requete['depart'] = $valeur;
143
                         break;
144
                     case 'navigation.limite' :
145
                         $this->limite_requete['limite'] = $valeur;
146
                         break;
147
                     case 'retour.champs' :
148
                         $this->champs_supp = explode(',',$valeur);
149
                     break;
150
                     case 'recherche' :
151
                         break;
152
                     case 'version.projet' :
153
                         break;
154
                     default :
155
                         $p = 'Erreur dans les paramètres de recherche de votre requête : '.
156
                             '</br> Le paramètre " '.$param.' " n\'existe pas.';
157
                             $this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $p);
158
                 }
159
             }
160
         }
161
     }
109 jpm 162
 
966 raphael 163
     public function ajouterFiltreMasque($nom_champ, $valeur) {
164
         if ($nom_champ == 'num_taxon') { // si il s'agit d'un chiffre
165
             $this->requete_condition[] = $nom_champ.' = '.$this->getBdd()->proteger($valeur);
166
         } else {
167
             if ($this->recherche == 'floue') {
168
                 $this->requete_condition[] = '(SOUNDEX('.$nom_champ.') = SOUNDEX(\''.$valeur.'\')'
169
                     .' OR SOUNDEX(REVERSE('.$nom_champ.')) = SOUNDEX(REVERSE(\''.$valeur.'\'))) ';
170
             } else {
171
                 if ($this->recherche == 'etendue') {
172
                     $valeur = '%'.str_replace(' ','% ', $valeur);
173
                     $valeur .= '%';
174
                 }
175
                 $this->requete_condition[] = $nom_champ.' LIKE '.$this->getBdd()->proteger($valeur);
176
             }
177
         }
178
     }
109 jpm 179
 
966 raphael 180
     //+------------------------------------------------------------------------------------------------------+
181
     // en fonction de la présence des ressources modifie requete_champ et requete_condition
182
     public function traiterRessources() {
183
         if (isset($this->ressources) && !empty($this->ressources)) {
184
             if (isset($this->ressources[0]) && !empty($this->ressources[0])) {
185
                 $this->traiterRessourceId(); // ajoute condition id=#valeur
186
                 if (isset($this->ressources[1]) && !empty($this->ressources[1])) {
187
                     $this->traiterRessourceChamp(); //modifie requete_champ ou requete_condition
188
                 }
189
             }
190
         } else { //rajoute distinct pour ne pas avoir plusieurs fois le même nom
191
             $this->requete_champ = array('distinct(id)', 'nom_vernaculaire ');
1107 mathias 192
			 $this->requete_champ = array_merge($this->requete_champ, $this->champs_supp);
966 raphael 193
         }
194
     }
109 jpm 195
 
966 raphael 196
     //requete : /noms-vernaculaires/#id (ex : /noms-vernaculaires/7)
197
     public function traiterRessourceId() {
198
         if (is_numeric($this->ressources[0])) {
199
             $this->requete_condition[] = ' id = '.$this->getBdd()->proteger($this->ressources[0]);
200
             $this->format_reponse .= '/id';
201
         } elseif ($this->ressources[0] == 'attributions') {
202
             $this->format_reponse .= '/attributions';
203
         } else {
204
             $r = 'Erreur dans les ressources de votre requête : </br> La ressource " '.$this->ressources[0].
205
                 ' " n\'existe pas.';
206
             $this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $r);
207
         }
208
     }
109 jpm 209
 
210
 
966 raphael 211
     public function traiterRessourceChamp() {
212
         $this->format_reponse .= '/champ';
213
         $this->analyserChamp();
214
     }
215
 
1109 mathias 216
    public function analyserChamp() {
217
        $this->recupererTableConfig('champs_possibles');// s'il y a plusieurs champs correspondant au champ demandé ils sont séparé par des |
218
        $champs = explode(' ', $this->ressources[1]);
219
		//$this->requete_champ = array(); // * car absence de mappings
220
        foreach ($champs as $champ) {
221
            preg_match('/^([^.]+)(\.([^.]+))?$/', $champ, $match);
222
            if (isset($this->champs_possibles[$match[1]])) {
223
				// wtf?
224
                //$this->requete_champ[] = str_replace('|', ', ', $this->champs_possibles[$match[1]]);
225
				// marche pas, pour chaque champ il faut en retourner un qui a un
226
				// autre nom etc. , pas le temps de faire des mappings
227
				$this->requete_champ[] = $match[1];
228
            } elseif (isset($this->champs_possibles[$match[0]])) {
229
				// wtf ?
230
                $this->requete_champ[] = str_replace('|', ', ', $this->champs_possibles[$match[0]]);
231
            } else {
232
                $champs_possibles = implode('</li><li>', array_keys($this->champs_possibles));
233
                $c = 'Erreur dans votre requête : </br> Le champ "'.$champ_possibles.'" n\'existe pas. '.
966 raphael 234
                     'Les champs disponibles sont : <li>'.$champs_possibles.'</li> et leurs déclinaisons (ex. ".code").';
1109 mathias 235
                $this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $c);
236
            }
237
        }
238
    }
966 raphael 239
 
1108 mathias 240
	 // fait du neuf avec du vieux
241
	public function assemblerLaRequete() {
242
		$requete = false;
243
		if ($this->format_reponse == 'noms-vernaculaires') {
244
			// mode liste
245
			$requete = $this->assemblerRequeteListe();
246
		} else {
247
			$requete = $this->assemblerRequeteAutre();
248
		}
249
		return $requete;
250
	}
1107 mathias 251
 
1108 mathias 252
	/**
253
	 * Exécute un astucieux GROUP BY afin que le service retourne ce qu'il
254
	 * annonce qu'il retourne (truc de ouf!) - pour le mode "liste"
255
	 */
256
	protected function assemblerRequeteListe() {
257
		$count = $this->recupererTotalResultat();
258
		$limiteClause = self::formerRequeteLimite( // LIMIT
259
			$this->limite_requete['depart'],
260
			$count,
261
			$this->limite_requete['limite']
262
		);
263
        $req = sprintf(
264
            'SELECT %s, group_concat(num_taxon) as num_taxon, IF(num_statut="",1,0) AS is_null' .
265
            ' FROM %s WHERE %s GROUP BY id ORDER BY %s is_null ASC, num_statut ASC %s -- %s:%d',
966 raphael 266
 
1108 mathias 267
            in_array('*', $this->requete_champ) ? ' * ' : implode(', ', $this->requete_champ),
268
            $this->table,
269
            $this->requete_condition ? implode(' AND ', $this->requete_condition) : 'TRUE',
270
			$this->tri ? ($this->tri . ' ' . $this->tri_ordre . ', ') : '',
271
            $limiteClause,
272
            __FILE__, __LINE__);
273
		return $req;
274
	}
275
 
276
	 /**
277
	  * Ancien système d'assemblage de requête
278
	  */
279
	protected function assemblerRequeteAutre() {
280
        $nolimit = in_array(
281
            $this->format_reponse,
282
            array($this->service.'/id', $this->service.'/id/champs'));
283
        if(!$nolimit) {
284
            $count = $this->recupererTotalResultat();
285
            $limiteClause = self::formerRequeteLimite( // LIMIT
286
                $this->limite_requete['depart'],
287
                $count,
288
                $this->limite_requete['limite']);
289
        }
290
        $req = sprintf(
291
            'SELECT %s, IF(num_statut="",1,0) AS is_null' .
292
            ' FROM %s WHERE %s ORDER BY %s is_null ASC, num_statut ASC %s -- %s:%d',
293
 
294
            in_array('*', $this->requete_champ) ? ' * ' : implode(', ', $this->requete_champ),
295
            $this->table,
296
            $this->requete_condition ? implode(' AND ', $this->requete_condition) : 'TRUE',
297
			$this->tri ? ($this->tri . ' ' . $this->tri_ordre . ', ') : '',
298
            $nolimit ? '' : $limiteClause,
299
            __FILE__, __LINE__);
300
		return $req;
301
	}
302
 
109 jpm 303
	//ajout d'une limite seulement pour les listes (pas plus de 100 resultats retournés pr les requetes
6 jpm 304
	// suivantes : /noms-vernaculaires et /noms-vernaculaires/#id/relations)
966 raphael 305
	static function formerRequeteLimite(&$depart, $total, $limite) {
306
        if ($depart > $total) {
307
			$depart = $total - $limite < 0 ? 0 : ($total - $limite);
308
			return ' LIMIT ' . $depart . ', ' . $limite;
309
        }
310
        return ' LIMIT ' . $depart . ', ' . $limite;
6 jpm 311
	}
109 jpm 312
 
6 jpm 313
	//on récupère le nombre total de résultats de la requete (ex : le nombre d'id contenu dans la liste /noms-vernaculaires)
314
	public function recupererTotalResultat() {
966 raphael 315
        $res = $this->getBdd()->recuperer(sprintf(
316
            'SELECT COUNT(%s) AS nombre FROM %s WHERE %s -- %s:%d',
317
 
318
            $this->format_reponse == 'noms-vernaculaires/attributions' ? 'id' : 'distinct(id)',
319
            $this->table,
320
            $this->requete_condition ? implode(' AND ', $this->requete_condition) : 'TRUE',
321
            __FILE__, __LINE__));
109 jpm 322
 
966 raphael 323
		if (! $res)
324
            throw new Exception('Données introuvables', RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
325
        if($res['nombre'] == 0) {
326
            print json_encode(
327
                array(
328
                    "entete" => array(
329
                        "depart" => $this->limite_requete['depart'],
330
                        "limite" => $this->limite_requete['limite'],
331
                        "masque" => $this->recupererMasque(),
332
                        "total" => 0
333
                    ),
334
                    "resultat" => array()
335
                ));
336
            die; // die() très dommage (pour phpunit), mais la stack d'imbrication ne nous permet pas de retourner proprement
337
            }
338
 
980 mathias 339
        $this->total_resultat = $res['nombre'];
966 raphael 340
        return $res['nombre'];
6 jpm 341
	}
109 jpm 342
 
343
	//+------------------------------------------------------------------------------------------------------+
344
	// determine en fct du service appelé (/noms-vernaculaires | /noms-vernaculaires/#id | /noms-vernaculaires/#id/champ |
6 jpm 345
	// /noms-vernaculaires/#id/relations) le format du tableau à retourner.
346
	public function retournerResultatFormate($resultat) {
347
		$this->recupererTableConfig('correspondance_champs');
348
		switch ($this->format_reponse) {
132 aurelien 349
			case 'noms-vernaculaires'				:
350
				$reponse = ($this->retour_format == 'oss') ? $this->formaterEnOss($resultat) : $this->formaterNomsVernaculaires($resultat);			break;
160 delphine 351
			case 'noms-vernaculaires/attributions'	: $reponse = $this->formaterNomsVernaculairesAttributions($resultat);	break;
6 jpm 352
			case 'noms-vernaculaires/id'			: $reponse = $this->formaterNomsVernaculairesId($resultat);			break;
353
			case 'noms-vernaculaires/id/champ'		: $reponse = $this->formaterNomsVernaculairesIdChamp($resultat);	break;
354
			default									:																	break;
355
		}
356
		return $reponse;
357
	}
608 mathilde 358
 
359
	public function ajouterJsonEnTeteNV() {
360
		$table_retour_json['masque'] = $this->recupererMasque();
361
		$table_retour_json['depart'] = $this->limite_requete['depart'];
362
		$table_retour_json['limite'] = $this->limite_requete['limite'];
363
		$table_retour_json['total']  = $this->total_resultat;
6 jpm 364
		$url = $this->formulerUrl($this->total_resultat, '/noms-vernaculaires');
608 mathilde 365
		if (isset($url['precedent']) && $url['precedent'] != '') {
366
			$table_retour_json['href.precedent'] = $url['precedent'];
6 jpm 367
		}
608 mathilde 368
		if (isset($url['suivant']) && $url['suivant']   != '') {
369
			$table_retour_json['href.suivant']   = $url['suivant'];
152 delphine 370
		}
608 mathilde 371
		return $table_retour_json;
372
	}
1108 mathias 373
 
374
	/**
375
	 * @TODO Ne devrait pas retourner un oblet mais un Array (conserve l'ordre,
376
	 * évite d'écraser des clefs etc.)
377
	 */
608 mathilde 378
	public function ajouterJsonResultatNV($resultat) {
1108 mathias 379
		$resultat_json = array();
6 jpm 380
		foreach ($resultat as $tab) {
1108 mathias 381
			$this->table_retour = array();
6 jpm 382
			foreach ($tab as $key => $valeur) {
383
				if ($valeur != '') {
384
					switch ($key) {
385
						case 'id'				: $num = $valeur;								break;
386
						case 'nom_vernaculaire'	: $this->table_retour['nom'] = $valeur;			break;
387
						default					:												break;
388
					}
1107 mathias 389
					// champs supplémentaires
390
					if (in_array($key, $this->champs_supp)) {
391
						$this->table_retour[$key] = $valeur;
392
					}
6 jpm 393
				}
394
			}
608 mathilde 395
		    if ($this->retour_format == 'max') $this->table_retour['href'] = $this->ajouterHref('noms-vernaculaires', $num);
6 jpm 396
			$resultat_json[$num] = $this->table_retour;
397
		}
1108 mathias 398
		return $resultat_json;
608 mathilde 399
	}
109 jpm 400
 
608 mathilde 401
 
402
	public function formaterNomsVernaculaires($resultat) {
403
		$table_retour_json['entete'] = $this->ajouterJsonEnTeteNV();
404
		$resultat = $this->hierarchiserResultat($resultat);
405
		$table_retour_json['resultat'] = $this->ajouterJsonResultatNV($resultat);
6 jpm 406
		return $table_retour_json;
407
	}
132 aurelien 408
 
608 mathilde 409
	public function hierarchiserResultat($resultat) {
410
		//tri recherche floue
411
		if (isset($this->parametres['masque.nv'])) {
966 raphael 412
			return $this->trierRechercheFloue($this->parametres['masque.nv'], $resultat, 'nom_vernaculaire');
608 mathilde 413
		}
414
		if (isset($this->parametres['masque'])) {
966 raphael 415
			return $this->trierRechercheFloue($this->parametres['masque'], $resultat, 'nom_vernaculaire');
608 mathilde 416
		}
417
		return $resultat;
418
	}
419
 
160 delphine 420
	public function recupererMasque() {
421
		$tab_masque = array();
422
		foreach ($this->parametres as $param=>$valeur) {
423
			if (strstr($param, 'masque') != false) {
424
				$tab_masque[] = $param.'='.$valeur;
425
			}
426
		}
966 raphael 427
		return implode('&', $tab_masque);
160 delphine 428
	}
429
 
132 aurelien 430
	public function formaterEnOss($resultat) {
431
		$table_nom = array();
432
		$oss = '';
433
		foreach ($resultat as $tab) {
434
			if (isset($tab['nom_vernaculaire']) ) {
435
				if (!in_array($tab['nom_vernaculaire'], $table_nom)) {
436
					$table_nom[] = $tab['nom_vernaculaire'];
437
					$oss [] = $tab['nom_vernaculaire'];
438
				}
439
			}
440
		}
441
		if (isset($this->masque)) $masque = implode('&', $this->masque);
442
		else $masque = 'Pas de masque';
966 raphael 443
		return array($masque, $oss);
132 aurelien 444
	}
160 delphine 445
 
446
	public function formaterNomsVernaculairesAttributions($resultat) {
447
		//on remplie la table $table_retour_json['entete']
448
		$table_retour_json['entete']['masque'] = $this->recupererMasque();
449
		$table_retour_json['entete']['depart'] = $this->limite_requete['depart'];
450
		$table_retour_json['entete']['limite'] = $this->limite_requete['limite'];
451
		$table_retour_json['entete']['total']  = $this->total_resultat;
452
		$url = $this->formulerUrl($this->total_resultat, '/noms-vernaculaires/attributions');
729 raphael 453
		if (!empty($url['precedent'])) {
160 delphine 454
			$table_retour_json['entete']['href.precedent'] = $url['precedent'];
455
		}
729 raphael 456
		if (!empty($url['suivant'])) {
160 delphine 457
			$table_retour_json['entete']['href.suivant']   = $url['suivant'];
458
		}
1109 mathias 459
		$resultat_json = array();
888 raphael 460
		foreach ($resultat as &$tab) {
730 raphael 461
			$nnv = $tab['num_nom_vernaculaire'];
462
			$resultat_json[$nnv]['id'] = $tab['id'];
463
			$resultat_json[$nnv]['nom_vernaculaire'] = $tab['nom_vernaculaire'];
888 raphael 464
			$resultat_json[$nnv]['langue.code'] = $resultat_json[$nnv]['code_langue'] = $tab['code_langue'];
730 raphael 465
			$resultat_json[$nnv]['taxon.code'] = 'bdtfx.nt:'.$tab['num_taxon'];
160 delphine 466
			if ($this->retour_format == 'max') {
284 jpm 467
				$this->taxons[] = $tab['num_taxon']; // utilisé pour chercher les noms latins plus bas
729 raphael 468
				if($this->champs_supp) {
730 raphael 469
					//$resultat_json[$nnv] = $this->ajouterChampsOntologieLigneResultat($tab);
470
					// simple initialisation par copie de la référence de l'original
471
					$resultat_json[$nnv] = &$tab;
1109 mathias 472
				} else {
730 raphael 473
					$resultat_json[$nnv]['num_taxon'] = $tab['num_taxon'];
474
					$resultat_json[$nnv]['nom_retenu.code'] = $tab['num_taxon'];
475
					$resultat_json[$nnv]['taxon'] = $tab['num_taxon'];
476
					$resultat_json[$nnv]['href'] = $this->ajouterHref('noms-vernaculaires', $tab['id']);
729 raphael 477
				}
160 delphine 478
			}
280 aurelien 479
		}
730 raphael 480
 
481
		// dans ce cas (particulier?) nous n'avons pour l'heure initialisé qu'une référence
482
		// vers le tableau de valeurs original
483
		if ($this->retour_format == 'max' && $this->champs_supp) {
484
			// récupérons désormais les ontologies
485
			$this->ajouterChampsOntologieLigneTousResultats($resultat_json);
486
		}
487
 
280 aurelien 488
		if ($this->retour_format == 'max') {
1109 mathias 489
			// Deuxième boucle pour demander tous lestaxons présents en une
284 jpm 490
			// fois et les attribuer aux noms car c'est beaucoup plus rapide
491
			$noms_sci = $this->recupererNomTaxons();
286 aurelien 492
			foreach ($resultat_json as $num_nom => &$tab) {
493
				$tab = $this->ajouterTaxonsAttributionsLigneResultat($tab, $noms_sci);
627 aurelien 494
				if($tab == null) {
495
					unset($resultat_json[$num_nom]);
496
				}
284 jpm 497
			}
160 delphine 498
		}
280 aurelien 499
 
160 delphine 500
		$table_retour_json['resultat'] = $resultat_json;
501
		return $table_retour_json;
502
	}
503
 
286 aurelien 504
	/**
505
	 * Ajoute les champs d'ontologie supplémentaires si necéssaire
832 raphael 506
	 * en faisant appels aux web services associés.
507
	 * Les appels peuvent être fait individuellement (pour un couple <ontologie:valeur>) ou bien
508
	 * regroupés, **si le webservice correspondant le supporte**.
509
	 *
510
	 * Nous disposons à ce jour de 3 (trois) webservices d'ontologies correspondant aux noms vernaculaires (cf $champ_infos)
511
	 * Mais 2 d'entre eux sont identiques, il s'agit de /nvjfl/ontologies/. Or ce webservice supporte le multi-critère.
512
	 * Nous pouvons donc factorisé l'appel pour "conseil_emploi" et "genre", mais pas pour "taxon".
513
	 *
730 raphael 514
	 * @param array in/out $resultats: tous les résultats
515
	 */
516
	public function ajouterChampsOntologieLigneTousResultats(&$resultats) {
832 raphael 517
		$champs_sup = array_intersect($this->champs_supp, array_keys(self::$champ_infos));
730 raphael 518
 
832 raphael 519
		// La regroupement des toutes les valeurs recherchées (pour tous les
520
		// résultats), pour "les" onotologies supportant le multi-critère est effectué ci-dessous.
521
		// Dans les faits ce n'est le cas que pour nvjfl.
522
		$ontologieParamPending = self::NvjflOntologieIndex($resultats, $champs_sup);
523
		$this->NvjflOntologieExpand($ontologieParamPending);
524
		self::NvjflOntologieCombine($resultats);
730 raphael 525
 
832 raphael 526
		// pour les ontologies multi-critères, on vient de le régler ci-dessus
527
		$champs_sup = array_diff($champs_sup, self::$onto_multi_support);
528
 
529
 
530
		// ici, $champs_sup ne peut contenir, au plus, que "taxon".
531
		// code historique:
532
		foreach($champs_sup as $cle) {
533
			$champs_supplementaires = self::$champ_infos[$cle];
730 raphael 534
			// extrait, depuis un élément de $champ_infos:
535
			// $service, $ressource, $projet, $nom, $intitule, $bdd_champ
536
			extract($champs_supplementaires);
537
 
538
			foreach ($resultats as &$tab) {
539
				$valeur_recherche = $tab[$bdd_champ];
540
				if(!trim($valeur_recherche)) continue;
541
 
542
				$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur_recherche, $projet);
543
				$tab[$intitule] = $this->chercherSignificationCode($url, $nom);
544
			}
545
		}
546
	}
547
 
731 raphael 548
	/* Récupère les valeurs recherchées pour une liste de résultats, (plus ou moins)
549
	   spécifiquement au service d'Ontologies de NVJFL.
550
	   Aggrège les valeurs dans le tableau retourné.
551
	   Une référence vers l'index du tableau (NULL pour l'instant) est laissée dans
552
	   un élément du résultat. */
832 raphael 553
	static function NvjflOntologieIndex(&$resultats, $champs_sup) {
554
		// nous ne supportons le multi-critère que sur les ontologies nvjfl, et nous
555
		// avons précisé celles qui sont concernées dans self::$onto_multi_support
556
		$champs_sup = array_intersect($champs_sup, self::$onto_multi_support);
731 raphael 557
		$ontologieParamPending = Array();
558
		foreach($resultats as &$resultat) {
832 raphael 559
			foreach($champs_sup as $v) {
560
				// de cet extract() nous n'utilisons que $bdd_champ et $ressource
561
				extract(self::$champ_infos[$v]);
562
				if(!isset($resultat[$bdd_champ])) continue;
563
 
564
				$valeur_recherche = $resultat[$bdd_champ];
565
				if(!trim($valeur_recherche)) continue;
566
 
567
				// XXX: $ressource contient déjà ':' comme suffixe
568
				$critere = $ressource . $valeur_recherche;
569
				$ontologieParamPending[$critere] = NULL;
570
				// placeholder pour le résultat
571
				$resultat[SPE_INDEX_NVJFL][$v][$critere] =
572
					&$ontologieParamPending[$critere];
573
			}
731 raphael 574
		}
575
		return $ontologieParamPending;
576
	}
577
 
578
	// TODO: switch to static si il peut en être de même pour ajouterHrefAutreProjet()
579
	/* À partir d'un aggrégat des critère de requêtes d'ontologies, spécifiques à NVJFL,
580
	   créé une URL multi-critère.
581
	   Celle-ci, dans ce cas précis, n'est que la concaténation, par des virgules,
832 raphael 582
	   des couples <ressource:ValeurRecherchée>.
583
	   L'URL est appelée et la valeur correspondante est remplacée dans $criteres_requete.
731 raphael 584
 
585
	   Note: dans le cadre du tryptique index/expand/combine pour lequel cette fonction existe,
832 raphael 586
	   la valeur est référencée par un élément d'une ou plusieurs lignes de $resultat correspondantes.
731 raphael 587
	   Celle(s)-ci sera[ont] donc changée(s) dans la foulée. */
588
	public function NvjflOntologieExpand(&$criteres_requete) {
589
		// équivalent spécifique de ajouterHrefAutreProjet()
590
		$valeurs_requises = implode(',', array_keys($criteres_requete));
832 raphael 591
		// en vérité, nous ne supportons ceci ici que pour nvjfl et non n'importe quel url_service
809 raphael 592
		$url = Config::get('url_service').'/ontologies/'.$valeurs_requises;
731 raphael 593
		$val = $this->consulterHref($url);
831 raphael 594
 
595
		// TODO, le webservice d'ontologies devrait être modifié pour retourner un tableau
596
		// indexé par critère requesté à *CHAQUE* fois, y compris lorsque 1 seul critère est
597
		// demandé.
598
		if(array_key_exists('id', $val) && count($criteres_requete) == 1) {
599
			$k = key($criteres_requete);
600
			$criteres_requete[$k] = $val;
601
			return;
602
		}
603
 
832 raphael 604
		// subtilité, cette affectation modifie par conséquent les valeurs dans
605
		// $resultats[X][SPE_INDEX_NVJFL]
731 raphael 606
		// dont la référence pointe toujours sur $v
607
		foreach($val as $k => $v) $criteres_requete[$k] = $val->$k;
608
	}
609
 
610
	/* Fonction finale du tryptique: réordonne les valeurs obtenues auprès du web-service
832 raphael 611
	   NVJFL en adéquation avec les champs attendus en sortie.
612
	   Dès l'indexation des critères, nous avons associé une (ou plusieurs) référence(s) du
613
	   tableau de résultats vers le tableau de retour des ontologies à l'aide d'un index
614
	   particulier l'index SPE_INDEX_NVJFL qui contient comme élément(s)
615
	   un ou plusieurs ontologies (les indexes de self::$champ_infos) qui elles-mêmes contiennent
616
	   une ou plusieurs valeurs représentant les valeurs recherchées appartement à cette ontologies.
617
	   Celui-ci est supprimé après avoir été correctement copié. */
618
	/**
619
	 * @param array in/out $resultats: tous les résultats
620
	 * @param array in $critere: tableau des ontologies:valeur demandées, de la forme [ numStatut:1, genreNombre:11, ... ]
621
	 */
848 raphael 622
	static function NvjflOntologieCombine(&$resultats) {
731 raphael 623
		foreach($resultats as &$resultat) {
832 raphael 624
			if(!array_key_exists(SPE_INDEX_NVJFL, $resultat)) continue;
625
 
626
			/* Note: la complétude d'un résultat peut dépendre de plusieurs ontologies différentes,
627
			   d'où cette boucle. Cependant une seule valeur sera demandé pour cette ontologie, c'est pourquoi
628
			   $resultat[SPE_INDEX_NVJFL][$onto_name], s'il existe, ne contiendra toujours qu'un seul élément.
629
			   Puisque par définition un résultat contenant des valeurs d'ontologie n'aura jamais qu'un seul et unique
630
			   attribut num_genre (ou num_statut, ou autre) */
631
			foreach(self::$onto_multi_support as $onto_name) {
848 raphael 632
				if(!array_key_exists($onto_name, $resultat[SPE_INDEX_NVJFL])) continue;
633
 
832 raphael 634
				/* $onto_name est un nom d'ontologie (l'une des clefs, parmi conseil_emploi et genre,
635
				   cf la boucle sur $champs_sup dans  NvjflOntologieIndex()
636
				   de cet extract() nous n'utilisons que $intitule et $nom */
637
				extract(self::$champ_infos[$onto_name]);
638
 
639
				// equivalent de l'affectation finale de chercherSignificationCode()
640
				// (utilisé lors de recherches d'ontologies en mono-critère)
641
				// XXX: PHP-5.3 pas de récupération d'attribut sur fonction
642
				$r = current($resultat[SPE_INDEX_NVJFL][$onto_name]);
643
				$resultat[$intitule] = $r->$nom;
644
 
645
				// XXX: certes nous pourrions nous contenter du unset() final
646
				unset($resultat[SPE_INDEX_NVJFL][$onto_name]);
647
			}
648
			unset($resultat[SPE_INDEX_NVJFL]);
731 raphael 649
		}
650
	}
651
 
730 raphael 652
	/**
653
	 * Ajoute les champs d'ontologie supplémentaires si necéssaire
654
	 * en faisant appels aux web services associés
286 aurelien 655
	 * @param array $ligne_resultat
656
	 *
657
	 * @return array la ligne modifiée
658
	 */
284 jpm 659
	public function ajouterChampsOntologieLigneResultat($ligne_resultat) {
832 raphael 660
		foreach(self::$champ_infos as $cle => $champs_supplementaires) {
729 raphael 661
			if(!in_array($cle, $this->champs_supp)) continue;
662
			// extrait, depuis un élément de $champ_infos:
663
			// $service, $ressource, $projet, $nom, $intitule, $bdd_champ
664
			extract($champs_supplementaires);
665
			$valeur_recherche = $ligne_resultat[$bdd_champ];
666
			if(!trim($valeur_recherche)) continue;
667
			$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur_recherche, $projet);
668
			$ligne_resultat[$intitule] = $this->chercherSignificationCode($url, $nom);
277 aurelien 669
		}
284 jpm 670
		return $ligne_resultat;
277 aurelien 671
	}
672
 
284 jpm 673
	/**
674
	 * Fonction qui ajoute les attributions à une ligne de résultats
675
	 *
676
	 * @param array $ligne_tableau_resultat
677
	 * @param array $nom_sci
678
	 */
679
	public function ajouterTaxonsAttributionsLigneResultat(&$ligne_tableau_resultat, &$noms_sci) {
285 aurelien 680
		if (isset($noms_sci[$ligne_tableau_resultat['num_taxon']])) {
681
			$ligne_tableau_resultat['nom_retenu.code'] = $noms_sci[$ligne_tableau_resultat['num_taxon']]['id'];
682
			$ligne_tableau_resultat['taxon'] = $noms_sci[$ligne_tableau_resultat['num_taxon']]['nom_sci'];
627 aurelien 683
		} else {
684
			$ligne_tableau_resultat = null;
284 jpm 685
		}
686
		return $ligne_tableau_resultat;
687
	}
688
 
689
	private function trierLigneTableau($a, $b) {
690
		$retour = 0;
691
 
692
		if ($a[$this->champ_tri] == $b[$this->champ_tri]) {
693
			$retour = 0;
694
		}
695
 
696
		if($this->champ_tri == 'code_langue') {
697
			if ($a[$this->champ_tri] == 'fra' && $b[$this->champ_tri] != 'fra') {
698
				$retour = ($this->direction_tri == 'asc') ? -1 : 1;
699
			} else if ($a[$this->champ_tri] != 'fra' && $b[$this->champ_tri] == 'fra') {
700
				$retour = ($this->direction_tri == 'asc') ? 1 : -1;
701
			} else {
702
				$retour = $this->comparerChaineSelonDirectionTri($a[$this->champ_tri], $b[$this->champ_tri]);
703
			}
704
		} else {
705
			$retour = $this->comparerChaineSelonDirectionTri($a[$this->champ_tri], $b[$this->champ_tri]);
706
		}
707
		return $retour;
708
	}
709
 
710
	private function comparerChaineSelonDirectionTri($a, $b) {
711
		if($this->direction_tri == 'asc') {
712
			return ($a < $b) ? -1 : 1;
713
		} else {
714
			return ($a > $b) ? -1 : 1;
715
		}
716
	}
717
 
6 jpm 718
	// formatage de la reponse /id ss la forme
719
	// id, nom_vernaculaire, attributions
720
	// langue
721
	// num_nom (correspond à un taxon bdtfx)
722
	public function formaterNomsVernaculairesId($resultat) {
723
		foreach ($resultat as $taxon) { // pour chaque attribution à un taxon bdtfx
724
			// on crée les variables qui serviront de clés et on les enléves du tableau
725
			$num_nom = $taxon['num_nom_vernaculaire']; // unique pour un trinôme id, langue, taxon
726
			unset($taxon['num_nom_vernaculaire']);
727
			$langue = $taxon['code_langue'];
728
			unset($taxon['code_langue']);
109 jpm 729
 
6 jpm 730
			foreach ($this->correspondance_champs as $key => $correspondance) { // ordonne les infos pour affichage
731
				if (isset($taxon[$key]) && $taxon[$key] != "") {
732
					$this->afficherDonnees($correspondance, $taxon[$key], $langue, $num_nom);
733
				}
734
			}
735
			foreach ($taxon as $key => $valeur) { // rajoute les champs non prévus dans l'api
736
				if (!isset($this->correspondance_champs[$key]) && $valeur != "") {
737
					$this->afficherDonnees($key, $valeur, $langue, $num_nom);
738
				}
739
			}
740
			if ($this->retour_format == 'max') $this->chargerBiblio($num_nom, $langue);
741
		}
742
		if ($this->retour_format == 'max') $this->afficherTaxons(); // va chercher les noms de tous les taxons
743
		unset($this->table_retour['href']);
744
		return $this->table_retour;
745
	}
109 jpm 746
 
6 jpm 747
	public function afficherDonnees($champ, $valeur, $langue = '', $num_nom = '') {
748
		if ($champ == 'id' || $champ == 'nom_vernaculaire') {
749
			$this->table_retour[$champ] = $valeur;
750
		} elseif (preg_match('/^(.*)\.code$/', $champ, $match)) {
751
				switch ($match[1]) {
752
					case 'taxon'	: if ($this->retour_format == 'max') {$this->taxons[$num_nom] = $valeur;}
753
						$this->afficherPointCode($match[1], $langue, $num_nom, $valeur);	break;
109 jpm 754
					case 'langue'	: //$this->afficherPointCode($match[1], 'iso-639-3', 'langues', $valeur);
6 jpm 755
						break;
756
					case 'genre'	: $this->afficherPointCode($match[1], $langue, $num_nom, $valeur);	break;
757
					case 'conseil_emploi'	: $this->afficherPointCode($match[1], $langue, $num_nom, $valeur);	break;
758
					default : break;
759
				}
109 jpm 760
 
6 jpm 761
		} elseif ($langue != '') {
762
			$this->table_retour['attributions'][$langue][$num_nom][$champ] = $valeur;
763
		} else {
764
			$this->table_retour[$champ] = $valeur;
765
		}
766
	}
109 jpm 767
 
6 jpm 768
	public function afficherPointCode($nomChamp, $langue, $num_nom, $valeur) {
832 raphael 769
		if (isset(self::$champ_infos[$nomChamp])) {
770
			extract(self::$champ_infos[$nomChamp]);
6 jpm 771
		}
109 jpm 772
 
6 jpm 773
		if ($this->retour_format == 'max') {
774
			$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur, $projet);
775
			if ($service == 'taxons') {
776
				$code_valeur = '';
164 delphine 777
				$this->table_retour['attributions'][$langue][$num_nom]['nom_retenu.code'] = $code_valeur;
109 jpm 778
			} else {
6 jpm 779
				$code_valeur = $this->chercherSignificationCode($url, $nom);
780
			}
781
			if ($projet != '') $projet .= '.';
782
			$this->table_retour['attributions'][$langue][$num_nom][$nomChamp] = $code_valeur;
783
			$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.code'] = $projet.$ressource.$valeur;
784
			$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.href'] = $url;
785
		} else {
786
			if ($projet != '') $projet .= '.';
787
			$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.code'] = $projet.$ressource.$valeur;
788
		}
789
	}
109 jpm 790
 
6 jpm 791
	public function chercherSignificationCode($url, $nom) {
792
		if (isset($this->signification_code[$url])) {
793
			$valeur = $this->signification_code[$url];
794
		} else {
795
			$res = $this->consulterHref($url);
796
			$valeur = $res->$nom;
797
			$this->signification_code[$url] = $valeur;
798
		}
799
		return $valeur;
800
	}
109 jpm 801
 
1109 mathias 802
	/**
803
	 * Apparemment, regroupe les noms vernaculaires par taxons (élimine donc
804
	 * certains noms) - j'ai bon ?
805
	 */
6 jpm 806
	public function afficherTaxons() {
160 delphine 807
		$resultat = $this->recupererNomTaxons();
6 jpm 808
		foreach ($this->table_retour['attributions'] as $code_langue=>$langue) {
809
			foreach ($langue as $num_nom=>$taxon) {
810
				$num_tax = ltrim($taxon['taxon.code'], 'bdtfx.nt:');
811
				if (isset($resultat[$num_tax])) {
164 delphine 812
					$this->table_retour['attributions'][$code_langue][$num_nom]['nom_retenu.code'] = $resultat[$num_tax]['id'];
813
					$this->table_retour['attributions'][$code_langue][$num_nom]['taxon'] = $resultat[$num_tax]['nom_sci'];
6 jpm 814
				}
815
			}
816
		}
817
	}
160 delphine 818
 
819
	public function recupererNomTaxons() {
627 aurelien 820
		$taxons = array_unique($this->taxons);
1109 mathias 821
		// @TODO attention à la limite de taille de l'URL - faire un POST plutôt
627 aurelien 822
		$url = Config::get('url_service_base').'bdtfx/taxons?navigation.limite=500&ns.structure=au&masque.nt='.implode(',', $taxons);
160 delphine 823
		$res = $this->consulterHref($url);
1109 mathias 824
		foreach ($res->resultat as $id => $taxon) {
164 delphine 825
			$resultat[$taxon->num_taxonomique]['id'] = 'bdtfx.nn:'.$id;
627 aurelien 826
			$resultat[$taxon->num_taxonomique]['nom_sci'] = $taxon->nom_sci_complet;
160 delphine 827
		}
828
		return $resultat;
829
	}
6 jpm 830
 
831
	public function formaterNomsVernaculairesIdChamp($resultat) {
109 jpm 832
		$this->table_retour['id'] = $this->ressources[0];
833
		$champs = explode(' ', $this->ressources[1]);
6 jpm 834
		if (in_array('attributions', $champs) != false) {
835
			$this->formaterNomsVernaculairesId($resultat);
836
			unset($this->table_retour['nom_vernaculaire']);
160 delphine 837
		} else {
6 jpm 838
			$champ_attributions = array('num_taxon', 'zone_usage', 'num_statut', 'num_genre', 'notes');
839
			foreach ($resultat as $taxon) {
840
				foreach ($taxon as $key=>$valeur) {
841
					if ($key == 'code_langue' && in_array('langue', $champs) != false) {
842
						$this->table_retour['attributions']['langue'][] = $valeur;
843
					} elseif (in_array($key, $champ_attributions) != false) {
844
						$this->afficherPoint($this->correspondance_champs[$key] , $valeur, $taxon['code_langue'], $taxon['num_nom_vernaculaire']);
845
					} elseif (in_array($key, $champs) != false) {
846
						$this->table_retour[$key] = $valeur;
847
					}
848
				}
849
				if (in_array('biblio', $champs) != false) $this->chargerBiblio($taxon['num_nom_vernaculaire'], $taxon['code_langue']);
850
			}
851
			if (in_array('biblio', $champs) != false && array_search('biblio.num_ref', $this->table_retour) != false) $this->table_retour['biblio'] = null;
852
		}
853
		return $this->table_retour;
854
	}
109 jpm 855
 
1109 mathias 856
	/**
857
	 * Quelqu'un sait-il ce que fait cette foutue fonction ? :-/
858
	 */
6 jpm 859
	public function afficherPoint($champ, $valeur, $langue, $num_nom) {
1109 mathias 860
		$aMatche = preg_match('/^(.*)\.code$/', $champ, $match);
861
		if ($aMatche !== false && $aMatche !== 0) {
862
			$champ = $match[1];
863
			if (isset(self::$champ_infos[$champ])) {
864
				extract(self::$champ_infos[$champ]);
865
				$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur, $projet);
866
				$projet .= '.';
867
			}
109 jpm 868
 
1109 mathias 869
			$champs = explode(' ', $this->ressources[1]);
870
			if (in_array($champ.'.*', $champs) !== false && isset($projet)) {
871
				$this->table_retour['attributions'][$langue][$num_nom][$champ.'.code'] = $projet.$ressource.$valeur;
872
				$this->table_retour['attributions'][$langue][$num_nom][$champ.'.href'] = $url;
6 jpm 873
			}
1109 mathias 874
			if (in_array($champ.'.code', $champs) !== false && isset($projet)) {
875
				$this->table_retour['attributions'][$langue][$num_nom][$champ.'.code'] = $projet.$ressource.$valeur;
876
			}
877
			if (in_array($champ.'.href', $champs) !== false && isset($projet)) {
878
				$this->table_retour['attributions'][$langue][$num_nom][$champ.'.href'] = $url;
879
			}
880
			if (in_array($champ, $champs) !== false) {
881
				if (isset($url)) {
882
					$this->table_retour['attributions'][$langue][$num_nom][$champ] = $this->chercherSignificationCode($url, $nom);
883
				} else {
884
					$this->table_retour['attributions'][$langue][$champ] = $valeur;
885
				}
886
			}
109 jpm 887
		}
6 jpm 888
	}
889
 
890
	public function afficherLangue($nomChamp, $projet, $service, $valeur, $ressource = '', $nom = 'nom') {
891
		if ($this->retour_format == 'max') {
892
				$this->table_retour['attributions'][$nomChamp] = $nom;
893
				$this->table_retour['attributions'][$nomChamp.'.code'] = $projet.$ressource.$valeur;
894
				$this->table_retour['attributions'][$nomChamp.'.href'] = $url;
895
		} else {
896
			$this->table_retour['attributions'][$nomChamp.'.code'] = $projet.$ressource.$valeur;
897
		}
898
	}
109 jpm 899
 
6 jpm 900
	public function chargerBiblio($num_nom, $langue) {
901
		list($table, $version) = explode('_v',$this->table);
902
		$requete = "SELECT b.*, lb.notes FROM nvjfl_lien_biblio_v$version lb, nvjfl_biblio_v$version b ".
903
					"WHERE b.num_ref = lb.num_ref AND lb.num_nom = '$num_nom' ;";
284 jpm 904
		$resultat = $this->getBdd()->recupererTous($requete);
109 jpm 905
 
6 jpm 906
		 if ($resultat == '') { //cas ou la requete comporte des erreurs
907
		 	$r = 'La requête SQL formée comporte une erreur !!';
908
			$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE, $r);
909
			Debug::printr($requete);
910
		 } elseif ($resultat) {
911
			foreach ($resultat as $res) {
912
			   	foreach ($res as $cle => $valeur) {
913
			   		if ($valeur !== "") {
914
			   			$this->table_retour['attributions'][$langue][$num_nom]['biblio.'.$cle] = $valeur;
915
			   		}
916
			    }
917
			}
918
		}
919
	}
109 jpm 920
 
6 jpm 921
}
922
?>