/tags/v0.1-20130829/services/modules/0.1/insee-d/ZoneGeo.php |
---|
New file |
0,0 → 1,405 |
<?php |
/** |
* Description : |
* Classe ZoneGeo.php fournit des informations sur ensemble structuré des termes et concepts représentant les éléments |
* d'un domaine de connaissances . |
* Le but étant de fournir un ensemble minimal d'information comprenant : |
* un identifiant (numérique ou alphanumérique sous forme de ChatMot si possible), un nom, une region et |
* éventuellement une relation hiérarchique avec un autre terme (=classe). |
* Si l'url finit par /zone-geo on retourne une liste de termes (seulement les 100 premières par défaut). |
* L'url peut contenir des paramètres optionnels passés après le ? : /observations?param1=val1¶m2=val2&... |
* |
* Les paramètres de requête disponibles sont : masque, masque.code, masque.nom, masque.region , recherche, |
* distinct, retour.format, navigation.depart et navigation.limite. |
* |
* Encodage en entrée : utf8 |
* Encodage en sortie : utf8 |
* @package framework-v3 |
* @author Delphine Cauquil <delphine@tela-botanica.org> |
* @author Jennifer Dhé <jennifer.dhe@tela-botanica.org> |
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt> |
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt> |
* @version 1.0 |
* @copyright 1999-${year} Tela Botanica (accueil@tela-botanica.org) |
*/ |
class ZoneGeo extends Commun { |
protected $service = 'zone-geo'; |
/** |
* Permet de stocker la requete formulée : /zone-geo | /zone-geo/#id | /zone-geo/#id/champ | /zone-geo/#id/relations |
* Est remplit au cours de l'analyse des ressources (traiterRessources()), par défaut, a la valeur du service. |
* Est utilisée principalement pr déterminer le format du tableau à retourner. */ |
protected $format_reponse = 'zone-geo'; |
/** Variables constituant les parametres de la requete SQL (champ, condition, group by, limit) remplie |
* selon ressources et paramètres */ |
protected $requete_champ = ' * '; |
protected $requete_condition = ''; |
protected $limite_requete = array( |
'depart' => 0, |
'limite' => 100 |
); |
/** Stockage des ressources et paramétres */ |
protected $table_ressources = array(); |
protected $table_param = array(); |
/** |
* Precise la contenance plus ou moins précise du tableau à retourner : |
* - min = les données présentes dans la table |
* - max = les données de la table + les informations complémentaires (pour les identifiants et les codes) |
* - oss = la liste des nom_sci (uniquement pour noms et taxons) |
*/ |
protected $retour_format = 'max'; |
/** Valeur du paramètre de requete recherche : |
* - stricte : le masque est passé tel quel à l'opérateur LIKE. |
* - etendue : ajout automatique du signe % à la place des espaces et en fin de masque avec utilisation de LIKE. |
* - floue : recherche tolérante vis-à-vis d'approximations ou d'erreurs (fautes d'orthographe par exemple) */ |
protected $recherche; |
/** Permet de stocker le tableau de résultat (non encodé en json) */ |
protected $table_retour = array(); |
/** Stocke le nombre total de résultats de la requete principale. Est calculée lors de l'assemblage de la requete */ |
protected $total_resultat; |
// +-----------------------------------------------------------------------------------------------------+ |
public function traiterParametres() { |
if (isset($this->parametres) && !empty($this->parametres)) { |
$this->table_param = $this->parametres; |
// masque : filtre la liste en fonction d'un masque de recherche portant sur le code, le nom ou la region. |
// masque.code : filtre uniquement sur le code. masque.nom : filtre uniquement sur le nom. |
// masque.region : filtre uniquement sur la region. |
if (isset($this->parametres['recherche']) && $this->parametres['recherche'] != '') { |
$this->recherche = $this->parametres['recherche']; |
} |
foreach ($this->parametres as $param => $valeur) { |
switch ($param) { |
case 'masque' : |
$this->ajouterLeFiltreMasque('masque', $valeur); |
break; |
case 'masque.code' : |
$this->ajouterLeFiltreMasque('dep', $valeur); |
break; |
case 'masque.nom' : |
$this->ajouterLeFiltreMasque('nccenr', $valeur); |
break; |
case 'masque.region' : |
$this->ajouterLeFiltreMasque('region', $valeur); |
break; |
case 'retour.format' : |
$this->retour_format = $valeur; |
break; |
case 'navigation.depart' : |
$this->limite_requete['depart'] = $valeur; |
break; |
case 'navigation.limite' : |
$this->limite_requete['limite'] = $valeur; |
break; |
case 'recherche' : |
break; |
default : |
$p = 'Erreur dans les paramètres de recherche de votre requête : '. |
'</br> Le paramètre " '.$param.' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $p); |
} |
} |
} |
} |
public function ajouterLeFiltreMasque($nom_champ, $valeur) { |
if ($nom_champ == 'dep' || $nom_champ == 'region') { |
$this->requete_condition[] = $nom_champ.' = '.$this->getBdd()->proteger($valeur); |
} else { |
if ($this->recherche == 'floue') { |
if ($nom_champ == 'masque') { |
$this->requete_condition[] = '( dep = '.$this->getBdd()->proteger($valeur) |
.' OR region = '.$this->getBdd()->proteger($valeur) |
.' OR ( SOUNDEX(nccenr) = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE(nccenr)) = SOUNDEX(REVERSE(\''.$valeur.'\')) ' |
.')) '; |
} else { |
$this->requete_condition[] = '(SOUNDEX('.$nom_champ.') = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE('.$nom_champ.')) = SOUNDEX(REVERSE(\''.$valeur.'\'))) '; |
} |
} else { |
if ($this->recherche == 'etendue') { |
$valeur = str_replace(' ','%', $valeur); |
$valeur .= '%'; |
} |
if ($nom_champ == 'masque') { |
$this->requete_condition[] = ' (dep = '.$this->getBdd()->proteger($valeur) |
.' OR nccenr LIKE '.$this->getBdd()->proteger($valeur) |
.' OR region = '.$this->getBdd()->proteger($valeur).')'; |
} else { |
$this->requete_condition[] = $nom_champ.' LIKE '.$this->getBdd()->proteger($valeur); |
} |
} |
} |
} |
//+------------------------------------------------------------------------------------------------------+ |
public function traiterRessources() { |
if (isset($this->ressources) && !empty($this->ressources)) { |
$this->table_ressources = $this->ressources; |
if (isset($this->table_ressources[0]) && !empty($this->table_ressources[0])) { |
//requete = /zone-geo/#id |
$this->traiterRessourceId(); |
if (isset($this->table_ressources[1]) && !empty($this->table_ressources[1])) { |
//dans le cas /zone-geo/#id/#champ ou /zone-geo/#id/relations |
$this->traiterRessourceChampOuRelations(); |
} |
} |
} |
} |
//requete : /zone-geo/#id (ex : /zone-geo/7) |
public function traiterRessourceId() { |
if (is_numeric($this->table_ressources[0])) { |
$this->requete_condition[] = ' dep = '.$this->getBdd()->proteger($this->table_ressources[0]); |
$this->format_reponse .= '/id'; |
} else { |
$r = 'Erreur dans les ressources de votre requête : </br> La ressource " '.$this->table_ressources[0]. |
' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $r); |
} |
} |
public function traiterRessourceChampOuRelations() { |
//requete = /zone-geo/#id/relations : |
if ($this->table_ressources[1] == 'relations') { |
$this->format_reponse .= '/relations'; |
$this->requete_condition[] = 'region = (SELECT region FROM '.$this->table.' WHERE ' |
.implode(' AND ', $this->requete_condition).')'; |
//requete = /zone-geo/#id/#champ : |
} else { |
$this->format_reponse .= '/champ'; |
} |
} |
//+------------------------------------------------------------------------------------------------------+ |
public function assemblerLaRequete() { |
//assemblage de la requete : |
$requete = ' SELECT '.$this->requete_champ. |
' FROM '.$this->table |
.$this->formerRequeteCondition() |
.$this->formerRequeteLimite(); |
return $requete; |
} |
public function formerRequeteCondition() { |
$condition = ''; |
if ($this->requete_condition != null) { |
$condition = ' WHERE '.implode(' AND ', $this->requete_condition); |
} |
return $condition; |
} |
//ajout d'une limite seulement pour les listes (pas plus de 100 resultats retournés pr les requetes |
// suivantes : /zone-geo et /zone-geo/#id/relations) |
public function formerRequeteLimite() { |
if ($this->format_reponse != 'zone-geo' && $this->format_reponse != 'zone-geo/id/relations') { |
$this->requete_limite = ''; |
} elseif (($depart = $this->limite_requete['depart']) > ($this->total_resultat = $this->recupererTotalResultat())) { |
//cas où la requete presente un navigation.depart supérieur au nb total de resultats. |
$this->limite_requete['depart'] = |
(($nb - $this->limite_requete['limite']) < 0) ? 0 : ($nb - $this->limite_requete['limite']); |
$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite']; |
} else { |
$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite']; |
} |
return $this->requete_limite; |
} |
public function recupererTotalResultat() { |
//on récupère le nombre total de résultats de la requete (ex : le nombre d'id contenu dans la liste /zone-geo) |
$requete = 'SELECT count(*) as nombre FROM ' |
.$this->table |
.$this->formerRequeteCondition(); |
$res = $this->getBdd()->recuperer($requete); |
if ($res) { |
$total = $res['nombre']; |
} else { |
$t = 'Fonction recupererTotalResultat() : <br/>Données introuvables dans la base'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE, $t); |
} |
return $total; |
} |
//+------------------------------------------------------------------------------------------------------+ |
// determine en fct du service appelé (/zone-geo | /zone-geo/#id | /zone-geo/#id/champ | |
// /zone-geo/#id/relations) le format du tableau à retourner. |
public function retournerResultatFormate($resultat) { |
$this->recupererTableConfig('correspondance_champs'); |
switch ($this->format_reponse) { |
case 'zone-geo' : $reponse = $this->formaterZoneGeo($resultat); break; |
case 'zone-geo/id' : $reponse = $this->formaterZoneGeoId($resultat[0]); break; |
case 'zone-geo/id/champ' : $reponse = $this->formaterZoneGeoIdChamp($resultat[0]); break; |
case 'zone-geo/id/relations' : $reponse = $this->formaterZoneGeoIdRelations($resultat); break; |
default : break; |
} |
return $reponse; |
} |
public function formaterZoneGeo($resultat) { |
//on remplit la table $table_retour_json['entete'] |
$this->table_retour['depart'] = $this->limite_requete['depart']; |
$this->table_retour['limite'] = $this->limite_requete['limite']; |
$this->table_retour['total'] = $this->total_resultat; |
$url = $this->formulerUrl($this->total_resultat, '/zone-geo'); |
if (isset($url['precedent']) && $url['precedent'] != '') { $this->table_retour['href.precedent'] = $url['precedent']; } |
if (isset($url['suivant']) && $url['suivant'] != '') { $this->table_retour['href.suivant'] = $url['suivant']; } |
$table_retour_json['entete'] = $this->table_retour; |
//on remplit la table $table_retour_json['resultat'] |
$this->table_retour = array(); |
if (isset($this->table_param['masque_nom'])) $resultat = $this->trierRechercheFloue($this->table_param['masque_nom'], $resultat, 'nccenr'); |
foreach ($resultat as $tab) { |
foreach ($tab as $key => $valeur) { |
if ($valeur != '') { |
switch ($key) { |
case 'dep' : $num = $valeur; $this->table_retour['code'] = $valeur; break; |
case 'nccenr' : $this->table_retour['nom'] = $valeur; break; |
default : break; |
} |
} |
} |
if ($this->retour_format == 'max') { |
$this->table_retour['href'] = $this->ajouterHref('zone-geo', $num); |
} |
$resultat_json[$num] = $this->table_retour; |
$this->table_retour = array(); |
} |
$table_retour_json['resultat'] = $resultat_json; |
return $table_retour_json; |
} |
public function formaterZoneGeoId($resultat) { |
foreach ($resultat as $key => $valeur) { |
if ($valeur != '') { |
$this->afficherDonnees($key, $valeur); |
} |
} |
unset($this->table_retour['href']); |
return $this->table_retour; |
} |
public function formaterZoneGeoIdRelations($resultat) { |
if ($resultat == '') { |
$retour = null; |
} else { |
//on remplit la table $table_retour_json['entete'] |
$this->table_retour['depart'] = $this->limite_requete['depart']; |
$this->table_retour['limite'] = $this->limite_requete['limite']; |
$this->table_retour['total'] = $this->total_resultat; |
//formuler les urls |
$url = $this->formulerUrl(count($resultat), '/zone-geo'); |
if ($url['precedent'] != '') { $this->table_retour['href.precedent'] = $url['precedent']; } |
if ($url['suivant'] != '') { $this->table_retour['href.suivant'] = $url['suivant']; } |
$retour['entete'] = $this->table_retour; |
$this->table_retour = array(); |
//on remplit la table $table_retour_json['resultat'] |
foreach ($resultat as $tab) { |
foreach ($tab as $key => $valeur) { |
switch ($key) { |
case 'dep' : $num = $valeur; $this->table_retour['code'] = $valeur; break; |
case 'nccenr' : $this->table_retour['nom'] = $valeur; break; |
default : break; |
} |
} |
if ($this->retour_format == 'max') $this->table_retour['href'] = $this->ajouterHref('zone-geo', $num); |
$resultat_json[$num] = $this->table_retour; |
$this->table_retour = array(); |
} |
$retour['resultat'] = $resultat_json; |
} |
return $retour; |
} |
public function formaterZoneGeoIdChamp($resultat) { |
//on recupère tous les resultats possibles |
$reponse = $this->formaterZoneGeoId($resultat); |
$this->table_retour = array(); |
//on recupère les résultats demandés à partir du tableau de résultat complet |
$this->table_retour['id'] = $reponse['code']; |
$champs = explode(' ', $this->table_ressources[1]); |
foreach ($champs as $champ) { |
if ($this->verifierValiditeChamp($champ)) { |
if (strrpos($champ, '.*') !== false) { |
$this->afficherPointEtoile($champ, $reponse); |
} else { |
if (isset($reponse[$champ])) { |
$this->table_retour[$champ] = $reponse[$champ]; |
} else { |
$this->table_retour[$champ] = null; |
} |
} |
} |
} |
return $this->table_retour; |
} |
public function verifierValiditeChamp($champ) { |
preg_match('/^([^.]+)(\.([^.]+))?$/', $champ, $match); |
$champs_possibles = $this->correspondance_champs; |
$champs_possibles[] = 'nom.*'; |
if (in_array($match[1], $champs_possibles)) { |
$validite = true; |
} elseif (in_array($match[0], $champs_possibles)) { |
$validite = true; |
} else { |
$champs_possibles = implode('</li><li>', $champs_possibles); |
$c = 'Erreur dans votre requête : </br> Le champ "'.$champ_possibles.'" n\'existe pas. '. |
'Les champs disponibles sont : <li>'.$champs_possibles.'</li>'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $c); |
} |
return $validite; |
} |
public function afficherPointEtoile($champ, $reponse) { |
preg_match('/^([^.]+\.)\*$/', $champ, $match); |
foreach ($reponse as $chp => $valeur) { |
if (strrpos($chp, $match[1]) !== false) { |
if ($valeur != '') { |
$this->table_retour[$chp] = $valeur; |
} else { |
$this->table_retour[$chp] = null; |
} |
} |
} |
} |
public function afficherDonnees($champ, $valeur) { |
if ($this->retour_format == 'max') { |
if ($champ == 'region' || $champ == 'chef_lieu') { |
$projet = 'insee-'.substr($champ, 0, 1); |
$this->table_retour[$champ.'.code'] = $valeur; |
$this->table_retour[$champ.'.href'] = $this->ajouterHrefAutreProjet('zone-geo', '', $valeur, $projet); |
} elseif ($champ == 'tncc') { |
$url = $this->ajouterHref('ontologies', $valeur); |
$res = $this->consulterHref($url); |
$this->table_retour['type_nom'] = $res->nom; |
$this->table_retour['type_nom.code'] = $valeur; |
$this->table_retour['type_nom.href'] = $url; |
} else { |
$this->table_retour[$this->correspondance_champs[$champ]] = $valeur; |
} |
} else { |
$this->table_retour[$this->correspondance_champs[$champ]] = $valeur; |
} |
} |
} |
?> |
/tags/v0.1-20130829/services/modules/0.1/nva/NomsVernaculaires.php |
---|
New file |
0,0 → 1,646 |
<?php |
/** |
* Description : |
* Classe NomsVernaculaires.php fournit une liste de noms vernaculaires et leur liaison à la bdtxa |
* Le but étant de fournir un ensemble minimal d'information comprenant : |
* un identifiant (numérique ou alphanumérique sous forme de ChatMot si possible), un nom, une langue et |
* une relation avec un taxon de la bdtxa. |
* Si l'url finit par /noms-vernaculaires on retourne une liste de noms (seulement les 100 premières par défaut). |
* L'url peut contenir des paramètres optionnels passés après le ? : /observations?param1=val1¶m2=val2&... |
* |
* Les paramètres de requête disponibles sont : masque, masque.code, masque.nom, masque.region , recherche, |
* distinct, retour.format, navigation.depart et navigation.limite. |
* |
* Encodage en entrée : utf8 |
* Encodage en sortie : utf8 |
* @package framework-v3 |
* @author Delphine Cauquil <delphine@tela-botanica.org> |
* @author Jennifer Dhé <jennifer.dhe@tela-botanica.org> |
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt> |
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt> |
* @version 1.0 |
* @copyright 1999-${year} Tela Botanica (accueil@tela-botanica.org) |
*/ |
class NomsVernaculaires extends Commun { |
protected $champ_infos = array( |
'taxon' => array('service' => 'taxons', 'ressource' => 'nt:', 'projet' => 'bdtxa', 'nom' => 'nom_sci')); |
protected $service = 'noms-vernaculaires'; |
/** |
* Permet de stocker la requete formulée : /noms-vernaculaires | /noms-vernaculaires/#id | |
* /noms-vernaculaires/#id/champ | /noms-vernaculaires/#id/relations |
* Est remplit au cours de l'analyse des ressources (traiterRessources()), par défaut, a la valeur du service. |
* Est utilisée principalement pr déterminer le format du tableau à retourner. */ |
protected $format_reponse = 'noms-vernaculaires'; |
/** Variables constituant les parametres de la requete SQL (champ, condition, limit) remplie |
* selon ressources et paramètres */ |
protected $requete_champ = array(' * '); |
protected $requete_condition = ''; |
protected $limite_requete = array( |
'depart' => 0, |
'limite' => 100 |
); |
protected $champ_tri = 'code_langue'; |
protected $direction_tri = 'asc'; |
/** |
* Indique les champs supplémentaires à retourner |
* - conseil_emploi = conseil d'emploi du nom vernaculaire |
* - genre = genre et nombre du nom |
* - taxon = nom retenu associé à ce nom |
*/ |
protected $champs_supp = array(); |
/** |
* Precise la contenance plus ou moins précise du tableau à retourner : |
* - min = les données présentes dans la table |
* - max = les données de la table + les informations complémentaires (pour les identifiants et les codes) |
* - oss = la liste des nom_sci (uniquement pour noms et taxons) */ |
protected $retour_format = 'max'; |
/** Valeur du paramètre de requete recherche : |
* - stricte : le masque est passé tel quel à l'opérateur LIKE. |
* - etendue : ajout automatique du signe % à la place des espaces et en fin de masque avec utilisation de LIKE. |
* - floue : recherche tolérante vis-à-vis d'approximations ou d'erreurs (fautes d'orthographe par exemple) */ |
protected $recherche; |
/** Permet de stocker le tableau de résultat (non encodé en json) */ |
protected $table_retour = array(); |
/** Stocke le nombre total de résultats de la requete principale. Est calculée lors de l'assemblage de la requete */ |
protected $total_resultat; |
private $config; |
public function __construct($config) { |
$this->config = is_null($config) ? Config::get('NomsVernaculaires') : $config; |
} |
//+------------------------------------------------------------------------------------------------------+ |
// créer une condition en fonction du paramétre |
public function traiterParametres() { |
if (isset($this->parametres) && !empty($this->parametres)) { |
if (isset($this->parametres['recherche']) && $this->parametres['recherche'] != '') { |
$this->recherche = $this->parametres['recherche']; |
} |
foreach ($this->parametres as $param => $valeur) { |
switch ($param) { |
case 'masque' : |
$this->ajouterFiltreMasque('nom_vernaculaire', $valeur); |
break; |
case 'masque.nt' : |
$this->ajouterFiltreMasque('num_taxon', $valeur); |
break; |
case 'masque.nv' : |
$this->ajouterFiltreMasque('nom_vernaculaire', $valeur); |
break; |
case 'masque.lg' : |
$this->ajouterFiltreMasque('code_langue', $valeur); |
break; |
case 'retour.format' : |
$this->retour_format = $valeur; |
break; |
case 'navigation.depart' : |
$this->limite_requete['depart'] = $valeur; |
break; |
case 'navigation.limite' : |
$this->limite_requete['limite'] = $valeur; |
break; |
case 'retour.champs' : |
$this->champs_supp = explode(',',$valeur); |
break; |
case 'recherche' : |
break; |
case 'version.projet' : |
break; |
default : |
$p = 'Erreur dans les paramètres de recherche de votre requête : '. |
'</br> Le paramètre " '.$param.' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $p); |
} |
} |
} |
} |
public function ajouterFiltreMasque($nom_champ, $valeur) { |
if ($nom_champ == 'num_taxon') { // si il s'agit d'un chiffre |
$this->requete_condition[] = $nom_champ.' = '.$this->getBdd()->proteger($valeur); |
} else { |
if ($this->recherche == 'floue') { |
$this->requete_condition[] = '(SOUNDEX('.$nom_champ.') = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE('.$nom_champ.')) = SOUNDEX(REVERSE(\''.$valeur.'\'))) '; |
} else { |
if ($this->recherche == 'etendue') { |
$valeur = '%'.str_replace(' ','% ', $valeur); |
$valeur .= '%'; |
} |
$this->requete_condition[] = $nom_champ.' LIKE '.$this->getBdd()->proteger($valeur); |
} |
} |
} |
//+------------------------------------------------------------------------------------------------------+ |
// en fonction de la présence des ressources modifie requete_champ et requete_condition |
public function traiterRessources() { |
if (isset($this->ressources) && !empty($this->ressources)) { |
if (isset($this->ressources[0]) && !empty($this->ressources[0])) { |
$this->traiterRessourceId(); // ajoute condition id=#valeur |
if (isset($this->ressources[1]) && !empty($this->ressources[1])) { |
$this->traiterRessourceChamp(); //modifie requete_champ ou requete_condition |
} |
} |
} else { //rajoute distinct pour ne pas avoir plusieurs fois le même nom |
$this->requete_champ = array('distinct(id)', 'nom_vernaculaire '); |
} |
} |
//requete : /noms-vernaculaires/#id (ex : /noms-vernaculaires/7) |
public function traiterRessourceId() { |
if (is_numeric($this->ressources[0])) { |
$this->requete_condition[] = ' id = '.$this->getBdd()->proteger($this->ressources[0]); |
$this->format_reponse .= '/id'; |
} elseif ($this->ressources[0] == 'attributions') { |
$this->format_reponse .= '/attributions'; |
} else { |
$r = 'Erreur dans les ressources de votre requête : </br> La ressource " '.$this->ressources[0]. |
' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $r); |
} |
} |
public function traiterRessourceChamp() { |
$this->format_reponse .= '/champ'; |
$this->analyserChamp(); |
} |
public function analyserChamp() { |
$this->requete_champ = array(); |
$this->recupererTableConfig('champs_possibles');// s'il y a plusieurs champs correspondant au champ demandé ils sont séparé par des | |
$champs = explode(' ', $this->ressources[1]); |
foreach ($champs as $champ) { |
preg_match('/^([^.]+)(\.([^.]+))?$/', $champ, $match); |
if (isset($this->champs_possibles[$match[1]])) { |
$this->requete_champ[] = str_replace('|', ', ', $this->champs_possibles[$match[1]]); |
} elseif (isset($this->champs_possibles[$match[0]])) { |
$this->requete_champ[] = str_replace('|', ', ', $this->champs_possibles[$match[0]]); |
} else { |
$champs_possibles = implode('</li><li>', array_keys($this->champs_possibles)); |
$c = 'Erreur dans votre requête : </br> Le champ "'.$champ_possibles.'" n\'existe pas. '. |
'Les champs disponibles sont : <li>'.$champs_possibles.'</li> et leurs déclinaisons (ex. ".code").'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $c); |
} |
} |
} |
//+------------------------------------------------------------------------------------------------------+ |
public function assemblerLaRequete() { |
$requete = ' SELECT '.$this->formerRequeteChamp(). |
', CASE code_langue WHEN "fra" THEN 1 ELSE 0 END AS tri '. |
' FROM '.$this->table |
.$this->formerRequeteCondition(). |
' ORDER BY tri DESC, nom_vernaculaire ASC ' |
.$this->formerRequeteLimite(); |
return $requete; |
} |
public function formerRequeteChamp() { |
if (in_array('*', $this->requete_champ)) { |
$champ = ' * '; |
} else { |
$champ = implode(', ', $this->requete_champ); |
} |
return $champ; |
} |
public function formerRequeteCondition() { |
$condition = ''; |
if ($this->requete_condition != null) { |
$condition = ' WHERE '.implode(' AND ', $this->requete_condition); |
} |
return $condition; |
} |
//ajout d'une limite seulement pour les listes (pas plus de 100 resultats retournés pr les requetes |
// suivantes : /noms-vernaculaires et /noms-vernaculaires/#id/relations) |
public function formerRequeteLimite() { |
if (in_array($this->format_reponse , array($this->service.'/id', $this->service.'/id/champs'))) { |
$this->requete_limite = ''; |
} elseif (($depart = $this->limite_requete['depart']) > ($this->total_resultat = $this->recupererTotalResultat())) { |
$this->limite_requete['depart'] = |
(($this->total_resultat - $this->limite_requete['limite']) < 0) ? 0 : ($this->total_resultat - $this->limite_requete['limite']); |
$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite']; |
} else { |
$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite']; |
} |
return $this->requete_limite; |
} |
//on récupère le nombre total de résultats de la requete (ex : le nombre d'id contenu dans la liste /noms-vernaculaires) |
public function recupererTotalResultat() { |
$distinct = ($this->format_reponse == 'noms-vernaculaires/attributions') ? 'id' : 'distinct id '; |
$requete = 'SELECT count('.$distinct.') as nombre FROM ' |
.$this->table |
.$this->formerRequeteCondition(); |
$res = $this->getBdd()->recuperer($requete); |
if ($res) { |
$total = $res['nombre']; |
} else { |
$t = 'Fonction recupererTotalResultat() : <br/>Données introuvables dans la base '.$requete; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE, $t); |
} |
return $total; |
} |
//+------------------------------------------------------------------------------------------------------+ |
// determine en fct du service appelé (/noms-vernaculaires | /noms-vernaculaires/#id | /noms-vernaculaires/#id/champ | |
// /noms-vernaculaires/#id/relations) le format du tableau à retourner. |
public function retournerResultatFormate($resultat) { |
$this->recupererTableConfig('correspondance_champs'); |
switch ($this->format_reponse) { |
case 'noms-vernaculaires' : |
$reponse = ($this->retour_format == 'oss') ? $this->formaterEnOss($resultat) : $this->formaterNomsVernaculaires($resultat); break; |
case 'noms-vernaculaires/attributions' : $reponse = $this->formaterNomsVernaculairesAttributions($resultat); break; |
case 'noms-vernaculaires/id' : $reponse = $this->formaterNomsVernaculairesId($resultat); break; |
case 'noms-vernaculaires/id/champ' : $reponse = $this->formaterNomsVernaculairesIdChamp($resultat); break; |
default : break; |
} |
return $reponse; |
} |
public function ajouterJsonEnTeteNV() { |
$table_retour_json['masque'] = $this->recupererMasque(); |
$table_retour_json['depart'] = $this->limite_requete['depart']; |
$table_retour_json['limite'] = $this->limite_requete['limite']; |
$table_retour_json['total'] = $this->total_resultat; |
$url = $this->formulerUrl($this->total_resultat, '/noms-vernaculaires'); |
if (isset($url['precedent']) && $url['precedent'] != '') { |
$table_retour_json['href.precedent'] = $url['precedent']; |
} |
if (isset($url['suivant']) && $url['suivant'] != '') { |
$table_retour_json['href.suivant'] = $url['suivant']; |
} |
return $table_retour_json; |
} |
public function ajouterJsonResultatNV($resultat) { |
foreach ($resultat as $tab) { |
foreach ($tab as $key => $valeur) { |
if ($valeur != '') { |
switch ($key) { |
case 'id' : $num = $valeur; break; |
case 'nom_vernaculaire' : $this->table_retour['nom'] = $valeur; break; |
default : break; |
} |
} |
} |
if ($this->retour_format == 'max') $this->table_retour['href'] = $this->ajouterHref('noms-vernaculaires', $num); |
$resultat_json[$num] = $this->table_retour; |
$this->table_retour = array(); |
} |
return $resultat_json; |
} |
public function formaterNomsVernaculaires($resultat) { |
$table_retour_json['entete'] = $this->ajouterJsonEnTeteNV(); |
$resultat = $this->hierarchiserResultat($resultat); |
$table_retour_json['resultat'] = $this->ajouterJsonResultatNV($resultat); |
return $table_retour_json; |
} |
public function hierarchiserResultat($resultat) { |
//tri recherche floue |
if (isset($this->parametres['masque.nv'])) { |
$resultat = $this->trierRechercheFloue($this->parametres['masque.nv'], $resultat, 'nom_vernaculaire'); |
} |
if (isset($this->parametres['masque'])) { |
$resultat = $this->trierRechercheFloue($this->parametres['masque'], $resultat, 'nom_vernaculaire'); |
} |
return $resultat; |
} |
public function recupererMasque() { |
$tab_masque = array(); |
foreach ($this->parametres as $param=>$valeur) { |
if (strstr($param, 'masque') != false) { |
$tab_masque[] = $param.'='.$valeur; |
} |
} |
$masque = implode('&', $tab_masque); |
return $masque; |
} |
public function formaterEnOss($resultat) { |
$table_nom = array(); |
$oss = ''; |
foreach ($resultat as $tab) { |
if (isset($tab['nom_vernaculaire']) ) { |
if (!in_array($tab['nom_vernaculaire'], $table_nom)) { |
$table_nom[] = $tab['nom_vernaculaire']; |
$oss [] = $tab['nom_vernaculaire']; |
} |
} |
} |
if (isset($this->masque)) $masque = implode('&', $this->masque); |
else $masque = 'Pas de masque'; |
$table_retour_oss = array($masque, $oss); |
return $table_retour_oss; |
} |
public function formaterNomsVernaculairesAttributions($resultat) { |
$table_retour_json['entete']['masque'] = $this->recupererMasque(); |
$table_retour_json['entete']['depart'] = $this->limite_requete['depart']; |
$table_retour_json['entete']['limite'] = $this->limite_requete['limite']; |
$table_retour_json['entete']['total'] = $this->total_resultat; |
$url = $this->formulerUrl($this->total_resultat, '/noms-vernaculaires/attributions'); |
if (isset($url['precedent']) && $url['precedent'] != '') { |
$table_retour_json['entete']['href.precedent'] = $url['precedent']; |
} |
if (isset($url['suivant']) && $url['suivant'] != '') { |
$table_retour_json['entete']['href.suivant'] = $url['suivant']; |
} |
foreach ($resultat as &$tab) { |
unset($tab['tri']); |
$resultat_json[$tab['id']]['id'] = $tab['id']; |
$resultat_json[$tab['id']]['nom_vernaculaire'] = $tab['nom_vernaculaire']; |
$resultat_json[$tab['id']]['code_langue'] = $tab['code_langue']; |
$resultat_json[$tab['id']]['taxon.code'] = 'bdtxa.nt:'.$tab['num_taxon']; |
if ($this->retour_format == 'max') { |
$resultat_json[$tab['id']]['num_taxon'] = $tab['num_taxon']; |
$resultat_json[$tab['id']]['nom_retenu.code'] = $tab['num_taxon']; |
$resultat_json[$tab['id']]['taxon'] = $tab['num_taxon']; |
$this->taxons[] = $tab['num_taxon']; // utilisé pour chercher les noms latins plus bas |
$resultat_json[$tab['id']]['href'] = $this->ajouterHref('noms-vernaculaires', $tab['id']); |
if($this->champs_supp != array()) { |
$resultat_json[$tab['id']] = $this->ajouterChampsOntologieLigneResultat($tab); |
} |
} |
} |
if ($this->retour_format == 'max') { |
// On est obligé de faire un deuxième boucle pour demander tous les taxons présents en une |
// fois et les attribuer aux noms car c'est beaucoup plus rapide |
$noms_sci = $this->recupererNomTaxons(); |
foreach ($resultat_json as $num_nom => &$tab) { |
$tab = $this->ajouterTaxonsAttributionsLigneResultat($tab, $noms_sci); |
if($tab == null) { |
unset($resultat_json[$num_nom]); |
} |
} |
} |
$table_retour_json['resultat'] = $resultat_json; |
return $table_retour_json; |
} |
/** |
* Ajoute les champs d'ontologie supplémentaires si necéssaire |
* en faisant appels aux web services associés |
* @param array $ligne_resultat |
* |
* @return array la ligne modifiée |
*/ |
public function ajouterChampsOntologieLigneResultat($ligne_resultat) { |
$intitule = ''; |
foreach($this->champ_infos as $cle => $champs_supplementaires) { |
if(in_array($cle, $this->champs_supp)) { |
extract($champs_supplementaires); |
$valeur_recherche = ''; |
switch($cle) { |
case 'taxon': |
$valeur_recherche = $ligne_resultat['num_taxon']; |
$intitule = 'taxon.code'; |
break; |
} |
$code_valeur = ''; |
if(trim($valeur_recherche) != '') { |
$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur_recherche, $projet); |
$code_valeur = $this->chercherSignificationCode($url, $nom); |
} |
$ligne_resultat[$intitule] = $code_valeur; |
} |
} |
return $ligne_resultat; |
} |
/** |
* Fonction qui ajoute les attributions à une ligne de résultats |
* |
* @param array $ligne_tableau_resultat |
* @param array $nom_sci |
*/ |
public function ajouterTaxonsAttributionsLigneResultat(&$ligne_tableau_resultat, &$noms_sci) { |
if (isset($noms_sci[$ligne_tableau_resultat['num_taxon']])) { |
$ligne_tableau_resultat['nom_retenu.code'] = $noms_sci[$ligne_tableau_resultat['num_taxon']]['id']; |
$ligne_tableau_resultat['taxon'] = $noms_sci[$ligne_tableau_resultat['num_taxon']]['nom_sci']; |
} else { |
$ligne_tableau_resultat = null; |
} |
return $ligne_tableau_resultat; |
} |
private function trierLigneTableau($a, $b) { |
$retour = 0; |
if ($a[$this->champ_tri] == $b[$this->champ_tri]) { |
$retour = 0; |
} |
if($this->champ_tri == 'code_langue') { |
if ($a[$this->champ_tri] == 'fra' && $b[$this->champ_tri] != 'fra') { |
$retour = ($this->direction_tri == 'asc') ? -1 : 1; |
} else if ($a[$this->champ_tri] != 'fra' && $b[$this->champ_tri] == 'fra') { |
$retour = ($this->direction_tri == 'asc') ? 1 : -1; |
} else { |
$retour = $this->comparerChaineSelonDirectionTri($a[$this->champ_tri], $b[$this->champ_tri]); |
} |
} else { |
$retour = $this->comparerChaineSelonDirectionTri($a[$this->champ_tri], $b[$this->champ_tri]); |
} |
return $retour; |
} |
private function comparerChaineSelonDirectionTri($a, $b) { |
if($this->direction_tri == 'asc') { |
return ($a < $b) ? -1 : 1; |
} else { |
return ($a > $b) ? -1 : 1; |
} |
} |
// formatage de la reponse /id ss la forme |
// id, nom_vernaculaire, attributions |
// langue |
// num_nom (correspond à un taxon bdtxa) |
public function formaterNomsVernaculairesId($resultat) { |
foreach ($resultat as $taxon) { // pour chaque attribution à un taxon bdtxa |
// on crée les variables qui serviront de clés et on les enléves du tableau |
$num_nom = $taxon['id']; // unique pour un trinôme id, langue, taxon |
unset($taxon['id']); |
$langue = $taxon['code_langue']; |
unset($taxon['code_langue']); |
foreach ($this->correspondance_champs as $key => $correspondance) { // ordonne les infos pour affichage |
if (isset($taxon[$key]) && $taxon[$key] != "") { |
$this->afficherDonnees($correspondance, $taxon[$key], $langue, $num_nom); |
} |
} |
foreach ($taxon as $key => $valeur) { // rajoute les champs non prévus dans l'api |
if (!isset($this->correspondance_champs[$key]) && $valeur != "") { |
$this->afficherDonnees($key, $valeur, $langue, $num_nom); |
} |
} |
} |
if ($this->retour_format == 'max') $this->afficherTaxons(); // va chercher les noms de tous les taxons |
unset($this->table_retour['href']); |
return $this->table_retour; |
} |
public function afficherDonnees($champ, $valeur, $langue = '', $num_nom = '') { |
if ($champ == 'id' || $champ == 'nom_vernaculaire') { |
$this->table_retour[$champ] = $valeur; |
} elseif (preg_match('/^(.*)\.code$/', $champ, $match)) { |
switch ($match[1]) { |
case 'taxon' : if ($this->retour_format == 'max') {$this->taxons[$num_nom] = $valeur;} |
$this->afficherPointCode($match[1], $langue, $num_nom, $valeur); break; |
case 'langue' : //$this->afficherPointCode($match[1], 'iso-639-3', 'langues', $valeur); |
break; |
default : break; |
} |
} elseif ($langue != '') { |
$this->table_retour['attributions'][$langue][$num_nom][$champ] = $valeur; |
} else { |
$this->table_retour[$champ] = $valeur; |
} |
} |
public function afficherPointCode($nomChamp, $langue, $num_nom, $valeur) { |
if (isset($this->champ_infos[$nomChamp])) { |
extract($this->champ_infos[$nomChamp]); |
} |
if ($this->retour_format == 'max') { |
$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur, $projet); |
if ($service == 'taxons') { |
$code_valeur = ''; |
$this->table_retour['attributions'][$langue][$num_nom]['nom_retenu.code'] = $code_valeur; |
} else { |
$code_valeur = $this->chercherSignificationCode($url, $nom); |
} |
if ($projet != '') $projet .= '.'; |
$this->table_retour['attributions'][$langue][$num_nom][$nomChamp] = $code_valeur; |
$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.code'] = $projet.$ressource.$valeur; |
$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.href'] = $url; |
} else { |
if ($projet != '') $projet .= '.'; |
$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.code'] = $projet.$ressource.$valeur; |
} |
} |
public function chercherSignificationCode($url, $nom) { |
if (isset($this->signification_code[$url])) { |
$valeur = $this->signification_code[$url]; |
} else { |
$res = $this->consulterHref($url); |
$valeur = $res->$nom; |
$this->signification_code[$url] = $valeur; |
} |
return $valeur; |
} |
public function afficherTaxons() { |
$resultat = $this->recupererNomTaxons(); |
foreach ($this->table_retour['attributions'] as $code_langue=>$langue) { |
foreach ($langue as $num_nom=>$taxon) { |
$num_tax = ltrim($taxon['taxon.code'], 'bdtxa.nt:'); |
if (isset($resultat[$num_tax])) { |
$this->table_retour['attributions'][$code_langue][$num_nom]['nom_retenu.code'] = $resultat[$num_tax]['id']; |
$this->table_retour['attributions'][$code_langue][$num_nom]['taxon'] = $resultat[$num_tax]['nom_sci']; |
} |
} |
} |
} |
public function recupererNomTaxons() { |
$taxons = array_unique($this->taxons); |
$url = Config::get('url_service_base').'bdtxa/taxons?navigation.limite=500&ns.structure=au&masque.nt='.implode(',', $taxons); |
$res = $this->consulterHref($url); |
foreach ($res->resultat as $id=>$taxon) { |
$resultat[$taxon->num_taxonomique]['id'] = 'bdtxa.nn:'.$id; |
$resultat[$taxon->num_taxonomique]['nom_sci'] = $taxon->nom_sci_complet; |
} |
return $resultat; |
} |
public function formaterNomsVernaculairesIdChamp($resultat) { |
$this->table_retour['id'] = $this->ressources[0]; |
$champs = explode(' ', $this->ressources[1]); |
if (in_array('attributions', $champs) != false) { |
$this->formaterNomsVernaculairesId($resultat); |
unset($this->table_retour['nom_vernaculaire']); |
} else { |
$champ_attributions = array('num_taxon', 'zone_usage', 'num_statut', 'num_genre', 'notes'); |
foreach ($resultat as $taxon) { |
foreach ($taxon as $key=>$valeur) { |
if ($key == 'code_langue' && in_array('langue', $champs) != false) { |
$this->table_retour['attributions']['langue'][] = $valeur; |
} elseif (in_array($key, $champ_attributions) != false) { |
$this->afficherPoint($this->correspondance_champs[$key] , $valeur, $taxon['code_langue'], $taxon['num_nom_vernaculaire']); |
} elseif (in_array($key, $champs) != false) { |
$this->table_retour[$key] = $valeur; |
} |
} |
if (in_array('biblio', $champs) != false) $this->chargerBiblio($taxon['num_nom_vernaculaire'], $taxon['code_langue']); |
} |
if (in_array('biblio', $champs) != false && array_search('biblio.num_ref', $this->table_retour) != false) $this->table_retour['biblio'] = null; |
} |
return $this->table_retour; |
} |
public function afficherPoint($champ, $valeur, $langue, $num_nom) { |
preg_match('/^(.*)\.code$/', $champ, $match); |
$champ = $match[1]; |
if (isset($this->champ_infos[$champ])) { |
extract($this->champ_infos[$champ]); |
$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur, $projet); |
$projet .= '.'; |
} |
$champs = explode(' ', $this->ressources[1]); |
if (in_array($champ.'.*', $champs) !== false && isset($projet)) { |
$this->table_retour['attributions'][$langue][$num_nom][$champ.'.code'] = $projet.$ressource.$valeur; |
$this->table_retour['attributions'][$langue][$num_nom][$champ.'.href'] = $url; |
} |
if (in_array($champ.'.code', $champs) !== false && isset($projet)) { |
$this->table_retour['attributions'][$langue][$num_nom][$champ.'.code'] = $projet.$ressource.$valeur; |
} |
if (in_array($champ.'.href', $champs) !== false && isset($projet)) { |
$this->table_retour['attributions'][$langue][$num_nom][$champ.'.href'] = $url; |
} |
if (in_array($champ, $champs) !== false) { |
if (isset($url)) { |
$this->table_retour['attributions'][$langue][$num_nom][$champ] = $this->chercherSignificationCode($url, $nom); |
} else { |
$this->table_retour['attributions'][$langue][$champ] = $valeur; |
} |
} |
} |
public function afficherLangue($nomChamp, $projet, $service, $valeur, $ressource = '', $nom = 'nom') { |
if ($this->retour_format == 'max') { |
$this->table_retour['attributions'][$nomChamp] = $nom; |
$this->table_retour['attributions'][$nomChamp.'.code'] = $projet.$ressource.$valeur; |
$this->table_retour['attributions'][$nomChamp.'.href'] = $url; |
} else { |
$this->table_retour['attributions'][$nomChamp.'.code'] = $projet.$ressource.$valeur; |
} |
} |
} |
?> |
/tags/v0.1-20130829/services/modules/0.1/iso-3166-1/ZoneGeo.php |
---|
New file |
0,0 → 1,401 |
<?php |
/** |
* Description : |
* Classe ZoneGeo.php fournit des informations sur un ensemble de lieux à une échelle donnée. |
* Le but étant de fournir un ensemble minimal d'information comprenant : |
* un identifiant (numérique ou alphanumérique sous forme de ChatMot si possible), un nom, une region et |
* éventuellement une relation hiérarchique avec un autre terme (=classe). |
* Si l'url finit par /zone-geo on retourne une liste de zones (seulement les 100 premières par défaut). |
* L'url peut contenir des paramètres optionnels passés après le ? : /zone-geo?param1=val1¶m2=val2&... |
* |
* Les paramètres de requête disponibles sont : masque, masque.code, masque.nom, masque.region , recherche, |
* distinct, retour.format, navigation.depart et navigation.limite. |
* |
* Encodage en entrée : utf8 |
* Encodage en sortie : utf8 |
* @package framework-v3 |
* @author Delphine Cauquil <delphine@tela-botanica.org> |
* @author Jennifer Dhé <jennifer.dhe@tela-botanica.org> |
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt> |
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt> |
* @version 1.0 |
* @copyright 1999-${year} Tela Botanica (accueil@tela-botanica.org) |
*/ |
class ZoneGeo extends Commun { |
protected $service = 'zone-geo'; |
/** |
* Permet de stocker la requete formulée : /zone-geo | /zone-geo/#id | /zone-geo/#id/champ | /zone-geo/#id/relations |
* Est remplit au cours de l'analyse des ressources (traiterRessources()), par défaut, a la valeur du service. |
* Est utilisée principalement pr déterminer le format du tableau à retourner. */ |
protected $format_reponse = 'zone-geo'; |
/** Variables constituant les parametres de la requete SQL (champ, condition, group by, limit) remplie |
* selon ressources et paramètres */ |
protected $requete_champ = ' * '; |
protected $requete_condition = ''; |
protected $limite_requete = array( |
'depart' => 0, |
'limite' => 100 |
); |
/** Stockage des ressources et paramétres */ |
protected $table_ressources = array(); |
protected $table_param = array(); |
/** |
* Precise la contenance plus ou moins précise du tableau à retourner : |
* - min = les données présentes dans la table |
* - max = les données de la table + les informations complémentaires (pour les identifiants et les codes) |
* - oss = la liste des nom_sci (uniquement pour noms et taxons) |
*/ |
protected $retour_format = 'max'; |
/** Valeur du paramètre de requete recherche : |
* - stricte : le masque est passé tel quel à l'opérateur LIKE. |
* - etendue : ajout automatique du signe % à la place des espaces et en fin de masque avec utilisation de LIKE. |
* - floue : recherche tolérante vis-à-vis d'approximations ou d'erreurs (fautes d'orthographe par exemple) */ |
protected $recherche; |
/** Permet de stocker le tableau de résultat (non encodé en json) */ |
protected $table_retour = array(); |
/** Stocke le nombre total de résultats de la requete principale. Est calculée lors de l'assemblage de la requete */ |
protected $total_resultat; |
// +-----------------------------------------------------------------------------------------------------+ |
public function traiterParametres() { |
if (isset($this->parametres) && !empty($this->parametres)) { |
$this->table_param = $this->parametres; |
// masque : filtre la liste en fonction d'un masque de recherche portant sur le code, le nom ou la region. |
// masque.code : filtre uniquement sur le code. masque.nom : filtre uniquement sur le nom. |
// masque.region : filtre uniquement sur la region. |
if (isset($this->parametres['recherche']) && $this->parametres['recherche'] != '') { |
$this->recherche = $this->parametres['recherche']; |
} |
foreach ($this->parametres as $param => $valeur) { |
switch ($param) { |
case 'masque' : |
$this->ajouterLeFiltreMasque('masque', $valeur); |
break; |
case 'masque.code' : |
$this->ajouterLeFiltreMasque('codet', $valeur); |
break; |
case 'masque.nom' : |
$this->ajouterLeFiltreMasque('nom', $valeur); |
break; |
case 'masque.statut' : |
$this->ajouterLeFiltreMasque('codet_statut', $valeur); |
break; |
case 'retour.format' : |
$this->retour_format = $valeur; |
break; |
case 'navigation.depart' : |
$this->limite_requete['depart'] = $valeur; |
break; |
case 'navigation.limite' : |
$this->limite_requete['limite'] = $valeur; |
break; |
case 'recherche' : |
break; |
default : |
$p = 'Erreur dans les paramètres de recherche de votre requête : '. |
'</br> Le paramètre " '.$param.' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $p); break; |
} |
} |
} |
} |
public function ajouterLeFiltreMasque($nom_champ, $valeur) { |
if ($nom_champ == 'codet') { |
$this->requete_condition[] .= $nom_champ.' = '.$this->getBdd()->proteger($valeur); |
} else { |
if ($this->recherche == 'floue') { |
if ($nom_champ == 'masque') { |
$this->requete_condition[] = ' ( codet = '.$this->getBdd()->proteger($valeur) |
.' OR (SOUNDEX(nom_francais) = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE(nom_francais)) = SOUNDEX(REVERSE(\''.$valeur.'\')) OR ' |
.'SOUNDEX(nom_anglais) = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE(nom_anglais)) = SOUNDEX(REVERSE(\''.$valeur.'\'))) ' |
.' OR ( SOUNDEX(codet_statut) = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE(codet_statut)) = SOUNDEX(REVERSE(\''.$valeur.'\')) ' |
.')) '; |
} elseif ($nom_champ == 'nom') { |
$this->requete_condition[] = '(SOUNDEX(nom_francais) = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE(nom_francais)) = SOUNDEX(REVERSE(\''.$valeur.'\'))) OR |
(SOUNDEX(nom_anglais) = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE(nom_anglais)) = SOUNDEX(REVERSE(\''.$valeur.'\'))) '; |
} else { |
$this->requete_condition[] = '(SOUNDEX('.$nom_champ.') = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE('.$nom_champ.')) = SOUNDEX(REVERSE(\''.$valeur.'\'))) '; |
} |
} else { |
if ($this->recherche == 'etendue') { |
$valeur = str_replace(' ','%', $valeur); |
$valeur .= '%'; |
} |
if ($nom_champ == 'masque') { |
$this->requete_condition[] = '(codet = '.$this->getBdd()->proteger($valeur) |
.' OR nom_francais LIKE '.$this->getBdd()->proteger($valeur) |
.' OR nom_anglais LIKE '.$this->getBdd()->proteger($valeur) |
.' OR codet_statut LIKE '.$this->getBdd()->proteger($valeur).')'; |
} elseif ($nom_champ == 'nom') { |
$this->requete_condition[] = '(nom_francais LIKE '.$this->getBdd()->proteger($valeur).' OR ' |
.'nom_anglais LIKE '.$this->getBdd()->proteger($valeur).') '; |
} else { |
$this->requete_condition[] = $nom_champ.' LIKE '.$this->getBdd()->proteger($valeur); |
} |
} |
} |
} |
// +-----------------------------------------------------------------------------------------------------+ |
public function traiterRessources() { |
if (isset($this->ressources) && !empty($this->ressources)) { |
$this->table_ressources = $this->ressources; |
if (isset($this->table_ressources[0]) && !empty($this->table_ressources[0])) { |
//requete = /zone-geo/#id |
$this->traiterRessourceId(); |
if (isset($this->table_ressources[1]) && !empty($this->table_ressources[1])) { |
//requete = /zone-geo/#id/#champ ou /zone-geo/#id/relations |
$this->traiterRessourceChampOuRelations(); |
} |
} |
} |
} |
public function traiterRessourceId() { |
//requete : /zone-geo/#id (ex : /zone-geo/7) |
if ($this->table_ressources[0]) { |
$this->requete_condition[] = ' codet = '.$this->getBdd()->proteger($this->table_ressources[0]); |
$this->format_reponse .= '/id'; |
} else { |
$r = 'Erreur dans les ressources de votre requête : </br> La ressource " '.$this->table_ressources[0]. |
' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $r); |
} |
} |
public function traiterRessourceChampOuRelations() { |
if ($this->table_ressources[1] == 'relations') { |
$r = 'Erreur dans les ressources de votre requête : </br> La ressource " '.$this->table_ressources[1]. |
' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $r); |
} else { |
$this->format_reponse .= '/champ'; |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
public function assemblerLaRequete() { |
//assemblage de la requete : |
$requete = ' SELECT '.$this->requete_champ. |
' FROM '.$this->table |
.$this->formerRequeteCondition() |
.$this->formerRequeteLimite(); |
return $requete; |
} |
//ajout d'une limite seulement pour les listes (pas plus de 100 resultats retournés pr les requetes |
// suivantes : /zone-geo et /zone-geo/#id/relations) |
public function formerRequeteLimite() { |
if ($this->format_reponse != 'zone-geo') { |
$this->requete_limite = ''; |
} elseif (($depart = $this->limite_requete['depart']) > ($this->total_resultat = $this->recupererTotalResultat())) { |
//cas ou la requete presente un navigation.depart supérieur au nb total de resultats. |
$this->limite_requete['depart'] = |
(($nb - $this->limite_requete['limite']) < 0) ? 0 : ($nb - $this->limite_requete['limite']); |
$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite']; |
} else { |
$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite']; |
} |
return $this->requete_limite; |
} |
public function formerRequeteCondition() { |
$condition = ''; |
if ($this->requete_condition != null) { |
$condition = ' WHERE '.implode(' AND ', $this->requete_condition); |
} |
return $condition; |
} |
public function recupererTotalResultat() { |
//on récupère le nombre total de résultats de la requete (ex : le nombre d'id contenu dans la liste /zone-geo) |
$requete = 'SELECT count(*) as nombre FROM ' |
.$this->table |
.$this->formerRequeteCondition(); |
$res = $this->getBdd()->recuperer($requete); |
if ($res) { |
$total = $res['nombre']; |
} else { |
$t = 'Fonction recupererTotalResultat() : <br/>Données introuvables dans la base'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE, $t); |
} |
return $total; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// determine en fct du service appelé (/zone-geo | /zone-geo/#id | /zone-geo/#id/champ | |
// /zone-geo/#id/relations) le format du tableau à retourner. Encode en json |
public function retournerResultatFormate($resultat) { |
$this->recupererTableConfig('correspondance_champs'); |
switch ($this->format_reponse) { |
case 'zone-geo' : $reponse = $this->formaterZoneGeo($resultat); break; |
case 'zone-geo/id' : $reponse = $this->formaterZoneGeoId($resultat[0]); break; |
case 'zone-geo/id/champ' : $reponse = $this->formaterZoneGeoIdChamp($resultat[0]); break; |
default : break; |
} |
return $reponse; |
} |
public function formaterZoneGeo($resultat) { |
//on remplit la table $table_retour_json['entete'] |
$this->table_retour['depart'] = $this->limite_requete['depart']; |
$this->table_retour['limite'] = $this->limite_requete['limite']; |
$this->table_retour['total'] = $this->total_resultat; |
$url = $this->formulerUrl($this->total_resultat, '/zone-geo'); |
if (isset($url['precedent']) && $url['precedent'] != '') { |
$this->table_retour['href.precedent'] = $url['precedent']; |
} |
if (isset($url['suivant']) && $url['suivant'] != '') { |
$this->table_retour['href.suivant'] = $url['suivant']; |
} |
$table_retour_json['entete'] = $this->table_retour; |
//on remplit la table $table_retour_json['resultat'] |
$this->table_retour = array(); |
if (isset($this->table_param['masque_nom'])) $resultat = $this->trierRechercheFloue($this->table_param['masque_nom'], $resultat, 'nom_francais'); |
foreach ($resultat as $tab) { |
foreach ($tab as $key => $valeur) { |
$valeur = rtrim($valeur); |
if ($valeur != '') { |
switch ($key) { |
case 'codet' : $num = $valeur; $this->table_retour['code'] = $valeur; break; |
case 'nom_francais' : $this->table_retour['nom'] = $valeur; break; |
case 'nom_anglais' : if ($tab['nom_francais'] == '') $this->table_retour['nom'] = $valeur; break; |
case 'codet_statut' : $this->table_retour['statut'] = $valeur; break; |
default : break; |
} |
} |
} |
if ($this->retour_format == 'max') { |
$this->table_retour['href'] = $this->ajouterHref('zone-geo', $num); |
} |
$resultat_json[$num] = $this->table_retour; |
$this->table_retour = array(); |
} |
$table_retour_json['resultat'] = $resultat_json; |
return $table_retour_json; |
} |
public function formaterZoneGeoId($resultat) { |
foreach ($resultat as $key => $valeur) { |
if ($valeur != '') { |
$this->afficherDonnees($key, $valeur); |
} |
} |
unset($this->table_retour['href']); |
return $this->table_retour; |
} |
public function formaterZoneGeoIdChamp($resultat) { |
//on recupère tous les resultats possibles |
$reponse = $this->formaterZoneGeoId($resultat); |
$this->table_retour = array(); |
//on recupère les résultats demandés à partir du tableau de résultat complet |
$this->table_retour['id'] = $reponse['code']; |
$champs = explode(' ', $this->table_ressources[1]); |
foreach ($champs as $champ) { |
if ($champ == 'nom') $champ = 'nom.fr'; |
if ($this->verifierValiditeChamp($champ)) { |
if (strrpos($champ, '.*') !== false) { |
$this->afficherPointEtoile($champ, $reponse); |
} else { |
if (isset($reponse[$champ])) { |
$this->table_retour[$champ] = $reponse[$champ]; |
} else { |
$this->table_retour[$champ] = null; |
} |
} |
} |
} |
return $this->table_retour; |
} |
public function verifierValiditeChamp($champ) { |
preg_match('/^([^.]+)(\.([^.]+))?$/', $champ, $match); |
$champs_possibles = $this->correspondance_champs; |
$champs_possibles[] = 'nom.*'; |
if (in_array($match[1], $champs_possibles)) { |
$validite = true; |
} elseif (in_array($match[0], $champs_possibles)) { |
$validite = true; |
} else { |
$champs_possibles = implode('</li><li>', $champs_possibles); |
$c = 'Erreur dans votre requête : </br> Le champ "'.$champ_possibles.'" n\'existe pas. '. |
'Les champs disponibles sont : <li>'.$champs_possibles.'</li>'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $c); |
} |
return $validite; |
} |
public function afficherPointEtoile($champ, $reponse) { |
preg_match('/^([^.]+\.)\*$/', $champ, $match); |
foreach ($reponse as $chp => $valeur) { |
if (strrpos($chp, $match[1]) !== false) { |
if ($valeur != '') { |
$this->table_retour[$chp] = $valeur; |
} else { |
$this->table_retour[$chp] = null; |
} |
} |
} |
} |
public function afficherDonnees($champ, $valeur) { |
if ($this->retour_format == 'max') { |
if ($champ == 'codet_statut') { |
$this->table_retour[$this->correspondance_champs[$champ]] = $valeur; |
$this->table_retour[$this->correspondance_champs[$champ].'.href'] = |
$this->ajouterHref('ontologies', 'masque.nom=Codet '.$valeur, '?'); |
} else { |
$this->table_retour[$this->correspondance_champs[$champ]] = $valeur; |
} |
} else { |
$this->table_retour[$this->correspondance_champs[$champ]] = $valeur; |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
/** Permet de retourner l'url http://tela-botanica.org/service:eflore:0.1/[projet]/[version_projet]/[service]/[ressource]:[valeur] |
* @param $service : correspond au nom de la ressource à laquelle on souhaite acceder |
* @param $val : correspond au paramètre de la ressource (ex : |
* @param $projet : est remplit dans les cas suivants : |
* - si le projet dans lequel se trouve l'information est différent de celui du service appelé |
* - si on souhaite rappeler le meme projet avec la meme ressource mais un parametre de ressource différent |
*/ |
public function ajouterHref($service, $val, $separation = '/') { |
$val = $this->encoderUrl($val); |
if ($this->version_projet == '+') { |
$url = Config::get('url_service_base').Config::get('nom_projet').'/'.$service.$separation.$val; |
} else { |
$url = Config::get('url_service_base').Config::get('nom_projet').'/'.$this->version_projet.'/'.$service.$separation.$val; |
} |
return $url; |
} |
public function encoderUrl($url) { |
$url = str_replace(' ', '%20', $url); |
$url = str_replace('?', urlencode('?'), $url); |
return $url; |
} |
} |
?> |
/tags/v0.1-20130829/services/modules/0.1/nvps/NomsVernaculaires.php |
---|
New file |
0,0 → 1,652 |
<?php |
/** |
* Description : |
* Classe NomsVernaculaires.php fournit une liste de noms vernaculaires et leur liaison à la bdtfx |
* Le but étant de fournir un ensemble minimal d'information comprenant : |
* un identifiant (numérique ou alphanumérique sous forme de ChatMot si possible), un nom, une langue et |
* une relation avec un taxon de la bdtfx. |
* Si l'url finit par /noms-vernaculaires on retourne une liste de noms (seulement les 100 premières par défaut). |
* L'url peut contenir des paramètres optionnels passés après le ? : /observations?param1=val1¶m2=val2&... |
* |
* Les paramètres de requête disponibles sont : masque, masque.code, masque.nom, masque.region , recherche, |
* distinct, retour.format, navigation.depart et navigation.limite. |
* |
* Encodage en entrée : utf8 |
* Encodage en sortie : utf8 |
* @package framework-v3 |
* @author Delphine Cauquil <delphine@tela-botanica.org> |
* @author Jennifer Dhé <jennifer.dhe@tela-botanica.org> |
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt> |
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt> |
* @version 1.0 |
* @copyright 1999-${year} Tela Botanica (accueil@tela-botanica.org) |
*/ |
class NomsVernaculaires extends Commun { |
protected $champ_infos = array( |
'taxon' => array('service' => 'taxons', 'ressource' => 'nt:', 'projet' => 'bdtfx', 'nom' => 'nom_sci')); |
protected $service = 'noms-vernaculaires'; |
/** |
* Permet de stocker la requete formulée : /noms-vernaculaires | /noms-vernaculaires/#id | |
* /noms-vernaculaires/#id/champ | /noms-vernaculaires/#id/relations |
* Est remplit au cours de l'analyse des ressources (traiterRessources()), par défaut, a la valeur du service. |
* Est utilisée principalement pr déterminer le format du tableau à retourner. */ |
protected $format_reponse = 'noms-vernaculaires'; |
/** Variables constituant les parametres de la requete SQL (champ, condition, limit) remplie |
* selon ressources et paramètres */ |
protected $requete_champ = array(' * '); |
protected $requete_condition = ''; |
protected $limite_requete = array( |
'depart' => 0, |
'limite' => 100 |
); |
protected $champ_tri = 'code_langue'; |
protected $direction_tri = 'asc'; |
/** |
* Indique les champs supplémentaires à retourner |
* - conseil_emploi = conseil d'emploi du nom vernaculaire |
* - genre = genre et nombre du nom |
* - taxon = nom retenu associé à ce nom |
*/ |
protected $champs_supp = array(); |
/** |
* Precise la contenance plus ou moins précise du tableau à retourner : |
* - min = les données présentes dans la table |
* - max = les données de la table + les informations complémentaires (pour les identifiants et les codes) |
* - oss = la liste des nom_sci (uniquement pour noms et taxons) */ |
protected $retour_format = 'max'; |
/** Valeur du paramètre de requete recherche : |
* - stricte : le masque est passé tel quel à l'opérateur LIKE. |
* - etendue : ajout automatique du signe % à la place des espaces et en fin de masque avec utilisation de LIKE. |
* - floue : recherche tolérante vis-à-vis d'approximations ou d'erreurs (fautes d'orthographe par exemple) */ |
protected $recherche; |
/** Permet de stocker le tableau de résultat (non encodé en json) */ |
protected $table_retour = array(); |
/** Stocke le nombre total de résultats de la requete principale. Est calculée lors de l'assemblage de la requete */ |
protected $total_resultat; |
private $config; |
public function __construct($config) { |
$this->config = is_null($config) ? Config::get('NomsVernaculaires') : $config; |
} |
//+------------------------------------------------------------------------------------------------------+ |
// créer une condition en fonction du paramétre |
public function traiterParametres() { |
if (isset($this->parametres) && !empty($this->parametres)) { |
if (isset($this->parametres['recherche']) && $this->parametres['recherche'] != '') { |
$this->recherche = $this->parametres['recherche']; |
} |
foreach ($this->parametres as $param => $valeur) { |
switch ($param) { |
case 'masque' : |
$this->ajouterFiltreMasque('nom_vernaculaire', $valeur); |
break; |
case 'masque.nt' : |
$this->ajouterFiltreMasque('num_taxon', $valeur); |
break; |
case 'masque.nv' : |
$this->ajouterFiltreMasque('nom_vernaculaire', $valeur); |
break; |
case 'masque.lg' : |
$this->ajouterFiltreMasque('code_langue', $valeur); |
break; |
case 'masque.cce' : |
$this->ajouterFiltreMasque('num_statut', $valeur); |
break; |
case 'retour.format' : |
$this->retour_format = $valeur; |
break; |
case 'navigation.depart' : |
$this->limite_requete['depart'] = $valeur; |
break; |
case 'navigation.limite' : |
$this->limite_requete['limite'] = $valeur; |
break; |
case 'retour.champs' : |
$this->champs_supp = explode(',',$valeur); |
break; |
case 'recherche' : |
break; |
case 'version.projet' : |
break; |
default : |
$p = 'Erreur dans les paramètres de recherche de votre requête : '. |
'</br> Le paramètre " '.$param.' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $p); |
} |
} |
} |
} |
public function ajouterFiltreMasque($nom_champ, $valeur) { |
if ($nom_champ == 'num_taxon') { // si il s'agit d'un chiffre |
$this->requete_condition[] = $nom_champ.' = '.$this->getBdd()->proteger($valeur); |
} else { |
if ($this->recherche == 'floue') { |
$this->requete_condition[] = '(SOUNDEX('.$nom_champ.') = SOUNDEX(\''.$valeur.'\')' |
.' OR SOUNDEX(REVERSE('.$nom_champ.')) = SOUNDEX(REVERSE(\''.$valeur.'\'))) '; |
} else { |
if ($this->recherche == 'etendue') { |
$valeur = '%'.str_replace(' ','% ', $valeur); |
$valeur .= '%'; |
} |
$this->requete_condition[] = $nom_champ.' LIKE '.$this->getBdd()->proteger($valeur); |
} |
} |
} |
//+------------------------------------------------------------------------------------------------------+ |
// en fonction de la présence des ressources modifie requete_champ et requete_condition |
public function traiterRessources() { |
if (isset($this->ressources) && !empty($this->ressources)) { |
if (isset($this->ressources[0]) && !empty($this->ressources[0])) { |
$this->traiterRessourceId(); // ajoute condition id=#valeur |
if (isset($this->ressources[1]) && !empty($this->ressources[1])) { |
$this->traiterRessourceChamp(); //modifie requete_champ ou requete_condition |
} |
} |
} else { //rajoute distinct pour ne pas avoir plusieurs fois le même nom |
$this->requete_champ = array('distinct(id)', 'nom_vernaculaire '); |
} |
} |
//requete : /noms-vernaculaires/#id (ex : /noms-vernaculaires/7) |
public function traiterRessourceId() { |
if (is_numeric($this->ressources[0])) { |
$this->requete_condition[] = ' id = '.$this->getBdd()->proteger($this->ressources[0]); |
$this->format_reponse .= '/id'; |
} elseif ($this->ressources[0] == 'attributions') { |
$this->format_reponse .= '/attributions'; |
} else { |
$r = 'Erreur dans les ressources de votre requête : </br> La ressource " '.$this->ressources[0]. |
' " n\'existe pas.'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $r); |
} |
} |
public function traiterRessourceChamp() { |
$this->format_reponse .= '/champ'; |
$this->analyserChamp(); |
} |
public function analyserChamp() { |
$this->requete_champ = array(); |
$this->recupererTableConfig('champs_possibles');// s'il y a plusieurs champs correspondant au champ demandé ils sont séparé par des | |
$champs = explode(' ', $this->ressources[1]); |
foreach ($champs as $champ) { |
preg_match('/^([^.]+)(\.([^.]+))?$/', $champ, $match); |
if (isset($this->champs_possibles[$match[1]])) { |
$this->requete_champ[] = str_replace('|', ', ', $this->champs_possibles[$match[1]]); |
} elseif (isset($this->champs_possibles[$match[0]])) { |
$this->requete_champ[] = str_replace('|', ', ', $this->champs_possibles[$match[0]]); |
} else { |
$champs_possibles = implode('</li><li>', array_keys($this->champs_possibles)); |
$c = 'Erreur dans votre requête : </br> Le champ "'.$champ_possibles.'" n\'existe pas. '. |
'Les champs disponibles sont : <li>'.$champs_possibles.'</li> et leurs déclinaisons (ex. ".code").'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $c); |
} |
} |
} |
//+------------------------------------------------------------------------------------------------------+ |
public function assemblerLaRequete() { |
$requete = ' SELECT '.$this->formerRequeteChamp(). |
' FROM '.$this->table |
.$this->formerRequeteCondition() |
.$this->formerRequeteLimite(); |
return $requete; |
} |
public function formerRequeteChamp() { |
if (in_array('*', $this->requete_champ)) { |
$champ = ' * '; |
} else { |
$champ = implode(', ', $this->requete_champ); |
} |
return $champ; |
} |
public function formerRequeteCondition() { |
$condition = ''; |
if ($this->requete_condition != null) { |
$condition = ' WHERE '.implode(' AND ', $this->requete_condition); |
} |
return $condition; |
} |
//ajout d'une limite seulement pour les listes (pas plus de 100 resultats retournés pr les requetes |
// suivantes : /noms-vernaculaires et /noms-vernaculaires/#id/relations) |
public function formerRequeteLimite() { |
if (in_array($this->format_reponse , array($this->service.'/id', $this->service.'/id/champs'))) { |
$this->requete_limite = ''; |
} elseif (($depart = $this->limite_requete['depart']) > ($this->total_resultat = $this->recupererTotalResultat())) { |
$this->limite_requete['depart'] = |
(($this->total_resultat - $this->limite_requete['limite']) < 0) ? 0 : ($this->total_resultat - $this->limite_requete['limite']); |
$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite']; |
} else { |
$this->requete_limite = ' LIMIT '.$this->limite_requete['depart'].', '.$this->limite_requete['limite']; |
} |
return $this->requete_limite; |
} |
//on récupère le nombre total de résultats de la requete (ex : le nombre d'id contenu dans la liste /noms-vernaculaires) |
public function recupererTotalResultat() { |
$distinct = ($this->format_reponse == 'noms-vernaculaires/attributions') ? 'id' : 'distinct(id)'; |
$requete = 'SELECT count('.$distinct.') as nombre FROM ' |
.$this->table |
.$this->formerRequeteCondition(); |
$res = $this->getBdd()->recuperer($requete); |
if ($res) { |
$total = $res['nombre']; |
} else { |
$t = 'Fonction recupererTotalResultat() : <br/>Données introuvables dans la base '.$requete; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE, $t); |
} |
return $total; |
} |
//+------------------------------------------------------------------------------------------------------+ |
// determine en fct du service appelé (/noms-vernaculaires | /noms-vernaculaires/#id | /noms-vernaculaires/#id/champ | |
// /noms-vernaculaires/#id/relations) le format du tableau à retourner. |
public function retournerResultatFormate($resultat) { |
$this->recupererTableConfig('correspondance_champs'); |
switch ($this->format_reponse) { |
case 'noms-vernaculaires' : |
$reponse = ($this->retour_format == 'oss') ? $this->formaterEnOss($resultat) : $this->formaterNomsVernaculaires($resultat); break; |
case 'noms-vernaculaires/attributions' : $reponse = $this->formaterNomsVernaculairesAttributions($resultat); break; |
case 'noms-vernaculaires/id' : $reponse = $this->formaterNomsVernaculairesId($resultat); break; |
case 'noms-vernaculaires/id/champ' : $reponse = $this->formaterNomsVernaculairesIdChamp($resultat); break; |
default : break; |
} |
return $reponse; |
} |
public function ajouterJsonEnTeteNV() { |
$table_retour_json['masque'] = $this->recupererMasque(); |
$table_retour_json['depart'] = $this->limite_requete['depart']; |
$table_retour_json['limite'] = $this->limite_requete['limite']; |
$table_retour_json['total'] = $this->total_resultat; |
$url = $this->formulerUrl($this->total_resultat, '/noms-vernaculaires'); |
if (isset($url['precedent']) && $url['precedent'] != '') { |
$table_retour_json['href.precedent'] = $url['precedent']; |
} |
if (isset($url['suivant']) && $url['suivant'] != '') { |
$table_retour_json['href.suivant'] = $url['suivant']; |
} |
return $table_retour_json; |
} |
public function ajouterJsonResultatNV($resultat) { |
foreach ($resultat as $tab) { |
foreach ($tab as $key => $valeur) { |
if ($valeur != '') { |
switch ($key) { |
case 'id' : $num = $valeur; break; |
case 'nom_vernaculaire' : $this->table_retour['nom'] = $valeur; break; |
default : break; |
} |
} |
} |
if ($this->retour_format == 'max') $this->table_retour['href'] = $this->ajouterHref('noms-vernaculaires', $num); |
$resultat_json[$num] = $this->table_retour; |
$this->table_retour = array(); |
} |
return $resultat_json; |
} |
public function formaterNomsVernaculaires($resultat) { |
$table_retour_json['entete'] = $this->ajouterJsonEnTeteNV(); |
$resultat = $this->hierarchiserResultat($resultat); |
$table_retour_json['resultat'] = $this->ajouterJsonResultatNV($resultat); |
return $table_retour_json; |
} |
public function hierarchiserResultat($resultat) { |
//tri recherche floue |
if (isset($this->parametres['masque.nv'])) { |
$resultat = $this->trierRechercheFloue($this->parametres['masque.nv'], $resultat, 'nom_vernaculaire'); |
} |
if (isset($this->parametres['masque'])) { |
$resultat = $this->trierRechercheFloue($this->parametres['masque'], $resultat, 'nom_vernaculaire'); |
} |
return $resultat; |
} |
public function recupererMasque() { |
$tab_masque = array(); |
foreach ($this->parametres as $param=>$valeur) { |
if (strstr($param, 'masque') != false) { |
$tab_masque[] = $param.'='.$valeur; |
} |
} |
$masque = implode('&', $tab_masque); |
return $masque; |
} |
public function formaterEnOss($resultat) { |
$table_nom = array(); |
$oss = ''; |
foreach ($resultat as $tab) { |
if (isset($tab['nom_vernaculaire']) ) { |
if (!in_array($tab['nom_vernaculaire'], $table_nom)) { |
$table_nom[] = $tab['nom_vernaculaire']; |
$oss [] = $tab['nom_vernaculaire']; |
} |
} |
} |
if (isset($this->masque)) $masque = implode('&', $this->masque); |
else $masque = 'Pas de masque'; |
$table_retour_oss = array($masque, $oss); |
return $table_retour_oss; |
} |
public function formaterNomsVernaculairesAttributions($resultat) { |
//on remplie la table $table_retour_json['entete'] |
$table_retour_json['entete']['masque'] = $this->recupererMasque(); |
$table_retour_json['entete']['depart'] = $this->limite_requete['depart']; |
$table_retour_json['entete']['limite'] = $this->limite_requete['limite']; |
$table_retour_json['entete']['total'] = $this->total_resultat; |
$url = $this->formulerUrl($this->total_resultat, '/noms-vernaculaires/attributions'); |
if (isset($url['precedent']) && $url['precedent'] != '') { |
$table_retour_json['entete']['href.precedent'] = $url['precedent']; |
} |
if (isset($url['suivant']) && $url['suivant'] != '') { |
$table_retour_json['entete']['href.suivant'] = $url['suivant']; |
} |
foreach ($resultat as &$tab) { |
$resultat_json[$tab['id']]['id'] = $tab['id']; |
$resultat_json[$tab['id']]['nom_vernaculaire'] = $tab['nom_vernaculaire']; |
$resultat_json[$tab['id']]['code_langue'] = $tab['code_langue']; |
$resultat_json[$tab['id']]['taxon.code'] = 'bdtfx.nt:'.$tab['num_taxon']; |
if ($this->retour_format == 'max') { |
$resultat_json[$tab['id']]['num_taxon'] = $tab['num_taxon']; |
$resultat_json[$tab['id']]['nom_retenu.code'] = $tab['num_taxon']; |
$resultat_json[$tab['id']]['taxon'] = $tab['num_taxon']; |
$this->taxons[] = $tab['num_taxon']; // utilisé pour chercher les noms latins plus bas |
$resultat_json[$tab['id']]['href'] = $this->ajouterHref('noms-vernaculaires', $tab['id']); |
if($this->champs_supp != array()) { |
$resultat_json[$tab['id']] = $this->ajouterChampsOntologieLigneResultat($tab); |
} |
} |
} |
if ($this->retour_format == 'max') { |
// On est obligé de faire un deuxième boucle pour demander tous les taxons présents en une |
// fois et les attribuer aux noms car c'est beaucoup plus rapide |
$noms_sci = $this->recupererNomTaxons(); |
foreach ($resultat_json as $num_nom => &$tab) { |
$tab = $this->ajouterTaxonsAttributionsLigneResultat($tab, $noms_sci); |
if($tab == null) { |
unset($resultat_json[$num_nom]); |
} |
} |
} |
uasort($resultat_json, array($this,'trierLigneTableau')); |
$table_retour_json['resultat'] = $resultat_json; |
return $table_retour_json; |
} |
/** |
* Ajoute les champs d'ontologie supplémentaires si necéssaire |
* en faisant appels aux web services associés |
* @param array $ligne_resultat |
* |
* @return array la ligne modifiée |
*/ |
public function ajouterChampsOntologieLigneResultat($ligne_resultat) { |
$intitule = ''; |
foreach($this->champ_infos as $cle => $champs_supplementaires) { |
if(in_array($cle, $this->champs_supp)) { |
extract($champs_supplementaires); |
$valeur_recherche = ''; |
switch($cle) { |
case 'taxon': |
$valeur_recherche = $ligne_resultat['num_taxon']; |
$intitule = 'taxon.code'; |
break; |
} |
$code_valeur = ''; |
if(trim($valeur_recherche) != '') { |
$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur_recherche, $projet); |
$code_valeur = $this->chercherSignificationCode($url, $nom); |
} |
$ligne_resultat[$intitule] = $code_valeur; |
} |
} |
return $ligne_resultat; |
} |
/** |
* Fonction qui ajoute les attributions à une ligne de résultats |
* |
* @param array $ligne_tableau_resultat |
* @param array $nom_sci |
*/ |
public function ajouterTaxonsAttributionsLigneResultat(&$ligne_tableau_resultat, &$noms_sci) { |
if (isset($noms_sci[$ligne_tableau_resultat['num_taxon']])) { |
$ligne_tableau_resultat['nom_retenu.code'] = $noms_sci[$ligne_tableau_resultat['num_taxon']]['id']; |
$ligne_tableau_resultat['taxon'] = $noms_sci[$ligne_tableau_resultat['num_taxon']]['nom_sci']; |
} else { |
$ligne_tableau_resultat = null; |
} |
return $ligne_tableau_resultat; |
} |
private function trierLigneTableau($a, $b) { |
$retour = 0; |
if ($a[$this->champ_tri] == $b[$this->champ_tri]) { |
$retour = 0; |
} |
if($this->champ_tri == 'code_langue') { |
if ($a[$this->champ_tri] == 'fra' && $b[$this->champ_tri] != 'fra') { |
$retour = ($this->direction_tri == 'asc') ? -1 : 1; |
} else if ($a[$this->champ_tri] != 'fra' && $b[$this->champ_tri] == 'fra') { |
$retour = ($this->direction_tri == 'asc') ? 1 : -1; |
} else { |
$retour = $this->comparerChaineSelonDirectionTri($a[$this->champ_tri], $b[$this->champ_tri]); |
} |
} else { |
$retour = $this->comparerChaineSelonDirectionTri($a[$this->champ_tri], $b[$this->champ_tri]); |
} |
return $retour; |
} |
private function comparerChaineSelonDirectionTri($a, $b) { |
if($this->direction_tri == 'asc') { |
return ($a < $b) ? -1 : 1; |
} else { |
return ($a > $b) ? -1 : 1; |
} |
} |
// formatage de la reponse /id ss la forme |
// id, nom_vernaculaire, attributions |
// langue |
// num_nom (correspond à un taxon bdtfx) |
public function formaterNomsVernaculairesId($resultat) { |
foreach ($resultat as $taxon) { // pour chaque attribution à un taxon bdtfx |
// on crée les variables qui serviront de clés et on les enléves du tableau |
$num_nom = $taxon['id']; // unique pour un trinôme id, langue, taxon |
$langue = $taxon['code_langue']; |
unset($taxon['code_langue']); |
foreach ($this->correspondance_champs as $key => $correspondance) { // ordonne les infos pour affichage |
if (isset($taxon[$key]) && $taxon[$key] != "") { |
$this->afficherDonnees($correspondance, $taxon[$key], $langue, $num_nom); |
} |
} |
foreach ($taxon as $key => $valeur) { // rajoute les champs non prévus dans l'api |
if (!isset($this->correspondance_champs[$key]) && $valeur != "") { |
$this->afficherDonnees($key, $valeur, $langue, $num_nom); |
} |
} |
} |
if ($this->retour_format == 'max') $this->afficherTaxons(); // va chercher les noms de tous les taxons |
unset($this->table_retour['href']); |
return $this->table_retour; |
} |
public function afficherDonnees($champ, $valeur, $langue = '', $num_nom = '') { |
if ($champ == 'id' || $champ == 'nom_vernaculaire') { |
$this->table_retour[$champ] = $valeur; |
} elseif (preg_match('/^(.*)\.code$/', $champ, $match)) { |
switch ($match[1]) { |
case 'taxon' : if ($this->retour_format == 'max') {$this->taxons[$num_nom] = $valeur;} |
$this->afficherPointCode($match[1], $langue, $num_nom, $valeur); break; |
case 'langue' : //$this->afficherPointCode($match[1], 'iso-639-3', 'langues', $valeur); |
break; |
default : break; |
} |
} elseif ($langue != '') { |
$this->table_retour['attributions'][$langue][$num_nom][$champ] = $valeur; |
} else { |
$this->table_retour[$champ] = $valeur; |
} |
} |
public function afficherPointCode($nomChamp, $langue, $num_nom, $valeur) { |
if (isset($this->champ_infos[$nomChamp])) { |
extract($this->champ_infos[$nomChamp]); |
} |
if ($this->retour_format == 'max') { |
$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur, $projet); |
if ($service == 'taxons') { |
$code_valeur = ''; |
$this->table_retour['attributions'][$langue][$num_nom]['nom_retenu.code'] = $code_valeur; |
} else { |
$code_valeur = $this->chercherSignificationCode($url, $nom); |
} |
if ($projet != '') $projet .= '.'; |
$this->table_retour['attributions'][$langue][$num_nom][$nomChamp] = $code_valeur; |
$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.code'] = $projet.$ressource.$valeur; |
$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.href'] = $url; |
} else { |
if ($projet != '') $projet .= '.'; |
$this->table_retour['attributions'][$langue][$num_nom][$nomChamp.'.code'] = $projet.$ressource.$valeur; |
} |
} |
public function chercherSignificationCode($url, $nom) { |
if (isset($this->signification_code[$url])) { |
$valeur = $this->signification_code[$url]; |
} else { |
$res = $this->consulterHref($url); |
$valeur = $res->$nom; |
$this->signification_code[$url] = $valeur; |
} |
return $valeur; |
} |
public function afficherTaxons() { |
$resultat = $this->recupererNomTaxons(); |
foreach ($this->table_retour['attributions'] as $code_langue=>$langue) { |
foreach ($langue as $num_nom=>$taxon) { |
$num_tax = ltrim($taxon['taxon.code'], 'bdtfx.nt:'); |
if (isset($resultat[$num_tax])) { |
$this->table_retour['attributions'][$code_langue][$num_nom]['nom_retenu.code'] = $resultat[$num_tax]['id']; |
$this->table_retour['attributions'][$code_langue][$num_nom]['taxon'] = $resultat[$num_tax]['nom_sci']; |
} |
} |
} |
} |
public function recupererNomTaxons() { |
$taxons = array_unique($this->taxons); |
$url = Config::get('url_service_base').'bdtfx/taxons?navigation.limite=500&ns.structure=au&masque.nt='.implode(',', $taxons); |
$res = $this->consulterHref($url); |
foreach ($res->resultat as $id=>$taxon) { |
$resultat[$taxon->num_taxonomique]['id'] = 'bdtfx.nn:'.$id; |
$resultat[$taxon->num_taxonomique]['nom_sci'] = $taxon->nom_sci_complet; |
} |
return $resultat; |
} |
public function formaterNomsVernaculairesIdChamp($resultat) { |
$this->table_retour['id'] = $this->ressources[0]; |
$champs = explode(' ', $this->ressources[1]); |
if (in_array('attributions', $champs) != false) { |
$this->formaterNomsVernaculairesId($resultat); |
unset($this->table_retour['nom_vernaculaire']); |
} else { |
$champ_attributions = array('num_taxon', 'genre', 'notes'); |
foreach ($resultat as $taxon) { |
foreach ($taxon as $key=>$valeur) { |
if ($key == 'code_langue' && in_array('langue', $champs) != false) { |
$this->table_retour['attributions']['langue'][] = $valeur; |
} elseif (in_array($key, $champ_attributions) != false) { |
$this->afficherPoint($this->correspondance_champs[$key] , $valeur, $taxon['code_langue'], $taxon['id']); |
} elseif (in_array($key, $champs) != false) { |
$this->table_retour[$key] = $valeur; |
} |
} |
} |
} |
return $this->table_retour; |
} |
public function afficherPoint($champ, $valeur, $langue, $num_nom) { |
preg_match('/^(.*)\.code$/', $champ, $match); |
$champ = $match[1]; |
if (isset($this->champ_infos[$champ])) { |
extract($this->champ_infos[$champ]); |
$url = $this->ajouterHrefAutreProjet($service, $ressource, $valeur, $projet); |
$projet .= '.'; |
} |
$champs = explode(' ', $this->ressources[1]); |
if (in_array($champ.'.*', $champs) !== false && isset($projet)) { |
$this->table_retour['attributions'][$langue][$num_nom][$champ.'.code'] = $projet.$ressource.$valeur; |
$this->table_retour['attributions'][$langue][$num_nom][$champ.'.href'] = $url; |
} |
if (in_array($champ.'.code', $champs) !== false && isset($projet)) { |
$this->table_retour['attributions'][$langue][$num_nom][$champ.'.code'] = $projet.$ressource.$valeur; |
} |
if (in_array($champ.'.href', $champs) !== false && isset($projet)) { |
$this->table_retour['attributions'][$langue][$num_nom][$champ.'.href'] = $url; |
} |
if (in_array($champ, $champs) !== false) { |
if (isset($url)) { |
$this->table_retour['attributions'][$langue][$num_nom][$champ] = $this->chercherSignificationCode($url, $nom); |
} else { |
$this->table_retour['attributions'][$langue][$champ] = $valeur; |
} |
} |
} |
public function afficherLangue($nomChamp, $projet, $service, $valeur, $ressource = '', $nom = 'nom') { |
if ($this->retour_format == 'max') { |
$this->table_retour['attributions'][$nomChamp] = $nom; |
$this->table_retour['attributions'][$nomChamp.'.code'] = $projet.$ressource.$valeur; |
$this->table_retour['attributions'][$nomChamp.'.href'] = $url; |
} else { |
$this->table_retour['attributions'][$nomChamp.'.code'] = $projet.$ressource.$valeur; |
} |
} |
} |
?> |
/tags/v0.1-20130829/services/modules/0.1/baseflor/GraphiquesTaxonsSup.php |
---|
New file |
0,0 → 1,146 |
<?php |
/** |
* Classe GraphiquesTaxonsSup.php transforme les données écologiques de la table baseflor_rang_sup_ecologie |
* en graphique svg |
* graphiques/#typegraphique/#bdnt.nn:#num_nomen --> renvoie un graphique avec les données connues |
* |
* |
* @package eflore-projets |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org> |
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt> |
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt> |
* @version 1.0 |
* @copyright 1999-2011 Tela Botanica (accueil@tela-botanica.org) |
*/ |
class GraphiquesTaxonsSup extends CommunGraphiques{ |
public function definirTable($version){ |
$this->table = Config::get('bdd_table_rang_sup')."_v".$version; |
} |
//+---- ressources ----+ |
public function traiterReferentieletNum(){ |
if (!empty($this->ressources[1])) { |
if(preg_match('/^(.+)\.nn:([0-9]+)$/', $this->ressources[1], $retour) == 1){ |
switch ($retour[1]) { |
case 'bdtfx' : // pour le moment un seul referentiel disponible |
$this->requete_condition[]= "num_nomen = ".$retour[2]." AND bdnt = 'bdtfx' "; |
break; |
default : |
$e = "Le référentiel {$retour[1]} n'existe pas."; |
throw new Exception( $e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
break; |
} |
}else { |
$e = "Erreur dans l'url de votre requête :". |
" précisez le référentiel et le numéro nomenclatural sous la forme {bdnt}.nn:{nn}."; |
throw new Exception( $e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
} |
} else { |
throw new Exception( "Erreur dans l'url de votre requête :". |
" précisez le référentiel et le numéro nomenclatural sous la forme {bdnt}.nn:{nn}.", |
RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
} |
} |
public function traiterTypeGraphique(){ |
if (!empty($this->ressources[0])) { |
switch ($this->ressources[0]) { |
case 'climat' : |
$this->requete_champs = ' ve_lumiere_min, ve_lumiere_max, ve_temperature_min,'. |
' ve_temperature_max, ve_continentalite_min,'. |
' ve_continentalite_max, ve_humidite_atmos_min,'. |
' ve_humidite_atmos_max' ; |
$this->nomGraphique= 'climat_min_max'; |
break; |
case 'sol' : |
$this->requete_champs = ' ve_humidite_edaph_min , ve_humidite_edaph_max,'. |
' ve_reaction_sol_min, ve_reaction_sol_max, '. |
' ve_nutriments_sol_min, ve_nutriments_sol_max,'. |
' ve_salinite_min, ve_salinite_max,'. |
' ve_texture_sol_min, ve_texture_sol_max,'. |
've_mat_org_sol_min,ve_mat_org_sol_max ' ; |
$this->nomGraphique = 'sol_min_max'; |
break; |
default : |
$e = "Erreur dans l'url de votre requête :". |
"</br> précisez le graphique -> \"sol\" ou \"climat\"."; |
throw new Exception($e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
break; |
} |
}else { |
throw new Exception("Erreur dans l'url de votre requête :". |
"</br> precisez le graphique -> \"sol\" ou \"climat\".", RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
} |
} |
//+-------------------------- formatage du résultat -------------------------------------------+ |
public function changerValeursSVG(){ |
$this->ajouterValeursIntermediaires(); |
$Dompath = new DOMXPath($this->dom); |
foreach ($this->valeurs_en_pourcentage as $cle => $val){ |
$val = preg_replace('/,/','.', $val); |
$grad_id = array_search($val,$this->graduations_id); |
$champs = preg_replace('/_min|_max|_[0-9]/','', $cle); |
// dans le cas de mauvaises données, pour ne pas que tout le graphique |
$case = $Dompath->query("//*[@id='".$grad_id."_".$champs."']")->item(0); |
if($case != null) { |
$case->setAttribute('fill','#EA6624'); |
$case->setAttribute('stroke','#EA6624'); |
$this->ajouterInfoAuSurvol($champs,$case); |
} |
$changement = true; |
} |
$this->ajusterFormatSVG(); |
} |
public function ajouterValeursIntermediaires(){ |
$champs_ecolo = array_keys($this->champs_ontologiques); |
foreach ($champs_ecolo as $chps ){ |
$min = !empty($this->valeurs_en_pourcentage[$chps.'_min']) ? $this->valeurs_en_pourcentage[$chps.'_min'] : -1; |
$max = !empty($this->valeurs_en_pourcentage[$chps.'_max']) ? $this->valeurs_en_pourcentage[$chps.'_max'] : -1; |
if ($min < ($max-0.1) ){ |
$i = $min + 0.1; |
$num = 1; |
for ($i ; $i < $max; $i += 0.1) { |
$this->valeurs_en_pourcentage[$chps.'_'.$num] = $i; |
$num++; |
} |
} |
} |
} |
public function ajouterInfoAuSurvol($champs, $case){ |
$min = $this->valeurs_champs[$champs."_min"]; |
$max = $this->valeurs_champs[$champs."_max"]; |
if ($min != $max){ |
$valeurMin = $this->recupererOntologies($min, $champs ); |
$valeurMax = $this->recupererOntologies($max, $champs ); |
$valeurMin = $this->traiterIntermediaires($valeurMin->nom, $champs, $champs.'_min'); |
$valeurMax = $this->traiterIntermediaires($valeurMax->nom, $champs, $champs.'_max'); |
$case->setAttribute('title',"de $min: $valeurMin à $max: $valeurMax " ); |
} else { |
$valeurMin = $this->recupererOntologies($min, $champs ); |
$valeurMin = $this->traiterIntermediaires($valeurMin->nom, $champs, $champs.'_min'); |
$case->setAttribute('title',"$min: $valeurMin" ); |
} |
} |
} |
?> |
/tags/v0.1-20130829/services/modules/0.1/baseflor/InformationsTaxonsSup.php |
---|
New file |
0,0 → 1,268 |
<?php |
/** |
* Classe InformationsTaxonsSup.php permet de faire des requetes pour les rangs superieurs de baseflor |
* du référentiel BDTFX et avec un numéro nomenclatural ( différent de 0 ). |
* fin d'url possibles : |
* |
* /informations/#bdnt.nn:#num_nomen?champs=ecologie --> retourne champs ecologiques pour un BDNT et un num_nomen |
* |
* |
* Encodage en entrée : utf8 |
* Encodage en sortie : utf8 |
* @package eflore-projets |
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org> |
* @author Delphine CAUQUIL <delphine@tela-botanica.org> |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt> |
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt> |
* @version 1.0 |
* @copyright 1999-2011 Tela Botanica (accueil@tela-botanica.org) |
*/ |
class InformationsTaxonsSup extends Commun{ |
protected $table = ""; |
private $champs_ontologiques = array(); |
private $format_reponse = 'informations'; |
protected $serviceNom = 'informations'; |
private $retour_format = 'max'; |
private $Bdd; |
private $requete_condition = ""; |
private $champs_recherches = '*'; |
public function consulter($ressources, $parametres) { |
$this->ressources = $ressources; |
$this->parametres = $parametres; |
$this->traiterParametres(); |
$this->definirTables(); |
$this->traiterRessources(); |
$resultats = ''; |
foreach ($this->table_version as $version) { |
$this->table = $version; |
$requete = $this->assemblerLaRequete(); |
$resultat = $this->Bdd->recupererTous($requete); |
$versionResultat = $this->analyserResultat($resultat); |
if (count($this->table_version) > 1) { |
$resultats[$version] = $versionResultat; |
} else { |
$resultats = $versionResultat; |
} |
} |
return $resultats; |
} |
public function analyserResultat($resultat) { |
$versionResultat = null; |
if ($resultat == '') { |
$message = 'La requête SQL formée comporte une erreur!'; |
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE; |
throw new Exception($message, $code); |
} elseif ($resultat) { |
$versionResultat = $this->retournerResultatFormate($resultat); |
} |
return $versionResultat; |
} |
public function __construct(Conteneur $Conteneur) { |
$this->Bdd = $Conteneur->getBdd(); |
} |
//+--------------------------traitement ressources ou paramètres -------------------------------------------+ |
public function traiterRessources() { |
if(preg_match('/^(.+)\.nn:([0-9]+)$/', $this->ressources[0], $retour)==1){ |
switch ($retour[1]) { |
case 'bdtfx' : |
$this->requete_condition[] = "num_nomen = ".$retour[2]." AND bdnt = 'bdtfx' "; |
break; |
default : |
$e = 'Erreur dans l\'url de votre requête : </br> Le référentiel " ' |
.$retour[1].' " n\'existe pas.'; |
throw new Exception($e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
break; |
} |
} |
} |
//+---- paramètres ----+ |
public function traiterParametres() { |
if (isset($this->parametres) && !empty($this->parametres) ) { |
foreach ($this->parametres as $param => $valeur) { |
switch ($param) { |
case 'categorie' : |
if ($valeur == "ecologie"){ |
$this->champs_recherches = ' num_nomen, bdnt, ve_lumiere_min , ve_lumiere_max,' |
.' ve_temperature_min, ve_temperature_max, ve_continentalite_min,' |
.' ve_continentalite_max, ve_humidite_atmos_min, ve_humidite_atmos_max,' |
.' ve_humidite_edaph_min, ve_humidite_edaph_max, ve_reaction_sol_min,' |
.' ve_reaction_sol_max, ve_nutriments_sol_min, ve_nutriments_sol_max,' |
.' ve_salinite_min, ve_salinite_max, ve_texture_sol_min,ve_texture_sol_max,' |
.' ve_mat_org_sol_min, ve_mat_org_sol_max '; |
} else { |
$e = "Valeur de paramètre inconnue pour 'categorie'. Ce paramètre n'est pas autorisé pour informations/#id"; |
throw new Exception($e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
} |
break; |
case 'retour.format' : |
if ($valeur == 'min' || $valeur == 'max') { |
$this->retour_format = $valeur; |
break; |
} else { |
$e = "Valeur de paramètre inconnue pour 'retour.format'. Ce paramètre n'est pas autorisé pour informations/#id"; |
throw new Exception($e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
} |
case 'version.projet' : |
$this->traiterVersion($valeur); |
break; |
default : |
$e = 'Erreur dans les parametres de votre requête : </br> Le paramètre " ' |
.$param.' " n\'existe pas.'; |
throw new Exception($e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); break; |
} |
} |
} |
} |
//+++------------------------------traitement des versions----------------------------------------++ |
public function traiterVersion($valeur) { |
if (preg_match('/^[0-9]+(?:[._][0-9]+)*$/', $valeur) || $valeur == '*' || $valeur == '+') { |
$this->version_projet = $valeur; |
} else { |
$e = "Erreur : La version est inconnue."; |
throw new Exception($e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
} |
if ($this->version_projet == '*' && $this->ressources == array()) { |
$message = "L'affichage de plusieurs versions ne fonctionne que pour les ressources de type /ressources/#id"; |
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE; |
throw new Exception($message, $code); |
} |
} |
public function definirTables() { |
$table_num_version = $this->recupererVersionDisponible(); |
$prefixe_table = config::get('bdd_table_rang_sup'); |
if ( in_array($this->version_projet,$table_num_version) ) { |
$this->table_version[] = $prefixe_table.'_v'.$this->version_projet; |
} elseif ($this->version_projet == '+') { |
$derniere_version = $table_num_version[count($table_num_version) - 1]; |
$this->table_version[] = $prefixe_table.'_v'.str_replace('.', '_', $derniere_version); |
} elseif ($this->version_projet == '*') { |
foreach ($table_num_version as $num_version) { |
$this->table_version[] = $prefixe_table.'_v'.str_replace('.', '_', $num_version); |
} |
} else { |
$e = "Erreur : La version est inconnue."; |
throw new Exception($e, RestServeur::HTTP_CODE_MAUVAISE_REQUETE); |
} |
} |
//+--------------------------formatages de resultats -------------------------------------------+ |
public function retournerResultatFormate($resultat) { |
$this->resultat_json = $resultat[0]; |
if ($this->retour_format == 'max') { |
$graphique_presence = $this->traiterEcologie() ; |
if ($graphique_presence) { |
$this->ajouterLiensGraphique($graphique_presence); |
} |
} |
return $this->resultat_json ; |
} |
public function traiterEcologie() { |
$donnees_presence = false; |
$this->champs_ontologiques = $this->recupererTableauConfig('champs_ontologiques'); |
foreach ($this->champs_ontologiques as $cle => $valeur){ |
/* Les deux tests commentés ci-dessous étaient présents dans eflore-test (uniquement) jusqu'à juin 2013. |
La valeur 0 pose question. |
cf baseflor_v2012_12_31 |
cf services/modules/0.1/baseflor/CommunGraphiques.php traiterValeursEcologiques() */ |
if ($this->resultat_json[$cle.'_min'] != "") { // && $this->resultat_json[$cle.'_min'] != 0) { |
$donnees_presence[$this->getNomGraphique($valeur)] = true; |
$tab_ontologie = $this->recupererOntologies($this->resultat_json[$cle.'_min'], $cle.'_min'); |
unset($this->resultat_json[$cle.'_min']); |
} |
if ($this->resultat_json[$cle.'_max'] != "") { // && $this->resultat_json[$cle.'_max'] != 0) { |
$this->recupererOntologies($this->resultat_json[$cle.'_max'], $cle.'_max'); |
unset($this->resultat_json[$cle.'_max']); |
} |
} |
return $donnees_presence; |
} |
//donne le nom du graphique correspondant à un champ écologique |
public function getNomGraphique($code_ecolo) { |
$graphique = null; |
if (in_array($code_ecolo, explode(',',Config::get('Paramètres.climat')))) { |
$graphique = 'climat'; |
} elseif (in_array($code_ecolo, explode(',', Config::get('Paramètres.sol')) )) { |
$graphique = 'sol'; |
} |
return $graphique; |
} |
public function ajouterLiensGraphique($graphique_presence) { |
if ($graphique_presence['climat']) { |
$this->resultat_json['graphique_climat']['libelle'] = 'climat'; |
$this->resultat_json['graphique_climat']['href'] = $this->ajouterHref('graphiques/climat', |
strtolower($this->resultat_json['bdnt']).'.nn:'.$this->resultat_json['num_nomen']); |
} |
if ($graphique_presence['sol']) { |
$this->resultat_json['graphique_sol']['libelle'] = 'sol'; |
$this->resultat_json['graphique_sol']['href'] = $this->ajouterHref('graphiques/sol', |
strtolower($this->resultat_json['bdnt']).'.nn:'.$this->resultat_json['num_nomen']); |
} |
} |
//+--------------------------traitement ontologies -------------------------------------------+ |
public function recupererOntologies($valeur, $champs){ |
$chps_sans = preg_replace("/_min|_max/", '', $champs); |
$url = Config::get('url_service_base').Config::get('nom_projet'). |
'/ontologies/'.$this->champs_ontologiques[$chps_sans].':'.urlencode(urlencode($valeur)); |
try { |
$val = $this->getBdd()->recuperer(sprintf( |
"SELECT a.nom FROM baseflor_ontologies a LEFT JOIN baseflor_ontologies b ON a.id = b.id LEFT JOIN baseflor_ontologies c ON b.classe_id = c.id WHERE". |
" b.code = BINARY '%s' AND c.code = BINARY '%s' LIMIT 0, 100", |
$valeur, |
$this->champs_ontologiques[$chps_sans]), |
Bdd::MODE_OBJET); |
$this->resultat_json[$champs.'.libelle'] = $val->nom; |
$this->resultat_json[$champs.'.code'] = $valeur; |
$this->resultat_json[$champs.'.href'] = $url; |
} catch (Exception $e) { |
$this->resultat_json[$champs.'.libelle'] = ''; |
$this->resultat_json[$champs.'.code'] = ''; |
$this->resultat_json[$champs.'.href'] = ''; |
} |
} |
//+--------------------------FONCTIONS D'ASSEMBLAGE DE LA REQUETE-------------------------------------------+ |
public function assemblerLaRequete() { |
$requete = ' SELECT '.$this->champs_recherches.' FROM '.$this->table.' ' |
.$this->retournerRequeteCondition(); |
return $requete; |
} |
public function retournerRequeteCondition() { |
$condition = ''; |
if (empty($this->requete_condition) == false) { |
$condition = ' WHERE '.implode(' AND ', $this->requete_condition); |
} |
return $condition; |
} |
} |
?> |