Subversion Repositories eFlore/Applications.moissonnage

Compare Revisions

No changes between revisions

Ignore whitespace Rev 33 → Rev 34

/trunk/services/framework.php
New file
0,0 → 1,6
<?php
// Inclusion du Framework
// Renomer ce fichier en "framework.php"
// Indiquer ci-dessous le chemin absolu vers le fichier autoload.inc.php de la bonne version du Framework
require_once '/home/alex/web/framework-0.3/framework/Framework.php';
?>
/trunk/services/modules/0.1/sources/FloradataFormateur.php
22,7 → 22,7
*
* Les donnees seront renvoyees au format JSON
*
* @package framework-0.3
* @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>
32,75 → 32,15
*/
 
 
class FloradataFormateur {
final class FloradataFormateur extends Formateur {
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'".
")";
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%')";
$requete =
"SELECT COUNT(id_observation) AS observations, 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 ".
"IF({$condition}, wgs84_latitude, latitude) AS latitude, IF({$condition}, wgs84_longitude, longitude) ".
"AS longitude, IF({$condition}, 'COMMUNE', 'STATION') AS type_site, 'floradata' AS source ".
"FROM cel_obs LEFT JOIN cel_zones_geo cz ON ce_zone_geo=id_zone_geo ".
"WHERE transmission=1 ".
$this->construireWhereDepartement().' '.
109,15 → 49,16
$this->construireWhereReferentiel().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesBbox().' '.
"GROUP BY longitude, latitude, wgs84_longitude, wgs84_latitude";
"GROUP BY IF({$condition},wgs84_longitude,longitude), IF({$condition},wgs84_latitude,latitude)";
return $requete;
}
private function construireRequeteObservations() {
final protected function construireRequeteObservations() {
$requete =
"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 ".
"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 ".
"FROM cel_obs WHERE transmission=1 ".
$this->construireWhereAuteur().' '.
$this->construireWhereReferentiel().' '.
124,24 → 65,38
$this->construireWhereDate().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesPoint().' '.
"ORDER BY nom_ret, date, observateur";
"ORDER BY IF(nom_sel IS NULL, 'A identifier',nom_sel), date, observateur";
return $requete;
}
protected function construireWhereTaxon() {
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() {
$sql = '';
if (isset($this->criteresRecherche->taxon)) {
$taxons = $this->criteresRecherche->taxon;
$criteres = array();
foreach ($taxons as $taxon) {
$nomRang = $this->getNomRang($taxon);
if ($nomRang == 'genre') {
if ($taxon['rang'] == Config::get('rang.famille')) {
$criteres[] = "famille=".$this->getBdd()->proteger($taxon['nom']);
} elseif ($taxon['rang'] == Config::get('rang.genre')) {
$criteres[] = "nom_sel LIKE ".$this->getBdd()->proteger($taxon['nom']." %");
} else {
$criteres[] = "nom_ret LIKE ".$this->getBdd()->proteger($taxon['nom']."%");
if ($nomRang == 'espece') {
$criteres = array_merge($criteres, $this->concatenerTaxonsSousEspeces($taxon));
}
$sousTaxons = $this->concatenerSynonymesEtSousEspeces($taxon);
$criteres[] = "nt IN (".implode(',', $sousTaxons).")";
}
}
$sql = "AND (".implode(' OR ',array_unique($criteres)).")";
148,35 → 103,17
}
return $sql;
}
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) {
 
private function concatenerSynonymesEtSousEspeces($taxon) {
$referentiel = new Referentiel($this->criteresRecherche->referentiel, $taxon);
$sousTaxons = $referentiel->recupererTaxonsSousEspeces();
$sousTaxons = $referentiel->recupererSynonymesEtSousEspeces();
$criteres = array();
foreach ($sousTaxons as $sousTaxon) {
$criteres[] = "nom_ret LIKE ".$this->getBdd()->proteger($sousTaxon['nom']."%");
$criteres[] = "nt=".$sousTaxon['nt'];
}
return $criteres;
return array_unique($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)) {
212,7 → 149,7
$sql = '';
if (isset($this->criteresRecherche->nbJours)) {
$nbJours = $this->criteresRecherche->nbJours;
$sql = "AND (Datediff(Curdate(), date_creation)<={$nbJours})";
$sql = "AND (Datediff(Curdate(), date_transmission)<={$nbJours})";
} else {
$sql = $this->construireWhereDateDebutEtFin();
}
227,13 → 164,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)";
242,42 → 179,75
}
private function construireWhereCoordonneesBbox() {
$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'].
$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_').
")".
")";
}
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() {
$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']).
")";
$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']).
")";
}
}
}
return "AND ($condition)";
if (count($conditions) > 0) {
$sql = "AND (".implode(" OR ", $conditions).")";
}
return $sql;
}
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;
private function obtenirCoordonneesCommune($longitude, $latitude) {
$requete = "SELECT id_zone_geo, nom FROM cel_zones_geo WHERE wgs84_longitude=$longitude ".
"AND wgs84_latitude=$latitude";
$commune = $this->getBdd()->recuperer($requete);
if ($commune === false) {
$commune = null;
285,12 → 255,13
return $commune;
}
private function obtenirNomStation() {
final protected function obtenirNomsStationsSurPoint() {
// verifier si les coordonnees du point de requetage correspondent a une commune
$station = $this->obtenirCoordonneesCommune();
$coordonnees = $this->recupererCoordonneesPremiereStation();
$station = $this->obtenirCoordonneesCommune($coordonnees[0], $coordonnees[1]);
if (is_null($station)) {
$requete = 'SELECT DISTINCT lieudit AS nom FROM cel_obs WHERE longitude='.
$this->criteresRecherche->longitude.' AND latitude='.$this->criteresRecherche->latitude;
$coordonnees[0].' AND latitude='.$coordonnees[1];
$station = $this->getBdd()->recuperer($requete);
}
$nomStation = '';
300,6 → 271,18
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,81 → 3,73
abstract class Formateur {
protected $criteresRecherche;
protected $bdd;
protected $bdd = null;
protected $nomSource = '';
public function __construct($criteresRecherche) {
public function __construct($criteresRecherche, $source) {
$this->criteresRecherche = $criteresRecherche;
$this->nomSource = Config::get('nom_source');
$this->nomSource = $source;
}
public function recupererStations() {
$stations = null;
if ($this->estTraitementRecuperationAutorise()) {
$stations = $this->traiterRecupererStations();
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}");
}
return $stations;
return $this->bdd;
}
public function recupererObservations() {
$stations = null;
if ($this->estTraitementRecuperationAutorise()) {
$stations = $this->traiterRecupererObservations();
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);
}
}
return $stations;
}
protected function estTraitementRecuperationAutorise() {
return (!(
isset($this->criteresRecherche->nbJours) ||
(isset($this->criteresRecherche->referentiel) &&
$this->criteresRecherche->referentiel != Config::get('referentiel_source'))
));
public function recupererWfs() {
$requeteSql = $this->construireRequeteWfs();
return $this->getBdd()->recupererTous($requeteSql);
}
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();
protected function determinerFormatRetour($nombreStations) {
$formatRetour = 'point';
$zoomMaxMaillage = Config::get('zoom_maximal_maillage');
if (isset($this->criteresRecherche->format) && $this->criteresRecherche->format == 'maille'
&& $this->criteresRecherche->zoom <= $zoomMaxMaillage) {
$formatRetour = 'maille';
} 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) {
$maillage = new Maillage($this->criteresRecherche->bbox, $zoom, $this->nomSource);
$maillage->genererMaillesVides();
$maillage->ajouterPoints($stations);
$stations = $maillage->formaterSortie();
$seuilMaillage = Config::get('seuil_maillage');
if ($this->criteresRecherche->zoom <= $zoomMaxMaillage && $nombreStations > $seuilMaillage) {
$formatRetour = 'maille';
}
}
$formateurJSON = new FormateurJson($this->nomSource);
$donneesFormatees = $formateurJSON->formaterStations($stations);
return $donneesFormatees;
return $formatRetour;
}
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', 'longitude', 'latitude', 'referentiel');
$criteresAIgnorer = array('zoom', 'bbox', 'stations', 'referentiel', 'format');
foreach ($this->criteresRecherche as $nomCritere => $valeur) {
if (!in_array($nomCritere, $criteresAIgnorer)) {
echo $nomCritere.chr(13);
$nombreParametresNonSpatiaux ++;
}
}
84,66 → 76,56
return $nombreParametresNonSpatiaux;
}
protected function getBdd() {
if (!isset($this->bdd)) {
$this->bdd = new Bdd();
abstract protected function construireRequeteStations();
protected function obtenirNombreStationsDansBbox() {}
protected function recupererMaillesDansBbox() {}
public function recupererObservations() {
$requeteSql = $this->construireRequeteObservations();
$observations = $this->getBdd()->recupererTous($requeteSql);
if ($this->nomSource != 'floradata') {
$this->recupererNumeroNomenclaturauxTaxons($observations);
}
$this->bdd->requeter("USE ".Config::get('bdd_nom'));
return $this->bdd;
}
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) {
$nomStation = $this->obtenirNomsStationsSurPoint();
if (strlen($nomStation) == 0) {
$nomStation = 'station sans nom';
}
for ($index = 0; $index < count($observations); $index ++) {
$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'] = '';
}
}
}
$observations[$index]['nom_station'] = $nomStation;
}
return $observations;
}
protected function rechercherTaxonDansReferentiel($nomScientifique, $nomReferentiel) {
$referentiel = new Referentiel($nomReferentiel);
$taxon = $referentiel->obtenirNumeroNomenclatural($nomScientifique);
return $taxon;
}
abstract protected function construireRequeteObservations();
protected function obtenirNumeroTaxon($nomScientifique) {
$taxonTrouve = null;
$listeReferentiels = Referentiel::recupererListeReferentielsDisponibles();
foreach ($listeReferentiels as $nomReferentiel) {
$taxon = $this->rechercherTaxonDansReferentiel($nomScientifique, $nomReferentiel);
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 ++;
}
if (!is_null($taxon)) {
$taxonTrouve = $taxon;
break;
$observations[$index]['nn'] = $taxon['nn'];
$observations[$index]['nom_referentiel'] = $taxon['referentiel'];
} else {
$observations[$index]['nn'] = '';
}
}
return $taxonTrouve;
}
abstract protected function obtenirNomsStationsSurPoint();
}
 
?>
/trunk/services/modules/0.1/sources/MoissonnageFormateur.php
New file
0,0 → 1,265
<?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.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 MoissonnageFormateur extends Formateur {
 
final protected function construireRequeteStations() {
$requete =
"SELECT COUNT(guid) AS observations, lieu_station_nom AS nom, lieu_station_latitude AS latitude, ".
"lieu_station_longitude AS longitude, 'STATION' AS type_site, lieu_commune_code_insee AS code_insee, ".
"'{$this->nomSource}' AS source FROM {$this->nomSource}_tapir WHERE 1 ".
$this->construireWhereDepartement().' '.
$this->construireWhereAuteur().' '.
$this->construireWhereDate().' '.
$this->construireWhereReferentiel().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesBbox().' '.
"GROUP BY lieu_station_longitude, lieu_station_latitude";
return $requete;
}
final protected 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, ".
"'{$this->nomSource}' AS projet FROM {$this->nomSource}_tapir WHERE 1 ".
$this->construireWhereAuteur().' '.
$this->construireWhereReferentiel().' '.
$this->construireWhereDate().' '.
$this->construireWhereTaxon().' '.
$this->construireWhereCoordonneesPoint().' '.
"ORDER BY nom_scientifique_complet, date, observateur";
return $requete;
}
final protected function construireRequeteWfs() {
$requete =
"SELECT nom_scientifique_complet AS taxon, lieu_station_nom AS nom, lieu_station_latitude AS latitude, ".
"lieu_station_longitude AS longitude, 'STATION' AS type_site, lieu_commune_code_insee AS code_insee, ".
"'{$this->nomSource}' AS source FROM {$this->nomSource}_tapir WHERE 1 ".
$this->construireWhereCoordonneesBbox().' '.
$this->construireWhereNomScientifique().' '.
"ORDER BY lieu_station_longitude, lieu_station_latitude";
return $requete;
}
private function construireWhereTaxon() {
$sql = '';
if (isset($this->criteresRecherche->taxon)) {
$taxons = $this->criteresRecherche->taxon;
$criteres = array();
foreach ($taxons as $taxon) {
$criteres[] = "nom_scientifique_complet LIKE ".$this->getBdd()->proteger($taxon['nom']."%");
if ($taxon['rang'] >= Config::get('rang.espece')) {
$criteres = array_merge($criteres, $this->concatenerSynonymesEtSousEspeces($taxon));
} elseif ($taxon['rang'] == Config::get('rang.famille')) {
$criteres = array_merge($criteres, $this->concatenerTaxonsGenres($taxon));
}
}
$sql = "AND (".implode(' OR ',array_unique($criteres)).")";
}
return $sql;
}
private function concatenerSynonymesEtSousEspeces($taxon) {
$referentiel = new Referentiel($this->criteresRecherche->referentiel, $taxon);
$sousTaxons = $referentiel->recupererSynonymesEtSousEspeces();
$criteres = array();
foreach ($sousTaxons as $sousTaxon) {
$criteres[] = "nom_scientifique_complet LIKE ".$this->getBdd()->proteger($sousTaxon['nom']."%");
}
return $criteres;
}
private function concatenerTaxonsGenres($taxon) {
$referentiel = new Referentiel($this->criteresRecherche->referentiel, $taxon);
$sousTaxons = $referentiel->recupererGenres();
$criteres = array();
foreach ($sousTaxons as $sousTaxon) {
$criteres[] = "nom_scientifique_complet LIKE ".$this->getBdd()->proteger($sousTaxon['nom']."%");
}
return $criteres;
}
private function construireWhereReferentiel() {
$sql = '';
if (isset($this->criteresRecherche->referentiel)) {
$referentielSource = Config::get('referentiel_source');
if (strstr($this->criteresRecherche->referentiel, $referentielSource) === false) {
$sql = "AND 0";
}
}
return $sql;
}
private function construireWhereDepartement() {
$sql = '';
if (isset($this->criteresRecherche->departement)) {
$valeurs_a_proteger = $this->criteresRecherche->departement;
foreach ($valeurs_a_proteger as $valeur) {
$aProteger = $this->getBdd()->proteger($valeur . '%');
$valeurs_protegees[] = "lieu_commune_code_insee LIKE {$aProteger}";
}
$valeurs = implode(' OR ', $valeurs_protegees);
$sql = "AND ($valeurs)";
}
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 construireWhereDate() {
$sql = '';
$dateDebut = isset($this->criteresRecherche->dateDebut) ? $this->criteresRecherche->dateDebut : null;
$dateFin = isset($this->criteresRecherche->dateFin) ? $this->criteresRecherche->dateFin : null;
if (!is_null($dateDebut) || !is_null($dateFin)) {
$dateDebut = !is_null($dateDebut) ? substr($dateDebut, 0, 4) : null;
$dateFin = !is_null($dateFin) ? substr($dateFin, 0, 4) : date('Y');
$condition = '';
if ($dateDebut == $dateFin) {
$condition = "observation_date=".$dateDebut;
} elseif (is_null($dateFin)) {
$condition = "observation_date>=".$dateDebut;
} elseif (is_null($dateDebut)) {
$condition = "observation_date<=".$dateFin;
} else {
$condition = "observation_date BETWEEN ".$dateDebut." AND ".$dateFin;
}
$sql = "AND ($condition)";
}
return $sql;
}
private function construireWhereCoordonneesBbox() {
$sql = '';
if (isset($this->criteresRecherche->bbox)) {
$bboxRecherche = $this->criteresRecherche->bbox;
$conditions = array();
foreach ($bboxRecherche as $bbox) {
$conditions[] = "(lieu_station_longitude BETWEEN ".$bbox['ouest']." AND ".$bbox['est']." ".
"AND lieu_station_latitude BETWEEN ".$bbox['sud']." AND ".$bbox['nord'].")";
}
$sql = 'AND ('.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_scientifique_complet {$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[2]));
$latitude = str_replace(",", ".", strval($station[3]));
$conditions[] = "(lieu_station_latitude={$longitude} AND lieu_station_longitude={$latitude})";
}
}
if (count($conditions) > 0) {
$sql = "AND (".implode(" OR ", $conditions).")";
}
return $sql;
}
final protected function obtenirNomsStationsSurPoint() {
$requete = "SELECT DISTINCTROW lieu_station_nom FROM {$this->nomSource}_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);
}
final protected function obtenirNombreStationsDansBbox() {
$bbox = $this->criteresRecherche->bbox;
$zoom = $this->criteresRecherche->zoom;
$requete =
"SELECT zoom, Sum(nombre_sites) AS total_points FROM mailles_{$this->nomSource} ".
"WHERE zoom=".$zoom." ".$this->construireWhereMaillesBbox()." GROUP BY zoom";
$resultat = $this->getBdd()->recuperer($requete);
return $resultat['total_points'];
}
final protected function recupererMaillesDansBbox() {
$bbox = $this->criteresRecherche->bbox;
$zoom = $this->criteresRecherche->zoom;
$requete =
"SELECT limite_sud AS sud, limite_ouest AS ouest, limite_est AS est, limite_nord AS nord, ".
"nombre_sites AS stations, nombre_observations AS observations FROM mailles_{$this->nomSource} ".
"WHERE zoom=".$zoom." ".$this->construireWhereMaillesBbox();
$mailles = $this->getBdd()->recupererTous($requete);
// placer les totaux des nombres de stations dans des mailles vides
$maillage = new Maillage($this->criteresRecherche->bbox, $zoom, $this->nomSource);
$maillage->genererMaillesVides();
$maillage->ajouterMailles($mailles);
return $maillage->formaterSortie();
}
private function construireWhereMaillesBbox() {
$bboxRecherche = $this->criteresRecherche->bbox;
$conditions = array();
$sql = '';
foreach ($bboxRecherche as $bbox) {
$conditions[] = "(limite_sud<=".$bbox['nord']." AND limite_nord>=".$bbox['sud']." ".
"AND limite_ouest<=". $bbox['est']." AND limite_est>=".$bbox['ouest'].")";
}
if (count($conditions) > 0) {
$sql = 'AND ('.implode(' OR ', $conditions).')';
}
return $sql;
}
}
 
?>
/trunk/services/modules/0.1/commun/Commun.php
1,35 → 1,288
<?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;
private $nomSource;
private $nomService;
private $parametres = array();
private $ressources = array();
private $nomSource = '';
private $nomService = '';
private $verificateur;
private $parametresRecherche;
private $verificateur = null;
private $parametresRecherche = null;
private $retour = array();
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 {
if (!$this->verifierExistenceSourcesDonnees()) {
$message = "Source de donnees indisponible";
$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');
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();
if ($this->ressources[0] == 'mailles') {
$retour = $this->recupererMaillage();
} else {
$this->chargerNomSource();
$this->chargerNomService();
$retour = $this->executerServicePourSource();
$listeSources = explode(',', $this->parametres['source']);
foreach ($listeSources as $source) {
$source = trim($source);
$resultat = $this->traiterSource($source);
$this->ajouterResultat($resultat, $source);
}
}
$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;
}
36,18 → 289,24
private function recupererRessourcesEtParametres($ressources, $parametres) {
$this->ressources = $ressources;
$this->parametres = $parametres;
$this->parametres = array();
foreach ($parametres as $nomParametre => $valeur) {
$this->parametres[strtolower($nomParametre)] = $valeur;
}
}
private function verifierExistenceSourcesDonnees() {
private function estParametreSourceExistant() {
$parametreExiste = false;
if (isset($this->parametres['source'])) {
$parametreExiste = true;
}
return $parametreExiste;
}
private function verifierExistenceSourcesDonnees($source) {
$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
if (in_array($source, $sourcesDisponibles)) {
$estDisponible = true;
}
return $estDisponible;
63,11 → 322,23
}
}
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() {
private function chargerNomSource($source) {
if (isset($this->parametres['source'])) {
$this->nomSource = $this->parametres['source'];
} else {
75,20 → 346,13
}
}
private function chargerNomService() {
$this->nomService = ucfirst($this->parametres['source']) . 'Formateur';
Projets::chargerConfigurationSource($this->parametres['source']);
private function chargerNomService($source) {
$this->nomService = ($source == 'floradata' ? 'Floradata' : 'Moissonnage').'Formateur';
Projets::chargerConfigurationSource($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);
private function executerServicePourSource($source) {
$objetTraitement = new $this->nomService($this->parametresRecherche, $source);
$methode = $this->genererNomMethodeAExecuter();
return $objetTraitement->$methode();
}
97,6 → 361,44
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/configurations/config_floradata.ini
4,8 → 4,8
nom_source = "floradata"
 
; Nom de la base utilisée.
bdd_nom = "tb_cel"
bdd_eflore = "tb_eflore"
bdd_nom_floradata = "tb_cel"
bdd_nom_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 = "tb_eflore"
bdd_nom_eflore = "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 = "tb_eflore"
bdd_nom_eflore = "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
/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 = 180
rang.famille = 220
rang.genre = 220
rang.famille = 180
rang.espece = 290
rang.sous_espece = 320
 
/trunk/services/bibliotheque/Maille.php
9,10 → 9,8
private $indexLatitude;
private $indexLongitude;
private $points = array();
private $nombrePoints;
private $stations = array();
private $observations = array();
private $nombreObservations;
public function __construct($sud, $ouest, $nord, $est, $indexLat, $indexLng) {
24,11 → 22,14
$this->indexLongitude = $indexLng;
}
public function ajouterPoint($point) {
$this->points[] = $point;
$this->nombrePoints ++;
$this->observations[] = $point['observations'];
$this->nombreObservations += $point['observations'];
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 getLatitudeNord() {
55,12 → 56,12
return $this->indexLongitude;
}
public function getPoints() {
return $this->points;
public function getStations() {
return $this->stations;
}
public function getNombrePoints() {
return $this->nombrePoints;
public function getNombreStations() {
return count($this->stations);
}
public function getObservations() {
67,19 → 68,28
return $this->observations;
}
public function getNombreObservations() {
return $this->nombreObservations;
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 totalNonNul() {
return count($this->points) > 0;
}
public function combinerMailles(& $maille) {
$this->nombrePoints += $maille->nombre_sites;
$this->nombreObservations += $maille->nombre_observations;
}
}
 
?>
/trunk/services/bibliotheque/EnteteHttp.php
New file
0,0 → 1,7
<?php
class EnteteHttp {
public $code = RestServeur::HTTP_CODE_OK;
public $encodage = 'utf-8';
public $mime = 'application/json';
}
?>
/trunk/services/bibliotheque/FormateurWfs.php
New file
0,0 → 1,120
<?php
 
class FormateurWfs {
const TYPE_MIME = 'text/xml';
private $bbox = null;
public function formaterGetCapabilities() {
$nomFichierWfs = dirname(__FILE__).DS."squelettes".DS."GetCapabilities.tpl.xml";
return SquelettePhp::analyser($nomFichierWfs);
}
public function formaterDescribeFeatureType($sources) {
$nomFichierWfs = dirname(__FILE__).DS."squelettes".DS."DescribeFeatureType.tpl.xml";
if (is_null($sources)) {
$sources = Config::get('sources_dispo');
}
$listeSources = is_array($sources) == 1 ? $sources : explode(',', $sources);
$item = array('listeSources' => $listeSources);
return SquelettePhp::analyser($nomFichierWfs, $item);
}
public function formaterGetFeature(& $stations, $sources) {
$nomFichierWfs = dirname(__FILE__).DS."squelettes".DS."GetFeature.tpl.xml";
$this->bbox = array('ouest' => null, 'est' => null, 'sud' => null, 'nord'=> null);
$stationsRetour = $this->mettreEnPageStations($stations);
$listeSources = implode(',', $sources);
$item = array('enveloppe' => $this->bbox, 'stations' => $stationsRetour, 'listeSources' => $listeSources);
return SquelettePhp::analyser($nomFichierWfs, $item);
}
private function mettreEnPageStations(& $stations) {
$station = array('longitude' => null, 'latitude' => null);
$stationsRetour = array();
foreach ($stations as $stationBdd) {
if ($this->estNonNul($stationBdd['longitude']) && $this->estNonNul($stationBdd['latitude'])
&& ($stationBdd['longitude'] != $station['longitude'] || $stationBdd['latitude'] != $station['latitude'])) {
if (isset($station['source'])) {
if ($station['source'] == 'floradata') {
$this->mettreEnPageStationFloradata($station);
} else {
$this->mettreEnPageStationMoissonnage($station);
}
$stationsRetour[] = $station;
}
foreach ($stationBdd as $cle => $valeur) {
if ($cle != 'taxon') {
$station[$cle] = $valeur;
}
}
$station['taxons'] = array(trim($stationBdd['taxon']));
$this->mettreAJourBbox($station);
} else {
$station['taxons'][] = trim($stationBdd['taxon']);
}
}
return $stationsRetour;
}
private function estNonNul($valeur) {
return (!is_null($valeur) && strlen(trim($valeur)) > 0);
}
private function mettreAJourBbox($station) {
if (is_null($this->bbox['sud']) || floatval($station['latitude']) < floatval($this->bbox['sud'])) {
$this->bbox['sud'] = $station['latitude'];
} elseif (is_null($this->bbox['nord']) || floatval($station['latitude']) > floatval($this->bbox['nord'])) {
$this->bbox['nord'] = $station['latitude'];
}
if (is_null($this->bbox['ouest']) || floatval($station['longitude']) < floatval($this->bbox['ouest'])) {
$this->bbox['ouest'] = $station['longitude'];
} elseif (is_null($this->bbox['est']) || floatval($station['longitude']) > floatval($this->bbox['est'])) {
$this->bbox['est'] = $station['longitude'];
}
}
private function mettreEnPageStationFloradata(& $station) {
$station['nom_station'] = trim($station['station']);
if ($this->estNonNul($station['zone_geo'])) {
$station['nom_station'] .= ", ".$station['zone_geo'];
}
$station['nom_station'] = str_replace("&", "&amp;", trim($station['nom_station']));
$station['departement'] = '';
$station['code_insee'] = '';
if ($this->estNonNul($station['ce_zone_geo'])) {
$station['code_insee'] = substr($station['ce_zone_geo'], 8);
$station['departement'] = substr($station['code_insee'],0, 2);
if (intval($station['departement']) > 95) {
$station['departement'] = substr($station['code_insee'],0, 2);
}
}
unset($station['station']);
unset($station['zone_geo']);
unset($station['ce_zone_geo']);
$station['taxons'] = str_replace("&", "&amp;", implode(',', $station['taxons']));
}
private function mettreEnPageStationMoissonnage(& $station) {
$station['nom_station'] = str_replace("&", "&amp;", trim($station['nom']));
$station['departement'] = '';
if ($this->estNonNul($station['code_insee'])) {
$station['departement'] = substr($station['code_insee'],0, 2);
if (intval($station['departement']) > 95) {
$station['departement'] = substr($station['code_insee'],0, 2);
}
}
unset($station['nom']);
$station['taxons'] = str_replace("&", "&amp;", implode(',', $station['taxons']));
}
public function formaterException(Exception $erreur) {
$nomFichierWfs = dirname(__FILE__).DS."squelettes".DS."Exception.tpl.xml";
$item = array('message' => $erreur->getMessage());
return SquelettePhp::analyser($nomFichierWfs, $item);
}
}
 
?>
/trunk/services/bibliotheque/Referentiel.php
39,6 → 39,7
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;
87,46 → 88,30
if (is_null($this->bdd)) {
$this->bdd = new Bdd();
}
$nomBdd = Config::get('bdd_eflore');
if (is_null($nomBdd)) {
$nomBdd = Config::get('bdd_nom');
}
$nomBdd = Config::get('bdd_nom');
$this->bdd->requeter("USE ".$nomBdd);
return $this->bdd;
}
public function recupererTaxonsSousEspeces($listeNn = null) {
public function recupererSynonymesEtSousEspeces() {
$sousTaxons = array();
if (!is_null($this->taxon) && $this->taxon['rang'] == Config::get('rang.espece')) {
if (is_null($listeNn)) {
$listeNn = $this->taxon['nn'];
}
if (!is_null($this->taxon) && $this->taxon['rang'] >= Config::get('rang.espece')) {
$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));
}
"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);
}
return $sousTaxons;
}
public function recupererTaxonsFamilles() {
public function recupererGenres() {
$sousTaxons = array();
if (!is_null($this->taxon) && $this->taxon['rang'] == Config::get('rang.genre')) {
if (!is_null($this->taxon) && $this->taxon['rang'] == Config::get('rang.famille')) {
$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;
149,10 → 134,13
return $tableau;
}
public function obtenirNumeroNomenclatural($nomScientifique) {
public function obtenirNumeroNomenclatural($nomScientifique, $numeroNomenclatural = null) {
$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;
163,4 → 151,5
}
}
 
?>
/trunk/services/bibliotheque/ResultatService.php
New file
0,0 → 1,9
<?php
 
class ResultatService {
public $mime = 'application/json';
public $encodage = 'utf-8';
public $corps = '';
}
 
?>
/trunk/services/bibliotheque/squelettes/GetCapabilities.tpl.xml
New file
0,0 → 1,153
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'."\n"; ?>
<wfs:WFS_Capabilities
xmlns:gml="http://www.opengis.net/gml"
xmlns:wfs="http://www.opengis.net/wfs"
xmlns:ows="http://www.opengis.net/ows"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns="http://www.opengis.net/wfs"
version="1.1.0"
xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">
<ows:ServiceIdentification>
<ows:Title>Observations Tela-Botanica</ows:Title>
<ows:Abstract>Observations Tela-Botanica</ows:Abstract>
<ows:Keywords>
<ows:Keyword>Tela-Botanica</ows:Keyword>
<ows:Keyword>Botanique</ows:Keyword>
<ows:Keyword>Observation naturaliste</ows:Keyword>
</ows:Keywords>
<ows:ServiceType codeSpace="OGC">OGC WFS</ows:ServiceType>
<ows:ServiceTypeVersion>1.1.0</ows:ServiceTypeVersion>
<ows:Fees>none</ows:Fees>
<ows:AccessConstraints>none</ows:AccessConstraints>
</ows:ServiceIdentification>
<ows:ServiceProvider>
<ows:ProviderName>Association Tela-Botanica</ows:ProviderName>
<ows:ProviderSite xlink:type="simple" xlink:href="http://tela-botanica.org" />
<ows:ServiceContact>
<ows:IndividualName>Tela-Botanica</ows:IndividualName>
<ows:ContactInfo>
<ows:Phone>
<ows:Voice>+33 467524122</ows:Voice>
</ows:Phone>
<ows:Address>
<ows:DeliveryPoint>163, Rue Auguste Broussonnet</ows:DeliveryPoint>
<ows:City>Montpellier</ows:City>
<ows:AdministrativeArea>Hérault (34)</ows:AdministrativeArea>
<ows:PostalCode>34090</ows:PostalCode>
<ows:Country>France</ows:Country>
<ows:ElectronicMailAddress>accueil@tela-botanica.org</ows:ElectronicMailAddress>
</ows:Address>
<ows:Role>resourceProvider</ows:Role>
</ows:ContactInfo>
</ows:ServiceContact>
</ows:ServiceProvider>
<ows:OperationsMetadata>
<ows:Operation name="GetCapabilities">
<ows:DCP>
<ows:HTTP>
<ows:Get xlink:type="simple" xlink:href="<?php echo Config::get('url_service_base'); ?>wfs" />
<ows:Post xlink:type="simple" xlink:href="<?php echo Config::get('url_service_base'); ?>wfs" />
</ows:HTTP>
</ows:DCP>
<ows:Parameter name="service">
<ows:Value>WFS</ows:Value>
</ows:Parameter>
<ows:Parameter name="AcceptVersions">
<ows:Value>1.1.0</ows:Value>
</ows:Parameter>
<ows:Parameter name="AcceptFormat">
<ows:Value>text/xml</ows:Value>
</ows:Parameter>
</ows:Operation>
<ows:Operation name="DescribeFeatureType">
<ows:DCP>
<ows:HTTP>
<ows:Get xlink:type="simple" xlink:href="<?php echo Config::get('url_service_base'); ?>wfs" />
<ows:Post xlink:type="simple" xlink:href="<?php echo Config::get('url_service_base'); ?>wfs" />
</ows:HTTP>
</ows:DCP>
<ows:Parameter name="outputFormat">
<ows:Value>text/xml; subtype=gml/3.1.1</ows:Value>
</ows:Parameter>
</ows:Operation>
<ows:Operation name="GetFeature">
<ows:DCP>
<ows:HTTP>
<ows:Get xlink:type="simple" xlink:href="<?php echo Config::get('url_service_base'); ?>wfs" />
<ows:Post xlink:type="simple" xlink:href="<?php echo Config::get('url_service_base'); ?>wfs" />
</ows:HTTP>
</ows:DCP>
<ows:Parameter name="resultType">
<ows:Value>results</ows:Value>
</ows:Parameter>
<ows:Parameter name="outputFormat">
<ows:Value>text/xml; subtype=gml/3.1.1</ows:Value>
</ows:Parameter>
</ows:Operation>
</ows:OperationsMetadata>
<FeatureTypeList>
<Operations>
<Operation>Query</Operation>
</Operations>
<FeatureType>
<Name>floradata</Name>
<Title>FloraData</Title>
<Abstract>Base de données constituée d'observations publiques du Carnet en Ligne de Tela Botanica. URL : http://www.tela-botanica.org/appli:cel</Abstract>
<DefaultSRS>EPSG:4326</DefaultSRS>
<OutPutFormats>
<Format>text/xml; subtype=gml/3.1.1</Format>
</OutPutFormats>
<ows:WGS84BoundingBox dimensions="2">
<ows:LowerCorner>-180 -90</ows:LowerCorner>
<ows:UpperCorner>180 90</ows:UpperCorner>
</ows:WGS84BoundingBox>
</FeatureType>
<FeatureType>
<Name>sophy</Name>
<Title>SOPHY, banque de données botaniques et écologiques</Title>
<Abstract>Données issues de SOPHY, une banque de données botaniques et écologiques réalisée par P. DE RUFFRAY, H. BRISSE, G. GRANDJOUAN et E. GARBOLINO dans le cadre de l'Association d'Informatique Appliquée à la Botanique (A.I.A.B.). URL : http://sophy.u-3mrs.fr/</Abstract>
<DefaultSRS>EPSG:4326</DefaultSRS>
<OutPutFormats>
<Format>text/xml; subtype=gml/3.1.1</Format>
</OutPutFormats>
<ows:WGS84BoundingBox dimensions="2">
<ows:LowerCorner>-180 -90</ows:LowerCorner>
<ows:UpperCorner>180 90</ows:UpperCorner>
</ows:WGS84BoundingBox>
</FeatureType>
<FeatureType>
<Name>baznat</Name>
<Title>BazNat - Flore</Title>
<Abstract>Données issues des prospections flore de la base de données naturaliste du réseau BazNat. URL : http://www.baznat.net/</Abstract>
<DefaultSRS>EPSG:4326</DefaultSRS>
<OutPutFormats>
<Format>text/xml; subtype=gml/3.1.1</Format>
</OutPutFormats>
<ows:WGS84BoundingBox dimensions="2">
<ows:LowerCorner>-180 -90</ows:LowerCorner>
<ows:UpperCorner>180 90</ows:UpperCorner>
</ows:WGS84BoundingBox>
</FeatureType>
</FeatureTypeList>
<ogc:Filter_Capabilities>
<ogc:Spatial_Capabilities>
<ogc:SpatialOperators>
<ogc:SpatialOperator name="BBOX"/>
</ogc:SpatialOperators>
</ogc:Spatial_Capabilities>
<ogc:Scalar_Capabilities>
<ogc:ComparisonOperators>
<ogc:ComparisonOperator>EqualTo</ogc:ComparisonOperator>
<ogc:ComparisonOperator>NotEqualTo</ogc:ComparisonOperator>
<ogc:ComparisonOperator>Like</ogc:ComparisonOperator>
</ogc:ComparisonOperators>
</ogc:Scalar_Capabilities>
</ogc:Filter_Capabilities>
</wfs:WFS_Capabilities>
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/trunk/services/bibliotheque/squelettes/GetFeature.tpl.xml
New file
0,0 → 1,30
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'."\n"; ?>
<wfs:FeatureCollection
xmlns:ms="http://mapserver.gis.umn.edu/mapserver"
xmlns:gml="http://www.opengis.net/gml"
xmlns:wfs="http://www.opengis.net/wfs"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://mapserver.gis.umn.edu/mapserver <?php echo Config::get('url_service_base'); ?>wfs?service=wfs&amp;version=1.1.0&amp;request=DescribeFeatureType&amp;typename=<?php echo $listeSources; ?> http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">
<gml:boundedBy>
<gml:Box srsName="EPSG:4326">
<gml:coordinates decimal="." cs="," ts=" "><?=$enveloppe['ouest']?>,<?=$enveloppe['sud']?>,<?=$enveloppe['est']?>,<?=$enveloppe['nord']?></gml:coordinates>
</gml:Box>
</gml:boundedBy>
<?php foreach ($stations as $station) { ?>
<gml:featureMember>
<ms:<?=$station['source']?>>
<ms:coordonnees>
<gml:Point srsName="EPSG:4326">
<gml:coordinates decimal="." cs="," ts=" "><?=$station['longitude']?>,<?=$station['latitude']?></gml:coordinates>
</gml:Point>
</ms:coordonnees>
<ms:nomStation><?=$station['nom_station']?></ms:nomStation>
<ms:precision><?=$station['type_site']?></ms:precision>
<ms:codeInsee><?=$station['code_insee']?></ms:codeInsee>
<ms:departement><?=$station['departement']?></ms:departement>
<ms:taxons><?=$station['taxons']?></ms:taxons>
</ms:<?=$station['source']?>>
</gml:featureMember>
<?php } ?>
</wfs:FeatureCollection>
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/trunk/services/bibliotheque/squelettes/DescribeFeatureType.tpl.xml
New file
0,0 → 1,28
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'."\n"; ?>
<schema
targetNamespace="http://mapserver.gis.umn.edu/mapserver"
xmlns:ms="http://mapserver.gis.umn.edu/mapserver"
xmlns:ogc="http://www.opengis.net/ogc"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:gml="http://www.opengis.net/gml"
elementFormDefault="qualified" version="0.1" >
<import namespace="http://www.opengis.net/gml" schemaLocation="http://schemas.opengis.net/gml/3.1.1/base/gml.xsd" />
<?php foreach ($listeSources as $source) { ?>
<element name="<?=$source ?>" type="ms:<?=$source ?>Type" substitutionGroup="gml:_Feature" />
<complexType name="<?=$source ?>Type">
<complexContent>
<extension base="gml:AbstractFeatureType">
<sequence>
<element name="coordonnees" type="gml:Point" />
<element name="nomStation" type="string" />
<element name="precision" type="string" />
<element name="codeInsee" type="string" />
<element name="departement" type="string" />
<element name="taxons" type="string" />
</sequence>
</extension>
</complexContent>
</complexType>
<?php } ?>
</schema>
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/trunk/services/bibliotheque/squelettes/Exception.tpl.xml
New file
0,0 → 1,7
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'."\n"; ?>
<ows:ExceptionReport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ows="http://www.opengis.net/ows/1.1" version="1.1.0" xml:lang="en-US" xsi:schemaLocation="http://www.opengis.net/ows/1.1 http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd">
xsi:schemaLocation="http://www.opengis.net/ows/1.1 http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd">
<ows:Exception exceptionCode="typename" locator="InvalidParameterValue">
<ows:ExceptionText><?=$message?></ows:ExceptionText>
</ows:Exception>
</ows:ExceptionReport>
Property changes:
Added: svn:mime-type
+text/plain
\ No newline at end of property
/trunk/services/bibliotheque/Maillage.php
3,40 → 3,47
 
class Maillage {
private $bbox;
private $zoom;
private $bbox = array();
private $zoom = '';
private $source = '';
private $indexLongitude;
private $indexLatitude;
private $mailles;
private $indexLongitude = array();
private $indexLatitude = array();
private $mailles = array();
private $bdd = null;
public function __construct($bbox, $zoom) {
$this->bbox = $bbox;
$this->zoom = $zoom;
public function __construct($bbox, $zoom, $source) {
$this->bbox = $this->calculerLimiteBboxGlobale($bbox);
$this->zoom = $zoom;
$this->source = $source;
$this->indexLongitude = array();
$this->indexLatitude = array();
$this->indexLatitude = array();
$this->mailles = array();
}
public function __destruct() {
while (count($this->indexLatitude) > 0) {
array_pop($this->indexLatitude);
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'];
}
}
while (count($this->indexLongitude) > 0) {
array_pop($this->indexLongitude);
}
return $bboxGlobale;
}
while (count($this->mailles) > 0) {
array_pop($this->mailles);
}
unset($this);
}
public function genererMaillesVides() {
$this->recupererIndexMaillesDansBbox();
foreach ($this->indexLatitude as $indexLat => $intervalleLat) {
51,7 → 58,6
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'].")";
66,7 → 72,6
") 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']);
74,51 → 79,36
$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');
}
$nomBdd = Config::get('bdd_nom_eflore');
$this->bdd->requeter("USE ".$nomBdd);
return $this->bdd;
}
public function ajouterPoints(& $points) {
foreach ($points as $point) {
list($longitude, $latitude) = $this->obtenirCoordonneesPoint($point);
public function ajouterStations(& $stations) {
foreach ($stations as $station) {
$longitude = $station['longitude'];
$latitude = $station['latitude'];
list($indexLongitude, $indexLatitude) = $this->rechercherIndexMaille($longitude, $latitude);
$this->mailles[$indexLatitude][$indexLongitude]->ajouterPoint($point);
$this->mailles[$indexLatitude][$indexLongitude]->ajouterStation($station, $this->source);
}
}
public function ajouterMailles(& $mailles) {
foreach ($mailles as $maille) {
$longitude = ($maille->longitudeOuest + $maille->longitudeEst) / 2;
$latitude = ($maille->latitudeSud + $maille->latitudeNord) / 2;
$longitude = ($maille['ouest'] + $maille['est']) / 2;
$latitude = ($maille['sud'] + $maille['nord']) / 2;
list($indexLongitude, $indexLatitude) = $this->rechercherIndexMaille($longitude, $latitude);
$this->mailles[$indexLatitude][$indexLongitude]->combinerMailles($maille);
$this->mailles[$indexLatitude][$indexLongitude]->combinerMailles($maille, $this->source);
}
}
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;
128,26 → 118,25
}
while ($indexLongitude < count($this->indexLongitude) - 1
&& $this->mailles[$indexLatitude][$indexLongitude]->getLongitudeEst() < $longitude) {
$indexLongitude ++;
$indexLongitude ++;
}
return array($indexLongitude, $indexLatitude);
}
 
public function formaterSortie($toutesLesMailles = false) {
public function formaterSortie() {
$mailles_resume = array();
foreach ($this->mailles as $ligne) {
foreach ($ligne as $maille) {
$nombrePoints = $maille->getNombrePoints();
if ($nombrePoints > 0 || $toutesLesMailles) {
$nombreStations = $maille->getNombrestations();
if ($nombreStations > 0) {
$mailles_resume[] = array(
'zoom' => $this->zoom,
'type_site' => 'MAILLE',
'sud' => $maille->getLatitudeSud(),
'ouest' => $maille->getLongitudeOuest(),
'nord' => $maille->getLatitudeNord(),
'est' => $maille->getLongitudeEst(),
'points' => $nombrePoints,
'observations' => $maille->getNombreObservations(),
'type_site' => 'MAILLE'
'stations' => $maille->getStations(),
'observations' => $maille->getObservations()
);
}
}
157,7 → 146,6
return $mailles_resume;
}
 
}
 
?>
/trunk/services/bibliotheque/ReponseHttp.php
2,16 → 2,11
 
class ReponseHttp {
 
private $mime = 'application/json';
private $encodage = 'utf-8';
private $codeHttp = RestServeur::HTTP_CODE_OK;
private $corps = '';
private $resultatService = null;
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){
32,18 → 27,21
}
}
 
public function setResultatService($resultat) {
$this->corps = $resultat;
if (!($resultat instanceof ResultatService)) {
$this->resultatService->corps = $resultat;
} else {
$this->resultatService = $resultat;
}
}
 
public function getCorps() {
if ($this->etreEnErreur()) {
$this->corps = $this->erreurs[0]['message'];
$this->resultatService->corps = $this->erreurs[0]['message'];
} else {
$this->transformerReponseCorpsSuivantMime();
}
return $this->corps;
return $this->resultatService->corps;
}
 
public function ajouterErreur(Exception $e) {
51,17 → 49,16
}
 
public function emettreLesEntetes() {
$enteteHttp = new EnteteHttp();
if ($this->etreEnErreur()) {
$codeHttp = $this->erreurs[0]['entete'];
$encodage = 'utf-8';
$mime = 'text/html';
$enteteHttp->code = $this->erreurs[0]['entete'];
$enteteHttp->mime = 'text/html';
} else {
$codeHttp = $this->codeHttp;
$encodage = $this->encodage;
$mime = $this->mime;
$enteteHttp->encodage = $this->resultatService->encodage;
$enteteHttp->mime = $this->resultatService->mime;
}
header("Content-Type: $mime; charset=$encodage");
RestServeur::envoyerEnteteStatutHttp($codeHttp);
header("Content-Type: $enteteHttp->mime; charset=$enteteHttp->encodage");
RestServeur::envoyerEnteteStatutHttp($enteteHttp->code);
}
 
private function etreEnErreur() {
73,14 → 70,14
}
 
private function transformerReponseCorpsSuivantMime() {
switch ($this->mime) {
switch ($this->resultatService->mime) {
case 'application/json' :
if (isset($_GET['callback'])) {
$contenu = $_GET['callback'].'('.json_encode($this->corps).');';
$contenu = $_GET['callback'].'('.json_encode($this->resultatService->corps).');';
} else {
$contenu = json_encode($this->corps);
$contenu = json_encode($this->resultatService->corps);
}
$this->corps = $contenu;
$this->resultatService->corps = $contenu;
break;
}
}
/trunk/services/bibliotheque/VerificateurParametres.php
14,8 → 14,9
* 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
* - 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.
*
* - referentiel : referentiel taxonomique a utiliser. On peut passer aussi bien en parametres
* son nom court que son nom complet (incluant le numero de version)
31,12 → 32,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
70,9 → 71,7
public function __construct($parametres) {
foreach ($parametres as $nomParametre => $valeur) {
if ($nomParametre != 'source') {
$this->parametres[$nomParametre] = $valeur;
}
$this->parametres[$nomParametre] = $valeur;
}
$this->bboxMonde = array(
'ouest' => floatval(Config::get('carte.limite_ouest')),
90,9 → 89,7
break;
case 'bbox' : $this->traiterParametreBbox($valeur);
break;
case 'longitude' :
case 'latitude' : $this->traiterParametresCoordonnees($this->parametres['longitude'],
$this->parametres['latitude']);
case 'stations' : $this->traiterParametreStations($this->parametres['stations']);
break;
case 'dept' : $this->traiterParametreDepartement($valeur);
break;
118,6 → 115,7
}
break;
}
case 'format' : $this->validation->format = strtolower($valeur); break;
// autres parametres ==> les ignorer
default : break;
}
164,7 → 162,20
}
}
private function traiterParametreBbox($bbox) {
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;
// 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) {
181,7 → 192,7
}
// verifier que les coordonnees de chaque bord de la bbox sont valides
if ($this->estUneBboxValide($bbox)) {
$this->validation->bbox = $bbox;
$bboxVerifiee = $bbox;
} else {
$message = "Certaines coordonnées de la bounding box sont situés en dehors des limites ".
"de notre monde";
188,6 → 199,7
$this->ajouterErreur($message);
}
}
return $bboxVerifiee;
}
private function estUneBboxValide($bbox) {
198,13 → 210,34
&& floatval($bbox['sud']) >= $monde['sud'] && floatval($bbox['sud']) <= $monde['nord']);
}
private function traiterParametresCoordonnees($longitude, $latitude) {
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]);
if ($this->sontDesCoordonneesValides($longitude, $latitude)) {
$this->validation->latitude = $latitude;
$this->validation->longitude = $longitude;
$station[2] = $latitude;
$station[3] = $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);
}
}
215,6 → 248,23
&& 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));
400,7 → 450,7
private function verifierPresenceParametreSpatial() {
$presenceParametreSpatial = false;
if (isset($this->parametres['bbox'])
|| (isset($this->parametres['longitude']) && isset($this->parametres['latitude']))) {
|| (isset($this->parametres['stations']))) {
$presenceParametreSpatial = true;
}
if ($presenceParametreSpatial == false) {
/trunk/services/bibliotheque/FormateurJson.php
3,11 → 3,8
 
class FormateurJson {
private $sourceDonnees;
public function __construct($source = '') {
$this->sourceDonnees = $source;
}
public function __construct() {}
public function formaterStations($stations) {
14,74 → 11,76
$objetJSON = new StdClass();
$objetJSON->type = "FeatureCollection";
$objetJSON->stats = new StdClass();
$objetJSON->stats->source = $this->sourceDonnees;
$objetJSON->stats->source = array();
$objetJSON->stats->formeDonnees = '';
if (count($stations) > 0) {
$objetJSON->stats->formeDonnees = ($stations[0]['type_site'] == 'MAILLE') ? 'maille' : 'point';
}
$objetJSON->stats->sites = 0;
$objetJSON->stats->stations = 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->sites += $station['points'];
$objetJSON->stats->stations += array_sum($station['stations']);
$objetJSON->stats->observations += array_sum($station['observations']);
} else {
$objetJSON->stats->sites ++;
$stationJSON = $this->formaterPoint($station);
$objetJSON->stats->stations ++;
$objetJSON->stats->observations += $station['observations'];
}
$objetJSON->stats->observations += $station['observations'];
if (!is_null($stationJSON)) {
$objetJSON->features[] = $stationJSON;
}
$objetJSON->features[] = $stationJSON;
$this->ajouterSourcesAuxStats($station, $objetJSON->stats);
}
return $objetJSON;
}
private function formaterPoint($station) {
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) {
$json = new StdClass();
$json->type = "Feature";
$json->geometry = new StdClass();
$json->properties = new StdClass();
$json->geometry->type = "Point";
$json->properties->source = $this->sourceDonnees;
$json->properties->source = $station['source'];
$json->properties->typeSite = $station['type_site'];
if ($this->sourceDonnees == 'floradata' && $station['type_site'] == 'COMMUNE') {
$json->geometry->coordinates = array($station['lat_commune'], $station['lng_commune']);
$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})";
} else {
$json->geometry->coordinates = array($station['latitude'], $station['longitude']);
$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})";
}
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 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 construireNomStation(& $station) {
}
private function extraireCodeDepartement($codeInsee) {
$codeInsee = substr($codeInsee,-5);
$codeDepartement = substr($codeInsee, 0 ,2);
if (intval($codeDepartement) > 95) {
substr($codeInsee, 0 ,3);
$codeDepartement = substr($codeInsee, 0 ,3);
}
return $codeDepartement;
}
100,20 → 99,26
array(floatval($maille['sud']), floatval($maille['ouest']))
);
$json->properties = new StdClass();
$json->properties->source = $this->sourceDonnees;
$json->properties->source = array();
foreach ($maille['stations'] as $source => $nombreStations) {
$json->properties->source[] = $source;
}
$json->properties->typeSite = 'MAILLE';
$json->properties->nombrePoints = $maille['points'];
$json->properties->stations = $maille['stations'];
$json->properties->observations = $maille['observations'];
return $json;
}
public function formaterObservations($observations, $nomSite) {
public function formaterObservations($observations) {
//print_r($observations); exit;
$objetJSON = new StdClass();
$objetJSON->site = trim($nomSite);
$objetJSON->site = trim($observations[0]['nom_station']);
$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') {
122,31 → 127,38
$observationJson->$colonne = is_string($valeur) ? trim($valeur) : $valeur;
}
}
$this->formaterDateObservation($observationJson);
$objetJSON->observations[] = $observationJson;
}
return $objetJSON;
}
private function genererUrlFicheEflore($observation) {
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) {
$url = null;
if (strstr('bdtfx', $observation['nom_referentiel']) !== false) {
if (strstr($observation['nom_referentiel'], 'bdtfx') !== false) {
$url = 'http://www.tela-botanica.org/bdtfx-nn-'.$observation['nn'];
}
return $url;
}
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);
private function concatenerLieuObservation(& $observation) {
$lieux = [];
if (!is_null($observation['lieudit'])) {
$lieux[] = $observation['lieudit'];
}
return $objetJSON;
if (!is_null($observation['milieu'])) {
$lieux[] = $observation['milieu'];
}
unset($observation['lieudit']);
unset($observation['milieu']);
$observation['lieu'] = implode(', ', $lieux);
}
}