Subversion Repositories eFlore/Applications.cel

Rev

Rev 473 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
/**
 * Service fournissant des informations concernant le CEL au format RSS1, RSS2 ou ATOM.
 * Encodage en entrée : utf8
 * Encodage en sortie : utf8
 * 
 * @author Jean-Pascal MILCENT <jpm@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 CelSyndicationImage extends Cel {
        
        private $format = null;
        private $service = null;
        private $squelette = null;
        private $squelette_dossier = null;
        private $flux = array();
        
        private $format_image = 'L';
        
        /**
         * Méthode appelée avec une requête de type GET.
         */
        public function getElement($param = array()) {
                // Initialisation des variables
                $info = array();
                $contenu = '';
                        
                // Pré traitement des paramêtres
                $pour_bdd = false;
                $p = $this->traiterParametres(array('service', 'format'), $param, $pour_bdd);
                unset($param[0]);
                unset($param[1]);
                
                sort($param);
                
                extract($p);
                
                // Récupération de la liste des flux
                $this->chargerListeDesFlux();
                
                // Chargement du bon type de service demandé
                if (isset($service)) {
                        $this->service = $service;
                        $methode = $this->getNomMethodeService();
                        if (method_exists($this, $methode)) {
                                if ($this->service != 'liste_des_flux') {
                                        if (isset($format) && preg_match('/^(?:rss1|rss2|atom)$/i', $format)) {
                                                // Multiplication par deux de la limite car nous récupérons deux lignes par item
                                                $this->limit = $this->limit*2;
                                                // Mise en minuscule de l'indication du format
                                                $this->format = strtolower($format);
                                                // Définition du fichier squelette demandé
                                                $this->squelette_dossier = dirname(__FILE__).DIRECTORY_SEPARATOR.'squelettes'.DIRECTORY_SEPARATOR;
                                                $this->squelette = $this->squelette_dossier.$this->format.'.tpl.xml';
                                        } else {
                                                $this->format = '';
                                                $this->messages[] = "Le service CEL Syndication nécessite d'indiquer en second paramètre le format : rss1, rss2 ou atom.";
                                        }
                                }
                                // Récupération du contenu à renvoyer
                                $contenu = $this->$methode($param);
                        } else {
                                $this->messages[] = "Le type d'information demandé '$this->service' n'est pas disponible.";
                        }
                } else {
                        $this->messages[] = "Le service CEL Syndication Image nécessite d'indiquer en premier paramètre le type d'information demandé.";
                }
                
                // Envoie sur la sortie standard
                $encodage = 'utf-8';
                $mime = $this->getTypeMime();
                $formatage_json = $this->getFormatageJson();
                $this->envoyer($contenu, $mime, $encodage, $formatage_json);
        }
        
        private function getUrlServiceBase() {
                $url_service = $this->config['settings']['baseURLAbsoluDyn'].'CelSyndicationImage/'.$this->service.'/'.$this->format;
                return $url_service;
        }
        
        private function getUrlImageBase($id, $format = 'L') {
                
                        $chemin_sur_serveur = $this->config['cel_db']['url_images'];
                
                        $id = sprintf('%09s', $id) ;
            $id = wordwrap($id, 3 , '_', true) ;
        
            $id_fichier = $id.".jpg" ;
            
            $niveauDossier = split("_", $id) ;
            
            $dossierNiveau1 = $niveauDossier[0] ;
            $dossierNiveau2 = $niveauDossier[1] ;
            
            $chemin_sur_serveur_final = $chemin_sur_serveur.'/'.$dossierNiveau1.'/'.$dossierNiveau2 ;
            $chemin_fichier = $chemin_sur_serveur_final.'/'.$format.'/'.$id.'_'.$format.'.jpg'; 

            return $chemin_fichier;
        }
        
        private function getNomMethodeService() {
                $methode = '';
                $service_formate = str_replace(' ', '', ucwords(implode(' ', explode('_', $this->service))));
                $methode = 'getService'.$service_formate;
                return $methode;
        }
        
        private function getTypeMime() {
                $mime = '';
                switch ($this->format) {
                        case 'atom' :
                                $mime = 'application/atom+xml';
                                break;
                        case 'rss1' :
                        case 'rss2' :
                                $mime = 'application/rss+xml';
                                break;
                        default:
                                $mime = 'text/html';
                }
                return $mime;
        }
        
        private function getFormatageJson() {
                $json = false;
                switch ($this->service) {
                        case 'liste_des_flux' :
                                $json = true;
                                break;
                        default:
                                $json = false;
                }
                return $json;
        }
        
        private function getFlux($nom) {
                return isset($this->flux[$nom]) ? $this->flux[$nom] : array();
        }

        private function setFlux($nom, $titre, $description) {
                $url_base = $this->config['settings']['baseURLAbsoluDyn'].'CoelSyndicationImage/';
                $formats = array('atom', 'rss2', 'rss1');
                $flux = array();
                foreach ($formats as $format) {
                        $url = $url_base.$nom.'/'.$format;
                        $flux[$format] = $url;
                }
                $this->flux[$nom] = array('titre' => $titre, 'description' => $description, 'urls' => $flux);
        }
        
        private function chargerListeDesFlux() {
                $this->setFlux('RssParDefaut', 'Flux de syndication par défaut', 
                        'Ce flux fournit des informations sur les images du CEL.');
                $this->setFlux('RssParMotsCles', 'Flux des images filtré par mots clés', 
                        'Ce flux fournit des informations sur les images du CEL filtrées par mots-clés.');
                $this->setFlux('RssParLocalisation','Flux des images filtré par localisation',
                        'Ce flux fournit des informations sur les images du CEL filtrées par localisation.');
        }
        
        private function getServiceListeDesFlux() {
                return $this->flux;
        }
        
        private function getServiceParDefaut() {
                // Construction de la requête
                $requete =      (($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' * '.
                        'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'date_modification DESC').' '.
                        "LIMIT $this->start,$this->limit ";
                
                $elements = $this->executerRequete($requete);
                
                // Création du contenu
                $contenu = $this->executerService($elements);
                return $contenu;
        }
        
        private function getServiceSimple($params) {
                
                if(isset($params[0])) {
                        $this->format_image = $params[0];
                }
                
                $this->start = 0;
                $this->limit = 10;
                
                // Construction de la requête
                $requete =      (($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' * '.
                        'FROM cel_obs_images a '.
                        'INNER JOIN cel_inventory b '.
                                'ON a.coi_ce_observation = b.ordre AND a.coi_ce_utilisateur = b.identifiant '.
                        'INNER JOIN cel_images c '.
                                'ON a.coi_ce_image = c.ci_id_image AND a.coi_ce_utilisateur = c.ci_ce_utilisateur '.  
                        'WHERE b.transmission = 1 AND b.identifiant = c.ci_ce_utilisateur '.
                        'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'ci_meta_date_ajout DESC').' '.
                        "LIMIT $this->start,$this->limit ";
                
                $elements = $this->executerRequete($requete);
                
                // Création du contenu
                $contenu = $this->executerService($elements);
                return $contenu;
        }
        
        protected function executerRequete($requete) {
                try {
                        $infos = $this->bdd->query($requete)->fetchAll(PDO::FETCH_ASSOC);
                        if ($infos === false) {
                                $this->messages[] = "La requête suivante a retourné aucun résultat :\n$requete";
                        }
                } catch (PDOException $e) {
                        $this->messages[] = sprintf($this->getTxt('sql_erreur'), $e->getFile(), $e->getLine(), $e->getMessage());
                }
                return $infos;
        }
        
        private function executerService($elements) {
                
                // Prétraitement des données
                $donnees = $this->construireDonneesCommunesAuFlux($elements);
                
                foreach ($elements as $element) {
                        $donnees['items'][] = $this->construireDonneesCommunesAuxItems($element);
                }
                
                // Création du contenu à partir d'un template PHP
                $contenu = Cel::traiterSquelettePhp($this->squelette, $donnees);
                
                return $contenu;
        }
        
        private function construireDonneesCommunesAuFlux($infos) {
                $donnees = $this->getFlux($this->service);
                $donnees['guid'] = $this->getUrlServiceBase();
                $donnees['lien_service'] = $this->creerUrlService();
                $donnees['lien_cel'] = sprintf($this->config['settings']['efloreUrlTpl'], $infos['num_nom_sel']);
                $donnees['editeur'] = $this->config['settings']['editeur'];
                $derniere_info_en_date = reset($infos);
                $date_modification_timestamp = strtotime($derniere_info_en_date['ci_meta_date_ajout']);
                $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'] = 'CEL - Jrest - CelSyndicationImage';
                preg_match('/([0-9]+)/', '$Revision$', $match);
                $donnees['generateur_version'] = $match[1];
                return $donnees; 
        }
        
        private function construireDonneesCommunesAuxItems($info) {
                
                $item = array();
                $date_modification_timestamp = strtotime($info['ci_meta_date_ajout']);
                $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['description'] = $this->creerDescription($info);
                $item['description_encodee'] = htmlspecialchars($item['description']);
                return $item;
        }
        
        private function creerTitre($element) {
                
                $titre = '';
                $titre = $element['nom_sel'].' [nn'.$element['num_nom_sel'].'] par '.$this->creerAuteur($element['identifiant']);
                
                return $titre;
        }
        
        private function nettoyerTexte($txt) {
                $txt = preg_replace('/&(?!(a-z+|#0-9+|#x0-9a-f+);)/i', '&amp;', $txt, -1);
                return $txt;
        }
        
        private function creerGuidItem($element) {
                $guid = sprintf($this->config['settings']['guidImgTpl'], $element['ci_id_image']);
                return $guid;
        }
        
        private function creerLienItem($element) {
                
                $lien = $this->getUrlImageBase($element['ci_id_image'],$this->format_image);
                return $lien;
        }
        
        private function creerDescription($element) {
                
                $description = sprintf($this->config['settings']['efloreUrlTpl'], urlencode($element['num_nom_sel']));
                $description = $this->nettoyerTexte($description);
                
                return $description;
        }
        
        private function creerAuteur($courriel) {
                $auteur = ($this->etreFluxAdmin()) ? $courriel : $this->traiterCourriel($courriel);
                return $auteur;
        }
        
        private function traiterCourriel($courriel) {
                $courriel = preg_replace('/[^@]+$/i', '...', $courriel);
                return $courriel;
        }
        
        private function etreFluxAdmin() {
                return ($this->service == 'pour-admin') ? true : false;
        }
        
        private function etreNull($valeur) {
                $etre_null = false;
                if ($valeur == '' || $valeur == null || $valeur == '000null' || $valeur == 'null') {
                        $etre_null = true;
                }
                return $etre_null;
        }
        
        private function creerUrlService() {
                $url_service = $this->getUrlServiceBase();
                if (isset($this->start) || isset($this->limit)) {
                        $arguments = array();
                        if (isset($this->start) && isset($_GET['start'])) {
                                $arguments[] = 'start='.$this->start;
                        }
                        if (isset($this->limit) && isset($_GET['limit'])) {
                                $arguments[] = 'limit='.($this->limit/2);
                        }
                        if (count($arguments) > 0) {
                                $url_service .= '?'.implode('&', $arguments);
                        }
                }
                return $url_service;
        }
        
        function calculerDimensions($tailleXY, $tailleoR = 300) {
        
        if($tailleXY[1] == 0) {
            $tailleXY[1] = $tailleOr;
        }
        
        if($tailleXY[0] == 0) {
            $tailleXY[0] = $tailleOr;
        }
        
        $maxTaille = max($tailleXY[1],$tailleXY[0]) ;
        
        if($maxTaille == $tailleXY[1]) {
            
            $rapport = $tailleXY[1]/$tailleXY[0] ;
            $tailleXY[1] = $tailleOr ;
            $tailleXY[0] = round($tailleXY[1]/$rapport,0) ;
            
        }else {
            $rapport = $tailleXY[0]/$tailleXY[1] ;
            $tailleXY[0] = $tailleOr ;
            $tailleXY[1] = round($tailleXY[0]/$rapport,0) ;  
        }
        
        return $tailleXY ;
    }
}