Subversion Repositories Applications.referentiel

Rev

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

<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Versionnage de référentiels de nomenclature et taxonomie
*
* Description : classe permettant de versionner les référentiels selon le manuel technique
* Utilisation : php script.php versionnage -p bdnff -a tout
*
//Auteur original :
* @author       Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright    Tela-Botanica 1999-2010
* @link                 http://www.tela-botanica.org/wikini/RTaxMethodo/wakka.php?wiki=MaNuel
* @licence              GPL v3 & CeCILL v2
* @version              $Id$
*/
// +-------------------------------------------------------------------------------------------------------------------+
// TODO : supprimer l'utilisation du paramêtres 'p' et chercher les infos depuis la bdd
class Versionnage extends ScriptCommande {
        
        const SCRIPT_NOM = 'versionnage';
        const MANUEL_VERSION = "2.1";
        
        private $projet = null;
        private $traitement = null;
        private $meta = null;
        private $version_courante = null;
        private $messages = null;
        private $manuel = null;
        private $manuel_nom = null;
        private $manuel_chemin = null;
        private $zip_chemin_dossier = null;
        private $zip_chemin_fichier = null;
        
        private $noms = null;
        private $noms_precedents = null;
        private $noms_stat = null;
        private $champs_ordre = null;
        private $champs_nom = null;
        private $diff_modif_types = null;
        private $signature_md5 = null;
        
        private $resultatDao = null;
        private $traitementDao = null;
        private $metaDao = null;
        private $tableStructureDao = null;
        private $referentielDao = null;
        
        public function executer() {
                // Récupération de paramêtres
                $this->projet = $this->getParam('p');
                
                // Récupération du dernier traitement demandé
                $this->traitementDao = new TraitementDao();
                $this->traitement = $this->traitementDao->getDernierTraitement($this->projet, self::SCRIPT_NOM);
                if (isset($this->traitement)) {
                        Debug::printr($this->traitement);
                        // Écriture de la date de début du traitement
                        Debug::printr('Debute:'.$this->traitementDao->debuterTraitement($this->traitement['id_traitement']));
                        
                        // Nettoyage des traitements obsolètes
                        $traitements_obsoletes = $this->traitementDao->getTraitementsObsoletes($this->projet, self::SCRIPT_NOM);
                        if (isset($traitements_obsoletes)) {
                                Debug::printr('Supp. obsoletes:'.$this->traitementDao->supprimer($traitements_obsoletes));
                        }
                        
                        // Lancement du test demandé
                        $cmd = $this->getParam('a');
                switch ($cmd) {
                                case 'tout' :
                                        $this->initialiserScript();
                                        Debug::printr('Départ lancement versionnage:');
                                        $this->lancerVersionnage();
                                        break;
                                default :
                                        $this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
                        }
                        // Écriture de la date de fin du traitement
                        Debug::printr('Termine:'.$this->traitementDao->terminerTraitement($this->traitement['id_traitement']));
                }
    }
        
    private function initialiserScript() {
                $this->metaDao = new MetaDao();
                $this->resultatDao = new ResultatDao();
                $this->referentielDao = new ReferentielDao();
                
                $this->manuel_nom = 'mtpr_v'.str_replace('.', '_', self::MANUEL_VERSION).'.pdf';
                $this->manuel_chemin = Config::get('chemin_appli').DS.'..'.DS.'configurations'.DS;
                
                $manuel_config_nom = 'referentiel_v'.self::MANUEL_VERSION.'.ini';
                $this->manuel = parse_ini_file($this->manuel_chemin.$manuel_config_nom);
        }
        
    public function lancerVersionnage() {
                $this->chargerTraitementParametre();
                $this->initialiserNomVersionCOurante();
                $this->initialiserCheminsZip();
                $this->creerDossierZip();
                $this->archiver();
        $this->chargerNomsATraiter();
        $this->analyserNomsATraiter();
                $this->creerFichiers();
                $this->nettoyerFichiers();
                $this->traiterMessages();
        }
        
        private function chargerTraitementParametre() {
                $this->meta = unserialize($this->traitement['script_parametres']);
        }
        
        private function archiver() {
                $ok = $this->referentielDao->archiver($this->projet, $this->meta['version']);
                if ($ok) {
                        $m = "L'archivage de la version '{$this->meta['version']}' du référentiel '{$this->projet}' a réussi";
                        $this->ajouterMessage($m);
                } else {
                        $m = "L'archivage de la version '{$this->meta['version']}' du référentiel '{$this->projet}' a échoué";
                        $this->ajouterMessage($m);
                }
        }
        
        private function initialiserNomVersionCOurante() {
                $this->version_courante = strtolower($this->projet).'_v'.str_replace('.', '_', $this->meta['version']);
                Debug::printr("Nom archive courante :".$this->version_courante);
        }
        
        private function initialiserCheminsZip() {
                $this->zip_chemin_dossier = Config::get('chemin_referentiel_zip').$this->version_courante.DIRECTORY_SEPARATOR;
                $this->zip_chemin_fichier = Config::get('chemin_referentiel_zip').$this->version_courante.'.zip';
        }
        
        private function creerDossierZip() {
                $recursivite = true;
                if (mkdir($this->zip_chemin_dossier, 0777, $recursivite) === false) {
                        $this->ajouterMessage("La création du dossier '$this->zip_chemin_dossier' devant contenir les fichiers a échouée.");
                }
        }
        
        private function chargerNomsATraiter() {
                $this->noms = $this->referentielDao->getTout($this->version_courante);
        }
        
        private function analyserNomsATraiter() {
                $this->noms_stat['combinaison'] = $this->getNombreCombinaison();
                $this->noms_stat['taxon'] = $this->getNombreTaxon();
                Debug::printr("Stats :".print_r($this->noms_stat, true));
        }
        
        private function getNombreCombinaison() {
                return count($this->noms);
        }
        
        private function getNombreTaxon() {
                $nbre = 0;
                foreach ($this->noms as $nom) {
                        if ($nom['num_nom_retenu'] == $nom['num_nom']) {
                                $nbre++;
                        }
                }
                return $nbre;
        }
        
        private function creerFichiers() {
                // Respecter l'ordre de traitement : BDNT puis DIFF puis META
                $this->creerFichierBdnt();
                $this->creerFichierDiff();
                $this->creerFichierMeta();
                $this->nettoyerMemoire();
                $this->copierManuel();
                $this->creerFichierZip();
        }
        
        private function creerFichierBdnt() {
                $noms =& $this->noms;
                reset($this->noms);
                Debug::printr("Element courrant du tableau des noms : ".count($this->noms).'-'.print_r(current($this->noms),true));
                
                $this->determinerOrdreDesChamps();
                $this->definirNomDesChamps();
                
                $donnees = array();
                $donnees['champs'] = $this->champs_nom;
                foreach ($this->noms as &$nom) {
                        $infos = array();
                        foreach ($nom as $champ => &$valeur) {
                                if (isset($this->champs_ordre[$champ])) {
                                        $ordre = $this->champs_ordre[$champ];
                                        $infos[(int) $ordre] = trim($valeur);
                                } else {
                                        $e = "Le champ '$champ' n'a pas été pris en compte dans l'attribution de l'ordre des champs.";
                                        $this->ajouterMessage($e);
                                }
                        }
                        ksort($infos);
                        $infos = $this->remplacerTabulation($infos);
                        $infos = $this->remplacerSautsDeLigne($infos);
                        $donnees['noms'][] = $infos;
                }
                Debug::printr("Dernier element du tableau des noms [trié] : ".print_r($infos,true));
                $bdnt_tsv =& $this->getVue('versionnage/squelettes/bdnt', $donnees, '.tpl.tsv');
                $this->ecrireFichierBdnt($bdnt_tsv);
        }
        
        private function determinerOrdreDesChamps() {
                $champs_ordre = explode(',', $this->manuel['champs']);
                $champs_ordre = array_flip($champs_ordre);
                $nom_courant = current($this->noms);
                $champs_ordre = $this->attribuerOrdreChampsSupplémentaires($champs_ordre, $nom_courant);
                asort($champs_ordre);
                $this->champs_ordre = $champs_ordre;
                Debug::printr("Ordre des champs : ".print_r($this->champs_ordre,true));
        }
        
        private function definirNomDesChamps() {
                $this->champs_nom = array_flip($this->champs_ordre);
        }
        
        private function attribuerOrdreChampsSupplémentaires($champs_ordre, $nom) {
                foreach ($nom as $champ => $info) {
                        if (!isset($champs_ordre[$champ])) {
                                $champs_ordre[$champ] = count($champs_ordre);
                        }
                }
                return $champs_ordre;
        }
        
        private function ajouterMessage($message) {
                $titre = self::SCRIPT_NOM.' #'.$this->traitement['id_traitement'];
                $this->messages[] = array('message' => $message, 'resultat' => true);
        }
        
        private function ecrireFichierBdnt(&$contenu) {
                $fichier_nom = $this->getBaseNomFichier().$this->manuel['ext_fichier_bdnt'];
                $fichier_chemin = $this->zip_chemin_dossier.$fichier_nom;
                
                if ($this->ecrireFichier($fichier_chemin, $contenu)) {
                        $this->ajouterMessage("Écriture du fichier bdnt réussie.");
                        $this->signature_md5 = md5_file($fichier_chemin);
                        $this->ajouterMessage("Signature MD5 du fichier bdnt :".$this->signature_md5);
                        $this->ajouterMessage("Nombre de combinaisons traités : ".$this->noms_stat['combinaison']);
                }
        }
        
        private function getBaseNomFichier() {
                return strtolower($this->meta['acronyme'].'_v'.$this->meta['version']);
        }
        
        private function ecrireFichier($fichier_chemin, &$contenu) {
                $retour = true;
                if (file_put_contents($fichier_chemin, $contenu) == false) {
                        $e = "Une erreur est survenu lors de l'écriture du fichier : $fichier_chemin";
                        $this->ajouterMessage($e);
                        $retour = false;
                }
                return $retour;
        }
        
        private function creerFichierDiff() {
                $derniere_meta = $this->metaDao->getDerniere($this->projet);
                if (is_null($derniere_meta === false)) {
                        $this->ajouterMessage("Un problème est survenu lors de la récupération des métadonnées précédentes.");
                } else if (is_null($derniere_meta)) {
                        $this->ajouterMessage("Premier versionnage pour ce projet, aucun fichier différentiel ne sera créé.");
                } else {
                        $code_projet_precedent = strtolower($derniere_meta['code']).'_v'.str_replace('.', '_', $derniere_meta['version']);
                        if ($code_projet_precedent == $this->version_courante) {
                                $e = "La code de la version préalablement versionnée ($code_projet_precedent) est le même que celui ".
                                        "de la demande actuel ({$this->version_courante}) pour ce projet, aucun fichier différentiel ne sera créé.";
                                $this->ajouterMessage($e);
                        } else {
                                $this->noms_precedents = $this->referentielDao->getTout($code_projet_precedent);
                                $donnees = array();
                                $donnees['diff'] =& $this->realiserDiff();
                                $donnees['champs'] = $this->champs_nom;
                                $diff_tsv = $this->getVue('versionnage/squelettes/diff', &$donnees, '.tpl.tsv');
                                $this->ecrireFichierDiff($diff_tsv);
                        }
                }
        }
        
        private function realiserDiff() {
                $diff = array();
                $this->noms_stat['modification'] = 0;
                $i = 0;
                foreach ($this->noms as $id => &$nom) {
                        $infos = array();
                        if (!isset($this->noms_precedents[$id])) {
                                $infos = $nom;
                                $infos['modification_type'] = 'A';
                                $infos['modification_type_1'] = '0';
                                $infos['modification_type_2'] = '0';
                                $infos['modification_type_3'] = '0';
                                $this->noms_stat['modification']++;
                        } else {
                                $nom_precedent =& $this->noms_precedents[$id];
                                $nom_diff = array_diff_assoc($nom, $nom_precedent);
                                Debug::printr($nom_diff);
                                if (count($nom_diff) > 0) {
                                        $this->noms_stat['modification']++;
                                        $modif['modification_type'] = 'M';
                                        $modif['modification_type_1'] = '0';
                                        $modif['modification_type_2'] = '0';
                                        $modif['modification_type_3'] = '0';
                                        $this->chargerTableauChampsModifTypes();
                                        foreach ($this->champs_nom as $champ) {
                                                if (isset($nom_diff[$champ])) {
                                                        $infos[$champ] = $nom_diff[$champ];
                                                        $type = $this->getDiffType($champ);
                                                        $modif['modification_type_'.$type] = '1';
                                                } else {
                                                        $infos[$champ] = '';
                                                }
                                        }
                                        foreach ($modif as $cle => $val) {
                                                $infos[$cle] = $val;
                                        }
                                }
                        }
                        $infos = $this->remplacerTabulation($infos);
                        $infos = $this->remplacerSautsDeLigne($infos);
                        Debug::printr($infos);
                        Debug::printr("-------------------------------------------------");
                        $diff[$id][] = $infos;
                        if ($i == 100) break;
                }
                return $diff;
        }
        
        private function chargerTableauChampsModifTypes() {
                $champs = explode(',', $this->manuel['champs_diff_type']);
                foreach ($champs as $champ) {
                        list($champ_nom, $type) = explode('=', trim($champ));
                        $this->diff_modif_types[$champ_nom] = $type;
                }
        }
        
        private function getDiffType($champ_nom) {
                $type = isset($this->diff_modif_types[$champ_nom]) ? $this->diff_modif_types[$champ_nom] : '3';
                return $type;
        }
        
        private function ecrireFichierDiff($contenu) {
                $fichier_nom = $this->getBaseNomFichier().$this->manuel['ext_fichier_diff'];
                $fichier_chemin = $this->zip_chemin_dossier.$fichier_nom;
                
                if ($this->ecrireFichier($fichier_chemin, $contenu)) {
                        $this->ajouterMessage("Écriture du fichier diff réussie.");
                }
        }
        
        private function creerFichierMeta() {
                $donnees = array();
                $donnees = $this->meta;
                $donnees['stats'] = $this->noms_stat;
                $donnees['signature'] = $this->signature_md5;
                
                $donnees = $this->remplacerTabulation($donnees);
                $donnees = $this->remplacerSautsDeLigne($donnees);
                
                $meta_tsv = $this->getVue('versionnage/squelettes/meta', $donnees, '.tpl.tsv');
                $this->ecrireFichierMeta($meta_tsv);
        }
        
        private function remplacerTabulation($doc) {
                if (is_string($doc)) {
                        $doc = str_replace("\t", ' ', $doc);
                } else if (is_array($doc) && count($doc) > 0) {
                        foreach ($doc as $cle => $valeur) {
                                $doc[$cle] = $this->remplacerTabulation($valeur);
                        }
                }
                return $doc;
        }
        
        private function remplacerSautsDeLigne($doc) {
                if (is_string($doc)) {
                        $a_remplacer = array("\r", "\n");
                        $doc = str_replace($a_remplacer, ' ', $doc);
                } else if (is_array($doc) && count($doc) > 0) {
                        foreach ($doc as $cle => $valeur) {
                                $doc[$cle] = $this->remplacerSautsDeLigne($valeur);
                        }
                }
                return $doc;
        }
        
        private function ecrireFichierMeta($contenu) {
                $fichier_nom = $this->getBaseNomFichier().$this->manuel['ext_fichier_meta'];
                $fichier_chemin = $this->zip_chemin_dossier.$fichier_nom;
                
                if ($this->ecrireFichier($fichier_chemin, $contenu)) {
                        $this->ajouterMessage("Écriture du fichier meta réussie.");
                        $this->archiverMetadonnees();
                }
        }
        
        private function archiverMetadonnees() {
                $metadonnees = $this->meta;
                $metadonnees['code'] = $this->meta['acronyme'];
                unset($metadonnees['acronyme']);
                $metadonnees['domaine_taxo'] = $this->meta['dom_tax'];
                unset($metadonnees['dom_tax']);
                $metadonnees['domaine_geo'] = $this->meta['dom_geo'];
                unset($metadonnees['dom_geo']);
                $metadonnees['domaine_nom'] = $this->meta['dom_code'];
                unset($metadonnees['dom_code']);
                $metadonnees['auteur'] = $this->meta['auteur_principal'];
                unset($metadonnees['auteur_principal']);
                $metadonnees['date_production'] = $this->meta['date_prod'];
                unset($metadonnees['date_prod']);
                $metadonnees['droit'] = $this->meta['copyright'];
                unset($metadonnees['copyright']);
                
                $ok = $this->metaDao->ajouter($metadonnees);
                if ($ok === false) {
                        $this->ajouterMessage("L'archivage des métadonnées a échoué.");
                }
        }
        
        private function nettoyerMemoire() {
                $this->noms = null;
                $this->noms_precedents = null;
                $this->noms_stat = null; 
        }
        
        private function copierManuel() {
                $fichier_source = $this->manuel_chemin.$this->manuel_nom;
                $fichier_destination = $this->zip_chemin_dossier.$this->manuel_nom;
                if (copy($fichier_source, $fichier_destination) === false) {
                        $this->ajouterMessage("La copie du manuel '$fichier_destination' a échouée.");
                }
        }
        
        private function creerFichierZip() {
                $fichierZip = new PclZip($this->zip_chemin_fichier);
                if ($fichierZip->add($this->zip_chemin_dossier, PCLZIP_OPT_REMOVE_ALL_PATH) == 0) {
                        $e = "La création du fichier zip '$this->zip_chemin_fichier' a échoué avec l'erreur : ".$fichierZip->errorInfo(true);
                        $this->ajouterMessage($e);
                }       
        }
        
        private function nettoyerFichiers() {
                $dossier = $this->zip_chemin_dossier;
                if (is_dir($dossier)) {
                        $objets = scandir($dossier);
                        foreach ($objets as $objet) {
                                if ($objet != '.' && $objet != '..') {
                                        if (filetype($dossier.'/'.$objet) == 'dir') {
                                                rrmdir($dossier.'/'.$objet);
                                        } else {
                                                unlink($dossier.'/'.$objet);
                                        }
                                }
                        }
                        reset($objets);
                        rmdir($dossier);
                }
        }
        
        private function traiterMessages() {
                if (isset($this->messages)) {
                        $num_message = 1;
                        foreach ($this->messages as $message) {
                                $message['nom'] = 'Message #'.$num_message++;
                                $this->resultatDao->ajouter($this->traitement['id_traitement'], $message);
                        }
                }
        }
}
?>