Subversion Repositories eFlore/Projets.eflore-projets

Rev

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

<?php
/*
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
 * @copyright 2013 Tela Botanica (accueil@tela-botanica.org)
 */

abstract class CommunNomsTaxons extends Commun {

        /** Tableau de correspondance entre les noms des champs et les codes de l'ontologie.*/
        private $relationsChampsCodesOntologie = null;
        protected $table_retour; //Permet de stocker le tableau de résultat (non encodé en json)
        protected $resultat_req; // Permet de stocker le résultat de la requete principale.
        protected $table;// Nom de la table dans laquelle on récupèrera les données dans les requetes SQL
        protected $total_resultat = null;
         /** Stocke le service appelé correspondant. Est utilisé principalement lors de l'affichage du href d'un synonyme
          (ex id=12, basionyme num 25 est un synonyme) dans le service taxon */
        protected $service_href = null;
        protected $erreursParametres = null;
        protected $sans_nom_sci = array('gen','sp','ssp','fam','au_ss','bib_ss');
        private $bib_traitees = array();

        static $correspondance_champs = array();
        static $champs_api = array();
        static $compo_nom = null; //Stocke sous forme de tableau les composant du nom à ajouter au nom scientifique
        static $cache_ontologies = array(); // cache des ontologies
//+------------------------------- PARAMÈTRES ---------------------------------------------------------------+

        public function traiterParametres() {
                $this->definirParametresParDefaut();
                $this->verifierParametres();
                if (isset($this->parametres) && count($this->parametres) > 0) {
                        foreach ($this->parametres as $param => $val) {
                                switch ($param) {
                                        case 'ns.structure' :
                                                self::remplirTableCompositionNom($val);
                                                if (in_array($val,$this->sans_nom_sci)){
                                                        $this->requete_champ = implode(', ',self::$compo_nom);
                                                }else {
                                                        $this->requete_champ .= ' ,'.implode(', ',self::$compo_nom);
                                                }
                                                break;
                                        case 'navigation.depart' :
                                                        $this->limite_requete['depart'] = $val;
                                                break;
                                        case 'navigation.limite' :
                                                        $this->limite_requete['limite'] = $val;
                                                break;
                                }
                        }
                        $this->traiterParametresSpecifiques();
                }
        }

        protected function definirParametresParDefaut() {
                if (empty($this->parametres['recherche'])) {
                        $this->parametres['recherche'] = 'stricte';
                }
                if (empty($this->parametres['ns.format'])) {
                        $this->parametres['ns.format'] =  'txt';
                }
                if (empty($this->parametres['retour.format'])) {
                        $this->parametres['retour.format'] = 'max';
                }
                if (empty($this->parametres['ns.structure']) &&
                        $this->parametres['retour.format'] != 'oss') {
                        $this->parametres['ns.structure'] = 'au,an,bib';
                }
        }


        public function verifierParametres() {
                //$this->verifierParametresAPI();

                $this->verifierParametre('recherche', 'stricte|floue|etendue|complete');
                $this->verifierParametre('ns.format', 'htm|txt');
                $this->verifierParametre('retour.format', 'min|max|oss|perso');
                $this->verifierParametreAvecValeurMultipe('ns.structure', 'an|au|bib|ad|gen|sp|ssp|fam|au_ss|bib_ss');

                /*if (count($this->erreursParametres) > 0) {
                        $m = 'Erreur dans votre requête : '.implode('<br/>', $this->erreursParametres);
                        throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
                }*/
        }

        public function verifierParametresAPI() {
                $parametresApi = Commun::recupererTableauConfig('parametresAPI');
                while (!is_null($parametre = key($this->parametres))) {
                        if (!in_array($parametre, $parametresApi)) {
                                $this->erreursParametres[] = "Le paramètre '$parametre' n'est pas pris en compte par cette version de l'API.";
                        }
                        next($this->parametres);
                }
        }

        public function verifierParametre($parametre, $valeursPermises) {
                if (isset($this->parametres[$parametre]) && !empty($this->parametres[$parametre])) {
                        $valeur = $this->parametres[$parametre];
                        $this->verifierValeursPermises($parametre, $valeur, $valeursPermises);
                }
        }

        public function verifierParametreAvecValeurMultipe($parametre, $valeursPermises) {
                if (isset($this->parametres[$parametre]) && !empty($this->parametres[$parametre])) {
                        $valeursConcatenees = $this->parametres[$parametre];
                        $valeurs = explode(',', $valeursConcatenees);
                        foreach ($valeurs as $valeur) {
                                $this->verifierValeursPermises($parametre, $valeur, $valeursPermises);
                        }
                }
        }

        private function verifierValeursPermises($parametre, $valeur, $valeursPermises) {
                if (!in_array($valeur, explode('|', $valeursPermises))) {
                        $this->erreursParametres[] = "Le paramètre '$parametre' ne peut pas prendre la valeur '$valeur'. Valeurs permises : $valeursPermises";
                }
        }

        public function ajouterFiltreMasque($nom_champ, $valeur) {
                $orig_val = $valeur;
                $valeur = explode(',',$valeur);
                $conditions = array();
                if ($nom_champ == 'annee' || $nom_champ == 'rang') {
                        foreach ($valeur as $val) {
                                 $conditions[] = "$nom_champ = ".$this->getBdd()->proteger($val);
                        }
                } else {
                        if ($this->parametres['recherche'] == 'etendue') {
                                foreach ($valeur as $val) {
                                        $val = self::preparerChainePourRechercheEtendue(self::remplacerCaractereHybrideEtChimere($val));
                                        $conditions[] = "$nom_champ LIKE ".$this->getBdd()->proteger($val);
                                }

                        } elseif ($this->parametres['recherche'] == 'floue') {
                                foreach ($valeur as $val) {
                                        $val = $this->getBdd()->proteger($val);
                                        $conditions[] = "( SOUNDEX($nom_champ) = SOUNDEX($val))".
                                                                                        " OR ( SOUNDEX(REVERSE($nom_champ)) = SOUNDEX(REVERSE($val)))";
                                }
                                // utile pour la détermination à partir d'un nom retenu (concat(nom_sci,auteur)) lors
                                // d'un import depuis le CEL
                        } elseif ($this->parametres['recherche'] == 'concat' && $nom_champ == 'nom_sci') {
                                $conditions[] = "CONCAT(nom_sci, ' ', auteur) = " . $this->getBdd()->proteger($orig_val);

                        } else {
                                foreach ($valeur as $val) {
                                        $conditions[] = "$nom_champ LIKE ".$this->getBdd()->proteger($val);
                                }
                        }
                }
                $this->requete_condition[]= '('.implode(' OR ', $conditions ).')';
                $this->masque[$nom_champ] = $nom_champ.'='.implode(',',$valeur);
        }

        static function remplacerCaractereHybrideEtChimere($valeur) {
                return str_replace(array('×', '%D7', '+', '%2B'),
                                                   array('x ','x ', '+', '+'),
                                                   $valeur);
        }

        static function preparerChainePourRechercheEtendue($valeur) {
                return str_replace(' ', '% ', trim($valeur)) . '%';
        }

        //+-------------------------------Fonctions d'analyse des ressources-------------------------------------+
        public function traiterRessources() {
                if (isset($this->ressources) && count($this->ressources) > 0) {
                        if ($this->ressources[0] == 'relations') {
                                $this->traiterRessourceRelations();
                        } elseif ($this->estUnIdentifiant($this->ressources[0])) { //l'identifiant peut etre de type /#id ou /nt:#id
                                $this->traiterRessourcesIdentifiant(); // dans le service noms ou taxons
                        } elseif ($this->ressources[0] == 'stats') { //ressource = noms/stats
                                $this->traiterRessourcesStats();
                        } else {
                                $e = 'Erreur dans votre requete </br> Ressources disponibles : <br/>
                                         <li> /'.$this->service.'/#id (id : L\'identifiant du nom rechercher)</li>
                                         <li> /'.$this->service.'/nt:#id (id : Numero du taxon recherche)</li>
                                         <li> /'.$this->service.'/stats </li>';
                                throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
                        }
                }
        }

        public function traiterRessourcesStats() {
                $this->format_reponse = $this->service.'/stats';

                $e = "Erreur dans votre requête </br> Ressources disponibles : $this->service/stats/[annees|rangs|initiales]";
                if (isset($this->ressources[1]) && !empty($this->ressources[1])) {
                        switch ($this->ressources[1]) {
                                case 'annees' :
                                        $this->traiterRessourceStatsAnnees();
                                        break;
                                case 'rangs' :
                                        $this->traiterRessourceStatsRangs();
                                        break;
                                case 'initiales' :
                                        $this->traiterRessourceStatsInitiales();
                                        break;
                                default :
                                        throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
                                        break;
                        }
                } else {
                        throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
                }
        }

        /** Vérifie si la première valeur de la table de ressource est un identifiant :
         * un numerique ou un numéro taxonomique sous la forme nt:xx */
        static function estUnIdentifiant($uripart) {
                return (is_numeric($uripart) || (strrpos($uripart,'nt:') !== false
                                && is_numeric(str_replace('nt:','',$uripart))));
        }

        //+------------------------------------------------------------------------------------------------------+
        // Fonction d'analyse des parametres

        /** Permet de remplir le tableau compo_nom. Il comprendra en fct du paramètre ns.structure les éléments à rajouter
         * au nom_sci (annee, auteur, biblio ou addendum). */
        static function remplirTableCompositionNom($valeur) {
                $structure_nom = explode(',', $valeur);

                foreach ($structure_nom as $structure) {
                        $structure = trim($structure);
                        $patterns = array('/^an$/', '/^au$/', '/^bib$/', '/^ad$/', '/^sp$/', '/^gen$/', '/^ssp$/','/^fam$/',
                                                          '/^au_ss$/','/^bib_ss$/');
                        $champs = array('annee', 'auteur', 'biblio_origine', 'nom_addendum', 'epithete_sp', 'genre',
                                                        'epithete_infra_sp','famille','auteur', 'biblio_origine');

                        // avec str_replace() 'sp' est inclu dans 'ssp', et la conversion pour 'ssp' est mauvaise
                        self::$compo_nom[$structure] = preg_replace($patterns, $champs, $structure);
                }
        }

        public function mettreAuFormat() {
                if ($this->parametres['ns.format'] == 'htm') {
                        if (strrpos($this->requete_champ, 'nom_sci_html as nom_sci') === false) {
                                $this->requete_champ = str_replace('nom_sci', 'nom_sci_html as nom_sci', $this->requete_champ);
                        }
                }
        }

        //+------------------------------------------------------------------------------------------------------+
        // Fonctions de formatage
        public function formaterEnOss($resultat) {
                $table_nom = array();
                $oss = '';
                foreach ($resultat as $tab) {
                        if (isset($tab['nom_sci']) ) {
                                if (!in_array($tab['nom_sci'], $table_nom)) {
                                        $table_nom[] = $tab['nom_sci'];
                                        $oss[] = $tab['nom_sci'].' '.self::ajouterCompositionNom($tab, $this->parametres['ns.format'], $this->bib_traitees);
                                }
                        }else {
                                $res = self::ajouterCompositionNom($tab, $this->parametres['ns.format'], $this->bib_traitees);
                                if($res) {
                                        $oss[] = $res;
                                }
                        }

                }

                if (isset($this->masque)) $masque = implode('&', $this->masque);
                else $masque = 'Pas de masque';
                $table_retour_oss = array($masque, $oss);
                return $table_retour_oss;
        }

        public function afficherEnteteResultat($url_service) {
                $this->table_retour['depart'] = $this->limite_requete['depart'];
                $this->table_retour['limite'] = $this->limite_requete['limite'];
                $this->table_retour['total']  = $this->total_resultat;
                $url = $this->formulerUrl($this->total_resultat, $url_service);
                if (isset($url['precedent']) && $url['precedent'] != '') {
                        $this->table_retour['href.precedent'] = $url['precedent'];
                }
                if (isset($url['suivant']) && $url['suivant']   != '') {
                        $this->table_retour['href.suivant']   = $url['suivant'];
                }
        }

        public function afficherNomHrefRetenu($tab, $num) {
                $this->resultat_req = $tab;
                $this->afficherDonnees('num_nom', $num);
                if ($this->parametres['retour.format'] == 'min') { // sinon est affiché ds afficherDonnees(num_nom, $val) ci-dessus
                         $this->table_retour['nom_sci'] = $tab['nom_sci'];
                         $this->table_retour['nom_sci_complet'] = $tab['nom_sci'].' '.self::ajouterCompositionNom($tab, $this->parametres['ns.format'], $this->bib_traitees);
                }
                if ($tab['num_nom_retenu'] != '') {
                        $retenu = ($tab['num_nom_retenu'] == $num) ? 'true' : 'false';
                } else {
                        $retenu = 'absent';
                }
                $this->table_retour['retenu'] = $retenu;
                // Pourquoi ce unset ? JPM - 28-03-2013
                unset($this->table_retour['id']);
        }


        //+------------------------------------------------------------------------------------------------------+
        // Fonction de formatage pour les services /#id/

        public function formaterId($resultat) {
                self::$correspondance_champs = Commun::recupererTableauConfig('correspondance_champs');
                foreach (self::$correspondance_champs as $key => $val) {
                        preg_match('/(hybride[.]parent_0[12](?:[.]notes)?|nom_sci[.][^.]+|[^.]+)(?:[.](id|code))?/', $val, $match);
                        self::$champs_api[$key] = $match[1];
                }

                $this->resultat_req = $resultat;

                foreach ($resultat as $cle => $valeur) {
                        if ($valeur != '') {
                                $this->afficherDonnees($cle, $valeur);
                        }
                }
                if (isset($this->parametres['retour.champs']) && $this->format_reponse == 'noms/id') {
                        $retour = $this->table_retour;
                        $this->table_retour = array();
                        $champs = explode(',', $this->parametres['retour.champs']);
                        self::ajouterChampsPersonnalises($champs, $retour, $this->champs_table, $this->table_retour, $this->resultat_req);
                }
                unset($this->table_retour['href']);
                return $this->table_retour;
        }

        public function formaterIdChamp($resultat) {
                self::$correspondance_champs = Commun::recupererTableauConfig('correspondance_champs');
                foreach (self::$correspondance_champs as $key => $val) {
                        preg_match('/(hybride[.]parent_0[12](?:[.]notes)?|nom_sci[.][^.]+|[^.]+)(?:[.](id|code))?/', $val, $match);
                        self::$champs_api[$key] = $match[1];
                }

                $reponse_id = $this->formaterId($resultat);
                $this->table_retour = array();
                $champs = explode(' ', $this->ressources[1]);
                self::ajouterChampsPersonnalises($champs, $reponse_id, $this->champs_table, $this->table_retour, $this->resultat_req);
                return $this->table_retour;
        }

        static function ajouterChampsPersonnalises($champs, $reponse_id, $champs_table, &$retour, $resultat_req) {
                $champs_a_libeller = array('nom_retenu', 'rang', 'basionyme', 'hybride', 'hybride.parent_01',
                         'hybride.parent_02', 'presence', 'tax_sup', 'statut_origine', 'statut_culture', 'statut_introduction');
                if (! is_null($champs) && is_array($champs) && count($champs) > 0) {
                        foreach ($champs as $champ) {
                                if (! self::verifierValiditeChamp($champ, $champs_table)) continue;

                                if (strrpos($champ, '.*') !== false) {
                                        self::afficherPointEtoile($champ, $reponse_id, $retour, $resultat_req);
                                } elseif (in_array($champ, $champs_a_libeller)) {
                                        $retour[$champ.'.libelle'] =
                                                (isset($reponse_id[$champ.'.libelle'])) ? $reponse_id[$champ.'.libelle'] : null;
                                } else {
                                        $champ_bdd = self::trouverChampBddCorrespondant($champ);
                                        $retour[$champ_bdd] = isset($reponse_id[$champ_bdd]) ? $reponse_id[$champ_bdd] : null;
                                }
                        }
                }
        }

        static function afficherPointEtoile($champ, $reponse, &$retour, $resultat_req) {
                preg_match('/^([^.]+\.)\*$/', $champ, $match);
                if ($match[1] == 'nom_sci') {
                        self::afficherNomSciPointEpithete($resultat_req, $retour);
                } else {
                        foreach ($reponse as $chp => $valeur) {
                                if (strrpos($chp, $match[1]) !== false) {
                                        if ($valeur != '') {
                                                $retour[$chp] = $valeur;
                                        } else {
                                                $retour[$chp] = null;
                                        }
                                }
                        }
                }
        }

        static function verifierValiditeChamp($champ, $champs_table) {
                if (! preg_match('/^(?:([^.]+\.parent_0[12]|[^.]+))(?:\.(.+))?$/', $champ, $match)) {
                        return true;
                }
                // decomposerNomChamp()
                $radical = $match[1];
                $suffixe = isset($match[2]) ? $match[2] : "";

                $champs_complementaire = array('nom_retenu_complet', 'basionyme_complet');
                // on verifie si le nom du champ existe bien
                $champs_complementaire2 = array_diff($champs_table, array_keys(self::$champs_api)); // XXX
                if (! self::estChampApi($radical) && ! in_array($radical_champ, $champs_complementaire2)) {
                        if (!in_array($radical, $champs_complementaire)) {
                                throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, 'Le champ "'.$radical.'" n\'existe pas dans la base. <br/><br/>');
                                return FALSE;
                        }
                } elseif (self::estUnPoint($champ)) {
                        return self::verifierValiditeSuffixe($suffixe, $radical);
                }

                return TRUE;
        }

        static function estChampApi($radical_champ) {
                $champ_api_ok = false;
                if (in_array($radical_champ, self::$champs_api) || in_array($radical_champ, self::$correspondance_champs)) {
                        $champ_api_ok = true;
                }
                return $champ_api_ok;
        }

        static function verifierValiditeSuffixe($suffixe, $radical_champ) {
                $validite_ressource = true;
                if (self::correspondAUnId($radical_champ) || $radical_champ == 'id') {
                        self::verificationSuffixesIdentifiant($suffixe, $radical_champ, $validite_ressource);
                } elseif (self::correspondAUnCode($radical_champ)) {
                        if (!in_array($suffixe, array('*', 'code', 'href', 'details'))) {
                                throw new Exception(RestServeur::HTTP_CODE_MAUVAISE_REQUETE, 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'.<br/> Les suffixes possibles sont les suivants : <li> .* </li><li> .code </li><li> .href </li><li> .details </li>');
                        }
                } elseif ($radical_champ == 'nom_sci') {
                        if ($suffixe != '*') {
                                $validite_ressource = false;
                                $m = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/>
                                        Les suffixes possibles sont les suivants : <li> * </li>';
                                throw new Exception( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
                        }
                } else {
                        $validite_ressource = false;
                        $m = 'Erreur : Le paramètre "'.$radical_champ.'" ne peut pas présenter de suffixe. <br/><br/>';
                        throw new Exception( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $m);
                }
                return $validite_ressource;
        }


        static function verificationSuffixesIdentifiant(&$suffixe, &$radical_champ, &$validite_ressource) {
                if ((strrpos($radical_champ, 'parent') !== false && !in_array($suffixe, array('*', 'id', 'href', 'details', 'notes')))
                        || !in_array($suffixe, array('*', 'id', 'href', 'details')) && strrpos($radical_champ, 'parent') === false) {
                        $validite_ressource = false;
                        $e = 'Erreur : Le suffixe demandé n\'existe pas pour le champ "'.$radical_champ.'".<br/> Les suffixes '
                                .'possibles sont les suivants : <li> .* </li><li> .id </li><li> .href </li><li> .details </li>'
                                .'<li> .notes (seulement pour les hybride.parent)';
                        throw new Exception( RestServeur::HTTP_CODE_MAUVAISE_REQUETE, $e);
                }
        }


//------------------------------fonction de formatage pour les services /stats/-----------------------------------------
        public function formaterStatsInitiales($resultat) {
                $rang = null;
                $table_rang = array();
                foreach ($resultat as $tuple) {
                        if ($tuple['rang'] != 0) {
                                $this->memoriserRang($table_rang, $tuple, $rang);
                                if ($tuple['lettre'] == 'x ') {
                                        self::ajouterHybrideChimere('hybride', $this->retour[$rang], $tuple);
                                } elseif ($tuple['lettre'] == '+ ') {
                                        self::ajouterHybrideChimere('chimere', $this->retour[$rang], $tuple);
                                } else {
                                        $l = substr($tuple['lettre'], 0, 1);
                                        if (isset($this->table_retour[$rang][$l])) {
                                                $this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] += floatval($tuple['nb']);
                                        } else {
                                                $this->table_retour[$rang][substr($tuple['lettre'], 0, 1)] = floatval($tuple['nb']);
                                        }
                                }
                        }
                }
                return $this->table_retour;
        }

        public function memoriserRang(&$table_rang, $tuple, &$rang) {
                if (is_array($table_rang)) {
                        if (!in_array($tuple['rang'], $table_rang)) {
                                $rang = $tuple['rang'];
                                $table_rang[] = $rang;
                                if ($this->parametres['retour.format'] == 'max') {
                                        $rang = self::ajouterSignificationCode('rang', $rang, $this->getBdd());
                                }
                        }
                }
        }

        static function ajouterHybrideChimere($groupe, &$tab, &$tuple) {
                if (isset($tab[str_replace('hybride', 'hyb', $groupe)])) {
                        $tab[$groupe] += floatval($tuple['nb']);
                } else {
                        $tab[$groupe] = floatval($tuple['nb']);
                }
        }

        //-----------------------------Fonctions d'affichage utiliser dans les fonctions de formatage---------------------------

        public function afficherDonnees($champApi, $valeur) {
                $champBdd = self::trouverChampBddCorrespondant($champApi);

                if ($this->parametres['retour.format'] == 'min') {
                        if ($champApi == 'nom_sci') {
                                $valeur = $valeur.' '.self::ajouterCompositionNom($this->resultat_req, $this->parametres['ns.format'], $this->bib_traitees);
                        }
                        if ($champApi == 'nom_sci_html') {
                                $valeur = $valeur.' '.self::ajouterCompositionNom($this->resultat_req, 'htm', $this->bib_traitees);
                        }
                        $this->table_retour[$champBdd] = $valeur;
                        // on essaye de permettre l'obtention du nom_sci_complet, y compris en retour.format == 'min',
                        // tout en évitant les appels aux ontologies
                        /*if ($this->correspondAUnId($champBdd) || $champBdd == 'id' && $valeur != '0') {
                                preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $champBdd, $match);
                                if(strpos($this->parametres['retour.format'], $match[1]) !== false) $this->afficherSignification($match[1], $valeur);
                                }*/
                } else {
                        $this->afficherToutesLesInfos($champBdd, $valeur);
                }
        }

        static function trouverChampBddCorrespondant($champApi) {
                if (array_key_exists($champApi, self::$champs_api)) {
                        $champBdd = self::$correspondance_champs[$champApi];
                } else {
                        $champBdd = $champApi;
                }
                return $champBdd;
        }

        public function afficherToutesLesInfos($nom_champ_api, $valeur) {
                if ($this->presentePlusieursId($nom_champ_api, $valeur)) {
                        preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
                        $this->afficherInfosPrecises($match[1], 'details', $valeur, $this->table_retour);
                        $this->table_retour[$nom_champ_api] = $valeur;

                } elseif (strrpos($nom_champ_api, 'parent') !== false && strrpos($nom_champ_api, 'notes') !== false) {
                        $this->table_retour[$nom_champ_api] = $valeur;

                } elseif ((self::correspondAUnId($nom_champ_api) || $nom_champ_api == 'id' && $valeur != '0')) {
                        preg_match('/^([^.]+\.parent_0[12]|[^.]+)(?:\.id)?$/', $nom_champ_api, $match);
                        $this->afficherInfosPrecises($match[1], 'id,href', $valeur, $this->table_retour);
                        self::afficherSignification($match[1], $valeur, $obj->resultat_req, $this->table_retour, $this->getBdd(), $this);

                } elseif (self::correspondAUnCode($nom_champ_api)) {
                        preg_match('/^([^.]+)(?:\.code)?$/', $nom_champ_api, $match);
                        $this->afficherInfosPrecises($match[1], 'code,href', $valeur, $this->table_retour);
                        self::afficherSignification($match[1], $valeur, $obj->resultat_req, $this->table_retour, $this->getBdd(), $this);

                } elseif ($nom_champ_api == 'nom_sci_html') {
                        $this->table_retour['nom_sci_html'] = $valeur;
                        $this->table_retour['nom_sci_html_complet'] = $valeur.' '.self::ajouterCompositionNom($this->resultat_req, 'htm', $this->bib_traitees);
                } elseif ($nom_champ_api != 'nom_sci') {
                        $this->table_retour[$nom_champ_api] = $valeur;
                }
        }

        public function presentePlusieursId($ressource, $valeur = null) {
                if ($valeur) {
                        $presente = strrpos($ressource, 'proparte') !== false && strrpos($valeur, ',') !== false;
                } else { //pour la vérification du champ, on ignore alors la valeur de la ressource
                        $presente = strrpos($ressource, 'proparte') !== false;
                }
                return $presente;
        }

        public function afficherInfosPrecises($champ, $suffixe, $valeur, &$retour) {
                $suffixes = explode(',', $suffixe);
                //on initialise au service appelé. Sera potentiellement modifié dans la fonction afficherSignification()
                $this->service_href = $this->service;
                foreach ($suffixes  as $suffixe) {
                        switch ($suffixe) {
                                case 'id'                        :
                                        $retour[str_replace('id.id', 'id', $champ.'.id')] = $valeur;
                                        break;
                                case 'details'           :
                                        $tab_id = explode(',', $valeur);
                                        $tab_res = $retour;
                                        $retour = array();
                                        foreach ($tab_id as $id) {
                                                $this->afficherInfosPrecises($champ, 'id,signification,href', $id, $retour);
                                                $tab_res[$champ.'.details'][] = $retour;
                                                $retour = array();
                                        }
                                        $retour = $tab_res;
                                        break;
                                case 'href'              :
                                        $retour[str_replace('id.href', 'href', $champ.'.href')] = self::creerUrl($champ, $valeur, $this->version_projet);
                                        break;
                                case 'code'              :
                                        $retour[$champ.'.code'] = "bdnt." . self::transformerChampEnCode($champ) . ":$valeur";
                                        break;
                                case 'notes'             :
                                        $retour[$champ.'.notes'] = $this->resultat_req[str_replace('.', '_', $champ).'_notes'];
                                        break;
                                default : break;
                        }
                }
        }

        static function transformerChampEnCode($champ) {
                static $tab;
                $tab = Outils::recupererTableauConfig('ChampsCodesOntologie');
                if (!array_key_exists($champ, $tab)) return $champ;
                return $tab[$champ];
        }

        static function creerUrl($champ, $valeur, $version_projet) {
                if (self::correspondAUnId($champ) || $champ == 'id') {
                        $service = $this->service_href;
                        $url = self::s_ajouterHref($service, $valeur, $version_projet);
                } else {
                        $code = self::transformerChampEnCode($champ);
                        $url = self::ajouterHrefAutreProjet('ontologies', "$code:", $valeur, 'bdnt');
                }
                return $url;
        }

        static function afficherSignification($champ, $valeur, $resreq, &$retour, $db, $obj) {
                $fmt = $obj->parametres['ns.format'];

                if ($champ == 'id' && isset($resreq['nom_sci']) && $resreq['num_nom'] == $valeur) {
                        //si le nom_sci du num_nom que l'on veut afficher est déjà dans la table de résultat :
                        $retour['nom_sci'] = $resreq['nom_sci'];
                        $retour['nom_sci_complet'] = $resreq['nom_sci'] . (($suff = self::ajouterCompositionNom($resreq, $fmt, $obj->bib_traitees)) ? ' ' . $suff : '');
                        return ;
                }

                if (self::correspondAUnCode($champ)) {
                        $retour[$champ.'.libelle'] = self::ajouterSignificationCode($champ, $valeur, $db);
                        return ;
                }

                if (self::correspondAUnId($champ) || $champ == 'id') {
                        // $nom = $obj->recupererNomSci($valeur);
                        $id = $valeur;

                        $nom = array();
                        if ($id != 0) {
                                if (self::$compo_nom == null) {
                                        $req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html FROM '.$obj->table.' WHERE num_nom = '.$id;
                                } else { //on ajoute à la requete sql, les champs de ns.structure
                                        //print_r(self::$compo_nom);
                                        $req = 'SELECT nom_sci, num_nom_retenu, nom_sci_html, '.implode(', ', self::$compo_nom)
                                                .' FROM '.$obj->table
                                                .' WHERE num_nom = '.$id;
                                }
                                if ($fmt == 'htm') {
                                        $req = str_replace('nom_sci', 'nom_sci_html as nom_sci', $req);
                                }
                                $res = $db->recuperer($req . ' -- ' . __FILE__ . ':' . __LINE__);
                                if ($res) {
                                        $nom['nom_sci'] = $res['nom_sci'];
                                        $nom['nom_sci_html'] = $res['nom_sci_html'];
                                        $nom['nom_sci_complet'] = $res['nom_sci'].' '.self::ajouterCompositionNom($res, $fmt, $obj->bib_traitees);
                                        $nom['nom_sci_complet_html'] = $res['nom_sci_html'].' '.self::ajouterCompositionNom($res, 'htm', $obj->bib_traitees);
                                        $nom['service'] = ($res['num_nom_retenu'] == $id && $obj->service == 'taxons') ? 'taxons' : 'noms';
                                }
                        }


                        if ($nom != array()) {
                                $retour[$champ.'.libelle'] = $nom['nom_sci'];
                                $retour[$champ.'_html'] = $nom['nom_sci_html'];
                                $retour[$champ.'_complet'] = $nom['nom_sci_complet'];
                                $retour[$champ.'_html_complet'] = $nom['nom_sci_complet_html'];
                                $obj->service_href = $nom['service'];
                        }
                }
        }

        /** Permet d'afficher les élements nomenclatural du nom_sci lors de l'appel dans le service noms/id/champ du champ^nom_sci.*/
        static function afficherNomSciPointEpithete($resultat, &$retour) {
                $tab_nom_sci   = array('nom_supra_generique', 'genre', 'epithete_infra_generique', 'epithete_sp',
                                                           'type_epithete', 'epithete_infra_sp', 'cultivar_groupe', 'cultivar', 'nom_commercial');
                foreach ($tab_nom_sci as $compo_nom) {
                        if (isset($resultat[$compo_nom]) && !empty($resultat[$compo_nom])) {
                                $table_retour['nom_sci.'.$compo_nom] = $resultat[$compo_nom];
                        }
                }
        }

        static function ajouterSignificationCode($champ, $valeur, $db) {
                // ontologie/cache
                if(array_key_exists($champ, self::$cache_ontologies) && array_key_exists($valeur, self::$cache_ontologies[$champ])) {
                        $nom_code = self::$cache_ontologies[$champ][$valeur];
                } else {
                        $code = self::transformerChampEnCode($champ);
                        if (preg_match('/^([^_-]+)(?:_|-)([^_-]+)$/', $code, $match)) {
                                $code = $match[1].ucfirst($match[2]);
                        }
                        $requete = sprintf('SELECT * FROM %1$s WHERE id IN (SELECT id FROM %1$s WHERE code = "%2$s" AND classe_id = (SELECT id FROM %1$s WHERE code = "%3$s")) LIMIT 0, 100 -- %4$s:%5$s',
                                                           Config::get('bdd_table_ontologies'), $valeur, $code, __FILE__,  __LINE__);
                        $res = $db->recuperer($requete);
                        $nom_code = $valeur;
                        if (is_array($res)) {
                                $nom_code = $res['nom'];
                        }
                        // cache
                        self::$cache_ontologies[$champ][$valeur] = $correspondance;
                }
                return $nom_code;
        }

        /** Permet de retourner une chaine de caractère composée des parametres du nom (ns.structure : annnée, auteur,
         * bibilio et addendum). A ajouter au nom scientifique */
        static function ajouterCompositionNom($tab_res, $format, &$bib_traitees) {
                if(!self::$compo_nom) return '';

                if ($format == 'htm') {
                        $format = array(
                                'au' => '<span class="auteur">%s</span>',
                                'an' => '[<span class="annee">%s</span>]',
                                'an_bib' => '[<span class="annee">%s</span>, <span class="biblio">%s</span>]',
                                'bib' => '[<span class="biblio">%s</span>]',
                                'ad' => '[<span class="adendum">%s</span>]');
                } else {
                        $format = array(
                                'au' => '%s',
                                'an' => '[%s]',
                                'an_bib' => '[%s, %s]',
                                'bib' => '[%s]',
                                'ad' => '[%s]',
                                'gen' => '%s',
                                'sp' => '%s',
                                'ssp' => '%s',
                                'fam' => '%s',
                                'au_ss' => '%s',
                                'bib_ss' => '%s');
                }
                $compo_nom_arr = array();
                foreach (self::$compo_nom as $key => $champ) {
                        if (isset($tab_res[$champ]) && !empty($tab_res[$champ])) {
                                $compo_nom_arr[$key] = $tab_res[$champ];
                        }
                }
                return rtrim(implode(' ', self::formerNomComplet($compo_nom_arr, $format, $bib_traitees)), ' ');
        }


        static function formerNomComplet($compo_nom_arr, $format, &$bib_traitees) {
                $nom_complet = array();
                extract($compo_nom_arr);
                if (isset($au)) $nom_complet[] = sprintf($format['au'], $au);
                if (isset($an)) {
                        if (isset($bib)) {
                                $nom_complet[] = sprintf($format['an_bib'], $an, $bib);
                        } else {
                                $nom_complet[] = sprintf($format['an'], $an);
                        }
                } elseif (isset($bib)) {
                        $nom_complet[] = sprintf($format['bib'], $bib);
                }
                if (isset($ad)) $nom_complet[] = sprintf($format['ad'], $ad);
                if (isset($gen)) $nom_complet[] = sprintf($format['gen'], $gen);
                if (isset($ssp)) $nom_complet[] = sprintf($format['ssp'], $ssp);
                if (isset($sp)) $nom_complet[] = sprintf($format['sp'], $sp);
                if (isset($fam)) $nom_complet[] = sprintf($format['fam'], $fam);
                if (isset($au_ss)) $nom_complet[] = sprintf($format['au_ss'], $au_ss);
                if (isset($bib_ss)) {
                        $bibl = self::tronquerBiblio($bib_ss);
                        //simule un 'select distinct' sur les biblio tronquées
                        if (!isset($bib_traitees[$bibl])) {
                                $nom_complet[] = sprintf($format['bib_ss'],$bibl );
                                $bib_traitees[$bibl] = 1;
                        }
                }
                return $nom_complet;
        }

        static function tronquerBiblio($valeur){
                $bib = '';
                if(strpos($valeur,',') !== false) {
                        $bib = explode(',',$valeur);
                }
                if(strpos($bib[0],';') !== false) {
                        $bib[0] = strstr($bib[0],';');
                        $bib[0] = str_replace('; ','',$bib[0]);
                }
                return $bib[0];
        }



        static function correspondAUnCode($key) {
                return strrpos($key, '.code') !== false || in_array($key.'.code', self::$correspondance_champs);
        }
        
        static function correspondAUnId($key) {
                return strrpos($key, '.id') !== false || in_array($key.'.id', self::$correspondance_champs);
        }

        static function estUnPoint($key) {
                if (strrpos($key, 'hybride.parent') !== false) {
                        $key = str_replace('hybride.parent', 'hybride_parent', $key);
                }
                return (strrpos($key, '.') !== false);
        }

        public function recupererMasquePrincipal() {
                $masque = null;
                $tab_masque   = array(
                        'masque' => 'nom_sci',
                        'masque_sg' => 'nom_supra_generique',
                        'masque_gen' => 'genre',
                        'masque_sp' => 'epithete_sp',
                        'masque_ssp' => 'epithete_infra_sp',
                        'masque_au' => 'auteur',
                        'masque_an' => 'annee',
                        'masque_bib' => 'biblio_origine',
                        'masque_ad' => 'addendum',
                        'masque_rg' => 'rang');
                $liste_masque = array();

                if (isset($this->masque['num_nom'])) {
                        $liste_masque[] = $this->masque['num_nom'];
                }

                foreach ($tab_masque as $key => $filtre) {
            if (isset($this->masque[$filtre])) {
                if (!isset($masque) && !in_array($filtre, array('rang', 'annee'))) {
                        $masque = array($key, $filtre);
                }
                $liste_masque[] = $this->masque[$filtre];
            }
        }
        $this->masque = $liste_masque;
        return $masque;
        }
}