Subversion Repositories eFlore/Applications.moissonnage

Compare Revisions

Ignore whitespace Rev 34 → Rev 33

/trunk/services/framework.php
File deleted
\ No newline at end of file
/trunk/services/bibliotheque/EnteteHttp.php
File deleted
\ No newline at end of file
/trunk/services/bibliotheque/FormateurWfs.php
File deleted
\ No newline at end of file
/trunk/services/bibliotheque/ResultatService.php
File deleted
\ No newline at end of file
/trunk/services/bibliotheque/squelettes/GetCapabilities.tpl.xml
File deleted
\ No newline at end of file
/trunk/services/bibliotheque/squelettes/GetFeature.tpl.xml
File deleted
/trunk/services/bibliotheque/squelettes/DescribeFeatureType.tpl.xml
File deleted
\ No newline at end of file
/trunk/services/bibliotheque/squelettes/Exception.tpl.xml
File deleted
\ No newline at end of file
/trunk/services/bibliotheque/FormateurJson.php
3,8 → 3,11
 
class FormateurJson {
private $sourceDonnees;
public function __construct() {}
public function __construct($source = '') {
$this->sourceDonnees = $source;
}
public function formaterStations($stations) {
11,76 → 14,74
$objetJSON = new StdClass();
$objetJSON->type = "FeatureCollection";
$objetJSON->stats = new StdClass();
$objetJSON->stats->source = array();
$objetJSON->stats->source = $this->sourceDonnees;
$objetJSON->stats->formeDonnees = '';
if (count($stations) > 0) {
$objetJSON->stats->formeDonnees = ($stations[0]['type_site'] == 'MAILLE') ? 'maille' : 'point';
}
$objetJSON->stats->stations = 0;
$objetJSON->stats->sites = 0;
$objetJSON->stats->observations = 0;
$objetJSON->features = array();
foreach ($stations as $station) {
$stationJSON = null;
$stationJSON = NULL;
if ($station['type_site'] == 'MAILLE') {
$stationJSON = $this->formaterMaille($station);
$objetJSON->stats->stations += array_sum($station['stations']);
$objetJSON->stats->observations += array_sum($station['observations']);
$objetJSON->stats->sites += $station['points'];
} else {
$objetJSON->stats->sites ++;
$stationJSON = $this->formaterPoint($station);
$objetJSON->stats->stations ++;
$objetJSON->stats->observations += $station['observations'];
}
$objetJSON->features[] = $stationJSON;
$this->ajouterSourcesAuxStats($station, $objetJSON->stats);
$objetJSON->stats->observations += $station['observations'];
if (!is_null($stationJSON)) {
$objetJSON->features[] = $stationJSON;
}
}
return $objetJSON;
}
private function ajouterSourcesAuxStats($station, & $stats) {
if ($station['type_site'] == 'MAILLE') {
foreach ($station['stations'] as $source => $nombreStations) {
if (!in_array($source, $stats->source)) {
$stats->source[] = $source;
}
}
} else {
if (!in_array($station['source'], $stats->source)) {
$stats->source[] = $station['source'];
}
}
}
private function formaterPoint(& $station) {
private function formaterPoint($station) {
$json = new StdClass();
$json->type = "Feature";
$json->geometry = new StdClass();
$json->properties = new StdClass();
$json->geometry->type = "Point";
$json->properties->source = $station['source'];
$json->properties->source = $this->sourceDonnees;
$json->properties->typeSite = $station['type_site'];
$json->geometry->coordinates = array($station['latitude'], $station['longitude']);
$codeInsee = isset($station['code_insee']) ? $station['code_insee'] : substr($station['ce_zone_geo'],-5);
$codeDepartement = $this->extraireCodeDepartement($codeInsee);
$nom = '';
if ($station['source'] != 'floradata') {
$json->properties->nom = trim($station['nom'])." ({$codeDepartement})";
if ($this->sourceDonnees == 'floradata' && $station['type_site'] == 'COMMUNE') {
$json->geometry->coordinates = array($station['lat_commune'], $station['lng_commune']);
} else {
$station['station'] = (is_null($station['station']) || strlen(trim($station['station'])) == 0)
? $station['zone_geo'] : $station['station'];
$nom = $station['type_site'] == 'COMMUNE' ? $station['zone_geo'] : $station['station'];
$json->properties->nom = trim($nom)." ({$codeDepartement})";
$json->geometry->coordinates = array($station['latitude'], $station['longitude']);
}
if ($this->sourceDonnees == 'floradata') {
$json->properties->nom = $this->construireNomStationFloradata($station);
} else {
$codeDepartement = $this->extraireCodeDepartement($station['code_insee']);
$json->properties->nom = trim($station['nom'])." ({$codeDepartement})";
}
return $json;
}
private function construireNomStation(& $station) {
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) {
$codeDepartement = substr($codeInsee, 0 ,3);
substr($codeInsee, 0 ,3);
}
return $codeDepartement;
}
99,26 → 100,20
array(floatval($maille['sud']), floatval($maille['ouest']))
);
$json->properties = new StdClass();
$json->properties->source = array();
foreach ($maille['stations'] as $source => $nombreStations) {
$json->properties->source[] = $source;
}
$json->properties->source = $this->sourceDonnees;
$json->properties->typeSite = 'MAILLE';
$json->properties->stations = $maille['stations'];
$json->properties->observations = $maille['observations'];
$json->properties->nombrePoints = $maille['points'];
return $json;
}
public function formaterObservations($observations) {
//print_r($observations); exit;
public function formaterObservations($observations, $nomSite) {
$objetJSON = new StdClass();
$objetJSON->site = trim($observations[0]['nom_station']);
$objetJSON->site = trim($nomSite);
$objetJSON->total = count($observations);
$objetJSON->observations = array();
foreach ($observations as $observation) {
$this->concatenerLieuObservation($observation);
$observationJson = new stdClass();
foreach ($observation as $colonne => $valeur) {
if ($colonne == 'nom_referentiel') {
127,38 → 122,31
$observationJson->$colonne = is_string($valeur) ? trim($valeur) : $valeur;
}
}
$this->formaterDateObservation($observationJson);
$objetJSON->observations[] = $observationJson;
}
return $objetJSON;
}
private function formaterDateObservation(& $observation) {
if (isset($observation->date) && strlen($observation->date) > 4) {
$dateFormatee = preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', $observation->date);
$observation->date = $dateFormatee;
}
}
private function genererUrlFicheEflore(& $observation) {
private function genererUrlFicheEflore($observation) {
$url = null;
if (strstr($observation['nom_referentiel'], 'bdtfx') !== false) {
if (strstr('bdtfx', $observation['nom_referentiel']) !== false) {
$url = 'http://www.tela-botanica.org/bdtfx-nn-'.$observation['nn'];
}
return $url;
}
private function concatenerLieuObservation(& $observation) {
$lieux = [];
if (!is_null($observation['lieudit'])) {
$lieux[] = $observation['lieudit'];
public function formaterMaillesVides($mailles) {
$objetJSON = new StdClass();
$objetJSON->type = "FeatureCollection";
$objetJSON->stats = new StdClass();
$objetJSON->stats->source = '';
$objetJSON->stats->formeDonnees = 'maille';
$objetJSON->stats->sites = 0;
$objetJSON->features = array();
foreach ($mailles as $maille) {
$objetJSON->features[] = $this->formaterMaille($maille);
}
if (!is_null($observation['milieu'])) {
$lieux[] = $observation['milieu'];
}
unset($observation['lieudit']);
unset($observation['milieu']);
$observation['lieu'] = implode(', ', $lieux);
return $objetJSON;
}
}
/trunk/services/bibliotheque/Maille.php
9,8 → 9,10
private $indexLatitude;
private $indexLongitude;
private $stations = array();
private $points = array();
private $nombrePoints;
private $observations = array();
private $nombreObservations;
public function __construct($sud, $ouest, $nord, $est, $indexLat, $indexLng) {
22,14 → 24,11
$this->indexLongitude = $indexLng;
}
public function ajouterStation($station, $source) {
if (!array_key_exists($source, $this->stations)) {
$this->stations[$source] = 1;
$this->observations[$source] = $station['observations'];
} else {
$this->stations[$source] += 1;
$this->observations[$source] += intval($station['observations']);
}
public function ajouterPoint($point) {
$this->points[] = $point;
$this->nombrePoints ++;
$this->observations[] = $point['observations'];
$this->nombreObservations += $point['observations'];
}
public function getLatitudeNord() {
56,12 → 55,12
return $this->indexLongitude;
}
public function getStations() {
return $this->stations;
public function getPoints() {
return $this->points;
}
public function getNombreStations() {
return count($this->stations);
public function getNombrePoints() {
return $this->nombrePoints;
}
public function getObservations() {
68,28 → 67,19
return $this->observations;
}
public function combinerMailles($maille, $sourceReference) {
if (is_array($maille['stations'])) {
foreach ($maille['stations'] as $source => $nombreStations) {
if (!array_key_exists($source, $this->stations)) {
$this->stations[$source] = $nombreStations;
$this->observations[$source] = $maille['observations'][$source];
} else {
$this->stations[$source] += $nombreStations;
$this->observations[$source] += $maille['observations'][$source];
}
}
} else {
if (!array_key_exists($sourceReference, $this->stations)) {
$this->stations[$sourceReference] = $maille['stations'];
$this->observations[$sourceReference] = $maille['observations'];
} else {
$this->stations[$sourceReference] += $maille['stations'];
$this->observations[$sourceReference] += $maille['observations'];
}
}
public function getNombreObservations() {
return $this->nombreObservations;
}
 
public function totalNonNul() {
return count($this->points) > 0;
}
public function combinerMailles(& $maille) {
$this->nombrePoints += $maille->nombre_sites;
$this->nombreObservations += $maille->nombre_observations;
}
}
 
?>
/trunk/services/bibliotheque/Referentiel.php
39,7 → 39,6
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;
88,30 → 87,46
if (is_null($this->bdd)) {
$this->bdd = new Bdd();
}
$nomBdd = Config::get('bdd_nom');
$nomBdd = Config::get('bdd_eflore');
if (is_null($nomBdd)) {
$nomBdd = Config::get('bdd_nom');
}
$this->bdd->requeter("USE ".$nomBdd);
return $this->bdd;
}
public function recupererSynonymesEtSousEspeces() {
public function recupererTaxonsSousEspeces($listeNn = null) {
$sousTaxons = array();
if (!is_null($this->taxon) && $this->taxon['rang'] >= Config::get('rang.espece')) {
if (!is_null($this->taxon) && $this->taxon['rang'] == Config::get('rang.espece')) {
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 ".
$this->champs['nt']."=".$this->taxon['nt']." OR hierarchie LIKE '%-".$this->champs['nn']."-%'";
$sousTaxons = $this->getBdd()->recupererTous($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->recupererTaxonsSousEspeces($nouvelleListeNn));
}
}
return $sousTaxons;
}
public function recupererGenres() {
public function recupererTaxonsFamilles() {
$sousTaxons = array();
if (!is_null($this->taxon) && $this->taxon['rang'] == Config::get('rang.famille')) {
if (!is_null($this->taxon) && $this->taxon['rang'] == Config::get('rang.genre')) {
$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=".$this->taxon['nn']." AND num_nom=".$this->champs['nn'];
"SELECT ".$this->champs['nn']." AS nn, ".$this->champs['nt']." AS nt, ".
$this->champs['ns']." AS nom, rang FROM ".$this->nomComplet." WHERE ".
"num_tax_sup=".$this->taxon['nn']." AND num_nom=".$this->champs['nn'];
$sousTaxons = $this->getBdd()->recupererTous($requete);
}
return $sousTaxons;
134,13 → 149,10
return $tableau;
}
public function obtenirNumeroNomenclatural($nomScientifique, $numeroNomenclatural = null) {
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;
if (!is_null($numeroNomenclatural) || strlen($numeroNomenclatural) > 0) {
$requete .= " OR ".$this->champs['nn']."={$numeroNomenclatural}";
}
$taxon = $this->getBdd()->recuperer($requete);
if ($taxon == false) {
$taxon = null;
151,5 → 163,4
}
}
 
?>
/trunk/services/bibliotheque/Maillage.php
3,47 → 3,40
 
class Maillage {
private $bbox = array();
private $zoom = '';
private $source = '';
private $bbox;
private $zoom;
private $indexLongitude = array();
private $indexLatitude = array();
private $mailles = array();
private $indexLongitude;
private $indexLatitude;
private $mailles;
private $bdd = null;
public function __construct($bbox, $zoom, $source) {
$this->bbox = $this->calculerLimiteBboxGlobale($bbox);
$this->zoom = $zoom;
$this->source = $source;
public function __construct($bbox, $zoom) {
$this->bbox = $bbox;
$this->zoom = $zoom;
$this->indexLongitude = array();
$this->indexLatitude = array();
$this->indexLatitude = array();
$this->mailles = array();
}
private function calculerLimiteBboxGlobale($bbox) {
$bboxGlobale = $bbox[0];
for ($index = 1; $index < count($bbox); $index ++) {
if ($bbox[$index]['ouest'] < $bboxGlobale['ouest']) {
$bboxGlobale['ouest'] = $bbox[$index]['ouest'];
}
if ($bbox[$index]['sud'] < $bboxGlobale['sud']) {
$bboxGlobale['sud'] = $bbox[$index]['sud'];
}
if ($bbox[$index]['est'] > $bboxGlobale['est']) {
$bboxGlobale['est'] = $bbox[$index]['est'];
}
if ($bbox[$index]['nord'] > $bboxGlobale['nord']) {
$bboxGlobale['nord'] = $bbox[$index]['nord'];
}
public function __destruct() {
while (count($this->indexLatitude) > 0) {
array_pop($this->indexLatitude);
}
return $bboxGlobale;
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) {
58,6 → 51,7
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'].")";
72,6 → 66,7
") 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']);
79,36 → 74,51
$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_nom_eflore');
$nomBdd = Config::get('bdd_eflore');
if (is_null($nomBdd)) {
$nomBdd = Config::get('bdd_nom');
}
$this->bdd->requeter("USE ".$nomBdd);
return $this->bdd;
}
public function ajouterStations(& $stations) {
foreach ($stations as $station) {
$longitude = $station['longitude'];
$latitude = $station['latitude'];
public function ajouterPoints(& $points) {
foreach ($points as $point) {
list($longitude, $latitude) = $this->obtenirCoordonneesPoint($point);
list($indexLongitude, $indexLatitude) = $this->rechercherIndexMaille($longitude, $latitude);
$this->mailles[$indexLatitude][$indexLongitude]->ajouterStation($station, $this->source);
$this->mailles[$indexLatitude][$indexLongitude]->ajouterPoint($point);
}
}
public function ajouterMailles(& $mailles) {
foreach ($mailles as $maille) {
$longitude = ($maille['ouest'] + $maille['est']) / 2;
$latitude = ($maille['sud'] + $maille['nord']) / 2;
$longitude = ($maille->longitudeOuest + $maille->longitudeEst) / 2;
$latitude = ($maille->latitudeSud + $maille->latitudeNord) / 2;
list($indexLongitude, $indexLatitude) = $this->rechercherIndexMaille($longitude, $latitude);
$this->mailles[$indexLatitude][$indexLongitude]->combinerMailles($maille, $this->source);
$this->mailles[$indexLatitude][$indexLongitude]->combinerMailles($maille);
}
}
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;
118,25 → 128,26
}
while ($indexLongitude < count($this->indexLongitude) - 1
&& $this->mailles[$indexLatitude][$indexLongitude]->getLongitudeEst() < $longitude) {
$indexLongitude ++;
$indexLongitude ++;
}
return array($indexLongitude, $indexLatitude);
}
 
public function formaterSortie() {
public function formaterSortie($toutesLesMailles = false) {
$mailles_resume = array();
foreach ($this->mailles as $ligne) {
foreach ($ligne as $maille) {
$nombreStations = $maille->getNombrestations();
if ($nombreStations > 0) {
$nombrePoints = $maille->getNombrePoints();
if ($nombrePoints > 0 || $toutesLesMailles) {
$mailles_resume[] = array(
'type_site' => 'MAILLE',
'zoom' => $this->zoom,
'sud' => $maille->getLatitudeSud(),
'ouest' => $maille->getLongitudeOuest(),
'nord' => $maille->getLatitudeNord(),
'est' => $maille->getLongitudeEst(),
'stations' => $maille->getStations(),
'observations' => $maille->getObservations()
'points' => $nombrePoints,
'observations' => $maille->getNombreObservations(),
'type_site' => 'MAILLE'
);
}
}
146,6 → 157,7
return $mailles_resume;
}
 
}
 
?>
/trunk/services/bibliotheque/ReponseHttp.php
2,11 → 2,16
 
class ReponseHttp {
 
private $resultatService = null;
private $mime = 'application/json';
private $encodage = 'utf-8';
private $codeHttp = RestServeur::HTTP_CODE_OK;
private $corps = '';
private $erreurs = array();
 
public function __construct() {
$this->resultatService = new ResultatService();
if (function_exists('json_decode') == false){
require_once (dirname(__FILE__).'/JSON.php');
function json_decode($content, $assoc = false){
27,21 → 32,18
}
}
 
public function setResultatService($resultat) {
if (!($resultat instanceof ResultatService)) {
$this->resultatService->corps = $resultat;
} else {
$this->resultatService = $resultat;
}
$this->corps = $resultat;
}
 
public function getCorps() {
if ($this->etreEnErreur()) {
$this->resultatService->corps = $this->erreurs[0]['message'];
$this->corps = $this->erreurs[0]['message'];
} else {
$this->transformerReponseCorpsSuivantMime();
}
return $this->resultatService->corps;
return $this->corps;
}
 
public function ajouterErreur(Exception $e) {
49,16 → 51,17
}
 
public function emettreLesEntetes() {
$enteteHttp = new EnteteHttp();
if ($this->etreEnErreur()) {
$enteteHttp->code = $this->erreurs[0]['entete'];
$enteteHttp->mime = 'text/html';
$codeHttp = $this->erreurs[0]['entete'];
$encodage = 'utf-8';
$mime = 'text/html';
} else {
$enteteHttp->encodage = $this->resultatService->encodage;
$enteteHttp->mime = $this->resultatService->mime;
$codeHttp = $this->codeHttp;
$encodage = $this->encodage;
$mime = $this->mime;
}
header("Content-Type: $enteteHttp->mime; charset=$enteteHttp->encodage");
RestServeur::envoyerEnteteStatutHttp($enteteHttp->code);
header("Content-Type: $mime; charset=$encodage");
RestServeur::envoyerEnteteStatutHttp($codeHttp);
}
 
private function etreEnErreur() {
70,14 → 73,14
}
 
private function transformerReponseCorpsSuivantMime() {
switch ($this->resultatService->mime) {
switch ($this->mime) {
case 'application/json' :
if (isset($_GET['callback'])) {
$contenu = $_GET['callback'].'('.json_encode($this->resultatService->corps).');';
$contenu = $_GET['callback'].'('.json_encode($this->corps).');';
} else {
$contenu = json_encode($this->resultatService->corps);
$contenu = json_encode($this->corps);
}
$this->resultatService->corps = $contenu;
$this->corps = $contenu;
break;
}
}
/trunk/services/bibliotheque/VerificateurParametres.php
14,9 → 14,8
* 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)
*
* - stations : liste de points d'observations. C'est une serie de stations qui est passee en parametres
* de cette maniere, separees entre elles par un seperateur vertical |. Chaque station est decrite
* par sa source de donnees, le type de site et ses coordonnees longitude et latitude.
* - 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)
32,12 → 31,12
*
* - auteur : l'auteur de l'observation
*
* - type_site : pour les observations, le type de point correspondant a la station cliquee
* (STATION ou COMMUNE). Cela indique le niveau de precision ramene aux coordonnees des observations
*
* - date_debut et date_fin : intervalle de dates d'observation. On verifie que ce sont des dates valides
* et que date_debut <= date_fin. Le programme peut accepter la presence d'un seul de ces deux
* parametres : soit une date de debut, soit une date de fin
*
* - nb_jours : valeur entiere qui indique de recuperer les observations effectuees ou transmises
* sur les derniers jours avant la date d'execution du script
*
* 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
71,7 → 70,9
public function __construct($parametres) {
foreach ($parametres as $nomParametre => $valeur) {
$this->parametres[$nomParametre] = $valeur;
if ($nomParametre != 'source') {
$this->parametres[$nomParametre] = $valeur;
}
}
$this->bboxMonde = array(
'ouest' => floatval(Config::get('carte.limite_ouest')),
89,7 → 90,9
break;
case 'bbox' : $this->traiterParametreBbox($valeur);
break;
case 'stations' : $this->traiterParametreStations($this->parametres['stations']);
case 'longitude' :
case 'latitude' : $this->traiterParametresCoordonnees($this->parametres['longitude'],
$this->parametres['latitude']);
break;
case 'dept' : $this->traiterParametreDepartement($valeur);
break;
115,7 → 118,6
}
break;
}
case 'format' : $this->validation->format = strtolower($valeur); break;
// autres parametres ==> les ignorer
default : break;
}
162,20 → 164,7
}
}
private function traiterParametreBbox($chaineBbox) {
$listeBbox = explode('|', trim($chaineBbox));
$critereBbox = array();
foreach ($listeBbox as $bbox) {
$bboxVerifiee = $this->verifierCoordonneesBbox($bbox);
if (!is_null($bboxVerifiee)) {
$critereBbox[] = $bboxVerifiee;
}
}
$this->validation->bbox = $critereBbox;
}
private function verifierCoordonneesBbox($bbox) {
$bboxVerifiee = null;
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) {
192,7 → 181,7
}
// verifier que les coordonnees de chaque bord de la bbox sont valides
if ($this->estUneBboxValide($bbox)) {
$bboxVerifiee = $bbox;
$this->validation->bbox = $bbox;
} else {
$message = "Certaines coordonnées de la bounding box sont situés en dehors des limites ".
"de notre monde";
199,7 → 188,6
$this->ajouterErreur($message);
}
}
return $bboxVerifiee;
}
private function estUneBboxValide($bbox) {
210,34 → 198,13
&& floatval($bbox['sud']) >= $monde['sud'] && floatval($bbox['sud']) <= $monde['nord']);
}
private function traiterParametreStations($listeStations) {
$stations = explode('|', trim($listeStations));
$critereStations = array();
foreach ($stations as $station) {
preg_match("/([a-z]+):([a-z]+):(-?\d{1,3}.\d+),(-?\d{1,3}.\d+)/", $station, $matches);
if (count($matches) < 5) {
$message = "Les données transmises sur la station à interroger sont incomplètes. ".
"Le format suivant doit être respecté : source:type_site:longitude:latitude";
$this->ajouterErreur($message);
} else {
$matches = array_splice($matches, 1, count($matches));
$this->verifierCoordonneesStation($matches);
$this->verifierSourceStation($matches[0]);
$this->verifierTypeStation($matches[1]);
$critereStations[] = $matches;
}
}
$this->validation->stations = $critereStations;
}
private function verifierCoordonneesStation(& $station) {
$longitude = floatval($station[2]);
$latitude = floatval($station[3]);
private function traiterParametresCoordonnees($longitude, $latitude) {
if ($this->sontDesCoordonneesValides($longitude, $latitude)) {
$station[2] = $latitude;
$station[3] = $longitude;
$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";
$message = "Les coordonnees du point passées en parametres sont en dehors des limites de ".
"notre monde";
$this->ajouterErreur($message);
}
}
248,23 → 215,6
&& floatval($latitude) >= $monde['sud'] && floatval($latitude) <= $monde['nord']);
}
private function verifierTypeStation($typeStation) {
$typeStationsValides = array('station', 'commune');
if (!in_array($typeStation, $typeStationsValides)) {
$message = "'$typeStation' n'est pas un type de station reconnu. Sont acceptés seulement 'station' et 'commune'.";
$this->ajouterErreur($message);
}
}
private function verifierSourceStation($source) {
$sourcesARequeter = explode(',', trim($this->parametres['source']));
if (!in_array($source, $sourcesARequeter)) {
$message = "La source '$source' n'est pas listée dans le paramètre source de l'URL (sont disponibles ".
implode(',', $sourcesARequeter).").";
$this->ajouterErreur($message);
}
}
private function traiterParametreDepartement($numeroDepartement) {
if ($numeroDepartement != '*') {
$departements = explode(',', trim($numeroDepartement));
450,7 → 400,7
private function verifierPresenceParametreSpatial() {
$presenceParametreSpatial = false;
if (isset($this->parametres['bbox'])
|| (isset($this->parametres['stations']))) {
|| (isset($this->parametres['longitude']) && isset($this->parametres['latitude']))) {
$presenceParametreSpatial = true;
}
if ($presenceParametreSpatial == false) {
/trunk/services/modules/0.1/commun/Commun.php
1,288 → 1,35
<?php
 
/**
*
* Classe principale du web service qui peut traiter des requetes provenant d'un navigateur web
* (stations dans bbox ou observations sur un point), ou d'un client SIG via appel au protocole/service WFS
* (demande d'observations par stations selon des filtres optionnels). Le web service analyse et verifie
* les parametres de l'URL de la requete qu'il recoit. S'ils sont tous valides, il va appeler une autre classe
* pour recuperer les informations demandees dans les differentes sources de donnees.
* Les donnees recuperees sont ensuite combinees si plusieurs sources sont demandees et mises en forme
* au format de sortie. Les formats de sortie utilises sont le GeoJSON (extension de JSON pour les donnees
* geographiques) en destination des navigateurs web et le GML adapte au service WFS pour les clients SIG.
* Dans le cas ou des erreurs sont levees, le web service renvoie un message d'erreur expliquant le probleme
* recnontre dans son fonctionnement.
*
*
* @package framework-0.4
* @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 Commun {
private $parametres = array();
private $ressources = array();
private $nomSource = '';
private $nomService = '';
private $parametres;
private $nomSource;
private $nomService;
private $verificateur = null;
private $parametresRecherche = null;
private $retour = array();
private $verificateur;
private $parametresRecherche;
const MIME_WFS = 'text/xml';
public function consulter($ressources, $parametres) {
$this->recupererRessourcesEtParametres($ressources, $parametres);
$retour = null;
if (in_array("wfs", $ressources)) {
$retour = $this->traiterRequeteWfs();
} else {
$retour = $this->traiterRequeteNavigateur();
}
return $retour;
}
/*********************************************/
// Verification parametres URL non-WFS
private function traiterRequeteWfs() {
$retour = null;
try {
$this->parametresRecherche = new StdClass();
$this->traiterParametreOperation();
if ($this->parametresRecherche->operation != 'GetCapabilities') {
$this->traiterParametreSource();
}
if ($this->parametresRecherche->operation == 'GetFeature') {
$retour = $this->getFeature();
} else {
$formateurWfs = new FormateurWfs();
$nomMethode = 'formater'.$this->parametresRecherche->operation;
$parametre = isset($this->parametresRecherche->sources)
? $this->parametresRecherche->sources : null;
$retour = new ResultatService();
$retour->mime = self::MIME_WFS;
$retour->corps = $formateurWfs->$nomMethode($parametre);
}
} catch (Exception $erreur) {
$formateurWfs = new FormateurWfs();
$retour = new ResultatService();
$retour->mime = self::MIME_WFS;
$retour->corps = $formateurWfs->formaterException($erreur);
}
return $retour;
}
private function getFeature() {
if (array_key_exists('bbox', $this->parametres)) {
$this->traiterParametreBbox();
} elseif (array_key_exists('filter', $this->parametres)) {
$this->traiterParametreFilter();
}
$this->recupererStationsWfs();
$formateurWfs = new FormateurWfs();
$retour = new ResultatService();
$retour->mime = self::MIME_WFS;
$retour->corps = $formateurWfs->formaterGetFeature($this->retour, $this->parametresRecherche->sources);
return $retour;
}
private function traiterParametreOperation() {
if ($this->verifierExistenceParametre('request')) {
if (!$this->estOperationWfsAutorisee()) {
$message = "L'opération '".$this->parametres['request']."' n'est pas autorisée.\n".
"Les opérations suivantes sont permises par le service : ".Config::get('operations_wfs');
if (!$this->verifierExistenceSourcesDonnees()) {
$message = "Source de donnees indisponible";
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
} else {
$this->parametresRecherche->operation = $this->parametres['request'];
}
}
}
private function verifierExistenceParametre($nomParametre) {
$estParametreExistant = false;
if (!array_key_exists($nomParametre, $this->parametres)) {
$message = "Le paramètre nom de l'opération '{$nomParametre}' ".
"n'a pas été trouvé dans la liste des paramètres.";
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
} else {
$estParametreExistant = true;
}
return $estParametreExistant;
}
private function estOperationWfsAutorisee() {
$operationsWfsService = explode(',' , Config::get('operations_wfs'));
return (in_array($this->parametres['request'], $operationsWfsService));
}
private function traiterParametreSource() {
// le parametre source (typename) est optionnel par defaut
if (array_key_exists('typename', $this->parametres)) {
$sources = explode(',', $this->parametres['typename']);
$estSourceValide = true;
foreach ($sources as $source) {
if (!$this->verifierExistenceSourcesDonnees($source)) {
$message = "Source de donnees '{$source}' indisponible. Les sources disponibles sont : ".
Config::get('sources_dispo');
$estSourceValide = false;
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
}
}
if ($estSourceValide) {
$this->parametresRecherche->sources = $sources;
}
}
}
private function traiterParametreBbox() {
$bboxVerifiee = $this->verifierCoordonneesBbox($this->parametres['bbox']);
if (is_array($bboxVerifiee) && count($bboxVerifiee) == 4) {
$this->parametresRecherche->bbox = array($bboxVerifiee);
}
}
private function verifierCoordonneesBbox($bbox) {
$bboxVerifiee = null;
// 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.";
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
} else {
$coordonnees = explode(',', $bbox);
$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)) {
$bboxVerifiee = $bbox;
} else {
$message = "Certaines coordonnées de la bounding box sont situés en dehors des limites ".
"de notre monde";
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
}
}
return $bboxVerifiee;
}
private function estUneBboxValide($bbox) {
$monde = 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'))
);
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 traiterParametreFilter() {
// la valeur du parametre filter est une chaine de texte qui compose en realite un document XML
// plus d'infos a l'URL suivante : http://mapserver.org/fr/ogc/filter_encoding.html
$filtreTexte = $this->recupererTexteParametreFilter();
$documentXML = new DomDocument();
$documentXML->loadXML($filtreTexte);
$filtres = $documentXML->documentElement->childNodes;
for ($index = 0; $index < $filtres->length; $index ++) {
$this->verifierFiltre($filtres->item($index));
}
}
private function recupererTexteParametreFilter() {
$parametresUrl = explode("&", $_SERVER['QUERY_STRING']);
$filtreTexte = '';
foreach ($parametresUrl as $parametre) {
list($cle, $valeur) = explode("=", $parametre);
if ($cle == 'filter') {
$filtreTexte = rawurldecode($valeur);
}
}
return $filtreTexte;
}
private function verifierFiltre($filtre) {
$operateursAcceptes = explode(',', Config::get('operateurs_wfs'));
$nomOperateur = $filtre->tagName;
if (!in_array($nomOperateur, $operateursAcceptes)) {
$message = "Le filtre '$nomOperateur' n'est pas pris en compte par le serrvice. ".
"Les opérateurs acceptés sont :".implode(', ', $operateursAcceptes);
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
} else {
if ($nomOperateur == 'BBOX') {
$bboxUrl = $filtre->lastChild->nodeValue;
$bboxVerifiee = $this->verifierCoordonneesBbox($bboxUrl);
$this->parametresRecherche->bbox = array($bboxVerifiee);
} else {
$this->traiterOperateurScalaire($filtre);
}
}
}
private function traiterOperateurScalaire($filtre) {
$nomOperateur = $filtre->tagName;
$champ = $filtre->childNodes->item(0)->nodeValue;
if ($champ != Config::get('champ_filtrage_wfs')) {
$message = "Le filtre ne peut pas être appliqué sur le champ '$champ'. ".
"Il est seulement accepté sur le champ '".Config::get('champ_filtrage_wfs')."'";
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
} else {
$valeur = $filtre->childNodes->item(1)->nodeValue;
$operateur = $nomOperateur == 'PropertyIsEqualTo' ? "=" : "LIKE";
$this->parametresRecherche->filtre = array("champ" => $champ, "operateur" => $operateur,
"valeur" => $valeur);
}
}
private function recupererStationsWfs() {
$this->nomMethode = $this->ressources[0];
foreach ($this->parametresRecherche->sources as $source) {
$source = trim($source);
$resultat = $this->traiterSource($source);
$this->ajouterResultat($resultat, $source);
}
}
/*********************************************/
// Verification parametres URL non-WFS
private function traiterRequeteNavigateur() {
$retour = null;
try {
if (!$this->estParametreSourceExistant()) {
$message = "Le paramètre source de données n'a pas été indiqué.";
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
} else {
$this->verifierParametres();
$listeSources = explode(',', $this->parametres['source']);
foreach ($listeSources as $source) {
$source = trim($source);
$resultat = $this->traiterSource($source);
$this->ajouterResultat($resultat, $source);
if ($this->ressources[0] == 'mailles') {
$retour = $this->recupererMaillage();
} else {
$this->chargerNomSource();
$this->chargerNomService();
$retour = $this->executerServicePourSource();
}
}
$formateur = new FormateurJson();
$nomMethode = 'formater'.ucfirst($this->ressources[0]);
$retour = new ResultatService();
$retour->corps = $formateur->$nomMethode($this->retour);
} catch (Exception $erreur) {
$retour = $erreur;
$retour = $erreur;
}
return $retour;
}
289,24 → 36,18
private function recupererRessourcesEtParametres($ressources, $parametres) {
$this->ressources = $ressources;
$this->parametres = array();
foreach ($parametres as $nomParametre => $valeur) {
$this->parametres[strtolower($nomParametre)] = $valeur;
}
$this->parametres = $parametres;
}
private function estParametreSourceExistant() {
$parametreExiste = false;
if (isset($this->parametres['source'])) {
$parametreExiste = true;
}
return $parametreExiste;
}
private function verifierExistenceSourcesDonnees($source) {
private function verifierExistenceSourcesDonnees() {
$sourcesDisponibles = explode(',', Config::get('sources_dispo'));
$estDisponible = false;
if (in_array($source, $sourcesDisponibles)) {
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;
322,23 → 63,11
}
}
private function traiterSource($source) {
$retour = array();
if (!$this->verifierExistenceSourcesDonnees($source)) {
$message = "Source de donnees indisponible";
throw new Exception($message, RestServeur::HTTP_CODE_RESSOURCE_INTROUVABLE);
} else {
$this->chargerNomService($source);
$retour = $this->executerServicePourSource($source);
}
return $retour;
}
private function recupererParametresRecherche() {
$this->parametresRecherche = $this->verificateur->renvoyerResultatVerification();
}
private function chargerNomSource($source) {
private function chargerNomSource() {
if (isset($this->parametres['source'])) {
$this->nomSource = $this->parametres['source'];
} else {
346,13 → 75,20
}
}
private function chargerNomService($source) {
$this->nomService = ($source == 'floradata' ? 'Floradata' : 'Moissonnage').'Formateur';
Projets::chargerConfigurationSource($source);
private function chargerNomService() {
$this->nomService = ucfirst($this->parametres['source']) . 'Formateur';
Projets::chargerConfigurationSource($this->parametres['source']);
}
private function executerServicePourSource($source) {
$objetTraitement = new $this->nomService($this->parametresRecherche, $source);
private function recupererMaillage() {
$maillage = new Maillage($this->parametresRecherche->bbox, $this->parametresRecherche->zoom);
$maillage->genererMaillesVides();
$formateurJSON = new FormateurJson();
return $formateurJSON->formaterMaillesVides($maillage->formaterSortie(true));
}
private function executerServicePourSource() {
$objetTraitement = new $this->nomService($this->parametresRecherche);
$methode = $this->genererNomMethodeAExecuter();
return $objetTraitement->$methode();
}
361,44 → 97,6
return 'recuperer' . ucfirst($this->ressources[0]);
}
private function ajouterResultat(& $resultat, $source) {
if (count($this->retour) > 0) {
if ($this->ressources[0] == 'stations' && count($resultat) > 0
&& $this->doitTransformerTypeDonnees($resultat)) {
$this->combinerResultats($resultat, $source);
} else {
$this->retour = array_merge($this->retour, $resultat);
}
} else {
$this->retour = array_merge($this->retour, $resultat);
}
}
private function doitTransformerTypeDonnees(& $resultat) {
return ($this->parametresRecherche->zoom <= Config::get('zoom_maximal_maillage') &&
(($resultat[0]['type_site'] == 'MAILLE' || $this->retour[0]['type_site'] == 'MAILLE')
|| ($resultat[0]['type_site'] != 'MAILLE' && $this->retour[0]['type_site'] != 'MAILLE'
&& count($resultat) + count($this->retour) > Config::get('seuil_maillage')))
);
}
private function combinerResultats(& $resultat, $source) {
$maillage = new Maillage($this->parametresRecherche->bbox, $this->parametresRecherche->zoom, $source);
$maillage->genererMaillesVides();
if ($resultat[0]['type_site'] == 'MAILLE') {
$maillage->ajouterMailles($resultat);
} else {
$maillage->ajouterStations($resultat);
}
if ($this->retour[0]['type_site'] == 'MAILLE') {
$maillage->ajouterMailles($this->retour);
} else {
$maillage->ajouterStations($this->retour);
}
$this->retour = $maillage->formaterSortie();
}
 
}
 
?>
/trunk/services/modules/0.1/sources/MoissonnageFormateur.php
File deleted
\ No newline at end of file
/trunk/services/modules/0.1/sources/FloradataFormateur.php
22,7 → 22,7
*
* Les donnees seront renvoyees au format JSON
*
* @package framework-0.4
* @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>
32,15 → 32,75
*/
 
 
final class FloradataFormateur extends Formateur {
class FloradataFormateur {
final protected function construireRequeteStations() {
$condition = "(longitude IS NULL OR latitude IS NULL OR (longitude=0 AND latitude=0) ".
"OR longitude>180 OR latitude>90 OR mots_cles_texte LIKE '%sensible%')";
private $criteresRecherche;
private $bdd;
public function __construct($criteresRecherche) {
$this->criteresRecherche = $criteresRecherche;
}
public function recupererStations() {
$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) {
$maillage = new Maillage($bbox, $zoom);
$maillage->genererMaillesVides();
$maillage->ajouterPoints($stations);
$stations = $maillage->formaterSortie();
}
$formateurJSON = new FormateurJson('floradata');
$donneesFormatees = $formateurJSON->formaterStations($stations);
return $donneesFormatees;
}
public function recupererObservations() {
$requeteSql = $this->construireRequeteObservations();
$observations = $this->getBdd()->recupererTous($requeteSql);
$nomSite = $this->obtenirNomStation();
$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() {
$bbox = $this->criteresRecherche->bbox;
$selectTypeSite =
"IF(".
"(longitude IS NULL OR latitude IS NULL) ".
"OR (longitude=0 AND latitude=0) ".
"OR (mots_cles_texte LIKE '%sensible%') ".
"OR NOT (".
"longitude BETWEEN ".$bbox['ouest']." AND ".$bbox['est']." ".
"AND latitude BETWEEN ".$bbox['sud']." AND ".$bbox['nord'].
")".
", 'COMMUNE', 'STATION'".
")";
$requete =
"SELECT COUNT(id_observation) AS observations, ce_zone_geo, zone_geo, station, ".
"IF({$condition}, wgs84_latitude, latitude) AS latitude, IF({$condition}, wgs84_longitude, longitude) ".
"AS longitude, IF({$condition}, 'COMMUNE', 'STATION') AS type_site, 'floradata' AS source ".
"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().' '.
49,16 → 109,15
$this->construireWhereReferentiel().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesBbox().' '.
"GROUP BY IF({$condition},wgs84_longitude,longitude), IF({$condition},wgs84_latitude,latitude)";
"GROUP BY longitude, latitude, wgs84_longitude, wgs84_latitude";
return $requete;
}
final protected function construireRequeteObservations() {
private function construireRequeteObservations() {
$requete =
"SELECT id_observation AS id_obs, nom_sel_nn AS nn, nom_referentiel, lieudit, milieu, ".
"(DATE(IF(date_observation != '0000-00-00 00:00:00', date_observation, date_transmission))) AS date, ".
"CONCAT(prenom_utilisateur, ' ', nom_utilisateur) AS observateur, ce_utilisateur AS observateurId, ".
"IF(nom_sel IS NULL, 'A identifier',nom_sel) AS nomSci, 'floradata' AS projet ".
"SELECT id_observation AS id_obs, nom_ret_nn AS nn, nom_ret AS nomSci, ".
"Date(date_observation) 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().' '.
65,38 → 124,24
$this->construireWhereDate().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesPoint().' '.
"ORDER BY IF(nom_sel IS NULL, 'A identifier',nom_sel), date, observateur";
"ORDER BY nom_ret, date, observateur";
return $requete;
}
final protected function construireRequeteWfs() {
$condition = "(longitude IS NULL OR latitude IS NULL OR (longitude=0 AND latitude=0) ".
"OR longitude>180 OR latitude>90 OR mots_cles_texte LIKE '%sensible%')";
$requete =
"SELECT nom_sel AS taxon, ce_zone_geo, zone_geo, station, 'floradata' AS source, ".
"IF({$condition}, wgs84_latitude, latitude) AS latitude, IF({$condition}, wgs84_longitude, longitude) ".
"AS longitude, IF({$condition}, 'COMMUNE', 'STATION') AS type_site ".
"FROM cel_obs LEFT JOIN cel_zones_geo cz ON ce_zone_geo=id_zone_geo ".
"WHERE transmission=1 ".
$this->construireWhereCoordonneesBbox().' '.
$this->construireWhereNomScientifique().' '.
"ORDER BY IF({$condition},wgs84_longitude,longitude), IF({$condition},wgs84_latitude,latitude)";
return $requete;
}
private function construireWhereTaxon() {
protected function construireWhereTaxon() {
$sql = '';
if (isset($this->criteresRecherche->taxon)) {
$taxons = $this->criteresRecherche->taxon;
$criteres = array();
foreach ($taxons as $taxon) {
if ($taxon['rang'] == Config::get('rang.famille')) {
$nomRang = $this->getNomRang($taxon);
if ($nomRang == 'genre') {
$criteres[] = "famille=".$this->getBdd()->proteger($taxon['nom']);
} elseif ($taxon['rang'] == Config::get('rang.genre')) {
$criteres[] = "nom_sel LIKE ".$this->getBdd()->proteger($taxon['nom']." %");
} else {
$sousTaxons = $this->concatenerSynonymesEtSousEspeces($taxon);
$criteres[] = "nt IN (".implode(',', $sousTaxons).")";
$criteres[] = "nom_ret LIKE ".$this->getBdd()->proteger($taxon['nom']."%");
if ($nomRang == 'espece') {
$criteres = array_merge($criteres, $this->concatenerTaxonsSousEspeces($taxon));
}
}
}
$sql = "AND (".implode(' OR ',array_unique($criteres)).")";
103,17 → 148,35
}
return $sql;
}
 
private function concatenerSynonymesEtSousEspeces($taxon) {
protected function getNomRang($taxon) {
$nomsRangs = array('famille', 'genre', 'espece', 'sous_espece');
for ($index = 0; $index < count($nomsRangs)
&& Config::get("rang.".$nomsRangs[$index]) != $taxon['rang']; $index ++);
$position = $index == count($nomsRangs) ? count($nomsRangs)-1 : $index;
return $nomsRangs[$position];
}
protected function concatenerTaxonsSousEspeces($taxon) {
$referentiel = new Referentiel($this->criteresRecherche->referentiel, $taxon);
$sousTaxons = $referentiel->recupererSynonymesEtSousEspeces();
$sousTaxons = $referentiel->recupererTaxonsSousEspeces();
$criteres = array();
foreach ($sousTaxons as $sousTaxon) {
$criteres[] = "nt=".$sousTaxon['nt'];
$criteres[] = "nom_ret LIKE ".$this->getBdd()->proteger($sousTaxon['nom']."%");
}
return array_unique($criteres);
return $criteres;
}
protected function concatenerTaxonsFamilles($taxon) {
$referentiel = new Referentiel($this->criteresRecherche->referentiel, $taxon);
$sousTaxons = $referentiel->recupererTaxonsFamilles();
$criteres = array();
foreach ($sousTaxons as $sousTaxon) {
$criteres[] = "nom_ret LIKE ".$this->getBdd()->proteger($sousTaxon['nom']."%");
}
return $criteres;
}
private function construireWhereReferentiel() {
$sql = '';
if (isset($this->criteresRecherche->referentiel) && !isset($this->criteresRecherche->taxon)) {
149,7 → 212,7
$sql = '';
if (isset($this->criteresRecherche->nbJours)) {
$nbJours = $this->criteresRecherche->nbJours;
$sql = "AND (Datediff(Curdate(), date_transmission)<={$nbJours})";
$sql = "AND (Datediff(Curdate(), date_creation)<={$nbJours})";
} else {
$sql = $this->construireWhereDateDebutEtFin();
}
164,13 → 227,13
$dateFin = !is_null($dateFin) ? $dateFin : date('Y-m-d');
$condition = '';
if ($dateDebut == $dateFin) {
$condition = "DATE(date_observation)=".$this->getBdd()->proteger($dateDebut);
$condition = "Date(date_observation)=".$this->getBdd()->proteger($dateDebut);
} elseif (is_null($dateFin)) {
$condition = "DATE(date_observation)>=".$this->getBdd()->proteger($dateDebut);
$condition = "Date(date_observation)>=".$this->getBdd()->proteger($dateDebut);
} elseif (is_null($dateDebut)) {
$condition = "DATE(date_observation)<=".$this->getBdd()->proteger($dateFin);
$condition = "Date(date_observation)<=".$this->getBdd()->proteger($dateFin);
} else {
$condition = "DATE(date_observation) BETWEEN ".$this->getBdd()->proteger($dateDebut)." ".
$condition = "Date(date_observation) BETWEEN ".$this->getBdd()->proteger($dateDebut)." ".
"AND ".$this->getBdd()->proteger($dateFin);
}
$sql = "AND ($condition)";
179,75 → 242,42
}
private function construireWhereCoordonneesBbox() {
$sql = '';
if (isset($this->criteresRecherche->bbox)) {
$sql = "AND (".
"(".$this->genererCritereWhereBbox('').") OR (".
"(longitude IS NULL OR latitude IS NULL OR (longitude=0 AND latitude=0) ".
"OR longitude>180 OR latitude>90 OR mots_cles_texte LIKE '%sensible%') AND ".
$this->genererCritereWhereBbox('wgs84_').
$bbox = $this->criteresRecherche->bbox;
$sql =
"AND (".
"(".
"latitude BETWEEN ".$bbox['sud']." AND ".$bbox['nord']." ".
"AND longitude BETWEEN ".$bbox['ouest']." AND ".$bbox['est'].
") OR (".
"((longitude IS NULL OR latitude IS NULL) OR (longitude=0 AND latitude=0) ".
"OR (longitude>180 AND latitude>90)) AND ".
"wgs84_longitude BETWEEN ".$bbox['ouest']." AND ". $bbox['est']." ".
"AND wgs84_latitude BETWEEN ".$bbox['sud']." AND ".$bbox['nord'].
")".
")";
}
return $sql;
}
private function genererCritereWhereBbox($suffixe) {
$bboxRecherche = $this->criteresRecherche->bbox;
$conditions = array();
$sql = '';
foreach ($bboxRecherche as $bbox) {
$conditions[] = "({$suffixe}latitude BETWEEN ".$bbox['sud']." AND ".$bbox['nord']." ".
"AND {$suffixe}longitude BETWEEN ".$bbox['ouest']." AND ".$bbox['est'].")";
}
if (count($conditions) > 0) {
$sql = '('.implode(' OR ', $conditions).')';
}
return $sql;
}
private function construireWhereNomScientifique() {
$sql = '';
if (isset($this->criteresRecherche->filtre)) {
$filtre = $this->criteresRecherche->filtre;
$valeur = "'{$filtre['valeur']}".($filtre['operateur'] == 'LIKE' ? "%" : "")."'";
switch ($filtre['champ']) {
case "taxon" : $sql = "AND nom_sel {$filtre['operateur']} {$valeur}"; break;
}
}
return $sql;
}
private function construireWhereCoordonneesPoint() {
$sql = '';
$conditions = array();
foreach ($this->criteresRecherche->stations as $station) {
if ($station[0] == $this->nomSource) {
$longitude = str_replace(",", ".", strval($station[3]));
$latitude = str_replace(",", ".", strval($station[2]));
if ($station[1] == 'station') {
$conditions[] = "(longitude=".$longitude." AND latitude=".$latitude." ".
"AND (mots_cles_texte IS NULL OR mots_cles_texte NOT LIKE '%sensible%'))";
} else {
$commune = $this->obtenirCoordonneesCommune($longitude, $latitude);
$conditions[] =
"(".
"((longitude IS NULL OR latitude IS NULL) OR (longitude=0 AND latitude=0) ".
"OR longitude>180 OR latitude>90 OR mots_cles_texte LIKE '%sensible%') ".
"AND ce_zone_geo=".$this->getBdd()->proteger($commune['id_zone_geo']).
")";
}
}
$longitude = $this->criteresRecherche->longitude;
$latitude = $this->criteresRecherche->latitude;
$condition = "(longitude=".$longitude." AND latitude=".$latitude." ".
"AND (mots_cles_texte IS NULL OR mots_cles_texte NOT LIKE '%sensible%'))";
if ($this->criteresRecherche->typeSite == 'commune') {
$commune = $this->obtenirCoordonneesCommune();
$condition .=
" OR (".
"((longitude IS NULL OR latitude IS NULL) OR (longitude=0 AND latitude=0) ".
"OR (longitude>180 AND latitude>90)) ".
"AND ce_zone_geo=".$this->getBdd()->proteger($commune['id_zone_geo']).
")";
}
if (count($conditions) > 0) {
$sql = "AND (".implode(" OR ", $conditions).")";
}
return $sql;
return "AND ($condition)";
}
private function obtenirCoordonneesCommune($longitude, $latitude) {
$requete = "SELECT id_zone_geo, nom FROM cel_zones_geo WHERE wgs84_longitude=$longitude ".
"AND wgs84_latitude=$latitude";
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;
255,13 → 285,12
return $commune;
}
final protected function obtenirNomsStationsSurPoint() {
private function obtenirNomStation() {
// verifier si les coordonnees du point de requetage correspondent a une commune
$coordonnees = $this->recupererCoordonneesPremiereStation();
$station = $this->obtenirCoordonneesCommune($coordonnees[0], $coordonnees[1]);
$station = $this->obtenirCoordonneesCommune();
if (is_null($station)) {
$requete = 'SELECT DISTINCT lieudit AS nom FROM cel_obs WHERE longitude='.
$coordonnees[0].' AND latitude='.$coordonnees[1];
$this->criteresRecherche->longitude.' AND latitude='.$this->criteresRecherche->latitude;
$station = $this->getBdd()->recuperer($requete);
}
$nomStation = '';
271,18 → 300,6
return $nomStation;
}
private function recupererCoordonneesPremiereStation() {
$coordonnees = null;
foreach ($this->criteresRecherche->stations as $station) {
if ($station[0] == $this->nomSource) {
$longitude = str_replace(",", ".", strval($station[3]));
$latitude = str_replace(",", ".", strval($station[2]));
$coordonnees = array($longitude, $latitude);
}
}
return $coordonnees;
}
}
 
?>
/trunk/services/modules/0.1/sources/Formateur.php
3,73 → 3,81
abstract class Formateur {
protected $criteresRecherche;
protected $bdd = null;
protected $bdd;
protected $nomSource = '';
public function __construct($criteresRecherche, $source) {
public function __construct($criteresRecherche) {
$this->criteresRecherche = $criteresRecherche;
$this->nomSource = $source;
$this->nomSource = Config::get('nom_source');
}
protected function getBdd() {
if (is_null($this->bdd)) {
$this->bdd = new Bdd();
$nomBdd = $this->nomSource == 'floradata' ? Config::get('bdd_nom_floradata') : Config::get('bdd_nom_eflore');
$this->bdd->requeter("USE {$nomBdd}");
public function recupererStations() {
$stations = null;
if ($this->estTraitementRecuperationAutorise()) {
$stations = $this->traiterRecupererStations();
}
return $this->bdd;
return $stations;
}
public function recupererStations() {
$stations = array();
if ($this->nomSource == 'floradata' || $this->calculerNombreCriteresNonSpatiaux() > 0) {
$requeteSql = $this->construireRequeteStations();
$stations = $this->getBdd()->recupererTous($requeteSql);
if ($this->determinerFormatRetour(count($stations)) == 'maille') {
$maillage = new Maillage($this->criteresRecherche->bbox,
$this->criteresRecherche->zoom, $this->nomSource);
$maillage->genererMaillesVides();
$maillage->ajouterStations($stations);
$stations = $maillage->formaterSortie();
}
} else {
$nombreStations = $this->obtenirNombreStationsDansBbox();
if ($this->determinerFormatRetour($nombreStations) == 'maille') {
$stations = $this->recupererMaillesDansBbox();
} else {
$requeteSql = $this->construireRequeteStations();
$stations = $this->getBdd()->recupererTous($requeteSql);
}
public function recupererObservations() {
$stations = null;
if ($this->estTraitementRecuperationAutorise()) {
$stations = $this->traiterRecupererObservations();
}
return $stations;
}
public function recupererWfs() {
$requeteSql = $this->construireRequeteWfs();
return $this->getBdd()->recupererTous($requeteSql);
protected function estTraitementRecuperationAutorise() {
return (!(
isset($this->criteresRecherche->nbJours) ||
(isset($this->criteresRecherche->referentiel) &&
$this->criteresRecherche->referentiel != Config::get('referentiel_source'))
));
}
protected function determinerFormatRetour($nombreStations) {
$formatRetour = 'point';
protected function traiterRecupererStations() {
$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 (isset($this->criteresRecherche->format) && $this->criteresRecherche->format == 'maille'
&& $this->criteresRecherche->zoom <= $zoomMaxMaillage) {
$formatRetour = 'maille';
} else {
$seuilMaillage = Config::get('seuil_maillage');
if ($this->criteresRecherche->zoom <= $zoomMaxMaillage && $nombreStations > $seuilMaillage) {
$formatRetour = 'maille';
if ($zoom <= $zoomMaxMaillage && count($stations) >= $seuilMaillage) {
$maillage = new Maillage($this->criteresRecherche->bbox, $zoom, $this->nomSource);
$maillage->genererMaillesVides();
$maillage->ajouterPoints($stations);
$stations = $maillage->formaterSortie();
}
}
return $formatRetour;
$formateurJSON = new FormateurJson($this->nomSource);
$donneesFormatees = $formateurJSON->formaterStations($stations);
return $donneesFormatees;
}
protected function traiterRecupererObservations() {
$requeteSql = $this->construireRequeteObservations();
$observations = $this->getBdd()->recupererTous($requeteSql);
$this->recupererNumeroNomenclaturauxTaxons($observations);
$nomStation = $this->obtenirNomsStationsSurPoint();
$formateurJSON = new FormateurJson($this->nomSource);
$donneesFormatees = $formateurJSON->formaterObservations($observations, $nomStation);
return $donneesFormatees;
}
protected function calculerNombreCriteresNonSpatiaux() {
$nombreParametresNonSpatiaux = 0;
$criteresAIgnorer = array('zoom', 'bbox', 'stations', 'referentiel', 'format');
$criteresAIgnorer = array('zoom', 'bbox', 'longitude', 'latitude', 'referentiel');
foreach ($this->criteresRecherche as $nomCritere => $valeur) {
if (!in_array($nomCritere, $criteresAIgnorer)) {
echo $nomCritere.chr(13);
$nombreParametresNonSpatiaux ++;
}
}
76,56 → 84,66
return $nombreParametresNonSpatiaux;
}
abstract protected function construireRequeteStations();
protected function getBdd() {
if (!isset($this->bdd)) {
$this->bdd = new Bdd();
}
$this->bdd->requeter("USE ".Config::get('bdd_nom'));
return $this->bdd;
}
protected function obtenirNombreStationsDansBbox() {}
protected function recupererMaillesDansBbox() {}
public function recupererObservations() {
$requeteSql = $this->construireRequeteObservations();
$observations = $this->getBdd()->recupererTous($requeteSql);
if ($this->nomSource != 'floradata') {
$this->recupererNumeroNomenclaturauxTaxons($observations);
}
$nomStation = $this->obtenirNomsStationsSurPoint();
if (strlen($nomStation) == 0) {
$nomStation = 'station sans nom';
}
protected function getNomRang($taxon) {
$nomsRangs = array('famille', 'genre', 'espece', 'sous_espece');
for ($index = 0; $index < count($nomsRangs)
&& Config::get("rang.".$nomsRangs[$index]) != $taxon['rang']; $index ++);
$position = $index == count($nomsRangs) ? count($nomsRangs)-1 : $index;
return $nomsRangs[$position];
}
 
protected function recupererNumeroNomenclaturauxTaxons(& $observations) {
for ($index = 0; $index < count($observations); $index ++) {
$observations[$index]['nom_station'] = $nomStation;
$taxons = isset($this->criteresRecherche->taxon) ? $this->criteresRecherche->taxon : null;
if (!is_null($taxons)) {
foreach ($taxons as $taxon) {
if ($observations[$index]['nomSci'] == 0) {
continue;
}
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'] = '';
}
}
}
}
return $observations;
}
abstract protected function construireRequeteObservations();
protected function rechercherTaxonDansReferentiel($nomScientifique, $nomReferentiel) {
$referentiel = new Referentiel($nomReferentiel);
$taxon = $referentiel->obtenirNumeroNomenclatural($nomScientifique);
return $taxon;
}
protected function recupererNumeroNomenclaturauxTaxons(& $observations) {
for ($index = 0; $index < count($observations); $index ++) {
if (strlen (trim($observations[$index]['nomSci'])) == 0) {
continue;
}
$numeroNomenclatural = isset($observations[$index]['nn']) ? $observations[$index]['nn'] : null;
$referentiels = Referentiel::recupererListeReferentielsDisponibles();
$taxon = null;
$indexRef = 0;
while ($indexRef < count($referentiels) && is_null($taxon)) {
$referentiel = new Referentiel($referentiels[$indexRef]);
$taxon = $referentiel->obtenirNumeroNomenclatural($observations[$index]['nomSci'],
$numeroNomenclatural);
$indexRef ++;
}
protected function obtenirNumeroTaxon($nomScientifique) {
$taxonTrouve = null;
$listeReferentiels = Referentiel::recupererListeReferentielsDisponibles();
foreach ($listeReferentiels as $nomReferentiel) {
$taxon = $this->rechercherTaxonDansReferentiel($nomScientifique, $nomReferentiel);
if (!is_null($taxon)) {
$observations[$index]['nn'] = $taxon['nn'];
$observations[$index]['nom_referentiel'] = $taxon['referentiel'];
} else {
$observations[$index]['nn'] = '';
$taxonTrouve = $taxon;
break;
}
}
return $taxonTrouve;
}
abstract protected function obtenirNomsStationsSurPoint();
}
 
?>
/trunk/services/configurations/config.defaut.ini
80,8 → 80,8
seuil_maillage = 250
 
; valeurs des rangs au niveau de la classification des taxons
rang.genre = 220
rang.famille = 180
rang.genre = 180
rang.famille = 220
rang.espece = 290
rang.sous_espece = 320
 
/trunk/services/configurations/config_floradata.ini
4,8 → 4,8
nom_source = "floradata"
 
; Nom de la base utilisée.
bdd_nom_floradata = "tb_cel"
bdd_nom_eflore = "tb_eflore"
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"
/trunk/services/configurations/config_baznat.ini
4,12 → 4,12
nom_source = "baznat"
 
; Nom de la base utilisée.
bdd_nom_eflore = "tb_eflore"
bdd_nom = "tb_eflore"
 
; URL de base des services de ce projet
url_service="{ref:url_base}service:moissonnage:0.1/baznat"
 
referentiel_source = "bdtfx"
referentiel_source = 'bdtfx';
 
 
[meta-donnees]
/trunk/services/configurations/config_sophy.ini
4,12 → 4,12
nom_source = "sophy"
 
; Nom de la base utilisée.
bdd_nom_eflore = "tb_eflore"
bdd_nom = "tb_eflore"
 
; URL de base des services de ce projet
url_service="{ref:url_base}service:moissonnage:0.1/sophy"
 
referentiel_source = "bdtfx"
referentiel_source = 'bdtfx';
 
[meta-donnees]
dureecache = 3600