Subversion Repositories eFlore/Applications.cel

Rev

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

 <?php
// declare(encoding='UTF-8');
/**
 * Service affichant les dernières photo publiques du CEL ouvrable sous forme de diaporama.
 * Encodage en entrée : utf8
 * Encodage en sortie : utf8
 *
 * Cas d'utilisation et documentation :
 * @link http://www.tela-botanica.org/wikini/eflore/wakka.php?wiki=AideCELWidgetPhoto
 *
 * Paramètres :
 * ===> extra = booléen (1 ou 0)  [par défaut : 1]
 * Affiche / Cache la vignette en taille plus importante au bas du widget.
 * ===> vignette = [0-9]+,[0-9]+  [par défaut : 4,3]
 * Indique le nombre de vignette par ligne et le nombre de ligne.
 *
 * @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   Copyright (c) 2010, Tela Botanica (accueil@tela-botanica.org)
 */
class Manager extends WidgetCommun {

        const DS = DIRECTORY_SEPARATOR;
        const SERVICE_DEFAUT = 'manager';
        private $cel_url_tpl = null;
        /** Si spécifié, on ajoute une barre de navigation inter-applications */
        private $bar;
        //private $parametres_autorises = array('projet', 'type', 'langue', 'order');
        private $parametres_autorises = array(
                'projet' => 'projet',
                'type' => 'type',
                'langue' => 'langue',
                'order' => 'order'
        );

        /**
         * Méthode appelée par défaut pour charger ce widget.
         */
        public function executer() {
                $retour = null;

                // Pour la création de l'id du cache nous ne tenons pas compte du paramètre de l'url callback
                unset( $this->parametres['callback'] );
                extract( $this->parametres );
                $this->bar = ( isset( $bar ) ) ? $bar : false;

                $framework = dirname( __FILE__ ) . '/framework.php';

                if ( !file_exists( $framework ) ) {
                        $e = 'Veuillez paramêtrer l\'emplacement et la version du Framework dans le fichier $framework';
                        trigger_error( $e, E_USER_ERROR );
                } else {
                        // Inclusion du Framework
                        require_once $framework;
                        // Ajout d'information concernant cette application
                        Framework::setCheminAppli( __FILE__ );// Obligatoire
                        Framework::setInfoAppli( Config::get( 'info' ) );// Optionnel
                }

                if ( !isset( $mode ) ) {
                        $mode = self::SERVICE_DEFAUT;
                }

                $this->cel_url_tpl = $this->config['manager']['celUrlTpl'];

                if ( $_POST !== array() ) { //print_r($_POST);
                        $this->parametres['projet'] = $_POST['projet'];
                        $this->parametres['langue'] = $_POST['langue'];

                        if ( $mode === 'modification' ) {
                                $parametres = $this->traiterParametresModif();
                                $donnees    = array_merge( $parametres, $this->traiterDonneesFiles() );
                                $json       = $this->getDao()->modifier( $this->cel_url_tpl, $donnees );
                        } else {
                                $donnees = array_merge( $_POST, $this->traiterDonneesFiles() );
                                $json    = $this->getDao()->ajouter( $this->cel_url_tpl, $donnees );
                                $mode    = $this->parametres['mode'] = 'modification';
                        }
                }

                $methode = $this->traiterNomMethodeExecuter( $mode );
                if ( method_exists( $this, $methode ) ) {
                        $retour = $this->$methode();
                } else {

                        $this->messages[] = "Ce type de service '$methode' n'est pas disponible.";
                }

                $contenu = '';
                if ( is_null( $retour ) ) {
                        $this->messages[] = 'La ressource demandée a retourné une valeur nulle.';

                } else {

                        if ( isset( $retour['donnees'] ) ) {
                                $retour['donnees']['params']        = '&projet=' . $_POST['projet'] . '&langue=' . $_POST['langue'];
                                $retour['donnees']['prod']          = ( $this->config['parametres']['modeServeur'] === 'prod' );
                                $retour['donnees']['bar']           = $this->bar;
                                $retour['donnees']['url_base']      = sprintf( $this->config['chemins']['baseURLAbsoluDyn'], '' );
                                $retour['donnees']['chemin_images'] = sprintf( $this->config['chemins']['baseURLAbsoluDyn'], $this->config['manager']['dossierTmp'] );
                                $retour['donnees']['mode']          = $mode;
                                $squelette = dirname( __FILE__ ) . self::DS . 'squelettes' . self::DS . $retour['squelette'] . '.tpl.html';
                                $contenu   = $this->traiterSquelettePhp( $squelette, $retour['donnees'] );
                        } else {
                                $this->messages[] = 'Les données à transmettre au squelette sont nulles.';
                        }
                }
                $this->envoyer($contenu);
        }

        private function executerManager() {
                $params = array();
                $retour['squelette'] = 'manager';

                foreach ( $this->parametres_autorises as $id => $pa ) {
                        if ( isset( $this->parametres[$pa] ) ) {
                                $params[] = $pa . '=' . $this->parametres[$pa];
                        }
                }

                $param = implode( $params, '&' );
                $url   = $this->cel_url_tpl;

                if ( $param !== '' ) {
                        $url .= '?' . $param;
                }

                $json = $this->getDao()->consulter( $url );
                $retour['donnees']['widget']        = (array) json_decode( $json, true );
                $retour['donnees']['widgetUrlTpl']  = $this->config['manager']['widgetUrlTpl'];

                return $retour;
        }

        private function executerCreation() {
                //https://api.tela-botanica.org/service:cel:NomsChampsEtendus/cle
                $jsonlangue    = $this->getDao()->consulter( $this->config['manager']['languesUrl'] );
                $tableaulangue = (array) json_decode( $jsonlangue, true );
                $retour['squelette']          = 'creation';
                $retour['donnees']['langues'] = $tableaulangue['resultat'] ;
                $retour['donnees']['widget']  = array();

                if ( isset( $this->parametres['projet'] ) ) {
                        $url     = $this->cel_url_tpl . '?projet=' . $this->parametres['projet'];
                        $json    = $this->getDao()->consulter( $url );
                        $tableau = (array) json_decode( $json, true );
                        $retour['donnees']['widget'] = $tableau[0];
                }

                $urltype     = $this->cel_url_tpl . '?esttype=1';
                $jsontype    = $this->getDao()->consulter( $urltype );
                $tableautype = (array) json_decode( $jsontype, true );
                $retour['donnees']['type'] = $tableautype;

                return $retour;
        }

        private function executerModification() {
                $retour = array();
                if ( isset( $this->parametres['projet'] ) ) {

                        $url     = $this->cel_url_tpl . '?projet=' . $this->parametres['projet'] . '&langue=' . $this->parametres['langue'];
                        $json    = $this->getDao()->consulter( $url );
                        $tableau = (array) json_decode( $json, true );
                        $retour['squelette']         = 'creation';
                        $retour['donnees']['widget'] = $tableau[0];
                        // obtenir un tableau de coordonnées+zoom expoitable
                        if (isset($retour['donnees']['widget']['localisation'])) {
                                $retour['donnees']['widget']['tableau-localisation'] = $this->traiterLocalisation($retour['donnees']['widget']['localisation']);
                        }
                        // En prévision d'un service permettant la suppression/modification champs supp
                        $retour['donnees']['widget']['chpSupp'] = $this->rechercherChampsSupp();

                        $urltype     = $this->cel_url_tpl .'?esttype=1';
                        $jsontype    = $this->getDao()->consulter( $urltype );
                        $tableautype = (array) json_decode( $jsontype, true );
                        $retour['donnees']['type'] = $tableautype;
                }//print_r($retour['donnees']);

                return $retour;
        }

        private function traiterParametres() {
                $parametres_flux = '?';
                $criteres        = array( 'projet', 'langue', 'titre' );

                foreach( $this->parametres as $nom_critere => $valeur_critere ) {
                        if ( in_array( $nom_critere, $criteres ) ) {
                                $valeur_critere   = str_replace( ' ', '%20', $valeur_critere );
                                $parametres_flux .= $nom_critere . '=' . $valeur_critere . '&';
                        }
                }

                $parametres_flux = ( $parametres_flux === '?' ) ? '' : rtrim( $parametres_flux, '&' );

                return $parametres_flux;
        }

        private function traiterParametresModif() {
                $parametres_modif = array();

                foreach ( $_POST as $id => $parametres ) {
                        if ($parametres !== '' ) {
                                $parametres_modif[$id] = addslashes($parametres);
                        } else {
                                $parametres_modif[$id] = ' ';
                        }
                }
                return $parametres_modif;
        }

        private function traiterLocalisation( $infos_localisation ) {
                $infos = explode(';', $infos_localisation);
                $tableauTmp = array();
                $retour = array();
                foreach ($infos as $info) {
                        $tableauTmp = explode(':', $info);
                        $retour[$tableauTmp[0]] = $tableauTmp[1];
                }
                return $retour;
        }

        private function traiterDonneesFiles() {
                $return = array();
                $transmettre_donnees = false;
                $files_names = array();
                $help_files_names = array();
                $error =
                        "<div class=\"message-echec container\">Echec du téléchargement : ".
                        "L\'extention de l\'image pour " . $nom . " n\'est pas bonne".
                        ", formats acceptés : png, gif, jpg, jpeg, csv, ou tsv.".
                        "</div>";
                $image_projet_langue = ( $this->parametres['langue'] !== 'fr' ) ? '_' . $this->parametres['langue'] : '';
                $dossier_url = __DIR__ . '/squelettes/img/images_projets/' . $_POST['projet'] . $image_projet_langue . '/';

                foreach ( array_keys( $_FILES ) as $file ) {
                        if ( $_FILES[$file]['name'] !== '' ) {
                                $extension = $this->obtenirExtension( $_FILES[$file] );

                                if ( $extension ) {
                                        $transmettre_donnees = true;

                                        if ( strstr( $file, 'help-') ) {
                                                // Pas besoin de $return :
                                                // Type déjà transmis dans le json des champs supp
                                                $real_file_key = str_replace( 'help-', '', $file );
                                                $help_files_names[$real_file_key] = $real_file_key . '.' . $extension;
                                        } else {
                                                $return[$file] = $_FILES[$file]['type'];
                                                $files_names[$file] = $file .'.' . $extension;
                                        }
                                } else {
                                        echo $error;
                                }
                        }
                }

                if ( $transmettre_donnees ) {
                        if( !is_dir( $dossier_url ) ) {
                                mkdir( $dossier_url, 0755 );
                        }
                        // Téléversements
                        if ( count( $files_names ) > 0 ) {
                                foreach ( array_keys( $files_names ) as $file ) {
                                        $this->televerser( $file, $files_names[ $file ], $dossier_url );
                                }
                        }
                        if ( count( $help_files_names ) > 0 ) {
                                foreach ( array_keys( $help_files_names ) as $file ) {
                                        $this->televerser( 'help-' . $file, $help_files_names[ $file ], $dossier_url );
                                }
                        }
                }
                return $return;
        }

        private function televerser( $file, $full_name, $dossier_url ) {
                $taille_maxi  = 5242880;
                $taille       = filesize( $_FILES[$file]['tmp_name'] );
                $extension    = $this->obtenirExtension( $_FILES[$file] );
                $file_name    = str_replace( '.' . $extension, '', $full_name );
                $file_exists  = file_exists( $dossier_url . $full_name );
                $ex_file_name = $full_name;

                // verifier l'existance d'un fichier avec une extention différente
                // ex: logo.png vers logo.jpg
                if ( !$file_exists ) {
                        switch ( $extension ) {
                                case 'png':
                                        $ex_file_name = $file_name . '.jpg';
                                        break;
                                case 'csv':
                                        $ex_file_name = $file_name . '.tsv';
                                        break;
                                case 'tsv':
                                        $ex_file_name = $file_name . '.csv';
                                        break;
                                case 'jpg':
                                default:
                                        $ex_file_name = $file_name . '.png';
                                        break;
                        }
                        $file_exists = file_exists( $dossier_url . $ex_file_name );
                }

                //Début des vérifications de sécurité...
                if ( $file_exists ) {
                        if ( $this->parametres['mode'] === 'modification' ) {
                                // Le fichier existe déjà, c'est normal si on est en mode modification
                                unlink( $dossier_url . $ex_file_name );
                        } else {
                                $erreur =
                                        "<div class=\"message-echec container\">Echec du téléchargement : ".
                                                "Un fichier pour \"" . $file_name.
                                                "\", existe déjà dans un projet nommé \"" . $_POST['projet'] . "\".".
                                                "<br>Vérifiez que le nom du projet n'est pas déjà pris, ".
                                                "ou qu'un fichier \"" . $full_name . "\" n'ait pas déjà été téléchargé pour ce projet.".
                                        "</div>";
                        }
                }

                if ( !$extension ) {
                        //Si le format n'est pas bon
                        $erreur =
                                "<div class=\"message-echec container\">".
                                        "Echec du téléchargement pour ".
                                        "\"" . $file_name . "\" ".
                                        ", formats acceptés : png, gif, jpg, jpeg, csv, ou tsv".
                                "</div>";
                }

                if ( $taille > $taille_maxi ) {
                        $erreur =
                                "<div class=\"message-echec container\">".
                                        "Echec du téléchargement pour ".
                                        "\"" . $file_name . "\" ".
                                        ": Max 5Mo".
                                "</div>";
                }

                if ( isset( $erreur ) ) {
                        echo $erreur;
                } else {
                        $dest_file = $dossier_url . $this->remove_accents( $full_name );
                        if ( !move_uploaded_file( $_FILES[$file]['tmp_name'], $dest_file ) ) {
                        // move_uploaded_file() renvoie false si l'upload a échoué
                                echo
                                        "<div class=\"message-echec container\">".
                                                "Erreur du téléchargement pour ".
                                                "\"" . $file_name . "\"".
                                        "</div>";
                        } else {
                                chmod($dest_file, 0666);
                        }
                }
        }

        private function obtenirExtension( $files ) {
                $type = exif_imagetype( $files['tmp_name'] );

                //une vérif pas mal pour les types image
                if ( $type == ( IMAGETYPE_PNG || IMAGETYPE_JPEG || IMAGETYPE_GIF ) ) {
                        switch ( $type ) {
                                case '1' :
                                        $format = 'gif';
                                        break;
                                case '2' :
                                        $format = 'jpg';
                                        break;
                                case '3' :
                                        $format = 'png';
                                        break;
                                default :
                                        break;
                        }
                } elseif ( str_replace( '.csv' , '', $files['name'] ) && substr( strrchr($files['type'], '/' ), 1 ) === 'csv' ) {
                        // Pas trouvé mieux pour csv :
                        // Les fonctions qui pourraient utiliser $_FILES[file]["tmp_path"] me répondent "text/plain"...
                        $format = 'csv';
                } elseif ( str_replace( '.tsv' , '', $files['name'] ) && substr( strrchr($files['type'], '/' ), 1 ) === 'tab-separated-values' ) {
                        $format = 'tsv';
                } else {
                        return false;
                }
                return $format;
        }

        // En prévision d'un service permettant la suppression/modification champs supp
        /* Recherche si un projet a des champs de saisie supplémentaire */
        private function rechercherChampsSupp() {
                $retour = array();
                $projet = $this->parametres['projet'];
                $url = $this->config['manager']['celChpSupTpl'] .'?projet=' . $projet . '&langue=' . $this->parametres['langue'];
                $json = $this->getDao()->consulter($url);
                $retour = (array) json_decode($json, true);

                foreach ( $retour[$projet]['champs-supp'] as $key => $chsup ) {

                        $retour[$projet]['champs-supp'][$key]['name'] = $this->clean_string( $chsup['name'] );
                        $retour[$projet]['champs-supp'][$key]['description'] = $this->clean_string( $chsup['description']);
                        $retour[$projet]['champs-supp'][$key]['unit'] = $this->clean_string( $chsup['unit'] );

                        if ( isset( $chsup['fieldValues'] ) ) {
                                $retour[$projet]['champs-supp'][$key]['fieldValues'] = json_decode( $this->clean_string( $chsup['fieldValues'] ), true );

                                if ( isset( $retour[$projet]['champs-supp'][$key]['fieldValues']['listValue'] ) ) {
                                        foreach( $retour[$projet]['champs-supp'][$key]['fieldValues']['listValue'] as $list_key => $list_value_array ) {
                                                // Obtenir une liste de valeurs utilisables dans les attributs for id ou name par exemple
                                                $retour[$projet]['champs-supp'][$key]['fieldValues']['cleanListValue'][] = ($list_value_array !== 'other') ? 'val-' . preg_replace( '/[^A-Za-z0-9_\-]/', '', $this->remove_accents( strtolower($list_value_array[0] ) ) ) : '';
                                        }
                                }
                        }
                        $retour[$projet]['champs-supp'][$key]['mandatory'] = intval( $chsup['mandatory'] );
                        $retour[$projet]['champs-supp'][$key]['is_visible'] = intval( $chsup['is_visible'] );
                }
                // renvoyer un json exploitable par le sccript js
                $retour[$projet]['champs-supp-json'] = json_encode($retour[$projet]['champs-supp']);
                return $retour;
        }
}