Rev 2202 | Blame | Compare with Previous | Last modification | View Log | RSS feed
<?php
/**
* Le web service plantnet récupère toutes les infos de la vue del_plantnet.
* Ordonées par date de modification.
* Les images sont regroupées en observations.
* Les tags, les votes et les propositions de determinations sont intégrés à l'observation.
*
* Paramètres: date.debut et date.fin (unixtime en secondes), navigation.limite (10 par défaut), navigation.depart, ordre (DESC par défaut)
* Ne pas Oublier l'api key dans le header $_SERVER['HTTP_API_KEY']
*
* @category DEL
* @package Services
* @subpackage Plantnet
* @version 0.1
* @author Mathias CHOUET <mathias@tela-botanica.org>
* @author Samuel DUFOUR-KOWALSKI <samuel.dufour@cirad.fr>
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @author Aurelien PERONNET <aurelien@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>
* @copyright 1999-2014 Tela Botanica <accueil@tela-botanica.org>
*/
class Changements {
private $conteneur;
private $navigation;
private $bdd;
private $parametres = array();
private $ressources = array();
private $ordre_defaut = 'asc';
private $idsObsImg = array();
private $infosObsImg = array();
public function __construct(Conteneur $conteneur = null) {
/* restore_exception_handler(); */
/* restore_error_handler(); */
/* ini_set("display_errors", "1"); */
$this->conteneur = $conteneur == null ? new Conteneur() : $conteneur;
$this->navigation = $conteneur->getNavigation();
$this->bdd = $this->conteneur->getBdd();
}
/**
* Méthode principale de la classe.
* Lance la récupération des images dans la base et les place dans un objet ResultatService
* pour l'afficher.
* @param array $ressources les ressources situées après l'url de base (ex : http://url/ressource1/ressource2)
* @param array $parametres les paramètres situés après le ? dans l'url
* */
public function consulter($ressources, $parametres) {
// initialiserRessourcesEtParametres()
$this->ressources = $ressources;
$this->parametres = $parametres;
if (!isset($parametres['date.debut'])) {
$this->parametres['date.debut'] = '0';
}
if (!isset($parametres['date.fin'])) {
$this->parametres['date.fin'] = time();
}
if (! isset($parametres['ordre'])) {
$this->parametres['ordre'] = $this->ordre_defaut;
} else {
$parametres['ordre'] = strtolower($parametres['ordre']);
if (! in_array($parametres['ordre'], array('asc', 'desc'))) {
$this->parametres['ordre'] = $this->ordre_defaut;
}
}
// Lancement du service
$this->idsObsImg = $this->getIdsObsImg();
$infos = array();
$total = 0;
if ($this->idsObsImg) {
$total = $this->getTotal();
$this->infosObsImg = $this->recupererInfos();
$infos = $this->formaterInfos();
$infos = $this->chargerPropositionPlusProbable($infos);
$infos = $this->orderArray($infos);
}
$this->navigation->setTotal($total);
// Mettre en forme le résultat et l'envoyer pour affichage
$resultat = new ResultatService();
$resultat->corps = array('entete' => $this->navigation->getEntete(), 'resultats' => $infos);
return $resultat;
}
/*-------------------------------------------------------------------------------
CHARGEMENT DES IMAGES
--------------------------------------------------------------------------------*/
private function getIdsObsImg() {
$date_debut = date('Y-m-d H:i:s', $this->parametres['date.debut']);
$date_fin = date('Y-m-d H:i:s', $this->parametres['date.fin']);
$limite = isset($this->parametres['navigation.limite']) ? intval($this->parametres['navigation.limite']) : 10;
$depart = intval(@$this->parametres['navigation.depart']);
$ordre = $this->parametres['ordre'];
$date_debut = "'{$date_debut}'";
$date_fin = "'{$date_fin}'";
$requete =
'SELECT SQL_CALC_FOUND_ROWS p.id_observation, GROUP_CONCAT(DISTINCT p.id_image) as id_image, '.
'iv.moyenne AS moyenne_votes, '.
'iv.nb_votes AS nb_votes, '.
'iv.nb_points AS nb_points_votes, '.
'GROUP_CONCAT(DISTINCT it.tag) AS del_image_tags, '.
'modif_date '.
'FROM del_plantnet AS p '.
' JOIN del_observation_modif_date '.
' ON (p.id_observation = del_observation_modif_date.id_observation '.
' AND modif_date >= '.$date_debut.' '.
' AND modif_date <= '.$date_fin.') '.
' LEFT JOIN del_image_stat AS iv '.
' ON (id_image = iv.ce_image AND iv.ce_protocole = 3) '.
' LEFT JOIN del_image_tag AS it '.
' ON (id_image = it.ce_image AND it.actif = 1) '.
' LEFT JOIN del_commentaire AS c '.
' ON (p.id_observation = c.ce_observation) '.
' LEFT JOIN del_commentaire_vote AS cv '.
' ON (c.id_commentaire = cv.ce_proposition) '.
'GROUP BY p.id_observation '.
'ORDER BY modif_date ' . $ordre . ' '.
'LIMIT '.$depart.', '.$limite.
' -- '.__FILE__.':'.__LINE__;
return $this->bdd->recupererTous($requete);
// On récupère id_obs, id_image, votes, tags, modif_date
}
private function getTotal() {
$compte = $this->bdd->recuperer('SELECT FOUND_ROWS() AS nbre');
$total = (int) $compte['nbre'];
return $total;
}
// recupere les donnée associées (fait en 2 requetes pour optimiser)
private function recupererInfos() {
// recuperer les ids
$idsImg = array();
foreach ($this->idsObsImg as $ids) {
$id = $ids['id_image'];
$idsImg[] = $id;
}
$idsImgConcat = implode(',', $idsImg);
$requete = 'SELECT '.
'p.id_observation, p.id_plantnet, p.id_image, '.
'cp.plant_net_occurrence_id, ' .
'p.nom_sel, p.nom_sel_nn, p.nom_ret, p.nom_ret_nn,'.
'p.nom_referentiel, p.famille, '.
'p.zone_geo, p.latitude, p.longitude,'.
'p.date_observation, p.date_created, p.date_published, '.
'p.type_donnees, p.identiplante_score, p.is_identiplante_validated, p.mots_cles_cel_obs, p.programme, '.
'p.ce_utilisateur, p.courriel_utilisateur, '.
'p.original_name AS nom_image, p.i_date_shot AS date_shot, p.i_date_updated AS image_updated, p.mots_cles_cel_image AS mots_cles_cel_image '.
'FROM del_plantnet AS p '.
'LEFT JOIN tb_new_cel.pn_tb_pair AS cp ON p.id_observation = cp.occurrence_id '.
"WHERE id_image IN ($idsImgConcat) ".
' -- '.__FILE__.':'.__LINE__;
// recuperer les donnees
$resultats = $this->bdd->recupererTous($requete);
// regroupe les données par id_image
$img_data = array();
foreach ($resultats as $infos) {
$idImg = $infos['id_image'];
$img_data[$idImg] = $infos;
}
return $img_data;
}
/**
* Retourner un tableau d'images formaté en fonction des liaisons trouvées
* @param $liaisons les liaisons de la table del_obs_images
*/
private function formaterInfos() {
// regroupe les observations
$obs = array();
$imgCelTpl = $this->conteneur->getParametre('cel_img_url_tpl');
foreach ($this->idsObsImg as $ids) {
$idobs = $ids['id_observation'];
$idimg = explode(',', $ids['id_image']);
$obs[$idobs]['id_observation'] = $idobs;
foreach ($idimg as $image){
$imgInfos = null;
$imgdata = null;
$imgdata = $this->infosObsImg[$image];
$imgInfos = $this->recupererInfosParImage($image);
if (!isset($obs[$idobs])) {
$obs[$idobs] = array();
}
$obs[$idobs]['id_plantnet'] = $imgdata['id_plantnet'];
$obs[$idobs]['auteur_courriel'] = $imgdata['courriel_utilisateur'];
$obs[$idobs]['mots_cles_cel_obs'] = $imgdata['mots_cles_cel_obs'];
$obs[$idobs]['programme'] = $imgdata['programme'];
$obs[$idobs]['date_observation'] = $imgdata['date_observation'];
$obs[$idobs]['date_creation'] = $imgdata['date_created'];
$obs[$idobs]['date_changement'] = $ids['modif_date'];
$obs[$idobs]['date_publication'] = $imgdata['date_published'];
$obs[$idobs]['type_donnees'] = $imgdata['type_donnees'];
$obs[$idobs]['identiplante_score'] = $imgdata['identiplante_score'];
$obs[$idobs]['is_identiplante_validated'] = $imgdata['is_identiplante_validated'];
$obs[$idobs]['nom_sel'] = $imgdata['nom_sel'];
$obs[$idobs]['nom_sel_nn'] = $imgdata['nom_sel_nn'];
$obs[$idobs]['nom_referentiel'] = $imgdata['nom_referentiel'];
$obs[$idobs]['nom_ret'] = $imgdata['nom_ret'];
$obs[$idobs]['nom_ret_nn'] = $imgdata['nom_ret_nn'];
$obs[$idobs]['famille'] = $imgdata['famille'];
$obs[$idobs]['zone_geo'] = $imgdata['zone_geo'];
$obs[$idobs]['latitude'] = $imgdata['latitude'];
$obs[$idobs]['longitude'] = $imgdata['longitude'];
if (!isset($obs[$idobs]['images'])) {
$obs[$idobs]['images'] = array();
}
$img_obj = array(
'id_image' => $image,
'nom_image' => $imgdata['nom_image'],
'image_updated' => $imgdata['image_updated'],
'date_shot' => $imgdata['date_shot'],
'mots_cles_cel_image' => $imgInfos[0]['mots_cles_cel_image'],
'url' => sprintf($imgCelTpl, $idimg, 'O'),
'votes' => [
'moyenne_votes' => $imgInfos[0]['moyenne_votes'],
'nb_votes' => $imgInfos[0]['nb_votes'],
'nb_points_votes' => $imgInfos[0]['nb_points_votes'],
],
'del_tags' => explode(',', $imgInfos[0]['del_image_tags']),
);
// push
$obs[$idobs]['images'][] = $img_obj;
}
}
return $obs;
}
/**
* Charger les votes pour chaque image
*/
private function chargerPropositionPlusProbable(&$obs) {
$obsIds = array_keys($obs);
$idsObsConcat = implode(',', $obsIds);
$requete = 'SELECT ce_observation, id_commentaire, valeur, nom_sel, nom_sel_nn, nom_ret, cv.ce_utilisateur '.
'FROM del_commentaire_vote AS cv, del_commentaire AS c '.
"WHERE ce_observation IN ($idsObsConcat) ".
'AND nom_sel IS NOT NULL '.
'AND c.id_commentaire = cv.ce_proposition '.
' -- '.__FILE__.':'.__LINE__;
$resultats = $this->bdd->recupererTous($requete);
// calcul des votes
// un vote identifié a un facteur de 3
// additionne tous les vote par ce_proposition
$votes = array(); // map ce_proposition -> score
foreach ($resultats as $vote) {
if (!isset($votes[$vote['id_commentaire']])) {
$votes[$vote['id_commentaire']] = 0;
}
$valeur = ($vote['valeur'] == 1) ? 1 : -1;
$votes[$vote['id_commentaire']] += is_numeric($vote['ce_utilisateur']) ? 3 * $valeur : $valeur;
}
foreach ($resultats as $vote) {
$idobs = $vote['ce_observation'];
if (!isset($obs[$idobs]['determinations'])) {
$obs[$idobs]['determinations'] = array();
}
$obs[$idobs]['determinations'][$vote['id_commentaire']] =
array('nom_sel' => $vote['nom_sel'],
'nom_ret' => $vote['nom_ret'],
'score' => $votes[$vote['id_commentaire']],
'nn' => $vote['nom_sel_nn']);
}
return $obs;
}
private function orderArray(&$obs) {
$ret = array();
foreach ($obs as $o) {
$ret[] = $o;
}
function cmpDesc($a, $b) {
return ($a['date_changement'] < $b['date_changement']) ? 1 : -1;
}
function cmpAsc($a, $b) {
return cmpDesc($b, $a);
}
if ($this->parametres['ordre'] == 'desc') {
usort($ret, 'cmpDesc');
} else {
usort($ret, 'cmpAsc');
}
return $ret;
}
/**
* Formater les mots clés du cel en n'affichant que ceux faisant partie
* d'une liste définie dans le fichier de configuration
* @param $chaineMotCleCel la chaine de mots clés du cel
* @return string la chaine filtrée
*/
private function formaterMotsClesCel($chaineMotCleCel) {
$mots_cles_cel_affiches = "fleur,fleurs,feuille,feuilles,ecorce,fruit,fruits,port,plantnet,plantscan_new,plantnet-mobile";
$result = array_intersect(
explode(',', $mots_cles_cel_affiches), // $tabMotsClesAffiches
explode(',', $chaineMotCleCel)); // $tabMotsClesCel
if (count($result) === 0) {
return array();
}
$ret = explode(',', implode(',', $result));
return $ret;
}
/**
* On charge les infos spécifique à chaque image d'une obs
*/
private function recupererInfosParImage($id_image){
$requete =
'SELECT SQL_CALC_FOUND_ROWS p.id_image, '.
'p.mots_cles_cel_image, '.
'iv.moyenne AS moyenne_votes, '.
'iv.nb_votes AS nb_votes, '.
'iv.nb_points AS nb_points_votes, '.
'GROUP_CONCAT(DISTINCT it.tag) AS del_image_tags '.
'FROM del_plantnet_images AS p '.
' LEFT JOIN del_image_stat AS iv '.
' ON (id_image = iv.ce_image AND iv.ce_protocole = 3) '.
' LEFT JOIN del_image_tag AS it '.
' ON (id_image = it.ce_image AND it.actif = 1) '.
' WHERE id_image = '. $id_image .' '.
'GROUP BY p.id_image '.
' -- '.__FILE__.':'.__LINE__;
return $this->bdd->recupererTous($requete);
}
}