Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 1108 | Rev 1195 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

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