Subversion Repositories eFlore/Projets.eflore-projets

Rev

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

Rev Author Line No. Line
6 jpm 1
<?php
2
 
3
/**
4
* Description :
5
* Classe Textes.php est une classe qui contient les méthodes permettant la consultation des textes (clé de détermination
6
*  ou description). Les identifiants des textes correspondent au tag de type CleCoste1937TXXPXXNomSci pour le projet
7
* coste.
8
* Encodage en entrée : utf8
9
* Encodage en sortie : utf8
10
* @package framework-v3
11
* @author Jennifer Dhé <jennifer.dhe@tela-botanica.org>
12
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
13
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
14
* @version 1.0
15
* @copyright 1999-${year} Tela Botanica (accueil@tela-botanica.org)
16
*/
17
 
18
 
19
class Textes extends Commun {
20
 
21
	protected $limite_requete	= array('depart' => 0, 'limite' => 100);
22
	protected $requete_champ = ' t1.resource AS tag, t1.value AS num_nom, t2.value AS titre, p.body AS texte';
23
	protected $requete_condition = null;
24
	protected $requete_group_by = ' ORDER BY CAST( t1.value AS DECIMAL )';
25
	protected $table_retour;
26
	protected $retour_format = 'max';
27
	protected $format_reponse = 'textes';
28
	protected $table_param = array();
29
	protected $total_resultat;
30
	protected $table_ressources = array();
31
	protected $html = 'txt';
32
	protected $recherche = 'stricte';
33
	protected $service = 'textes';
34
	protected $masque = null;
536 gduche 35
	protected $config;
6 jpm 36
 
536 gduche 37
	public function __construct() {
38
		$this->config = is_null($config) ? Config::get('Textes') : $config;
39
	}
6 jpm 40
 
41
	public function consulter($ressources, $parametres) {
536 gduche 42
 
6 jpm 43
		$resultat_formate = '';
44
		$this->table = array(Config::get("bdd_triples")." t1", Config::get("bdd_triples")." t2", Config::get("bdd_pages")." p");
45
		$this->traiterParametres($parametres);
46
		$this->traiterRessources($ressources);
47
		if ($this->corps_http == '' && $this->entete_http == '') {
288 delphine 48
			$requete = $this->assemblerLaRequete();
6 jpm 49
			$resultat = $this->getBdd()->recupererTous($requete);
50
			$this->testerResultat($resultat, $resultat_formate, $requete);
51
		}
52
		return $this->formerReponseHTTP($resultat_formate);
53
	}
54
 
288 delphine 55
	public function formerReponseHTTP($resultat_formate, $mime = 'application/json', $encodage= 'utf-8') {
56
		// Si aucune erreur n'a été établie (donc un tableau de résultat a bien ete renvoyé...)
57
		if ($this->corps_http == '' && $this->entete_http == '') {
58
			$this->entete_http = RestServeur::HTTP_CODE_OK;
59
			$this->corps_http  = $resultat_formate;
60
		}
61
		if ($this->entete_http != RestServeur::HTTP_CODE_OK) {
62
			$mime = 'text/html';
63
		}
64
		// Gestion du type de contenu
65
		if (!is_null($mime) && !is_null($encodage)) {
66
			header("Content-Type: $mime; charset=$encodage");
67
		} else if (!is_null($mime) && is_null($encodage)) {
68
			header("Content-Type: $mime");
69
		}
70
		// Envoie de l'entête
71
		RestServeur::envoyerEnteteStatutHttp($this->entete_http);
72
		// Envoie du corps
73
		return $this->corps_http;
74
	}
6 jpm 75
 
288 delphine 76
 
6 jpm 77
	public function testerResultat($resultat, &$resultat_formate, $requete) {
78
		if ($resultat == '') { //cas ou coste/services/ ou la requete comporte des erreurs
79
			$e = 'La requête SQL formée comporte une erreur!';
80
			$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE,$e);
81
			Debug::printr($requete);
82
		} elseif ($resultat) {
83
			$resultat_formate = $this->retournerResultatFormate($resultat);
84
		} else {
356 delphine 85
			if ($this->format_reponse == 'textes/relations') {
6 jpm 86
				$resultat_formate = 'null';
87
			} else {
88
				$m = 'Données introuvables dans la base';
89
				$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE,$m);
90
				Debug::printr($requete);
91
			}
92
		}
93
	}
94
 
95
 
96
//---------------------------------TRAITER RESSOURCES-----------------------------------------------------------------
97
 
98
	public function traiterRessources(&$ressources) {
99
		if (isset($ressources) && !empty($ressources)) {
100
			$this->table = Config::get('bdd_triples');
101
			$this->table_ressources = $ressources;
102
			if ($ressources[0] == 'relations') {
103
				$this->traiterRelationsProjet($ressources);
104
				$this->format_reponse .= '/relations';
105
			} elseif (isset($this->table_ressources[0]) && !empty($this->table_ressources[0])) {
106
				$this->traiterRessourceId($this->table_ressources[0]);
107
				if (isset($this->table_ressources[1]) && !empty($this->table_ressources[1])) {
108
					$this->format_reponse .= '/champ';
109
				}
110
			} else {
111
				$e = "Erreur dans votre requête. <br/> Les ressources disponibles sont :
112
				<li> /textes/#id (id correspondant au tag de la page </li>
113
				<li> /textes/#id/#champ+#champ </li>
114
				<li> /textes/relations/bdtfx/#id (id correspondant au num_nom du projet bdtfx </li>";
115
				$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
116
			}
117
		} else {
118
			$this->traiterRessourcesListe();
119
		}
120
		$this->requete_condition[] = "p.latest = 'Y'";
121
	}
122
 
123
	public function traiterRessourceId($id) {
124
		$this->format_reponse .= '/id';
125
		if ($this->recherche == 'etendue') {
126
			$id = '%'.str_replace(' ','%', $id).'%';
289 delphine 127
		}
128
		if (is_numeric($id)) {
129
			$this->requete_condition[] = 'c.id ='.$this->getBdd()->proteger($id);
130
		} else {
131
			$id = explode('bdtfx.nn:', $id);
132
			if (is_numeric($id[1])) {
133
				$this->requete_condition[] = 'c.num_nom ='.$this->getBdd()->proteger($id[1]);
134
			}
135
		}
288 delphine 136
 
137
		$this->requete_champ = 'c.id AS num_nom, i.nom_sci AS titre, t1.resource AS tag, p.body AS texte';
138
		$this->table = array(Config::get("bdd_correspondance_bdnff").' c',
139
			Config::get("bdd_triples").' t1',
140
			Config::get("bdd_index").' i',
141
			Config::get("bdd_pages").' p');
289 delphine 142
 
288 delphine 143
		$this->requete_condition[] = 'c.id = i.num_nom';
144
		$this->requete_condition[] = 'i.nom_sci = t1.value';
145
		$this->requete_condition[] = 't1.resource = p.tag';
146
 
147
		/*$this->requete_champ = ' t1.resource AS tag, t1.value AS num_nom, t2.value AS titre, p.body AS texte';
6 jpm 148
		$this->requete_condition[] = 't1.resource LIKE '.$this->getBdd()->proteger($id);
149
		$this->requete_condition[] = 't1.property = "num_nom"';
150
		$this->requete_condition[] = '(t1.resource = t2.resource AND t2.property = "titre")';
151
		$this->requete_condition[] = 't1.resource = p.tag';
152
		$this->table = array(Config::get("bdd_triples").' t1',
153
							Config::get("bdd_triples").' t2',
154
							Config::get("bdd_pages").' p');
288 delphine 155
		$this->ajouterRechercheFloue('t1.resource', $id);*/
6 jpm 156
	}
157
 
158
	public function traiterRessourcesListe() {
159
		$this->requete_condition[] = "t1.property = 'num_nom'";
160
		$this->requete_condition[] = "(t1.resource = t2.resource AND t2.property = 'titre')";
161
		$this->requete_condition[] = "t1.resource = p.tag";
162
	}
163
 
164
	public function traiterRelationsProjet($tab_ress) {
165
		$this->table = array(Config::get("bdd_triples")." t1", Config::get("bdd_pages")." p", Config::get("bdd_table").'_v0_1 c');
166
		$projet = $tab_ress[1];
167
		$num_nom = $tab_ress[2];
168
		$nom_champ_projet = "flore_$projet"."_num";
169
		if (isset($tab_ress[3])) {
170
			$type = $tab_ress[3];
171
			if (!in_array($type, array('cle', 'dsc'))) {
172
				$e = "Le type de texte ne peut etre que clé ou description";
173
				$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
174
			}
175
		}
176
		$this->requete_condition[] = "c.flore_bdnff_num = ".$this->getBdd()->proteger($num_nom);
177
		$this->requete_condition[] = "t1.value = c.num_nom";
178
		$this->requete_condition[] = "t1.property = 'num_nom'";
179
		$this->requete_condition[] = "t1.resource = p.tag";
180
		$this->requete_champ = 't1.resource AS tag, t1.value AS num_nom, p.body AS texte';
181
		if (isset($type)) $this->requete_condition[] = "t1.resource LIKE ".$this->getBdd()->proteger(ucfirst($type.'%'));
182
	}
183
 
184
 
185
	public function ajouterRechercheFloue($nom_champ, $id) {
186
		if ($this->recherche == 'floue') {
187
			$id = $this->getBdd()->proteger($id);
188
			$this->requete_condition[array_search("$nom_champ LIKE $id",
189
				$this->requete_condition)] =
190
				"($nom_champ LIKE $id)".
191
				" OR ( SOUNDEX($nom_champ) = SOUNDEX($id))".
192
				" OR SOUNDEX(REVERSE($nom_champ)) = SOUNDEX(REVERSE($id))))";
193
		}
194
	}
195
 
196
//---------------------------------------TRAITER PARAMETRES-------------------------------------------------------------
197
 
198
	public function traiterParametres($parametres) {
199
		if (isset($parametres) && !empty($parametres)) {
200
			$this->table_param = $parametres;
201
			if (isset($parametres['recherche']) && $parametres['recherche'] != '') {
202
				$this->recherche = $parametres['recherche'];
203
			}
204
			foreach ($parametres as $param => $val) {
205
				switch ($param) {
288 delphine 206
					case 'retour.format'	: $this->retour_format = $val;										break;
207
					case 'masque.titre' 	: $this->ajouterLeFiltreMasque('titre', $val);						break;
208
					case 'masque.famille'	: $this->ajouterLeFiltreMasque('famille', $val);					break;
209
					case 'masque.ns'		: $this->ajouterLeFiltreMasque('nom_sci', $val);					break;
210
					case 'masque.type'		: $this->ajouterLeFiltreMasque('type', $val);						break;
211
					case 'masque.txt'		: $this->ajouterLeFiltreMasque('texte', $val);						break;
212
					case 'masque.page'		: $this->ajouterLeFiltreMasque('page',$val);						break;
213
					case 'masque.tome'		: $this->ajouterLeFiltreMasque('tome',$val);						break;
214
					case 'navigation.depart': $this->limite_requete['depart'] = $val;							break;
215
					case 'navigation.limite': $this->limite_requete['limite'] = $val;							break;
6 jpm 216
					case 'recherche'		: 																	break;
290 delphine 217
					case 'txt.format'		: 																	break;
6 jpm 218
					default					:
219
						$e = "Erreur dans les paramètres de recherche de votre requête : </br> Le parametre	$param n\'existe pas.";
220
						$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE,$e);
221
						break;
222
				}
223
			}
224
		}
225
	}
226
 
227
 
228
	public function ajouterLeFiltreMasque($masque, $valeur) {
229
		if ($this->recherche == 'etendue') {
230
			$valeur = '%'.str_replace(' ','%', $valeur).'%';
231
		}
232
		$valeur = $this->getBdd()->proteger($valeur);
233
		$this->masque[] = "$masque=$valeur";
234
		switch ($masque) {
235
			case 'famille' :
236
				break;
237
			case 'nom_sci' :
238
				$this->requete_condition[] = "t1.value = c.num_nom AND nom_sci LIKE $valeur)";
239
				$this->ajouterRechercheFloue('nom_sci', $valeur);
240
				$this->table[] = Config::get("bdd_table").'_v0_1 c';
241
				break;
242
			case 'type'    :
243
				$type = ($this->getBdd()->proteger($valeur) == '"cle"') ? 'Cle%' : 'Dsc%';
244
				$this->requete_condition[] = 't1.resource LIKE '.$this->getBdd()->proteger($type);
245
				break;
246
			case 'texte'   :
247
				$this->requete_condition[] = "p.body LIKE $valeur";
248
				$this->ajouterRechercheFloue('p.body', $valeur);
249
				break;
250
			case 'titre'   :
251
				$this->requete_condition[] = "t2.value LIKE $valeur";
252
				$this->ajouterRechercheFloue('t2.value', $valeur);
253
				break;
254
			case 'page'	   :
255
				$this->requete_condition[] =  "t1.value = c.num_nom AND c.page = $valeur";
256
				$this->table[] = Config::get("bdd_table").'_v0_1 c';
257
				break;
258
			case 'tome'	   :
259
				$this->requete_condition[] =  "t1.value = c.num_nom AND c.tome = $valeur";
260
				$this->table[] = Config::get("bdd_table").'_v0_1 c';
261
				break;
262
			default 		:
263
				break;
264
		}
265
	}
266
 
267
 
268
//-----------------------------FONCTIONS DASSEMBLAGE DE LA REQUETE-----------------------------------------------------
269
 
270
	public function assemblerLaRequete() {
271
		$requete = 	' SELECT '.$this->requete_champ.
272
					' FROM '.implode(', ', $this->table)
273
					.$this->retourneRequeteCondition()
274
					.$this->requete_group_by
275
					.$this->formerRequeteLimite();
276
		return $requete;
277
	}
278
 
279
 
280
	public  function retourneRequeteCondition() {
281
		$condition = '';
282
		if ($this->requete_condition !== null) {
283
			$condition = ' WHERE '.implode(' AND ', $this->requete_condition);
284
		}
285
		return $condition;
286
	}
287
 
288
	public function formerRequeteLimite() {
289
		if (in_array($this->format_reponse , array('textes/id', 'textes/id/relations'))) {
290
			$this->requete_limite = '';
291
		} elseif (($depart = $this->limite_requete['depart']) > ($this->total_resultat = $this->recupererTotalResultat())) {
292
			$this->limite_requete['depart'] =
293
				(($this->total_resultat - $this->limite_requete['limite']) < 0) ? 0 : ($this->total_resultat - $this->limite_requete['limite']);
294
			$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite'];
295
		} else {
296
			$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite'];
297
		}
298
		return $this->requete_limite;
299
	}
300
 
301
 
302
	/**
303
	 * Recupere le nombre total de résultat d'une requete lancée.
304
	 * Est utilisée lors de l'affichage du total dans le résultat retourné et pr déterminer les limites et départ
305
	 * @return nombre total de résultat
306
	 */
307
	public function recupererTotalResultat() {
308
		$total = null;
309
		$requete = 'SELECT count(*) as nombre FROM '
310
					.implode(', ', $this->table).$this->retourneRequeteCondition()
311
					.$this->requete_group_by;
312
		$res = $this->getBdd()->recuperer($requete);
313
		if ($res) {
314
			$total = $res['nombre'];
315
		} else {
316
			$e = 'Données introuvables dans la base ou erreur dans la requête SQL';
317
			$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE, $e);
318
		}
319
		return $total;
320
	}
321
 
322
 
323
 
324
//-------------------FONCTIONS POUR LE FORMATAGE EN JSON----------------------------------------------------------------
325
 
326
	public function retournerResultatFormate($resultat) {
327
		$reponse = '';
328
		switch ($this->format_reponse) {
329
			case 'textes' 				: $reponse = $this->formaterTextes($resultat);  		break;
330
			case 'textes/relations'		: $reponse = $this->formaterTextesRelations($resultat); break;
331
			case 'textes/id' 			: $reponse = $this->formaterTextesId($resultat[0]); 	 break;
332
			case 'textes/id/champ' 		: $reponse = $this->formaterTextesIdChamp($resultat[0]); break;
333
			default : break;
334
		}
335
		return $reponse;
336
	}
337
 
338
 
339
	public function formaterTextes($resultat) {
340
		$this->ajouterEnteteResultat($resultat);
341
		$reponse['entete'] = $this->table_retour;
342
		$this->table_retour = array();
343
		foreach ($resultat as $description) {
344
			$tag = $description['tag'];
345
			$this->afficherDonnees('titre', $description['titre']);
346
			$type = (preg_match('/^Cle.*$/', $tag)) ? '1' : '2' ;
347
			$this->afficherDonnees('type', $type);
348
			$this->table_retour['texte'] = $description['texte'];
349
			$reponse['resultat'][$tag] = $this->table_retour;
350
			$this->table_retour = array();
351
			$reponse['resultat'][$tag]['href'] = $this->ajouterHref('textes', $tag);
352
		}
353
		return $reponse;
354
	}
355
 
356
	public function formaterTextesRelations($resultat) {
357
		foreach ($resultat as $description) {
358
			$tag = $description['tag'];
359
			$type = (preg_match('/^Cle.*$/', $tag)) ? '1' : '2' ;
360
			$this->afficherDonnees('type', $type);
361
			$this->table_retour['texte'] = $description['texte'];
362
			$reponse[$tag] = $this->table_retour;
363
			$this->table_retour = array();
364
			$reponse[$tag]['href'] = $this->ajouterHref('textes', $tag);
365
		}
366
		return $reponse;
367
	}
368
 
369
	public function ajouterEnteteResultat($resultat) {
370
		if ($this->masque) {
371
			$this->table_retour['masque'] = implode('&', $this->masque);
372
		}
373
		$this->table_retour['depart'] = $this->limite_requete['depart'];
374
		$this->table_retour['limite'] = $this->limite_requete['limite'];
375
		$this->table_retour['total']  = $this->total_resultat;
376
		//formuler les urls
377
		$url = $this->formulerUrl($this->total_resultat, '/'.$this->service);
378
		if ($url['precedent'] != '') { $this->table_retour['href.precedent'] = $url['precedent']; }
379
		if ($url['suivant']   != '') { $this->table_retour['href.suivant']   = $url['suivant']; }
380
	}
381
 
382
 
383
	public function formaterTextesId($reponse) {
384
 
385
		$this->afficherDonnees('titre', $reponse['titre']);
386
		$type = (preg_match('/^Cle.*$/', $reponse['tag'])) ? '2' : '1' ;
387
		$this->afficherDonnees('type', $type);
388
		$this->table_retour['texte'] = $reponse['texte'];
289 delphine 389
		//$this->afficherDonnees('id', $reponse['num_nom']);
6 jpm 390
 
391
		return $this->table_retour;
392
	}
393
 
394
 
395
	public function formaterTextesIdChamp($resultat) {
396
		//on recupère tous les resultats possibles
397
		$reponse_id = $this->formaterTextesId($resultat);
398
		$this->table_retour = array();
399
		//on recupère les résultats demandés à partir du tableau de résultat complet
400
		$this->table_retour['id'] = $resultat['tag'];
401
		$champs = explode(' ', $this->table_ressources[1]);
402
		foreach ($champs as $champ) {
403
			if ($this->verifierValiditeChamp($champ, $reponse_id)) {
404
				if (preg_match('/^[^.]+\.\*$/', $champ)) {
405
					$this->afficherPointEtoile($champ, $reponse_id);
406
				} else {
407
					$this->table_retour[$champ] = $reponse_id[$champ];
408
				}
409
			}
410
		}
411
		return $this->table_retour;
412
	}
413
 
414
 
415
	public function afficherPointEtoile($champ, $reponse_id) {
416
		preg_match('/^([^.]+\.)\*$/', $champ, $match);
417
		foreach ($reponse_id as $chp => $valeur) {
418
			if (strrpos($chp, $match[1]) !== false) {
419
				$this->table_retour[$chp] = $valeur;
420
			}
421
		}
422
	}
423
 
424
 
425
	public function verifierValiditeChamp($champ, $reponse_id) {
426
		$validite = false;
427
		preg_match('/^([^.]+)(:?\.([^.]+))?$/', $champ, $match);
428
		if (array_key_exists($match[1], $reponse_id)) {
429
			$validite = true;
430
			if (isset($match[2]) && !empty($match[2])) {
431
				if ($match[1] == 'type') {
432
					$suffixes = array('.code', '.href', '.*');
433
				$validite = (in_array($match[2], $suffixes)) ? true : false;
434
				} else {
435
					$validite = false;
436
				}
437
			}
438
		}
439
		if (!$validite) {
440
			$champs = implode('</li><li>', array_keys($reponse_id));
441
			$e = 'Erreur dans votre requête : </br> Le champ "'.$champ.'" n\'existe pas. Les champs disponibles
442
				 sont : <li>'.$champs.'</li>';
443
			$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
444
		}
445
		return $validite;
446
	}
447
 
448
 
449
//------------------------------------------------Fonction d'affichage ------------------------------------------------
450
 
451
	public function afficherDonnees($champ, $valeur) {
452
		if ($this->retour_format == 'min') {
453
			$champ = ($champ == 'type') ? $champ.'.code' : $champ;
454
			$this->table_retour[$champ] = $valeur;
455
		} else {
456
			$this->afficherDonneesMax($champ, $valeur);
457
		}
458
	}
459
 
460
 
461
	public function afficherDonneesMax($champ, $valeur) {
462
		if ($champ == 'id') {
463
			$this->table_retour[$champ] = "coste.".$valeur;
464
			$this->table_retour['nom_sci'] = $this->recupererNomSci($valeur);
465
			$this->table_retour['id.href'] = $this->ajouterHref('noms', $valeur);
466
		} elseif (in_array($champ, array('type'))) {
467
			$this->table_retour[$champ.'.code'] = $valeur;
468
			$this->table_retour[$champ] = $this->recupererSignificationCode($valeur);
289 delphine 469
			$this->table_retour[$champ.'.href'] = $this->ajouterHrefAutreProjet('ontologies', 'texteType:', $valeur, 'eflore');
6 jpm 470
		} else {
471
			$this->table_retour[$champ] = $valeur;
472
		}
473
	}
474
 
475
 
476
	public function recupererSignificationCode($code) {
289 delphine 477
		$url = $this->ajouterHrefAutreProjet('ontologies', 'texteType:', $code.'/nom', 'eflore');
6 jpm 478
		$res = $this->consulterHref($url);
479
		return $res->nom;
480
	}
481
 
482
 
483
	public function recupererNomSci($id) {
484
		$req = 'SELECT nom_sci FROM coste_v0_1 WHERE num_nom = '.$id;
485
		if ($this->html == 'htm') {
486
			$req = str_replace('nom_sci', 'nom_sci_html as nom_sci', $req);
487
		}
488
		$res = $this->getBdd()->recuperer($req);
489
		return $res['nom_sci'];
490
	}
491
 
492
}
493
 
494
?>