Subversion Repositories eFlore/Applications.del

Rev

Rev 1318 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
/**
 * Service fournissant des informations concernant les commentaire de DEL au format RSS1, RSS2 ou ATOM.
 * Encodage en entrée : utf8
 * Encodage en sortie : utf8
 *
 * @author Aurélien 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>
 * @version $Id$
 * @copyright 2010
 */
class SyndicationCommentaires {

        private $ressources = null;
        private $parametres = null;
        private $format = null;
        private $service = null;
        private $squelette = null;
        private $squelette_dossier = null;
        private $masque = array();
        private $mappingFiltre = array();
        private $conteneur = null;
        private $gestionBdd = null;
        private $navigation = null;

        public function __construct(Conteneur $conteneur = null) {
                $this->conteneur = $conteneur == null ? new Conteneur() : $conteneur;
                $this->conteneur->chargerConfiguration('config_syndication_commentaires.ini');
                $this->mappingFiltre = $this->conteneur->getParametre('mapping_masque');
                $this->masque = $conteneur->getMasque();
                $this->gestionBdd = $conteneur->getGestionBdd();
                $this->navigation = $conteneur->getNavigation();
        }

        public function consulter($params = array()) {
                $this->verifierConfiguration();

                if ($this->fluxAdminDemande()) {
                        $this->demanderAutorisationAdmin();
                }

                $donnees_brutes = $this->getDerniersCommentaires();
                $commentaires_formates = $this->formaterPourRss($donnees_brutes) ;
                return $commentaires_formates;
        }

        /**
        * Vérifier que le service est bien configuré
        * */
        public function verifierConfiguration() {
                $erreurs = array();

                if (empty($this->mappingFiltre)) {
                        $erreurs[] = 'Le fichier de configuration ne contient pas le tableau [mapping_masque] ou celui-ci est vide.';
                }

                if (!empty($erreurs)) {
                        $e = 'Erreur lors de la configuration : '."\n";
                        $e .= implode("\n", $erreurs);
                        throw new Exception($e, RestServeur::HTTP_CODE_ERREUR);
                }
        }

        /**
         * Verifier si le flux admin est demande
         */
        private function fluxAdminDemande() {
                return $this->conteneur->getParametre('admin') != null && $this->conteneur->getParametre('admin') == 1;
        }

        private function demanderAutorisationAdmin() {
                $verification = new ControleAcces($this->conteneur);
                $verification->demanderAuthentificationAdmin();
        }

        private function formaterPourRss($elements) {
                $donnees = $this->construireDonneesCommunesAuFlux($elements);
                foreach ($elements as $element) {
                        $identifiants[$element['id_commentaire']] = $element['id_commentaire'];
                }
                foreach ($elements as $element) {
                        $donnees['items'][] = $this->construireDonneesCommunesAuxItems($element);
                }
                return $donnees;
        }

        private function construireDonneesCommunesAuFlux($infos) {
                $donnees = array();
                $donnees['guid'] = htmlspecialchars($this->creerUrlService());
                $donnees['titre'] = 'identiPlante : commentaires et propositions';
                $donnees['description'] = 'Ce flux regroupe les dernières déterminations et commentaires rédigés dans l\'application identiPlante';
                $donnees['lien_service'] = htmlspecialchars($this->creerUrlService());
                $donnees['lien_del'] = $this->conteneur->getParametre('delAppliLien');
                $donnees['editeur'] = $this->conteneur->getParametre('editeur');
                $derniere_info_en_date = reset($infos);
                $date_modification_timestamp = $this->convertirDateHeureMysqlEnTimestamp($derniere_info_en_date['date']);
                $donnees['date_maj_RSS'] = date(DATE_RSS, $date_modification_timestamp);
                $donnees['date_maj_ATOM'] = date(DATE_ATOM, $date_modification_timestamp);
                $donnees['date_maj_W3C'] = date(DATE_W3C, $date_modification_timestamp);
                $donnees['annee_courante'] = date('Y');
                $donnees['generateur'] = 'DEL - SyndicationCommentaire';
                $donnees['generateur_version'] = (preg_match('/([0-9]+)/', '$Revision$', $match)) ?  $match[1] : '0';
                return $donnees;
        }

        private function creerUrlService() {
                $url_service = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
                return $url_service;
        }

        private function construireDonneesCommunesAuxItems($info) {
                $item = array();
                $date_modification_timestamp = $this->convertirDateHeureMysqlEnTimestamp($info['date']);
                $item['date_maj_simple'] = strftime('%A %d %B %Y à %H:%M', $date_modification_timestamp);
                $item['date_maj_RSS'] = date(DATE_RSS, $date_modification_timestamp);
                $item['date_maj_ATOM'] = date(DATE_ATOM, $date_modification_timestamp);
                $item['date_maj_W3C'] = date(DATE_W3C, $date_modification_timestamp);
                $item['titre'] = $this->creerTitre($info);
                $item['guid'] = $this->creerGuidItem($info);
                $item['lien'] = $this->creerLienItem($info);
                $item['categorie'] = $this->creerCategorie($item);
                $item['description'] = $this->creerDescription($info, $item);
                $item['description_encodee'] = htmlspecialchars($this->creerDescription($info, $item));
                $item['modifier_par'] = $this->creerAuteur($info);
                return $item;
        }

        protected function convertirDateHeureMysqlEnTimestamp($date_heure_mysql){
                $timestamp = 0;
                // Le date de 1970-01-01 pose problème dans certains lecteur de Flux, on met donc la date de création de Tela
                $date_heure_mysql = ($date_heure_mysql == '0000-00-00 00:00:00') ? '1999-12-14 00:00:00' : $date_heure_mysql;
                if ($date_heure_mysql != '0000-00-00 00:00:00') {
                        $val = explode(' ', $date_heure_mysql);
                        $date = explode('-', $val[0]);
                        $heure = explode(':', $val[1]);
                        $timestamp = mktime((int) $heure[0], (int) $heure[1], (int) $heure[2], (int) $date[1], (int) $date[2], (int) $date[0]);
                }
                return $timestamp;
        }

        private function creerTitre($element) {
                $nomPropose = htmlspecialchars($element['nom_sel']);
                $intitule = ($element['nom_sel'] != '') ? "Proposition $nomPropose" : 'Commentaire';
                $auteur = htmlspecialchars($this->creerAuteur($element));
                $nomSelActuel = htmlspecialchars($element['dob_nom_sel']);
                $zoneGeo = htmlspecialchars((($element['dob_zone_geo'] != '') ? $element['dob_zone_geo'] : '?'));
                $dateObs = htmlspecialchars(strftime('%d %B %Y', strtotime($element['dob_date_observation'])));

                $titre = "$intitule par $auteur pour $nomSelActuel à $zoneGeo le $dateObs";
                return $titre;
        }

        private function creerAuteur($info) {
                $auteur = 'Anonyme';
                if ($info['utilisateur_prenom'] != '' && $info['utilisateur_nom'] != '') {
                        $auteur = $info['utilisateur_prenom'].' '.$info['utilisateur_nom'];
                }
                return $auteur;
        }

        private function creerGuidItem($element) {
                $guid = sprintf($this->conteneur->getParametre('guidObsTpl'), $element['id_commentaire']);
                return $guid;
        }

        private function creerLienItem($element) {
                $lien = sprintf($this->conteneur->getParametre('delFicheObsTpl'), $element['dob_id_observation']);
                return $lien;
        }

        private function creerCategorie($element) {
                $categorie = 'Commentaires';
                $categorie = htmlentities($categorie);
                return $categorie;
        }

        private function creerDescription($donnees, $item) {
                $idCommentaire = $donnees['id_commentaire'];
                $idObs = $donnees['dob_id_observation'];
                $nomPropose = ($donnees['nom_sel'] != '') ? htmlspecialchars($donnees['nom_sel']) : '';
                $dateCommentaire = htmlspecialchars(strftime('%A %d %B %Y à %H:%M', $this->convertirDateHeureMysqlEnTimestamp($donnees['date'])));
                $nomSelActuel = htmlspecialchars($donnees['dob_nom_sel']);
                $etreProposition = ($nomPropose != '') ? true : false;
                $intitule = ($etreProposition) ? 'Proposition' : 'Commentaire';
                $txt = ($donnees['texte'] != '') ? htmlspecialchars($donnees['texte']) : '';
                $auteur = htmlspecialchars($this->creerAuteur($donnees)).
                        ($this->fluxAdminDemande() ? ' ('.$donnees['utilisateur_courriel'].')' : '');
                $lieuObs = htmlspecialchars((($donnees['dob_zone_geo'] != '') ? $donnees['dob_zone_geo'] : '?'));
                $dateObs = htmlspecialchars(str_replace(' 00:00:00', '', $donnees['dob_date_observation']));
                $observateur = htmlspecialchars($this->creerObservateur($donnees));

                $contenuCommentaire = '';
                if ($etreProposition) {
                        $contenuCommentaire =
                                '<li><span class="champ">'."Nom proposé :</span> <em>$nomPropose</em></li>".
                                ((!empty($txt)) ? '<li><span class="champ">'."Argumentaire :</span> $txt</li>" : '').
                                '<li><span class="champ">'."Auteur de la proposition :</span> $auteur</li>".
                                '<li><span class="champ">'."Proposé le :</span> $dateCommentaire</li>";
                } else {
                        $contenuCommentaire =
                                '<li><span class="champ">'."Commentaire #$idCommentaire :</span> <pre>$txt</pre></li>".
                                '<li><span class="champ">'."Auteur du commentaire :</span> $auteur</li>".
                                '<li><span class="champ">'."Commenté le :</span> $dateCommentaire</li>";
                }

                $description = '<style>.champ{color:grey} .gauche{float:left;padding:0 20px 0 0;} ul{list-style-type:none;padding:0;}</style>'.
                        '<h2>'."$intitule identiPlante #$idCommentaire pour l'observation #$idObs".'</h2>'.
                        '<div class="gauche">'.
                        "       <h3>Observation #$idObs</h3>".
                        '       <ul>'.
                        '               <li><span class="champ">'."Nom saisi actuel :</span> <em>$nomSelActuel</em></li>".
                        '               <li><span class="champ">'."Lieu :</span> $lieuObs</li>".
                        '               <li><span class="champ">'."Date :</span> $dateObs</li>".
                        '               <li><span class="champ">'."Auteur :</span> $observateur</li>".
                        '       </ul>'.
                        '</div>'.
                        '<div class="gauche">'.
                        "       <h3>$intitule #$idCommentaire</h3>".
                        "       <ul>$contenuCommentaire</ul>".
                        '</div>';
                return $description;
        }

        private function creerObservateur($info) {
                $observateur = 'Anonyme';
                if ($info['observateur_prenom'] != '' && $info['observateur_nom'] != '') {
                        $observateur = $info['observateur_prenom'].' '.$info['observateur_nom'];
                }
                return $observateur;
        }

        private function getDerniersCommentaires() {
                $requete = 'SELECT DISTINCT dc.*, '.
                        '       dob.id_observation AS dob_id_observation, dob.ce_zone_geo AS dob_ce_zone_geo, '.
                        '       dob.zone_geo AS dob_zone_geo, dob.date_observation AS dob_date_observation, dob.nom_sel AS dob_nom_sel, '.
                        '       duo.prenom AS observateur_prenom, duo.nom AS observateur_nom, duo.courriel AS observateur_courriel '.
                        'FROM del_commentaire AS dc '.
                        '       INNER JOIN del_observation AS dob '.
                        '               ON dob.id_observation = dc.ce_observation '.
                        '       LEFT JOIN del_utilisateur AS duo '.
                        '               ON dob.ce_utilisateur = duo.id_utilisateur '.
                        'WHERE proposition_initiale != 1 '.
                        $this->chargerClauseWhere().' '.
                        'ORDER BY dc.date DESC '.
                        'LIMIT '.$this->navigation->getDepart().','.$this->navigation->getLimite().' ';

                $elements = $this->gestionBdd->getBdd()->recupererTous($requete);
                return $elements;
        }

        /**
        * Charger la clause WHERE en fonction des paramètres de masque
        * */
        private function chargerClauseWhere() {
                $where = array();

                $tableauMasque = $this->masque->getMasque();
                if (!empty($tableauMasque)) {
                        foreach ($tableauMasque as $idMasque => $valeurMasque) {
                                $idMasque = str_replace('masque.', '', $idMasque);
                                $champ = $this->mappingFiltre[$idMasque];
                                $valeurMasquePattern = $this->gestionBdd->getBdd()->proteger($valeurMasque.'%');
                                $valeurMasqueProtegee = $this->gestionBdd->getBdd()->proteger($valeurMasque);

                                switch ($idMasque) {
                                        case 'espece':
                                                $where[] = " dob.$champ LIKE $valeurMasquePattern OR dc.$champ LIKE $valeurMasquePattern ";
                                                break;
                                        case 'auteur':
                                                $where[] = $this->creerFiltreAuteur($valeurMasque);
                                                break;
                                        default:
                                                $where[] = " $champ = $valeurMasqueProtegee ";
                                }
                        }
                }

                $whereSql = '';
                if (!empty($where)) {
                        $whereSql = ' AND '.implode('AND', $where);
                }
                return $whereSql;
        }

        private function creerFiltreAuteur($auteurId) {
                $whereAuteur = '';
                if (is_numeric($auteurId)) {
                        $whereAuteur = " dc.ce_utilisateur = $auteurId ";
                } else {
                        $auteurIdMotif = $this->gestionBdd->getBdd()->proteger($auteurId.'%');

                        if (strpos($auteurId, '@') === false) {
                                $tableauNomPrenom = explode(' ', $auteurId, 2);
                                if (count($tableauNomPrenom) == 2) {
                                        // on teste potentiellement un nom prenom ou bien un prénom nom
                                        $nomMotif = $this->gestionBdd->getBdd()->proteger($tableauNomPrenom[0].'%');
                                        $prenomMotif = $this->gestionBdd->getBdd()->proteger($tableauNomPrenom[1].'%');

                                        $whereAuteur = ' ('.
                                                "(dc.utilisateur_nom LIKE $nomMotif AND dc.utilisateur_prenom LIKE $prenomMotif) ".
                                                'OR '.
                                                "(dc.utilisateur_nom LIKE $nomMotif AND dc.utilisateur_prenom LIKE $prenomMotif) ".
                                        ') ';
                                } else {
                                        $whereAuteur = "(dc.utilisateur_nom LIKE $auteurIdMotif OR dc.utilisateur_prenom LIKE $auteurIdMotif) ";
                                }
                        } else {
                                $whereAuteur = " dob.utilisateur_courriel LIKE $auteurIdMotif ";
                        }
                }
                return $whereAuteur;
        }
}
?>