/branches/refact/initialiserBdd.sh |
---|
New file |
0,0 → 1,66 |
#!/bin/bash |
############################################################################################################## |
# But : Script permettant d'initialiser en une seule commande l'ensemble de la base de données eFlore. |
# Auteur : Jean-Pascal Milcent <jpm@tela-botanica.org> (translate bat file to shell script) |
# License : GPL v3 |
# Création : 07 decembre 2011 |
# Version: 0.1 |
# 2011-12-07 - Création |
# $Id$ |
############################################################################################################## |
# Constante |
APPDIR_ABSOLU=`pwd`; |
# |
CHEMIN_PHP="/opt/lampp/bin" |
CHEMIN_TBF_CLI="$APPDIR_ABSOLU/scripts" |
MEMORY_LIMIT="3500M" |
echo -e "\033[31m`tput blink`ATTENTION :`tput sgr0` Nécessite la création préalable de la base de données \033[31mtb_eflore\033[00m" |
echo "Nettoyage et chargement en cours..."; |
echo "BASEFLOR :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php baseflor -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php baseflor -a chargerTous |
echo "BIBLIO_BOTA :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php biblio_bota -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php biblio_bota -a chargerTous |
echo "BDNT :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php bdnt -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php bdnt -a chargerTous |
echo "BDTFX :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php bdtfx -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php bdtfx -a chargerTous |
echo "CHORODEP :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php chorodep -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php chorodep -a chargerTous |
echo "COSTE :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php coste -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php coste -a chargerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php coste -a chargerTxt |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php coste -a chargerIndex |
echo "EFLORE :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php eflore -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php eflore -a chargerTous |
echo "INSEE-D :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php insee_d -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php insee_d -a chargerTous |
echo "ISO-3166-1 :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php iso_3166_1 -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php iso_3166_1 -a chargerTous |
echo "ISO-639-1 :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php iso_639_1 -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php iso_639_1 -a chargerTous |
echo "NVJFL :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php nvjfl -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php nvjfl -a chargerTous |
echo "PHOTOFLORA :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php photoflora -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php photoflora -a chargerTous |
echo "CEL :"; |
echo -e "\033[31m`tput blink`ATTENTION :`tput sgr0` Nécessite la création préalable de la base de données \033[31mtb_cel\033[00m" |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php cel -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php cel -a chargerTous |
echo "TAPIRLINK :"; |
echo -e "\033[31m`tput blink`ATTENTION :`tput sgr0` Nécessite la création préalable de la base de données \033[31mtb_hit_indexation\033[00m" |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php tapirlink -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php tapirlink -a chargerTous |
Property changes: |
Added: svn:eol-style |
+native |
\ No newline at end of property |
Added: svn:executable |
+* |
\ No newline at end of property |
/branches/refact/livraison.sh |
---|
New file |
0,0 → 1,21 |
#!/bin/bash |
############################################################################################################## |
# But : Script permettant d'initialiser en une seule commande l'ensemble de la base de données eFlore. |
# Auteur : Jean-Pascal Milcent <jpm@tela-botanica.org> (translate bat file to shell script) |
# License : GPL v3 |
# Création : 07 decembre 2011 |
# Version: 0.1 |
# 2011-12-07 - Création |
# $Id$ |
############################################################################################################## |
# ATTENTION NE PAS UTILISER !!! |
# compresser les services en excluant les fichiers svn et les fichiers de config et framework |
#tar cvzf services.tar.gz services/ --exclude=".svn" --exclude="*.ini" --exclude="framework.php" --exclude="*.sh" |
# envoyer sur tela |
#scp services.tar.gz root@tela-botanica.org:/home/telabotap/www/eflore-test/. |
# se connecter sur tela botanica en ssh et effectuer le déploiement |
#ssh root@tela-botanica.org "cd /home/telabotap/www/eflore-test/; cd services; tar cvzf ../backup/services.tar.gz .; cd ../; rm -Rf services; tar xvzf services.tar.gz; cd services; cp ../configurations/services/* . -R; chown #telabotap:users /home/telabotap/www/eflore-test/services -R; chmod 755 /home/telabotap/www/eflore-test/services -R; exit"; |
#echo "Done !" |
Property changes: |
Added: svn:eol-style |
+native |
\ No newline at end of property |
Added: svn:executable |
+* |
\ No newline at end of property |
/branches/refact/chargerDonnees.sh |
---|
New file |
0,0 → 1,50 |
#!/bin/bash |
############################################################################################################## |
# But : téléchargement automatique en local des données des projets depuis le serveur de Tela Botanica par ftp |
# Auteur : Jean-Pascal Milcent <jpm@tela-botanica.org> (translate bat file to shell script) |
# License : GPL v3 |
# Création : 07 decembre 2011 |
# Version: 0.1 |
# 2011-12-07 - Création |
# $Id$ |
############################################################################################################## |
# Constante |
NBREPARAM=$# |
APPDIR_ABSOLU=`pwd`; |
DOSSIER_LOCAL="$APPDIR_ABSOLU/donnees/" |
DOSSIER_DISTANT="/www/eflore/donnees/" |
# Aide |
E_OPTERR=65 |
if [ "$1" = '--help' ] |
then # Le script a besoin d'au moins un argument sur la ligne de commande |
echo "Usage $0 -[parameters -u, -p ]" |
echo "Paramétres : " |
echo " -h: indiquer l'hote ftp" |
echo " -u: indiquer le nom de l'utilisateur ftp" |
echo " -p: indiquer le mot de passe de l'utilisateur ftp" |
exit $E_OPTERR |
fi |
# Récupération des paramètres et des options de la ligne de commande |
TEMP=`getopt -o u:p:h: -l help: -- "$@"` |
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi |
eval set -- "$TEMP" |
while [ ! -z "$1" ] ; do |
#echo $1" # "$2 |
case "$1" in |
-h) HOST=$2;; |
-u) FTP_USER=$2;; |
-p) FTP_PASSWD=$2;; |
--) shift ; break ;; |
*) echo "Internal error!" ; exit 1 ;; |
esac |
shift 2 |
done |
# Transfert sur le serveur par FTP |
if [ $NBREPARAM -eq 0 ]; then |
echo "Pas de transfert sur le serveur. Utiliser --help pour voir les options de transfert." |
else |
echo "Téléchargement en cours :"; |
lftp ftp://$FTP_USER:$FTP_PASSWD@$HOST -e "set ftp:passive off; mirror -e --no-symlinks -x '.*cel\/images\/.*' -x '.*osm\/.*' -x '.*plantscan\/.*' -x '.*coste\/cles\/.*' -x '.*coste\/descriptions\/.*' -x '.*coste\/images\/.*' -x '.*coste\/ressources\/.*' $DOSSIER_DISTANT $DOSSIER_LOCAL ; quit" |
fi; |
Property changes: |
Added: svn:eol-style |
+native |
\ No newline at end of property |
Added: svn:executable |
+* |
\ No newline at end of property |
/branches/refact/services/modules/0.1/nvjfl/NomsVernaculaires.php |
---|
New file |
0,0 → 1,683 |
<?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'), |
'conseil_emploi' => array('service' => 'ontologies', 'ressource' => 'numStatut:', 'projet' => 'nvjfl', 'nom' => 'nom'), |
'genre' => array('service' => 'ontologies', 'ressource' => 'genreNombre:', 'projet' => 'nvjfl', 'nom' => 'nom')); |
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['num_nom_vernaculaire']]['id'] = $tab['id']; |
$resultat_json[$tab['num_nom_vernaculaire']]['nom_vernaculaire'] = $tab['nom_vernaculaire']; |
$resultat_json[$tab['num_nom_vernaculaire']]['code_langue'] = $tab['code_langue']; |
$resultat_json[$tab['num_nom_vernaculaire']]['taxon.code'] = 'bdtfx.nt:'.$tab['num_taxon']; |
if ($this->retour_format == 'max') { |
$resultat_json[$tab['num_nom_vernaculaire']]['num_taxon'] = $tab['num_taxon']; |
$resultat_json[$tab['num_nom_vernaculaire']]['nom_retenu.code'] = $tab['num_taxon']; |
$resultat_json[$tab['num_nom_vernaculaire']]['taxon'] = $tab['num_taxon']; |
$this->taxons[] = $tab['num_taxon']; // utilisé pour chercher les noms latins plus bas |
$resultat_json[$tab['num_nom_vernaculaire']]['href'] = $this->ajouterHref('noms-vernaculaires', $tab['id']); |
if($this->champs_supp != array()) { |
$resultat_json[$tab['num_nom_vernaculaire']] = $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; |
case 'genre': |
$valeur_recherche = $ligne_resultat['num_genre']; |
$intitule = 'genre'; |
break; |
case 'conseil_emploi': |
$valeur_recherche = $ligne_resultat['num_statut']; |
$intitule = 'conseil_emploi'; |
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['num_nom_vernaculaire']; // unique pour un trinôme id, langue, taxon |
unset($taxon['num_nom_vernaculaire']); |
$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->chargerBiblio($num_nom, $langue); |
} |
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; |
case 'genre' : $this->afficherPointCode($match[1], $langue, $num_nom, $valeur); break; |
case 'conseil_emploi' : $this->afficherPointCode($match[1], $langue, $num_nom, $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', '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; |
} |
} |
public function chargerBiblio($num_nom, $langue) { |
list($table, $version) = explode('_v',$this->table); |
$requete = "SELECT b.*, lb.notes FROM nvjfl_lien_biblio_v$version lb, nvjfl_biblio_v$version b ". |
"WHERE b.num_ref = lb.num_ref AND lb.num_nom = '$num_nom' ;"; |
$resultat = $this->getBdd()->recupererTous($requete); |
if ($resultat == '') { //cas ou la requete comporte des erreurs |
$r = 'La requête SQL formée comporte une erreur !!'; |
$this->renvoyerErreur(RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE, $r); |
Debug::printr($requete); |
} elseif ($resultat) { |
foreach ($resultat as $res) { |
foreach ($res as $cle => $valeur) { |
if ($valeur !== "") { |
$this->table_retour['attributions'][$langue][$num_nom]['biblio.'.$cle] = $valeur; |
} |
} |
} |
} |
} |
} |
?> |
/branches/refact/services/modules/0.1/lion1906/NomCommune.php |
---|
New file |
0,0 → 1,143 |
<?php |
// declare(encoding='UTF-8'); |
/** |
* Classe permettant d'obtenir le nom et le code INSEE des communes les plus proches d'un point (latitude et longitude). |
* La latitude et longitude doivent être exprimée par un nombre décimal. |
* Ce service fonctionne uniquement sur les communes de France métropolitaine (Corse comprise) présentent |
* dans les données Lion1906 téléchargeable à cette adrese : http://www.lion1906.com/Pages/francais/utile/telechargements.html. |
* Source des données : Lion1906.com http://www.lion1906.com |
* Paramètres du service : |
* - lat : latitude |
* - lon : longitude |
* Exemple : |
* http://localhost/lion1906/services/0.1/nom-commune?lat=44.71546&lon=3.84216 |
* |
* @category php 5.2 |
* @package lion1906 |
* @author Mohcen BENMOUNAH <mohcen@tela-botanica.org> |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2010, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
class NomCommune { |
const PATTERN_LAT = '/^[0-9]+(?:[.][0-9]+|)$/'; |
const PATTERN_LON = '/^[-]?[0-9]+(?:[.][0-9]+|)$/'; |
const LAT_MAX = 51.071667; |
const LAT_MIN = 41.316667; |
const LON_MAX = 9.513333; |
const LON_MIN = -5.140278; |
const NBRE_COMMUNE_PAR_DEFAUT = 10; |
const NBRE_COMMUNE_MAX = 100; |
const MIME_JSON = 'application/json'; |
private $parametres = array(); |
private $ressources = array(); |
private $bdd = null; |
public function __construct(Bdd $bdd) { |
$this->bdd = $bdd; |
} |
public function consulter($ressources, $parametres) { |
$this->parametres = $parametres; |
$this->ressources = $ressources; |
$this->definirParametresParDefaut(); |
$this->verifierParametres(); |
$nomINSEEs = $this->trouverCommunesProches(); |
$corps = $this->formaterResultats($nomINSEEs); |
$resultat = new ResultatService(); |
$resultat->mime = self::MIME_JSON; |
$resultat->corps = $corps; |
return $resultat; |
} |
private function definirParametresParDefaut() { |
if (array_key_exists('nbre', $this->parametres) === false) { |
$this->parametres['nbre'] = self::NBRE_COMMUNE_PAR_DEFAUT; |
} |
} |
private function verifierParametres() { |
extract($this->parametres); |
$messages = array(); |
if (! array_key_exists('lat', $this->parametres)) { |
$messages[] = "Vous devez indiquer une latitude en degré décimal à l'aide du paramètres d'url : lat"; |
} else if (!preg_match(self::PATTERN_LAT, $lat)) { |
$messages[] = "La valeur de latitude doit être un nombre décimal positif dont le séparateur décimal est un point. Ex. : 44 ou 43.03"; |
} else if ($lat > self::LAT_MAX) { |
$messages[] = "La valeur de latitude indiquée est supérieure à {self::LAT_MAX} qui est le point le plus au Nord de la France métropolitaine."; |
} else if ($lat < self::LAT_MIN) { |
$messages[] = "La valeur de latitude indiquée est infèrieure à {self::LAT_MIN} qui est le point le plus au Sud de la France métropolitaine."; |
} |
if (! array_key_exists('lon', $this->parametres)) { |
$messages[] = "Vous devez indiquer une longitude en degré décimal à l'aide du paramètres d'url : lon"; |
} else if (!preg_match(self::PATTERN_LON, $lon)) { |
$messages[] = "La valeur de longitude doit être un nombre décimal dont le séparateur décimal est un point. Ex. : -4.03 ou 3.256"; |
} else if ($lon > self::LON_MAX) { |
$messages[] = "La valeur de longitude indiquée est supérieure à {self::LON_MAX} qui est le point le plus à l'Est de la France métropolitaine."; |
} else if ($lon < self::LON_MIN) { |
$messages[] = "La valeur de longitude indiquée est infèrieure à {self::LON_MIN} qui est le point le plus à l'Ouest de la France métropolitaine."; |
} |
if (array_key_exists('nbre', $this->parametres)) { |
if (!preg_match('/^[0-9]+$/', $nbre)) { |
$messages[] = "Le nombre de commune le plus proche à retourner doit être un entier positif. Ex. : 10"; |
} else if ($nbre > self::NBRE_COMMUNE_MAX) { |
$messages[] = "Le nombre de commune le plus proche à retourner doit être un entier positif inférieur à 100. Ex. : 10"; |
} |
} |
if (count($messages) != 0) { |
$message = implode('<br />', $messages); |
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE; |
throw new Exception($message, $code); |
} |
} |
private function formaterResultats($nomINSEEs) { |
$communes_trouvees = null; |
if (isset($nomINSEEs) && !empty($nomINSEEs)) { |
foreach ($nomINSEEs as $nomINSEE) { |
$communes_trouvees[] = array('nom' => $nomINSEE['nom'], 'codeINSEE' => $nomINSEE['insee']); |
} |
if (!is_null($communes_trouvees)) { |
if ($this->parametres['nbre'] == 1 && count($communes_trouvees) == 1) { |
$communes_trouvees = $communes_trouvees[0]; |
} |
} else { |
$message = "Le service '".get_class($this)."' n'a trouvé aucune commune correspondant aux coordonnées : {$parametres['lat']}, {$parametres['lon']}."; |
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE; |
throw new Exception($message, $code); |
} |
} else { |
$message = "Le service '".get_class($this)."' n'a trouvé aucune commune dont le centroïde correspond aux coordonnées : {$parametres['lat']}, {$parametres['lon']}."; |
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE; |
throw new Exception($message, $code); |
} |
return $communes_trouvees; |
} |
/** |
* requête qui récupère les 20 communes les plus proches du point recherché |
* La distance(AB = \sqrt{(x_B-x_A)^2 + (y_B-y_A)^2}) est calculée sans la racine |
* (calcul en plus qui change pas le résultat). |
*/ |
private function trouverCommunesProches() { |
$lat = $this->parametres['lat']; |
$lon = $this->parametres['lon']; |
$requete = 'SELECT '. |
" (({$lat} - X(centroide)) * ({$lat} - X(centroide)) + ({$lon} - Y(centroide)) * ({$lon} - Y(centroide))) AS distance, ". |
"insee, nom ". |
'FROM lion1906_communes_v2008 '. |
'ORDER BY distance '. |
"LIMIT {$this->parametres['nbre']} "; |
$resultat = $this->bdd->recupererTous($requete); |
return $resultat; |
} |
} |
?> |
/branches/refact/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; |
} |
} |
} |
?> |
/branches/refact/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; |
} |
} |
?> |
/branches/refact/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; |
} |
} |
} |
?> |