Subversion Repositories eFlore/Applications.moissonnage

Compare Revisions

No changes between revisions

Ignore whitespace Rev 25 → Rev 26

/trunk/services/bibliotheque/Maillage.php
New file
0,0 → 1,229
<?php
 
 
class Maillage {
private $bbox;
private $zoom;
private $indexLongitude;
private $indexLatitude;
private $mailles;
private $bdd = null;
public function __construct($bbox, $zoom) {
$this->bbox = $bbox;
$this->zoom = $zoom;
$this->indexLongitude = array();
$this->indexLatitude = array();
$this->mailles = array();
}
public function __destruct() {
while (count($this->indexLatitude) > 0) {
array_pop($this->indexLatitude);
}
while (count($this->indexLongitude) > 0) {
array_pop($this->indexLongitude);
}
while (count($this->mailles) > 0) {
array_pop($this->mailles);
}
unset($this);
}
public function genererMaillesVides() {
$this->recupererIndexMaillesDansBbox();
foreach ($this->indexLatitude as $indexLat => $intervalleLat) {
$ligne = array();
foreach ($this->indexLongitude as $indexLng => $intervalleLng) {
$ligne[] = new Maille($intervalleLat[0], $intervalleLng[0], $intervalleLat[1],
$intervalleLng[1], $indexLat, $indexLng);
}
$this->mailles[] = $ligne;
}
}
private function recupererIndexMaillesDansBbox() {
// recuperer toutes les mailles qui couvrent l'espace a requeter
$conditionsLongitude = "";
if ($this->bbox['ouest'] > $this->bbox['est']) {
$conditionsLongitude = "NOT(debut>=".$this->bbox['ouest']." AND fin<=".$this->bbox['est'].")";
} else {
$conditionsLongitude = "fin>=".$this->bbox['ouest']." AND debut <=".$this->bbox['est'];
}
$requete =
"SELECT axe, position, debut, fin FROM mailles_index WHERE zoom=".$this->zoom." ".
"AND (".
"(axe='lat' AND fin>=".$this->bbox['sud']." AND debut<=".$this->bbox['nord'].") ".
"OR (axe='lng' AND {$conditionsLongitude})".
") ORDER BY axe, position";
$indexMailles = $this->getBdd()->recupererTous($requete);
foreach ($indexMailles as $index) {
if ($index['axe'] == 'lng') {
$this->indexLongitude[$index['position']] = array($index['debut'], $index['fin']);
} else {
$this->indexLatitude[$index['position']] = array($index['debut'], $index['fin']);
}
}
}
private function getBdd() {
if (is_null($this->bdd)) {
$this->bdd = new Bdd();
}
$nomBdd = Config::get('bdd_eflore');
if (is_null($nomBdd)) {
$nomBdd = Config::get('bdd_nom');
}
$this->bdd->requeter("USE ".$nomBdd);
return $this->bdd;
}
public function ajouterPoints(& $points) {
foreach ($points as $index => $point) {
list($longitude, $latitude) = $this->obtenirCoordonneesPoint($point);
list($indexLongitude, $indexLatitude) = $this->rechercherIndexMaille($longitude, $latitude);
$this->mailles[$indexLatitude][$indexLongitude]->ajouterPoint($point);
}
}
private function obtenirCoordonneesPoint($point) {
$longitude = 0;
$latitude = 0;
if (!isset($point['type_site']) || $point['type_site'] == 'STATION') {
$longitude = $point['longitude'];
$latitude = $point['latitude'];
} else {
$longitude = $point['lng_commune'];
$latitude = $point['lat_commune'];
}
return array($longitude, $latitude);
}
private function rechercherIndexMaille($longitude, $latitude) {
$indexLatitude = 0;
$indexLongitude = 0;
while ($indexLatitude < count($this->indexLatitude) - 1
&& $this->mailles[$indexLatitude][0]->getLatitudeNord() < $latitude) {
$indexLatitude ++;
}
while ($indexLongitude < count($this->indexLongitude) - 1
&& $this->mailles[$indexLatitude][$indexLongitude]->getLongitudeEst() < $longitude) {
$indexLongitude ++;
}
return array($indexLongitude, $indexLatitude);
}
 
public function formaterSortie() {
$mailles_resume = array();
foreach ($this->mailles as $ligne) {
foreach ($ligne as $maille) {
$nombrePoints = $maille->getNombrePoints();
if ($nombrePoints == 0)
continue;
$mailles_resume[] = array(
'zoom' => $this->zoom,
'sud' => $maille->getLatitudeSud(),
'ouest' => $maille->getLongitudeOuest(),
'nord' => $maille->getLatitudeNord(),
'est' => $maille->getLongitudeEst(),
'points' => $nombrePoints,
'type_site' => 'MAILLE'
);
}
}
if (count($mailles_resume) == 0 || count($mailles_resume[0]) == 0)
return array();
return $mailles_resume;
}
public function formaterPourInsertionBdd() {
$mailles_resume = array();
foreach ($this->mailles as $ligne) {
foreach ($ligne as $maille) {
if ($maille->getNombrePoints() > 0) {
$mailles_resume[] = array(
'zoom' => $this->zoom,
'sud' => $maille->getLatitudeSud(),
'ouest' => $maille->getLongitudeOuest(),
'nord' => $maille->getLatitudeNord(),
'est' => $maille->getLongitudeEst(),
'indexLat' => $maille->getIndexLatitude(),
'indexLng' => $maille->getIndexLongitude(),
'points' => $maille->getNombrePoints()
);
}
}
}
if (count($mailles_resume[0]) == 0)
return array();
return $mailles_resume;
}
 
public function zoomer() {
$this->zoom += 1;
}
// redecoupage des mailles en 4 (fonction quadtree)
// TODO : revoir le fonctionnement de cette methode (pour utilisation par les scripts uniquement)
public function redecouperMailles() {
$bdd = new Bdd();
while (count($this->indexLatitude) > 0) {
array_pop($this->indexLatitude);
}
while (count($this->indexLongitude) > 0) {
array_pop($this->indexLongitude);
}
$mailles = $this->resumePourInsertionBdd();
while (count($this->mailles) > 0) {
array_pop($this->mailles);
}
foreach ($mailles as $maille) {
$indexLat = 2 * $maille['indexLat'];
$indexLng = 2 * $maille['indexLng'];
// rechercher les nouvelles coordonnees des mailles au niveau de zoom inferieur
$requete = "SELECT axe,position,debut,fin FROM mailles_index WHERE zoom=". $this->zoom ." AND ((axe='lat'"
. " AND (position={$indexLat} OR position=" . ($indexLat+1) . ")) OR (axe='lng' AND"
. " (position={$indexLng} OR position=" . ($indexLng+1) . "))) ORDER BY If(axe='lat',0,1)";
$resultats = $bdd->recupererTous($requete);
$this->indexLatitude[$indexLat] = array($resultats[0]['debut'], $resultats[0]['fin']);
$this->indexLatitude[$indexLat+1] = array($resultats[1]['debut'], $resultats[1]['fin']);
$this->indexLongitude[$indexLng] = array($resultats[2]['debut'], $resultats[2]['fin']);
$this->indexLongitude[$indexLng+1] = array($resultats[3]['debut'], $resultats[3]['fin']);
}
ksort($this->indexLatitude);
ksort($this->indexLongitude);
// creer et ajouter les nouvelles mailles a partir des nouveaux index
foreach ($this->indexLatitude as $indexLat => $intervalleLat) {
$ligne = array();
foreach ($this->indexLongitude as $indexLng => $intervalleLng) {
$ligne[] = new Maille($intervalleLat[0], $intervalleLng[0], $intervalleLat[1],
$intervalleLng[1], $indexLat, $indexLng);
}
$this->mailles[] = $ligne;
}
 
}
public function getNombreMailles() {
return count($this->mailles);
}
}
 
?>
/trunk/services/bibliotheque/VerificateurParametres.php
New file
0,0 → 1,305
<?php
 
 
/**
* Classe commune a tous les services de ce projet qui va analyser et rechercher des erreurs
* sur les valeurs passees en parametres lors d'un appel a ces web services.
*
* Les parametres suivants sont traites :
* - zoom : le niveau de zoom sur la carte (API cartographique client)
* On va verifier que c'est un nombre entier compris entre une valeur minimale et une valeur maximale
*
* - bbox : rectangle dont les bords delimitent en coordonnees l'espace de recherche de donnees spatiales
* L'ordre des valeurs est le suivant : ouest, sud, est, nord
* On va verifier que c'est une serie de quatre nombre decimaux delimites par des virgules
* et compris dans l'espace representant le monde a partir du systeme de projection WGS84 (EPSG:4326)
*
* - longitude et latitude : representent les coordonnees d'un point dans l'espace
* On va verifier que ces coordonnees soient valides dans le systeme de projection utilise
*
* - referentiel : referentiel taxonomique a utiliser. On peut passer aussi bien en parametres
* son nom court que son nom complet (incluant le numero de version)
* On va verifier la disponibilite du referentiel pour ce service
*
* - num_taxon : numero taxonomique d'une espece
* On va rechercher sa presence dans les referentiels disponibles
* (les informations principales sur ce taxon seront renvoyees)
*
* - dept : une liste de numeros de departements separees entre eux par des virgules
* On va verifier que chaque numero est un nombre entier et represente un code de departement valide
*
* - auteur : l'auteur de l'observation
*
* La fonction principale de verification des parametres va parcourir tous les parametres, et verifier
* pour chacun d'eux la validite de leurs valeurs. Dans le cas ou une valeur anormale est detectee
* ou qu'elle se trouve en dehors de l'intervalle des resultats acceptes, une liste de messages d'erreur
* sera generee et mise a jour.
*
* Le resultat final de la verfication peut entrainer deux cas d'utilisation possibles. Si des messages
* d'erreurs ont ete generes durant la verification, ils sont regroupes en un seul message pour lever
* une exception qui sera interpretee par la classe appelante. Dans le cas ou la verification n'a rien
* rencontre d'anormal, une fonction renverra la liste des parametres valides utilisables
* pour des recherches de donnees pour la suite du traitement pour le service.
*
* @package framework-0.3
* @author Alexandre GALIBERT <alexandre.galibert@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 $Id$
* @copyright 2013 Tela Botanica (accueil@tela-botanica.org)
*
*/
 
class VerificateurParametres {
private $parametres = array();
private $validation = null;
private $erreurs = array();
private $bboxMonde = null;
public function __construct($parametres) {
foreach ($parametres as $nomParametre => $valeur) {
if ($nomParametre != 'source') {
$this->parametres[$nomParametre] = $valeur;
}
}
$this->bboxMonde = array(
'ouest' => floatval(Config::get('carte.limite_ouest')),
'est' => floatval(Config::get('carte.limite_est')),
'sud' => floatval(Config::get('carte.limite_sud')),
'nord' => floatval(Config::get('carte.limite_nord'))
);
$this->validation = new StdClass();
}
public function verifierParametres() {
foreach ($this->parametres as $nomParametre => $valeur) {
switch ($nomParametre) {
case 'zoom' : $this->traiterParametreZoom($valeur);
break;
case 'bbox' : $this->traiterParametreBbox($valeur);
break;
case 'longitude' :
case 'latitude' : $this->traiterParametresCoordonnees($this->parametres['longitude'],
$this->parametres['latitude']);
break;
case 'dept' : $this->traiterParametreDepartement($valeur);
break;
case 'auteur' : $this->traiterParametreAuteur($valeur);
break;
case 'referentiel' : $this->traiterParametreReferentiel($valeur);
break;
case 'num_taxon' : $this->traiterParametreTaxon($valeur);
break;
// autres parametres ==> les ignorer
default : break;
}
}
$this->verifierPresenceParametreSpatial();
}
private function ajouterErreur($messageErreur) {
$this->erreurs[] = $messageErreur;
}
public function renvoyerResultatVerification() {
return $this->validation;
}
public function contienterreurs() {
return count($this->erreurs);
}
public function leverException() {
$messagesErreur = "Les erreurs suivantes ont été rencontrées : \n".
implode("\n", $this->erreurs);
throw new Exception($messagesErreur, RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
}
// ------------------------------------------------------------------------- //
// Fonctions de verification de parametres et detection de valeurs anormales //
// ------------------------------------------------------------------------- //
private function traiterParametreZoom($zoom) {
$zoom = intval($zoom);
$mondeZoom = array(
'min' => intval(Config::get('carte.zoom_minimal')),
'max' => intval(Config::get('carte.zoom_maximal'))
);
if ($zoom < $mondeZoom['min'] || $zoom > $mondeZoom['max']) {
$message = 'Niveau de zoom non reconnu par le service. Il doit être compris entre '.
$mondeZoom['min'].' et '.$mondeZoom['max'];
$this->ajouterErreur($message);
} else {
$this->validation->zoom = $zoom;
}
}
private function traiterParametreBbox($bbox) {
// verifier que la chaine de caracteres $bbox est une serie de chaque nombre decimaux
// separes entre eux par une virgule
if (preg_match('/^(-?\d{1,3}(.\d+)?,){3}(-?\d{1,3}(.\d+)?)$/', $bbox) == 0) {
$message = "Format de saisie des coordonnees de la bounding box non valide. Le service ".
"n'accepte seulement qu'une serie de 4 nombre décimaux séparés par des virgules.";
$this->ajouterErreur($message);
} else {
$coordonnees = explode(',', $bbox);
// index du tableau des coordonnees : ouest/sud/est/nord
$nomsIndexBbox = array("ouest", "sud", "est", "nord");
$bbox = array();
for ($i = 0; $i < count($coordonnees); $i ++) {
$bbox[$nomsIndexBbox[$i]] = $coordonnees[$i];
}
// verifier que les coordonnees de chaque bord de la bbox sont valides
if ($this->estUneBboxValide($bbox)) {
$this->validation->bbox = $bbox;
} else {
$message = "Certaines coordonnées de la bounding box sont situés en dehors des limites ".
"de notre monde";
$this->ajouterErreur($message);
}
}
}
private function estUneBboxValide($bbox) {
$monde = $this->bboxMonde;
return (floatval($bbox['ouest']) >= $monde['ouest'] && floatval($bbox['ouest']) <= $monde['est']
&& floatval($bbox['est']) >= $monde['ouest'] && floatval($bbox['est']) <= $monde['est']
&& floatval($bbox['nord']) >= $monde['sud'] && floatval($bbox['nord']) <= $monde['nord']
&& floatval($bbox['sud']) >= $monde['sud'] && floatval($bbox['sud']) <= $monde['nord']);
}
private function traiterParametresCoordonnees($longitude, $latitude) {
if ($this->sontDesCoordonneesValides($longitude, $latitude)) {
$this->validation->latitude = $latitude;
$this->validation->longitude = $longitude;
} else {
$message = "Les coordonnees du point passées en parametres sont en dehors des limites de ".
"notre monde";
$this->ajouterErreur($message);
}
}
private function sontDesCoordonneesValides($longitude, $latitude) {
$monde = $this->bboxMonde;
return (floatval($longitude) >= $monde['ouest'] && floatval($longitude) <= $monde['est']
&& floatval($latitude) >= $monde['sud'] && floatval($latitude) <= $monde['nord']);
}
private function traiterParametreDepartement($numeroDepartement) {
if ($numeroDepartement != '*') {
$departements = explode(',', trim($numeroDepartement));
foreach ($departements as $departement) {
if($this->estUnCodeDepartementValide($departement)) {
$this->validation->departement[] = $departement;
} else {
$message = "Code de département non valide";
$this->ajouterErreur($message);
}
}
}
}
private function estUnCodeDepartementValide($departement) {
// expression reguliere pour verifier que c'est un nombre entier a 2 ou 3 chiffres
$estUnDepartementValide = true;
if (preg_match('/^\d{2,3}$/', $departement) != 1) {
$estUnDepartementValide = false;
} else {
if ((intval($departement) < 1 || intval($departement) > 95)
&& (intval($departement) < 971 || intval($departement) > 978)) {
$estUnDepartementValide = false;
}
}
return $estUnDepartementValide;
}
private function traiterParametreAuteur($auteur) {
if ($auteur != '*') {
$this->validation->auteur = trim($auteur);
}
}
private function traiterParametreReferentiel($referentiel) {
if (!isset($this->validation->referentiel) && $referentiel != '*') {
$referentielAUtiliser = $this->affecterNomCompletReferentiel($referentiel);
if (is_null($referentielAUtiliser)) {
$message = "Le référentiel demandé n'est pas reconnu par le service.";
$this->ajouterErreur($message);
} else {
$this->validation->referentiel = $referentielAUtiliser;
}
}
}
private function affecterNomCompletReferentiel($referentiel) {
$referentielAUtiliser = null;
$listeReferentiels = Referentiel::recupererListeReferentielsDisponibles();
foreach ($listeReferentiels as $nomReferentiel) {
$nomCourtReferentiel = current(explode('_', $nomReferentiel));
if ($referentiel == $nomCourtReferentiel || $referentiel == $nomReferentiel) {
$referentielAUtiliser = $nomReferentiel;
break;
}
}
return $referentielAUtiliser;
}
private function traiterParametreTaxon($numeroTaxon) {
if ($numeroTaxon != '*') {
$taxon = null;
if (isset($this->validation->referentiel)) {
$taxon = $this->renvoyerTaxonDansReferentiel($numeroTaxon, $this->validation->referentiel);
} else {
// parcours de tous les referentiels jusqu'a retrouver le taxon dans sa liste
$taxon = $this->rechercherTaxonDansReferentiels($numeroTaxon);
}
if (is_null($taxon)) {
$message = "Le numéro de taxon n'a pas permis de retrouver le taxon associé.";
$this->ajouterErreur($message);
} else {
$this->validation->taxon = $taxon;
$this->validation->referentiel = $taxon['referentiel'];
}
}
}
private function rechercherTaxonDansReferentiels($numeroTaxon) {
$taxon = null;
$listeReferentiels = Referentiel::recupererListeReferentielsDisponibles();
foreach ($listeReferentiels as $nomReferentiel) {
$taxon = $this->renvoyerTaxonDansReferentiel($numeroTaxon, $nomReferentiel);
if (!is_null($taxon)) {
break;
}
}
return $taxon;
}
private function renvoyerTaxonDansReferentiel($numeroTaxon, $nomReferentiel) {
$referentiel = new Referentiel($nomReferentiel);
$referentiel->chargerTaxon($numeroTaxon);
$taxon = $referentiel->renvoyerTaxon();
return $taxon;
}
private function verifierPresenceParametreSpatial() {
$presenceParametreSpatial = false;
if (isset($this->parametres['bbox'])
|| (isset($this->parametres['longitude']) && isset($this->parametres['latitude']))) {
$presenceParametreSpatial = true;
}
if ($presenceParametreSpatial == false) {
$message = "Aucune coordonnée n'a été saisie";
$this->ajouterErreur($message);
}
}
}
 
?>
/trunk/services/bibliotheque/FormateurJson.php
New file
0,0 → 1,141
<?php
 
 
class FormateurJson {
private $sourceDonnees;
public function __construct($source) {
$this->sourceDonnees = $source;
}
public function formaterStations($stations) {
$objetJSON = new StdClass();
$objetJSON->type = "FeatureCollection";
$objetJSON->stats = new StdClass();
$objetJSON->stats->communes = 0;
$objetJSON->stats->stations = 0;
$objetJSON->features = array();
foreach ($stations as $station) {
$stationJSON = NULL;
// construction d'un objet feature adapte a la structure des donnees spatiales
if ($station['type_site'] == 'MAILLE') {
$stationJSON = $this->formaterMaille($station);
} else {
if ($station['type_site'] == 'STATION') {
$objetJSON->stats->communes ++;
} else {
$objetJSON->stats->stations ++;
}
$stationJSON = $this->formaterPoint($station);
}
if (!is_null($stationJSON)) {
$objetJSON->features[] = $stationJSON;
}
}
return $objetJSON;
}
private function formaterPoint($station) {
$json = new StdClass();
$json->type = "Feature";
$json->geometry = new StdClass();
$json->properties = new StdClass();
$json->geometry->type = "Point";
$json->properties->typeSite = $station['type_site'];
if ($this->sourceDonnees == 'floradata' && $station['type_site'] == 'COMMUNE') {
$json->geometry->coordinates = array($station['lat_commune'], $station['lng_commune']);
} else {
$json->geometry->coordinates = array($station['latitude'], $station['longitude']);
}
if ($this->sourceDonnees == 'floradata') {
$json->properties->nom = $this->construireNomStationFloradata($station);
} else {
$station['code_insee'] = '';
$codeDepartement = $this->extraireCodeDepartement($station['code_insee']);
$json->properties->nom = trim($station['nom'])." ({$codeDepartement})";
}
return $json;
}
private function construireNomStationFloradata($station) {
$nom = ($station['type_site'] == 'COMMUNE') ? trim($station['nom_commune']) : trim($station['station']);
$codeDepartement = $this->extraireCodeDepartement($station['ce_zone_geo']);
if ($station['type_site'] == 'COMMUNE') {
$nom = $station['zone_geo'] . " ({$codeDepartement})";
} else {
if (strlen($nom) == 0) {
$nom = 'station sans nom, '.trim($station['zone_geo']);
}
$nom .= " ({$codeDepartement})";;
}
return $nom;
}
private function extraireCodeDepartement($codeInsee) {
$codeInsee = substr($codeInsee,-5);
$codeDepartement = substr($codeInsee, 0 ,2);
if (intval($codeDepartement) > 95) {
substr($codeInsee, 0 ,3);
}
return $codeDepartement;
}
private function formaterMaille($maille) {
if ($maille['points'] == 0) {
return null;
}
$json = new StdClass();
$json->type = "Feature";
$json->geometry = new StdClass();
$json->geometry->type = "Polygon";
$json->geometry->coordinates = array(
array(floatval($maille['sud']), floatval($maille['ouest'])),
array(floatval($maille['sud']), floatval($maille['est'])),
array(floatval($maille['nord']), floatval($maille['est'])),
array(floatval($maille['nord']), floatval($maille['ouest'])),
array(floatval($maille['sud']), floatval($maille['ouest']))
);
$json->properties = new StdClass();
$json->properties->typeSite = $maille['type_site'];
$json->properties->nombrePoints = $maille['points'];
return $json;
}
public function formaterObservations($observations, $nomSite) {
$objetJSON = new StdClass();
$objetJSON->site = trim($nomSite);
$objetJSON->total = count($observations);
$objetJSON->observations = array();
foreach ($observations as $observation) {
$observationJson = new stdClass();
foreach ($observation as $colonne => $valeur) {
if ($colonne == 'nom_referentiel') {
$observationJson->urlEflore = $this->genererUrlFicheEflore($observation);
} else {
$observationJson->$colonne = is_string($valeur) ? trim($valeur) : $valeur;
}
}
$objetJSON->observations[] = $observationJson;
}
return $objetJSON;
}
private function genererUrlFicheEflore($observation) {
$url = null;
if (strstr('bdtfx', $observation['nom_referentiel']) !== false) {
$url = 'http://www.tela-botanica.org/bdtfx-nn-'.$observation['nn'];
}
return $url;
}
}
 
?>
/trunk/services/bibliotheque/Maille.php
New file
0,0 → 1,68
<?php
 
class Maille {
private $latitudeSud;
private $longitudeOuest;
private $latitudeNord;
private $longitudeEst;
private $indexLatitude;
private $indexLongitude;
private $points = array();
private $nombrePoints = 0;
public function __construct($sud, $ouest, $nord, $est, $indexLat, $indexLng) {
$this->latitudeSud = $sud;
$this->longitudeOuest = $ouest;
$this->latitudeNord = $nord;
$this->longitudeEst = $est;
$this->indexLatitude = $indexLat;
$this->indexLongitude = $indexLng;
}
public function ajouterPoint(& $point) {
$this->points[] = $point;
$this->nombrePoints ++;
}
public function getLatitudeNord() {
return $this->latitudeNord;
}
public function getLongitudeOuest() {
return $this->longitudeOuest;
}
public function getLatitudeSud() {
return $this->latitudeSud;
}
public function getLongitudeEst() {
return $this->longitudeEst;
}
public function getIndexLatitude() {
return $this->indexLatitude;
}
public function getIndexLongitude() {
return $this->indexLongitude;
}
public function getNombrePoints() {
return $this->nombrePoints;
}
public function getPoint($index = 0) {
return (!isset($this->points[$index])) ? NULL : $this->points[$index];
}
public function totalNonNul() {
return !is_null($this->nombrePoints);
}
}
 
?>
/trunk/services/bibliotheque/Referentiel.php
New file
0,0 → 1,165
<?php
 
 
/**
* Classe qui va effectuer toutes les operations liees aux referentiels ou rechercher
* des informations sur les taxons dans les tables des referentiels dans la base de donnees
*
* Operations a utiliser :
* - recupererListeReferentielsDisponibles (statique) : recherche dans les fichiers de configuration
* la liste des referentiels disponibles et les renvoie dans un tableau
*
* - chargerTaxon : recherche dans la table possedant le meme nom que le nom du referentiel en attribut
* les informations generales sur un taxon (numero nomenclatural retenu, numero taxonomique,
* nom scientifique, rang) a partir de son numero taxonomique
* On stockera dans un attribut un tableau associatif contenant ces informations + le nom du referentiel,
* ou la valeur nulle si aucun taxon n'a ete trouve
*
* - recupererSousTaxons : a partir du numero nomenclatural d'un taxon, la fonction va recuperer
* tous les taxons de rang inferieur de maniere recursive jusqu'en ne plus en trouver de nouveaux
* la recherche s'effectuera seulement au niveau des rangs famille, genre, espece et sous-espece
* pour limiter le nombre d'informations qui sera a la fin renvoye
*
* - obtenirNumeroNomenclatural : recherche le numero nomenclatural d'un taxon a partir de son nom scientifique
*
* @package framework-0.3
* @author Alexandre GALIBERT <alexandre.galibert@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 $Id$
* @copyright 2013 Tela Botanica (accueil@tela-botanica.org)
*
*/
 
define("RANG_FAMILLE", 180);
 
 
 
class Referentiel {
private $nomComplet;
private $nomCourt;
private $taxon;
private $bdd = null;
private $nomsChampsBdtfx = array('nn' => 'num_nom_retenu', 'nt' => 'num_taxonomique', 'ns' => 'nom_sci');
private $nomsChampsBdtxa = array('nn' => 'num_nom_retenu', 'nt' => 'num_tax', 'ns' => 'nom_sci');
private $champs;
public function __construct($nomReferentiel, $taxon = null) {
$this->nomComplet = $nomReferentiel;
$this->nomCourt = current(explode('_', $nomReferentiel));
$proprieteChamps = 'nomsChamps' . ucfirst($this->nomCourt);
foreach ($this->$proprieteChamps as $nomCourt => $nomChamp) {
$this->champs[$nomCourt] = $nomChamp;
}
$this->taxon = $taxon;
}
public function renvoyerNomCompletReferentiel() {
return $this->nomComplet;
}
public function renvoyerTaxon() {
return $this->taxon;
}
public function chargerTaxon($numTaxon) {
$taxon = null;
// verifier que le numero de taxon soit bien une chaine de caracteres composee uniquement
// que de nombres entiers avant de construire la requete SQL a executer
if (preg_match('/^\d+$/', $numTaxon) == 1) {
$requete =
"SELECT ".$this->champs['nn']." AS nn, ".$this->champs['nt']." AS nt, ".
$this->champs['ns']." AS nom, rang FROM ".$this->nomComplet." WHERE ".
$this->champs['nt']."={$numTaxon} AND num_nom=".$this->champs['nn']." ".
"ORDER BY rang, If(num_nom=".$this->champs['nn'].", 0, 1) LIMIT 0, 1";
$taxon = $this->getBdd()->recuperer($requete);
if ($taxon == false) {
$taxon = null;
} else {
$taxon['referentiel'] = $this->nomComplet;
}
}
$this->taxon = $taxon;
}
public function recupererSousTaxons($listeNn = null) {
$sousTaxons = array();
if (!is_null($this->taxon) && $this->taxon['rang'] >= RANG_FAMILLE) {
if (is_null($listeNn)) {
$listeNn = $this->taxon['nn'];
}
$requete =
"SELECT ".$this->champs['nn']." AS nn, ".$this->champs['nt']." AS nt, ".
$this->champs['ns']." AS nom, rang FROM ".$this->nomComplet." WHERE ".
"num_tax_sup IN ({$listeNn}) AND num_nom=".$this->champs['nn'];
$resultats = $this->getBdd()->recupererTous($requete);
$nouvelleListeNn = '';
foreach ($resultats as $sousTaxon) {
$sousTaxons[] = $sousTaxon;
$nouvelleListeNn .= (strlen($nouvelleListeNn) == 0 ? '' : ',') . $sousTaxon['nn'];
}
// recherche de sous taxons au niveau inferieur (parcours recursif de la methode)
if (count($resultats) > 0) {
$sousTaxons = array_merge($sousTaxons, $this->recupererSousTaxons($nouvelleListeNn));
}
}
return $sousTaxons;
}
private function getBdd() {
if (is_null($this->bdd)) {
$this->bdd = new Bdd();
}
$nomBdd = Config::get('bdd_eflore');
if (is_null($nomBdd)) {
$nomBdd = Config::get('bdd_nom');
}
$this->bdd->requeter("USE ".$nomBdd);
return $this->bdd;
}
public static function recupererListeReferentielsDisponibles() {
$tableau = array();
$tableauPartiel = explode(',', Config::get('referentiels_dispo'));
$tableauPartiel = array_map('trim', $tableauPartiel);
foreach ($tableauPartiel as $champ) {
if (strpos($champ, '=') === false) {
$tableau[] = $champ;
} else {
list($cle, $val) = explode('=', $champ);
$clePropre = trim($cle);
$valeurPropre = trim($val);
$tableau[$clePropre] = $valeurPropre;
}
}
return $tableau;
}
public function obtenirNumeroNomenclatural($nomScientifique) {
$aProteger = $this->getBdd()->proteger(trim($nomScientifique) . '%');
$requete = "SELECT ".$this->champs['nn']." AS nn FROM ".$this->nomComplet." ".
"WHERE ".$this->champs['ns']." LIKE ".$aProteger;
$taxon = $this->getBdd()->recuperer($requete);
if ($taxon == false) {
$taxon = null;
} else {
$taxon['referentiel'] = $this->nomComplet;
}
return $taxon;
}
}
?>
/trunk/services/bibliotheque/CacheMoissonnage.php
4,18 → 4,20
private $service;
private $config;
private $dureecache = 0;
private $projetNom;
private $serviceNom;
private $cache;
private $cacheActif;
public function __construct($service, $projetNom, $serviceNom, $cacheActif) {
public function __construct($service, $serviceNom, $cacheActif) {
$this->cacheActif = $cacheActif;
$this->service = $service;
$this->chargerDureeCache();
$this->projetNom = $projetNom;
$this->serviceNom = $serviceNom;
$this->cache = new CacheSimple(array("mise_en_cache" => true, "stockage_chemin" => Config::get("chemincache"), "duree_de_vie" => $this->dureecache));
$this->cache = new CacheSimple(array(
"mise_en_cache" => true,
"stockage_chemin" => Config::get("chemincache"),
"duree_de_vie" => $this->dureecache
));
}
 
public function chargerDureeCache() {
59,7 → 61,7
}
}
$chaineMD5 = $this->projetNom.'/'.$this->serviceNom.'/'.md5($chaineRessources.$chaineParametres);
$chaineMD5 = $this->serviceNom.'/'.md5($chaineRessources.$chaineParametres);
return $chaineMD5;
}
}
/trunk/services/modules/0.1/Projets.php
New file
0,0 → 1,175
<?php
 
 
class Projets extends RestService {
 
private $parametres = array();
private $ressources = array();
private $squeletteDossier = '';
private $cache;
public function __construct() {
$this->squeletteDossier = dirname(__FILE__).DIRECTORY_SEPARATOR;
}
 
public function consulter($ressources, $parametres) {
$resultat = '';
$reponseHttp = new ReponseHttp();
try {
$this->initialiserRessourcesEtParametres($ressources, $parametres);
$resultat = $this->traiterRessources();
$reponseHttp->setResultatService($resultat);
} catch (Exception $e) {
$reponseHttp->ajouterErreur($e);
}
$reponseHttp->emettreLesEntetes();
$corps = $reponseHttp->getCorps();
return $corps;
}
private function initialiserRessourcesEtParametres($ressources, $parametres) {
$this->ressources = $ressources;
$this->parametres = $parametres;
}
private function traiterRessources() {
$retour = '';
if ($this->avoirRessources()) {
if ($this->avoirRessourceService()) {
$retour = $this->initialiserService();
}
}
return $retour;
}
private function avoirRessources() {
$presenceDeRessources = false;
if (isset($this->ressources) && count($this->ressources) > 0) {
$presenceDeRessources = true;
} else {
$message = "Accès au service refusé : aucune ressource indiquée.\n"
. "Veuillez indiquer au moins une source de données à interroger"
. " et le type d'informations a renvoyer.";
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
throw new Exception($message, $code);
}
return $presenceDeRessources;
}
private function chargerConfiguration($nomParametre) {
$tableau = array();
$tableauPartiel = explode(',', Config::get($nomParametre));
$tableauPartiel = array_map('trim', $tableauPartiel);
foreach ($tableauPartiel as $champ) {
if (strpos($champ, '=') === false) {
$tableau[] = $champ;
} else {
list($cle, $val) = explode('=', $champ);
$clePropre = trim($cle);
$valeurPropre = trim($val);
$tableau[$clePropre] = $valeurPropre;
}
}
return $tableau;
}
public static function chargerConfigurationSource($nomSource) {
$chemin = Config::get('chemin_configurations')."config_$nomSource.ini";
Config::charger($chemin);
}
private function chargerClasse($classe) {
if (class_exists($classe)) {
return null;
}
$cheminBiblio = Config::get('chemin_bibliotheque');
$chemins = array();
$chemins[] = $this->squeletteDossier;
$chemins[] = $this->squeletteDossier.'commun' .DIRECTORY_SEPARATOR;
$chemins[] = $this->squeletteDossier.'sources'.DIRECTORY_SEPARATOR;
$chemins[] = $cheminBiblio;
$chemins[] = $cheminBiblio.'robots'.DIRECTORY_SEPARATOR;
foreach ($chemins as $chemin) {
$chemin = $chemin.$classe.'.php';
if (file_exists($chemin)) {
require_once $chemin;
break;
}
}
}
private function avoirRessourceService() {
$presenceRessourceService = false;
$servicesDispo = $this->chargerConfiguration('services_dispo');
if (isset($this->ressources[0])) {
$service = $this->ressources[0];
if (in_array($service, $servicesDispo)) {
$presenceRessourceService = true;
} else {
$message = "La service demandé '$service' n'est pas disponible !\n"
. "Les services disponibles sont : ".implode(', ', $servicesDispo);
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
}
} else {
$message = "Vous n'avez pas indiqué de service !\n"
. "Les services disponibles sont : ".implode(', ', $servicesDispo);
$code = RestServeur::HTTP_CODE_MAUVAISE_REQUETE;
throw new Exception($message, $code);
}
return $presenceRessourceService;
}
 
private function initialiserService() {
$nomService = 'commun';
$classe = $this->obtenirNomClasseService($nomService);
$chemins = array();
$chemins[] = $this->squeletteDossier.'commun'.DIRECTORY_SEPARATOR.'Commun.php';
// php5.3 : Enregistrement en première position des autoload de la méthode gérant les classes des services
if (phpversion() < 5.3) {
spl_autoload_register(array($this, 'chargerClasse'));
} else {
spl_autoload_register(array($this, 'chargerClasse'), true , true);
}
$retour = '';
$service = null;
foreach ($chemins as $chemin) {
if (file_exists($chemin)) {
$service = new $classe($this->getBdd());
$ressourcesPourService = $this->filtrerRessourcesPourService();
$this->cache = new CacheMoissonnage($service, $nomService,
Config::get('cache'));
$retour = $this->cache->consulter($ressourcesPourService, $this->parametres);
if (get_class($retour) == 'Exception') {
throw new Exception($retour->getMessage(), RestServeur::HTTP_CODE_MAUVAISE_REQUETE);
}
}
}
if (is_null($service)) {
$message = "Le service demandé '{$nomService}' n'existe pas !";
$code = RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE;
throw new Exception($message, $code);
}
return $retour;
}
private function obtenirNomClasseService($mot) {
$classeNom = str_replace(' ', '', ucwords(strtolower(str_replace('-', ' ', $mot))));
return $classeNom;
}
private function filtrerRessourcesPourService() {
return $this->ressources;
}
}
 
?>
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/trunk/services/modules/0.1/commun/Commun.php
New file
0,0 → 1,92
<?php
 
class Commun {
private $parametres;
private $nomSource;
private $nomService;
private $verificateur;
private $parametresRecherche;
public function consulter($ressources, $parametres) {
$this->recupererRessourcesEtParametres($ressources, $parametres);
$retour = null;
try {
if (!$this->verifierExistenceSourcesDonnees()) {
$message = "Source de donnees indisponible";
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
} else {
$this->chargerNomSource();
$this->verifierParametres();
$this->chargerNomService();
$objetTraitement = new $this->nomService($this->parametresRecherche);
$methode = $this->genererNomMethodeAExecuter();
$retour = $objetTraitement->$methode();
}
} catch (Exception $erreur) {
$retour = $erreur;
}
return $retour;
}
private function recupererRessourcesEtParametres($ressources, $parametres) {
$this->ressources = $ressources;
$this->parametres = $parametres;
}
private function chargerNomService() {
$this->nomService = ucfirst($this->parametres['source']) . 'Formateur';
Projets::chargerConfigurationSource($this->parametres['source']);
}
private function genererNomMethodeAExecuter() {
return 'recuperer' . ucfirst($this->ressources[0]);
}
private function verifierExistenceSourcesDonnees() {
$sourcesDisponibles = explode(',', Config::get('sources_dispo'));
$estDisponible = false;
if (isset($this->parametres['source'])) {
if (in_array($this->parametres['source'], $sourcesDisponibles)) {
$estDisponible = true;
}
} else {
// choisir la source par defaut, qui est toujours disponible
$estDisponible = true;
}
return $estDisponible;
}
private function chargerNomSource() {
if (isset($this->parametres['source'])) {
$this->nomSource = $this->parametres['source'];
} else {
$this->nomSource = Config::get('source_defaut');
}
}
private function verifierParametres() {
$this->verificateur = new VerificateurParametres($this->parametres);
$this->verificateur->verifierParametres();
if ($this->verificateur->contientErreurs()) {
$this->verificateur->leverException();
} else {
$this->recupererParametresRecherche();
}
}
private function recupererParametresRecherche() {
$this->parametresRecherche = $this->verificateur->renvoyerResultatVerification();
}
}
 
?>
/trunk/services/modules/0.1/sources/FloradataFormateur.php
New file
0,0 → 1,233
<?php
 
/**
*
* Classe en charge de recuperer les donnees d'observation ou liees a leur localisation
* Le jeu de donnees a interroger est celui utilise par l'application Carnet En Ligne
* (http://www.tela-botanica.org/page:cel)
*
* On passera en parametre lors de la creation d'une instance un objet contenant la liste des criteres
* qui vont restreindre le nombre de resultats a renvoyer
*
* Les deux operations suivantes peuvent etre utilisees dans les services :
* - recupererStations : va rechercher dans la base de donnees tous les points d'observations
* correspondant aux criteres de recherche demandes. La precision des lieux d'observation est
* soit un point precis, soit ramenee au niveau de la commune dans laquelle l'observation a ete faite
* En fonction du niveau de zoom et du nombre de resultats trouves, la presentation se fera
* soit par les points localisant les stations pour des niveaux de zoom eleves ou pour un nombre
* de stations inferieur a un seuil, ou par des mailles de 64*64 pixels dans le cas contraire
*
* - recupererObservations : va rechercher dans la base de donnees les donnees sur des observations
* a partir des coordonnees longitude et latitude d'une station (+ des parametres additionnels)
*
* Les donnees seront renvoyees au format JSON
*
* @package framework-0.3
* @author Alexandre GALIBERT <alexandre.galibert@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 $Id$
* @copyright 2013 Tela Botanica (accueil@tela-botanica.org)
*
*/
 
 
class FloradataFormateur {
private $criteresRecherche;
private $bdd;
public function __construct($criteresRecherche) {
$this->criteresRecherche = $criteresRecherche;
}
public function recupererStations() {
// recuperer les informations au niveau de la base de donnees
$requeteSql = $this->construireRequeteStations();
$stations = $this->getBdd()->recupererTous($requeteSql);
$zoomMaxMaillage = Config::get('zoom_maximal_maillage');
$seuilMaillage = Config::get('seuil_maillage');
$zoom = $this->criteresRecherche->zoom;
$bbox = $this->criteresRecherche->bbox;
// TODO: gérer une notion d'échelle plutot que de zoom (pour les clients SIG)
if (count($stations) > $seuilMaillage && intval($zoom)<= $zoomMaxMaillage) {
// partitionnement des donnees en mailles
$maillage = new Maillage($bbox, $zoom);
$maillage->genererMaillesVides();
$maillage->ajouterPoints($stations);
$stations = $maillage->formaterSortie();
}
// mettre en forme les informations au format JSON
$formateurJSON = new FormateurJson('floradata');
$donneesFormatees = $formateurJSON->formaterStations($stations);
return $donneesFormatees;
}
public function recupererObservations() {
// recuperer les informations sur les stations repondant a ces parametres
$requeteSql = $this->construireRequeteObservations();
$observations = $this->getBdd()->recupererTous($requeteSql);
$nomSite = $this->obtenirNomStation();
// mettre en forme les informations au format JSON
$formateurJSON = new FormateurJson('floradata');
$donneesFormatees = $formateurJSON->formaterObservations($observations, $nomSite);
return $donneesFormatees;
}
// ------------------------------------------------------------------------ //
// Fonctions de construction des criteres de recherches pour la requete SQL //
// ------------------------------------------------------------------------ //
private function getBdd() {
if (!isset($this->bdd)) {
$this->bdd = new Bdd();
}
$this->bdd->requeter("USE ".Config::get('bdd_nom'));
return $this->bdd;
}
private function construireRequeteStations() {
$selectTypeSite =
"IF(".
"(longitude IS NULL OR latitude IS NULL) ".
"OR (longitude=0 AND latitude=0) ".
"OR (longitude=999.99999 AND latitude=999.99999)".
", 'COMMUNE', 'STATION'".
")";
$requete =
'SELECT ce_zone_geo, zone_geo, station, longitude, latitude, nom AS "nom_commune",'.
'wgs84_longitude AS "lng_commune", wgs84_latitude AS "lat_commune", '.
$selectTypeSite.' AS "type_site" '.
'FROM cel_obs LEFT JOIN cel_zones_geo cz ON ce_zone_geo=id_zone_geo '.
'WHERE transmission=1 '.
$this->construireWhereDepartement().' '.
$this->construireWhereAuteur().' '.
$this->construireWhereReferentiel().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesBbox().' '.
"GROUP BY longitude, latitude, wgs84_longitude, wgs84_latitude";
return $requete;
}
private function construireRequeteObservations() {
$requete =
"SELECT id_observation AS id_obs, nom_ret_nn AS nn, nom_ret AS nomSci, ".
"Date(date_transmission) AS date, milieu AS lieu, nom_referentiel, ".
"Concat(prenom_utilisateur, ' ', nom_utilisateur) AS observateur, ce_utilisateur AS observateurId ".
"FROM cel_obs WHERE transmission=1 ".
$this->construireWhereAuteur().' '.
$this->construireWhereReferentiel().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesPoint().' '.
"ORDER BY nom_ret, date, observateur";
return $requete;
}
private function construireWhereTaxon() {
$sql = '';
if (isset($this->criteresRecherche->taxon)) {
$taxon = $this->criteresRecherche->taxon;
$criteres = "nom_ret LIKE ".$this->getBdd()->proteger($taxon['nom']."%");
$referentiel = new Referentiel($this->criteresRecherche->referentiel, $this->criteresRecherche->taxon);
$sousTaxons = $referentiel->recupererSousTaxons();
foreach ($sousTaxons as $sousTaxon) {
$criteres .= " OR nom_ret LIKE ".$this->getBdd()->proteger($taxon['nom']."%");
}
$sql = "AND ($criteres)";
}
return $sql;
}
private function construireWhereReferentiel() {
$sql = '';
if (isset($this->criteresRecherche->referentiel) && !isset($this->criteresRecherche->taxon)) {
$referentiel = current(explode('_', $this->criteresRecherche->referentiel));
$sql = "AND nom_referentiel LIKE ".$this->getBdd()->proteger($referentiel."%");
}
return $sql;
}
private function construireWhereDepartement() {
$sql = '';
if (isset($this->criteresRecherche->departement)) {
$valeurs_a_proteger = $this->criteresRecherche->departement;
foreach ($valeurs_a_proteger as $valeur) {
$valeurs_protegees[] = "ce_zone_geo LIKE " . $this->getBdd()->proteger('INSEE-C:' . $valeur . '%');
}
$valeurs = implode(' OR ', $valeurs_protegees);
$sql = "AND ($valeurs)";
}
return $sql;
}
private function construireWhereAuteur() {
$sql = '';
if (isset($this->criteresRecherche->auteur)) {
$utilisateur = $this->getBdd()->proteger($this->criteresRecherche->auteur);
$sql = "AND courriel_utilisateur = $utilisateur";
}
return $sql;
}
private function construireWhereCoordonneesBbox() {
$bbox = $this->criteresRecherche->bbox;
$sql =
"AND (".
"(".
"longitude BETWEEN ".$bbox['ouest']." AND ".$bbox['est']." ".
"AND latitude BETWEEN ".$bbox['sud']." AND ".$bbox['nord']." ".
"AND (wgs84_longitude IS NULL OR wgs84_latitude IS NULL)".
") OR (".
"wgs84_longitude BETWEEN ".$bbox['ouest']." AND ". $bbox['est']." ".
"AND wgs84_latitude BETWEEN ".$bbox['sud']." AND ".$bbox['nord'].
")".
")";
return $sql;
}
private function construireWhereCoordonneesPoint() {
$commune = $this->obtenirCoordonneesCommune();
$condition = "(longitude=".$this->criteresRecherche->longitude." ".
"AND latitude=".$this->criteresRecherche->latitude.")";
if (!is_null($commune)) {
$condition .= " OR (longitude IS NULL AND latitude IS NULL AND ce_zone_geo=".
$this->getBdd()->proteger($commune['id_zone_geo']).")";
}
return "AND ($condition)";
}
private function obtenirCoordonneesCommune() {
$requete = "SELECT id_zone_geo, nom FROM cel_zones_geo WHERE wgs84_longitude=".
$this->criteresRecherche->longitude." AND wgs84_latitude=".$this->criteresRecherche->latitude;
$commune = $this->getBdd()->recuperer($requete);
if ($commune === false) {
$commune = null;
}
return $commune;
}
private function obtenirNomStation() {
// verifier si les coordonnees du point de requetage correspondent a une commune
$station = $this->obtenirCoordonneesCommune();
if (is_null($station)) {
$requete = 'SELECT DISTINCT lieudit AS nom FROM cel_obs WHERE longitude='.
$this->criteresRecherche->longitude.' AND latitude='.$this->criteresRecherche->latitude;
$station = $this->getBdd()->recuperer($requete);
}
$nomStation = '';
if ($station !== false) {
$nomStation = trim($station['nom']);
}
return $nomStation;
}
}
 
?>
/trunk/services/modules/0.1/sources/SophyFormateur.php
New file
0,0 → 1,263
<?php
 
/**
*
* Classe en charge de recuperer les donnees d'observation ou liees a leur localisation
* Le jeu de donnees a interroger est partage en commun avec l'application EFlore
*
* On passera en parametre lors de la creation d'une instance un objet contenant la liste des criteres
* qui vont restreindre le nombre de resultats a renvoyer
*
* Les deux operations suivantes peuvent etre utilisees dans les services :
* - recupererStations : va rechercher dans la base de donnees tous les points d'observations
* correspondant aux criteres de recherche demandes. La precision des lieux d'observation est
* soit un point precis, soit ramenee au niveau de la commune dans laquelle l'observation a ete faite
* En fonction du niveau de zoom et du nombre de resultats trouves, la presentation se fera
* soit par les points localisant les stations pour des niveaux de zoom eleves ou pour un nombre
* de stations inferieur a un seuil, ou par des mailles de 64*64 pixels dans le cas contraire
*
* - recupererObservations : va rechercher dans la base de donnees les donnees sur des observations
* a partir des coordonnees longitude et latitude d'une station (+ des parametres additionnels)
*
* Les donnees seront renvoyees au format JSON
*
* @package framework-0.3
* @author Alexandre GALIBERT <alexandre.galibert@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 $Id$
* @copyright 2013 Tela Botanica (accueil@tela-botanica.org)
*
*/
 
class SophyFormateur {
private $criteresRecherche;
private $bdd;
public function __construct($criteresRecherche) {
$this->criteresRecherche = $criteresRecherche;
}
public function recupererStations() {
$stations = array();
$nombreStations = $this->obtenirNombreStationsDansBbox();
$seuilMaillage = Config::get('seuil_maillage');
$nombreParametresNonSpatiaux = $this->calculerNombreCriteresNonSpatiaux();
if ($nombreStations >= $seuilMaillage && $nombreParametresNonSpatiaux == 0) {
// pas besoin de rechercher les stations correspondant a ces criteres
// recuperer les mailles se trouvant dans l'espace de recherche demande
$stations = $this->recupererMaillesDansBbox();
} else {
$requeteSql = $this->construireRequeteStations();
$stations = $this->getBdd()->recupererTous($requeteSql);
$zoom = $this->criteresRecherche->zoom;
$zoomMaxMaillage = Config::get('zoom_maximal_maillage');
if ($zoom <= $zoomMaxMaillage && count($stations) >= $seuilMaillage) {
// generer un maillage a partir des stations recuperees dans la base de donnees
$maillage = new Maillage($this->criteresRecherche->bbox, $zoom, 'sophy');
$maillage->genererMaillesVides();
$maillage->ajouterPoints($stations);
$stations = $maillage->formaterSortie();
}
}
// mettre en forme les informations au format JSON
$formateurJSON = new FormateurJson('sophy');
$donneesFormatees = $formateurJSON->formaterStations($stations);
return $donneesFormatees;
}
public function recupererObservations() {
$requeteSql = $this->construireRequeteObservations();
$observations = $this->getBdd()->recupererTous($requeteSql);
$this->recupererNumeroNomenclaturauxTaxons($observations);
$nomStation = $this->obtenirNomsStationsSurPoint();
$formateurJSON = new FormateurJson('sophy');
$donneesFormatees = $formateurJSON->formaterObservations($observations, $nomStation);
return $donneesFormatees;
}
private function calculerNombreCriteresNonSpatiaux() {
$nombreParametresNonSpatiaux = 0;
$criteresSpatiaux = array('zoom', 'bbox', 'longitude', 'latitude');
foreach ($this->criteresRecherche as $nomCritere => $valeur) {
if (!in_array($nomCritere, $criteresSpatiaux)) {
$nombreParametresNonSpatiaux ++;
}
}
return $nombreParametresNonSpatiaux;
}
 
 
 
// ------------------------------------------------------------------------ //
// Fonctions de construction des criteres de recherches pour la requete SQL //
// ------------------------------------------------------------------------ //
private function getBdd() {
if (!isset($this->bdd)) {
$this->bdd = new Bdd();
}
$this->bdd->requeter("USE ".Config::get('bdd_nom'));
return $this->bdd;
}
private function construireRequeteStations() {
$requete =
"SELECT DISTINCT lieu_station_nom AS nom, lieu_station_latitude AS latitude, ".
"lieu_station_longitude AS longitude, 'STATION' AS type_site ".
"FROM sophy_tapir WHERE 1 ".
$this->construireWhereDepartement().' '.
$this->construireWhereAuteur().' '.
$this->construireWhereReferentiel().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesBbox().' '.
"GROUP BY lieu_station_latitude, lieu_station_longitude";
return $requete;
}
private function construireRequeteObservations() {
$requete =
"SELECT observation_id AS id_obs, nom_scientifique_complet AS nomSci, ".
"observation_date AS date, lieu_station_nom AS lieu, observateur_nom_complet AS observateur ".
"FROM sophy_tapir WHERE 1 ".
$this->construireWhereAuteur().' '.
$this->construireWhereReferentiel().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesPoint().' '.
"ORDER BY nom_scientifique_complet, date, observateur";
return $requete;
}
private function construireWhereTaxon() {
$sql = '';
if (isset($this->criteresRecherche->taxon)) {
$taxon = $this->criteresRecherche->taxon;
$criteres = "nom_scientifique_complet LIKE ".$this->getBdd()->proteger($taxon['nom']."%");
$referentiel = new Referentiel($this->criteresRecherche->referentiel, $this->criteresRecherche->taxon);
$sousTaxons = $referentiel->recupererSousTaxons();
foreach ($sousTaxons as $sousTaxon) {
$criteres .= " OR nom_scientifique_complet LIKE ".$this->getBdd()->proteger($taxon['nom']."%");
}
$sql = "AND ($criteres)";
}
return $sql;
}
// TODO : completer le corps des methodes construire where pour referentiel et departement
private function construireWhereReferentiel() {
$sql = '';
return $sql;
}
private function construireWhereDepartement() {
$sql = '';
return $sql;
}
private function construireWhereAuteur() {
$sql = '';
if (isset($this->criteresRecherche->auteur)) {
$auteur = $this->getBdd()->proteger($this->criteresRecherche->auteur);
$sql = "AND observateur_nom_complet = $auteur";
}
return $sql;
}
private function construireWhereCoordonneesBbox() {
$bbox = $this->criteresRecherche->bbox;
$sql = "AND lieu_station_longitude BETWEEN ".$bbox['ouest']." AND ".$bbox['est']." ".
"AND lieu_station_latitude BETWEEN ".$bbox['sud']." AND ".$bbox['nord'];
return $sql;
}
private function construireWhereCoordonneesPoint() {
$sql = "AND lieu_station_latitude=".$this->criteresRecherche->latitude." ".
"AND lieu_station_longitude=".$this->criteresRecherche->longitude;
return $sql;
}
private function obtenirNomsStationsSurPoint() {
$requete = "SELECT DISTINCTROW lieu_station_nom FROM sophy_tapir WHERE 1 ".
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesPoint();
$stations = $this->getBdd()->recupererTous($requete);
$nomsStations = array();
foreach ($stations as $station) {
$nomsStations[] = $station['lieu_station_nom'];
}
return implode(', ', $nomsStations);
}
private function obtenirNombreStationsDansBbox() {
$bbox = $this->criteresRecherche->bbox;
$zoom = $this->criteresRecherche->zoom;
$requete =
"SELECT zoom, Sum(nombre_sites) AS total_points FROM mailles_sophy ".
"WHERE zoom=".$zoom." AND limite_sud<=".$bbox['nord']." AND limite_nord>=".$bbox['sud']." ".
"AND limite_ouest<=".$bbox['est']." AND limite_est>=".$bbox['ouest']." GROUP BY zoom";
$resultat = $this->getBdd()->recuperer($requete);
return $resultat['total_points'];
}
private function recupererMaillesDansBbox() {
$bbox = $this->criteresRecherche->bbox;
$zoom = $this->criteresRecherche->zoom;
$requete =
"SELECT zoom, position_latitude, position_longitude, limite_sud AS sud, limite_ouest AS ouest, ".
"limite_nord AS nord, limite_est AS est, nombre_sites AS points, 'MAILLE' AS type_site ".
"FROM mailles_sophy WHERE zoom=".$zoom." AND limite_sud<=".$bbox['nord']." ".
"AND limite_nord>=".$bbox['sud']." AND limite_ouest<=". $bbox['est']." ".
"AND limite_est>=".$bbox['ouest'];
return $this->getBdd()->recupererTous($requete);
}
private function recupererNumeroNomenclaturauxTaxons(& $observations) {
for ($index = 0; $index < count($observations); $index ++) {
$taxon = isset($this->criteresRecherche->taxon) ? $this->criteresRecherche->taxon : null;
if (is_null($taxon) && strlen(trim($observations[$index]['nomSci'])) > 0) {
if (isset($this->criteresRecherche->taxon)) {
$taxon = $this->rechercherTaxonDansReferentiel($observations[$index]['nomSci'],
$this->criteresRecherche->referentiel);
} else {
$taxon = $this->obtenirNumeroTaxon($observations[$index]['nomSci']);
}
}
if (!is_null($taxon)) {
$observations[$index]['nn'] = $taxon['nn'];
$observations[$index]['num_referentiel'] = $taxon['referentiel'];
} else {
$observations[$index]['nn'] = '';
}
}
}
private function rechercherTaxonDansReferentiel($nomScientifique, $nomReferentiel) {
$referentiel = new Referentiel($nomReferentiel);
$taxon = $referentiel->obtenirNumeroNomenclatural($nomScientifique);
return $taxon;
}
private function obtenirNumeroTaxon($nomScientifique) {
$taxonTrouve = null;
$listeReferentiels = Referentiel::recupererListeReferentielsDisponibles();
foreach ($listeReferentiels as $nomReferentiel) {
$taxon = $this->rechercherTaxonDansReferentiel($nomScientifique, $nomReferentiel);
if (!is_null($taxon)) {
$taxonTrouve = $taxon;
break;
}
}
return $taxonTrouve;
}
}
 
?>
/trunk/services/configurations/config_floradata.ini
5,14 → 5,11
 
; Nom de la base utilisée.
bdd_nom = "tb_cel"
bdd_eflore = "tb_eflore"
 
; URL de base des services de ce projet
url_service="{ref:url_base}service:moissonnage:0.1/floradata"
 
; +------------------------------------------------------------------------------------------------------+
; Config spécifique au projet
; Noms des services disponibles pour ce projet
servicesDispo = "stations,observations"
 
[meta-donnees]
dureecache = 3600
/trunk/services/configurations/config_sophy.ini
9,10 → 9,6
; URL de base des services de ce projet
url_service="{ref:url_base}service:moissonnage:0.1/sophy"
 
; +------------------------------------------------------------------------------------------------------+
; Config spécifique au projet
; Noms des services disponibles pour ce projet
servicesDispo = "stations,observations"
 
[meta-donnees]
dureecache = 3600
/trunk/services/configurations/config.defaut.ini
66,8 → 66,23
; URL de base des services
url_service_base='{ref:url_base}service:moissonnage:0.1/'
 
 
 
; +------------------------------------------------------------------------------------------------------+
; Infos sur les controles a effectuer sur les cartes et les donnees a afficher
carte.limite_ouest = -180
carte.limite_est = 180
carte.limite_sud = -85.051129
carte.limite_nord = 85.051129
carte.zoom_minimal = 3
carte.zoom_maximal = 18
zoom_maximal_maillage = 13
seuil_maillage = 500
 
; +------------------------------------------------------------------------------------------------------+
; Autres informations
sourcesDispo = "cel,sophy"
referentielsDispo = "bdtfx_v1_01,bdtxa_v1_00"
sources_dispo = "floradata,sophy"
source_defaut = "floradata"
services_dispo = "stations,observations"
referentiels_dispo = "bdtfx_v1_01,bdtxa_v1_00"