/tags/v5.7-arrayanal/CHANGELOG |
---|
New file |
0,0 → 1,91 |
Changements <next>: |
Changements 2014-03-24 [création de la branche "v5.6-arganeraie"]: |
* Services : renommage "bdtao" => "apd" |
* Scripts : renommage "bdtao" => "apd" |
* Apd: version "1_00" => "3_4_0" |
* derniere version baseveg |
* carte sans contours de département pour moissonnage petit format (png) |
* Légère amélioration de la gestion des couleurs pour les petites tailles de png |
* Prise en compte de la migration des données eFlore sur Agathis |
* Mise à jour des services, scripts et docs du projet OSM. |
* Ajout d'une condition dans les requetes sur les ids inférieurs et supérieurs des taxons qui les limite au nom retenu |
* Ajout du champ num type s'il n'est pas déjà demandé dans les requetes de synonymie |
Changements 2014-03-04 [création de la branche "v5.5-arbousiere"]: |
* Ajout du web service renvoyant des liens vers les cartes de flore probable isssue de sophy |
* nouvelle version de la bdtfx |
* debug graphique baseflor valeur vide ne s'affiche plus comme 0 |
* correction requete vue tapir |
* Script d'intégration du référentiel bdtao |
* Ajout des scripts eFlore pour bdtao ; utilisation de 'num_basionyme' à la place de 'basionyme'. |
Changements 2014-02-11 [création de la branche "v5.4-Arboretum"]: |
* nouvelle version baseflor |
* Les services Noms des trois référentiels (bdtfx, bdtxa, isfan) retournent maintenant en plus du libellé du rang, le code du rang dans "rang.code" lorsqu'on leur demande "champs.retour=rang" |
* script de création données ifn et vue tapir |
* script transformant les données des tables de tb_moissonnage à une table _tapir et une table meta dans tb_eflore |
* ajout du moissonage de l'ifn |
* interrogation ifn et baznat par num_nom et plus par nom_sci |
Changements 2014-01-06 [création de la branche "v5.3-Amandaie"]: |
* service presencemuseum |
* Protection du graphique Baseflor contre les données NULL |
* ajout de version chorodep |
* Coste/textes : REDIRECT_QUERY_STRING => QUERY_STRING |
* array_unique() sur les courriels de la carte de répartition |
Changements 20130912 [création de la branche "Acheb"]: |
* API change: coste |
* référentiels: bdtfx 2.00, ontologies 4.40 |
* config: |
- directives inutiles supprimées pour Coste [r857] |
- bdnt: ontologie: 4_40 |
* coste: réécriture du webservice |
Changements [[http://svn.tela-botanica.net/websvn/filedetails.php?repname=eFlore%2FProjets.eflore-projets&path=%2Ftrunk%2FChangelog&peg=839 v5.0-agropyraie-20130829]] : |
- tenue du Changelog |
- config: directives modifiées: |
- cache.miseEnCache |
- cache.dureeDeVie |
- cache.stockageChemin |
- ontologies: |
- support critères multiples bdnt |
- support critères multiples nvjfl |
- support critères multiples baseflor |
- cache d'appels pour bdtfx/meta-donnees |
- SQL hard-codé en place du HTTP dans certains cas |
- tests: nombreux ajouts et quelques changements de prototypes |
- scripts: |
- upgrades pour Cel |
- Makefile pour configuration/ |
- renommage de noms de classes en conflit: Cartes et Ontologies |
- améliorations dans l'usage du cache |
Changements v0.1-20130830-1: |
* nvjfl: fix notices |
* cache: correction du cache des synonymes (noms à 255 caractères) |
* cel/images: déduplication de auteurs au préalable de la requête d'identités |
* Note: erreur de tag sur "v0.1-20130830" |
Changements v0.1-20130829: |
* tenue du Changelog |
* config: directives modifiées: |
- cache.miseEnCache |
- cache.dureeDeVie |
- cache.stockageChemin |
* ontologies: |
* support critères multiples bdnt |
* support critères multiples nvjfl |
* support critères multiples baseflor |
* support critères multiples eflore |
* cache d'appels pour bdtfx/meta-donnees |
* SQL hard-codé en place du HTTP dans certains cas |
* tests: nombreux ajouts et quelques changements de prototypes |
* scripts: |
* upgrades pour Cel |
* Makefile pour configuration/ |
* renommage de noms de classes en conflit: Cartes et Ontologies |
* améliorations dans l'usage du cache |
v0.1-20130600 |
/tags/v5.7-arrayanal/scripts/tests/bibliotheque/GenerateurNomSciHtmlTest.php |
---|
New file |
0,0 → 1,82 |
<?php |
class GenerateurNomSciHtmlTest extends PHPUnit_Framework_TestCase { |
public static function setUpBeforeClass() { |
error_reporting(E_ALL); |
define('DS', DIRECTORY_SEPARATOR); |
require_once dirname(__FILE__).DS.'..'.DS.'..'.DS.'bibliotheque'.DS.'GenerateurNomSciHtml.php'; |
} |
public function testGenerer() { |
$nomsDecomposes[] = array( |
'num_nom' => 1009, |
'rang' => 340, |
'nom_supra_generique' => '', |
'genre' => 'Aegilops', |
'epithete_infra_generique' => '', |
'epithete_sp' => 'triuncialis', |
'type_epithete' => 'var.', |
'epithete_infra_sp' => 'nigroferruginea', |
'cultivar_groupe' => '', |
'nom_commercial' => '', |
'cultivar' => '', |
'annee' => '1923', |
'auteur' => 'Popova', |
'biblio_origine' => 'Trudy Prikl. Bot. Selekc., 13 : 476'); |
$generateur = new GenerateurNomSciHtml(); |
$nomsSciHtml = $generateur->generer($nomsDecomposes); |
$nomSciHtmlGenere = $nomsSciHtml[1009]; |
$nomSciHtmlAttendu = '<span class="sci"><span class="gen">Aegilops</span> <span class="sp">triuncialis</span> <abbr class="type_epithete" title="Variété">var.</abbr> <span class="infra-sp">nigroferruginea</span></span>'; |
$this->assertEquals($nomSciHtmlAttendu, $nomSciHtmlGenere); |
} |
public function testGenererHybride() { |
$nomsDecomposes[] = array( |
'num_nom' => 179, |
'rang' => 290, |
'nom_supra_generique' => '', |
'genre' => 'Acer', |
'epithete_infra_generique' => '', |
'epithete_sp' => 'x martinii', |
'type_epithete' => '', |
'epithete_infra_sp' => '', |
'cultivar_groupe' => '', |
'nom_commercial' => '', |
'cultivar' => '', |
'annee' => '1852', |
'auteur' => 'Jord.', |
'biblio_origine' => 'Pugill. Pl. Nov., 52' |
); |
$generateur = new GenerateurNomSciHtml(); |
$nomsSciHtml = $generateur->generer($nomsDecomposes); |
$nomSciHtmlGenere = $nomsSciHtml[179]; |
$nomSciHtmlAttendu = '<span class="sci"><span class="gen">Acer</span> <span class="hyb">x <span class="sp">martinii</span></span></span>'; |
$this->assertEquals($nomSciHtmlAttendu, $nomSciHtmlGenere); |
} |
public function testGenererChimere() { |
$nomsDecomposes[] = array( |
'num_nom' => 80380, |
'rang' => 290, |
'nom_supra_generique' => '', |
'genre' => '+ Cytisus', |
'epithete_infra_generique' => '', |
'epithete_sp' => 'adami', |
'type_epithete' => '', |
'epithete_infra_sp' => '', |
'cultivar_groupe' => '', |
'nom_commercial' => '', |
'cultivar' => '', |
'annee' => '1830', |
'auteur' => 'Poit.', |
'biblio_origine' => 'Ann. Soc. Hort. Paris, 7 : 96' |
); |
$generateur = new GenerateurNomSciHtml(); |
$nomsSciHtml = $generateur->generer($nomsDecomposes); |
$nomSciHtmlGenere = $nomsSciHtml[80380]; |
$nomSciHtmlAttendu = '<span class="sci"><span class="chimere">+ <span class="gen">Cytisus</span></span> <span class="sp">adami</span></span>'; |
$this->assertEquals($nomSciHtmlAttendu, $nomSciHtmlGenere); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/tests/bibliotheque/OutilsTest.php |
---|
New file |
0,0 → 1,63 |
<?php |
require_once dirname(__FILE__).'/../ScriptEflorePhpUnit.php'; |
class OutilsTest extends ScriptEflorePhpUnit { |
public function testRecupererTableauConfigAssociatif() { |
$chaineDeParametres = "param1=valeur1,\nparam2=valeur2"; |
$tableauDeParametres = Outils::recupererTableauConfig($chaineDeParametres); |
$tableauDeParametresAttendus = array('param1' => 'valeur1','param2' => 'valeur2'); |
$this->assertEquals($tableauDeParametresAttendus, $tableauDeParametres); |
} |
public function testRecupererTableauConfigAssociatifAvecEspace() { |
$chaineDeParametres = "param1 =valeur1 , \nparam2 = valeur2"; |
$tableauDeParametres = Outils::recupererTableauConfig($chaineDeParametres); |
$tableauDeParametresAttendus = array('param1' => 'valeur1','param2' => 'valeur2'); |
$this->assertEquals($tableauDeParametresAttendus, $tableauDeParametres); |
} |
public function testRecupererTableauConfigSimple() { |
$chaineDeParametres = "param1,\nparam2"; |
$tableauDeParametres = Outils::recupererTableauConfig($chaineDeParametres); |
$tableauDeParametresAttendus = array('param1', 'param2'); |
$this->assertEquals($tableauDeParametresAttendus, $tableauDeParametres); |
} |
public function testRecupererTableauConfigSimpleAvecEspace() { |
$chaineDeParametres = " param1 ,\n param2 "; |
$tableauDeParametres = Outils::recupererTableauConfig($chaineDeParametres); |
$tableauDeParametresAttendus = array('param1', 'param2'); |
$this->assertEquals($tableauDeParametresAttendus, $tableauDeParametres); |
} |
public function testExtraireRequetes() { |
$contenuSql = "CREATE TABLE IF NOT EXISTS bdtfx_v1_01 (". |
"num_nom int(9) NOT NULL DEFAULT '0',". |
"num_nom_retenu varchar(9) CHARACTER SET utf8 DEFAULT NULL,". |
") ENGINE=MyISAM DEFAULT CHARSET=utf8;\n\n". |
"INSERT INTO bdtfx_meta (guid) VALUES". |
"('urn:lsid:tela-botanica.org:bdtfx:1.01');\n". |
"SELECT * FROM ma_table;"; |
$tableauDeRequetes = Outils::extraireRequetes($contenuSql); |
$tableauDeRequetesAttendus = array("CREATE TABLE IF NOT EXISTS bdtfx_v1_01 (". |
"num_nom int(9) NOT NULL DEFAULT '0',". |
"num_nom_retenu varchar(9) CHARACTER SET utf8 DEFAULT NULL,". |
") ENGINE=MyISAM DEFAULT CHARSET=utf8", |
"INSERT INTO bdtfx_meta (guid) VALUES". |
"('urn:lsid:tela-botanica.org:bdtfx:1.01')", |
"SELECT * FROM ma_table"); |
$this->assertEquals($tableauDeRequetesAttendus, $tableauDeRequetes); |
} |
public function testAfficherAvancement() { |
ob_start(); |
for ($i = 0; $i < 10; $i++) { |
$tableauDeRequetes = Outils::afficherAvancement("Test"); |
} |
$messageFinal = ob_get_clean(); |
$messageFinalAttendu = 'Test : 0'.chr(8).'1'.chr(8).'2'.chr(8).'3'.chr(8).'4'.chr(8).'5'.chr(8).'6'.chr(8).'7'.chr(8).'8'.chr(8).'9'; |
$this->assertEquals($messageFinalAttendu, $messageFinal); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/tests/bibliotheque/EfloreScriptTest.php |
---|
New file |
0,0 → 1,48 |
<?php |
require_once dirname(__FILE__).'/../ScriptEflorePhpUnit.php'; |
class EfloreScriptTest extends ScriptEflorePhpUnit { |
public function testChargerConfigDuProjetAvecFichiersIni() { |
$cheminRacine = realpath(dirname(__FILE__).'/../tmp/').'/'; |
if (!file_exists($cheminRacine.'test.ini')) { |
file_put_contents($cheminRacine.'test.ini', "[tables]\ntest=OK"); |
} |
$script = $this->getMock('EfloreScript', array('getScriptChemin', 'getProjetNom', 'executer')); |
$script->expects($this->any())->method('getScriptChemin')->will($this->returnValue($cheminRacine)); |
$script->expects($this->any())->method('getProjetNom')->will($this->returnValue('test')); |
$chargerConfigDuProjet = self::getProtectedMethode($script, 'chargerConfigDuProjet'); |
$chargerConfigDuProjet->invoke($script); |
$parametreConfig = Config::get('tables.test'); |
$this->assertEquals('OK', $parametreConfig); |
} |
public function testGetBdd() { |
$nomDuScript = 'Test'; |
$parametresCli = array('-a' => 'tester', '-v' => '3'); |
$script = $this->getClasseAbstraite('EfloreScript', array($nomDuScript, $parametresCli)); |
$getBdd = self::getProtectedMethode($script, 'getBdd'); |
$bdd = $getBdd->invoke($script); |
$this->assertTrue(is_object($bdd)); |
$this->assertEquals('Bdd', get_class($bdd)); |
} |
public function testStopperLaBoucle() { |
$nomDuScript = 'Test'; |
$parametresCli = array('-a' => 'tester', '-v' => '3'); |
$script = $this->getClasseAbstraite('EfloreScript', array($nomDuScript, $parametresCli)); |
$stopperLaBoucle = self::getProtectedMethode($script, 'stopperLaBoucle'); |
for ($i = 0; $i < 100; $i++) { |
if ($stopperLaBoucle->invoke($script, '10')) { |
break; |
} |
} |
$this->assertEquals('9', $i); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/tests/ScriptEflorePhpUnit.php |
---|
New file |
0,0 → 1,92 |
<?php |
// declare(encoding='UTF-8'); |
/** |
* Classe contenant des méthodes : |
* - d'intialisation des tests, |
* - refactorisant le code des tests, |
* - facilitant les tests. |
* |
* @category php 5.3 |
* @package Tests/Scripts |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
abstract class ScriptEflorePhpUnit extends PHPUnit_Framework_TestCase { |
public static function setUpBeforeClass() { |
error_reporting(E_ALL); |
self::chargerFramework(); |
} |
private static function chargerFramework() { |
$cheminRacine = realpath(dirname(__FILE__).'/../').'/'; |
$framework = $cheminRacine.'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($cheminRacine);// Obligatoire |
} |
} |
//+------------------------------------------------------------------------------------------------------+ |
// Méthodes facilitant les tests |
/** |
* Récupère un bouchon de classe abstraite. |
* Comment l'utiliser : |
* $classeAstraite = $this->getClasseAbstraite('MaClasse', array('param1', 'param2')); |
* $foo = $classeAstraite->methodeConcretePublique(); |
* |
* @param String $classeNom Le nom de la classe |
* @param Array $parametres Les paramètres à passer au constructeur. |
* @return Object Le bouchon de la classe abstraite |
*/ |
public function getClasseAbstraite($classeNom, Array $parametres) { |
$efloreScript = $this->getMockForAbstractClass($classeNom, $parametres); |
return $efloreScript; |
} |
/** |
* Récupère une méthode privée d'une classe pour tester/documenter. |
* Comment l'utiliser : |
* MyClass->foo(): |
* $cls = new MyClass(); |
* $foo = self::getPrivateMethode($cls, 'foo'); |
* $foo->invoke($cls, $...); |
* |
* @param object $objet Une instance de votre classe |
* @param string $methode Le nom de la méthode private |
* @return ReflectionMethod La méthode demandée |
*/ |
public static function getPrivateMethode($objet, $nomMethode) { |
$classe = new ReflectionClass($objet); |
$methode = $classe->getMethod($nomMethode); |
$methode->setAccessible(true); |
return $methode; |
} |
/** |
* Récupère une méthode protégée d'une classe pour tester/documenter. |
* Comment l'utiliser : |
* MyClass->foo(): |
* $cls = new MyClass(); |
* $foo = self::getProtectedMethode($cls, 'foo'); |
* $foo->invoke($cls, $...); |
* @param object $objet Une instance de votre classe |
* @param string $methode Le nom de la méthode protected |
* @return ReflectionMethod La méthode demandée |
*/ |
public static function getProtectedMethode($objet, $nomMethode) { |
return self::getPrivateMethode($objet, $nomMethode); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/tests/tmp |
---|
New file |
Property changes: |
Added: svn:ignore |
+test.defaut.ini |
+test.ini |
/tags/v5.7-arrayanal/scripts/modules/coste/Description.php |
---|
New file |
0,0 → 1,570 |
<?php |
// commande : /opt/lampp/bin/php cli.php description_sp -a tester -n /home/jennifer/Tela-botanica_projets/Coste/descriptions/html |
class Description { |
const DOSSIER_V0 = '../../../donnees/coste/0.00/'; |
const DOSSIER_DSC_HTML = '../../../donnees/coste/descriptions/html/'; |
const DOSSIER_DSC_TXT = '../../../donnees/coste/descriptions/txt/'; |
const DOSSIER_LOG = 'log/'; |
private $auteurs = array(); |
private $dossierBase = ''; |
private $conteneur = null; |
private $outils = null; |
private $messages = null; |
private $action = ''; |
private $nomFichier = ''; |
private $nomDossier = ''; |
private $listeFichiers = array(); |
private $fichierNum = ''; |
private $fichier = ''; |
private $log = ''; |
private $correspondance = array(); |
private $infosCorrespondanceBase = array( |
'nom_sci' => '', |
'auteur' => '', |
'nom_addendum' => '', |
'annee' => '', |
'biblio_origine' => '', |
'rang' => 290, |
'nom_francais' => '', |
'nom_coste' => '', |
'auteur_coste' => '', |
'biblio_coste' => '', |
'num_nom_coste' => '', |
'num_nom_retenu_coste' => '', |
'num_tax_sup_coste' => '', |
'tome' => '', |
'page' => '', |
'synonymie_coste' => '', |
'flore_bdtfx_nn' => '', |
'flore_bdtfx_nt' => ''); |
public function __construct(Conteneur $conteneur) { |
mb_internal_encoding('UTF-8'); |
setlocale(LC_ALL, 'fr_FR.UTF-8'); |
$this->conteneur = $conteneur; |
$this->outils = $conteneur->getOutils(); |
$this->messages = $conteneur->getMessages(); |
$this->dossierBase = dirname(__FILE__).'/'; |
} |
public function genererDescriptionTxt() { |
$this->chargerFichiers(); |
foreach ($this->listeFichiers as $this->fichierNum => $this->fichier) { |
$this->messages->afficherAvancement("Création des descriptions au format txt"); |
$this->genererFichier(); |
} |
echo "\n"; |
} |
public function verifierDescriptionTxt() { |
$this->chargerFichiers(); |
foreach ($this->listeFichiers as $this->fichierNum => $this->fichier) { |
$this->messages->afficherAvancement("Analyse des descriptions"); |
$this->verifierFichier(); |
} |
echo "\n"; |
$this->ecrireLogs(); |
} |
public function genererCorrespondance() { |
$this->chargerFichiers(); |
$this->ajouterLogSyno(implode("\t", array_keys($this->infosCorrespondanceBase))); |
foreach ($this->listeFichiers as $this->fichierNum => $this->fichier) { |
$this->messages->afficherAvancement("Création du fichier de correspondance"); |
$this->extraireInfosCorrespondance(); |
} |
echo "\n"; |
$fichierTxt = $this->dossierBase.self::DOSSIER_V0.'index_general_sp.tsv'; |
$txtCorrespondance = $this->creerFichierCsvCorrespondance(); |
file_put_contents($fichierTxt, $txtCorrespondance); |
ksort($this->auteurs); |
foreach ($this->auteurs as $auteur => $nbre) { |
$this->ajouterLogAuteur("$auteur\t$nbre"); |
} |
$this->ecrireLogs(); |
} |
private function chargerFichiers() { |
$this->nomDossier = $this->dossierBase.self::DOSSIER_DSC_HTML; |
if (file_exists($this->nomDossier) === true) { |
if (is_dir($this->nomDossier)) { |
if ($dossierOuvert = opendir($this->nomDossier)) { |
while (($this->nomFichier = readdir($dossierOuvert)) !== false) { |
if (! is_dir($this->nomFichier) && preg_match('/e([0-9]{4})\.htm/', $this->nomFichier, $match)) { |
$this->listeFichiers[$match[1]] = $this->nomDossier.'/'.$this->nomFichier; |
} |
} |
closedir($dossierOuvert); |
} else { |
$this->messages->traiterErreur("Le dossier {$this->nomDossier} n'a pas pu être ouvert."); |
} |
} else { |
$this->messages->traiterErreur("{$this->nomDossier} n'est pas un dossier."); |
} |
} else { |
$this->messages->traiterErreur("Le dossier {$this->nomDossier} est introuvable."); |
} |
asort($this->listeFichiers); |
} |
private function verifierFichier() { |
$donnees = $this->analyserFichier(); |
$txt = $donnees['texte']; |
$this->verifierOuvertureFermetureBalise($txt); |
$this->verifierAbscenceEgale($txt); |
$this->verifierNumero($txt); |
// TODO : vérifier les noms vernauclaire qui sont abrégés |
} |
private function verifierOuvertureFermetureBalise($txt) { |
$b_ouvert = substr_count($txt, '<B>'); |
$b_ferme = substr_count($txt, '</B>'); |
if ($b_ouvert != $b_ferme) { |
$message = "{$this->fichierNum} contient $b_ouvert balises B ouvertes et $b_ferme fermées"; |
$this->ajouterLogAnalyse($message); |
} |
$i_ouvert = substr_count($txt, '<I>'); |
$i_ferme = substr_count($txt, '</I>'); |
if ($i_ouvert != $i_ferme) { |
$message = "{$this->fichierNum} contient $i_ouvert balises I ouvertes et $i_ferme fermées"; |
$this->ajouterLogAnalyse($message); |
} |
} |
private function verifierAbscenceEgale($txt) { |
if (strripos($txt, '=') === false) { |
$message = "{$this->fichierNum} ne contient pas le séparateur de phénologie (=)"; |
$this->ajouterLogAnalyse($message); |
} |
} |
private function verifierNumero($txt) { |
if (preg_match('/^<B>[0-9]{1,4}. – /', $txt) == 0) { |
$message = "{$this->fichierNum} ne contient pas un numéro bien formaté"; |
$this->ajouterLogAnalyse($message); |
} |
} |
private function extraireInfosCorrespondance() { |
$donnees = $this->analyserFichier(); |
$infos = $this->infosCorrespondanceBase; |
$titre = $donnees['titre']; |
if (preg_match('/^Coste ([0-9]+) - ((?:(?! - ).)+) - F[0-9]+, (?:(?! - ).)+ - (G[0-9]+), T([123])[.]p([0-9]+)$/', $titre, $match)) { |
$infos['num_nom_coste'] = $match[1]; |
$infos['num_nom_retenu_coste'] = $match[1]; |
$infos['nom_sci'] = $match[2]; |
$infos['num_tax_sup_coste'] = $match[3]; |
$infos['tome'] = $match[4]; |
$infos['page'] = $match[5]; |
} else { |
$this->messages->traiterErreur("Le titre du fichier {$this->fichierNum} est mal formaté."); |
} |
$corres = $donnees['correspondance']; |
if (preg_match('/^Bdnff ([0-9]+) - (?:(?! - ).)+ - (?:(?! - ).)+ - Tax=([0-9]+)$/', $corres, $match)) { |
$infos['flore_bdtfx_nn'] = $match[1]; |
$infos['flore_bdtfx_nt'] = $match[2]; |
} else { |
$this->messages->traiterErreur("La correspondance du fichier {$this->fichierNum} est mal formatée."); |
} |
$txt = $donnees['texte']; |
$txt = $this->corrigerDescription($txt); |
if (preg_match('/^<B>[0-9]{1,4}[.] – ([^<]+)<\/B> ([^–]*)– (?:<I>([^<]+)<\/I>[.] – |<I>([^<]+)<\/I>( \([^)]+\))[.] – |[A-Z]|<I>(?:Sous-|Espèce|Turion|Souche|Plante|Feuille|Racine))/u', $txt, $match)) { |
$infos['nom_coste'] = trim($match[1]); |
$infos['rang'] = $this->obtenirRangNom($infos['nom_coste']); |
$infos['auteur_coste'] = trim($match[2]); |
$infos['nom_francais'] = isset($match[3]) ? $match[3] : ''; |
$infos['nom_francais'] = isset($match[4]) && isset($match[5]) ? $match[4].$match[5] : $infos['nom_francais']; |
if (strpos($infos['auteur_coste'], '(' ) !== false) { |
if (preg_match('/^([^(]*)\(([^)]+)\)(?:[.]?| ; ((?:(?! – ).)+))$/', $infos['auteur_coste'], $match)) { |
$infos['auteur_coste'] = $this->traiterAuteur(trim($match[1])); |
$infos['auteur'] = $this->normaliserAuteur($infos['auteur_coste']); |
$parentheseContenu = trim($match[2]); |
if (preg_match('/^[0-9]+$/', $parentheseContenu)) { |
$infos['annee'] = $parentheseContenu; |
} else { |
$infos['synonymie_coste'] = $parentheseContenu; |
$infos['biblio_coste'] = isset($match[3]) ? trim($match[3]) : ''; |
} |
} else { |
$this->messages->traiterErreur("L'auteur du nom sciencitifique du fichier {$this->fichierNum} est mal formaté."); |
} |
} |
} else { |
$this->messages->traiterErreur("La texte du fichier {$this->fichierNum} est mal formaté."); |
} |
$this->correspondance[] = $infos; |
if ($infos['synonymie_coste'] != '') { |
$this->traiterSynonymie($infos); |
} |
} |
private function normaliserAuteur($auteurCoste) { |
$auteur = ''; |
if ($auteurCoste != '') { |
$auteur = str_replace(' et ', ' & ', $auteurCoste); |
} |
return $auteur; |
} |
private function traiterSynonymie($infos) { |
$synoCoste = $infos['synonymie_coste']; |
$synoCoste = preg_replace('/, etc[.]$/', '', $synoCoste); |
$synoCoste = preg_replace('/^et /', '', $synoCoste); |
$synoCoste = preg_replace('/^(([A-Z][.]|[A-Z]{3,}) [A-Z]{3,}(?:(?! et ).+)) et ([A-Z]{3,}) ((?![A-Z]{3,}).+)$/', '$1 ; $2 $3 $4', $synoCoste); |
$synoCoste = preg_replace('/ et ((?:[A-Z][.]|[A-Z]{3,}) [A-Z]{3,})/', ' ; $1', $synoCoste); |
$synoCoste = preg_replace('/, ((?:(?!non |part[.]|an |G[.] G[.]|part[.]|centr[.])[^,]+))/', ' ;$1', $synoCoste); |
$synonymes = explode(';', $synoCoste); |
foreach ($synonymes as $num => $syno) { |
$synoTraite = $this->traiterNomSyno($syno); |
$nomSci = $this->obtenirNomSci($synoTraite, $infos, $synonymes, $num); |
$rang = $this->obtenirRangNom($nomSci); |
$complementNom = $this->obtenirComplementNom($synoTraite); |
$auteurCoste = $this->obtenirAuteur($complementNom); |
$auteur = $this->normaliserAuteur($auteurCoste); |
$this->ajouterAuteur($auteur); |
$biblioCoste = $this->obtenirBiblio($complementNom); |
$annee = $this->extraireAnnee($complementNom); |
$infosSyno = $this->infosCorrespondanceBase; |
$infosSyno['nom_sci'] = $nomSci; |
$infosSyno['auteur'] = $auteur; |
$infosSyno['biblio_origine'] = $biblioCoste; |
$infosSyno['annee'] = $annee; |
$infosSyno['nom_addendum'] = $this->obtenirNomAddendum($syno); |
$infosSyno['rang'] = $rang; |
$infosSyno['nom_coste'] = $synoTraite; |
$infosSyno['auteur_coste'] = $auteurCoste; |
$infosSyno['biblio_coste'] = $biblioCoste; |
$infosSyno['num_nom_coste'] = $infos['num_nom_coste'].'.'.($num + 1); |
$infosSyno['num_nom_retenu_coste'] = $infos['num_nom_coste']; |
$this->ajouterLogSyno(implode("\t", $infosSyno)); |
$this->correspondance[] = $infosSyno; |
} |
} |
private function traiterNomSyno($syno) { |
$syno = $this->nettoyerEspacesNomSyno($syno); |
$syno = preg_replace('/^(?:avec|(?:compr|incl)[.]) /', '', $syno); |
return $syno; |
} |
private function nettoyerEspacesNomSyno($syno) { |
$syno = trim($syno); |
$syno = trim($syno, ' '); |
return $syno; |
} |
private function obtenirComplementNom($syno) { |
$complementNom = ''; |
if (preg_match('/^(?:[^ ]+ [^ ]+ (?:(?:var|V)[.] [^ ]+|STELATUM|MINUS)|[^ ]+ [^ ]+) (.+)$/', $syno, $match)) { |
$complementNom = $match[1]; |
} |
return $complementNom; |
} |
private function obtenirBiblio($complementNom) { |
$biblioCoste = ''; |
if (preg_match("/ (p[.] [0-9]{1,}|in .+||Fl[.] fr[.]|(?: Sp[.])? ed[.] [1-2])$/", $complementNom, $match)) { |
$biblioCoste = $match[1]; |
} |
return $biblioCoste; |
} |
private function extraireAnnee($complementNom) { |
$annee = ''; |
if (preg_match('/(?:^| )([0-9]+)$/', $complementNom, $match)) { |
$annee = $match[1]; |
} |
return $annee; |
} |
private function obtenirAuteur($complementNom) { |
$auteurCoste = ''; |
if ($complementNom != '') { |
if (preg_match("/^((?!(?:auct.+|(?:, )?(?:non|an) .+|p[.] p[.])$).+)$/", $complementNom, $match)) { |
$auteurCoste = $this->traiterAuteur($match[1]); |
} else { |
$message = "Impossible de récupérer l'auteur pour le complément de nom ($complementNom)."; |
$this->ajouterLogProbleme($message); |
} |
} |
return $auteurCoste; |
} |
private function traiterAuteur($auteurCoste) { |
$auteur = ''; |
if ($auteurCoste != '') { |
$remplacementTxt = array(' p. p.', ' saltem part.', 'Fl. fr.'); |
$auteurCoste = str_replace($remplacementTxt, '', $auteurCoste); |
$remplacementsRegExp = array( |
' [0-9]{4}', |
'[^ ]+ et auct[.], .+', |
' auct.+', |
',? part[.]', |
' p[.] [0-9]{1,}', |
' in .+|,? (?:non|an) .+', |
'(?: Sp[.])? ed[.] [1-2]'); |
$auteur = preg_replace('/(?:'.implode('|', $remplacementsRegExp).')$/', '', $auteurCoste); |
} |
return $auteur; |
} |
private function ajouterAuteur($auteur) { |
if (!isset($this->auteurs[$auteur])) { |
$this->auteurs[$auteur] = 1; |
} else { |
$this->auteurs[$auteur]++; |
} |
} |
private function obtenirNomAddendum($syno) { |
$syno = $this->nettoyerEspacesNomSyno($syno); |
$nomAddendum = array(); |
if (preg_match('/^((?:compr|incl)[.]) /', $syno, $match)) { |
$nomAddendum[] = '['.$match[1].']'; |
} |
if (preg_match('/ ([^ ]+ et auct[.], .+)$/', $syno, $match)) { |
$nomAddendum[] = '['.$match[1].']'; |
} elseif (preg_match('/ (auct[.],? .+)$/', $syno, $match)) { |
$nomAddendum[] = '['.$match[1].']'; |
} else if (preg_match('/,? ((?:non|an) .+)$/', $syno, $match)) { |
$nomAddendum[] = '['.$match[1].']'; |
} else if (preg_match('/ (p[.] p[.])$/', $syno, $match)) { |
$nomAddendum[] = '['.$match[1].']'; |
} else if (preg_match('/ (saltem part[.])$/', $syno, $match)) { |
$nomAddendum[] = '['.$match[1].']'; |
} else if (preg_match('/,? (part[.])$/', $syno, $match)) { |
$nomAddendum[] = '['.$match[1].']'; |
} |
$nomAddendum = implode(' ; ', $nomAddendum); |
return $nomAddendum; |
} |
private function remplacerAbreviationGenre($syno, $infos, $synonymes, $num) { |
$nomSci = $syno; |
if (preg_match('/^(([A-Zƌ])[.]) /', $syno, $matchSyno)) { |
if ($matchSyno[2] == substr($infos['nom_coste'], 0, 1)) { |
if (preg_match('/^([^ ]+) /', $infos['nom_coste'], $matchNomRetenu)) { |
$nomSci = str_replace($matchSyno[1], $matchNomRetenu[1], $syno); |
} |
} else { |
$synoPrecedent = $this->obtenirSynoAvecGenreComplet($synonymes, $num); |
if ($matchSyno[2] == substr($synoPrecedent, 0, 1)) { |
if (preg_match('/^([^ ]+) /', $synoPrecedent, $matchSynoPrec)) { |
$nomSci = str_replace($matchSyno[1], $matchSynoPrec[1], $syno); |
} |
} else { |
$message = "L'initiale du synonyme ($syno) ne correspondant pas au nom retenu {$infos['num_nom_coste']} ({$infos['nom_coste']}) ". |
"ni au synonyme précédent ($synoPrecedent)."; |
$this->ajouterLogProbleme($message); |
} |
} |
} |
return $nomSci; |
} |
private function obtenirSynoAvecGenreComplet($synonymes, $num) { |
$synoPrecedent = ''; |
$synoOk = false; |
while ($synoOk == false) { |
if ($num < 0) { |
$synoOk = true; |
} |
$synoPrecedent = $this->obtenirSynoPrecedent($synonymes, $num); |
if (preg_match('/^[A-Zƌ][.] /', $synoPrecedent)) { |
$num = $num - 1; |
} else { |
$synoOk = true; |
} |
} |
return $synoPrecedent; |
} |
private function obtenirSynoPrecedent($synonymes, $num) { |
$synoPrecedent = ''; |
if (isset($synonymes[($num - 1 )])) { |
$synoPrecedent = $this->traiterNomSyno($synonymes[($num - 1 )]); |
} |
return $synoPrecedent; |
} |
private function obtenirNomSci($syno, $infos, $synonymes, $num) { |
$nomSci = $this->remplacerAbreviationGenre($syno, $infos, $synonymes, $num); |
if (preg_match('/^([^ ]+) ([^ ]+) (?:(?:var|V)[.] ([^ ]+)|(STELATUM||MINUS) )/', $nomSci, $match)) { |
$genre = $this->normaliserGenre($match[1]); |
$sp = $this->normaliserEpithete($match[2]); |
$infrasp = isset($match[4]) ? $match[4] : $match[3]; |
$infrasp = $this->normaliserEpithete($infrasp); |
$nomSci = "$genre $sp var. $infrasp"; |
} else if (preg_match('/^([^ ]+) ([^ ]+)(?: |$)/', $nomSci, $match)) { |
$genre = $this->normaliserGenre($match[1]); |
$sp = $this->normaliserEpithete($match[2]); |
$nomSci = "$genre $sp"; |
} else { |
$message = "Le synonyme ($nomSci) du nom {$infos['num_nom_coste']} a une structure étrange."; |
$this->ajouterLogProbleme($message); |
} |
return $nomSci; |
} |
private function normaliserGenre($genre) { |
$genre = mb_convert_case(mb_strtolower($genre), MB_CASE_TITLE); |
$genre = str_replace('Æ', 'æ', $genre); |
return $genre; |
} |
private function normaliserEpithete($sp) { |
$sp = mb_strtolower($sp); |
$sp = str_replace('Æ', 'æ', $sp); |
return $sp; |
} |
private function obtenirRangNom($syno) { |
$rang = 290; |
if (strpos($syno, ' var. ')) { |
$rang = 340; |
} |
return $rang; |
} |
private function creerFichierCsvCorrespondance() { |
$lignes[] = implode("\t", array_keys($this->infosCorrespondanceBase)); |
foreach ($this->correspondance as $infos) { |
$lignes[] = implode("\t", $infos); |
} |
$txt = ''; |
$txt = implode("\n", $lignes); |
return $txt; |
} |
private function genererFichier() { |
$donnees = $this->analyserFichier(); |
$txt = $this->nettoyerDescription($donnees['texte']); |
$txt = $this->corrigerDescription($txt); |
$txt = $this->remplacerHtmlParSyntaxeWiki($txt); |
$fichierTxt = $this->dossierBase.self::DOSSIER_DSC_TXT.$this->fichierNum.'.txt'; |
file_put_contents($fichierTxt, $txt); |
unset($donnees['texte']); |
$txt = implode("\n", $donnees); |
$fichierTxt = $this->dossierBase.self::DOSSIER_DSC_TXT.$this->fichierNum.'.json'; |
file_put_contents($fichierTxt, $txt); |
} |
private function analyserFichier() { |
$donnees = array('titre' => '', 'texte' => '', 'correspondance' => ''); |
if ($fichierOuvert = fopen($this->fichier, 'r')) { |
$i = 1; |
while ($ligne = fgets($fichierOuvert)) { |
if ($i == 24) { |
$donnees['titre'] = $this->supprimerHtml($ligne); |
} elseif ($i >= 45 && $i <= 60) { |
$donnees['texte'] .= $this->traiterLigneDescription($ligne); |
} elseif ($i >= 61 && preg_match('/Bdnff /ui', $ligne)) { |
$donnees['correspondance'] = $this->supprimerHtml($ligne); |
} |
$i++; |
} |
fclose($fichierOuvert); |
} else { |
$this->messages->traiterErreur("Le fichier {$this->fichier} n'a pas pu être ouvert."); |
} |
return $donnees; |
} |
private function supprimerHtml($txt) { |
$txt = strip_tags($txt,'<b>,<i>'); |
$txt = str_replace('­', '', $txt); |
$txt = str_ireplace(' ', ' ', $txt); |
$txt = trim($txt); |
$txt = preg_replace('/^<\/I>/', '', $txt); |
$txt = html_entity_decode($txt, ENT_NOQUOTES, 'UTF-8'); |
return $txt; |
} |
private function traiterLigneDescription($txt) { |
$txt = $this->supprimerHtml($txt); |
$txt = $txt."\n"; |
return $txt; |
} |
private function nettoyerDescription($txt) { |
$txt = preg_replace("/\n{2,}+/", "\n", $txt); |
$txt = trim($txt); |
return $txt; |
} |
private function corrigerDescription($txt) { |
$txt = preg_replace("/– <I>([^.]+?)[.] – <\/I>/", "– <I>$1</I>. – ", $txt); |
$txt = preg_replace("/– <I>([^.]+?)[.] – ([A-Z])<\/I>/", "– <I>$1</I>. – $2", $txt); |
$txt = preg_replace("/– <I>([^.]+?) – <\/I>/", "– <I>$1</I>. – ", $txt); |
return $txt; |
} |
private function remplacerHtmlParSyntaxeWiki($txt) { |
$txt = str_replace(array('<B>', '</B>'), '**', $txt); |
$txt = str_replace(array('<I>', '</I>'), '//', $txt); |
return $txt; |
} |
private function ajouterLogAnalyse($txt) { |
if (isset($this->log['analyse']) == false) { |
$this->log['analyse'] = ''; |
} |
$this->log['analyse'] .= "$txt\n"; |
} |
private function ajouterLogSyno($txt) { |
if (isset($this->log['synonymes']) == false) { |
$this->log['synonymes'] = ''; |
} |
$this->log['synonymes'] .= "$txt\n"; |
} |
private function ajouterLogAuteur($txt) { |
if (isset($this->log['auteurs']) == false) { |
$this->log['auteurs'] = ''; |
} |
$this->log['auteurs'] .= "$txt\n"; |
} |
private function ajouterLogProbleme($txt) { |
if (isset($this->log['problemes']) == false) { |
$this->log['problemes'] = ''; |
} |
$this->log['problemes'] .= "$txt\n"; |
} |
private function ecrireLogs() { |
foreach ($this->log as $nom => $log) { |
$fichier = $this->dossierBase.self::DOSSIER_LOG.$nom.'.log'; |
file_put_contents($fichier, $log); |
} |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/coste/Wiki.php |
---|
New file |
0,0 → 1,251 |
<?php |
class Wiki { |
const DOSSIER_V2 = '../../../donnees/coste/2.00/'; |
const DOSSIER_DSC_TXT = '../../../donnees/coste/descriptions/txt/'; |
private $URL_WIKI = ''; |
private $URL_WIKI_EFLORE = ''; |
private $conteneur = null; |
private $outils = null; |
private $messages = null; |
private $restClient = null; |
private $bdd = null; |
private $dossierBase = ''; |
private $index = array(); |
public function __construct(Conteneur $conteneur) { |
mb_internal_encoding('UTF-8'); |
setlocale(LC_ALL, 'fr_FR.UTF-8'); |
$this->conteneur = $conteneur; |
$this->URL_WIKI = $this->conteneur->getParametre('wiki.travail'); |
$this->URL_WIKI_EFLORE = $this->conteneur->getParametre('wiki.eflore'); |
$this->outils = $conteneur->getOutils(); |
$this->messages = $conteneur->getMessages(); |
$this->restClient = $conteneur->getRestClient(); |
$this->bdd = $conteneur->getBdd(); |
$this->dossierBase = dirname(__FILE__).'/'; |
} |
public function uploaderFichiersSp() { |
$this->chargerIndex(); |
$envoyes = array(); |
foreach ($this->index as $nom) { |
$tag = $nom['page_wiki_dsc']; |
if (isset($envoyes[$tag]) == false && preg_match('/^Esp([0-9]{4})/', $tag, $match)) { |
$fichier = $this->dossierBase.self::DOSSIER_DSC_TXT.$match[1].'.txt'; |
if (file_exists($fichier) === true) { |
$txt = file_get_contents($fichier); |
$donnees = array('pageTag' => $tag, 'pageContenu' => $txt); |
$this->restClient->ajouter($this->URL_WIKI, $donnees); |
$envoyes[$tag] = 'OK'; |
} else { |
$this->messages->traiterErreur("Le fichier $fichier est introuvable."); |
} |
} |
$this->messages->afficherAvancement("Upload des fichiers d'espèce dans le wikini"); |
} |
echo "\n"; |
} |
public function dowloaderPagesWiki() { |
$this->chargerIndex(); |
$envoyes = array(); |
foreach ($this->index as $nom) { |
$tagDsc = $nom['page_wiki_dsc']; |
$tagCle = $nom['page_wiki_cle']; |
if (isset($envoyes[$tagDsc]) == false) { |
$url = $this->URL_WIKI.'/'.$tagDsc; |
$txt = $this->telechargerTxt($url); |
$fichier = $this->dossierBase.self::DOSSIER_V2.'dsc/'.$tagDsc.'.txt'; |
if (file_put_contents($fichier, $txt)) { |
$envoyes[$tagDsc] = 'OK'; |
} |
} |
if (isset($envoyes[$tagCle]) == false) { |
$url = $this->URL_WIKI.'/'.$tagCle; |
$txt = $this->telechargerTxt($url); |
$fichier = $this->dossierBase.self::DOSSIER_V2.'cle/'.$tagCle.'.txt'; |
if (file_put_contents($fichier, $txt)) { |
$envoyes[$tagCle] = 'OK'; |
} |
} |
$this->messages->afficherAvancement("Download des fichiers en cours"); |
} |
echo "\n"; |
} |
public function uploaderDansWikiEflore() { |
$this->chargerIndex(); |
$envoyes = array(); |
foreach ($this->index as $nom) { |
$tagDsc = $nom['page_wiki_dsc']; |
if (isset($envoyes[$tagDsc]) == false) { |
$fichier = $this->dossierBase.self::DOSSIER_V2.'dsc/'.$tagDsc.'.txt'; |
if (file_exists($fichier) === true) { |
$txt = file_get_contents($fichier); |
$this->envoyerPage($tagDsc, $txt); |
$envoyes[$tagDsc] = 'OK'; |
} else { |
$this->messages->traiterErreur("Le fichier $fichier est introuvable."); |
} |
} |
$tagCle = $nom['page_wiki_cle']; |
if (isset($envoyes[$tagCle]) == false) { |
$fichier = $this->dossierBase.self::DOSSIER_V2.'cle/'.$tagCle.'.txt'; |
if (file_exists($fichier) === true) { |
$txt = file_get_contents($fichier); |
$this->envoyerPage($tagCle, $txt); |
$envoyes[$tagCle] = 'OK'; |
} else { |
$this->messages->traiterErreur("Le fichier $fichier est introuvable."); |
} |
} |
$this->messages->afficherAvancement("Upload des textes dans le wikini eFlore"); |
} |
echo "\n"; |
} |
public function chargerTxtDansWikiEflore() { |
$this->chargerIndex(); |
$envoyes = array(); |
foreach ($this->index as $nom) { |
$tagDsc = $nom['page_wiki_dsc']; |
if ($tagDsc != '' && isset($envoyes[$tagDsc]) == false) { |
$fichier = $this->dossierBase.self::DOSSIER_V2.'dsc/'.$tagDsc.'.txt'; |
if (file_exists($fichier) === true) { |
$txt = file_get_contents($fichier); |
$this->enregistrerPage($tagDsc, $txt); |
$envoyes[$tagDsc] = 'OK'; |
} else { |
$this->messages->traiterErreur("Le fichier $fichier est introuvable."); |
} |
} |
$tagCle = $nom['page_wiki_cle']; |
if ($tagCle != '' && isset($envoyes[$tagCle]) == false) { |
$fichier = $this->dossierBase.self::DOSSIER_V2.'cle/'.$tagCle.'.txt'; |
if (file_exists($fichier) === true) { |
$txt = file_get_contents($fichier); |
$this->enregistrerPage($tagCle, $txt); |
$envoyes[$tagCle] = 'OK'; |
} else { |
$this->messages->traiterErreur("Le fichier $fichier est introuvable."); |
} |
} |
$this->messages->afficherAvancement("Enregistrement des textes dans le wikini eFlore"); |
} |
echo "\n"; |
} |
public function chargerIndexDansWikiEflore() { |
$index = $this->creerIndex(); |
foreach ($index as $titre => $txt) { |
$this->enregistrerPage($titre, $txt); |
} |
} |
public function uploaderIndexDansWikiEflore() { |
$index = $this->creerIndex(); |
foreach ($index as $titre => $txt) { |
$this->envoyerPage($titre, $txt); |
} |
} |
public function creerIndex() { |
$this->chargerIndex(); |
$envoyes = array(); |
$pageIndexFamille = "==Index Famille Coste==\n\n"; |
$pageIndexGenre = "==Index Genre Coste==\n\n"; |
$pageIndexEspece = "==Index Espèce Coste==\n\n"; |
foreach ($this->index as $nom) { |
$indentation = $this->getIndentationTxtLien($nom); |
$txtLien = $this->getTxtLienGenerique($nom); |
$img = $nom['image']; |
$tagDsc = $nom['page_wiki_dsc']; |
if (isset($envoyes[$tagDsc]) == false) { |
//$fichier = $this->dossierBase.self::DOSSIER_V2.'dsc/'.$tagDsc.'.txt'; |
if ($nom['rang'] <= 180) { |
$pageIndexFamille .= "$indentation- [[$tagDsc $txtLien]]\n"; |
} elseif ($nom['rang'] == 220) { |
$pageIndexGenre .= "$indentation- [[$tagDsc $txtLien]]\n"; |
} else { |
$pageIndexEspece .= "$indentation- [[$tagDsc $txtLien]] - [[http://www.tela-botanica.org/eflore/donnees/coste/2.00/img/$img]]\n"; |
} |
$envoyes[$tagDsc] = 'OK'; |
} |
$tagCle = $nom['page_wiki_cle']; |
if (isset($envoyes[$tagCle]) == false) { |
//$fichier = $this->dossierBase.self::DOSSIER_V2.'cle/'.$tagCle.'.txt'; |
$indentation = $indentation.' '; |
if ($nom['rang'] <= 180) { |
$pageIndexFamille = rtrim($pageIndexFamille, "\n"); |
$pageIndexFamille .= " - [[$tagCle Clé]]\n"; |
} elseif ($nom['rang'] == 220) { |
$pageIndexGenre = rtrim($pageIndexGenre, "\n"); |
$pageIndexGenre .= " - [[$tagCle Clé]]\n"; |
} |
$envoyes[$tagCle] = 'OK'; |
} |
$this->messages->afficherAvancement("Création des pages d'index pour le wikini eFlore"); |
} |
echo "\n"; |
$index = array('IndexFamille' => $pageIndexFamille, 'IndexGenre' => $pageIndexGenre, 'IndexEspece' => $pageIndexEspece); |
return $index; |
} |
private function getIndentationTxtLien($nom) { |
$rangs = array('Reg' => 1, 'Emb' => 2, 'Cla' => 3, 'Fam' => 4, 'Gen' => 5, 'Esp' => 6); |
$indentation = ''; |
if (preg_match('/^(Reg|Emb|Cla|Fam|Gen|Esp)[0-9]+/', $nom['page_wiki_dsc'], $match)) { |
$type = $match[1]; |
$indentation = str_repeat(' ', $rangs[$type]); |
} |
return $indentation; |
} |
private function getTxtLienGenerique($nom) { |
$rangs = array('Reg' => 'Règne', 'Emb' => 'Embranchement', 'Cla' => 'Classe', 'Fam' => 'Famille', |
'Gen' => 'Genre', 'Esp' => 'Espèce'); |
$nomSci = $nom['nom_sci']; |
$nomCoste = $nom['nom_coste']; |
$txtLien = ''; |
if (preg_match('/^(Reg|Emb|Cla|Fam|Gen|Esp)([0-9]*)/', $nom['page_wiki_dsc'], $match)) { |
$numCoste = $match[2]; |
$type = $match[1]; |
$nomRang = $rangs[$type]; |
$nom = ($type == 'Fam') ? $nomCoste : $nomSci; |
$txtLien = "$nomRang $numCoste - $nom"; |
} |
return $txtLien; |
} |
private function envoyerPage($titre, $txt) { |
$donnees = array('pageTag' => $titre, 'pageContenu' => $txt); |
$this->restClient->ajouter($this->URL_WIKI_EFLORE, $donnees); |
} |
private function enregistrerPage($titre, $txt) { |
$titre = $this->bdd->proteger($titre); |
$time = $this->bdd->proteger(date('Y-m-d H:i:s')); |
$txt = $this->bdd->proteger($txt); |
$requete = "INSERT INTO `coste_pages` (`tag`, `time`, `body`, `body_r`, `owner`, `user`, `latest`, `handler`, `comment_on`) VALUES ". |
"($titre, $time, $txt, '', '', 'ScriptEflore', 'Y', 'page', '')"; |
$this->bdd->requeter($requete); |
} |
private function telechargerTxt($url) { |
$json = $this->restClient->consulter($url); |
$donnees = json_decode($json, true); |
return $donnees['texte']; |
} |
private function chargerIndex() { |
$indexTxt = $this->dossierBase.self::DOSSIER_V2.'coste_v2_00.tsv'; |
$this->index = $this->outils->transformerTxtTsvEnTableau($indexTxt); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/coste/coste.ini |
---|
New file |
0,0 → 1,30 |
; Ajouter les nouvelles version à la suite dans versions et versionsDonnees. |
version="2_00" |
versionDonnees="2.00" |
dossierTsv = "{ref:dossierDonneesEflore}coste/{ref:versionDonnees}/" |
dossierTsvTpl = "{ref:dossierDonneesEflore}coste/%s/" |
dossierSql = "{ref:dossierDonneesEflore}coste/" |
[tables] |
costeMeta = "coste_meta" |
coste = "coste_v{ref:version}" |
costeTpl = "coste_v%s" |
[fichiers] |
structureSqlVersion = "coste_v{ref:version}.sql" |
structureSqlVersionTpl = "coste_v%s.sql" |
coste = "coste_v{ref:version}.tsv" |
costeTpl = "coste_v%s.tsv" |
costeWikiniTpl = "coste_wikini_v%s.sql" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
structureSqlVersion = "{ref:dossierTsv}{ref:fichiers.structureSqlVersion}" |
structureSqlVersionTpl = "{ref:dossierTsvTpl}{ref:fichiers.structureSqlVersionTpl}" |
coste = "{ref:dossierTsv}{ref:fichiers.coste}" |
costeTpl = "{ref:dossierTsvTpl}{ref:fichiers.costeTpl}" |
costeWikiniTpl = "{ref:dossierTsvTpl}{ref:fichiers.costeWikiniTpl}" |
[wiki] |
travail = "http://www.tela-botanica.org/wikini/florecoste/api/rest/0.5/pages" |
eflore = "http://www.tela-botanica.org/wikini/coste/api/rest/0.5/pages" |
/tags/v5.7-arrayanal/scripts/modules/coste/Index.php |
---|
New file |
0,0 → 1,329 |
<?php |
class Index { |
const DOSSIER_V0 = '../../../donnees/coste/0.00/'; |
const DOSSIER_V2 = '../../../donnees/coste/2.00/'; |
private $conteneur = null; |
private $outils = null; |
private $messages = null; |
private $generateur = null; |
private $dossierBase = ''; |
private $spIndex = array(); |
private $supraSpIndex = array(); |
private $imgIndex = array(); |
private $indexFinal = array(); |
private $tableauParDefaut = array(); |
private $nbreTaxonInf = array(); |
private $enteteFinal = array( |
'num_nom', |
'num_nom_retenu', |
'num_tax_sup', |
'rang', |
'nom_sci', |
'nom_supra_generique', |
'genre', |
'epithete_infra_generique', |
'epithete_sp', |
'type_epithete', |
'epithete_infra_sp', |
'cultivar_groupe', |
'cultivar', |
'nom_commercial', |
'auteur', |
'annee', |
'biblio_origine', |
'notes', |
'nom_addendum', |
'nom_francais', |
'nom_coste', |
'auteur_coste', |
'biblio_coste', |
'num_nom_coste', |
'num_nom_retenu_coste', |
'num_tax_sup_coste', |
'synonymie_coste', |
'tome', |
'page', |
'nbre_taxons', |
'flore_bdtfx_nn', |
'flore_bdtfx_nt', |
'image', |
'image_auteur', |
'page_wiki_dsc', |
'page_wiki_cle', |
'nom_sci_html'); |
public function __construct(Conteneur $conteneur) { |
mb_internal_encoding('UTF-8'); |
setlocale(LC_ALL, 'fr_FR.UTF-8'); |
$this->conteneur = $conteneur; |
$this->outils = $conteneur->getOutils(); |
$this->messages = $conteneur->getMessages(); |
$this->generateur = $conteneur->getGenerateurNomSciHtml(); |
$this->dossierBase = dirname(__FILE__).'/'; |
} |
public function fusionnerIndex() { |
$this->chargerIndexSp(); |
$this->chargerIndexSupraSp(); |
$this->initialiserTableauLigneIndexFinal(); |
$this->creerIndexFinal(); |
$this->insererCorrections(); |
$this->ajouterChampsDansIndexFinal(); |
$this->ajouteurAuteurImage(); |
$this->decomposerNomSci(); |
$this->ajouteurNomSciHtml(); |
$this->creerFichierCsvIndexFinal(); |
} |
private function chargerIndexSp() { |
$spIndexFichier = $this->dossierBase.self::DOSSIER_V0.'index_general_sp.tsv'; |
$index = $this->outils->transformerTxtTsvEnTableau($spIndexFichier); |
$index = $this->reindexerParNumNomCoste($index); |
foreach ($index as $numNomCoste => $infos) { |
$numTaxSup = ''; |
if ($infos['num_nom_coste'] == $infos['num_nom_retenu_coste']) { |
$numTaxSup = $infos['num_tax_sup_coste']; |
} else { |
$infosNomRetenu = $index[$infos['num_nom_retenu_coste']]; |
$numTaxSup = $infosNomRetenu['num_tax_sup_coste']; |
} |
$this->spIndex[$numTaxSup][] = $infos; |
} |
} |
private function reindexerParNumNomCoste($index) { |
$nouvelIndex = array(); |
foreach ($index as $infos) { |
$nouvelIndex[$infos['num_nom_coste']] = $infos; |
} |
return $nouvelIndex; |
} |
private function chargerIndexSupraSp() { |
$infraSpIndexFichier = $this->dossierBase.self::DOSSIER_V0.'index_general.tsv'; |
$this->supraSpIndex = $this->outils->transformerTxtTsvEnTableau($infraSpIndexFichier); |
foreach ($this->supraSpIndex as $cle => $infos) { |
$this->supraSpIndex[$cle]['num_nom_retenu_coste'] = $infos['num_nom_coste']; |
} |
} |
private function initialiserTableauLigneIndexFinal() { |
$this->tableauParDefaut = array(); |
foreach ($this->enteteFinal as $cle) { |
$this->tableauParDefaut[$cle] = ''; |
} |
} |
private function creerIndexFinal() { |
foreach ($this->supraSpIndex as $infos) { |
$this->ajouterDansIndexFinal($infos); |
if (preg_match('/^G[0-9]+$/', $infos['num_nom_coste'])) { |
foreach ($this->spIndex[$infos['num_nom_coste']] as $infosSp) { |
$this->ajouterDansIndexFinal($infosSp); |
} |
} |
} |
} |
private function ajouterDansIndexFinal($infos) { |
$infos = array_merge($this->tableauParDefaut, $infos); |
$infos['num_nom'] = (count($this->indexFinal) + 1); |
$this->indexFinal[$infos['num_nom_coste']] = $infos; |
} |
private function ajouterChampsDansIndexFinal() { |
$this->genererNbreTaxons(); |
foreach ($this->indexFinal as $nnc => $infos) { |
if ($infos['num_nom_coste'] == $infos['num_nom_retenu_coste']) { |
$infos['num_nom_retenu'] = $infos['num_nom']; |
if ($nnc != 'R') { |
$nomSuperieur = $this->indexFinal[$infos['num_tax_sup_coste']]; |
$infos['num_tax_sup'] = $nomSuperieur['num_nom']; |
} |
$nomRetenu = $infos; |
} else { |
$nomRetenu = $this->indexFinal[$infos['num_nom_retenu_coste']]; |
$infos['num_nom_retenu'] = $nomRetenu['num_nom']; |
$infos['page'] = $nomRetenu['page']; |
$infos['tome'] = $nomRetenu['tome']; |
} |
$infos['image'] = $this->obtenirNomFichierImg($nomRetenu); |
$infos['nbre_taxons'] = $this->obtenirNbreTaxon($infos); |
$nomRetenu['nbre_taxons'] = $infos['nbre_taxons']; |
$infos['page_wiki_dsc'] = $this->genererPageWikiDsc($nomRetenu); |
$infos['page_wiki_cle'] = $this->genererPageWikiCle($nomRetenu); |
$this->indexFinal[$nnc] = $infos; |
} |
} |
private function genererNbreTaxons() { |
foreach ($this->indexFinal as $infos) { |
if ($infos['num_tax_sup_coste'] != '') { |
if (isset($this->nbreTaxonInf[$infos['num_tax_sup_coste']])) { |
$this->nbreTaxonInf[$infos['num_tax_sup_coste']] += 1; |
} else { |
$this->nbreTaxonInf[$infos['num_tax_sup_coste']] = 1; |
} |
} |
} |
} |
private function genererPageWikiDsc($infos) { |
$prefixe = $this->genererPrefixePage($infos); |
if ($infos['rang'] == '180') { |
$nomSci = str_replace(' ', '', ucwords(strtolower($infos['nom_coste']))); |
} else { |
$nomSci = str_replace(' ', '', ucwords(strtolower($infos['nom_sci']))); |
} |
$pageWiki = $prefixe.$nomSci; |
return $pageWiki; |
} |
private function genererPageWikiCle($infos) { |
$pageWiki = ''; |
if ($infos['nbre_taxons'] > 1) { |
$prefixe = $this->genererPrefixePage($infos); |
if ($infos['rang'] == '20') { |
$pageWiki = $prefixe.'TabClaEtEmb'; |
} elseif ($infos['rang'] == '40' && ($infos['num_nom_coste'] == 'E2' || $infos['num_nom_coste'] == 'E3')) { |
$pageWiki = $prefixe.'TabFam'; |
} else if ($infos['rang'] == '80') { |
$pageWiki = $prefixe.'TabFam'; |
} else if ($infos['rang'] == '180') { |
$pageWiki = $prefixe.'TabGen'; |
} else if ($infos['rang'] == '220') { |
$pageWiki = $prefixe.'TabSp'; |
} |
} |
return $pageWiki; |
} |
private function genererPrefixePage($infos) { |
$prefixe = ''; |
$num = preg_replace('/^[a-z]*([0-9]+)(?:[.][0-9a-z]|)$/i', '$1', $infos['num_nom_coste']); |
if (preg_match('/^([0-9]+)[.][0-9a-z]$/i', $infos['num_nom_coste'], $match)) { |
$num = sprintf('%04s', $match[1]); |
} else if ($infos['rang'] == 20 ) { |
$num = ''; |
} else if ($infos['rang'] < 80 ) { |
$num = sprintf('%02s', $num); |
} else if ($infos['rang'] < 290 ) { |
$num = sprintf('%03s', $num); |
} else { |
$num = sprintf('%04s', $num); |
} |
$rangsTxt = array('20' => 'Reg', '40' => 'Emb', '80' => 'Cla', '180' => 'Fam', '220' => 'Gen', '290' => 'Esp', '340' => 'Var'); |
$rang = $rangsTxt[$infos['rang']]; |
$prefixe = $rang.$num; |
return $prefixe; |
} |
private function obtenirNbreTaxon($infos) { |
$nbre = ''; |
if (isset($this->nbreTaxonInf[$infos['num_nom_coste']])) { |
$nbre = $this->nbreTaxonInf[$infos['num_nom_coste']]; |
} |
return $nbre; |
} |
private function obtenirNomFichierImg($infos) { |
$img = ''; |
if ($infos['rang'] == '290') { |
$prefixe = preg_replace('/[.][a-z]$/', '', $infos['num_nom_retenu']); |
$img = $prefixe.'.png'; |
} |
return $img; |
} |
private function ajouteurAuteurImage() { |
$this->chargerAuteurImg(); |
foreach ($this->indexFinal as $nnc => $infos) { |
$infos['image_auteur'] = $this->imgIndex[$infos['image']]; |
$this->indexFinal[$nnc] = $infos; |
} |
} |
private function chargerAuteurImg() { |
$imgIndexFichier = $this->dossierBase.self::DOSSIER_V0.'coste_images_auteur_correspondance_bdnff.tsv'; |
$index = $this->outils->transformerTxtTsvEnTableau($imgIndexFichier); |
foreach ($index as $infos) { |
$id = $infos['id_image']; |
$this->imgIndex[$id] = $infos['auteur']; |
} |
} |
private function decomposerNomSci() { |
$majuscule = "[ÆŒA-Z]"; |
$epithete = "[æœïa-z-]+"; |
foreach ($this->indexFinal as $nnc => $infos) { |
$id = $infos['num_nom_coste']; |
$nomSci = $infos['nom_sci']; |
$rang = $infos['rang']; |
if ($rang < 220) { |
$infos['nom_supra_generique'] = $nomSci; |
} else if ($rang == 220) { |
$infos['genre'] = $nomSci; |
} else if ($rang == 290) { |
if (preg_match("/^($majuscule$epithete) ($epithete)$/", $nomSci, $match)) { |
$infos['genre'] = $match[1]; |
$infos['epithete_sp'] = $match[2]; |
} else { |
$this->messages->traiterErreur("Le nom $nomSci ($id) de rang $rang n'est pas standard."); |
} |
} else if ($rang == 340) { |
if (preg_match("/^($majuscule$epithete) ($epithete) (var[.]) ($epithete)$/", $nomSci, $match)) { |
$infos['genre'] = $match[1]; |
$infos['epithete_sp'] = $match[2]; |
$infos['type_epithete'] = $match[3]; |
$infos['epithete_infra_sp'] = $match[4]; |
} else { |
$this->messages->traiterErreur("Le nom $nomSci ($id) de rang $rang n'est pas standard."); |
} |
} |
$this->indexFinal[$nnc] = $infos; |
$this->messages->afficherAvancement("Décomposition des noms scientifiques en cours"); |
} |
echo "\n"; |
} |
private function ajouteurNomSciHtml() { |
foreach ($this->indexFinal as $nnc => $infos) { |
$this->indexFinal[$nnc]['nom_sci_html'] = $this->generateur->genererNomSciHtml($infos); |
$this->messages->afficherAvancement("Création des noms scientifiques HTML en cours"); |
} |
echo "\n"; |
} |
private function insererCorrections() { |
$correctionsFichier = $this->dossierBase.self::DOSSIER_V2.'coste_v2_00_corrections.tsv'; |
$corrections = $this->outils->transformerTxtTsvEnTableau($correctionsFichier); |
foreach ($corrections as $infos) { |
$nnc = $infos['num_nom_coste']; |
$infosACorriger = isset($this->indexFinal[$nnc]) ? $this->indexFinal[$nnc] : array(); |
foreach ($corrections as $champ => $valeur) { |
$infosACorriger[$champ] = $valeur; |
} |
$this->indexFinal[$nnc] = $infosACorriger; |
} |
} |
private function creerFichierCsvIndexFinal() { |
$lignes = array(); |
array_unshift($this->indexFinal, $this->enteteFinal); |
foreach ($this->indexFinal as $infos) { |
$lignes[] = implode("\t", $infos); |
} |
$txt = ''; |
$txt = implode("\n", $lignes); |
$fichierTsvIndexFinal = $this->dossierBase.self::DOSSIER_V2.'coste_v2_00.tsv'; |
file_put_contents($fichierTsvIndexFinal, $txt); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/coste/Versions.php |
---|
New file |
0,0 → 1,71 |
<?php |
class Versions { |
private $conteneur = null; |
private $eflore = null; |
private $bdd = null; |
public function __construct(Conteneur $conteneur) { |
$this->conteneur = $conteneur; |
$this->eflore = $conteneur->getEfloreCommun(); |
$this->bdd = $conteneur->getBdd(); |
} |
public function chargerTous() { |
$this->chargerVersions(); |
} |
public function chargerVersions() { |
$versions = explode(',', Config::get('versions')); |
$versionsDonnees = explode(',', Config::get('versionsDonnees')); |
foreach ($versions as $id => $version) { |
$versionDonnees = $versionsDonnees[$id]; |
$this->chargerStructureSqlVersion($versionDonnees, $version); |
$this->chargerIndexVersion($versionDonnees, $version); |
$this->chargerDumpWikiniVersion($versionDonnees, $version); |
} |
} |
private function chargerStructureSqlVersion($versionDonnees, $version) { |
$fichierSqlTpl = Config::get('chemins.structureSqlVersionTpl'); |
$fichierSql = sprintf($fichierSqlTpl, $versionDonnees, $version); |
$contenuSql = $this->eflore->recupererContenu($fichierSql); |
$this->eflore->executerScriptSql($contenuSql); |
} |
private function chargerIndexVersion($versionDonnees, $version) { |
$fichierTsvTpl = Config::get('chemins.costeTpl'); |
$fichierTsv = sprintf($fichierTsvTpl, $versionDonnees, $version); |
$tableTpl = Config::get('tables.costeTpl'); |
$table = sprintf($tableTpl, $version); |
$requete = "LOAD DATA INFILE '$fichierTsv' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES '; |
$this->bdd->requeter($requete); |
} |
private function chargerDumpWikiniVersion($versionDonnees, $version) { |
$versionMajeure = (int) substr($version, 0, 1); |
if ($versionMajeure < 2) { |
$fichierWikiTpl = Config::get('chemins.costeWikiniTpl'); |
$fichierDump = sprintf($fichierWikiTpl, $versionDonnees, $version); |
$contenuSql = $this->eflore->recupererContenu($fichierDump); |
$this->eflore->executerScriptSql($contenuSql); |
} |
} |
public function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS coste_meta, ". |
" coste_correspondance_bdnff, coste_images_auteur_correspondance_bdnff, ". |
" coste_images_correspondance_bdnff, coste_index, coste_index_general, ". |
" coste_acls, coste_links, coste_pages, coste_referrers, coste_triples, coste_users, ". |
" coste_v1_00, coste_v2_00 "; |
$this->bdd->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/coste/Coste.php |
---|
New file |
0,0 → 1,117 |
<?php |
//declare(encoding='UTF-8'); |
/** |
* Exemple de lancement du script : : |
* /opt/lampp/bin/php cli.php coste -a chargerTous |
* |
* @category php 5.2 |
* @package eFlore/Scripts |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2012, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
class Coste extends EfloreScript { |
public function executer() { |
try { |
$this->initialiserProjet('coste'); |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$version = $this->getClasseVersion(); |
$version->chargerTous(); |
break; |
case 'chargerStructureSql' : |
$version = $this->getClasseVersion(); |
$version->chargerStructureSql(); |
break; |
case 'chargerVersions' : |
$version = $this->getClasseVersion(); |
$version->chargerVersions(); |
break; |
case 'supprimerTous' : |
$version = $this->getClasseVersion(); |
$version->supprimerTous(); |
break; |
case 'creerDscTxt' : |
$description = $this->getClasseDescription(); |
$description->genererDescriptionTxt(); |
break; |
case 'statDscTxt' : |
$description = $this->getClasseDescription(); |
$description->verifierDescriptionTxt(); |
break; |
case 'correspondanceDsc' : |
$description = $this->getClasseDescription(); |
$description->genererCorrespondance(); |
break; |
case 'fusionIndex' : |
$description = $this->getClasseIndex(); |
$description->fusionnerIndex(); |
break; |
case 'uploadFichiersSp' : |
$wiki = $this->getClasseWiki(); |
$wiki->uploaderFichiersSp(); |
break; |
case 'downloadWiki' : |
$wiki = $this->getClasseWiki(); |
$wiki->dowloaderPagesWiki(); |
break; |
case 'uploadTxt' : |
$wiki = $this->getClasseWiki(); |
$wiki->uploaderDansWikiEflore(); |
break; |
case 'uploadIndex' : |
$wiki = $this->getClasseWiki(); |
$wiki->uploaderIndexDansWikiEflore(); |
break; |
case 'chargerTxt' : |
$wiki = $this->getClasseWiki(); |
$wiki->chargerTxtDansWikiEflore(); |
break; |
case 'chargerIndex' : |
$wiki = $this->getClasseWiki(); |
$wiki->chargerIndexDansWikiEflore(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function getClasseVersion() { |
$version = $this->getClasse('Versions'); |
return $version; |
} |
private function getClasseDescription() { |
$description = $this->getClasse('Description'); |
return $description; |
} |
private function getClasseIndex() { |
$index = $this->getClasse('Index'); |
return $index; |
} |
private function getClasseWiki() { |
$wiki = $this->getClasse('Wiki'); |
return $wiki; |
} |
private function getClasse($classeNom) { |
$conteneur = new Conteneur(); |
$conteneur->setParametre('-v', $this->getParametre('-v')); |
$conteneur->setParametre('scriptChemin', $this->getScriptChemin()); |
require_once dirname(__FILE__).'/'.$classeNom.'.php'; |
$objet = new $classeNom($conteneur); |
return $objet; |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/photoflora/photoflora.ini |
---|
New file |
0,0 → 1,13 |
version="1_0" |
dossierTsv = "{ref:dossierDonneesEflore}photoflora/1.0/" |
dossierSql = "{ref:dossierTsv}" |
bdd_nom = "tb_eflore" |
[tables] |
bdtfxMeta = "photoflora_meta" |
[fichiers] |
structureSql = "photoflora_v1_0.sql" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
/tags/v5.7-arrayanal/scripts/modules/photoflora/Photoflora.php |
---|
New file |
0,0 → 1,38 |
<?php |
/** Exemple lancement: |
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php bdnt -a chargerTous |
*/ |
class Photoflora extends EfloreScript { |
public function executer() { |
// Lancement de l'action demandée |
try { |
$this->initialiserProjet('photoflora'); |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerOntologies' : |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS photoflora_meta"; |
$this->getBdd()->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/lion1906/lion1906.ini |
---|
New file |
0,0 → 1,17 |
version="2008" |
dossierTsv = "{ref:dossierDonneesEflore}lion1906/2008-12-17/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
lion1906Meta = "lion1906_meta" |
lion1906 = "lion1906_communes_v{ref:version}" |
[fichiers] |
structureSql = "lion1906.sql" |
lion1906Meta = "lion1906_meta.sql" |
lion1906 = "villes.csv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
lion1906Meta = "{ref:dossierSql}{ref:fichiers.lion1906Meta}" |
lion1906 = "{ref:dossierTsv}{ref:fichiers.lion1906}" |
/tags/v5.7-arrayanal/scripts/modules/lion1906/Lion1906.php |
---|
New file |
0,0 → 1,122 |
<?php |
//declare(encoding='UTF-8'); |
/** |
* Classe permettant de : |
* - convertir la latitude et longitude en degre, et rajouter l'objet point centroide de la commune. |
* - charger la bdd |
* Exemple de lancement du script : : |
* /opt/lampp/bin/php cli.php lion1906 -a chargerTous |
* |
* @category php 5.2 |
* @package eFlore/Scripts |
* @author Mohcen BENMOUNAH <mohcen@tela-botanica.org> |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
class Lion1906 extends EfloreScript { |
public function executer() { |
try { |
$this->initialiserProjet('lion1906'); |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerMetaDonnees(); |
$this->chargerLion1906(); |
$this->preparerTable(); |
$this->convertirRadianEnDegre(); |
break; |
case 'convertir' : |
$this->preparerTable(); |
$this->convertirRadianEnDegre(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
protected function chargerMetaDonnees() { |
$contenuSql = $this->recupererContenu(Config::get('chemins.lion1906Meta')); |
$this->executerScripSql($contenuSql); |
} |
private function chargerLion1906() { |
$chemin = Config::get('chemins.lion1906'); |
$table = Config::get('tables.lion1906'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET latin1 '. |
'FIELDS '. |
" TERMINATED BY ';' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function convertirRadianEnDegre() { |
$table = Config::get('tables.lion1906'); |
$requete = 'SELECT insee, latitude_radian, longitude_radian '. |
"FROM $table "; |
$LatLons = $this->getBdd()->recupererTous($requete); |
foreach ($LatLons as $LatLon) { |
$insee = $LatLon['insee'] ; |
$latitude_degre = $LatLon['latitude_radian'] * 180 / pi(); |
$longitude_degre = $LatLon['longitude_radian'] * 180 / pi(); |
$latitude_degre = str_replace(',', '.', $latitude_degre); |
$longitude_degre = str_replace(',', '.', $longitude_degre); |
$this->formerPointCentre($latitude_degre, $longitude_degre, $insee); |
$this->afficherAvancement('Analyse des communes Lion1906'); |
} |
} |
private function preparerTable() { |
$table = Config::get('tables.lion1906'); |
$requete = "ALTER TABLE $table ". |
'DROP latitude_degre, '. |
'DROP longitude_degre, '. |
'DROP centroide, '. |
'DROP INDEX insee '; |
$this->getBdd()->requeter($requete); |
$requete = "ALTER TABLE $table ". |
' ADD latitude_degre double NOT NULL , '. |
' ADD longitude_degre double NOT NULL , '. |
' ADD centroide point NOT NULL '; |
$this->getBdd()->requeter($requete); |
$requete = "ALTER TABLE $table ". |
'ADD INDEX insee (insee, latitude_degre, longitude_degre, centroide) '; |
$this->getBdd()->requeter($requete); |
} |
private function formerPointCentre($latitude_degre, $longitude_degre, $insee) { |
$centre = "$latitude_degre $longitude_degre" ; |
$table = Config::get('tables.lion1906'); |
$requete = "UPDATE $table ". |
"SET latitude_degre = '$latitude_degre', longitude_degre = '$longitude_degre', ". |
" centroide = POINTFROMTEXT('POINT($centre)') ". |
"WHERE insee = '$insee' "; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS lion1906_meta, lion1906_communes_v2008"; |
$this->getBdd()->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/nva/Nva.php |
---|
New file |
0,0 → 1,97 |
<?php |
/** Corriger les codes langues pays genre et nombre à la main |
* Exemple lancement: |
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php nva -a chargerTous |
*/ |
class Nva extends EfloreScript { |
public function executer() { |
// Lancement de l'action demandée |
try { |
$this->initialiserProjet('nva'); |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerDonnees(Config::get('chemins.nva'), Config::get('tables.nva')); |
$this->chargerDonnees(Config::get('chemins.index'), Config::get('tables.index')); |
$this->ajouterChampNomVernaIndex(); |
$this->chargerDonnees(Config::get('chemins.ontologies'), Config::get('tables.ontologies')); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerDonnees' : |
$this->chargerDonnees(); |
break; |
case 'ajouterChampNomVernaIndex' : |
$this->ajouterChampNomVernaIndex(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function chargerDonnees($chemin, $table) { |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function ajouterChampNomVernaIndex() { |
$this->preparerTablePrChpNomVerna(); |
$this->remplirChpNomVerna(); |
} |
private function preparerTablePrChpNomVerna() { |
$table = Config::get('tables.index'); |
$requete = "SHOW COLUMNS FROM $table LIKE 'nom_vernaculaire' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE $table ". |
'ADD `nom_vernaculaire` VARCHAR( 40 ) NOT NULL , |
ADD `code_langue` VARCHAR( 10 ) NOT NULL , |
ADD `num_genre` INT( 1 ), ADD `num_nombre` INT( 1 ) '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function remplirChpNomVerna() { |
$table = Config::get('tables.index'); |
$requete = "UPDATE `nva_index_v2_03` |
SET nom_vernaculaire=(select n.nom_vernaculaire from nva_v2_03 n where n.num_nom_vernaculaire=nva_index_v2_03.num_nom_vernaculaire), |
code_langue=(select n.code_langue from nva_v2_03 n where n.num_nom_vernaculaire=nva_index_v2_03.num_nom_vernaculaire), |
num_genre=(select n.num_genre from nva_v2_03 n where n.num_nom_vernaculaire=nva_index_v2_03.num_nom_vernaculaire), |
num_nombre=(select n.num_nombre from nva_v2_03 n where n.num_nom_vernaculaire=nva_index_v2_03.num_nom_vernaculaire)"; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
throw new Exception("Erreur d'update d'ajouts des noms"); |
} |
$this->afficherAvancement("Ajout des noms vernaculaires à l'index"); |
echo "\n"; |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS ".Config::get('tables.nva').", ".Config::get('tables.index'). |
", ".Config::get('tables.ontologies').", nva_meta "; |
$this->getBdd()->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/nva/nva.ini |
---|
New file |
0,0 → 1,21 |
version="2_03" |
dossierTsv = "{ref:dossierDonneesEflore}nva/{ref:version}/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
nva = "nva_v{ref:version}" |
index = "nva_index_v{ref:version}" |
ontologies = "nva_ontologies" |
bdtxa = "bdtxa_v1_00" |
[fichiers] |
structureSql = "nva_v{ref:version}.sql" |
nva = "nva_v{ref:version}.tsv" |
index = "index_v{ref:version}.tsv" |
ontologies = "nva_ontologies.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
nva = "{ref:dossierTsv}{ref:fichiers.nva}" |
index = "{ref:dossierTsv}{ref:fichiers.index}" |
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}" |
/tags/v5.7-arrayanal/scripts/modules/nvps/nvps.ini |
---|
New file |
0,0 → 1,14 |
version = "2012" |
dossierTsv = "{ref:dossierDonneesEflore}nvps/2012/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
nvps = "nvps_v{ref:version}" |
[fichiers] |
structureSql = "nvps_v{ref:version}.sql" |
nvps = "{ref:tables.nvps}.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
nvps = "{ref:dossierTsv}{ref:fichiers.nvps}" |
/tags/v5.7-arrayanal/scripts/modules/nvps/Nvps.php |
---|
New file |
0,0 → 1,124 |
<?php |
/** Exemple lancement: |
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php nvps |
* -a chargerTous |
* Options : |
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes). |
*/ |
class Nvps extends EfloreScript { |
private $nomsIndex = array(); |
private $numeroIndex = 1; |
protected $parametres_autorises = array( |
'-t' => array(false, false, 'Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).')); |
public function executer() { |
// Lancement de l'action demandée |
try { |
$this->initialiserProjet('nvps'); |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerNvps(); |
break; |
case 'chargerStructure' : |
$this->chargerStructureSql(); |
break; |
case 'chargerNvps' : |
$this->chargerNvps(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
/** |
* Charge le fichier en créant un id pour chaque nom vernaculaire. |
*/ |
private function chargerNvps() { |
//Debug::printr(Config::get('fichiers')); |
$fichierOuvert = $this->ouvrirFichier(Config::get('chemins.nvps')); |
$donnees = $this->analyserFichier($fichierOuvert); |
fclose($fichierOuvert); |
foreach ($donnees as $donnee) { |
$table = Config::get('tables.nvps'); |
$fields = implode(', ', array_keys($donnee)); |
$values = implode(', ', $donnee); |
$requete = "INSERT INTO $table ($fields) VALUES ($values) "; |
$this->getBdd()->requeter($requete); |
$this->afficherAvancement("Insertion des noms vernaculaires dans la base de données"); |
if ($this->stopperLaBoucle($this->getParametre('t'))) { |
break; |
} |
} |
echo "\n"; |
} |
private function ouvrirFichier($chemin) { |
$fichierOuvert = false; |
if ($chemin) { |
if (file_exists($chemin) === true) { |
$fichierOuvert = fopen($chemin, 'r'); |
if ($fichierOuvert == false) { |
throw new Exception("Le fichier $chemin n'a pas pu être ouvert."); |
} |
} else { |
throw new Exception("Le fichier $chemin est introuvable."); |
} |
} else { |
throw new Exception("Aucun chemin de fichier n'a été fourni."); |
} |
return $fichierOuvert; |
} |
private function analyserFichier($fichierOuvert) { |
$entetesCsv = explode("\t", trim(fgets($fichierOuvert))); |
$donnees = array(); |
while ($ligneCsv = fgets($fichierOuvert)) { |
$champs = explode("\t", trim($ligneCsv)); |
if (count($champs) > 0) { |
$infos = array(); |
foreach ($entetesCsv as $ordre => $champNom) { |
$valeur = isset($champs[$ordre]) ? $champs[$ordre] : ''; |
$infos[$champNom] = $valeur; |
} |
$infos['id'] = $this->getIndexNomVernaculaire($infos['nom_vernaculaire']); |
$donnees[] = $this->getBdd()->protegerTableau($infos); |
} |
$this->afficherAvancement("Analyse du fichier des noms vernaculaires"); |
if ($this->stopperLaBoucle()) { |
break; |
} |
} |
echo "\n"; |
return $donnees; |
} |
private function getIndexNomVernaculaire($nomVernaculaire) { |
$indexCourrant = null; |
if (array_key_exists($nomVernaculaire, $this->nomsIndex) == false) { |
$this->nomsIndex[$nomVernaculaire] = $this->numeroIndex++; |
} |
$indexCourrant = $this->nomsIndex[$nomVernaculaire]; |
return $indexCourrant; |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS nvps_meta, nvps_v2007, nvps_v2012"; |
$this->getBdd()->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/iso_3166_1/Iso31661.php |
---|
New file |
0,0 → 1,82 |
<?php |
/** Exemple lancement: |
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php iso6391 |
* -a chargerTous |
* Options : |
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes). |
*/ |
class Iso31661 extends EfloreScript { |
public function executer() { |
// Lancement de l'action demandée |
try { |
$this->initialiserProjet('iso-3166-1'); |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerIso31661(); |
$this->chargerOntologies(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerIso31661' : |
$this->chargerIso31661(); |
break; |
case 'chargerOntologies' : |
$this->chargerOntologies(); |
break; |
case 'test' : |
$this->tester(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd)); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function tester() { |
echo Config::get('test'); |
} |
private function chargerIso31661() { |
$chemin = Config::get('chemins.iso31661'); |
$table = Config::get('tables.iso31661'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '\"' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function chargerOntologies() { |
$chemin = Config::get('chemins.ontologies'); |
$table = Config::get('tables.ontologies'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '\"' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS iso_3166_1_meta, iso_3166_1_ontologies_v2006, iso_3166_1_v2006"; |
$this->getBdd()->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/iso_3166_1/iso-3166-1.ini |
---|
New file |
0,0 → 1,18 |
version="2006" |
dossierTsv = "{ref:dossierDonneesEflore}iso-3166-1/{ref:version}/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
iso31661 = "iso_3166_1_v{ref:version}" |
ontologies = "iso_3166_1_ontologies_v{ref:version}" |
[fichiers] |
structureSql = "iso-3166-1_v{ref:version}.sql" |
iso31661 = "iso-3166-1_v{ref:version}.tsv" |
ontologies = "iso-3166-1_ontologies_v{ref:version}.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
iso31661 = "{ref:dossierTsv}{ref:fichiers.iso31661}" |
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}" |
/tags/v5.7-arrayanal/scripts/modules/iso_3166_1 |
---|
New file |
Property changes: |
Added: svn:ignore |
+iso-3166-1.ini |
/tags/v5.7-arrayanal/scripts/modules/tapirlink/tapirlink.ini |
---|
New file |
0,0 → 1,15 |
version="1_00" |
dossierTsv = "{ref:dossierDonneesEflore}tapirlink/2012-01-30/" |
dossierSql = "{ref:dossierTsv}" |
bdd_nom = "tb_hit_indexation" |
[tables] |
enr = raw_occurrence_record |
[fichiers] |
structureSql = "raw_occurrence_record_v{ref:version}.sql" |
enr = "{ref:tables.enr}.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
enr = "{ref:dossierTsv}{ref:fichiers.enr}" |
/tags/v5.7-arrayanal/scripts/modules/tapirlink/Tapirlink.php |
---|
New file |
0,0 → 1,93 |
<?php |
//declare(encoding='UTF-8'); |
/** |
* Exemple de lancement du script : : |
* /opt/lampp/bin/php cli.php cel -a chargerTous |
* |
* @category php 5.2 |
* @package eFlore/Scripts |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
class Tapirlink extends EfloreScript { |
public function executer() { |
try { |
$this->initialiserProjet('tapirlink'); |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerTapirlink(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
protected function initialiserProjet($projet) { |
$bases = $this->getListeBases(); |
parent::initialiserProjet($projet); |
$this->verifierPresenceBdd($bases); |
} |
private function getListeBases() { |
$requete = "SHOW DATABASES"; |
$bases = $this->getBdd()->recupererTous($requete); |
return $bases; |
} |
private function verifierPresenceBdd($bases) { |
$bddNom = Config::get('bdd_nom'); |
$existe = false; |
foreach ($bases as $base) { |
if ($base['Database'] == $bddNom) { |
$existe = true; |
break; |
} |
} |
if ($existe === false) { |
$message = "Veuillez créer la base de données '$bddNom'."; |
throw new Exception($message); |
} |
} |
private function chargerTapirlink() { |
$tablesCodes = array_keys(Config::get('tables')); |
foreach ($tablesCodes as $code) { |
echo "Chargement de la table : $code\n"; |
$this->chargerFichierTsvDansTable($code); |
} |
} |
private function chargerFichierTsvDansTable($code) { |
$chemin = Config::get('chemins.'.$code); |
$table = Config::get('tables.'.$code); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS raw_occurrence_record "; |
$this->getBdd()->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/tapirlink/A_LIRE.txt |
---|
New file |
0,0 → 1,0 |
Créer une base de données tb_hit_indexation avant de lancer les scripts |
Property changes: |
Added: svn:eol-style |
+native |
\ No newline at end of property |
/tags/v5.7-arrayanal/scripts/modules/baseflor/BaseflorIndex.php |
---|
New file |
0,0 → 1,83 |
<?php |
/** |
* |
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org> |
* |
* |
*/ |
class BaseflorIndex { |
private $conteneur; |
private $efloreCommun; |
private $message; |
private $dossierBase; |
private $valeurs_insertion = array(); |
private $Bdd; |
public function __construct(Conteneur $conteneur, Bdd $Bdd) { |
$this->conteneur = $conteneur; |
$this->Bdd = $Bdd; |
$this->efloreCommun = $conteneur->getEfloreCommun(); |
$this->message = $conteneur->getMessages(); |
$this->dossierBase = dirname(__FILE__).'/'; |
} |
public function insererDonnees(){ |
$this->efloreCommun->chargerFichierSql('chemins.index_sql'); |
$this->recupererDonneesBaseflor(); |
$this->recupererDonneesRangSup(); |
$this->insererDonneesIndex(); |
} |
private function recupererDonneesBaseflor() { |
$table = Config::get('tables.donnees'); |
$requete = "SELECT cle, num_nomen, BDNT FROM $table WHERE num_nomen != 0 ". |
" AND num_nomen != 0 ". |
" AND !(ve_lumiere = '' and ve_mat_org_sol = '' and ve_temperature = '' and ve_continentalite = '' ". |
" and ve_humidite_atmos = '' and ve_humidite_edaph = '' and ve_nutriments_sol = '' and ve_salinite = ''". |
" and ve_texture_sol = '' and ve_reaction_sol = '')"; |
$resultat = $this->Bdd->recupererTous($requete); |
$this->valeurs_insertion['baseflor'] = $resultat; |
$this->valeurs_insertion['rangSup'] = $resultat; |
} |
private function recupererDonneesRangSup() { |
$table = Config::get('tables.rang_sup'); |
$requete = "SELECT cle, num_nomen, bdnt FROM $table ;"; |
$resultat = $this->Bdd->recupererTous($requete); |
$this->valeurs_insertion['rangSup']= $resultat; |
} |
private function insererDonneesIndex() { |
$table = Config::get('tables.index'); |
$requete_truncate = 'TRUNCATE TABLE '.$table; |
$this->Bdd->requeter($requete_truncate); |
$i = 0; |
foreach ($this->valeurs_insertion as $tab => $res){ |
if ($tab == 'baseflor') { |
foreach ($res as $valeurs ) { |
if ($valeurs['num_nomen'] != 0) { |
$requete = "INSERT INTO $table VALUES({$i},{$valeurs['cle']},null,'".strtolower($valeurs['BDNT']).".nn:{$valeurs['num_nomen']}')"; |
$this->Bdd->requeter($requete); |
$i++; |
$this->message->afficherAvancement('Insertion des valeurs issues de baseflor en cours'); |
} |
} |
} else { |
foreach ($res as $valeurs ) { |
if ($valeurs['num_nomen'] != 0) { |
$requete = "INSERT INTO $table VALUES({$i},null,{$valeurs['cle']},'{$valeurs['bdnt']}.nn:{$valeurs['num_nomen']}')"; |
$this->Bdd->requeter($requete); |
$i++; |
$this->message->afficherAvancement('Insertion des valeurs issues des rangs supérieurs en cours'); |
} |
} |
} |
} |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/baseflor/baseflor.ini |
---|
New file |
0,0 → 1,52 |
version="2014_01_06" |
dossierTsv = "{ref:dossierDonneesEflore}baseflor/2014-01-06/" |
dossierSql = "{ref:dossierTsv}" |
dossierRangSup = "{ref:dossierDonneesEflore}baseflor/2014-01-06/rang_sup/" |
dossierIndex = "{ref:dossierDonneesEflore}baseflor/2014-01-06/index/" |
[tables] |
donnees = "baseflor_v{ref:version}" |
ontologies = "baseflor_ontologies" |
metadonnees = "baseflor_meta" |
rang_sup = "baseflor_rang_sup_ecologie_v{ref:version}" |
taxons = "bdtfx_v2_00"; |
index = "baseflor_index_v{ref:version}"; |
[fichiers] |
structureSql = "baseflor.sql" |
metadonnees = "insertion_baseflor_meta.sql" |
donnees = "baseflor_v{ref:version}.tsv" |
donnees_verif = "baseflor_verif.txt" |
ontologies = "baseflor_ontologies.tsv" |
rang_sup_sql = "baseflor_rang_sup_ecologie.sql" |
index_sql = "baseflor_index.sql" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
donnees = "{ref:dossierTsv}{ref:fichiers.donnees}" |
donnees_verif = "{ref:dossierTsv}{ref:fichiers.donnees_verif}" |
ontologies ="{ref:dossierTsv}{ref:fichiers.ontologies}" |
metadonnees = "{ref:dossierSql}{ref:fichiers.metadonnees}" |
rang_sup_sql = "{ref:dossierRangSup}{ref:fichiers.rang_sup_sql}" |
index_sql = "{ref:dossierIndex}{ref:fichiers.index_sql}" |
[services] |
url_base="http://localhost/" |
url_service_base="{ref:url_base}service:eflore:0.1/" |
[Parametres] |
typesBio = "A,a,B,b,C,c,Cfru,cfru,Csuf,csuf,Ccou,ccou,H,h,Heri,heri,Hsto,hsto,Hces,hces,Hros,hros,Hrub,hrub,Hbis,hbis,G,g,Gbul,gbul,Gtub,gtub,Grhi,grhi,T,t,Tver,tver,Test,test" |
sousTypesBio = "aqua,lia,épi,hpar,par,suc,semp,cad,car" |
signesSeuls = "?, x, x~, x=, xb, xB, -" |
signesNonSeuls = "~, =, b, B" |
intervalles = "1-9 = 23;24;25;26;28;29;31;32;33;34;35;37;38, |
1-12 = 27;36, |
0-9 = 30;39" |
motifs = "/(^[0-9]*\/)|(inconnu)/ = 1, |
/(^[AB]?[0-9]+$)|(^nc$)/ = 2;3, |
/[^0-9]+/ = 4;5;6;7;8;9;10;11;12;13;16;19;20;21;22;40;41;42;43;44;45;46;47;48;49;50;51;52;53;54;55, |
/^([1-9]|1[0-2])(\-([1-9]|1[0-2]))*$/ = 14" |
champsEcologiques = "ve_lumiere,ve_temperature,ve_continentalite,ve_humidite_atmos,ve_humidite_edaph,ve_reaction_sol,ve_nutriments_sol,ve_salinite,ve_texture_sol,ve_mat_org_sol" |
/tags/v5.7-arrayanal/scripts/modules/baseflor/BaseflorRangSupInsertion.php |
---|
New file |
0,0 → 1,272 |
<?php |
/** |
* |
* |
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org> |
* |
* |
*/ |
class BaseflorRangSupInsertion { |
private $table = null; |
private $donnees_initiales = array(); |
private $valeurs_insertion; |
private $infos_taxon = array(); |
private $conteneur; |
private $efloreCommun; |
private $message; |
private $outils; |
private $nn_courant; |
private $nn_superieur; |
private $champs_ecologiques = array(); |
private $Bdd; |
public function __construct(Conteneur $conteneur, Bdd $bdd) { |
$this->conteneur = $conteneur; |
$this->Bdd = $bdd; |
$this->efloreCommun = $conteneur->getEfloreCommun(); |
$this->message = $conteneur->getMessages(); |
$this->outils = $conteneur->getOutils(); |
$this->dossierBase = dirname(__FILE__).'/'; |
} |
public function insererDonnees(){ |
echo "Chargement de la structure en cours \n" ; |
$this->efloreCommun->chargerFichierSql('chemins.rang_sup_sql'); |
echo "Récupération des données de baseflor en cours \n"; |
$this->recupererDonneesInitiales(); |
echo "Calcul des valeurs pour les rangs supérieurs en cours \n"; |
$this->consulterInfosTaxons(); |
$this->recupererValeursInsertion(); |
$this->insererDonneesRangSup(); |
} |
private function insererDonneesRangSup() { |
$table = Config::get('tables.rang_sup'); |
$requete_truncate = 'TRUNCATE TABLE '.$table; |
$this->Bdd->requeter($requete_truncate); |
$i = 0; |
foreach ($this->valeurs_insertion as $nn => $valeurs){ |
$requete = "INSERT INTO $table VALUES({$i},$nn, 'bdtfx', '{$valeurs['ve_lumiere']['min']}', ". |
"'{$valeurs['ve_lumiere']['max']}','{$valeurs['ve_temperature']['min']}',". |
"'{$valeurs['ve_temperature']['max']}','{$valeurs['ve_continentalite']['min']}',". |
"'{$valeurs['ve_continentalite']['max']}','{$valeurs['ve_humidite_atmos']['min']}',". |
"'{$valeurs['ve_humidite_atmos']['max']}','{$valeurs['ve_humidite_edaph']['min']}',". |
"'{$valeurs['ve_humidite_edaph']['max']}','{$valeurs['ve_reaction_sol']['min']}',". |
"'{$valeurs['ve_reaction_sol']['max']}','{$valeurs['ve_nutriments_sol']['min']}',". |
"'{$valeurs['ve_nutriments_sol']['max']}','{$valeurs['ve_salinite']['min']}',". |
"'{$valeurs['ve_salinite']['max']}','{$valeurs['ve_texture_sol']['min']}',". |
"'{$valeurs['ve_texture_sol']['max']}','{$valeurs['ve_mat_org_sol']['min']}',". |
"'{$valeurs['ve_mat_org_sol']['max']}');"; |
$this->Bdd->requeter($requete); |
$i++; |
$this->message->afficherAvancement('Insertion des valeurs pour les rangs supérieurs en cours'); |
} |
} |
// dans cette solution je parcours les donnees de baseflor |
// je teste une donnée (si min max) pour récuperer les valeurs pour chaque rang superieur |
// jusqu'à famille (180) puis je passe à la suivante jusqu'à avoir parcouru tout baseflor |
private function recupererValeursInsertion(){ |
$this->champs_ecologiques = $this->outils->recupererTableauConfig(Config::get('Parametres.champsEcologiques')); |
$this->valeurs_insertion = array(); |
if (empty($this->donnees_initiales)) { |
throw new Exception("Erreur : pas de données à traiter."); |
} else { |
foreach ($this->donnees_initiales as $nn => $ecologie) { |
$this->nn_courant = $nn; |
$this->nn_superieur = isset($this->infos_taxon[$this->nn_courant]) ? $this->infos_taxon[$this->nn_courant]['nn_sup'] : null; |
$rang = isset($this->infos_taxon[$this->nn_superieur]) ? $this->infos_taxon[$this->nn_superieur]['rang'] : 179 ; |
while ($rang >= 180){ |
if (!isset($donnees_initiales[$this->nn_superieur])) { |
foreach ($this->champs_ecologiques as $nom) { |
$this->testerSiMinMax($nom, $ecologie[$nom]); |
} |
} |
$this->nn_superieur = isset($this->infos_taxon[$this->nn_superieur]) ? $this->infos_taxon[$this->nn_superieur]['nn_sup'] : null; |
$rang = !empty($this->nn_superieur) ? $this->infos_taxon[$this->nn_superieur]['rang'] : 179 ; |
} |
} |
} |
} |
// ici je parcours toutes les données de baseflor et je teste et récupère les valeurs pour le rang superieur |
//direct puis je récupère les données obtenues et je recommence jusqu'à que tous les rangs obtenus soient des familles |
private function recupererValeursInsertion2(){ |
$this->champs_ecologiques = $this->outils->recupererTableauConfig(Config::get('Parametres.champsEcologiques')); |
$this->valeurs_insertion = array(); |
if (empty($this->donnees_initiales)) { |
throw new Exception("Erreur : pas de données à traiter."); |
} else { |
$donnees_traitees = $this->donnees_initiales; |
$donnees_deja_traitees = array(); |
$condition_fin = true; |
$tab_num_nom = array_keys($donnees_traitees); |
while (!empty($donnees_traitees)) { |
reset($donnees_traitees); |
$this->nn_courant = array_shift($tab_num_nom); |
$data = array_shift($donnees_traitees); |
if (isset($this->infos_taxon[$this->nn_courant])) { |
$this->nn_superieur = $this->infos_taxon[$this->nn_courant]['nn_sup']; |
if (!isset($donnees_deja_traitees[$this->nn_courant])) { |
if ($this->infos_taxon[$this->nn_superieur]['rang'] >= 180){ |
$condition_fin = false; |
foreach ($this->champs_ecologiques as $nom) { |
$this->testerSiMinMax($nom, $data[$nom]); |
} |
} |
} |
$donnees_deja_traitees[$this->nn_courant] = 1; |
} |
if ($condition_fin == false && empty($donnees_traitees)) { |
$donnees_traitees = $this->valeurs_insertion; |
$tab_num_nom = array_keys($donnees_traitees); |
$condition_fin = true; |
} |
} |
} |
} |
// je stocke des valeurs à insérer sous la forme : $insertion [{nn_tax_sup}][{nom_de_chps}][{max ou min}] = {valeur} |
private function testerSiMinMax($nom, $valeur) { |
$nn = $this->nn_superieur; |
if ( !isset($this->valeurs_insertion[$nn][$nom]['min']) |
|| empty($valeur['min']) |
|| empty($this->valeurs_insertion[$nn][$nom]['min']) |
|| $this->valeurs_insertion[$nn][$nom]['min'] > $valeur['min'] ){ |
$this->valeurs_insertion[$nn][$nom]['min'] = $valeur['min']; |
} |
if ( !isset($this->valeurs_insertion[$nn][$nom]['max']) |
|| empty($this->valeurs_insertion[$nn][$nom]['max']) |
|| empty($valeur['max']) |
|| $this->valeurs_insertion[$nn][$nom]['max'] < $valeur['max'] ) { |
$this->valeurs_insertion[$nn][$nom]['max'] = $valeur['max']; |
} |
} |
// je stocke les infos taxons sous la forme : $info_taxon[{num_nomem}][{num_nomen_sup ou rang}] = {valeur} |
private function consulterInfosTaxons() { |
$table = Config::get('tables.taxons'); |
$requete = 'SELECT A.num_nom AS nn, B.num_tax_sup AS nn_sup, A.rang '. |
"FROM $table A JOIN $table B ON (A.num_nom_retenu = B.num_nom) ". |
'WHERE B.num_nom = B.num_nom_retenu '; |
$resultat = $this->Bdd->recupererTous($requete); |
foreach ($resultat as $res) { |
$this->infos_taxon[$res['nn']] = array('nn_sup' => $res['nn_sup'], 'rang' => $res['rang'] ); |
} |
} |
// je stocke les valeurs initiales sous la forme : $initiales[{nn_nomem}][{champs ecologique}][{'min' ou 'max'}] |
private function recupererDonneesInitiales() { |
$table = Config::get('tables.donnees'); |
$requete = "SELECT num_nomen, ve_lumiere, ve_temperature, ve_continentalite, ve_humidite_atmos, ". |
"ve_humidite_edaph, ve_reaction_sol, ve_nutriments_sol, ve_salinite, ve_texture_sol, ve_mat_org_sol ". |
"FROM $table WHERE BDNT = 'BDTFX' ". |
" AND num_nomen != 0 ". |
" AND !(ve_lumiere = '' and ve_mat_org_sol = '' and ve_temperature = '' and ve_continentalite = '' ". |
" and ve_humidite_atmos = '' and ve_humidite_edaph = '' and ve_nutriments_sol = '' and ve_salinite = ''". |
" and ve_texture_sol = '' and ve_reaction_sol = '')"; |
$resultat = $this->Bdd->recupererTous($requete); |
foreach ($resultat as $res) { |
$this->donnees_initiales[$res['num_nomen']] = array( |
've_lumiere' => array('min' => $res['ve_lumiere'], 'max' => $res['ve_lumiere']), |
've_temperature' => array('min' => $res['ve_temperature'], 'max' => $res['ve_temperature']), |
've_continentalite' => array('min' => $res['ve_continentalite'], 'max' => $res['ve_continentalite']), |
've_humidite_atmos' => array('min' => $res['ve_humidite_atmos'], 'max' => $res['ve_humidite_atmos']), |
've_humidite_edaph' => array('min' => $res['ve_humidite_edaph'], 'max' => $res['ve_humidite_edaph']), |
've_reaction_sol' => array('min' => $res['ve_reaction_sol'], 'max' => $res['ve_reaction_sol']), |
've_nutriments_sol' => array('min' => $res['ve_nutriments_sol'], 'max' => $res['ve_nutriments_sol']), |
've_salinite' => array('min' => $res['ve_salinite'], 'max' => $res['ve_salinite']), |
've_texture_sol' => array('min' => $res['ve_texture_sol'], 'max' => $res['ve_texture_sol']), |
've_mat_org_sol' => array('min' => $res['ve_mat_org_sol'], 'max' => $res['ve_mat_org_sol'])); |
} |
} |
// +++ Fonctions de vérification des donnée obtenues ++++// |
public function testAscendantsDeBaseflor(){ |
$this->recupererDonneesInitiales(); |
$this->consulterInfosTaxons(); |
$fichier = dirname(__FILE__).'/log/verifTaxonsSup.log'; |
$liste = array(); |
foreach ($this->donnees_initiales as $nn => $data) { |
$nn_sup = isset($this->infos_taxon[$nn]) ? $this->infos_taxon[$nn]['nn_sup'] : '' ; |
if (!empty($nn_sup) && !isset($donnees_initiales[$nn_sup])){ |
$rang = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['rang'] : 179 ; |
while ($rang >= 180) { |
if (!empty($nn_sup)) { |
if (isset($liste["$nn_sup($rang)"])){ |
$liste["$nn_sup($rang)"] .= ", $nn"; |
}else { |
$liste["$nn_sup($rang)"] = "$nn"; |
} |
$nn_sup = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['nn_sup'] : '' ; |
$rang = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['rang'] : 179 ; |
}else { |
break; |
} |
} |
} |
} |
$log = "un ascendant (pas forcement l'ascendant directement au dessus) : les descendants contenus dans baseflor \n"; |
foreach ($liste as $cle => $inferieur){ |
$log .= "$cle : $inferieur \n"; |
} |
file_put_contents($fichier, $log); |
} |
public function testEcologieAscendantsDeBaseflor(){ |
$this->recupererDonneesInitiales(); |
$this->consulterInfosTaxons(); |
$fichier = dirname(__FILE__).'/log/verifTaxonsSupEcolo.log'; |
$liste = array(); |
foreach ($this->donnees_initiales as $nn => $data) { |
$nn_sup = isset($this->infos_taxon[$nn]) ? $this->infos_taxon[$nn]['nn_sup'] : '' ; |
if (!empty($nn_sup) && !isset($donnees_initiales[$nn_sup])){ |
$rang = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['rang'] : 179 ; |
while ($rang >= 180) { |
if (!empty($nn_sup)) { |
$ecolo = array_values($data); |
list($l,$t,$c,$ha,$he,$r,$n,$s,$tx,$mo) = $ecolo; |
if (isset($liste["$nn_sup($rang)"])){ |
$liste["$nn_sup($rang)"] .= ",[{$l['min']}, {$t['min']}, {$c['min']}," |
."{$ha['min']}, {$he['min']}, {$r['min']}, {$n['min']}, {$s['min']}," |
."{$tx['min']}, {$mo['min']}]"; |
}else { |
$liste["$nn_sup($rang)"] = "[{$l['min']}, {$t['min']}, {$c['min']}," |
."{$ha['min']}, {$he['min']}, {$r['min']}, {$n['min']}, {$s['min']}," |
."{$tx['min']}, {$mo['min']}]"; |
} |
$nn_sup = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['nn_sup'] : '' ; |
$rang = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['rang'] : 179 ; |
}else { |
break; |
} |
} |
} |
} |
$log = "nn ascendant (pas forcement l'ascendant directement au dessus) :" |
." valeurs descendants contenus dans baseflor \n" |
."Pour le calcul des valeurs min et max de gauche, les valeurs de droite sont utilisées. \n"; |
foreach ($liste as $cle => $inferieurs){ |
$log .= "$cle : $inferieurs \n"; |
} |
file_put_contents($fichier, $log); |
} |
} |
/tags/v5.7-arrayanal/scripts/modules/baseflor/BaseflorVerif.php |
---|
New file |
0,0 → 1,149 |
<?php |
class BaseflorVerif extends VerificateurDonnees { |
private $type_bio = array(); |
private $ss_type_bio = array(); |
private $signes_seuls = array();// basés sur valeurs trouvées (--> pas de légende !) |
private $signes_nn_seuls = array();// basés sur valeurs trouvées (--> pas de légende !) |
private $intervalles = array(); |
private $motifs = array(); |
//obligatoire |
public function definirTraitementsColonnes() { |
$this->initialiserParametresVerif() ; |
if (( $this->colonne_num > 0 && $this->colonne_num < 15 ) |
|| $this->colonne_num == 16 |
|| ($this->colonne_num > 18 && $this->colonne_num < 23) |
|| $this->colonne_num > 39) { |
$this->verifierColonne(); |
} elseif ($this->colonne_num == 15) { |
$this->verifierTypeBio(); |
} elseif ($this->colonne_num >= 23 && $this->colonne_num <= 32) { |
$this->verifierIntervalles($this->colonne_valeur); |
} elseif ($this->colonne_num >= 33 && $this->colonne_num < 41) { |
$this->verifierValeursIndic(); |
} |
} |
private function initialiserParametresVerif() { |
$this->type_bio = $this->getParametreTableau('Parametres.typesBio'); |
$this->ss_type_bio = $this->getParametreTableau('Parametres.sousTypesBio'); |
$this->signes_seuls = $this->getParametreTableau('Parametres.signesSeuls'); |
$this->signes_nn_seuls = $this->getParametreTableau('Parametres.signesNonSeuls'); |
$this->intervalles = $this->inverserTableau($this->getParametreTableau('Parametres.intervalles')); |
$this->motifs = $this->inverserTableau($this->getParametreTableau('Parametres.motifs')); |
} |
//++---------------------------------traitements des colonnes baseflor------------------------------------++ |
private function verifierColonne(){ |
$motif = $this->motifs[$this->colonne_num]; |
if (preg_match($motif, $this->colonne_valeur) == 0 && $this->verifierSiVide() == false){ |
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur; |
} |
} |
private function verifierSiVide(){ |
$vide = ($this->colonne_valeur == '') ? true : false; |
return $vide; |
} |
private function verifierTypeBio(){ |
if (preg_match("/(.+)\((.+)\)$/", $this->colonne_valeur, $retour) == 1) { |
$this->verifierTypeEtSsType($retour[1]); |
$this->verifierTypeEtSsType($retour[2]); |
} else { |
$this->verifierTypeEtSsType($this->colonne_valeur); |
} |
} |
private function verifierTypeEtSsType($chaine_a_verif){ |
if (preg_match("/^([a-zA-Zé]+)\-(.+)$|^([a-zA-Zé]+[^\-])$/", $chaine_a_verif, $retour) == 1) { |
$type = (isset($retour[3])) ? $retour[3] : $retour[1]; |
$this->verifierType($type); |
$sousType = $retour[2]; |
$this->verifierSousType($sousType); |
} |
} |
private function verifierType($type) { |
if (in_array($type, $this->type_bio) == false) { |
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur; |
} |
} |
private function verifierSousType($sousType) { |
if ($sousType != ''){ |
$ss_type = explode('-', $sousType); |
foreach ($ss_type as $sst) { |
if (in_array($sst, $this->ss_type_bio) == false) { |
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur; |
} |
} |
} |
} |
private function verifierIntervalles($valeur){ |
if ($valeur != '') { |
list($min, $max) = explode('-', $this->intervalles[$this->colonne_num]); |
if ($valeur < $min || $valeur > $max){ |
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur; |
} |
} |
} |
private function verifierValeursIndic(){ |
if (preg_match("/^([^0-9])*([0-9]+)([^0-9])*$/", $this->colonne_valeur, $retour) == 1){ |
$this->verifierIntervalles($retour[2]); |
if (isset($retour[3]) && in_array($retour[3], $this->signes_nn_seuls) == false){ |
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur; |
} |
if ($retour[1] != '-' && $retour[1] != ''){ |
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur; |
} |
} elseif (in_array( $this->colonne_valeur, $this->signes_seuls) == false && $this->verifierSiVide() == false) { |
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur; |
} |
} |
/*--------------------------------------------OUtils-------------------------------------------*/ |
private function getParametreTableau($cle) { |
$tableau = array(); |
$parametre = Config::get($cle); |
if (empty($parametre) === false) { |
$tableauPartiel = explode(',', $parametre); |
$tableauPartiel = array_map('trim', $tableauPartiel); |
foreach ($tableauPartiel as $champ) { |
if (strpos($champ, '=') !== false && strlen($champ) >= 3) { |
list($cle, $val) = explode('=', $champ); |
$tableau[trim($cle)] = trim($val); |
} else { |
$tableau[] = trim($champ); |
} |
} |
} |
return $tableau; |
} |
private function inverserTableau($tableau) { |
$inverse = array(); |
foreach ($tableau as $cle => $valeurs) { |
$valeurs = explode(';', $valeurs); |
foreach ($valeurs as $valeur) { |
$inverse[$valeur] = $cle; |
} |
} |
return $inverse; |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/baseflor/log |
---|
New file |
Property changes: |
Added: svn:ignore |
+test |
/tags/v5.7-arrayanal/scripts/modules/baseflor/Baseflor.php |
---|
New file |
0,0 → 1,313 |
<?php |
/** Exemple lancement: |
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php baseflor -a chargerTous |
*/ |
class Baseflor extends EfloreScript { |
private $table = null; |
public function executer() { |
try { |
$this->initialiserProjet('baseflor'); |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerMetadonnees': |
$this->chargerMetadonnees(); |
break; |
case 'chargerOntologies' : |
$this->chargerOntologies(); |
break; |
case 'verifierFichier' : |
$this->verifierFichier(); |
break; |
case 'chargerDonnees' : |
$this->chargerDonnees(); |
break; |
case 'genererChamps' : |
$this->genererChamps(); |
break; |
case 'chargerTous': |
$this->chargerStructureSql(); |
$this->chargerMetadonnees(); |
$this->chargerOntologies(); |
$this->chargerDonnees(); |
$this->genererChamps(); |
$this->insererDonneesBaseflorRangSupEcolo(); |
$this->insererDonneesIndex(); |
break; |
case 'insererDonneesRangSup' : |
$this->insererDonneesBaseflorRangSupEcolo(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
case 'voirRangSup' : |
$this->voirRangSup(); |
break; |
case 'voirRangSupEcologie' : |
$this->voirRangSupEcologie(); |
break; |
case 'insererDonneesIndex' : |
$this->insererDonneesIndex(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
//-- traitement de la table baseflorRangSupInsertion --// |
private function getClasseBaseflorRangSupInsertion() { |
$conteneur = new Conteneur(); |
require_once dirname(__FILE__)."/BaseflorRangSupInsertion.php"; |
$rangSupInsert = new BaseflorRangSupInsertion($conteneur, $this->getBdd()); |
return $rangSupInsert; |
} |
private function insererDonneesBaseflorRangSupEcolo(){ |
$rangSupInsert = $this->getClasseBaseflorRangSupInsertion(); |
$rangSupInsert->insererDonnees(); |
} |
private function voirRangSup(){ |
$rangSupInsert = $this->getClasseBaseflorRangSupInsertion(); |
$rangSupInsert->testAscendantsDeBaseflor(); |
} |
private function voirRangSupEcologie(){ |
$rangSupInsert = $this->getClasseBaseflorRangSupInsertion(); |
$rangSupInsert->testEcologieAscendantsDeBaseflor(); |
} |
//-- traitement de la table baseflorIndex --// |
private function getClasseBaseflorIndex() { |
$conteneur = new Conteneur(); |
require_once dirname(__FILE__)."/BaseflorIndex.php"; |
$Index = new BaseflorIndex($conteneur, $this->getBdd()); |
return $Index; |
} |
private function insererDonneesIndex(){ |
$Index= $this->getClasseBaseflorIndex(); |
$Index->insererDonnees(); |
} |
//-- traitement de la table generer champs --// |
private function genererChamps(){ |
$this->initialiserGenerationChamps(); |
$this->ajouterChamps(); |
$this->analyserChampsExistant(); |
} |
private function initialiserGenerationChamps() { |
$this->table = Config::get('tables.donnees'); |
} |
private function ajouterChamps() { |
$this->preparerTablePrChpsBDNT(); |
$this->preparerTablePrChpsNumTaxon(); |
$this->preparerTablePrChpsNumNomen(); |
} |
private function preparerTablePrChpsBDNT() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'BDNT' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD BDNT VARCHAR( 6 ) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci '. |
'NOT NULL AFTER catminat_code '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function preparerTablePrChpsNumTaxon() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'num_taxon' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD num_taxon INT( 10 ) NOT NULL '. |
'AFTER catminat_code'; |
$this->getBdd()->requeter($requete); |
} |
} |
private function preparerTablePrChpsNumNomen() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'num_nomen' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD num_nomen INT( 10 ) NOT NULL '. |
'AFTER catminat_code'; |
$this->getBdd()->requeter($requete); |
} |
} |
private function analyserChampsExistant() { |
$resultats = $this->recupererTuplesNumsOriginels(); |
foreach ($resultats as $chps) { |
$cle = $chps['cle']; |
$nno = $chps['num_nomen_originel']; |
$nto = $chps['num_taxon_originel']; |
$valeurs = array(); |
$valeurs["BDNT"] = $this->genererChpsBDNT($nno, $nto); |
$valeurs["num_taxon"] = $this->genererChpsNumTaxon($nto); |
$valeurs["num_nomen"] = $this->genererChpsNumNomen($nno); |
$this->remplirChamps($cle, $valeurs); |
$this->afficherAvancement("Insertion des valeurs dans la base en cours"); |
} |
echo "\n"; |
} |
private function recupererTuplesNumsOriginels(){ |
$requete = "SELECT cle, num_taxon_originel, num_nomen_originel FROM {$this->table} "; |
$resultat = $this->getBdd()->recupererTous($requete); |
return $resultat; |
} |
private function genererChpsBDNT($nno, $nto) { |
$bdnt = ''; |
if (preg_match("/^([AB])[0-9]+$/", $nno, $retour) || preg_match("/^([AB])[0-9]+$/", $nto, $retour)){ |
if ($retour[1]=='A') { |
$bdnt = "BDAFX"; |
} else { |
$bdnt = "BDBFX"; |
} |
} elseif (($nno == 'nc') && ($nto == 'nc')) { |
$bdnt = "nc"; |
} else { |
$bdnt = "BDTFX"; |
} |
return $bdnt; |
} |
private function genererChpsNumTaxon($nto){ |
$num_taxon = ''; |
if (preg_match("/^[AB]([0-9]+)$/", $nto, $retour)) { |
$num_taxon = intval($retour[1]); |
} elseif($nto == 'nc') { |
$num_taxon = 0; |
} else { |
$num_taxon = intval($nto); |
} |
return $num_taxon; |
} |
private function genererChpsNumNomen($nno) { |
$num_nomen = ''; |
if (preg_match("/^[AB]([0-9]+)$/", $nno, $retour)) { |
$num_nomen = intval($retour[1]); |
} elseif ($nno == 'nc') { |
$num_nomen = 0; |
} else { |
$num_nomen = intval($nno); |
} |
return $num_nomen; |
} |
private function remplirChamps($cle, $valeurs) { |
foreach ($valeurs as $nomChamp => $valeurChamp) { |
$valeurChamp = $this->getBdd()->proteger($valeurChamp); |
$requete = "UPDATE {$this->table} SET $nomChamp = $valeurChamp WHERE cle = $cle "; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
throw new Exception("Erreur d'insertion pour le tuple clé = $cle"); |
} |
} |
} |
//+------------------------------------------------------------------------------------------------------+ |
// chargements, suppression, exécution |
protected function chargerMetadonnees() { |
$contenuSql = $this->recupererContenu(Config::get('chemins.metadonnees')); |
$this->executerScriptSql($contenuSql); |
} |
private function chargerOntologies() { |
$chemin = Config::get('chemins.ontologies'); |
$table = Config::get('tables.ontologies'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' " |
; |
$this->getBdd()->requeter($requete); |
} |
protected function chargerStructureSql() { |
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSql')); |
$this->executerScriptSql($contenuSql); |
} |
protected function executerScriptSql($sql) { |
$requetes = Outils::extraireRequetes($sql); |
foreach ($requetes as $requete) { |
$this->getBdd()->requeter($requete); |
} |
} |
private function chargerDonnees() { |
$nb_err = $this->verifierFichier(); |
if ($nb_err > 0) { |
$e = "Je ne peux pas charger les données car le fichier comporte des erreurs.". |
"Voir le fichier baseflor_verif.txt\n"; |
throw new Exception($e); |
} |
$table = Config::get('tables.donnees'); |
$requete = "LOAD DATA INFILE '".Config::get('chemins.donnees')."' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\'"; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
// TODO : rajouter une boucle utilisant un parametre de config stockant toutes les versions pour supprimer les tables |
$requete = "DROP TABLE IF EXISTS baseflor_meta, baseflor_ontologies, ". |
" baseflor_v2012_03_19, ". |
" baseflor_v2012_05_08, baseflor_rang_sup_ecologie_v2012_05_08, baseflor_index_v2012_05_08, ". |
" baseflor_v2012_12_31, baseflor_rang_sup_ecologie_v2012_12_31, baseflor_index_v2012_12_31, ". |
" baseflor_v2013_07_04, baseflor_rang_sup_ecologie_v2013_07_04, baseflor_index_v2013_07_04"; |
$this->getBdd()->requeter($requete); |
} |
//++------------------------------------verifierFichier------------------------------------------++// |
private function getClasseBaseflorVerif() { |
$conteneur = new Conteneur(); |
require_once dirname(__FILE__)."/BaseflorVerif.php"; |
$verif = new BaseflorVerif($conteneur,'baseflor'); |
return $verif; |
} |
private function verifierFichier() { |
$verif = $this->getClasseBaseflorVerif(); |
$nb_erreurs = $verif->verifierFichier(Config::get('chemins.donnees')); |
return $nb_erreurs; |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/isfan/Isfan.php |
---|
New file |
0,0 → 1,391 |
<?php |
//declare(encoding='UTF-8'); |
/** |
* Exemple de lancement du script : : |
* /opt/lampp/bin/php cli.php isfan -a chargerTous |
* |
* @category php 5.2 |
* @package eFlore/Scripts |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2012, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
class Isfan extends EfloreScript { |
private $table = null; |
private $pasInsertion = 1000; |
private $departInsertion = 0; |
protected $parametres_autorises = array( |
'-t' => array(false, false, 'Permet de tester le script sur un jeu réduit de données (indiquer le nombre de lignes).')); |
public function executer() { |
try { |
$this->initialiserProjet('isfan'); |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerisfan(); |
$this->genererChpNumTax(); |
$this->genererChpNomSciHtml(); |
$this->genererChpFamille(); |
$this->genererChpNomComplet(); |
$this->genererChpHierarchie(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerIsfan' : |
$this->chargerIsfan(); |
break; |
case 'genererChpNumTax' : |
$this->genererChpNumTax(); |
break; |
case 'genererChpNomSciHtml' : |
$this->genererChpNomSciHtml(); |
break; |
case 'genererChpNomComplet' : |
$this->initialiserGenerationChamps(); |
$this->genererChpNomComplet(); |
break; |
case 'genererChpFamille' : |
$this->genererChpFamille(); |
break; |
case 'genererChpHierarchie' : |
$this->genererChpHierarchie(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function chargerIsfan() { |
$chemin = Config::get('chemins.bdt'); |
$table = Config::get('tables.isfan'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function genererChpNumTax() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpNumTax(); |
$erreurs = array(); |
$this->departInsertion = 0; |
$dernier_num_tax = 0; |
$requete = 'SELECT num_nom '. |
'FROM '.$this->table.' '. |
'WHERE num_nom = num_nom_retenu AND num_nom_retenu != 0 '. |
'ORDER by num_nom_retenu ASC '; |
$resultat = $this->getBdd()->recupererTous($requete); |
foreach ($resultat as $taxon) { |
$dernier_num_tax++; |
$requete_maj = 'UPDATE '.$this->table.' '. |
'SET num_taxonomique = '.$dernier_num_tax.' '. |
'WHERE num_nom_retenu = '.$taxon['num_nom']; |
$this->getBdd()->requeter($requete_maj); |
$this->pasInsertion++; |
$this->afficherAvancement("Insertion des num tax, ".count($resultat)." num tax a traiter"); |
} |
echo "\n"; |
$this->creerFichierLog('Erreurs lors de la génération des numéros taxonomiques', $erreurs, 'erreurs_num_tax'); |
} |
private function preparerTablePrChpNumTax() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'num_taxonomique' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD num_taxonomique INT( 9 ) '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function genererChpNomSciHtml() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpNomSciHtml(); |
$generateur = new GenerateurNomSciHtml(); |
$nbreTotal = $this->recupererNbTotalTuples(); |
$erreurs = array(); |
$this->departInsertion = 0; |
while ($this->departInsertion < $nbreTotal) { |
$resultat = $this->recupererTuplesPrChpNomSciHtml(); |
try { |
$nomsSciEnHtml = $generateur->generer($resultat); |
} catch (Exception $e) { |
$erreurs[] = $e->getMessage(); |
} |
$this->remplirChpNomSciHtm($nomsSciEnHtml); |
$this->departInsertion += $this->pasInsertion; |
$this->afficherAvancement("Insertion des noms scientifique au format HTML dans la base par paquet de {$this->pasInsertion} en cours"); |
if ($this->stopperLaBoucle($this->getParametre('t'))) break; |
} |
echo "\n"; |
$this->creerFichierLog('Erreurs lors de la génération HTML des noms scientifiques', $erreurs, 'erreurs_noms_sci_html'); |
} |
private function initialiserGenerationChamps() { |
$this->table = Config::get('tables.isfan'); |
} |
private function preparerTablePrChpNomSciHtml() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD nom_sci_html VARCHAR( 500 ) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function recupererNbTotalTuples(){ |
$requete = "SELECT count(*) AS nb FROM {$this->table} "; |
$resultat = $this->getBdd()->recuperer($requete); |
return $resultat['nb']; |
} |
private function recupererTuplesPrChpNomSciHtml() { |
$requete = 'SELECT num_nom, rang, genre, '. |
' epithete_sp, type_epithete, epithete_infra_sp '. |
"FROM {$this->table} ". |
"LIMIT {$this->departInsertion},{$this->pasInsertion} "; |
$resultat = $this->getBdd()->recupererTous($requete); |
return $resultat; |
} |
private function remplirChpNomSciHtm($nomsSciHtm) { |
foreach ($nomsSciHtm as $id => $html) { |
$html = $this->getBdd()->proteger($html); |
$requete = "UPDATE {$this->table} SET nom_sci_html = $html WHERE num_nom = $id "; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
throw new Exception("Erreur d'insertion pour le tuple $id"); |
} |
} |
} |
private function genererChpNomComplet() { |
$this->preparerTablePrChpNomComplet(); |
$this->remplirChpNomComplet(); |
} |
private function preparerTablePrChpNomComplet() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_complet' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD nom_complet VARCHAR( 500 ) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function remplirChpNomComplet() { |
echo "Attribution du champ nom complet au taxons : "; |
$requete = "UPDATE {$this->table} SET nom_complet = CONCAT(nom_sci,' ',auteur)"; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
echo "KO\n"; |
throw new Exception("Erreur de génération du champ nom complet"); |
} else { |
echo "OK\n"; |
} |
} |
private function genererChpFamille() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpFamille(); |
$resultats = $this->recupererTuplesPrChpFamille(); |
$noms = array(); |
$introuvables = array(); |
$introuvablesSyno = array(); |
foreach ($resultats as $id => $nom) { |
$nn = $nom['num_nom']; |
$nnr = $nom['num_nom_retenu']; |
$nts = $nom['num_tax_sup']; |
$rg = $nom['rang']; |
if ($nnr != '') { |
if ($rg == '180') { |
$noms[$nn] = $nom['nom_sci']; |
} else { |
if ($nn == $nnr) {// nom retenu |
if (isset($noms[$nts])) { |
$noms[$nn] = $noms[$nts]; |
} else { |
$introuvables[] = $nn; |
} |
} else {// nom synonyme |
if (isset($noms[$nnr])) { |
$noms[$nn] = $noms[$nnr]; |
} else { |
$introuvablesSyno[] = $nom; |
} |
} |
} |
} |
unset($resultats[$id]); |
$this->afficherAvancement("Attribution de leur famille aux noms en cours"); |
if ($this->stopperLaBoucle($this->getParametre('t'))) break; |
} |
echo "\n"; |
foreach ($introuvablesSyno as $id => $nom) { |
$nn = $nom['num_nom']; |
$nnr = $nom['num_nom_retenu']; |
if (isset($noms[$nnr])) { |
$noms[$nn] = $noms[$nnr]; |
} else { |
$introuvables[] = $nn; |
} |
unset($introuvablesSyno[$id]); |
$this->afficherAvancement("Attribution de leur famille aux synonymes en cours"); |
} |
echo "\n"; |
$msg = 'Plusieurs familles sont introuvables'; |
$this->creerFichierLog($msg, $introuvables, 'famille_introuvable'); |
$this->remplirChpFamille($noms); |
} |
private function preparerTablePrChpFamille() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'famille' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD famille VARCHAR(255) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function recupererTuplesPrChpFamille() { |
$requete = 'SELECT num_nom, num_nom_retenu, num_tax_sup, rang, nom_sci '. |
"FROM {$this->table} ". |
"WHERE rang >= 180 ". |
"ORDER BY rang ASC, num_tax_sup ASC, num_nom_retenu DESC "; |
$resultat = $this->getBdd()->recupererTous($requete); |
return $resultat; |
} |
private function remplirChpFamille($noms) { |
foreach ($noms as $id => $famille) { |
$famille = $this->getBdd()->proteger($famille); |
$requete = "UPDATE {$this->table} SET famille = $famille WHERE num_nom = $id "; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
throw new Exception("Erreur d'insertion pour le tuple $id"); |
} |
$this->afficherAvancement("Insertion des noms de famille dans la base en cours"); |
} |
echo "\n"; |
} |
private function genererChpHierarchie() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpHierarchie(); |
$table = Config::get('tables.isfan'); |
$requete = "UPDATE $table SET hierarchie = NULL "; |
$mise_a_jour = $this->getBdd()->requeter($requete); |
$requete_hierarchie = "SELECT num_nom, num_nom_retenu, num_tax_sup FROM ".$table." ORDER BY rang DESC"; |
$resultat = $this->getBdd()->recupererTous($requete_hierarchie); |
$num_nom_a_num_sup = array(); |
foreach($resultat as &$taxon) { |
$num_nom_a_num_sup[$taxon['num_nom']] = $taxon['num_tax_sup']; |
} |
$chemin_taxo = ""; |
foreach($resultat as &$taxon) { |
$chemin_taxo = $this->traiterHierarchieNumTaxSup($taxon['num_nom_retenu'], $num_nom_a_num_sup).'-'; |
$requete = "UPDATE $table SET hierarchie = ".$this->getBdd()->proteger($chemin_taxo)." WHERE num_nom = ".$taxon['num_nom']." "; |
$mise_a_jour = $this->getBdd()->requeter($requete); |
$this->afficherAvancement("Insertion de la hierarchie taxonomique en cours"); |
} |
echo "\n"; |
} |
private function traiterHierarchieNumTaxSup($num_nom_retenu, &$num_nom_a_num_sup) { |
$chaine_hierarchie = ""; |
if(isset($num_nom_a_num_sup[$num_nom_retenu])) { |
$num_tax_sup = $num_nom_a_num_sup[$num_nom_retenu]; |
$chaine_hierarchie = '-'.$num_tax_sup; |
if($num_tax_sup != 0 && $num_tax_sup != '') { |
$chaine_hierarchie = $this->traiterHierarchieNumTaxSup($num_tax_sup, $num_nom_a_num_sup).$chaine_hierarchie; |
} |
} |
return $chaine_hierarchie; |
} |
private function preparerTablePrChpHierarchie() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'hierarchie' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD hierarchie VARCHAR(1000) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function genererDonneesTestMultiVersion() { |
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSqlTest')); |
$this->executerScripSql($contenuSql); |
$table = Config::get('tables.isfan'); |
$tableTest = Config::get('tables.isfanTest'); |
$requete = "INSERT INTO $tableTest SELECT * FROM $table"; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerDonneesTestMultiVersion() { |
$tableMeta = Config::get('tables.isfanMeta'); |
$requete = "DELETE FROM $tableMeta WHERE guid = 'urn:lsid:tela-botanica.org:isfan:1.00'"; |
$this->getBdd()->requeter($requete); |
$tableTest = Config::get('tables.isfanTest'); |
$requete = "DROP TABLE IF EXISTS $tableTest"; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS isfan_meta, isfan_v0_01, isfan_v1_00"; |
$this->getBdd()->requeter($requete); |
} |
private function creerFichierLog($message, $lignes, $nomFichier) { |
$lignesNbre = count($lignes); |
if ($lignesNbre != 0) { |
echo "$message. Voir le log de $lignesNbre lignes :\n"; |
$logContenu = implode(", \n", $lignes); |
$logFichier = realpath(dirname(__FILE__))."/log/$nomFichier.log"; |
echo $logFichier."\n"; |
file_put_contents($logFichier, $logContenu); |
} |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/isfan/isfan.ini |
---|
New file |
0,0 → 1,18 |
code="isfan" |
version="2013" |
dossierTsv = "{ref:dossierDonneesEflore}{ref:code}/1.00/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
isfanMeta = "isfan_meta" |
isfan = "isfan_v{ref:version}" |
isfanTest = "isfan_v2013" |
[fichiers] |
structureSql = "{ref:code}_v{ref:version}.sql" |
bdt = "{ref:code}_v{ref:version}_ref.txt" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
bdt = "{ref:dossierTsv}{ref:fichiers.bdt}" |
/tags/v5.7-arrayanal/scripts/modules/bdtxa/bdtxa.ini |
---|
New file |
0,0 → 1,18 |
code="bdtxa" |
version="1_00" |
dossierTsv = "{ref:dossierDonneesEflore}{ref:code}/1.00/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
bdtxaMeta = "bdtxa_meta" |
bdtxa = "bdtxa_v{ref:version}" |
bdtxaTest = "bdtxa_v1_00" |
[fichiers] |
structureSql = "{ref:code}_v{ref:version}.sql" |
bdt = "{ref:code}_v{ref:version}_ref.txt" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
bdt = "{ref:dossierTsv}{ref:fichiers.bdt}" |
/tags/v5.7-arrayanal/scripts/modules/bdtxa/Bdtxa.php |
---|
New file |
0,0 → 1,353 |
<?php |
//declare(encoding='UTF-8'); |
/** |
* Exemple de lancement du script : : |
* /opt/lampp/bin/php cli.php bdtxa -a chargerTous |
* |
* @category php 5.2 |
* @package eFlore/Scripts |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2012, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
class Bdtxa extends EfloreScript { |
private $table = null; |
private $pasInsertion = 1000; |
private $departInsertion = 0; |
protected $parametres_autorises = array( |
'-t' => array(false, false, 'Permet de tester le script sur un jeu réduit de données (indiquer le nombre de lignes).')); |
public function executer() { |
try { |
$this->initialiserProjet('bdtxa'); |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerBdtxa(); |
$this->genererChpNomSciHtml(); |
$this->genererChpFamille(); |
$this->genererChpNomComplet(); |
$this->genererChpHierarchie(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerBdtxa' : |
$this->chargerBdtxa(); |
break; |
case 'genererChpNomSciHtml' : |
$this->genererChpNomSciHtml(); |
break; |
case 'genererChpNomComplet' : |
$this->initialiserGenerationChamps(); |
$this->genererChpNomComplet(); |
break; |
case 'genererChpFamille' : |
$this->genererChpFamille(); |
break; |
case 'genererChpHierarchie' : |
$this->genererChpHierarchie(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function chargerBdtxa() { |
$chemin = Config::get('chemins.bdt'); |
$table = Config::get('tables.bdtxa'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function genererChpNomSciHtml() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpNomSciHtml(); |
$generateur = new GenerateurNomSciHtml(); |
$nbreTotal = $this->recupererNbTotalTuples(); |
$erreurs = array(); |
$this->departInsertion = 0; |
while ($this->departInsertion < $nbreTotal) { |
$resultat = $this->recupererTuplesPrChpNomSciHtml(); |
try { |
$nomsSciEnHtml = $generateur->generer($resultat); |
} catch (Exception $e) { |
$erreurs[] = $e->getMessage(); |
} |
$this->remplirChpNomSciHtm($nomsSciEnHtml); |
$this->departInsertion += $this->pasInsertion; |
$this->afficherAvancement("Insertion des noms scientifique au format HTML dans la base par paquet de {$this->pasInsertion} en cours"); |
if ($this->stopperLaBoucle($this->getParametre('t'))) break; |
} |
echo "\n"; |
$this->creerFichierLog('Erreurs lors de la génération HTML des noms scientifiques', $erreurs, 'erreurs_noms_sci_html'); |
} |
private function initialiserGenerationChamps() { |
$this->table = Config::get('tables.bdtxa'); |
echo $this->table; |
} |
private function preparerTablePrChpNomSciHtml() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD nom_sci_html VARCHAR( 500 ) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function recupererNbTotalTuples(){ |
$requete = "SELECT count(*) AS nb FROM {$this->table} "; |
$resultat = $this->getBdd()->recuperer($requete); |
return $resultat['nb']; |
} |
private function recupererTuplesPrChpNomSciHtml() { |
$requete = 'SELECT num_nom, rang, nom_supra_generique, genre, epithete_infra_generique, '. |
' epithete_sp, type_epithete, epithete_infra_sp,cultivar_groupe, '. |
' nom_commercial, cultivar '. |
"FROM {$this->table} ". |
"LIMIT {$this->departInsertion},{$this->pasInsertion} "; |
$resultat = $this->getBdd()->recupererTous($requete); |
return $resultat; |
} |
private function remplirChpNomSciHtm($nomsSciHtm) { |
foreach ($nomsSciHtm as $id => $html) { |
$html = $this->getBdd()->proteger($html); |
$requete = "UPDATE {$this->table} SET nom_sci_html = $html WHERE num_nom = $id "; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
throw new Exception("Erreur d'insertion pour le tuple $id"); |
} |
} |
} |
private function genererChpNomComplet() { |
$this->preparerTablePrChpNomComplet(); |
$this->remplirChpNomComplet(); |
} |
private function preparerTablePrChpNomComplet() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_complet' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD nom_complet VARCHAR( 500 ) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function remplirChpNomComplet() { |
echo "Attribution du champ nom complet au taxons : "; |
$requete = "UPDATE {$this->table} SET nom_complet = CONCAT(nom_sci,' ',auteur)"; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
echo "KO\n"; |
throw new Exception("Erreur de génération du champ nom complet"); |
} else { |
echo "OK\n"; |
} |
} |
private function genererChpFamille() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpFamille(); |
$resultats = $this->recupererTuplesPrChpFamille(); |
$noms = array(); |
$introuvables = array(); |
$introuvablesSyno = array(); |
foreach ($resultats as $id => $nom) { |
$nn = $nom['num_nom']; |
$nnr = $nom['num_nom_retenu']; |
$nts = $nom['num_tax_sup']; |
$rg = $nom['rang']; |
if ($nnr != '') { |
if ($rg == '180') { |
$noms[$nn] = $nom['nom_sci']; |
} else { |
if ($nn == $nnr) {// nom retenu |
if (isset($noms[$nts])) { |
$noms[$nn] = $noms[$nts]; |
} else { |
$introuvables[] = $nn; |
} |
} else {// nom synonyme |
if (isset($noms[$nnr])) { |
$noms[$nn] = $noms[$nnr]; |
} else { |
$introuvablesSyno[] = $nom; |
} |
} |
} |
} |
unset($resultats[$id]); |
$this->afficherAvancement("Attribution de leur famille aux noms en cours"); |
if ($this->stopperLaBoucle($this->getParametre('t'))) break; |
} |
echo "\n"; |
foreach ($introuvablesSyno as $id => $nom) { |
$nn = $nom['num_nom']; |
$nnr = $nom['num_nom_retenu']; |
if (isset($noms[$nnr])) { |
$noms[$nn] = $noms[$nnr]; |
} else { |
$introuvables[] = $nn; |
} |
unset($introuvablesSyno[$id]); |
$this->afficherAvancement("Attribution de leur famille aux synonymes en cours"); |
} |
echo "\n"; |
$msg = 'Plusieurs familles sont introuvables'; |
$this->creerFichierLog($msg, $introuvables, 'famille_introuvable'); |
$this->remplirChpFamille($noms); |
} |
private function preparerTablePrChpFamille() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'famille' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD famille VARCHAR(255) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function recupererTuplesPrChpFamille() { |
$requete = 'SELECT num_nom, num_nom_retenu, num_tax_sup, rang, nom_sci '. |
"FROM {$this->table} ". |
"WHERE rang >= 180 ". |
"ORDER BY rang ASC, num_tax_sup ASC, num_nom_retenu DESC "; |
$resultat = $this->getBdd()->recupererTous($requete); |
return $resultat; |
} |
private function remplirChpFamille($noms) { |
foreach ($noms as $id => $famille) { |
$famille = $this->getBdd()->proteger($famille); |
$requete = "UPDATE {$this->table} SET famille = $famille WHERE num_nom = $id "; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
throw new Exception("Erreur d'insertion pour le tuple $id"); |
} |
$this->afficherAvancement("Insertion des noms de famille dans la base en cours"); |
} |
echo "\n"; |
} |
private function genererChpHierarchie() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpHierarchie(); |
$table = Config::get('tables.bdtxa'); |
$requete = "UPDATE $table SET hierarchie = NULL "; |
$mise_a_jour = $this->getBdd()->requeter($requete); |
$requete_hierarchie = "SELECT num_nom, num_nom_retenu, num_tax_sup FROM ".$table." ORDER BY rang DESC"; |
$resultat = $this->getBdd()->recupererTous($requete_hierarchie); |
$num_nom_a_num_sup = array(); |
foreach($resultat as &$taxon) { |
$num_nom_a_num_sup[$taxon['num_nom']] = $taxon['num_tax_sup']; |
} |
$chemin_taxo = ""; |
foreach($resultat as &$taxon) { |
$chemin_taxo = $this->traiterHierarchieNumTaxSup($taxon['num_nom_retenu'], $num_nom_a_num_sup).'-'; |
$requete = "UPDATE $table SET hierarchie = ".$this->getBdd()->proteger($chemin_taxo)." WHERE num_nom = ".$taxon['num_nom']." "; |
$mise_a_jour = $this->getBdd()->requeter($requete); |
$this->afficherAvancement("Insertion de la hierarchie taxonomique en cours"); |
} |
echo "\n"; |
} |
private function traiterHierarchieNumTaxSup($num_nom_retenu, &$num_nom_a_num_sup) { |
$chaine_hierarchie = ""; |
if(isset($num_nom_a_num_sup[$num_nom_retenu])) { |
$num_tax_sup = $num_nom_a_num_sup[$num_nom_retenu]; |
$chaine_hierarchie = '-'.$num_tax_sup; |
if($num_tax_sup != 0 && $num_tax_sup != '') { |
$chaine_hierarchie = $this->traiterHierarchieNumTaxSup($num_tax_sup, $num_nom_a_num_sup).$chaine_hierarchie; |
} |
} |
return $chaine_hierarchie; |
} |
private function preparerTablePrChpHierarchie() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'hierarchie' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD hierarchie VARCHAR(1000) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function genererDonneesTestMultiVersion() { |
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSqlTest')); |
$this->executerScripSql($contenuSql); |
$table = Config::get('tables.bdtxa'); |
$tableTest = Config::get('tables.bdtxaTest'); |
$requete = "INSERT INTO $tableTest SELECT * FROM $table"; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerDonneesTestMultiVersion() { |
$tableMeta = Config::get('tables.bdtxaMeta'); |
$requete = "DELETE FROM $tableMeta WHERE guid = 'urn:lsid:tela-botanica.org:bdtxa:1.00'"; |
$this->getBdd()->requeter($requete); |
$tableTest = Config::get('tables.bdtxaTest'); |
$requete = "DROP TABLE IF EXISTS $tableTest"; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS bdtxa_meta, bdtxa_v0_01, bdtxa_v1_00"; |
$this->getBdd()->requeter($requete); |
} |
private function creerFichierLog($message, $lignes, $nomFichier) { |
$lignesNbre = count($lignes); |
if ($lignesNbre != 0) { |
echo "$message. Voir le log de $lignesNbre lignes :\n"; |
$logContenu = implode(", \n", $lignes); |
$logFichier = realpath(dirname(__FILE__))."/log/$nomFichier.log"; |
echo $logFichier."\n"; |
file_put_contents($logFichier, $logContenu); |
} |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/sitemap/Sitemap.php |
---|
New file |
0,0 → 1,160 |
<?php |
// Encodage : UTF-8 |
// +-------------------------------------------------------------------------------------------------------------------+ |
/** |
* Sitemap |
* |
* Description : classe permettant de réaliser un fichier Sitemap pour eFlore |
* |
//Auteur original : |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Tela-Botanica 1999-2008 |
* @link http://www.tela-botanica.org/wikini/eflore |
* @licence GPL v3 & CeCILL v2 |
* @version $Id: Sitemap.class.php 1873 2009-03-31 10:07:24Z Jean-Pascal MILCENT $ |
*/ |
// +-------------------------------------------------------------------------------------------------------------------+ |
/** |
* Classe crééant un Sitemap |
*/ |
class Robot extends ScriptCommande { |
private $lastmod = '2008-04-28'; |
private $changefreq = 'monthly'; |
public function executer() { |
$cmd = $this->getParam('a'); |
switch ($cmd) { |
case 'creer' : |
$this->creerSiteMap(); |
break; |
default : |
trigger_error('Erreur : la commande "'.$cmd.'" n\'existe pas!'."\n", E_USER_ERROR); |
} |
} |
private function creerSiteMap() { |
// +-----------------------------------------------------------------------------------------------------------+ |
// Initialisation des paramêtres variables |
$url_site = 'http://www.tela-botanica.org/'; |
$url_eflore = $url_site.'eflore/%s/nt/%s/%s'; |
$projets = array( array('id' => 25, 'code' => 'BDNFF', 'url' => $url_eflore, 'taxon_max' => 50000, 'onglets' => '*'), |
array('id' => 29, 'code' => 'BDNFM', 'url' => $url_eflore, 'taxon_max' => 50000, 'onglets' => 'synthese,synonymie,vernaculaire,chorologie,biblio,information,illustration,wiki'), |
array('id' => 38, 'code' => 'BDNBE', 'url' => $url_eflore, 'taxon_max' => 50000, 'onglets' => 'synthese,synonymie,chorologie,biblio,information,illustration,wiki'), |
array('id' => 45, 'code' => 'BDAFN', 'url' => $url_eflore, 'taxon_max' => 500000, 'onglets' => 'synthese,synonymie,chorologie,biblio,information,illustration,wiki') |
); |
$onglets = array( 'synthese' => '0.9', |
'synonymie' => '0.6', |
'vernaculaire' => '0.8', |
'chorologie' => '0.7', |
'biblio' => '0.8', |
'information' => '0.2', |
'illustration' => '0.9', |
'wiki' => '0.3', |
'cel' => '0.5'); |
$xmlstr_sitemap = '<?xml version="1.0" encoding="UTF-8"?>'."\n". |
'<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '. |
'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 '. |
'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" '. |
'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n". |
'</urlset>'."\n"; |
$xmlstr_sitemapindex = '<?xml version="1.0" encoding="UTF-8"?>'."\n". |
'<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '. |
'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 '. |
'http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" '. |
'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n". |
'</sitemapindex>'."\n"; |
// +-----------------------------------------------------------------------------------------------------------+ |
// Initialisation des variables |
$UrlSet = null; |
$SiteMapIndex = null; |
$cpt_url = 1; |
$cpt_fichier = 1; |
$Taxon = new EfloreTaxon(true); |
// +-----------------------------------------------------------------------------------------------------------+ |
// Lancement du traitement |
foreach ($projets as $projet) { |
// Gestion des onglets affichables pour le projet courrant |
if ($projet['onglets'] != '*') { |
$projet['onglets'] = array_flip(explode(',', $projet['onglets'])); |
} |
// +-------------------------------------------------------------------------------------------------------+ |
echo "Création des URLs des taxons pour le projet {$projet['code']} : "; |
$i = 1; |
$taxons = $Taxon->consulterTaxon($projet['id']); |
foreach ($taxons as $taxon) { |
// Seul les taxons du projet sont indexés, on exclue les taxons virtuels |
if ($taxon['et']['id']['taxon'] < $projet['taxon_max']) { |
foreach ($onglets as $onglet => $priorite) { |
// Vérification que l'onglet est autorisé pour ce projet |
if ($projet['onglets'] == '*' || isset($projet['onglets'][$onglet])) { |
// Affichage en console et en cas de test... |
echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++; |
// Création du fichier XML si nécessaire |
if (is_null($UrlSet)) { |
$UrlSet = new SimpleXMLElement($xmlstr_sitemap); |
} |
// Ajout de l'url |
$Url = $UrlSet->addChild('url'); |
$Url->addChild('loc', sprintf($projet['url'], $projet['code'], $taxon['et']['id']['taxon'], $onglet)); |
$Url->addChild('lastmod', $this->lastmod); |
$Url->addChild('changefreq', $this->changefreq); |
$Url->addChild('priority', $priorite); |
// Vérification écriture du fichier ou pas |
if ($cpt_url == 1) { |
$estimation = strlen($UrlSet->asXml()); |
} |
if (49999 == $cpt_url++ || ($estimation * $cpt_url) > 20000000 || $i == (int)$this->getParam('t')) { |
$contenu = $UrlSet->asXml(); |
$cpt_url = 1; |
$UrlSet = null; |
// Création du fichier Sitemap compressé |
$fichier_nom = 'sitemap'.$cpt_fichier++.'.xml'; |
$compression = false; |
if (!is_numeric($this->getParam('t'))) { |
$compression = true; |
$fichier_nom .= '.gz'; |
} |
$fichier = $this->getIni('log_chemin').$fichier_nom; |
$this->creerFichier($fichier, $contenu, $compression); |
// Création du XML d'index des Sitemap si nécessaire |
if (is_null($SiteMapIndex)) { |
$SiteMapIndex = new SimpleXMLElement($xmlstr_sitemapindex); |
} |
// Ajout du fichier Sitemap à l'index |
$SiteMap = $SiteMapIndex->addChild('sitemap'); |
$SiteMap->addChild('loc', $url_site.$fichier_nom); |
$SiteMap->addChild('lastmod', date('c', time())); |
} |
if ($i == (int)$this->getParam('t')) {break;} |
} |
} |
} |
// En cas de test... |
if ($i == (int)$this->getParam('t')) {break;} |
} |
echo "\n"; |
// Création du fichier d'index des Sitemap |
if (is_object($SiteMapIndex)) { |
$index_contenu = $SiteMapIndex->asXml(); |
$index_fichier_nom = 'sitemap_index.xml'; |
$index_fichier = $this->getIni('log_chemin').$index_fichier_nom; |
$this->creerFichier($index_fichier, $index_contenu); |
} |
} |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/sitemap/sitemap.ini |
---|
New file |
0,0 → 1,2 |
; Encodage : UTF-8 |
; ici mettre les variables du module |
/tags/v5.7-arrayanal/scripts/modules/sophy/Insertionflore.php |
---|
New file |
0,0 → 1,295 |
<?php |
// Encodage : UTF-8 |
// +-------------------------------------------------------------------------------------------------------------------+ |
/** |
* Traitement des fichiers de la banque de données SOPHY pour insertion |
* |
* Description : classe permettant d'insérer les flores nécessaires à l'étude des données issues de SOPHY. |
* Avant d'utiliser cette classe nettoyer les fichiers pour ne garder que les lignes à insérer. |
* Utilisation : php script.php insertionFlore -a test |
* |
* @category PHP 5.3 |
* @package phytosocio |
//Auteur original : |
* @author Delphine CAUQUIL <delphine@tela-botanica.org> |
* @copyright Copyright (c) 2009, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL-v3 |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2 |
* @version $Id$ |
*/ |
// +-------------------------------------------------------------------------------------------------------------------+ |
class Insertionflore extends Script { |
protected $dao; |
protected $dossier; |
protected $flore; |
protected $parametres_autorises = array( |
'-n' => array(true, true, 'Nom du fichier ou du dossier à traiter')); |
public function executer() { |
include_once dirname(__FILE__).'/bibliotheque/FloreDao.php'; |
Config::charger(dirname(__FILE__).'/sophy.ini'); |
$this->dossier = Config::get('dossierDonneesSophy').'FLORE/'; |
$this->dao = new FloreDao(); |
// Récupération de paramètres |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'florenbi' : // fournier |
$this->executerFlorenbi(); |
break; |
case 'bdnff' : // bdnff |
$this->executerBdnff(); |
break; |
case 'listepla' : // fournier/bdnff |
$this->executerListePla(); |
break; |
case 'floeur' : // flora europea |
$this->executerFloeur(); |
break; |
case 'bryo' : // bryophyte |
$this->executerBryo(); |
break; |
case 'syntri' : //syntri : numéro complémentaire |
$this->executerSyntri(); |
break; |
case 'ciff' : // CIFF CIFF/BDNFF |
$this->executerCiff(); |
break; |
case 'donneebb' : // Num_nom num_tax bdnff |
$this->executerDonneebb(); |
break; |
case 'codefr' : // CODEFR94 |
$this->executerCodefr(); |
break; |
default : |
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd)); |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier flore florenbi qui contient tous codes, numéro et nom fournier |
// /opt/lampp/bin/php cli.php sophy/insertionflore -a florenbi -n ./../donnees/sophy/2010-12-02/FLORE/FLORENBI |
private function executerFlorenbi() { |
$nomFichier = $this->dossier.'FLORENBI'; |
if (file_exists($nomFichier) === true) { |
if ( $fichierOuvert = fopen($nomFichier, 'r') ) { |
$nom = ''; |
while ($ligne = fgets($fichierOuvert)) { |
if (preg_match('/^\s{2}[\d\s]{4}\s([\d\s]{3}\d)\s{2}([\d\s]\d\.\d\d\.\d)\s[\d\s]{5}[A-Z\s]\s(\d)\s*(.+)$/', $ligne, $champs)) { |
// si le rang taxonomique est inf à 4 (subsp et var) |
if ($champs[3] < 4) { |
$flore[$champs[1]] = $champs[4]; |
$nom = trim($champs[4]); |
} else { |
$flore[$champs[1]] = $nom." ".$champs[4]; |
} |
} |
} |
$info = $this->dao->integrerFlore($flore, 'fournier'); |
$this->traiterErreur($info); |
} |
fclose($fichierOuvert); |
} else { |
$this->traiterErreur("Le fichier {$fichier} n'existe pas."); |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier flore florenbi qui contient tous codes, numéro et nom fournier |
// /opt/lampp/bin/php cli.php sophy/insertionflore -a florenbi -n ./../donnees/sophy/2010-12-02/FLORE/FLORENBI |
private function executerBdnff() { |
$nomFichier = $this->dossier.'bdnffv5.csv'; |
if (file_exists($nomFichier) === true) { |
$this->dao->chargerDonnees($nomFichier, 'sophy_bdnff'); |
} else { |
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas."); |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier flore listePla qui contient numéro de fournier, nom de fournier, numéro bdnff, nom bdnff |
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a listepla -n ./../doc/jeux_test/FLORE/LISTEPLA.csv |
private function executerListePla() { |
// Parcours le fichier .csv et enregistre chaque ligne dans un tableau. |
$nomFichier = $this->dossier.'LISTEPLA.csv'; |
if ($nomFichier && file_exists($nomFichier) ){ |
$extensionFichier = strtolower(strrchr($nomFichier, '.')); |
if ($extensionFichier === ".csv"){ |
$file = new SplFileObject($nomFichier); |
$file->setFlags(SplFileObject::SKIP_EMPTY); |
$i = 0; |
echo "Traitement de LISTEPLA : "; |
while (!$file->eof()){ |
$flore = $this->transformerFournierBdnff($file->fgetcsv()); |
echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++; |
} |
echo "\n"; |
//$info = $this->dao->integrerFlore($this->flore['bdnff'], 'bdnff'); |
$info .= $this->dao->integrerFlore($this->flore['correspondance'], 'fournier_bdnff'); |
$this->traiterErreur($info); |
} else { |
$this->traiterErreur("Le fichier $nomFichier n'est pas au format csv."); |
} |
} else { |
$this->traiterErreur("Le fichier $nomFichier n'existe pas."); |
} |
} |
private function transformerFournierBdnff($ligne_csv){ |
//$this->flore['bdnff'][$ligne_csv[5]] = $ligne_csv[6]; |
$this->flore['correspondance'][$ligne_csv[3]] = $ligne_csv[5]; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier flore floeur.bis qui contient numéro et nom de flora europea |
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a floeur -n ./../doc/jeux_test/FLORE/FLOEUR.BIS |
private function executerFloeur() { |
$nomFichier = $this->dossier.'FLOEUR.BIS'; |
if (file_exists($nomFichier) === true) { |
if ( $fichierOuvert = fopen($nomFichier, 'r') ) { |
$i = 0; |
while ($ligne = fgets($fichierOuvert)) { |
if (preg_match('/^\s[\d\s]{9}[\d\sA-Z]\s([\d\s]{4}\d)\s(.{71})[\s\d]{2}/', $ligne, $champs)) { |
$this->flore[$champs[1]] = trim($champs[2]); |
} |
} |
$info = $this->dao->integrerFlore($this->flore, 'flora_europea'); |
$this->traiterErreur($info); |
} |
fclose($fichierOuvert); |
} else { |
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas."); |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier flore codebry qui contient numéro et nom des bryophytes |
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a bryo -n ./../doc/jeux_test/FLORE/codebry.txt |
private function executerBryo() { |
$nomFichier = $this->dossier.'codebry.txt'; |
if (file_exists($nomFichier) === true) { |
if ( $fichierOuvert = fopen($nomFichier, 'r') ) { |
$i = 0; |
while ($ligne = fgets($fichierOuvert)) { |
if (preg_match('/^\s([\d\s]{4})\s[\d\s][\d\s]{4}\s{2}\d\s*(.*)\s[\d\s]{4}/', $ligne, $champs)) { |
if ($champs[1] != 0) { |
$this->flore[$champs[1]] = trim($champs[2]); |
} |
} |
} |
$info = $this->dao->integrerFlore($this->flore, 'bryophyte'); |
$this->traiterErreur($info); |
} |
fclose($fichierOuvert); |
} else { |
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas."); |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier flore Syntri qui contient numéro de fournier, numéro syntri, nom syntri |
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a syntri -n ./../doc/jeux_test/FLORE/SYNTRI.TXT |
private function executerSyntri() { |
$nomFichier = $this->dossier.'SYNTRI.TXT'; |
if (file_exists($nomFichier) === true) { |
if ( $fichierOuvert = fopen($nomFichier, 'r') ) { |
$i = 0; |
while ($ligne = fgets($fichierOuvert)) { |
if (preg_match('/^(\d+)\s{2}\d\s([A-Z,\-\'\.()\s]+[A-Z,\-\'\.()])\s+([\d\s]+)$/', trim($ligne), $champs)) { |
$syntri = preg_split('/\s+/', $champs[3]); |
if (count($syntri) == 3) { |
$num = $syntri[1]; |
} elseif (count($syntri) == 1){ |
$num = $syntri[0]; |
} |
if (isset($flore['correspondance'][$num])) { |
$flore['syntri'][$num] = $flore['syntri'][$num].$champs[2]; |
} else { |
$flore['correspondance'][$num] = $champs[1]; |
$flore['syntri'][$num] = $champs[2]; |
} |
$i++; |
} |
} |
$info = $this->dao->integrerFlore($flore['syntri'], 'syntri'); |
$info .= $this->dao->integrerFlore($flore['correspondance'], 'syntri_fournier'); |
$this->traiterErreur($info); |
} |
fclose($fichierOuvert); |
} else { |
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas."); |
} |
} |
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a ciff -n ./../doc/jeux_test/FLORE/ciff.txt |
private function executerCiff() { |
$nomFichier = $this->dossier.'ciff.txt'; |
if (file_exists($nomFichier) === true) { |
if ( $fichierOuvert = fopen($nomFichier, 'r') ) { |
$i = 0; |
while ($ligne = fgets($fichierOuvert)) { |
if (preg_match('/^(\d*)\t([A-Za-z].*)\t(\d*)\t\d*/', $ligne, $champs)) { |
$flore['ciff'][$champs[1]] = $champs[2]; |
if ($champs[3] != '') { |
$flore['correspondance'][$champs[1]] = $champs[3]; |
} |
} |
} |
$info = $this->dao->integrerFlore($flore['ciff'], 'ciff'); |
$info .= $this->dao->integrerFlore($flore['correspondance'], 'ciff_bdnff'); |
$this->traiterErreur($info); |
} |
fclose($fichierOuvert); |
} else { |
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas."); |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier flore donneebb.tri qui contient le numero tax t numero nomenclatural de la bdnff |
// num_tax||num_nom||num_nom_retenu||?||nom |
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a donneebb -n ./../doc/jeux_test/FLORE/donneebb.tri |
private function executerDonneebb() { |
$nomFichier = $this->dossier.'donneebb.tri'; |
if (file_exists($nomFichier) === true) { |
if ( $fichierOuvert = fopen($nomFichier, 'r') ) { |
while ($ligne = fgets($fichierOuvert)) { |
if (preg_match('/^([\d\s]{4}\d)\|([\d\s]{5})\|([\d\s]{5})\|/', $ligne, $champs)) { |
if (!isset($this->flore[$champs[1]])) { |
$this->flore[$champs[2]]['num_tax'] = $champs[1]; |
if (trim($champs[3]) != '') { |
$this->flore[$champs[2]]['num_nom_retenu'] = $champs[3]; |
} else { |
$this->flore[$champs[2]]['num_nom_retenu'] = $champs[2]; |
} |
} |
} |
} |
$info = $this->dao->ajouterColonnes($this->flore, 'sophy_bdnff'); |
$this->traiterErreur($info); |
} |
fclose($fichierOuvert); |
} else { |
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas."); |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier flore codefr94 qui contient numéro et nom codefr94 |
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a ciff -n ./../doc/jeux_test/FLORE/CODEFR94 |
private function executerCodefr() { |
$nomFichier = $this->dossier.'CODEFR94'; |
if (file_exists($nomFichier) === true) { |
if ( $fichierOuvert = fopen($nomFichier, 'r') ) { |
$i = 0; |
while ($ligne = fgets($fichierOuvert)) { |
if (preg_match('/^([\d\s]{5})[\d\s]{7}(.*)/', $ligne, $champs)) { |
$flore[$champs[1]] = trim($champs[2]); |
} |
} |
$info = $this->dao->integrerFlore($flore, 'codefr94'); |
$this->traiterErreur($info); |
} |
fclose($fichierOuvert); |
} else { |
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas."); |
} |
} |
} |
/tags/v5.7-arrayanal/scripts/modules/sophy/insertion.ini |
---|
New file |
0,0 → 1,20 |
; +------------------------------------------------------------------------------------------------------+ |
; Général |
; Séparateur de dossier |
ds = DIRECTORY_SEPARATOR |
; +------------------------------------------------------------------------------------------------------+ |
; Info sur l'application |
info.nom = Scripts de gestion de la phytosociologie |
; Abréviation de l'application |
info.abr = sophy |
; Version du Framework nécessaire au fonctionnement de cette application |
info.framework.version = 0.2 |
;Encodage de l'application |
appli_encodage = "UTF-8" |
version="2010-12-02" |
dossierSql = "{ref:dossierDonneesEflore}{ref:info.abr}/{ref:version}/" |
[fichiers] |
structureSql = "sophy.sql" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
/tags/v5.7-arrayanal/scripts/modules/sophy/bibliotheque/FloreDao.php |
---|
New file |
0,0 → 1,74 |
<?php |
class FloreDao extends Bdd { |
public function integrerFlore($flore, $nom_flore){ |
$flore = array_map(array($this, 'proteger'), $flore); |
$requete = "INSERT INTO sophy_{$nom_flore} VALUES "; |
$i = 0; $j = 1000; $info = ''; |
foreach ($flore as $num => $nom) { |
if ($i < $j) { |
$requete .= " ({$num}, {$nom}), "; |
} else { |
$requete = substr($requete,0,-2).";"; |
$resultat = $this->requeter($requete); |
if ($resultat === false) { |
$info .= $nom_flore.$j." n'est pas intégrée.\n"; |
} else { |
$info .= $nom_flore.$j." est intégrée.\n"; |
} |
$j += 1000; |
$requete = "INSERT INTO sophy_{$nom_flore} VALUES ({$num}, {$nom}), "; |
} |
$i++; |
} |
$requete = substr($requete,0,-2).";"; |
$resultat = $this->requeter($requete); |
if ($resultat === false) { |
$info .= $nom_flore.$i." n'est pas intégrée.\n"; |
//echo $requete."\n"; |
} else { |
$info .= $nom_flore.$i." est intégrée.\n"; |
} |
return $info; |
} |
public function chargerDonnees($fichier, $table) { |
$requete = "LOAD DATA INFILE '$fichier' ". |
"REPLACE INTO TABLE $table ". |
"CHARACTER SET utf8 ". |
"FIELDS |
TERMINATED BY ','"; |
$this->requeter($requete); |
} |
public function ajouterColonnes($donnees, $table) { |
$this->preparerTable($table, 'sb_num_nom_retenu'); |
$this->preparerTable($table, 'sb_num_tax'); |
$this->lancerRequeteModification($table, $donnees); |
} |
private function preparerTable($table, $colonne) { |
$requete = "SHOW COLUMNS FROM {$table} LIKE '{$colonne}' "; |
$resultat = $this->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$table} ". |
"ADD {$colonne} INT(5) "; |
$this->requeter($requete); |
} |
} |
private function lancerRequeteModification($table, $flore) { |
foreach ($flore as $num_nom => $info) { |
$requete = "UPDATE {$table} ". |
"SET sb_num_nom_retenu = {$info['num_nom_retenu']} ". |
", sb_num_tax = {$info['num_tax']} ". |
"WHERE sb_id_num_bdnff = $num_nom ";//echo $requete."\n"; |
$res = $this->requeter($requete); |
if ($res === false) { |
$this->traiterErreur("erreur d'insertion pour le tuple %s", array($id)); |
} |
} |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/sophy/bibliotheque/TaxonDao.php |
---|
New file |
0,0 → 1,279 |
<?php |
class TaxonDao extends Bdd { |
// tableau de la forme $taxons[num][flore][id] |
// $taxons[num][flore][nom] |
protected $taxons = array(); |
private $id = 0; |
private $flores = array('syntri', 'ciff', 'codefr94', 'bdnff', 'bryo', 'floeur', 'algues', 'characees', 'lichen', 'fournier'); |
private $table_flores = array('bdnff', 'fournier', 'ciff', 'syntri', 'codefr94', 'bryo', 'floeur'); |
public function __construct() { |
Bdd::__construct(); |
$this->id = $this->chargerId() + 1; |
$this->taxons = $this->chargerTaxon(); |
} |
// recherche si un taxon existe sinon le crée et renvoie son id |
public function getId($num_taxon, $flore = 'ind', $nom = null, $flore_supp = null, $num_supp = null, $remarques = '') { |
$idTaxon = null; $nom_supp = $nom; |
if ($nom == null && $remarques != '') { |
$nom = "rem:".$flore_supp.$num_supp.'/'.$remarques; |
} |
if (isset($this->taxons['ind'][$nom]['id'])) { |
$idTaxon = $this->taxons['ind'][$nom]['id']; |
} elseif (isset($this->taxons[$flore][$num_taxon]['id']) && $nom == null) { |
$idTaxon = $this->taxons[$flore][$num_taxon]['id']; |
} else { |
$idTaxon = $this->ajouterTaxon($num_taxon, $flore, $nom_supp, $flore_supp, $num_supp, $remarques); |
} |
return $idTaxon; |
} |
// renvoie un nom d'apres son id |
public function getNom($id) { |
foreach ($this->taxons['ind'] as $nom=>$param) { |
if ($param['id'] === $id) { |
if (preg_match('/rem:[a-z]+\d+\/(.*)/', $nom, $match)) { |
$nom = $match[1]; |
} |
return $nom; |
} |
} |
return ''; |
} |
// Ajoute taxon avec pour clé le numéro taxon, le nom ou la remarque |
public function ajouterTaxon($num_taxon, $flore, $nom, $flore_supp, $num_supp, $remarques) { |
if ($nom != null) { |
$cle = 'ind'; |
$num = $nom; |
} elseif ($remarques != '') { |
$cle = 'ind'; |
$num = "rem:".$flore_supp.$num_supp.'/'.$remarques; |
} else { |
$cle = $flore; |
$num = $num_taxon; |
} |
$this->taxons[$cle][$num]['id'] = $this->id; |
foreach ($this->flores as $nom_flore) { |
if ($nom_flore == $flore) { |
$this->taxons[$cle][$num][$nom_flore] = $num_taxon; |
} elseif ($nom_flore == $flore_supp) { |
$this->taxons[$cle][$num][$nom_flore] = $num_supp; |
} else { |
$this->taxons[$cle][$num][$nom_flore] = 'NULL'; |
} |
} |
$this->taxons[$cle][$num]['nom'] = $this->ajouterNomTaxon($num_taxon, $flore, $nom, $flore_supp, $num_supp); |
$this->taxons[$cle][$num]['remarques'] = $remarques; |
$this->id++; |
return $this->taxons[$cle][$num]['id']; |
} |
public function ajouterNomTaxon($num_taxon, $flore, $nom_supp, $flore_supp, $num_supp) { |
$nom = ''; |
$nomCherche = false; |
foreach ($this->table_flores as $nom_flore) { |
if ($nomCherche == false) { |
if ($nom_flore == $flore) { |
$nom = $this->rechercherNomTaxon($nom_flore, $num_taxon); |
if ($nom != false) { |
$nomCherche = true; |
} |
} elseif ($nom_flore == $flore_supp) { |
$nom = $this->rechercherNomTaxon($nom_flore, $num_supp); |
if ($nom != false) { |
$nomCherche = true; |
} |
} |
} |
} |
if ($nom == false && $nom_supp != null) { |
$nom = $nom_supp; |
} elseif ($nom == '' && $nom_supp != null) { |
$nom = $nom_supp; |
} |
return $nom; |
} |
public function rechercherNomTaxon($nom_flore, $num_taxon) { |
$requete2 = null; |
switch ($nom_flore) { |
case 'bdnff' : |
$requete = "SELECT sb_nom_complet AS nom FROM sophy_bdnff |
WHERE sb_num_tax = {$num_taxon} AND sb_id_num_bdnff = sb_num_nom_retenu; "; |
break; |
case 'fournier' : |
$requete = "SELECT sb_nom_complet AS nom FROM sophy_bdnff, sophy_fournier_bdnff |
WHERE sfb_id_num_fournier = {$num_taxon} AND sb_num_tax = sfb_id_num_bdnff AND sb_id_num_bdnff = sb_num_nom_retenu;"; |
$requete2 = "SELECT sf_nom_fournier AS nom FROM sophy_fournier WHERE sf_id_num_fournier = {$num_taxon};"; |
break; |
case 'ciff' : |
$requete = "SELECT sb_nom_complet AS nom |
FROM sophy_bdnff, sophy_ciff_bdnff |
WHERE scb_id_num_ciff = {$num_taxon} AND scb_id_num_bdnff = sb_id_num_bdnff;"; |
$requete2 = "SELECT sci_nom_ciff AS nom FROM sophy_ciff WHERE sci_id_num_ciff = {$num_taxon};"; |
break; |
case 'syntri' : |
$requete = "SELECT sb_nom_complet AS nom |
FROM sophy_bdnff, sophy_syntri_fournier, sophy_fournier_bdnff |
WHERE ssf_id_num_syntri = {$num_taxon} AND ssf_id_num_fournier = sfb_id_num_fournier |
AND sb_num_tax = sfb_id_num_bdnff AND sb_id_num_bdnff = sb_num_nom_retenu;"; |
$requete2 = "SELECT ssyn_nom_supp AS nom FROM sophy_syntri WHERE ssyn_id_num_supp = {$num_taxon};"; |
break; |
case 'codefr94' : |
$requete = "SELECT sc_nom_codefr AS nom FROM sophy_codefr94 WHERE sc_id_num_codefr = {$num_taxon};"; |
break; |
case 'bryo' : |
$requete = "SELECT sbr_nom_bryo AS nom FROM sophy_bryophyte WHERE sbr_id_num_bryo = {$num_taxon};"; |
break; |
case 'floeur' : |
$requete = "SELECT sfe_nom_floeur AS nom FROM sophy_flora_europea WHERE sfe_id_num_floeur = {$num_taxon};"; |
break; |
} |
$resultat_requete = $this->recuperer($requete); |
if ($resultat_requete['nom'] == false && $requete2 != null) { |
$resultat_requete = $this->recuperer($requete2); |
} |
return $resultat_requete['nom']; |
} |
// recherche le dernier id de la base |
public function chargerId() { |
$id = 0; |
$requete_select_id = "SELECT MAX(st_id_taxon) AS idMax FROM sophy_taxon;"; |
$resultat_requete_id = $this->recuperer($requete_select_id); |
if ($resultat_requete_id['idMax'] != false) { |
$id = $resultat_requete_id['idMax']; |
} |
return $id; |
} |
// Regarde si il y a des taxons dans la base, retourne le tableau de valeur et vide la base |
public function chargerTaxon() { |
$resultat = null; |
$retour = null; |
$requete_select = "SELECT * FROM sophy_taxon;"; |
$resultat = $this->recupererTous($requete_select); |
if ($resultat != false) { |
foreach ($resultat as $result) { |
if ($result['st_nom_supp'] != null) { |
$retour['ind'][$result['st_nom_supp']]['id'] = $result['st_id_taxon']; |
foreach ($this->flores as $nom_flore) { |
$retour['ind'][$result['st_nom_supp']][$nom_flore] = $result["st_ce_num_".$nom_flore]; |
} |
$retour['ind'][$result['st_nom_supp']]['remarques'] = $result['st_nom_supp']; |
} elseif ($result['st_remarques'] != null) { |
$nom = $result['st_remarques']; |
$retour['ind'][$nom]['id'] = $result['st_id_taxon']; |
foreach ($this->flores as $nom_flore) { |
$retour['ind'][$result['st_nom_supp']][$nom_flore] = $result["st_ce_num_".$nom_flore]; |
} |
$retour['ind'][$nom]['remarques'] = $result['st_nom_supp']; |
} elseif ($result['st_ce_num_syntri'] != null) { |
$retour['syntri'][$result['st_ce_num_syntri']]['id'] = $result['st_id_taxon']; |
$retour['syntri'][$result['st_ce_num_syntri']]['num_supp'] = $result['st_num_supp']; |
} elseif ($result['st_ce_num_floeur'] != null) { |
$retour['floeur'][$result['st_ce_num_floeur']]['id'] = $result['st_id_taxon']; |
} elseif ($result['st_ce_num_bdnff'] != null) { |
$retour['bdnff'][$result['st_ce_num_bdnff']]['id'] = $result['st_id_taxon']; |
} elseif ($result['st_ce_num_codefr94'] != null) { |
$retour['codefr94'][$result['st_ce_num_codefr94']]['id'] = $result['st_id_taxon']; |
} elseif ($result['st_ce_num_bryo'] != null) { |
$retour['bryo'][$result['st_ce_num_bryo']]['id'] = $result['st_id_taxon']; |
} elseif ($result['st_ce_num_ciff'] != null) { |
$retour['ciff'][$result['st_ce_num_ciff']]['id'] = $result['st_id_taxon']; |
} elseif ($result['st_ce_num_fournier'] != null) { |
$retour['fournier'][$result['st_ce_num_fournier']]['id'] = $result['st_id_taxon']; |
} |
} |
} |
$requete = "TRUNCATE TABLE `sophy_taxon`; "; |
$res = $this->requeter($requete); |
return $retour; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Requête sur table sophy_taxon et toutes les tables flore de sophy |
public function integrerTaxons() { |
foreach ($this->taxons as $flore=>$taxons) { |
switch ($flore) { |
case 'ind' : |
// insertion par 1000 pour éviter que la requête soit trop lourde |
$i = 0; $j = 1000; |
$requete = "INSERT INTO `sophy_taxon` (`st_id_taxon`, `st_nom`, `st_nom_supp`,"; |
foreach ($this->flores as $nom_flore) { |
$requete .= "st_ce_num_{$nom_flore}, "; |
} |
$requete .= " st_remarques) VALUES "; |
foreach ($taxons as $taxon=>$valeur) { |
if (!isset($valeur['remarques'])){ |
$valeur['remarques'] = 'NULL'; |
$taxon = $this->proteger($taxon); |
} elseif (substr_compare($taxon, 'rem:', 0, 4) == 0){ |
$valeur['remarques'] = $this->proteger($taxon); |
$taxon = 'NULL'; |
} else { |
$taxon = $this->proteger($taxon); |
$valeur['remarques'] = $this->proteger($valeur['remarques']); |
} |
if ($i < $j) { |
$requete .= " (".$valeur['id'].", ".$this->proteger($valeur['nom']).", ".$taxon.", "; |
foreach ($this->flores as $nom_flore) { |
$requete .= $valeur[$nom_flore].", "; |
} |
$requete .= " ".$valeur['remarques']."),"; |
} elseif ($i == $j) {$j += 1000; |
$requete = substr($requete,0,-1).";"; |
$resultat = $this->requeter($requete); |
if ($resultat == false) { |
echo $flore.' : '.$i; |
} |
$requete = "INSERT INTO `sophy_taxon` (`st_id_taxon`, `st_nom`, `st_nom_supp`,"; |
foreach ($this->flores as $nom_flore) { |
$requete .= "st_ce_num_{$nom_flore}, "; |
} |
$requete .= " st_remarques) VALUES (".$valeur['id'].", ".$this->proteger($valeur['nom']). |
", ".$taxon.", "; |
foreach ($this->flores as $nom_flore) { |
$requete .= $valeur[$nom_flore].", "; |
} |
$requete .= " ".$valeur['remarques']."),"; |
} |
$i++; |
} |
$requete = substr($requete,0,-1).";"; |
break; |
case 'syntri' : |
$i = 0; |
$requete = "INSERT INTO `sophy_taxon` (`st_id_taxon`, "; |
foreach ($this->flores as $nom_flore) { |
$requete .= "st_ce_num_{$nom_flore}, "; |
} |
$requete .= "`st_nom`) VALUES "; |
foreach ($taxons as $taxon=>$valeur) { |
$requete .= " (".$valeur['id'].", "; |
foreach ($this->flores as $nom_flore) { |
$requete .= $valeur[$nom_flore].", "; |
} |
$requete .= $this->proteger($valeur['nom'])."), "; |
} |
$requete = substr($requete,0,-2).";"; |
break; |
default: |
$requete = "INSERT INTO `sophy_taxon` (`st_id_taxon`, `st_nom`, st_ce_num_{$flore}) VALUES "; |
foreach ($taxons as $numTaxon=>$valeur) { |
$requete .= " (".$valeur['id'].", ".$this->proteger($valeur['nom']).", ".$numTaxon."),"; |
} |
$requete = substr($requete,0,-1).";"; |
break; |
} |
$resultat = $this->requeter($requete); |
if ($resultat == false) { |
echo " - flore : ".$flore; |
} |
} |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/sophy/bibliotheque/gPoint.php |
---|
New file |
0,0 → 1,534 |
<?php |
/*------------------------------------------------------------------------------ |
** File: gPoint.php |
** Description: PHP class to convert Latitude & Longitude coordinates into |
** UTM & Lambert Conic Conformal Northing/Easting coordinates. |
** Version: 1.3 |
** Author: Brenor Brophy |
** Email: brenor dot brophy at gmail dot com |
** Homepage: brenorbrophy.com |
**------------------------------------------------------------------------------ |
** COPYRIGHT (c) 2005, 2006, 2007, 2008 BRENOR BROPHY |
** |
** The source code included in this package is free software; you can |
** redistribute it and/or modify it under the terms of the GNU General Public |
** License as published by the Free Software Foundation. This license can be |
** read at: |
** |
** http://www.opensource.org/licenses/gpl-license.php |
** |
** This program is distributed in the hope that it will be useful, but WITHOUT |
** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
** FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. |
**------------------------------------------------------------------------------ |
** |
** Code for datum and UTM conversion was converted from C++ code written by |
** Chuck Gantz (chuck dot gantz at globalstar dot com) from |
** http://www.gpsy.com/gpsinfo/geotoutm/ This URL has many other references to |
** useful information concerning conversion of coordinates. |
** |
** Rev History |
** ----------------------------------------------------------------------------- |
** 1.0 08/25/2005 Initial Release |
** 1.1 05/15/2006 Added software license language to header comments |
** Fixed an error in the convertTMtoLL() method. The latitude |
** calculation had a bunch of variables without $ symbols. |
** Fixed an error in convertLLtoTM() method, The $this-> was |
** missing in front of a couple of variables. Thanks to Bob |
** Robins of Maryland for catching the bugs. |
** 1.2 05/18/2007 Added default of NULL to $LongOrigin arguement in convertTMtoLL() |
** and convertLLtoTM() to eliminate warning messages when the |
** methods are called without a value for $LongOrigin. |
** 1.3 02/21/2008 Fixed a bug in the distanceFrom method, where the input parameters |
** were not being converted to radians prior to calculating the |
** distance. Thanks to Enrico Benco for finding pointing it out. |
*/ |
define ("meter2nm", (1/1852)); |
define ("nm2meter", 1852); |
/*------------------------------------------------------------------------------ |
** class gPoint ... for Geographic Point |
** |
** This class encapsulates the methods for representing a geographic point on the |
** earth in three different coordinate systema. Lat/Long, UTM and Lambert Conic |
** Conformal. |
*/ |
class gPoint |
{ |
/* Reference ellipsoids derived from Peter H. Dana's website- |
** http://www.colorado.edu/geography/gcraft/notes/datum/datum_f.html |
** email: pdana@pdana.com, web page: www.pdana.com |
** |
** Source: |
** Defense Mapping Agency. 1987b. DMA Technical Report: Supplement to Department |
** of Defense World Geodetic System 1984 Technical Report. Part I and II. |
** Washington, DC: Defense Mapping Agency |
*/ |
var $ellipsoid = array(//Ellipsoid name, Equatorial Radius, square of eccentricity |
"Airy" =>array (6377563, 0.00667054), |
"Australian National" =>array (6378160, 0.006694542), |
"Bessel 1841" =>array (6377397, 0.006674372), |
"Bessel 1841 Nambia" =>array (6377484, 0.006674372), |
"Clarke 1866" =>array (6378206, 0.006768658), |
"Clarke 1880" =>array (6378249, 0.006803511), |
"Everest" =>array (6377276, 0.006637847), |
"Fischer 1960 Mercury" =>array (6378166, 0.006693422), |
"Fischer 1968" =>array (6378150, 0.006693422), |
"GRS 1967" =>array (6378160, 0.006694605), |
"GRS 1980" =>array (6378137, 0.00669438), |
"Helmert 1906" =>array (6378200, 0.006693422), |
"Hough" =>array (6378270, 0.00672267), |
"International" =>array (6378388, 0.00672267), |
"Krassovsky" =>array (6378245, 0.006693422), |
"Modified Airy" =>array (6377340, 0.00667054), |
"Modified Everest" =>array (6377304, 0.006637847), |
"Modified Fischer 1960" =>array (6378155, 0.006693422), |
"South American 1969" =>array (6378160, 0.006694542), |
"WGS 60" =>array (6378165, 0.006693422), |
"WGS 66" =>array (6378145, 0.006694542), |
"WGS 72" =>array (6378135, 0.006694318), |
"WGS 84" =>array (6378137, 0.00669438)); |
// Properties |
var $a; // Equatorial Radius |
var $e2; // Square of eccentricity |
var $datum; // Selected datum |
var $Xp, $Yp; // X,Y pixel location |
var $lat, $long; // Latitude & Longitude of the point |
var $utmNorthing, $utmEasting, $utmZone; // UTM Coordinates of the point |
var $lccNorthing, $lccEasting; // Lambert coordinates of the point |
var $falseNorthing, $falseEasting; // Origin coordinates for Lambert Projection |
var $latOfOrigin; // For Lambert Projection |
var $longOfOrigin; // For Lambert Projection |
var $firstStdParallel; // For lambert Projection |
var $secondStdParallel; // For lambert Projection |
// constructor |
function gPoint($datum='WGS 84') // Default datum is WGS 84 |
{ |
$this->a = $this->ellipsoid[$datum][0]; // Set datum Equatorial Radius |
$this->e2 = $this->ellipsoid[$datum][1]; // Set datum Square of eccentricity |
$this->datum = $datum; // Save the datum |
} |
// |
// Set/Get X & Y pixel of the point (used if it is being drawn on an image) |
// |
function setXY($x, $y) |
{ |
$this->Xp = $x; $this->Yp = $y; |
} |
function Xp() { return $this->Xp; } |
function Yp() { return $this->Yp; } |
// |
// Set/Get/Output Longitude & Latitude of the point |
// |
function setLongLat($long, $lat) |
{ |
$this->long = $long; $this->lat = $lat; |
} |
function Lat() { return $this->lat; } |
function Long() { return $this->long; } |
function printLatLong() { printf("Latitude: %1.5f Longitude: %1.5f",$this->lat, $this->long); } |
// |
// Set/Get/Output Universal Transverse Mercator Coordinates |
// |
function setUTM($easting, $northing, $zone='') // Zone is optional |
{ |
$this->utmNorthing = $northing; |
$this->utmEasting = $easting; |
$this->utmZone = $zone; |
} |
function N() { return $this->utmNorthing; } |
function E() { return $this->utmEasting; } |
function Z() { return $this->utmZone; } |
function printUTM() { print( "Northing: ".(int)$this->utmNorthing.", Easting: ".(int)$this->utmEasting.", Zone: ".$this->utmZone); } |
// |
// Set/Get/Output Lambert Conic Conformal Coordinates |
// |
function setLambert($easting, $northing) |
{ |
$this->lccNorthing = $northing; |
$this->lccEasting = $easting; |
} |
function lccN() { return $this->lccNorthing; } |
function lccE() { return $this->lccEasting; } |
function printLambert() { print( "Northing: ".(int)$this->lccNorthing.", Easting: ".(int)$this->lccEasting); } |
//------------------------------------------------------------------------------ |
// |
// Convert Longitude/Latitude to UTM |
// |
// Equations from USGS Bulletin 1532 |
// East Longitudes are positive, West longitudes are negative. |
// North latitudes are positive, South latitudes are negative |
// Lat and Long are in decimal degrees |
// Written by Chuck Gantz- chuck dot gantz at globalstar dot com, converted to PHP by |
// Brenor Brophy, brenor dot brophy at gmail dot com |
// |
// UTM coordinates are useful when dealing with paper maps. Basically the |
// map will can cover a single UTM zone which is 6 degrees on longitude. |
// So you really don't care about an object crossing two zones. You just get a |
// second map of the other zone. However, if you happen to live in a place that |
// straddles two zones (For example the Santa Babara area in CA straddles zone 10 |
// and zone 11) Then it can become a real pain having to have two maps all the time. |
// So relatively small parts of the world (like say California) create their own |
// version of UTM coordinates that are adjusted to conver the whole area of interest |
// on a single map. These are called state grids. The projection system is the |
// usually same as UTM (i.e. Transverse Mercator), but the central meridian |
// aka Longitude of Origin is selected to suit the logitude of the area being |
// mapped (like being moved to the central meridian of the area) and the grid |
// may cover more than the 6 degrees of lingitude found on a UTM map. Areas |
// that are wide rather than long - think Montana as an example. May still |
// have to have a couple of maps to cover the whole state because TM projection |
// looses accuracy as you move further away from the Longitude of Origin, 15 degrees |
// is usually the limit. |
// |
// Now, in the case where we want to generate electronic maps that may be |
// placed pretty much anywhere on the globe we really don't to deal with the |
// issue of UTM zones in our coordinate system. We would really just like a |
// grid that is fully contigious over the area of the map we are drawing. Similiar |
// to the state grid, but local to the area we are interested in. I call this |
// Local Transverse Mercator and I have modified the function below to also |
// make this conversion. If you pass a Longitude value to the function as $LongOrigin |
// then that is the Longitude of Origin that will be used for the projection. |
// Easting coordinates will be returned (in meters) relative to that line of |
// longitude - So an Easting coordinate for a point located East of the longitude |
// of origin will be a positive value in meters, an Easting coordinate for a point |
// West of the longitude of Origin will have a negative value in meters. Northings |
// will always be returned in meters from the equator same as the UTM system. The |
// UTMZone value will be valid for Long/Lat given - thought it is not meaningful |
// in the context of Local TM. If a NULL value is passed for $LongOrigin |
// then the standard UTM coordinates are calculated. |
// |
function convertLLtoTM($LongOrigin = NULL) |
{ |
$k0 = 0.9996; |
$falseEasting = 0.0; |
//Make sure the longitude is between -180.00 .. 179.9 |
$LongTemp = ($this->long+180)-(integer)(($this->long+180)/360)*360-180; // -180.00 .. 179.9; |
$LatRad = deg2rad($this->lat); |
$LongRad = deg2rad($LongTemp); |
if (!$LongOrigin) |
{ // Do a standard UTM conversion - so findout what zone the point is in |
$ZoneNumber = (integer)(($LongTemp + 180)/6) + 1; |
// Special zone for South Norway |
if( $this->lat >= 56.0 && $this->lat < 64.0 && $LongTemp >= 3.0 && $LongTemp < 12.0 ) // Fixed 1.1 |
$ZoneNumber = 32; |
// Special zones for Svalbard |
if( $this->lat >= 72.0 && $this->lat < 84.0 ) |
{ |
if( $LongTemp >= 0.0 && $LongTemp < 9.0 ) $ZoneNumber = 31; |
else if( $LongTemp >= 9.0 && $LongTemp < 21.0 ) $ZoneNumber = 33; |
else if( $LongTemp >= 21.0 && $LongTemp < 33.0 ) $ZoneNumber = 35; |
else if( $LongTemp >= 33.0 && $LongTemp < 42.0 ) $ZoneNumber = 37; |
} |
$LongOrigin = ($ZoneNumber - 1)*6 - 180 + 3; //+3 puts origin in middle of zone |
//compute the UTM Zone from the latitude and longitude |
$this->utmZone = sprintf("%d%s", $ZoneNumber, $this->UTMLetterDesignator()); |
// We also need to set the false Easting value adjust the UTM easting coordinate |
$falseEasting = 500000.0; |
} |
$LongOriginRad = deg2rad($LongOrigin); |
$eccPrimeSquared = ($this->e2)/(1-$this->e2); |
$N = $this->a/sqrt(1-$this->e2*sin($LatRad)*sin($LatRad)); |
$T = tan($LatRad)*tan($LatRad); |
$C = $eccPrimeSquared*cos($LatRad)*cos($LatRad); |
$A = cos($LatRad)*($LongRad-$LongOriginRad); |
$M = $this->a*((1 - $this->e2/4 - 3*$this->e2*$this->e2/64 - 5*$this->e2*$this->e2*$this->e2/256)*$LatRad |
- (3*$this->e2/8 + 3*$this->e2*$this->e2/32 + 45*$this->e2*$this->e2*$this->e2/1024)*sin(2*$LatRad) |
+ (15*$this->e2*$this->e2/256 + 45*$this->e2*$this->e2*$this->e2/1024)*sin(4*$LatRad) |
- (35*$this->e2*$this->e2*$this->e2/3072)*sin(6*$LatRad)); |
$this->utmEasting = ($k0*$N*($A+(1-$T+$C)*$A*$A*$A/6 |
+ (5-18*$T+$T*$T+72*$C-58*$eccPrimeSquared)*$A*$A*$A*$A*$A/120) |
+ $falseEasting); |
$this->utmNorthing = ($k0*($M+$N*tan($LatRad)*($A*$A/2+(5-$T+9*$C+4*$C*$C)*$A*$A*$A*$A/24 |
+ (61-58*$T+$T*$T+600*$C-330*$eccPrimeSquared)*$A*$A*$A*$A*$A*$A/720))); |
if($this->lat < 0) |
$this->utmNorthing += 10000000.0; //10000000 meter offset for southern hemisphere |
} |
// |
// This routine determines the correct UTM letter designator for the given latitude |
// returns 'Z' if latitude is outside the UTM limits of 84N to 80S |
// Written by Chuck Gantz- chuck dot gantz at globalstar dot com, converted to PHP by |
// Brenor Brophy, brenor dot brophy at gmail dot com |
// |
function UTMLetterDesignator() |
{ |
if((84 >= $this->lat) && ($this->lat >= 72)) $LetterDesignator = 'X'; |
else if((72 > $this->lat) && ($this->lat >= 64)) $LetterDesignator = 'W'; |
else if((64 > $this->lat) && ($this->lat >= 56)) $LetterDesignator = 'V'; |
else if((56 > $this->lat) && ($this->lat >= 48)) $LetterDesignator = 'U'; |
else if((48 > $this->lat) && ($this->lat >= 40)) $LetterDesignator = 'T'; |
else if((40 > $this->lat) && ($this->lat >= 32)) $LetterDesignator = 'S'; |
else if((32 > $this->lat) && ($this->lat >= 24)) $LetterDesignator = 'R'; |
else if((24 > $this->lat) && ($this->lat >= 16)) $LetterDesignator = 'Q'; |
else if((16 > $this->lat) && ($this->lat >= 8)) $LetterDesignator = 'P'; |
else if(( 8 > $this->lat) && ($this->lat >= 0)) $LetterDesignator = 'N'; |
else if(( 0 > $this->lat) && ($this->lat >= -8)) $LetterDesignator = 'M'; |
else if((-8 > $this->lat) && ($this->lat >= -16)) $LetterDesignator = 'L'; |
else if((-16 > $this->lat) && ($this->lat >= -24)) $LetterDesignator = 'K'; |
else if((-24 > $this->lat) && ($this->lat >= -32)) $LetterDesignator = 'J'; |
else if((-32 > $this->lat) && ($this->lat >= -40)) $LetterDesignator = 'H'; |
else if((-40 > $this->lat) && ($this->lat >= -48)) $LetterDesignator = 'G'; |
else if((-48 > $this->lat) && ($this->lat >= -56)) $LetterDesignator = 'F'; |
else if((-56 > $this->lat) && ($this->lat >= -64)) $LetterDesignator = 'E'; |
else if((-64 > $this->lat) && ($this->lat >= -72)) $LetterDesignator = 'D'; |
else if((-72 > $this->lat) && ($this->lat >= -80)) $LetterDesignator = 'C'; |
else $LetterDesignator = 'Z'; //This is here as an error flag to show that the Latitude is outside the UTM limits |
return($LetterDesignator); |
} |
//------------------------------------------------------------------------------ |
// |
// Convert UTM to Longitude/Latitude |
// |
// Equations from USGS Bulletin 1532 |
// East Longitudes are positive, West longitudes are negative. |
// North latitudes are positive, South latitudes are negative |
// Lat and Long are in decimal degrees. |
// Written by Chuck Gantz- chuck dot gantz at globalstar dot com, converted to PHP by |
// Brenor Brophy, brenor dot brophy at gmail dot com |
// |
// If a value is passed for $LongOrigin then the function assumes that |
// a Local (to the Longitude of Origin passed in) Transverse Mercator |
// coordinates is to be converted - not a UTM coordinate. This is the |
// complementary function to the previous one. The function cannot |
// tell if a set of Northing/Easting coordinates are in the North |
// or South hemesphere - they just give distance from the equator not |
// direction - so only northern hemesphere lat/long coordinates are returned. |
// If you live south of the equator there is a note later in the code |
// explaining how to have it just return southern hemesphere lat/longs. |
// |
function convertTMtoLL($LongOrigin = NULL) |
{ |
$k0 = 0.9996; |
$e1 = (1-sqrt(1-$this->e2))/(1+sqrt(1-$this->e2)); |
$falseEasting = 0.0; |
$y = $this->utmNorthing; |
if (!$LongOrigin) |
{ // It is a UTM coordinate we want to convert |
sscanf($this->utmZone,"%d%s",$ZoneNumber,$ZoneLetter); |
if($ZoneLetter >= 'N') |
$NorthernHemisphere = 1;//point is in northern hemisphere |
else |
{ |
$NorthernHemisphere = 0;//point is in southern hemisphere |
$y -= 10000000.0;//remove 10,000,000 meter offset used for southern hemisphere |
} |
$LongOrigin = ($ZoneNumber - 1)*6 - 180 + 3; //+3 puts origin in middle of zone |
$falseEasting = 500000.0; |
} |
// $y -= 10000000.0; // Uncomment line to make LOCAL coordinates return southern hemesphere Lat/Long |
$x = $this->utmEasting - $falseEasting; //remove 500,000 meter offset for longitude |
$eccPrimeSquared = ($this->e2)/(1-$this->e2); |
$M = $y / $k0; |
$mu = $M/($this->a*(1-$this->e2/4-3*$this->e2*$this->e2/64-5*$this->e2*$this->e2*$this->e2/256)); |
$phi1Rad = $mu + (3*$e1/2-27*$e1*$e1*$e1/32)*sin(2*$mu) |
+ (21*$e1*$e1/16-55*$e1*$e1*$e1*$e1/32)*sin(4*$mu) |
+(151*$e1*$e1*$e1/96)*sin(6*$mu); |
$phi1 = rad2deg($phi1Rad); |
$N1 = $this->a/sqrt(1-$this->e2*sin($phi1Rad)*sin($phi1Rad)); |
$T1 = tan($phi1Rad)*tan($phi1Rad); |
$C1 = $eccPrimeSquared*cos($phi1Rad)*cos($phi1Rad); |
$R1 = $this->a*(1-$this->e2)/pow(1-$this->e2*sin($phi1Rad)*sin($phi1Rad), 1.5); |
$D = $x/($N1*$k0); |
$tlat = $phi1Rad - ($N1*tan($phi1Rad)/$R1)*($D*$D/2-(5+3*$T1+10*$C1-4*$C1*$C1-9*$eccPrimeSquared)*$D*$D*$D*$D/24 |
+(61+90*$T1+298*$C1+45*$T1*$T1-252*$eccPrimeSquared-3*$C1*$C1)*$D*$D*$D*$D*$D*$D/720); // fixed in 1.1 |
$this->lat = rad2deg($tlat); |
$tlong = ($D-(1+2*$T1+$C1)*$D*$D*$D/6+(5-2*$C1+28*$T1-3*$C1*$C1+8*$eccPrimeSquared+24*$T1*$T1) |
*$D*$D*$D*$D*$D/120)/cos($phi1Rad); |
$this->long = $LongOrigin + rad2deg($tlong); |
} |
//------------------------------------------------------------------------------ |
// Configure a Lambert Conic Conformal Projection |
// |
// falseEasting & falseNorthing are just an offset in meters added to the final |
// coordinate calculated. |
// |
// longOfOrigin & LatOfOrigin are the "center" latitiude and longitude of the |
// area being projected. All coordinates will be calculated in meters relative |
// to this point on the earth. |
// |
// firstStdParallel & secondStdParallel are the two lines of longitude (that |
// is they run east-west) that define where the "cone" intersects the earth. |
// Simply put they should bracket the area being projected. |
// |
// google is your friend to find out more |
// |
function configLambertProjection ($falseEasting, $falseNorthing, |
$longOfOrigin, $latOfOrigin, |
$firstStdParallel, $secondStdParallel) |
{ |
$this->falseEasting = $falseEasting; |
$this->falseNorthing = $falseNorthing; |
$this->longOfOrigin = $longOfOrigin; |
$this->latOfOrigin = $latOfOrigin; |
$this->firstStdParallel = $firstStdParallel; |
$this->secondStdParallel = $secondStdParallel; |
} |
//------------------------------------------------------------------------------ |
// |
// Convert Longitude/Latitude to Lambert Conic Easting/Northing |
// |
// This routine will convert a Latitude/Longitude coordinate to an Northing/ |
// Easting coordinate on a Lambert Conic Projection. The configLambertProjection() |
// function should have been called prior to this one to setup the specific |
// parameters for the projection. The Northing/Easting parameters calculated are |
// in meters (because the datum used is in meters) and are relative to the |
// falseNorthing/falseEasting coordinate. Which in turn is relative to the |
// Lat/Long of origin The formula were obtained from URL: |
// http://www.ihsenergy.com/epsg/guid7_2.html. |
// Code was written by Brenor Brophy, brenor dot brophy at gmail dot com |
// |
function convertLLtoLCC() |
{ |
$e = sqrt($this->e2); |
$phi = deg2rad($this->lat); // Latitude to convert |
$phi1 = deg2rad($this->firstStdParallel); // Latitude of 1st std parallel |
$phi2 = deg2rad($this->secondStdParallel); // Latitude of 2nd std parallel |
$lamda = deg2rad($this->long); // Lonitude to convert |
$phio = deg2rad($this->latOfOrigin); // Latitude of Origin |
$lamdao = deg2rad($this->longOfOrigin); // Longitude of Origin |
$m1 = cos($phi1) / sqrt(( 1 - $this->e2*sin($phi1)*sin($phi1))); |
$m2 = cos($phi2) / sqrt(( 1 - $this->e2*sin($phi2)*sin($phi2))); |
$t1 = tan((pi()/4)-($phi1/2)) / pow(( ( 1 - $e*sin($phi1) ) / ( 1 + $e*sin($phi1) )),$e/2); |
$t2 = tan((pi()/4)-($phi2/2)) / pow(( ( 1 - $e*sin($phi2) ) / ( 1 + $e*sin($phi2) )),$e/2); |
$to = tan((pi()/4)-($phio/2)) / pow(( ( 1 - $e*sin($phio) ) / ( 1 + $e*sin($phio) )),$e/2); |
$t = tan((pi()/4)-($phi /2)) / pow(( ( 1 - $e*sin($phi ) ) / ( 1 + $e*sin($phi ) )),$e/2); |
$n = (log($m1)-log($m2)) / (log($t1)-log($t2)); |
$F = $m1/($n*pow($t1,$n)); |
$rf = $this->a*$F*pow($to,$n); |
$r = $this->a*$F*pow($t,$n); |
$theta = $n*($lamda - $lamdao); |
$this->lccEasting = $this->falseEasting + $r*sin($theta); |
$this->lccNorthing = $this->falseNorthing + $rf - $r*cos($theta); |
} |
//------------------------------------------------------------------------------ |
// |
// Convert Easting/Northing on a Lambert Conic projection to Longitude/Latitude |
// |
// This routine will convert a Lambert Northing/Easting coordinate to an |
// Latitude/Longitude coordinate. The configLambertProjection() function should |
// have been called prior to this one to setup the specific parameters for the |
// projection. The Northing/Easting parameters are in meters (because the datum |
// used is in meters) and are relative to the falseNorthing/falseEasting |
// coordinate. Which in turn is relative to the Lat/Long of origin The formula |
// were obtained from URL http://www.ihsenergy.com/epsg/guid7_2.html. Code |
// was written by Brenor Brophy, brenor dot brophy at gmail dot com |
// |
function convertLCCtoLL() |
{ |
$e = sqrt($this->e2); |
$phi1 = deg2rad($this->firstStdParallel); // Latitude of 1st std parallel |
$phi2 = deg2rad($this->secondStdParallel); // Latitude of 2nd std parallel |
$phio = deg2rad($this->latOfOrigin); // Latitude of Origin |
$lamdao = deg2rad($this->longOfOrigin); // Longitude of Origin |
$E = $this->lccEasting; |
$N = $this->lccNorthing; |
$Ef = $this->falseEasting; |
$Nf = $this->falseNorthing; |
$m1 = cos($phi1) / sqrt(( 1 - $this->e2*sin($phi1)*sin($phi1))); |
$m2 = cos($phi2) / sqrt(( 1 - $this->e2*sin($phi2)*sin($phi2))); |
$t1 = tan((pi()/4)-($phi1/2)) / pow(( ( 1 - $e*sin($phi1) ) / ( 1 + $e*sin($phi1) )),$e/2); |
$t2 = tan((pi()/4)-($phi2/2)) / pow(( ( 1 - $e*sin($phi2) ) / ( 1 + $e*sin($phi2) )),$e/2); |
$to = tan((pi()/4)-($phio/2)) / pow(( ( 1 - $e*sin($phio) ) / ( 1 + $e*sin($phio) )),$e/2); |
$n = (log($m1)-log($m2)) / (log($t1)-log($t2)); |
$F = $m1/($n*pow($t1,$n)); |
$rf = $this->a*$F*pow($to,$n); |
$r_ = sqrt( pow(($E-$Ef),2) + pow(($rf-($N-$Nf)),2) ); |
$t_ = pow($r_/($this->a*$F),(1/$n)); |
$theta_ = atan(($E-$Ef)/($rf-($N-$Nf))); |
$lamda = $theta_/$n + $lamdao; |
$phi0 = (pi()/2) - 2*atan($t_); |
$phi1 = (pi()/2) - 2*atan($t_*pow(((1-$e*sin($phi0))/(1+$e*sin($phi0))),$e/2)); |
$phi2 = (pi()/2) - 2*atan($t_*pow(((1-$e*sin($phi1))/(1+$e*sin($phi1))),$e/2)); |
$phi = (pi()/2) - 2*atan($t_*pow(((1-$e*sin($phi2))/(1+$e*sin($phi2))),$e/2)); |
$this->lat = rad2deg($phi); |
$this->long = rad2deg($lamda); |
} |
//------------------------------------------------------------------------------ |
// This is a useful function that returns the Great Circle distance from the |
// gPoint to another Long/Lat coordinate |
// |
// Result is returned as meters |
// |
function distanceFrom($lon1, $lat1) |
{ |
$lon1 = deg2rad($lon1); $lat1 = deg2rad($lat1); // Added in 1.3 |
$lon2 = deg2rad($this->Long()); $lat2 = deg2rad($this->Lat()); |
$theta = $lon2 - $lon1; |
$dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta)); |
// Alternative formula supposed to be more accurate for short distances |
// $dist = 2*asin(sqrt( pow(sin(($lat1-$lat2)/2),2) + cos($lat1)*cos($lat2)*pow(sin(($lon1-$lon2)/2),2))); |
return ( $dist * 6366710 ); // from http://williams.best.vwh.net/avform.htm#GCF |
} |
//------------------------------------------------------------------------------ |
// This function also calculates the distance between two points. In this case |
// it just uses Pythagoras's theorm using TM coordinates. |
// |
function distanceFromTM(&$pt) |
{ |
$E1 = $pt->E(); $N1 = $pt->N(); |
$E2 = $this->E(); $N2 = $this->N(); |
$dist = sqrt(pow(($E1-$E2),2)+pow(($N1-$N2),2)); |
return $dist; |
} |
//------------------------------------------------------------------------------ |
// This function geo-references a geoPoint to a given map. This means that it |
// calculates the x,y pixel coordinate that coresponds to the Lat/Long value of |
// the geoPoint. The calculation is done using the Transverse Mercator(TM) |
// coordinates of the gPoint with respect to the TM coordinates of the center |
// point of the map. So this only makes sense if you are using Local TM |
// projection. |
// |
// $rX & $rY are the pixel coordinates that corespond to the Northing/Easting |
// ($rE/$rN) coordinate it is to this coordinate that the point will be |
// geo-referenced. The $LongOrigin is needed to make sure the Easting/Northing |
// coordinates of the point are correctly converted. |
// |
function gRef($rX, $rY, $rE, $rN, $Scale, $LongOrigin) |
{ |
$this->convertLLtoTM($LongOrigin); |
$x = (($this->E() - $rE) / $Scale) // The easting in meters times the scale to get pixels |
// is relative to the center of the image so adjust to |
+ ($rX); // the left coordinate. |
$y = $rY - // Adjust to bottom coordinate. |
(($rN - $this->N()) / $Scale); // The northing in meters |
// relative to the equator. Subtract center point northing |
// to get relative to image center and convert meters to pixels |
$this->setXY((int)$x,(int)$y); // Save the geo-referenced result. |
} |
} // end of class gPoint |
?> |
/tags/v5.7-arrayanal/scripts/modules/sophy/bibliotheque/Dao.php |
---|
New file |
0,0 → 1,175 |
<?php |
class Dao extends Bdd { |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Requête d'intégration sur table sophy_publication |
public function integrerBiblio($biblio){ |
$biblio = array_map(array($this, 'proteger'), $biblio); |
$requete = 'INSERT INTO sophy_publication VALUES ('.implode(', ', $biblio).');'; |
$resultat = $this->requeter($requete); |
if ($resultat === false) { |
$info = $biblio['id_publi']." n'est pas intégrée.\n"; |
} else { |
$info = $biblio['id_publi']." est intégrée.\n"; |
} |
return $info; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Requête d'intégration sur table sophy_tableau |
public function integrerTableau($titre) { |
$titre = array_map(array($this, 'proteger'), $titre); |
$requete_integre_tableau = 'INSERT INTO sophy_tableau VALUES ('.implode(', ', $titre).');'; |
$reponse_requete_int_tab = $this->requeter($requete_integre_tableau); |
if ($reponse_requete_int_tab === false) { |
$info = "tableau ".$titre['numPubli']."-".$titre['numTableau']." non intégrée."; |
} else { |
$info = ''; |
} |
return $info; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Requêtes sur table sophy_station |
// Requête d'intégration qui retourne l'id de la dernière station insérée (rechercheIdStation) |
public function integrerStation($station) { |
$station = array_map(array($this, 'proteger'), $station); |
$reponse['id_station'] = null; |
$requete_integre_station = 'INSERT INTO sophy_station (`ss_num_source`, `ss_poste_meteo`, `ss_localisation`, |
`ss_latitude`, `ss_pays`, `ss_longitude`,`ss_code_departement`, `ss_altitude`, `ss_code_insee_commune`, |
`ss_ce_precision_geographique`, `ss_systeme_projection`, `ss_latitude_dms`, `ss_longitude_dms`, `ss_latitude_wgs`, |
`ss_longitude_wgs`, `ss_utmNorthing`, `ss_utmEasting`, `ss_utmZone`) VALUES |
('.implode(', ', $station).');'; |
$reponse_requete_int_stat = $this->requeter($requete_integre_station); |
if ($reponse_requete_int_stat === false) { |
$reponse['info'] = "station ".$station['numSource']." non intégrée. $requete_integre_station"; |
} else { |
$reponse['id_station'] = $this->rechercheIdStation(); |
$reponse['info'] = ''; |
} |
return $reponse; |
} |
// Retourne le dernier identifiant de la table station |
public function rechercheIdStation() { |
$requete_select_id = "SELECT MAX(ss_id_station) as idMax FROM sophy_station;"; |
$resultat_requete_id = $this->recuperer($requete_select_id); |
return $resultat_requete_id['idMax']; |
} |
public function rechercherCoordonneesWgs() { |
$requete = "SELECT `ss_longitude_wgs` as longitude, `ss_latitude_wgs` as latitude |
FROM `sophy_station` |
GROUP BY `longitude` , `latitude`"; |
/* Les stations restantes avec coordonnées sans code insee |
SELECT COUNT( * ) AS `Lignes` , `ss_longitude_wgs` , `ss_latitude_wgs` |
FROM `sophy_station` |
WHERE `ss_latitude_wgs` != '' |
AND `ss_code_insee_calculee` =0 |
GROUP BY `ss_longitude_wgs` , `ss_latitude_wgs` |
ORDER BY `Lignes` DESC |
*/ |
$resultat = $this->recupererTous($requete); |
return $resultat; |
} |
public function creerColonneCodeInseeCalculee() { |
$create = "ALTER TABLE `sophy_station` ADD `ss_code_insee_calculee` VARCHAR( 5 ) NOT NULL , |
ADD INDEX ( `ss_code_insee_calculee` )"; |
$this->requeter($create); |
} |
public function ajouterCodeInseeCalculee($latitude, $longitude, $code_insee) { |
$insert = "UPDATE `sophy_station` SET `ss_code_insee_calculee` = '$code_insee' ". |
"WHERE ss_latitude_wgs = '$latitude' AND ss_longitude_wgs = '$longitude'"; |
$this->requeter($insert); |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Requête d'intégration sur table sophy_releve |
public function integrerReleve($titre, $numReleve, $idStation) { |
$requete_integre_releve = "INSERT INTO sophy_releve VALUES (".$titre['numPubli'].", ". |
$titre['numTableau'].", ".$numReleve.", ".$idStation.");"; |
$reponse_requete_int_tab = $this->requeter($requete_integre_releve); |
if ($reponse_requete_int_tab === false) { |
$info = "releve ".$titre['numPubli']."-".$titre['numTableau']."-".$numReleve." non intégrée."; |
echo $requete_integre_releve."\n"; |
} else { |
$info = ''; |
} |
return $info; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Requête d'intégration sur table sophy_observation |
public function integrerObservation($observations) { |
$requete = "INSERT INTO `sophy_observation` (`so_id_publi`, `so_id_tableau`, `so_id_releve`, `so_num_ligne`,". |
" `so_id_taxon`, `so_id_strate`, `so_ce_abondance`) VALUES "; |
foreach ($observations as $plante) { |
if (isset($plante)) { |
foreach ($plante as $observation) { |
$observation = array_map(array($this, 'proteger'), $observation); |
$requete .= " (".implode(', ', $observation)." ),"; |
} |
} |
} |
$requete = substr($requete,0,-1).";"; |
$resultat = $this->requeter($requete); |
if ($resultat === false) { |
echo $requete."\n"; |
$info = " n'est pas intégrée.\n"; |
} else { |
$info = ''; |
} |
return $info; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Requête pour calculer les statistiques sur toutes les tables |
public function getNombreLigne($tables) { |
$requete = null; |
foreach ($tables as $nomTable => $colonnes) { |
$requete = "SELECT COUNT(*) as nombreTotal"; |
foreach ($colonnes as $recherche => $nom) { |
$requete .= ", count(distinct {$recherche}) as {$nom}"; |
} |
$requete .= " FROM {$nomTable}; "; |
$resultat[$nomTable] = $this->recupererTous($requete); |
} |
return $resultat; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Requête de création et d'insertion sur table sophy_tapir |
public function creerTapir() { |
$info = 'Créé'; |
$requete = "DROP TABLE IF EXISTS `sophy_tapir`; |
CREATE table `sophy_tapir` AS |
SELECT CONCAT(_utf8'urn:lsid:tela-botanica.org:sophy:',o.so_id_publi,'.', |
o.so_id_tableau,'.',o.so_id_releve,'.',o.so_num_ligne,'.', |
o.so_id_taxon,'.',o.so_id_strate) AS `guid`, |
CONCAT(o.so_id_publi,'.',o.so_id_tableau,'.',o.so_id_releve,'.', |
o.so_num_ligne,'.',o.so_id_taxon,'.',o.so_id_strate) AS `observation_id`, |
p.sp_date AS observation_date, |
t.st_nom AS nom_scientifique_complet, |
CONCAT(s.ss_code_departement,s.ss_code_insee_commune) AS lieu_commune_code_insee, |
s.ss_localisation AS `lieu_station_nom`, |
s.ss_latitude_wgs AS `lieu_station_latitude`, |
s.ss_longitude_wgs AS `lieu_station_longitude`, |
s.ss_utmEasting AS `lieu_station_utm_est`, |
s.ss_utmNorthing AS `lieu_station_utm_nord`, |
s.ss_utmZone AS `lieu_station_utm_zone`, |
p.sp_auteur AS observateur_nom_complet |
FROM sophy_observation o LEFT JOIN sophy_taxon t ON (o.so_id_taxon = t.st_id_taxon) |
LEFT JOIN sophy_releve r ON (r.sr_id_publi = o.so_id_publi AND r.sr_id_tableau = o.so_id_tableau AND r.sr_id_releve = o.so_id_releve ) |
LEFT JOIN sophy_station s ON (r.sr_id_station = s.ss_id_station) |
LEFT JOIN sophy_publication p ON (r.sr_id_publi = p.sp_id_publi);"; |
$reponse = $this->requeter($requete); |
if ($reponse === false) { |
$info = "Erreur"; |
} |
return $info; |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/sophy/Insertion.php |
---|
New file |
0,0 → 1,906 |
<?php |
// Encodage : UTF-8 |
// +-------------------------------------------------------------------------------------------------------------------+ |
/** |
* Traitement des fichiers de la banque de données SOPHY pour insertion |
* |
* Description : classe permettant d'insérer les tableaux phytosociologiques de la banque de données SOPHY |
* Utilisation : php script.php insertion -a test |
* |
* @category PHP 5.3 |
* @package phytosocio |
//Auteur original : |
* @author Delphine CAUQUIL <delphine@tela-botanica.org> |
* @copyright Copyright (c) 2009, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL-v3 |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2 |
* @version $Id$ |
*/ |
// +-------------------------------------------------------------------------------------------------------------------+ |
class Insertion extends EfloreScript { |
protected $tableauTaxon; |
protected $dao; |
protected $observations; |
// Paramêtres autorisées lors de l'appel au script en ligne de commande |
protected $parametres_autorises = array( |
'-n' => array(true, true, 'Nom du fichier ou du dossier à traiter')); |
protected $param_bd_pour_stat = array( |
'sophy_publication' => array(), |
'sophy_tableau' => array('stab_id_publi' => 'nombrePubli'), |
'sophy_releve' => array( |
'sr_id_publi' => 'nombrePubli', |
'sr_id_publi, sr_id_tableau' => 'nombreTableau', |
'sr_id_station' => 'nombreStation'), |
'sophy_observation' => array( |
'so_id_publi' => 'nombrePubli', |
'so_id_publi, so_id_tableau' => 'nombreTableau', |
'so_id_publi, so_id_tableau, so_id_releve' => 'nombreReleve', |
'so_id_taxon' => 'nombreTaxon'), |
'sophy_station' => array(), |
'sophy_taxon' => array() |
); |
// Composition classique d'un titre de tableau de stations ou phytosociologiques |
protected $format_titre = array( |
'numPubli' => array(0, 4), |
'numTableau' => array(4, 3), |
'nombreStations' => array(7, 3), |
'titrePubli' => array(11, -1), |
'typeTableau' => array(79, 1) |
); |
// Composition classique d'une station |
protected $format_station = array( |
'numSource' => array(0, 4), |
'posteMeteo' => array(4, 5), |
'nomStation' => array(10, 38), |
'latitude' => array(49, 7), |
'codePays' => array(56, 2), |
'longitude' => array(59, 6), |
'codeDept' => array(66, 2), |
'altitude' => array(69, 4), |
'codeCommune' => array(74, 3), |
'precisionGeographique' => array(78, 1), |
'systemeProjection' => array(79, 1), |
'latitude2' => array(80, 8), |
'longitude2' => array(88, 8) |
); |
// Composition classique d'une ligne de tableau phytosociologique |
protected $format_tableau = array( |
0 => array( |
'numLigne' => array(0, 3), |
'idTaxon' => array(3, 5), |
'strate' => array(8, 1), |
'codeFlore' => array(9, 1), |
'abondance_rem' => array(10, 70)), |
2 => array( |
'numSource' => array(0, 5), |
'posteMeteo' => array(5, 3), |
'numLigne' => array(8, 2), |
'codeFournier1' => array(10, 5), |
'abondance1' => array(15, 1), |
'strate1' => array(16, 1), |
'codeFournier2' => array(17, 5), |
'abondance2' => array(22, 1), |
'strate2' => array(23, 1), |
'codeFournier3' => array(24, 5), |
'abondance3' => array(29, 1), |
'strate3' => array(30, 1), |
'codeFournier4' => array(31, 5), |
'abondance4' => array(36, 1), |
'strate4' => array(37, 1), |
'codeFournier5' => array(38, 5), |
'abondance5' => array(43, 1), |
'strate5' => array(44, 1), |
'codeFournier6' => array(45, 5), |
'abondance6' => array(50, 1), |
'strate6' => array(51, 1), |
'codeFournier7' => array(52, 5), |
'abondance7' => array(57, 1), |
'strate7' => array(58, 1), |
'codeFournier8' => array(59, 5), |
'abondance8' => array(64, 1), |
'strate8' => array(65, 1), |
'codeFournier9' => array(66, 5), |
'abondance9' => array(71, 1), |
'strate9' => array(72, 1), |
'codeFournier10' => array(73, 5), |
'abondance10' => array(78, 1), |
'strate10' => array(79, 1)), |
6 => array( |
'numSource' => array(0, 4), |
'posteMeteo' => array(4, 4), |
'numLigne' => array(8, 2), |
'strate1' => array(10, 1), |
'codeFournier1' => array(11, 4), |
'abondance1' => array(16, 1), |
'strate2' => array(17, 1), |
'codeFournier2' => array(18, 4), |
'abondance2' => array(23, 1), |
'strate3' => array(24, 1), |
'codeFournier3' => array(25, 4), |
'abondance3' => array(30, 1), |
'strate4' => array(31, 1), |
'codeFournier4' => array(32, 4), |
'abondance4' => array(37, 1), |
'strate5' => array(38, 1), |
'codeFournier5' => array(39, 4), |
'abondance5' => array(44, 1), |
'strate6' => array(45, 1), |
'codeFournier6' => array(46, 4), |
'abondance6' => array(51, 1), |
'strate7' => array(52, 1), |
'codeFournier7' => array(53, 4), |
'abondance7' => array(58, 1), |
'strate8' => array(59, 1), |
'codeFournier8' => array(60, 4), |
'abondance8' => array(65, 1), |
'strate9' => array(66, 1), |
'codeFournier9' => array(67, 4), |
'abondance9' => array(72, 1), |
'strate10' => array(73, 1), |
'codeFournier10' => array(74, 4), |
'abondance10' => array(79, 1)), |
7 => array( |
'numReleve' => array(2, 3), |
'posteMeteo' => array(7, 3), |
'codeFournier1' => array(10, 4), |
'abondance1' => array(14, 1), |
'strate1' => array(15, 1), |
'codeFournier2' => array(16, 4), |
'abondance2' => array(20, 1), |
'strate2' => array(21, 1), |
'codeFournier3' => array(22, 4), |
'abondance3' => array(26, 1), |
'strate3' => array(27, 1), |
'codeFournier4' => array(28, 4), |
'abondance4' => array(32, 1), |
'strate4' => array(33, 1), |
'codeFournier5' => array(34, 4), |
'abondance5' => array(38, 1), |
'strate5' => array(39, 1), |
'codeFournier6' => array(40, 4), |
'abondance6' => array(44, 1), |
'strate6' => array(45, 1), |
'codeFournier7' => array(46, 4), |
'abondance7' => array(50, 1), |
'strate7' => array(51, 1), |
'codeFournier8' => array(52, 4), |
'abondance8' => array(56, 1), |
'strate8' => array(57, 1), |
'codeFournier9' => array(58, 4), |
'abondance9' => array(62, 1), |
'strate9' => array(63, 1), |
'codeFournier10' => array(64, 4), |
'abondance10' => array(68, 1), |
'strate10' => array(69, 1), |
'numLigne' => array(71, 2), |
'codeCarte' => array(73, 7)) |
); |
// +-------------------------------------------------------------------------------------------------------------------+ |
public function executer() { |
include_once dirname(__FILE__).'/bibliotheque/Dao.php'; |
Config::charger(dirname(__FILE__).'/sophy.ini'); |
$this->dao = new Dao(); |
// Récupération de paramétres |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'testDossier' : |
$this->executerTestDossier(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
case 'biblio' : |
$this->executerBiblio(); |
break; |
case 'station' : |
include_once dirname(__FILE__).'/bibliotheque/gPoint.php'; |
$this->executerStation(); |
break; |
case 'stationCodeInsee' : |
$this->executerStationCodeInsee(); |
break; |
case 'tableau' : |
include_once dirname(__FILE__).'/bibliotheque/TaxonDao.php'; |
$this->tableauTaxon = new TaxonDao(); |
$this->executerTableau(); |
break; |
case 'stats' : |
$this->executerStats(); |
break; |
case 'tapir' : |
$info = $this->dao->creerTapir(); |
$this->traiterErreur($info); |
break; |
default : |
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd)); |
} |
} |
protected function chargerStructureSql() { |
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSql')); |
$this->executerScripSql($contenuSql); |
} |
protected function executerScripSql($sql) { |
$requetes = Outils::extraireRequetes($sql); |
foreach ($requetes as $requete) { |
$this->getBdd()->requeter($requete); |
} |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS sophy_abondance, `sophy_bdnff`, `sophy_bryophyte`, `sophy_ciff`, ". |
"`sophy_ciff_fournier`, `sophy_codefr94`, `sophy_flora_europea`, `sophy_fournier`, `sophy_fournier_bdnff`,". |
" `sophy_observation`, `sophy_precision_geo`, `sophy_publication`, `sophy_releve`, `sophy_station`, `sophy_strate`,". |
" `sophy_syntri`, `sophy_syntri_fournier`, `sophy_tableau`, `sophy_taxon`"; |
$this->getBdd()->requeter($requete); |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// vérifie qu'il n'y est pas de fichier en double dans le dossier |
// à faire avant d'insérer un nouveau dossier |
private function executerTestDossier() { |
$nomDossier = Config::get('dossierDonneesSophy').$this->getParametre('n'); |
if (file_exists($nomDossier) === true) { |
if (is_dir($nomDossier)) { |
if ($dossierOuvert = opendir($nomDossier) ) { |
while ( ($nomFichier = readdir($dossierOuvert)) !== false) { |
if ( !is_dir($nomFichier) ) { |
if (preg_match('/^[ST]{1,2}(\d{2}1)(\d{2}0)\.*/', $nomFichier, $match)) { |
// fichier normal type 001 à 010 |
} elseif (preg_match('/^([ST]{1,2})(\d{3})(\d{3})\.*/', $nomFichier, $match)) { |
if (($match[1]=='ST' || $match[1]=='T') && ($match[3] - $match[2] == 1)) { |
// fichier normal type 1000 à 1010 |
} else { |
$this->traiterErreur("Le fichier $nomFichier risque d'être en double."); |
} |
} |
} |
} |
closedir($dossierOuvert); |
} else { |
$this->traiterErreur("Le dossier $nomDossier n'a pas pu être ouvert."); |
} |
} else { |
$this->traiterErreur("$nomDossier n'est pas un dossier."); |
} |
} else { |
$this->traiterErreur("Le dossier $nomDossier est introuvable."); |
} |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement du fichier biblio format csv |
// /opt/lampp/bin/php cli.php sophy/insertion -a biblio -n ./../donnees/sophy/BIBLIO.csv |
private function executerBiblio() { |
// Parcours le fichier .csv et enregistre chaque ligne dans un tableau. |
$nomFichier = Config::get('dossierDonneesSophy').'BIBLIO.csv'; |
if ($nomFichier && file_exists($nomFichier) ){ |
$extensionFichier = strtolower(strrchr($nomFichier, '.')); |
if ($extensionFichier === ".csv"){ |
$file = new SplFileObject($nomFichier); |
$file->setFlags(SplFileObject::SKIP_EMPTY); |
$i = 0; |
echo "Traitement de la biblio : "; |
while (!$file->eof()){ |
$ligne_csv = $file->fgetcsv(); |
if (preg_match('/^\d+$/', $ligne_csv[0])){ |
// récupére les colonnes du csv pour les transformer en table publication |
$biblio = $this->transformerBiblio($ligne_csv); |
// integre les publications à la bdd |
$info = $this->dao->integrerBiblio($biblio); |
$this->traiterInfo($info); |
} |
echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++; |
} |
echo "\n"; |
} else { |
$this->traiterErreur("Le fichier de références bibliographiques : $nomFichier n'est pas au format csv."); |
} |
} else { |
$this->traiterErreur("Le fichier de références bibliographiques : $nomFichier n'existe pas."); |
} |
} |
private function transformerBiblio($ligne_csv){ |
$biblio['id_publi'] = $ligne_csv[0]; |
$biblio['auteur'] = $ligne_csv[2].' '.$ligne_csv[3]; |
$biblio['date'] = $ligne_csv[4]; |
$biblio['titre'] = rtrim($ligne_csv[5].' '.$ligne_csv[6].' '.$ligne_csv[7].' '.$ligne_csv[8].' '.$ligne_csv[9]); |
$biblio['revue'] = rtrim($ligne_csv[10].' '.$ligne_csv[11]); |
$biblio['volume'] = $ligne_csv[12]; |
$biblio['tome'] = $ligne_csv[13]; |
$biblio['fascicule'] = $ligne_csv[14]; |
$biblio['page_debut'] = $ligne_csv[15]; |
$biblio['page_fin'] = $ligne_csv[16]; |
return $biblio; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement des fichiers stations |
// /opt/lampp/bin/php cli.php insertion -a station -n ./../doc/donnees/ST/ |
private function executerStation() { |
// transforme les fichiers passés en un tableau |
//de la forme [nom du fichier][index des tableaux][numéro de ligne] |
$tableaux = $this->ouvrirDossier(Config::get('dossierDonneesSophy').'ST/'); |
foreach ($tableaux as $fichier) { |
foreach ($fichier as $tableau) { |
if ($tableau[0] != "") { |
// découpe la première ligne du tableau et insére les données dans la table tableau |
$titre = $this->analyserTitreStation($tableau['0']); |
for ($numReleve = 1; $numReleve < sizeof($tableau); $numReleve++) { |
// découpe les autres lignes, insére les données dans la table station et retourne l'id de la station |
if (trim($tableau[$numReleve]) == '') { |
$id_station = 0; |
} else { |
$id_station = $this->analyserStation($tableau[$numReleve]); |
} |
// insére les données tableau et station dans la table relevé |
$info = $this->dao->integrerReleve($titre, $numReleve, $id_station); |
if ($info != '') { |
$this->traiterErreur($info); |
} |
} |
} |
} |
} |
} |
private function analyserTitreStation($titre) { |
$titreDecoupe = $this->decouperLigne($titre, $this->format_titre); |
$info = $this->dao->integrerTableau($titreDecoupe); |
if ($info != '') { |
$this->traiterErreur($info); |
} |
return $titreDecoupe; |
} |
private function analyserStation($ligne) { |
$ligneDecoupe = $this->decouperLigne($ligne, $this->format_station); |
$ligneDecoupe['latitude_wgs'] = null; |
$ligneDecoupe['longitude_wgs'] = null; |
// vérifie que les zéro du code sont présents |
$ligneDecoupe = $this->analyserCodeDeptComm($ligneDecoupe); |
// transforme les grades paris en degrés décimaux wms |
$ligneDecoupe = $this->analyserCoordGrdParis($ligneDecoupe, $ligne); |
// transforme les degrés sexagécimaux en degrés décimaux |
$ligneDecoupe = $this->analyserCoordDmsWms($ligneDecoupe); |
// transforme les degrés décimaux en UTM |
$ligneDecoupe = $this->transformerCoordWmsUtm($ligneDecoupe); |
$ligneDecoupe['nomStation'] = utf8_encode($ligneDecoupe['nomStation']); |
$retour_requete = $this->dao->integrerStation($ligneDecoupe); |
if ($retour_requete['info'] != '') { |
$this->traiterErreur($retour_requete['info']); |
} |
return $retour_requete['id_station']; |
} |
private function executerStationCodeInsee() { |
$this->dao->creerColonneCodeInseeCalculee(); |
$liste_coordonnees = $this->dao->rechercherCoordonneesWgs(); |
foreach ($liste_coordonnees as $coordonnees) { |
$code_insee = $this->chercherCodeCommune($coordonnees['latitude'], $coordonnees['longitude']); |
if ($code_insee != "") { |
$this->dao->ajouterCodeInseeCalculee($coordonnees['latitude'], $coordonnees['longitude'], $code_insee); |
} |
} |
} |
private function chercherCodeCommune($latitude, $longitude) { |
$code_insee = ''; |
if ($this->testerCoordonneesWgsFrance($latitude, $longitude)) { |
$url_service = "www.tela-botanica.org/service:eflore:0.1/osm/nom-commune". |
"?lat={$latitude}&lon={$longitude}"; |
$url_service = str_replace(',', '.', $url_service); |
$ch = curl_init($url_service); |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
$reponse = curl_exec($ch); |
$reponse = json_decode($reponse); |
if (isset($reponse->codeINSEE)) { |
$code_insee = $reponse->codeINSEE; |
} |
curl_close($ch); |
} |
return $code_insee; |
} |
private function testerCoordonneesWgsFrance($latitude, $longitude) { |
$coord_france = false; |
if ($latitude != '' && $longitude != '') { |
if ($latitude < 51.071667 && $latitude > 41.316667) { |
if ($longitude < 9.513333 && $longitude > -5.140278) { |
$coord_france = true; |
} |
} |
} |
return $coord_france; |
} |
private function analyserCodeDeptComm($ligneDecoupe) { |
if (preg_match('/^\d{2}$/', $ligneDecoupe['codeDept'])) { |
} elseif (preg_match('/^\s{0,1}\d{1,2}\s{0,1}$/',$ligneDecoupe['codeDept'])) { |
$ligneDecoupe['codeDept'] = str_replace(' ', '0', $ligneDecoupe['codeDept']); |
} else { |
$ligneDecoupe['codeDept'] = null; |
} |
if (preg_match('/^\d{3}$/', $ligneDecoupe['codeCommune'])) { |
} elseif (preg_match('/^\s{0,2}\d{1,2,3}\s{0,2}$/', $ligneDecoupe['codeCommune'])) { |
$ligneDecoupe['codeCommune'] = str_replace(' ', '0', $ligneDecoupe['codeCommune']); |
} elseif ($ligneDecoupe['codeDept'] == null) { |
$ligneDecoupe['codeCommune'] = null; |
} else { |
$ligneDecoupe['codeCommune'] = '000'; |
} |
return $ligneDecoupe; |
} |
private function analyserCoordGrdParis($ligneDecoupe, $ligne) { |
if (preg_match('/[\s0]0\.000/', $ligneDecoupe['latitude'], $match)) { |
$ligneDecoupe['latitude'] = null; |
$ligneDecoupe['longitude'] = null; |
} elseif (preg_match('/\d{1,2}\.\d{2,3}/', $ligneDecoupe['latitude'], $match)) {// format souhaité |
$ligneDecoupe['latitude_wgs'] = round($ligneDecoupe['latitude']*0.9, 7); |
$ligneDecoupe['longitude_wgs'] = round($ligneDecoupe['longitude']*0.9+2.3372291, 7); |
} elseif (preg_match('/(\d{2})[\d\s,](\d{3})/', $ligneDecoupe['latitude'], $match)) {//erreur de saisie |
$ligneDecoupe['latitude'] = $match[1].'.'.$match[2]; |
$ligneDecoupe['latitude_wgs'] = round($ligneDecoupe['latitude']*0.9, 7); |
$ligneDecoupe['longitude_wgs'] = round($ligneDecoupe['longitude']*0.9 + 2.3372291, 7); |
} elseif (preg_match('/^[a-zA-Z\s]*[a-zA-Z][a-zA-Z\s]*$/', $ligneDecoupe['latitude'])) {// lat absente + nom long |
$ligneDecoupe['nomStation'] = rtrim(substr($ligne, 10, 48)); |
$ligneDecoupe['latitude'] = null; |
$ligneDecoupe['longitude'] = null; |
} elseif (preg_match('/.[AO].123/', $ligneDecoupe['latitude'], $match)) { |
$ligneDecoupe['latitude'] = null; |
$ligneDecoupe['longitude'] = null; |
} elseif ($ligneDecoupe['latitude'] != null) { |
$ligneDecoupe['latitude'] = null; |
$ligneDecoupe['longitude'] = null; |
} |
return $ligneDecoupe; |
} |
private function analyserCoordDmsWms($ligneDecoupe) { |
if (preg_match('/(\d{1,2})\.(\d{2})\.(\d{2})/', $ligneDecoupe['latitude2'], $match)) { |
$ligneDecoupe['latitude_wgs'] = round($match[1]+($match[2]/60)+($match[3]/3600), 7); |
} |
if (preg_match('/(-{0,1})(\d{1,2})\.(\d{2})\.(\d{2})/', $ligneDecoupe['longitude2'], $match)) { |
$ligneDecoupe['longitude_wgs'] = round($match[2]+($match[3]/60)+($match[4]/3600), 7); |
if ($match[1] == '-') { |
$ligneDecoupe['longitude_wgs'] = -$ligneDecoupe['longitude_wgs']; |
} |
} |
return $ligneDecoupe; |
} |
private function transformerCoordWmsUtm($ligneDecoupe) { |
$ligneDecoupe['utmNorthing'] = null; |
$ligneDecoupe['utmEasting'] = null; |
$ligneDecoupe['utmZone'] = null; |
if ($ligneDecoupe['longitude_wgs'] != null && $ligneDecoupe['latitude_wgs'] != null) { |
$convertisseur = new gPoint(); |
$convertisseur->setLongLat($ligneDecoupe['longitude_wgs'], $ligneDecoupe['latitude_wgs']); |
$convertisseur->convertLLtoTM(); |
$ligneDecoupe['utmNorthing'] = round($convertisseur->N(), 2); |
$ligneDecoupe['utmEasting'] = round($convertisseur->E(), 2); |
$ligneDecoupe['utmZone'] = $convertisseur->Z(); |
} |
return $ligneDecoupe; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Traitement des fichiers tableaux |
// /opt/lampp/bin/php cli.php insertion -a tableau -n ./../doc/donnees/T/ |
private function executerTableau() { |
$tableaux = $this->ouvrirDossier(Config::get('dossierDonneesSophy').'T/'); |
$observations = array(); |
foreach ($tableaux as $fichier) { |
foreach ($fichier as $tableau) { |
if ($tableau[0] != "") { |
$this->observations = array(); |
$titre = $this->decouperLigne($tableau[0], $this->format_titre); |
$this->analyserTableau($tableau, $titre); |
/*$info = $this->dao->integrerObservation($this->observations, $titre); |
if ($info != '') { |
$this->traiterErreur($info); |
}*/ |
} |
} |
} $this->tableauTaxon->integrerTaxons(); |
} |
private function analyserTableau($tableau, $titre) { |
if ($titre['typeTableau'] == ' ') { |
$titre['typeTableau'] = 0; |
} |
switch ($titre['typeTableau']) { |
case 0 : |
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) { |
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['0']); |
if (trim($ligneDecoupe['idTaxon']) == '' && trim($ligneDecoupe['abondance_rem']) == '' && |
preg_match('/^\s+\*N\s*\*\s*$/', $ligneDecoupe['indetermine'])) { |
for ($nombreReleve = 1; $nombreReleve <= $titre['nombreStations']; $nombreReleve ++) { |
$this->observations[$numeroLigne][$nombreReleve]['sc_id_publi'] = $titre['numPubli']; |
$this->observations[$numeroLigne][$nombreReleve]['sc_id_tableau'] = $titre['numTableau']; |
$this->observations[$numeroLigne][$nombreReleve]['sc_id_releve'] = $nombreReleve; |
$this->observations[$numeroLigne][$nombreReleve]['sc_num_ligne'] = $ligneDecoupe['numLigne']; |
$this->observations[$numeroLigne][$nombreReleve]['sc_id_taxon'] = 0; |
$this->observations[$numeroLigne][$nombreReleve]['sc_id_strate'] = 0; |
$this->observations[$numeroLigne][$nombreReleve]['sc_ce_abondance'] = '?'; |
} |
} else { |
$this->creerObservType0($titre, $ligneDecoupe, $numeroLigne); |
} |
} |
for ($nombreReleve = 1; $nombreReleve <= $titre['nombreStations']; $nombreReleve ++) { |
$j = false; |
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) { |
if (isset($this->observations[$numeroLigne][$nombreReleve])) { |
$j = true; |
} |
} |
if ($j == false) { |
$this->observations[0][$nombreReleve]['sc_id_publi'] = $titre['numPubli']; |
$this->observations[0][$nombreReleve]['sc_id_tableau'] = $titre['numTableau']; |
$this->observations[0][$nombreReleve]['sc_id_releve'] = $nombreReleve; |
$this->observations[0][$nombreReleve]['sc_num_ligne'] = 0; |
$this->observations[0][$nombreReleve]['sc_id_taxon'] = 0; |
$this->observations[0][$nombreReleve]['sc_id_strate'] = 0; |
$this->observations[0][$nombreReleve]['sc_ce_abondance'] = '?'; |
} |
} |
break; |
case 2 : |
$numSource = 0; $numReleve = 0; |
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) { |
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['2']); |
if ($ligneDecoupe['numSource'] != $numSource) { |
// $numSource correspond au numero à la station par l'auteur, |
// $numReleve correspond à l'id de la station |
$numSource = $ligneDecoupe['numSource']; |
$numReleve ++; |
} |
if (strlen(trim($tableau[$numeroLigne])) < 10) { |
$this->observations[$numeroLigne][1]['sc_id_publi'] = $titre['numPubli']; |
$this->observations[$numeroLigne][1]['sc_id_tableau'] = $titre['numTableau']; |
$this->observations[$numeroLigne][1]['sc_id_releve'] = $numReleve; |
$this->observations[$numeroLigne][1]['sc_num_ligne'] = 0; |
$this->observations[$numeroLigne][1]['sc_id_taxon'] = 0; |
$this->observations[$numeroLigne][1]['sc_id_strate'] = 0; |
$this->observations[$numeroLigne][1]['sc_ce_abondance'] = '?'; |
} else { |
$this->creerObservType2($titre, $ligneDecoupe, $numReleve, $numeroLigne); |
} |
} |
break; |
case 6 : |
$numSource = 0; $numReleve = 0; |
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) { |
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['6']); |
$num = (preg_match('/[\dA-Z]+\s+[\dA-Z]+/', $ligneDecoupe['numSource'].$ligneDecoupe['posteMeteo'])) |
? ltrim($ligneDecoupe['numSource']) |
: $ligneDecoupe['numSource'].$ligneDecoupe['posteMeteo']; |
if ($num !== $numSource) { |
$numSource = $num; |
$numReleve ++; |
} |
$this->creerObservType2($titre, $ligneDecoupe, $numReleve, $numeroLigne); |
} |
break; |
case 7 : |
$numSource = 0; $numReleve = 0; |
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) { |
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['7']); |
if (trim($ligneDecoupe['numReleve']) !== $numSource) { |
$numSource = trim($ligneDecoupe['numReleve']); |
$numReleve ++; |
} |
$this->creerObservType2($titre, $ligneDecoupe, $numReleve, $numeroLigne); |
} |
break; |
default : |
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) { |
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['0']); |
$this->creerObservType0($titre, $ligneDecoupe); |
} |
break; |
} |
return $ligneDecoupe; |
} |
// crée des observations au format de la table à partir d'un tableau de type standard (0) |
private function creerObservType0($titre, $ligneDecoupe, $numeroLigne) { |
$observation = null; |
// Retourne l'id du taxon dans la bd sophy |
$idTaxon = $this->identifierTaxon($titre['nombreStations'], $ligneDecoupe, $numeroLigne); |
// découpe le champs abondance_rem ou indetermine selon le nombre de relevés |
$remAbondance = substr( |
($ligneDecoupe['abondance_rem'] != null) ? $ligneDecoupe['abondance_rem'] : $ligneDecoupe['indetermine'], |
0, $titre['nombreStations']); |
// si aucun relevé ne contient d'abondance pour un taxon, ajout d'une abondance ? pour ce taxon |
if (trim($remAbondance) == '') { |
$remAbondance = '?'; |
} |
for ($numReleve = 1; $numReleve <= $titre['nombreStations']; $numReleve++) { |
if ($remAbondance === '?' && $numeroLigne === 1) { |
$abondance = '?'; |
} else { |
$abondance = substr($remAbondance, ($numReleve-1), 1); |
} |
if ($abondance != '' && $abondance != ' ') { |
$this->observations[$numeroLigne][$numReleve]['sc_id_publi'] = $titre['numPubli']; |
$this->observations[$numeroLigne][$numReleve]['sc_id_tableau'] = $titre['numTableau']; |
$this->observations[$numeroLigne][$numReleve]['sc_id_releve'] = $numReleve; |
$this->observations[$numeroLigne][$numReleve]['sc_num_ligne'] = $numeroLigne; |
$this->observations[$numeroLigne][$numReleve]['sc_id_taxon'] = $idTaxon; |
if ($ligneDecoupe['strate'] != null) { |
$this->observations[$numeroLigne][$numReleve]['sc_id_strate'] = $ligneDecoupe['strate']; |
} else { |
$this->observations[$numeroLigne][$numReleve]['sc_id_strate'] = 0; |
} |
$this->observations[$numeroLigne][$numReleve]['sc_ce_abondance'] = $abondance; |
} |
} |
} |
// crée des observations au format de la table à partir d'un tableau de type 2, 6 ou 7 (10 plantes en lignes) |
private function creerObservType2($titre, $ligneDecoupe, $numReleve, $numeroLigne) { |
$observation = null; |
for ($i = 1; $i < 11; $i++) { |
// si le numéro de taxon et l'abondance ne sont pas nulls |
if ((($ligneDecoupe['abondance'.$i] == '' || $ligneDecoupe['abondance'.$i] == '0') && |
(trim($ligneDecoupe['codeFournier'.$i]) == '' || $ligneDecoupe['codeFournier'.$i] == '0'))) { |
} else { |
$positionTaxon = $ligneDecoupe['numLigne']*10 + $i - 10; |
$this->observations[$numeroLigne][$positionTaxon]['sc_id_publi'] = $titre['numPubli']; |
$this->observations[$numeroLigne][$positionTaxon]['sc_id_tableau'] = $titre['numTableau']; |
$this->observations[$numeroLigne][$positionTaxon]['sc_id_releve'] = $numReleve; |
$this->observations[$numeroLigne][$positionTaxon]['sc_num_ligne'] = $positionTaxon; |
$idTaxon = str_replace(' ', '0', $ligneDecoupe['codeFournier'.$i]); |
$this->observations[$numeroLigne][$positionTaxon]['sc_id_taxon'] = |
$this->identifierTaxon2($idTaxon, $titre['typeTableau']); |
if ($ligneDecoupe['strate'.$i] != null) { |
$this->observations[$numeroLigne][$positionTaxon]['sc_id_strate'] = $ligneDecoupe['strate'.$i]; |
} else { |
$this->observations[$numeroLigne][$positionTaxon]['sc_id_strate'] = 0; |
} |
if ($ligneDecoupe['abondance'.$i] == '' || $ligneDecoupe['abondance'.$i] == '0') { |
$this->observations[$numeroLigne][$positionTaxon]['sc_ce_abondance'] = '?'; |
} else { |
$this->observations[$numeroLigne][$positionTaxon]['sc_ce_abondance'] = $ligneDecoupe['abondance'.$i]; |
} |
} |
} |
} |
private function identifierTaxon2($idTaxon, $typeTableau) { |
$id = 0; |
if ($typeTableau == 2 && $idTaxon == 75000) { |
$id = $this->tableauTaxon->getId(75000, 'algues'); |
} elseif ($typeTableau == 2 && $idTaxon == 85000) { |
$id = $this->tableauTaxon->getId(85000, 'characees'); |
} elseif ($typeTableau == 2 && $idTaxon == 90000) { |
$id = $this->tableauTaxon->getId(90000, 'bryo'); |
} elseif ($typeTableau == 2 && $idTaxon == 95000) { |
$id = $this->tableauTaxon->getId(95000, 'lichen'); |
} elseif ($typeTableau == 2 && $idTaxon >= 90000) { |
$idTaxon -= 90000; |
$id = $this->tableauTaxon->getId($idTaxon, 'bryo'); |
} elseif ($typeTableau == 2 && $idTaxon >= 20000) { |
$idTaxon -= 20000; |
$id = $this->tableauTaxon->getId($idTaxon, 'floeur'); |
} else { |
if ($typeTableau == 2 && ($idTaxon != '00000' && $idTaxon != '')) { |
$idTaxon = (substr($idTaxon, 0, 2) - 1)*600 + |
(substr($idTaxon, 2, 2) - 11)*10 + (substr($idTaxon, 4, 1) + 1); |
} elseif ($idTaxon != '00000' && $idTaxon != '') { |
$idTaxon = ltrim($idTaxon, "0"); |
} else { |
$idTaxon = 0; |
} |
$id = $this->tableauTaxon->getId($idTaxon, 'fournier'); |
} |
return $id; |
} |
// fonctions nécessaires pour les tableaux de type standard (0) |
private function identifierTaxon($nombreReleves, $ligneDecoupe, $numeroLigne) { |
// decoupe le champs remarque |
if ($ligneDecoupe['abondance_rem'] != null) { |
$rem = trim(substr($ligneDecoupe['abondance_rem'], (int) ltrim($nombreReleves), strlen($ligneDecoupe['abondance_rem']))); |
} else { |
$rem = substr($ligneDecoupe['indetermine'], (int) ltrim($nombreReleves), strlen($ligneDecoupe['indetermine'])); |
} |
$remAnalyse = $this->analyserRemarque($rem, $numeroLigne); |
$id = 0; |
if ($ligneDecoupe['idTaxon'] != null) { |
$idTaxon = str_replace(' ', '0', $ligneDecoupe['idTaxon']); |
switch ($idTaxon) { // probleme code dans les 80000 attentes reponses brisse |
case 0 : $id = $this->recupererId($remAnalyse, 00000); break; |
case 00000 : $id = $this->recupererId($remAnalyse, $idTaxon); break; |
case 20000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'floeur'); break; |
case 75000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'algues'); break; |
case 85000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'characees'); break; |
case 90000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'bryo'); break; |
case 95000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'lichen'); break; |
default : |
if ($idTaxon < 1100) { |
$id = $this->recupererId($remAnalyse, 0); |
}elseif ($idTaxon < 20000) { |
// transformer code fournier en numéro fournier |
$numeroFournier = (substr($idTaxon, 0, 2) - 1)*600 + (substr($idTaxon, 2, 2) - 11)*10 + |
(substr($idTaxon, 4, 1) + 1); |
$id = $this->recupererId($remAnalyse, $numeroFournier, 'fournier'); break; |
} elseif ($idTaxon < 90000) { |
$idTaxon -= 20000; |
$id = $this->recupererId($remAnalyse, $idTaxon, 'floeur'); break; |
} else { |
$idTaxon -= 90000; |
$id = $this->recupererId($remAnalyse, $idTaxon, 'bryo'); break; |
} |
break; |
} |
} else { |
$id = $this->recupererId($remAnalyse, 0); |
} |
return $id; |
} |
private function recupererId($remAnalyse, $idTaxon, $flore = 'ind') { |
if ($remAnalyse['presence'] == true) { |
$id = $this->tableauTaxon->getId($remAnalyse['num'], $remAnalyse['flore'], $remAnalyse['nom'], |
$flore, $idTaxon, $remAnalyse['remarques']); |
} else { |
$id = $this->tableauTaxon->getId($idTaxon, $flore); |
} |
return $id; |
} |
private function analyserRemarque($rem, $numeroLigne) { |
$taxon['presence'] = false; |
if ($rem != '') { |
$taxon['flore'] = 'ind'; |
$taxon['num'] = 0; |
$taxon['nom'] = null; |
$taxon['remarques'] = null; |
$remAsterique = preg_split('/\*/', $rem); |
// recuperer le numero et/ou le nom qui sont en remarque |
foreach ($remAsterique as $morceauRem) { |
if ($morceauRem == 'N000000') { |
} elseif (preg_match('/^[A-Z]{1,2}\s{5,6}$/', $morceauRem)) { |
} elseif (preg_match('/^[\s0]*$/', $morceauRem)) { |
} elseif (preg_match('/^([A-Z]{1,2})([0\s]{5,6})$/', $morceauRem)) { |
} elseif (preg_match('/^[\d\s]{5}\d$/', $morceauRem)) { |
$taxon['num'] = ltrim(str_replace(' ', '0', $morceauRem), '0'); |
$taxon['flore'] = 'syntri'; |
$taxon['presence'] = true; |
} elseif (preg_match('/^\s*(\d[\d\s]+\d)\s*$/', $morceauRem, $match)) { |
$taxon['num'] = ltrim(str_replace(' ', '0', $match[1]), '0'); |
$taxon['flore'] = 'syntri'; |
$taxon['presence'] = true; |
} elseif (preg_match('/^\s*[A-Za-z][a-z\s\.()]+$/', $morceauRem)) { |
$taxon['nom'] = $morceauRem; |
$taxon['presence'] = true; |
} elseif (preg_match('/^\s*("\s*[\s"]*)([A-Za-z][A-Za-z\s\.()]+)$/', $morceauRem, $match)) { |
foreach ($this->observations[$numeroLigne-1] as $obsPrec) { |
$idPrec = $obsPrec['sc_id_taxon']; |
} |
$nombreQuote = substr_count($match[1], '"'); |
$nomPrec = preg_split('/\s/', $this->tableauTaxon->getNom($idPrec)); $nom = ''; |
if (preg_match('/^(x|var|ssp)/', $match[2])) { |
} elseif ($nombreQuote == 2 || $nombreQuote == 4) { |
$nombreQuote = $nombreQuote/2; |
} |
for ($i = 0; $i < $nombreQuote; $i++) { |
if ($i < count($nomPrec)) { |
$nom .= $nomPrec[$i]." "; |
} |
} |
$taxon['nom'] = $nom.$match[2]; |
$taxon['remarques'] = $morceauRem; |
$taxon['presence'] = true; |
} elseif (preg_match('/^([A-Z]{1,2})([\d\s]{4,5}\d)$/', $morceauRem, $match) || |
preg_match('/^(\s{1,2})([\d\s]{4,5}\d)$/', $morceauRem, $match)) { |
switch (trim($match[1])) { |
case 'S' : $taxon['flore'] = 'syntri'; break; |
case 'CI' : $taxon['flore'] = 'ciff'; break; |
case 'C' : $taxon['flore'] = 'codefr94'; break; |
case 'BD' : $taxon['flore'] = 'bdnff'; break; |
case 'N' : $taxon['flore'] = 'syntri'; break; |
case '' : $taxon['flore'] = 'syntri'; break; |
default : $taxon['flore'] = 'ind'; break; |
} |
$taxon['num'] = ltrim(str_replace(' ', '0', $match[2]), '0'); |
$taxon['presence'] = true; |
} else { |
$morceauRem = trim($morceauRem); |
if ($morceauRem != '' && $morceauRem != null) { |
$taxon['remarques'] = $morceauRem; |
$taxon['presence'] = true; |
} |
} |
} |
} |
return $taxon; |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Fonction Statistiques |
private function executerStats() { |
$nombreTotalLignesTable = $this->dao->getNombreLigne($this->param_bd_pour_stat); |
print_r($nombreTotalLignesTable); |
} |
// +-------------------------------------------------------------------------------------------------------------------+ |
// Fonction générale |
private function ouvrirDossier($nomDossier) { |
$tableaux = null; |
if (file_exists($nomDossier) === true) { |
if (is_dir($nomDossier)) { |
if ($dossierOuvert = opendir($nomDossier) ) { |
while ( ($nomFichier = readdir($dossierOuvert)) !== false) { |
if ( !is_dir($nomFichier) ) { |
$nomFichier = $nomDossier.$nomFichier; |
$tableaux[$nomFichier] = $this->ouvrirFichier($nomFichier); |
} |
} |
closedir($dossierOuvert); |
} else { |
$this->traiterErreur("Le dossier $nomDossier n'a pas pu être ouvert."); |
} |
} else { |
$tableaux[$nomDossier] = $this->ouvrirFichier($nomDossier); |
} |
} else { |
$this->traiterErreur("Le dossier $nomDossier est introuvable."); |
} |
return $tableaux; |
} |
// Prend en entree un fichier et retourne un tableau de Tableau phytosocio ou stations |
private function ouvrirFichier($nomFichier) { |
$tableauxDecoupes = null; |
$clefTableau = 0; |
$clefLigne = 0; |
if (file_exists($nomFichier) === true) { |
if ( $fichierOuvert = fopen($nomFichier, 'r') ) { |
while ($ligne = fgets($fichierOuvert)) { |
if (preg_match('/^.*9{10}.*$/', $ligne)) { |
$clefTableau ++ ; |
$clefLigne = 0; |
} else { |
$tableauxDecoupes[$clefTableau][$clefLigne] = rtrim($ligne, " \t"); |
$clefLigne ++; |
} |
} |
fclose($fichierOuvert); |
} else { |
$this->traiterErreur("Le fichier $nomFichier n'a pas pu être ouvert."); |
} |
} else { |
$this->traiterErreur("Le fichier $nomFichier est introuvable."); |
} |
return $tableauxDecoupes; |
} |
// utilise les tableaux format_titre ou format_station pour découper les lignes |
private function decouperLigne($ligne, $format) { |
$ligne = rtrim($ligne); |
$taille = strlen($ligne); |
foreach ($format as $param => $position) { |
// si la taille de la ligne est inférieure à la taille du champs que l'on veut récupérer |
if ($taille < ($position[0]+$position[1])) { |
// on met à null sauf dans certains formats |
$ligneDecoupe[$param] = null; |
if (isset($format['numLigne'])) { |
$ligneDecoupe['indetermine'] = rtrim(substr($ligne, $position[0], $taille)); |
} |
} else { |
$ligneDecoupe[$param] = trim(substr($ligne, $position[0], $position[1])); |
} |
} |
return $ligneDecoupe; |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/sophy/sophy.ini |
---|
New file |
0,0 → 1,20 |
; +------------------------------------------------------------------------------------------------------+ |
; Général |
; Séparateur de dossier |
ds = DIRECTORY_SEPARATOR |
; +------------------------------------------------------------------------------------------------------+ |
; Info sur l'application |
info.nom = Scripts de gestion de la phytosociologie |
; Abréviation de l'application |
info.abr = sophy |
; Version du Framework nécessaire au fonctionnement de cette application |
info.framework.version = 0.2 |
;Encodage de l'application |
appli_encodage = "UTF-8" |
version="2010-12-02" |
dossierDonneesSophy = "{ref:dossierDonneesEflore}{ref:info.abr}/{ref:version}/" |
[fichiers] |
structureSql = "sophy.sql" |
[chemins] |
structureSql = "{ref:dossierDonneesSophy}{ref:fichiers.structureSql}" |
/tags/v5.7-arrayanal/scripts/modules/sophy/Export.php |
---|
New file |
0,0 → 1,224 |
<?php |
// Encodage : UTF-8 |
// +-------------------------------------------------------------------------------------------------------------------+ |
/** |
* Export des données de SOPHY |
* |
* Description : classe permettant d'exporter les tableaux phytosociologiques de la banque de données SOPHY |
* Utilisation : php script.php export |
* |
* @category PHP 5.3 |
* @package phytosocio |
//Auteur original : |
* @author Delphine CAUQUIL <delphine@tela-botanica.org> |
* @copyright Copyright (c) 2009, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL-v3 |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2 |
* @version $Id$ |
* |
* /opt/lampp/bin/php -d memory_limit=2048M cli.php sophy/export -a rien -c publication/strate/flore |
* -f annee:sup:1990/auteur:like:ma%/departement:in:14,50,61,76,27/nomsci:like:trifolium%/fournier:neg: >log.txt |
* |
* |
* |
* export pour le crpf |
* |
* |
* export pour les plantes de la liste rouge des suisses |
* /opt/lampp/bin/php -d memory_limit=2048M cli.php sophy/export -a rien -f nomsci:in:"'Adenophora liliifolia (L.) A. DC.','Adenostyles leucophylla (Willd.) Rchb.','Allium angulosum L.','Allium rotundum L.','Anagallis minima (L.) E. H. L. Krause','Anagallis tenella (L.) L.','Anchusa officinalis L.','Andromeda polifolia L.','Androsace brevis (Hegetschw.) Ces.','Anemone baldensis L.','Anemone sylvestris L.','Anogramma leptophylla (L.) Link','Apium repens (Jacq.) Lag.','Aquilegia einseleana F. W. Schultz','Artemisia nivalis Braun-Blanq.','Asperugo procumbens L.','Asplenium adulterinum Milde','Asplenium billotii F. W. Schultz','Asplenium foreziense Magnier','Astragalus australis (L.) Lam.','Barbarea stricta Andrz.','Blackstonia acuminata (W. D. J. Koch & Ziz) Domin','Bromus grossus DC.','Bufonia paniculata Dubois','Campanula excisa Murith','Campanula latifolia L.','Cardamine kitaibelii Bech.','Cardamine matthioli Moretti','Carduus crispus L.','Carex baldensis L.','Carex fimbriata Schkuhr','Carex hartmanii Cajander','Carpesium cernuum L.','Chenopodium ficifolium Sm.','Chenopodium rubrum L.','Clematis alpina (L.) Mill.','Corydalis intermedia (L.) Mérat','Corydalis solida (L.) Clairv.','Crepis pygmaea L.','Crepis terglouensis (Hacq.) A. Kern.','Cuscuta europaea L.','Cytisus decumbens (Durande) Spach','Cytisus emeriflorus Rchb.','Cytisus nigricans L.','Cytisus scoparius (L.) Link','Deschampsia littoralis (Gaudin) Reut.','Dianthus gratianopolitanus Vill.','Dianthus seguieri Vill.','Diphasiastrum complanatum (L.) Holub','Diplotaxis muralis (L.) DC.','Draba fladnizensis Wulfen','Draba hoppeana Rchb.','Draba ladina Braun-Blanq.','Draba siliquosa M. Bieb.','Draba tomentosa Clairv.','Equisetum ramosissimum Desf.','Eriophorum gracile Roth','Erythronium dens-canis L.','Euonymus latifolius (L.) Mill.','Euphrasia christii Gremli','Falcaria vulgaris Bernh.','Fragaria viridis Duchesne','Gagea pratensis (Pers.) Dumort.','Galeopsis pubescens Besser','Gentiana engadinensis (Wettst.) Braun-Blanq. & Sam.','Geranium rivulare Vill.','Gladiolus imbricatus L.','Gladiolus italicus Mill.','Gladiolus palustris Gaudin','Gratiola officinalis L.','Hammarbya paludosa (L.) Kuntze','Helianthemum salicifolium (L.) Mill.','Iberis saxatilis L.','Inula britannica L.','Inula helvetica Weber','Inula spiraeifolia L.','Isopyrum thalictroides L.','Juniperus sabina L.','Knautia godetii Reut.','Lathyrus sphaericus Retz.','Leucanthemum halleri (Vitman) Ducommun','Leucojum aestivum L.','Linaria alpina subsp. petraea (Jord.) Rouy','Lindernia procumbens (Krock.) Borbás','Linnaea borealis L.','Littorella uniflora (L.) Asch.','Minuartia cherlerioides subsp. rionii (Gremli) Friedrich','Myosotis rehsteineri Wartm.','Myrrhis odorata (L.) Scop.','Nigella arvensis L.','Notholaena marantae (L.) Desv.','Ononis rotundifolia L.','Orchis laxiflora Lam.','Orchis papilionacea L.','Orchis provincialis DC.','Orchis spitzelii W. D. J. Koch','Ostrya carpinifolia Scop.','Pedicularis oederi Hornem.','Peucedanum verticillare (L.) Mert. & W. D. J. Koch','Phyteuma humile Gaudin','Pilularia globulifera L.','Pinguicula grandiflora Lam. s.str.','Polygonum minus Huds.','Potentilla alpicola Fauc.','Potentilla caulescens L.','Potentilla grammopetala Moretti','Potentilla inclinata Vill.','Primula daonensis (Leyb.) Leyb.','Primula latifolia Lapeyr.','Pulmonaria helvetica Bolliger','Ranunculus gramineus L.','Ranunculus parnassiifolius L.','Rhodiola rosea L.','Rhynchospora alba (L.) Vahl','Rumex nivalis Hegetschw.','Sagina nodosa (L.) Fenzl','Saponaria lutea L.','Saxifraga adscendens L.','Saxifraga aphylla Sternb.','Saxifraga diapensioides Bellardi','Saxifraga mutata L.','Scorzonera laciniata L. s.str.','Scutellaria alpina L.','Sedum anacampseros L.','Sedum cepaea L.','Sedum rubens L.','Senecio aquaticus Hill','Senecio halleri Dandy','Senecio incanus subsp. insubricus (Chenevard) Braun-Blanq.','Senecio paludosus L.','Silene pusilla Waldst. & Kit.','Silene suecica (Lodd.) Greuter & Burdet','Sisymbrium supinum L.','Teucrium scordium L.','Thlaspi rotundifolium subsp. corymbosum Gremli','Trifolium saxatile All.','Trochiscanthes nodiflora (All.) W. D. J. Koch','Typha minima Hoppe','Valeriana celtica L.','Valeriana supina Ard.','Viola cenisia L.','Viola elatior Fr.','Viola lutea Huds.','Viola persicifolia Schreb.','Viola pinnata L.','Viola pyrenaica DC.','Woodsia alpina (Bolton) Gray'"/departement:in:14,39,25,90,68,74 |
* |
*/ |
// +-------------------------------------------------------------------------------------------------------------------+ |
class Export extends EfloreScript { |
protected $tableauTaxon; |
protected $dao; |
protected $observations; |
// Paramêtres autorisées lors de l'appel au script en ligne de commande |
protected $parametres_autorises = array( |
'-n' => array(false, 'export', 'Nom du fichier à créer'), |
'-c' => array(false, 'tous', 'Liste des champs à récupérer'), |
'-f' => array(false, true, 'Liste des filtres à executer')); |
// à utiliser dans les valeurs des parametres pour séparer les champs ou filtres |
protected $separateur = "/"; |
// correspondances parametres/champs de la bd |
protected $champs_exportes = array( |
"code_identifiant" => "CONCAT(o.so_id_publi,'.',o.so_id_tableau,'.',o.so_id_releve,'.', |
o.so_num_ligne,'.',o.so_id_taxon,'.',o.so_id_strate) AS code_identifiant", |
"numero_publication" => "sp_id_publi AS numero_publication", |
"publication" => "CONCAT (sp_auteur, '. ', sp_revue, ' ', sp_volume, ' ', sp_tome, ' ', sp_fascicule, ', ', sp_date, |
'. ', sp_titre, ', p.', sp_page_debut, '-', sp_page_fin, '.') AS publication", |
"auteur" => "sp_auteur AS auteur", |
"annee" => "sp_date AS annee", |
"numero_tableau" => "sr_id_tableau AS numero_tableau", |
"numero_releve" => "sr_id_releve AS numero_releve", |
"nom_station" => "ss_localisation AS nom_station", |
"code_insee" => "IF (ss_code_departement != 0, |
CONCAT(ss_code_departement, ss_code_insee_commune), ss_code_insee_calculee) AS code_insee", |
"code_insee_calcule" => "ss_code_insee_calculee AS code_insee_calcule", |
"altitude" => "ss_altitude AS altitude", |
"coordonnees_wgs" => "ss_latitude_wgs, ss_longitude_wgs", |
"coordonnees_utm" => "ss_utmEasting, ss_utmNorthing, ss_utmZone", |
"precision_geographique" => "ss_ce_precision_geographique", |
"nom_scientifique" => "st_nom AS nom_scientifique", |
"flore" => "st_ce_num_fournier, st_ce_num_floeur, st_ce_num_algues, st_ce_num_characees, st_ce_num_bryo, |
st_ce_num_lichen, st_ce_num_syntri, st_ce_num_bdnff, st_ce_num_ciff, st_ce_num_codefr94", |
"strate" => "so_id_strate AS strate", |
"code_abondance" => "so_ce_abondance AS code_abondance"); |
protected $autresChamps = array( |
"signification_precision" => "spg_num_precision, spg_valeur", |
"signification_strate" => "so_id_strate", |
"signification_abondance" => "sa_valeur"); |
protected $filtres_existants = array( |
"annee" => "sp_date", |
"auteur" => "sp_auteur", |
"departement" => "", |
"commune" => "", |
"precisiongeo" => "ss_ce_precision_geographique", |
"nomsci" => "st_nom", |
"fournier" => "st_ce_num_fournier", |
"floeur" => "st_ce_num_floeur", |
"algues" => "st_ce_num_algues", |
"characees" => "st_ce_num_characees", |
"bryo" => "st_ce_num_bryo", |
"lichen" => "st_ce_num_lichen", |
"syntri" => "st_ce_num_syntri", |
"bdnff" => "st_ce_num_bdnff", |
"ciff" => "st_ce_num_ciff", |
"codefr" => "st_ce_num_codefr94"); |
protected $operateurs = array( |
"inf" => "<", |
"sup" => ">", |
"eg" => "=", |
"neg" => "!=", |
"infeg" => "<=", |
"supeg" => ">=", |
"in" => " IN ", |
"like" => " LIKE "); |
// +-------------------------------------------------------------------------------------------------------------------+ |
public function executer() { |
include_once dirname(__FILE__).'/bibliotheque/Dao.php'; |
Config::charger(dirname(__FILE__).'/sophy.ini'); |
$this->dao = new Dao(); |
// Récupération de paramétres |
$requete['nomFichier'] = $this->getParametre('n'); |
$requete['champs'] = $this->formaterChamps($this->getParametre('c')); |
$requete['filtres'] = $this->formaterFiltres($this->getParametre('f')); |
$donnees = $this->recupererDonnees($requete); |
if ($donnees === false) { |
$info = "Pas de données"; |
} else { |
$titre = $this->formaterTitre($this->getParametre('c')); //à revoir |
$this->exportCSV($requete['nomFichier'], $titre, $donnees); |
} |
} |
protected function formaterFiltres($filtres) { |
$where = array(); |
if ($filtres != '') { |
$liste_filtres = explode($this->separateur, $filtres); |
foreach ($liste_filtres as $filtre) { |
$morceaux_filtre = explode(':', $filtre); |
if (isset($this->filtres_existants[$morceaux_filtre[0]])) { |
if (isset($this->operateurs[$morceaux_filtre[1]])) { |
$where[] = $this->traiterFiltres($morceaux_filtre); |
} else { |
echo "L'operateur demandé {$morceaux_filtre[1]} n'existe pas. Les opérateurs existants sont :\n". |
implode(', ', array_keys($this->operateurs)); |
} |
} else { |
echo "Le filtre demandé {$morceaux_filtre[0]} n'existe pas. Les filtres existants sont :\n". |
implode(', ', array_keys($this->filtres_existants)); |
} |
} |
$where = ' WHERE '.implode(' AND ', $where); |
} |
return $where; |
} |
protected function traiterFiltres($morceaux) { |
$where = ''; |
if ($this->operateurs[$morceaux[1]] == ' IN ') { |
$where = $this->operateurs[$morceaux[1]].'('.$morceaux[2].')'; |
} else { |
$where= $this->operateurs[$morceaux[1]].$this->getBdd()->proteger($morceaux[2]); |
} |
switch ($morceaux[0]) { |
case 'departement' : |
$where = "( ss_code_departement".$where. |
" OR substring( `ss_code_insee_calculee`, -5, 2 ) ".$where.") "; |
break; |
case 'commune' : |
$where = "( CONCAT(ss_code_departement, ss_code_insee_commune) ".$where. |
" OR `ss_code_insee_calculee` ".$where.") "; |
break; |
default : $where= $this->filtres_existants[$morceaux[0]].$where; |
break; |
} |
return $where; |
} |
protected function formaterChamps($champs_demandes) { |
$champs_demandes = explode($this->separateur, $champs_demandes); |
if ($champs_demandes[0] == 'tous') { |
$champs = implode(', ', array_values($this->champs_exportes)); |
} else { |
foreach ($champs_demandes as $champ) { |
if (isset($this->champs_exportes[$champ])) { |
$champs[] = $this->champs_exportes[$champ]; |
} else { |
echo "Le champ demandé {$champ} n'existe pas. Les champs existants sont :\n". |
implode(', ', array_keys($this->champs_exportes)); |
} |
} |
$champs = implode(', ', $champs); |
} |
return $champs; |
} |
protected function formaterTitre($champs) { |
$liste_champs = ($champs == 'tous') ? array_keys($this->champs_exportes) :explode(',', $champs); |
foreach ($liste_champs as $champs) { |
switch ($champs) { |
case "flore" : $titre[] = "fournier"; $titre[] = "floeur"; $titre[] = "algues"; $titre[] = "characees"; |
$titre[] = "bryo"; $titre[] = "lichen"; $titre[] = "syntri"; $titre[] = "bdnff"; $titre[] = "ciff"; |
$titre[] = "code france 94"; break; |
case "coordonnees_wgs": $titre[] = "latitude (wgs)"; $titre[] = "longitude (wgs)"; break; |
case "coordonnees_utm" : |
$titre[] = "Easting (utm)"; $titre[] = "Northing (utm)"; $titre[] = "zone utm"; break; |
default: $titre[] = $champs; break; |
} |
} |
return $titre; |
} |
// Requête de création et d'insertion sur table sophy_tapir |
public function recupererDonnees($parametre) { |
$bdd = new Bdd(); |
$requete = "SELECT {$parametre['champs']} |
FROM sophy_observation o LEFT JOIN sophy_taxon t ON (o.so_id_taxon = t.st_id_taxon) |
LEFT JOIN sophy_releve r ON (r.sr_id_publi = o.so_id_publi AND r.sr_id_tableau = o.so_id_tableau AND r.sr_id_releve = o.so_id_releve ) |
LEFT JOIN sophy_station s ON (r.sr_id_station = s.ss_id_station) |
LEFT JOIN sophy_publication p ON (r.sr_id_publi = p.sp_id_publi) |
{$parametre['filtres']}"; |
//INTO OUTFILE '/home/delphine/web/eflore-projets/scripts/{$parametre['nomFichier']}.csv';"; |
echo $requete; |
$reponse = $bdd->recupererTous($requete); |
return $reponse; |
} |
function exportCSV($nomFichier, $titre, $data) { |
$outstream = fopen("./{$nomFichier}.csv", 'w'); |
fputcsv($outstream, $titre, ';', '"'); |
function __outputCSV(&$vals, $key, $filehandler) { |
fputcsv($filehandler, $vals, ';', '"'); //\t = chr(9) |
} |
array_walk($data, '__outputCSV', $outstream); |
fclose($outstream); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/chorodep/Chorodep.php |
---|
New file |
0,0 → 1,629 |
<?php |
// /opt/lampp/bin/php cli.php chorodep -a chargerVersions |
class Chorodep extends EfloreScript { |
protected $nbre_dep = 0; |
private $type_donnee = ''; |
protected $aso_num_nomenc = array(); |
protected $nbre_ligne = 0; |
protected $nbre_plte_presente = 0; |
protected $nbre_plte_a_confirmer = 0; |
protected $nbre_plte_douteux = 0; |
protected $nbre_plte_erreur = 0; |
protected $nbre_plte_disparue = 0; |
protected $nbre_plte_erreur_a_confirmer = 0; |
protected $nc_autres_valeur_champ = 0; |
protected $nc_nbre_plte_presente = 0; |
protected $nc_nbre_plte_a_confirmer = 0; |
protected $nc_nbre_plte_douteux = 0; |
protected $nc_nbre_plte_disparue = 0; |
protected $nc_nbre_plte_erreur = 0; |
protected $nc_nbre_plte_erreur_a_confirmer = 0; |
protected $aso_totaux_dep = array(); |
private $fichier_verif = './chorodep_verif.html'; |
public function executer() { |
try { |
$this->initialiserProjet('chorodep'); |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerVersions(); |
$this->chargerChorodepContributeurs(); |
$this->chargerChorodepSources(); |
$this->chargerChorodepOntologies(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerVersions' : |
$this->chargerVersions(); |
break; |
case 'chargerChorodep' : |
$this->chargerChorodepContributeurs(); |
$this->chargerChorodepSources(); |
$this->chargerChorodepOntologies(); |
break; |
case 'verifierDonnees' : |
$this->initialiserTraitement(); |
$this->verifierDonnees(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function chargerChorodepContributeurs() { |
$chemin = Config::get('chemins.chorodepContributeurs'); |
$table = Config::get('tables.chorodepContributeurs'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 2 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function chargerChorodepSources() { |
$chemin = Config::get('chemins.chorodepSources'); |
$table = Config::get('tables.chorodepSources'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 2 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function chargerChorodepOntologies() { |
$chemin = Config::get('chemins.chorodepOntologies'); |
$table = Config::get('tables.chorodepOntologies'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function chargerVersions() { |
$versions = explode(',', Config::get('versions')); |
$versionsDonnees = explode(',', Config::get('versionsDonnees')); |
foreach ($versions as $id => $version) { |
$versionDonnees = $versionsDonnees[$id]; |
$this->chargerStructureSqlVersion($versionDonnees); |
$this->chargerDonneesVersion($versionDonnees, $version); |
} |
} |
private function chargerStructureSqlVersion($versionDonnees) { |
$fichierSqlTpl = Config::get('chemins.structureSqlVersionTpl'); |
$fichierSql = sprintf($fichierSqlTpl, $versionDonnees, $versionDonnees); |
$contenuSql = $this->recupererContenu($fichierSql); |
$this->executerScripSql($contenuSql); |
} |
private function chargerDonneesVersion($versionDonnees, $version) { |
$fichierTsvTpl = Config::get('chemins.chorodepTpl'); |
$fichierTsv = sprintf($fichierTsvTpl, $versionDonnees, $versionDonnees); |
$tableTpl = Config::get('tables.chorodepTpl'); |
$table = sprintf($tableTpl, $version); |
$champs = Config::get('chorodepChamps'.$version); |
$requete = "LOAD DATA INFILE '$fichierTsv' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
"($champs) "; |
$this->getBdd()->requeter($requete); |
} |
private function initialiserTraitement() { |
//------------------------------------------------------------------------------------------------------------// |
// Récupération des informations à vérifier |
$table = $this->getNomTableDernierVersion(); |
$requete = 'SELECT * '. |
"FROM $table "; |
$taxons = $this->getBdd()->recupererTous($requete); |
$tax_col = $taxons[1]; |
$col = array_keys($tax_col); |
$this->initialiserTableaux($col); |
//------------------------------------------------------------------------------------------------------------// |
// Analyse des données |
echo 'Traitement de la ligne n° :'; |
$i = 0; |
$j = 0; |
$aso_departements_analyses = array(); |
$this->nbre_ligne_avec_guillemet = 0; |
foreach ($taxons as $aso_champs) { |
$nom = $aso_champs['nom_sci']; |
$num_taxo = $aso_champs['num_tax']; |
$num_nomenc = $aso_champs['num_nom']; |
if ($num_nomenc == 'nc') { |
$this->nc_nbre_nom++; |
} else if ($num_nomenc != 'nc') { |
$this->nbre_nom++; |
// Vérification de la nom duplication des numéros nomenclaturaux |
if ( !array_key_exists($num_nomenc, (array) $this->aso_num_nomenc) ) { |
$this->aso_num_nomenc[$num_nomenc]['compteur'] = 1; |
$this->aso_num_nomenc[$num_nomenc]['ligne'] = ($this->nbre_ligne+1); |
} else { |
$this->aso_num_nomenc[$num_nomenc]['compteur']++; |
$this->aso_num_nomenc[$num_nomenc]['ligne'] .= ' - '.($this->nbre_ligne+1); |
} |
} |
foreach ($aso_champs as $cle => $val ) {# Pour chaque département du taxon, on regarde la valeur |
$this->nbre_ligne_avec_guillemet += preg_match('/"/', $val); |
if ( preg_match('/^\d{2}$/', $cle) ) {# Nous vérifions que le nom du champs comprend bien le numéro du département entre () |
$nd = $cle;# Numéro du département |
// Nous comptons le nombre de département en base de données |
if (!isset($aso_departements_analyses[$nd])) { |
$this->nbre_dep_analyse++; |
$aso_departements_analyses[$nd] = $nd; |
} |
if ( $num_nomenc != 'nc' && isset($val) && $val != '') {# Si le taxon n'est pas abscent du département |
if ($val == '1') {# Présent |
// Calcul du nombre de plante ayant un statut "Présent" |
$this->nbre_plte_presente++; |
// Stockage par département du nombre de plante ayant un statut "Présent" |
$this->aso_totaux_dep[$nd]['plte_presente']++; |
// Stockage des informations |
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 3, $this->id_donnee_choro++); |
} else if ($val == '1?') {# Présence à confirmer |
// Calcul du nombre de plante ayant un statut "Présence à confirmer" |
$this->nbre_plte_a_confirmer++; |
// Stockage par département du nombre de plante ayant un statut "Présence à confirmer" |
$this->aso_totaux_dep[$nd]['plte_a_confirmer']++; |
// Stockage des informations |
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 4, $this->id_donnee_choro++); |
} else if (preg_match('/^\s*(?:\?)\s*$/', $val)) {# Douteux |
// Calcul du nombre de plante ayant un statut "Disparu ou douteux" |
$this->nbre_plte_douteux++; |
// Stockage par département du nombre de plante ayant un statut "Douteux" |
$this->aso_totaux_dep[$nd]['plte_douteux']++; |
// Stockage des informations |
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 5, $this->id_donnee_choro++); |
if (preg_match('/(?: \?|\? | \? )/', $val)) {# Douteux |
// Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "?". |
$this->autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} elseif (preg_match('/^\s*(?:#)\s*$/', $val)) {# Erreur |
# Calcul du nombre de plante ayant un statut "Erreur" |
$this->nbre_plte_erreur++; |
# Stockage par département du nombre de plante ayant un statut "Erreur" |
$this->aso_totaux_dep[$nd]['plte_erreur']++; |
# Stockage des informations |
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 6, $this->id_donnee_choro++); |
if (preg_match('/(?: #|# | # )/', $val)) {# Erreur avec espace |
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "#". |
$autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} elseif (preg_match('/^\s*(?:-\|-)\s*$/', $val)) {# Disparu |
# Calcul du nombre de plante ayant un statut "Disparu" |
$this->nbre_plte_disparue++; |
# Stockage par département du nombre de plante ayant un statut "Disparu" |
$this->aso_totaux_dep[$nd]['plte_disparue']++; |
# Stockage des informations |
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 6, $this->id_donnee_choro++); |
if (preg_match('/(?: -\|-|-\|- | -\|- )/', $val)) {# Disparu avec espace |
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "-|-". |
$autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} elseif (preg_match('/^\s*(?:#\?)\s*$/', $val)) {# Erreur à confirmer |
# Calcul du nombre de plante ayant un statut "Erreur à confirmer" |
$this->nbre_plte_erreur_a_confirmer++; |
# Stockage par département du nombre de plante ayant un statut "Erreur à confirmer" |
$this->aso_totaux_dep[$nd]['plte_erreur_a_confirmer']++; |
# Stockage des informations |
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 6, $this->id_donnee_choro++); |
if (preg_match('/^(?:\s+#\?|#\?\s+|\s+#\?\s+)$/', $val)) {# Erreur à confirmer avec espace |
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "#?". |
$autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} else { |
// Ajout de la valeur dans une variable car elle n'est pas conforme. |
$this->autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
$j++; |
} else if (isset($val) && $val != '') { |
if ($val == '1') {# Présent |
// Calcul du nombre de plante 'nc' ayant un statut "Présent" |
$this->nc_nbre_plte_presente++; |
// Stockage par département du nombre de plante 'nc' ayant un statut "Présent" |
$this->aso_totaux_dep[$nd]['nc_plte_presente']++; |
} elseif ($val == '1?') {# Présence à confirmer |
// Calcul du nombre de plante 'nc' ayant un statut "Présence à confirmer" |
$this->nc_nbre_plte_a_confirmer++; |
// Stockage par département du nombre de plante 'nc' ayant un statut "Présence à confirmer" |
$this->aso_totaux_dep[$nd]['nc_plte_a_confirmer']++; |
} elseif (preg_match('/^(?:\?| \?|\? | \?)$/', $val)) {# Douteux |
// Calcul du nombre de plante 'nc' ayant un statut "Douteux" |
$this->nc_nbre_plte_douteux++; |
// Stockage par département du nombre de plante 'nc' ayant un statut "Douteux" |
$this->aso_totaux_dep[$nd]['nc_plte_douteux']++; |
if (preg_match('/(?: \?|\? | \? )/', $val)) {# Douteux |
// Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "?". |
$this->nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} elseif (preg_match('/^(?:#| #|# | # )$/', $val)) {# Erreur |
# Calcul du nombre de plante 'nc' ayant un statut "Erreur" |
$this->nc_nbre_plte_erreur++; |
# Stockage par département du nombre de plante 'nc' ayant un statut "Erreur" |
$this->aso_totaux_dep[$nd]['nc_plte_erreur']++; |
if (preg_match('/(?: #|# | # )/', $val)) {# Erreur avec espace |
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "#". |
$nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} elseif (preg_match('/^\s*(?:-\|-)\s*$/', $val)) {# Disparu |
# Calcul du nombre de plante 'nc' ayant un statut "Disparu" |
$this->nc_nbre_plte_disparue++; |
# Stockage par département du nombre de plante 'nc' ayant un statut "Disparu" |
$this->aso_totaux_dep[$nd]['nc_plte_disparue']++; |
if (preg_match('/(?: -\|-|-\|- | -\|- )/', $val)) {# Disparu avec espace |
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "-|-". |
$nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} elseif (preg_match('/^\s*(?:#\?)\s*$/', $val)) {# Erreur à confirmer |
# Calcul du nombre de plante 'nc' ayant un statut "Erreur à confirmer" |
$this->nc_nbre_plte_erreur_a_confirmer++; |
# Stockage par département du nombre de plante 'nc' ayant un statut "Erreur à confirmer" |
$this->aso_totaux_dep[$nd]['nc_plte_erreur_a_confirmer']++; |
if (preg_match('/^(?:\s+#\?|#\?\s+|\s+#\?\s+)$/', $val)) {# Erreur à confirmer avec espace |
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "#?". |
$nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} else { |
// Ajout de la valeur dans une variable car elle n'est pas conforme. |
$this->nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2). |
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />'; |
} |
} |
// Affichage dans la console du numéro de l'enregistrement analysé. |
//echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++; |
} |
}// fin du foreach |
// Affichage dans la console du numéro de l'enregistrement analysé. |
echo str_repeat(chr(8), ( strlen( $this->nbre_ligne ) + 1 ))."\t".$this->nbre_ligne++; |
} |
echo "\n"; |
} |
private function initialiserTableaux($dep) { |
foreach ($dep as $code_dep) { |
if ( preg_match('/^\d{2}$/', $code_dep) ) { |
$this->aso_totaux_dep[$code_dep]['plte_presente'] = 0; |
$this->aso_totaux_dep[$code_dep]['plte_a_confirmer'] = 0; |
$this->aso_totaux_dep[$code_dep]['plte_douteux'] = 0; |
$this->aso_totaux_dep[$code_dep]['plte_erreur'] = 0; |
$this->aso_totaux_dep[$code_dep]['plte_disparue'] = 0; |
$this->aso_totaux_dep[$code_dep]['plte_erreur_a_confirmer'] = 0; |
$this->aso_totaux_dep[$code_dep]['autres_valeur_champ'] = 0; |
$this->aso_totaux_dep[$code_dep]['nc_plte_presente'] = 0; |
$this->aso_totaux_dep[$code_dep]['nc_plte_a_confirmer'] = 0; |
$this->aso_totaux_dep[$code_dep]['nc_plte_douteux'] = 0; |
$this->aso_totaux_dep[$code_dep]['nc_plte_erreur'] = 0; |
$this->aso_totaux_dep[$code_dep]['nc_plte_disparue'] = 0; |
$this->aso_totaux_dep[$code_dep]['nc_plte_erreur_a_confirmer'] = 0; |
$this->aso_totaux_dep[$code_dep]['nc_autres_valeur_champ'] = 0; |
} |
} |
} |
private function verifierDonnees() { |
// Ouverture du fichier contenant les résultats (sortie) |
if (!$handle = fopen($this->fichier_verif, 'w')) { |
echo "Impossible d'ouvrir le fichier ($this->fichier_verif)"; |
exit; |
} |
// Création de la page |
$page = '<html>'."\n"; |
$page .= '<head>'."\n"; |
$page .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n"; |
$page .= '<title>RESULTAT DE LA VERIFICATION DU FICHIER TABULE DE LA CHOROLOGIE</title>'."\n"; |
$page .= '</head>'."\n"; |
$page .= '<body>'."\n"; |
$page .= '<h1>RESULTAT DE LA VERIFICATION DU FICHIER TABULE DE LA CHOROLOGIE</h1>'."\n"; |
$page .= '<hr/>'."\n"; |
$page .= '<p>'. |
'Adresse fichier analysé : '.'<br />'."\n". |
'</p>'."\n"; |
$page .= '<hr/>'."\n"; |
$page .= '<h2>RESULTATS PROGRAMME DE VERIFICATION</h2>'."\n"; |
$page .= '<p>'. |
'Nom du programme générant ce fichier : '.__FILE__.'<br />'."\n". |
'Nombre de lignes analysées : '.$this->nbre_ligne.'<br />'."\n". |
'Nbre de départements analysés : '.$this->nbre_dep_analyse.'<br />'."\n". |
'Date d\'exécution du programme : '.date('d.m.Y').'<br />'."\n". |
'</p>'."\n"; |
$page .= '<hr/>'."\n"; |
$page .= '<h2>RESULTATS ANALYSE CHOROLOGIE</h2>'."\n"; |
$page .= '<p>'. |
'Nombre de nom "nc" : '.$this->nc_nbre_nom.'<br />'."\n". |
'Nombre de nom : '.$this->nbre_nom.'<br />'."\n". |
'Valeurs autres que 1, 1?, ?, #, #? et -|- : '.$this->autres_valeur_champ.'<br />'."\n". |
'Valeurs autres que 1, 1?, ?, #, #? et -|- pour les plantes nc : <br />'."\n".$this->nc_autres_valeur_champ.'</br>'."\n". |
'</p>'."\n"; |
$page .= '<hr/>'."\n"; |
$page .= '<h2>RESULTATS ANALYSE des CHAMPS</h2>'."\n"; |
$page .= '<p>'. |
'Nombre de guillemets antislashés: '.$this->nbre_ligne_avec_guillemet.'<br />'."\n". |
'</p>'."\n"; |
$page .= '<hr/>'."\n"; |
$page .= '<h2>TABLEAUX</h2>'."\n"; |
// Tableau des numéros nomenclaturaux dupliqués |
$table = '<table><thead><tr><th colspan="3">Tableau des numéros nomenclaturaux dupliqués </th></tr>'; |
$table .= '<tr><th>Numéro nomenclatural</th><th>Nbre d\'itération</th><th>Lignes</th></tr></thead>'; |
$afficher_tab_num_duplique = 0; |
ksort($this->aso_num_nomenc); |
$table .= '<tbody style="text-align: center;">'; |
foreach ($this->aso_num_nomenc as $cle_nomenc => $val ) { |
$ligne = '<tr><td>'.$cle_nomenc.'</td><td>'.$val['compteur'].'</td><td>'.$val['ligne'].'</td></tr>'; |
if ($val['compteur'] > 1) { |
$table .= $ligne; |
$afficher_tab_num_duplique = 1; |
} |
} |
if ( $afficher_tab_num_duplique == 1 ) { |
$page .= $table.'</tbody></table>'; |
} |
// Tableau des résultats par départements |
$table = '<table><thead><tr><th colspan="14">Tableau des résulats par départements</th></tr>'; |
$table .= '<tr><th>Département</th><th>Nbre pltes présentes</th><th>Nbre pltes à confirmer</th>'. |
'<th>Nbre pltes douteuses</th><th>Nbre pltes disparues</th><th>Nbre pltes erreur</th><th>Nbre pltes erreur à confirmer</th>'. |
'<th>Total</th><th>Nbre pltes nc présentes</th><th>Nbre pltes nc à confirmer</th>'. |
'<th>Nbre nc pltes douteuses</th><th>Nbre nc pltes disparues</th><th>Nbre nc pltes erreur</th><th>Nbre nc pltes erreur à confirmer</th></tr></thead>'; |
$table .= '<tbody style="text-align: center;">'; |
ksort($this->aso_totaux_dep); |
foreach ($this->aso_totaux_dep as $cle_dep => $val ) { |
$plt_total = $val{'plte_presente'} + $val{'plte_a_confirmer'} + $val{'plte_douteux'} + $val{'plte_disparue'} + $val{'plte_erreur'} + $val{'plte_erreur_a_confirmer'}; |
$table .= '<tr><td>'.ZgFrDepartements::getNom($cle_dep).' ('.ZgFrDepartements::getIdChaine($cle_dep).') </td>'. |
'<td>'.$val{'plte_presente'}.'</td><td>'.$val{'plte_a_confirmer'}.'</td><td>'.$val{'plte_douteux'}.'</td>'. |
'<td>'.$val{'plte_disparue'}.'</td><td>'.$val{'plte_erreur'}.'</td><td>'.$val{'plte_erreur_a_confirmer'}.'</td><td>'.$plt_total.'</td>'. |
'<td>'.$val{'nc_plte_presente'}.'</td><td>'.$val{'nc_plte_a_confirmer'}.'</td><td>'.$val{'nc_plte_douteux'}.'</td>'. |
'<td>'.$val{'nc_plte_disparue'}.'</td><td>'.$val{'nc_plte_erreur'}.'</td><td>'.$val{'nc_plte_erreur_a_confirmer'}.'</td></tr>'; |
} |
$table .= '<tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td>'. |
'<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>'; |
$plt_total = $this->nbre_plte_presente + $this->nbre_plte_a_confirmer + $this->nbre_plte_douteux + $this->nbre_plte_disparue + $this->nbre_plte_erreur + $this->nbre_plte_erreur_a_confirmer; |
$table .= '<tr><td>Totaux : '.$this->nbre_dep_analyse.' départements</td><td>'.$this->nbre_plte_presente.'</td>'. |
'<td>'.$this->nbre_plte_a_confirmer.'</td><td>'.$this->nbre_plte_douteux.'</td><td>'.$this->nbre_plte_disparue.'</td>'. |
'<td>'.$this->nbre_plte_erreur.'</td><td>'.$this->nbre_plte_erreur_a_confirmer.'</td><td>'.$plt_total.'</td>'. |
'<td>'.$this->nc_nbre_plte_presente.'</td>'.'<td>'.$this->nc_nbre_plte_a_confirmer.'</td>'. |
'<td>'.$this->nc_nbre_plte_douteux.'</td><td>'.$this->nc_nbre_plte_disparue.'</td><td>'.$this->nc_nbre_plte_erreur.'</td><td>'.$this->nc_nbre_plte_erreur_a_confirmer.'</td></tr>'; |
$table .= '<tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td>'. |
'<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>'; |
$total_nbre_plte = ($this->nbre_plte_presente + $this->nbre_plte_a_confirmer + $this->nbre_plte_douteux + $this->nbre_plte_disparue + $this->nbre_plte_erreur + $this->nbre_plte_erreur_a_confirmer); |
$total_nbre_plte_nc = ($this->nc_nbre_plte_presente + $this->nc_nbre_plte_a_confirmer + $this->nc_nbre_plte_douteux + $this->nc_nbre_plte_disparue + $this->nc_nbre_plte_erreur + $this->nc_nbre_plte_erreur_a_confirmer); |
$table .= '<tr><td>Totaux plante / plante nc</td><td colspan="7">'.$total_nbre_plte.'</td>'. |
'<td colspan="6">'.$total_nbre_plte_nc.'</td></tr>'; |
$table .= '<tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td>'. |
'<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>'; |
$plt_total = $this->nbre_plte_presente + $this->nc_nbre_plte_presente + $this->nc_nbre_plte_a_confirmer + $this->nbre_plte_a_confirmer; |
$table .= '<tr><td>Total plantes présentes et à confirmer</td><td colspan="13">'.$plt_total.'</td></tr>'; |
$table .= '<tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td>'. |
'<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>'; |
$plt_total = $this->nbre_plte_presente + $this->nc_nbre_plte_presente; |
$table .= '<tr><td>Total plantes présentes</td><td colspan="13">'.$plt_total.'</td></tr>'; |
$table .= '<tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td>'. |
'<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>'; |
$plt_total = $total_nbre_plte + $total_nbre_plte_nc; |
$table .= '<tr><td>Total données chorologiques</td><td colspan="13">'.$plt_total.'</td></tr>'; |
$table .= '</tbody></table>'; |
$page .= $table; |
$page .= '<hr/>'."\n"; |
$page .= '<h2>NOTES</h2>'."\n"; |
$page .= '<p>'. |
'1.- Chaque champ précédé par "ATTENTION" doit être vide.'."\n". |
'S\'il ne l\'est pas, il y a une erreur'."\n". |
'</p>'."\n"; |
$page .= '</body>'."\n"; |
$page .= '</html>'."\n"; |
// Fermeture de la poignée sur le fichier de sortie |
if (fwrite($handle, $page) === FALSE) { |
echo "Impossible d'écrire dans le fichier ($this->fichier_verif)"; |
exit; |
} |
echo 'Ecriture du fichier de vérification de la chorologie réalisée!'."\n"; |
fclose($handle); |
} |
private function supprimerTous() { |
$tablesChorodep = implode(',', $this->getNomsTablesChorodep()); |
$tableContributeurs = Config::get('tables.chorodepContributeurs'); |
$tableSources = Config::get('tables.chorodepSources'); |
$tableOntologies = Config::get('tables.chorodepOntologies'); |
$requete = "DROP TABLE IF EXISTS chorodep_meta, $tablesChorodep, $tableContributeurs, $tableSources, $tableOntologies "; |
$this->getBdd()->requeter($requete); |
} |
private function getNomsTablesChorodep() { |
$versions = explode(',', Config::get('versions')); |
$tableTpl = Config::get('tables.chorodepTpl'); |
$tablesChorodep = array(); |
foreach ($versions as $version) { |
$tablesChorodep[] = sprintf($tableTpl, $version); |
} |
return $tablesChorodep; |
} |
private function getNomTableDernierVersion() { |
$version = $this->getDerniereVersion(); |
$table = sprintf(Config::get('tables.chorodepTpl'), $version); |
return $table; |
} |
private function getDerniereVersion() { |
$version = array_pop(explode(',', Config::get('versions'))); |
return $version; |
} |
} |
class ZgFrDepartements { |
static private $departements = |
array( |
"01" => array("Ain", "01", 1), |
"02" => array("Aisne", "02", 2), |
"03" => array("Allier", "03", 3), |
"04" => array("Alpes-de-Haute-Provence", "04", 4), |
"05" => array("Hautes-Alpes", "05", 5), |
"06" => array("Alpes-Maritimes", "06", 6), |
"07" => array("Ardèche", "07", 7), |
"08" => array("Ardennes", "08", 8), |
"09" => array("Ariège", "09", 9), |
"10" => array("Aube", "10", 10), |
"11" => array("Aude", "11", 11), |
"12" => array("Aveyron", "12", 12), |
"13" => array("Bouches-du-Rhône", "13", 13), |
"14" => array("Calvados", "14", 14), |
"15" => array("Cantal", "15", 15), |
"16" => array("Charente", "16", 16), |
"17" => array("Charente-Maritime", "17", 17), |
"18" => array("Cher", "18", 18), |
"19" => array("Corrèze", "19", 19), |
"20" => array("Corse", "20", 20), |
"2A" => array("Haute-Corse", "2A", 20), |
"2B" => array("Corse-du-Sud", "2B", 20), |
"21" => array("Côte-d'Or", "21", 21), |
"22" => array("Côtes-d'Armor", "22", 22), |
"23" => array("Creuse", "23", 23), |
"24" => array("Dordogne", "24", 24), |
"25" => array("Doubs","25", 25), |
"26" => array("Drôme", "26", 26), |
"27" => array("Eure", "27", 27), |
"28" => array("Eure-et-Loir", "28", 28), |
"29" => array("Finistère", "29", 29), |
"30" => array("Gard", "30", 30), |
"31" => array("Haute-Garonne", "31", 31), |
"32" => array("Gers", "32", 32), |
"33" => array("Gironde", "33", 33), |
"34" => array("Hérault", "34", 34), |
"35" => array("Ille-et-Vilaine", "35", 35), |
"36" => array("Indre", "36", 36), |
"37" => array("Indre-et-Loire", "37", 37), |
"38" => array("Isère", "38", 38), |
"39" => array("Jura", "39", 39), |
"40" => array("Landes", "40", 40), |
"41" => array("Loir-et-Cher", "41", 41), |
"42" => array("Loire", "42", 42), |
"43" => array("Haute-Loire", "43", 43), |
"44" => array("Loire-Atlantique", "44", 44), |
"45" => array("Loiret", "45", 45), |
"46" => array("Lot", "46", 46), |
"47" => array("Lot-et-Garonne", "47", 47), |
"48" => array("Lozére ", "48", 48), |
"49" => array("Maine-et-Loire", "49", 49), |
"50" => array("Manche", "50", 50), |
"51" => array("Marne", "51", 51), |
"52" => array("Haute-Marne", "52", 52), |
"53" => array("Mayenne", "53", 53), |
"54" => array("Meurthe-et-Moselle", "54", 54), |
"55" => array("Meuse", "55", 55), |
"56" => array("Morbihan", "56", 56), |
"57" => array("Moselle", "57", 57), |
"58" => array("Nièvre", "58", 58), |
"59" => array("Nord", "59", 59), |
"60" => array("Oise", "60", 60), |
"61" => array("Orne", "61", 61), |
"62" => array("Pas-de-Calais", "62", 62), |
"63" => array("Puy-de-Dôme", "63", 63), |
"64" => array("Pyrénées-Atlantiques", "64", 64), |
"65" => array("Hautes-Pyrénées", "65", 65), |
"66" => array("Pyrénées-Orientales", "66", 66), |
"67" => array("Bas-Rhin", "67", 67), |
"68" => array("Haut-Rhin", "68", 68), |
"69" => array("Rhône", "69", 69), |
"70" => array("Haute-Saône", "70", 70), |
"71" => array("Saône-et-Loire", "71", 71), |
"72" => array("Sarthe", "72", 72), |
"73" => array("Savoie", "73", 73), |
"74" => array("Haute-Savoie", "74", 74), |
"75" => array("Paris", "75", 75), |
"76" => array("Seine-Maritime", "76", 76), |
"77" => array("Seine-et-Marne", "77", 77), |
"78" => array("Yvelines", "78", 78), |
"79" => array("Deux-Sèvres", "79", 79), |
"80" => array("Somme", "80", 80), |
"81" => array("Tarn", "81", 81), |
"82" => array("Tarn-et-Garonne", "82", 82), |
"83" => array("Var", "83", 83), |
"84" => array("Vaucluse", "84", 84), |
"85" => array("Vendée", "85", 85), |
"86" => array("Vienne", "86", 86), |
"87" => array("Haute-Vienne", "87", 87), |
"88" => array("Vosges", "88", 88), |
"89" => array("Yonne", "89", 89), |
"90" => array("Territoire-de-Belfort", "90", 90), |
"91" => array("Essonne", "91", 91), |
"92" => array("Hauts-de-Seine", "92", 92), |
"93" => array("Seine-Saint-Denis", "93", 93), |
"94" => array("Val-de-Marne", "94", 94), |
"95" => array("Val-d'Oise", "95", 95), |
"96" => array("aaa", "96", 96), |
"971" => array("Guadeloupe", "971", 971), |
"972" => array("Martinique", "972", 972), |
"973" => array("Guyane", "973", 973), |
"974" => array("Réunion", "974", 974), |
"99" => array("Etranger", "99", 99), |
); |
static public function get() { |
return self::$departements; |
} |
static public function getNom($n) { |
return self::$departements[$n][0]; |
} |
static public function getIdChaine($n) { |
return self::$departements[$n][1]; |
} |
static public function getIdNumerique($n) { |
return (int)self::$departements[$n][2]; |
} |
static public function getIdEflore($n) { |
return (int)self::$departements[$n][3]; |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/chorodep/chorodep.ini |
---|
New file |
0,0 → 1,40 |
; Ajouter les nouvelles version à la suite dans versions et versionsDonnees. |
versions = "2011_04,2012_01,2013_07,2013_08,2013_11" |
versionsDonnees="2011-04-05,2012-01-01,2013-07-22,2013-08-05,2013-11-13" |
dossierTsv = "{ref:dossierDonneesEflore}chorodep/{ref:versionDonnees}/" |
dossierTsvTpl = "{ref:dossierDonneesEflore}chorodep/%s/" |
dossierSql = "{ref:dossierDonneesEflore}chorodep/" |
chorodepChamps2011_04 = "rang, catminat, num_tax, num_nom, nom_sci, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat"; |
chorodepChamps2012_01 = "rang, catminat, num_tax, num_nom, nom_sci, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat"; |
chorodepChamps2013_07 = "rang, catminat,syntaxons, num_tax, num_nom, nom_sci, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat"; |
chorodepChamps2013_08 = "rang, catminat,indication_phytosocio_caracteristique, num_tax, num_nom, nom_sci, chorologie, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat"; |
chorodepChamps2013_11 = "rang, catminat,indication_phytosocio_caracteristique, num_tax, num_nom, nom_sci, chorologie, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat"; |
[tables] |
chorodepMeta = "chorodep_meta" |
chorodepContributeurs = "chorodep_contributeurs" |
chorodepSources = "chorodep_sources" |
chorodepOntologies = "chorodep_ontologies" |
chorodep = "chorodep_v{ref:version}" |
chorodepTpl = "chorodep_v%s" |
[fichiers] |
structureSql = "chorodep.sql" |
structureSqlVersion = "chorodep_v{ref:versionDonnees}.sql" |
structureSqlVersionTpl = "chorodep_v%s.sql" |
chorodepContributeurs = "chorodep_contributeurs.tsv" |
chorodepSources = "chorodep_sources.tsv" |
chorodepOntologies = "chorodep_ontologies.tsv" |
chorodep = "chorodep_v{ref:versionDonnees}.tsv" |
chorodepTpl = "chorodep_v%s.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
structureSqlVersion = "{ref:dossierTsv}{ref:fichiers.structureSqlVersion}" |
structureSqlVersionTpl = "{ref:dossierTsvTpl}{ref:fichiers.structureSqlVersionTpl}" |
chorodepContributeurs = "{ref:dossierSql}{ref:fichiers.chorodepContributeurs}" |
chorodepSources = "{ref:dossierSql}{ref:fichiers.chorodepSources}" |
chorodepOntologies = "{ref:dossierSql}{ref:fichiers.chorodepOntologies}" |
chorodep = "{ref:dossierTsv}{ref:fichiers.chorodep}" |
chorodepTpl = "{ref:dossierTsvTpl}{ref:fichiers.chorodepTpl}" |
/tags/v5.7-arrayanal/scripts/modules/cel/lib-split-auteur.php |
---|
New file |
0,0 → 1,165 |
<?php |
/* |
fork temporaire de cel/jrest/lib/RechercheInfosTaxonBeta.php |
[php-5.4 & co] |
*/ |
require_once('/home/raphael/cel/jrest/lib/Cel.php'); |
// require_once('/home/raphael/cel/jrest/lib/RechercheInfosTaxonBeta.php'); |
require_once('/home/raphael/cel/jrest/lib/NameParser.php'); |
class RechercheInfosTaxonBeta { |
static function getSpaceNoAfter($nom_saisi, $pattern, $offset) { |
if( ($q = strpos($nom_saisi, $pattern, max(0, $offset))) ) { |
// position du premier espace après $pattern, |
// ou position de fin de $pattern autrement |
if(! ($r = strpos($nom_saisi, ' ', $offset + strlen($pattern))) ) |
return $offset + strlen($pattern); |
return $r; |
} |
return FALSE; |
} |
static function supprimerAuteurBis($nom_saisi, &$auteur = null) { |
$strip_pos = 600; |
$before = 600; |
$after = 0; |
// temp var |
$p = $q = NULL; |
if(strpos($nom_saisi, ' ') === FALSE) return FALSE; // pas d'espace, pas de nom d'auteur |
// si "(", break après "Gp)" si présent, sinon, avant "(" |
if( ($p = strpos($nom_saisi, ' Gp)')) ) { |
$after = $p + 4; |
goto sendAuthor; |
} |
// si ".": |
if( ($p = strpos($nom_saisi, '.')) ) { |
// " f. " |
/* SELECT nom_sci, LOCATE(' ', SUBSTRING_INDEX(nom_sci, ' f. ', -1)) AS space_pos |
FROM tb_eflore.bdtfx_v1_02 WHERE nom_sci LIKE '% f. %' HAVING space_pos > 0; */ |
// f. suivi de 1 mot sauf, "Rosa pomifera f. x longicruris" (2) |
/*if( ($q = strpos($nom_saisi, ' f. ', $p - 2)) ) { |
$after = max($after, strpos($nom_saisi, ' ', $q + 4)); // premier espace après ' f. ' |
}*/ |
$after = max($after, self::getSpaceNoAfter($nom_saisi, ' f. ', $p - 2)); |
// " var. " |
// var. n'est pas un repère vraiment adéquat, on sait juste qu'il fait partie du nom sci |
// $after = min($strip_pos, strpos($nom_saisi, ' var. ')); |
$after = max($after, self::getSpaceNoAfter($nom_saisi, ' var. ', $p - 4)); |
// " subsp. " |
// après subsp.: le plus souvent un ' x ', donc pas vraiment de règle (1 ou 2 mots) |
$after = max($after, self::getSpaceNoAfter($nom_saisi, ' subsp. ', $p - 6)); |
// AUTEUR "." |
// autrement, avant un "." dans la partie auteur, il peut y avoir entre 1 et 7 mots à gauche |
// grep -o '^[^.]*\.' liste-auteur.txt|while read f; do grep -o ' '<<<"$f"|wc -l; done|sort -n|tail -1 |
if(!$after) { // si le "." rencontré n'est pas l'un du "nom_sci", c'est de "auteur" |
$before = min($before, $p); |
} |
} |
if( ($p = strpos($nom_saisi, ' x ')) ) { |
$after = max($after, strpos($nom_saisi, ' x ', $p + 3)); |
} |
// " (L.)" et " L." |
if( ($p = strpos($nom_saisi, ' (L.)')) ) { |
$before = min($before, $p); |
} |
// note: on supprime le " L." en amont |
// if( ($p = strpos($nom_saisi, ' L.')) ) $before = min($before, $p); |
// "(" et ")", uniquement dans nom_sci dans le cadre de " Gp)", autrement: auteur |
// XXX: ce cas englobe " (L.)" |
if( ($p = strpos($nom_saisi, '(')) ) { |
$before = min($before, $p); |
} |
// TODO: gérer le " sp." [taxon supérieur], pour l'instant return FALSE |
if( ($p = strpos($nom_saisi, ' sp.')) ) { |
return FALSE; |
} |
// TODO: idem |
if( ($p = strpos($nom_saisi, ' sp ')) ) { |
return FALSE; |
} |
// si "&": auteur, et entre 1 et 10 mots à gauche |
// grep -o '^[^&]*&' liste-auteur.txt|while read f; do grep -o ' '<<<"$f"|wc -l; done|sort -n|tail -1 |
// si ",": auteur, et entre 1 et 5 mots à gauche |
// grep -o '^[^,]*,' liste-auteur.txt|while read f; do grep -o ' '<<<"$f"|wc -l; done|sort -n|tail -1 |
// TRIM auteurs: |
// sed -e 's/[()]//g' liste-auteur.txt|awk '{print $1}'|sed -e 's/[ .,]*$//g'|awk '{print $1}'|sed -r '/^.{0,3}$/d'|sort -u|wc -l |
sendAuthor: |
$x = self::contientAuteur($nom_saisi, $after, $auteur); |
if($x) { |
$n = substr($nom_saisi, 0, min($before, strpos($nom_saisi, $auteur[1]))); |
$auteur = trim(substr($nom_saisi, strlen($n))); |
return trim($n, " \t\n\r\0\x0B(),.&"); |
} |
return FALSE; |
} |
static function contientAuteur($nom_saisi, $start, &$auteur = NULL) { |
static $auteurs; |
// XXX: PHP-5.3 |
// $auteurs = file_get_contents(dirname(__FILE__) . "/../static/auteurs-bdtfx.min.txt"); |
$auteurs = file_get_contents(__DIR__ . "/auteurs-bdtfx.min.txt") or die('no file: auteurs-bdtfx.min.txt'); |
return preg_match('^\s(' . $auteurs . ')^S', $nom_saisi, $auteur, 0, $start); |
} |
static function supprimerAuteur($nom_saisi, &$auteur = null) { |
// TODO: gérer les hybrides |
if(self::estUnHybride($nom_saisi) || self::estUneFormuleHybridite($nom_saisi)) { |
$nom_decoupe = explode(' ', $nom_saisi); |
$derniere_position_hybride = end(array_keys($nom_decoupe, 'x')); |
$nom_saisi_sans_auteur = implode(' ',array_slice($nom_decoupe, 0, $derniere_position_hybride + 2)); |
/* |
var_dump($nom_saisi, $nom_decoupe, $derniere_position_hybride, $nom_saisi_sans_auteur); |
if($auteur != NULL) { |
$c = strpos($nom_saisi, ' x '); |
$auteur = substr($nom_saisi, $c + 3); |
return substr($nom_saisi, 0, $c); |
} |
var_dump(substr($nom_saisi, 0, strpos($nom_saisi, ' x '))); |
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n";*/ |
} else { |
/* Attention le parseur de nom n'est pas fiable à 100% |
mais ça marche dans la plupart des cas |
à part les formules d'hybridité saisies avec un auteur */ |
$nameparser = new NameParser(); |
$auteur = $nameparser->parse_auth($nom_saisi); |
$nom_saisi_sans_auteur = str_replace($auteur, '', $nom_saisi); |
} |
return trim($nom_saisi_sans_auteur); |
} |
static function estUneFormuleHybridite($nom_saisi) { |
return strpos($nom_saisi,' x ') !== false; |
} |
static function estUnHybride($nom_saisi) { |
return strpos($nom_saisi,'x ') === 0; |
} |
} |
/tags/v5.7-arrayanal/scripts/modules/cel/Cel.php |
---|
New file |
0,0 → 1,94 |
<?php |
//declare(encoding='UTF-8'); |
/** |
* Exemple de lancement du script : : |
* /opt/lampp/bin/php cli.php cel -a chargerTous |
* |
* @category php 5.2 |
* @package eFlore/Scripts |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
class Cel extends EfloreScript { |
public function executer() { |
try { |
$this->initialiserProjet('cel'); |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerCel(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
protected function initialiserProjet($projet) { |
$bases = $this->getListeBases(); |
parent::initialiserProjet($projet); |
$this->verifierPresenceBdd($bases); |
} |
private function getListeBases() { |
$requete = "SHOW DATABASES"; |
$bases = $this->getBdd()->recupererTous($requete); |
return $bases; |
} |
private function verifierPresenceBdd($bases) { |
$bddNom = Config::get('bdd_nom'); |
$existe = false; |
foreach ($bases as $base) { |
if ($base['Database'] == $bddNom) { |
$existe = true; |
break; |
} |
} |
if ($existe === false) { |
$message = "Veuillez créer la base de données '$bddNom'."; |
throw new Exception($message); |
} |
} |
public function chargerCel() { |
$tablesCodes = array_keys(Config::get('tables')); |
foreach ($tablesCodes as $code) { |
echo "Chargement de la table : $code\n"; |
$this->chargerFichierTsvDansTable($code); |
} |
} |
private function chargerFichierTsvDansTable($code) { |
$chemin = Config::get('chemins.'.$code); |
$table = Config::get('tables.'.$code); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS cel_meta, cel_images, cel_inventory, cel_mots_cles_images, cel_mots_cles_obs, ". |
"cel_obs_images, locations "; |
$this->getBdd()->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/cel/sphinx-maj.log |
---|
New file |
0,0 → 1,39 |
Array |
( |
[no_nom_sel] => Array |
( |
[count] => 0 |
) |
[not found] => Array |
( |
[count] => 6597 |
) |
[too many] => Array |
( |
[count] => 1065 |
) |
[fixable] => Array |
( |
[count] => 1448 |
) |
[sauvages] => Array |
( |
[count] => 590 |
) |
[sphinx errors] => Array |
( |
[count] => 0 |
) |
[ref pb] => Array |
( |
[count] => 1543 |
) |
) |
total traité: 11243 |
/tags/v5.7-arrayanal/scripts/modules/cel/.current |
---|
New file |
0,0 → 1,9 |
-- conserver ce fichier, il illustre les substitutions effectuées par le Makefile |
-- et permet à celui-ci de déterminer et d'informer quelles bases seront utilisées/concernées par |
-- les changements |
BASEEDIT=`BASEEDIT` |
BASEANNUAIRE=`BASEANNUAIRE` |
BASESOURCE=`BASESOURCE` |
TABLE_BDTFX=TABLEBDTFX |
TABLE_BDTXA=TABLEBDTXA |
TABLE_ISFAN=TABLEISFAN |
/tags/v5.7-arrayanal/scripts/modules/cel/maj-referentiel-201307.sql |
---|
New file |
0,0 → 1,78 |
/* |
Mise à jour de réferentiels NULL ou vides pour les observations dotées d'un nom_sel_nn |
75427 observations trouvées au 2013/07/19 |
Les observations problématiques sont les suivantes: |
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, famille |
FROM `BASEEDIT`.`cel_obs` |
WHERE nom_referentiel IS NULL AND nom_sel != '' AND nom_sel IS NOT NULL AND nom_ret_nn IS NOT NULL; |
Or maj-cleanup-201307.sql reset les valeurs des observations ayant un nom_sel NULL ou '', de plus la préférence de sélection est |
donné au nom_sel (incluant les synonymes) plutôt que nom_ret_nn. |
La requête est donc: |
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, famille |
FROM `BASEEDIT`.`cel_obs` WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL; |
=> 76486 |
*/ |
DROP TEMPORARY TABLE IF EXISTS T_bis; |
DROP PROCEDURE IF EXISTS majreferentiel; |
CREATE TEMPORARY TABLE IF NOT EXISTS T_bis ( INDEX(`nom`(30))) AS \ |
SELECT "bdtfx" AS valid_ref, CONCAT(b.nom_sci, ' ', b.auteur) AS nom, b.num_nom, b.num_taxonomique, b.famille FROM `BASESOURCE`.`TABLEBDTFX` b UNION ALL \ |
SELECT "bdtxa" AS valid_ref, CONCAT(a.nom_sci, ' ', a.auteur) AS nom, a.num_nom, a.num_tax, a.famille FROM `BASESOURCE`.`TABLEBDTXA` a UNION ALL \ |
SELECT "isfan" AS valid_ref, CONCAT(i.nom_sci, ' ', i.auteur) AS nom, i.num_nom, i.num_taxonomique, i.famille FROM `BASESOURCE`.`TABLEISFAN` i; |
/* Donc nous JOINons: |
-- INNER JOIN sur bdtfx: 62633 |
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEBDTFX` b ON (b.num_nom = c.nom_sel_nn) WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL; |
-- INNER JOIN sur bdtxa: 9469 |
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEISFAN` i ON (i.num_nom = c.nom_sel_nn) WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL; |
-- INNER JOIN sur isfan: 1991 |
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEISFAN` i ON (i.num_nom = c.nom_sel_nn) WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL; |
-- INNER JOIN sur les 3 référentiels (bdtxa + bdtfx + isfan): 74093 |
SELECT id_observation, valid_ref, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille FROM `BASEEDIT`.`cel_obs` c INNER JOIN T_bis b ON (b.num_nom = c.nom_sel_nn) WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL; |
*/ |
/* mais de nombreux noms sont exactement présents dans plusieurs référentiels, |
d'où GROUP BY id_observation HAVING count(id_observation) = 1, |
ce qui ne produit plus que 51359 matches (soit 22734 dups) */ |
/* |
SELECT id_observation, valid_ref, nom_sel, nom, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille |
FROM `BASEEDIT`.`cel_obs` c |
INNER JOIN T_bis b |
ON (b.num_nom = c.nom_sel_nn) |
WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL GROUP BY id_observation HAVING count(id_observation) = 1; |
-- 63941, tous bdtfx... |
*/ |
delimiter | |
CREATE PROCEDURE majreferentiel() |
BEGIN |
DECLARE done INT DEFAULT 0; |
DECLARE subst INT DEFAULT 0; |
DECLARE _id_observation bigint(20) DEFAULT 0; |
DECLARE _valid_ref varchar(20) DEFAULT NULL; |
DECLARE cur1 CURSOR FOR SELECT id_observation, valid_ref FROM `BASEEDIT`.`cel_obs` c INNER JOIN T_bis b ON (b.num_nom = c.nom_sel_nn) |
WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL GROUP BY id_observation HAVING count(id_observation) = 1; |
-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; |
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; |
OPEN cur1; |
REPEAT |
FETCH cur1 INTO _id_observation, _valid_ref; |
UPDATE `BASEEDIT`.`cel_obs` c SET nom_referentiel = _valid_ref WHERE id_observation = _id_observation; |
SET subst = subst + 1; |
UNTIL done END REPEAT; |
select subst AS 'nombre de mises à jour de référentiel effectuées'; |
CLOSE cur1; |
END |
| |
delimiter ; |
CALL majreferentiel; |
/tags/v5.7-arrayanal/scripts/modules/cel/dedup-ordre-201307.sql |
---|
New file |
0,0 → 1,109 |
-- suppress dup: |
-- >= 115 au 22/07/2013 |
-- mysql -N <<<"SELECT distinct ce_utilisateur FROM `BASEEDIT`.`cel_obs` GROUP BY ce_utilisateur, ordre HAVING COUNT(*) > 1;" > ordre-dup.txt |
DROP FUNCTION IF EXISTS next_ordre; |
DROP PROCEDURE IF EXISTS ordre_need_update; |
DROP PROCEDURE IF EXISTS update_ordre_user; |
DROP PROCEDURE IF EXISTS update_ordre_users; |
DELIMITER | |
CREATE FUNCTION next_ordre( s1 VARCHAR(255) ) |
RETURNS INT |
READS SQL DATA |
BEGIN |
DECLARE c INT; |
SET c = (SELECT MAX(ordre) + 1 FROM `BASEEDIT`.`cel_obs` where ce_utilisateur = s1); |
RETURN c; |
END |
| |
-- SELECT next_ordre(""); |
CREATE PROCEDURE ordre_need_update(IN _s1 VARCHAR(255), OUT _ordre INT, OUT _c INT, OUT _min_obs INT) |
BEGIN |
SELECT ordre, count(ordre), MIN(id_observation) INTO _ordre, _c, _min_obs FROM `BASEEDIT`.`cel_obs` WHERE ce_utilisateur = _s1 GROUP BY ordre HAVING COUNT(ordre) > 1 LIMIT 1; |
END |
| |
-- SELECT ordre_need_update(""); |
CREATE PROCEDURE update_ordre_user(IN _s1 VARCHAR(255)) |
BEGIN |
DECLARE obs_match int default -1; |
CALL ordre_need_update(_s1, @o, @c, @minobs); |
-- pour chaque ordre dupliqué |
WHILE @o IS NOT NULL DO |
SELECT CONCAT(" ", @o) as " ordre", @c as "(count/doublons)"; |
-- SELECT id_observation FROM `BASEEDIT`.`cel_obs` WHERE ce_utilisateur = _s1 AND ordre = @o AND id_observation != @minobs; |
-- pour chaque obs concernée, exceptée la première, on met à jour l'ordre, |
-- en utilisant next_ordre() |
WHILE obs_match != 0 DO |
-- SELECT CONCAT("== do update on", @o); |
UPDATE `BASEEDIT`.`cel_obs` SET ordre = next_ordre(_s1) |
WHERE ce_utilisateur = _s1 AND ordre = @o AND id_observation != @minobs LIMIT 1; |
SELECT ROW_COUNT() into obs_match; |
-- SELECT @o, obs_match; |
END WHILE; |
-- toutes les observations dupliquées pour l'ordre @o ont été mises à jour |
-- un nouvel ordre à mettre à jour va être obtenu par ordre_need_update() |
-- dont nous restaurons obs_match à une valeur qui n'empêche pas la boucle |
-- contenant l'UPDATE |
SELECT -1 into obs_match; |
CALL ordre_need_update(_s1, @o, @c, @minobs); |
-- SELECT "====X", @o, @c; |
END WHILE; |
END |
| |
-- CALL update_ordre_user(""); |
CREATE PROCEDURE update_ordre_users() |
BEGIN |
DECLARE _nom VARCHAR(255); |
DECLARE subst INT DEFAULT 0; |
DECLARE done INT DEFAULT 1; |
-- temp table |
-- the following fails, pas d'index (see EXPLAIN + http://dba.stackexchange.com/questions/48231 ?) |
-- ( SELECT DISTINCT ce_utilisateur FROM `BASEEDIT`.`cel_obs` GROUP BY ce_utilisateur, ordre HAVING COUNT(*) > 1 ); |
IF (SELECT SUBSTR(version(),3,1)) != 5 THEN |
-- mais celle-ci fonctionne, car l'ordre du GROUP BY correspond à l'INDEX [id_obs] : 16 secondes |
CREATE TEMPORARY TABLE IF NOT EXISTS _temp_users (ce_utilisateur VARCHAR(255)) ENGINE=MEMORY AS \ |
( SELECT DISTINCT ce_utilisateur FROM `BASEEDIT`.`cel_obs` GROUP BY ordre, ce_utilisateur HAVING COUNT(1) > 1 ); |
ELSE |
-- alternativement, comme solution de replis (nécessaire pour MariaDB ?): |
CREATE TEMPORARY TABLE IF NOT EXISTS _temp_users (ce_utilisateur VARCHAR(255)) ENGINE=MEMORY AS \ |
( SELECT DISTINCT ce_utilisateur FROM `BASEEDIT`.`cel_obs` WHERE ce_utilisateur IN \ |
(SELECT ce_utilisateur FROM `BASEEDIT`.`cel_obs` GROUP BY ce_utilisateur, ordre HAVING COUNT(1) > 1) ); |
END IF; |
SELECT COUNT(*) INTO done FROM _temp_users; |
-- la requête principale de sélection des utilisateurs à mettre à jour |
WHILE done > 0 DO |
SELECT ce_utilisateur INTO _nom FROM _temp_users LIMIT 1; |
SELECT _nom AS "utilisateur en mise à jour:"; |
CALL update_ordre_user(_nom); |
SET subst = subst + 1; |
DELETE FROM _temp_users WHERE ce_utilisateur = _nom; |
SELECT COUNT(*) INTO done FROM _temp_users; |
END WHILE; |
SELECT subst AS "utilisateurs mis à jour"; |
END |
| |
DELIMITER ; |
CALL update_ordre_users(); |
DROP FUNCTION IF EXISTS next_ordre; |
DROP PROCEDURE IF EXISTS ordre_need_update; |
DROP PROCEDURE IF EXISTS update_ordre_user; |
DROP PROCEDURE IF EXISTS update_ordre_users; |
-- clef unique sur (id_utilisateur, ordre) |
-- [mais seulement si on a dédupliqué TOUS les utilisateurs, y compris l'utilisateur '' |
-- à voir aussi: maj-hash-id-obs-migr.sql] |
DROP INDEX `id_obs` ON `BASEEDIT`.`cel_obs`; |
CREATE UNIQUE INDEX `id_obs` ON `BASEEDIT`.`cel_obs` (`ce_utilisateur` ASC, `ordre` ASC); |
/tags/v5.7-arrayanal/scripts/modules/cel/cel_references.sql |
---|
New file |
0,0 → 1,128 |
/* |
TODO: |
* fix référentiel: suppression n° de version et uniformisation |
SELECT DISTINCT nom_referentiel, COUNT(id_observation) AS count FROM `BASEEDIT`.`cel_obs` GROUP BY nom_referentiel ORDER BY count DESC; |
* ajout INDEX nom_referentiel(5) sur `BASEEDIT`.`cel_obs` |
* ajout INDEX catminat_code sur baseflor_v2012_12_31 |
* ajout INDEX num_taxon sur nva_v2013_06 |
* fix date: set NULL pour les dates dans le futur |
SELECT courriel_utilisateur, id_observation, date_observation FROM `BASEEDIT`.`cel_obs` WHERE date_observation > NOW(); |
* intégrer les noms non-associés à un taxon (bdtfx where num_taxonomique = '') |
* intégrer les noms non-associés à un taxon (bdtxa where num_tax = '' || num_tax IS NULL) |
CREATE INDEX i_nom_referentiel ON `BASEEDIT`.`cel_obs` (`nom_referentiel`(5)); |
CREATE INDEX i_catminat_code ON baseflor_v2012_12_31 (`catminat_code`); |
CREATE INDEX i_num_taxon ON nva_v2013_06 (`num_taxon`); |
*/ |
-- malheureusement ceci est impossible en SQL d'où l'utilisation du shell-script |
-- SET @destdb = 'tb_cel'; |
-- SET @desttable = 'cel_references'; |
-- -- SET BASEEDIT = `tb_cel`; |
-- SET @dst = CONCAT('`',@destdb,'`','.`',@desttable,'`'); |
DROP TABLE IF EXISTS `BASEEDIT`.`cel_references`; |
CREATE TABLE IF NOT EXISTS `BASEEDIT`.`cel_references` ( |
`referentiel` CHAR(5) NOT NULL COMMENT 'eg: "bdtfx", "bdtfx", "bdtxa", ... No ENUM!', |
-- bdtfx |
`num_nom` INT(9) NOT NULL DEFAULT '0' COMMENT 'depuis bdtfx', |
`num_nom_retenu` VARCHAR(9) DEFAULT NULL COMMENT 'depuis bdtfx', |
-- bdtfx + nvjfl_v2007 + nva_v2013_06 |
`num_taxon` int(9) NOT NULL COMMENT "depuis bdtfx, nvjfl_v2007 et nva_v2013_06 (commun), les noms non-associés ne sont pas intégrés pour l'instant", -- 'relax emacs |
-- bdtfx |
`nom_sci` VARCHAR(500) NOT NULL COMMENT 'depuis bdtfx', |
`auteur` VARCHAR(100) DEFAULT NULL COMMENT 'depuis bdtfx', |
-- `BASEEDIT`.`cel_obs` |
-- `nom_ret_nn` DECIMAL(9,0) DEFAULT NULL COMMENT 'Numéro du nom retenu.', |
-- `nom_ret` VARCHAR(255) DEFAULT NULL, |
-- nvjfl_v2007 (`nom_vernaculaire` text NOT NULL) |
-- mais NULL à cause de nva |
`nom_commun` VARCHAR(60) NULL COMMENT 'nom_vernaculaire pour nvjfl_v2007 et nva_v2013_06', |
-- baseflor_v2012_12_31 |
`catminat_code` varchar(18) DEFAULT 'inconnu' COMMENT 'depuis baseflor_v2012_12_31', |
`ve_lumiere` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_temperature` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_continentalite` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_humidite_atmos` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_humidite_edaph` int(2) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_reaction_sol` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_nutriments_sol` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_salinite` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_texture_sol` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
`ve_mat_org_sol` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31', |
-- baseveg_v2013_01_09 |
`syntaxon` varchar(255) NULL COMMENT 'depuis baseveg_v2013_01_09', |
PRIMARY KEY (`referentiel`, `num_nom`), |
INDEX (`referentiel`(5)), |
INDEX (`num_nom`), |
INDEX (`num_taxon`) |
) ENGINE=MyISAM \ |
DEFAULT CHARSET=utf8 \ |
COMMENT 'table générée par eflore/projets/scripts/modules/cel/cel_references.sql à partir de `TABLEBDTFX`, `TABLEBDTXA` et `TABLEISFAN`'; |
-- tables temporaires |
DROP TEMPORARY TABLE IF EXISTS `T_nvjfl_v2007`, `T_nva_v2013_06`, `T_basevegflor`; |
-- pour nvjfl_v2007, le nom recommandé ou typique est celui pour lequel num_statut = 1 (mais plusieurs sont possibles, d'où le GROUP BY num_taxon) |
CREATE TEMPORARY TABLE T_nvjfl_v2007 ( INDEX(`num_taxon`) ) AS \ |
-- ( SELECT n.num_taxon, n.nom_vernaculaire FROM `BASESOURCE`.`nvjfl_v2007` n WHERE n.code_langue = 'fra' GROUP BY n.num_taxon, n.num_statut HAVING n.num_statut = MAX(n.num_statut) ); |
-- ( SELECT n.num_taxon, n.nom_vernaculaire, n.num_statut as void, MAX(n.num_statut) as void2 FROM `BASESOURCE`.`nvjfl_v2007` n WHERE n.code_langue = 'fra' GROUP BY n.num_taxon HAVING n.num_statut = MAX(n.num_statut) ); |
( SELECT n.num_taxon, n.nom_vernaculaire FROM `BASESOURCE`.`nvjfl_v2007` n WHERE n.code_langue = 'fra' AND n.num_statut = 1 GROUP BY n.num_taxon ); |
-- table temporaire uniquement parce qu'il manque un index-key, autrement le LEFT JOIN ci-dessous est bien trop long |
CREATE TEMPORARY TABLE T_nva_v2013_06 ( INDEX(`num_taxon`) ) AS \ |
-- ( SELECT n.num_taxon, n.nom_vernaculaire FROM `BASESOURCE`.`nva_v2013_06` n WHERE n.code_langue = 'fra' /* DB pb */ AND n.num_taxon IS NOT NULL /* /DB pb */ GROUP BY n.num_nom); -- aggrégat arbitraire car pas de num_statut |
-- pour nva_index, le nom recommandé ou typique est celui pour lequel num_statut = 0 (mais il n'y en a aucun à l'heure actuelle) (mais plusieurs sont possibles, d'où le GROUP BY num_nom) |
( SELECT n.num_taxon, n.nom_vernaculaire FROM `BASESOURCE`.`nva_index_v2_03` n WHERE n.code_langue = 'fra' /* AND n.num_statut = 0 */ GROUP BY n.num_taxon); |
-- JOIN ON num_taxon_originel car INDEX |
-- cf: eflore/projets/donnees/baseflor/2012-12-31/baseflor.sql |
CREATE TEMPORARY TABLE T_basevegflor ( INDEX(`num_nomen`), INDEX(`num_taxon`) ) AS \ |
SELECT f.num_nomen, f.num_taxon, f.catminat_code, f.ve_lumiere, f.ve_temperature, f.ve_continentalite, f.ve_humidite_atmos, f.ve_humidite_edaph, f.ve_reaction_sol, f.ve_nutriments_sol, f.ve_salinite, f.ve_texture_sol, f.ve_mat_org_sol, \ |
v.syntaxon \ |
FROM `BASESOURCE`.`baseflor_v2012_12_31` f LEFT JOIN `BASESOURCE`.`baseveg_v2013_01_09` v ON (f.catminat_code = v.code_catminat AND v.niveau = 'ALL' AND v.syntaxon IS NOT NULL) WHERE f.BDNT = "BDTFX" \ |
GROUP BY f.num_nomen, f.num_taxon; -- group by car plusieurs couple (f.num_nomen, f.num_taxon) peuvent exister dans baseveg_v2013_01_09 or num_nom est PRIMARY dans cel_references |
-- INSERTIONS |
-- pour le futur: attention au numéro taxonomique à 0 (WHERE b.num_taxonomique != '') |
INSERT INTO `BASEEDIT`.`cel_references` (`referentiel`, `num_nom`, `num_nom_retenu`, `num_taxon`, `nom_sci`, `auteur`, `nom_commun`, \ |
`catminat_code`, `ve_lumiere`, `ve_temperature`, `ve_continentalite`, `ve_humidite_atmos`, `ve_humidite_edaph`, \ |
`ve_reaction_sol`, `ve_nutriments_sol`, `ve_salinite`, `ve_texture_sol`, `ve_mat_org_sol`, `syntaxon`) \ |
SELECT "bdtfx", b.num_nom, b.num_nom_retenu, b.num_taxonomique, b.nom_sci, b.auteur, n.nom_vernaculaire, \ |
bf.catminat_code, bf.ve_lumiere, bf.ve_temperature, bf.ve_continentalite, bf.ve_humidite_atmos, bf.ve_humidite_edaph, \ |
bf.ve_reaction_sol, bf.ve_nutriments_sol, bf.ve_salinite, bf.ve_texture_sol, bf.ve_mat_org_sol, bf.syntaxon |
FROM `BASESOURCE`.`TABLEBDTFX` b LEFT JOIN T_nvjfl_v2007 n ON (b.num_taxonomique = n.num_taxon ) \ |
LEFT JOIN T_basevegflor bf ON (b.num_taxonomique = bf.num_taxon AND b.num_nom = bf.num_nomen); |
-- pour le futur: attention au numéro taxonomique à 0 (WHERE b.num_tax IS NOT NULL AND b.num_tax != '') |
INSERT INTO `BASEEDIT`.`cel_references` (`referentiel`, `num_nom`, `num_nom_retenu`, `num_taxon`, `nom_sci`, `auteur`, `nom_commun`) \ |
SELECT "bdtxa", b.num_nom, b.num_nom_retenu, b.num_tax, b.nom_sci, b.auteur, n.nom_vernaculaire FROM `BASESOURCE`.`TABLEBDTXA` b LEFT JOIN T_nva_v2013_06 n ON (b.num_tax = n.num_taxon); |
INSERT INTO `BASEEDIT`.`cel_references` (`referentiel`, `num_nom`, `num_nom_retenu`, `num_taxon`, `nom_sci`, `auteur`) \ |
SELECT "isfan", b.num_nom, b.num_nom_retenu, b.num_taxonomique, b.nom_sci, b.auteur FROM `BASESOURCE`.`TABLEISFAN` b; |
DROP TEMPORARY TABLE IF EXISTS `T_nvjfl_v2007`, `T_nva_v2013_06`, `T_basevegflor`; |
SELECT SUM(theorie.a) AS théorie, pratique.a AS total FROM \ |
(SELECT COUNT(1) AS a FROM `BASESOURCE`.`TABLEBDTFX` UNION ALL \ |
SELECT COUNT(1) AS a FROM `BASESOURCE`.`TABLEBDTXA` UNION ALL \ |
SELECT COUNT(1) AS a FROM `BASESOURCE`.`TABLEISFAN` \ |
) AS theorie, \ |
(SELECT COUNT(1) AS a FROM `BASEEDIT`.cel_references) AS pratique; |
-- bdtfx+bdtxa+isfan: 141181 (2013/07/23) |
/tags/v5.7-arrayanal/scripts/modules/cel/A_LIRE.txt |
---|
New file |
0,0 → 1,117 |
Créer une base de données tb_cel avant de lancer les scripts |
== Sommaire == |
1) à propos de la mise à jour de septembre 2013 |
2) à propos de la table cel_references |
============== |
1) cel_references.sql |
création de la table `cel_references` |
2) maj-struct-201307.sql |
mise à jour des structure de table (les index notamment): |
3) maj-cleanup-201307.sql |
uniformisation des données (lon/lat, date, ...) |
et des NULL vs 0 (pour nom_sel_nn et nom_ret_nn) |
4) fix-utilisateur-32.sql |
5) dedup-ordre-201307.sql |
6) maj-referentiel-201307.sql |
fix le référentiel pour les observation ayant un nom_sel_nn sans nom_referentiel en se |
basant sur une match exact de CONCAT(nom_sci, auteur) parmi bdtfx, bdtxa et isfan |
7) referonosaure.sql |
MAJ des observations (valides) avec les nouvelles données générées, à partir de bdtfx/bdtxa/isfan |
===== |
8) TODO: maj-nom-ret.sql |
TODO (pas sûr) MAJ du référentiel pour les observation ayant un nom_ret sans nom_ret_nn mais dont le nom_ret |
ne match pas le nom_sci en BDTFX (car en BDTFX nom_ret_nn peut être égal à 0 !) |
9) maj-referentiel-und-201307.sql |
MAJ du référentiel pour les observation n'ayant pas de nom_ret_nn (tentative de détermination par nom) |
=== 2: À propos de la table cel_references === |
Celle-ci existe car: |
* les projets doivent être indépendants (eflore, cel, projets nvjfl, ...) |
* les données nécessaires à l'export et à l'import sont massives |
* or les webservices s'appellent parfois récursivement, sont lents et inadaptés |
La conséquence est que la construction d'une table dérivée de bdtfx/bdtxa/isfan contenant |
les informations utiles pour CEL s'avère nécessaire. |
cel_references.sql construit une telle table. |
Suivent quelques éléments de compréhension et exemples de requêtes liés à cette initialisation: |
1) Détermination des noms vernaculaires meilleurs et uniques: |
Ce sont ceux qui ont le num_statut le plus élevé pour un num_taxon donné dans nvjfl_v2007. |
Plusieurs méthodes sont exposées ci-dessous, sachant que le couple (référentiel, num_nom) est la clef |
unique de cel_references. |
Il existe à ce jour 16146 nom communs français distincts, 12312 num_taxon pour code_lang = fra et aucun num_statut NULL en français. |
1.1: |
SELECT n.num_taxon, n.nom_vernaculaire, n.num_statut, n2.num_statut FROM nvjfl_v2007 n LEFT JOIN nvjfl_v2007 n2 ON (n.num_taxon = n2.num_taxon) WHERE n.num_taxon < 32 AND n.code_langue = 'fra' GROUP BY n.num_taxon, n.num_statut HAVING n.num_statut = MAX(n2.num_statut) LIMIT 100; |
# 12311 résultats |
1.2: |
SELECT n.num_taxon, n.nom_vernaculaire FROM nvjfl_v2007 n INNER JOIN nvjfl_v2007 n2 ON (n.num_taxon = n2.num_taxon AND n.code_langue = n2.code_langue AND n.num_statut > n2.num_statut) WHERE n.code_langue = 'fra' GROUP BY n.num_taxon; |
# 2680 résultats |
1.3: |
SELECT n.num_taxon, n.nom_vernaculaire FROM nvjfl_v2007 n LEFT JOIN nvjfl_v2007 n2 ON (n.num_taxon = n2.num_taxon AND n.code_langue = n2.code_langue AND n.num_statut > n2.num_statut) WHERE n.code_langue = 'fra' AND n2.num_statut IS NOT NULL GROUP BY num_taxon; |
# 2680 résultats |
Mais problème ensuite: SELECT n.* from cel_references NATURAL JOIN nvjfl_v2007 n WHERE `nom_commun` = '' AND n.code_langue = 'fra'; |
2) à propos de l'insertion dans cel_references proprement dit: |
Le modèle simplifié théorique de base est le suivant: |
INSERT INTO @dst (`referentiel`, `num_nom`, `num_nom_retenu`, `nom_sci`, `auteur`, `nom_commun`) \ |
SELECT "bdtfx", b.num_nom, b.num_nom_retenu, b.nom_sci, b.auteur, n.nom_vernaculaire, MAX(n.num_statut) FROM bdtfx_v1_01 b LEFT JOIN nvjfl_v2007 n ON (b.num_taxonomique = n.num_taxon AND n.code_langue = 'fra' ) GROUP BY b.num_nom \ |
UNION \ |
SELECT "bdtxa", b.num_nom, b.num_nom_retenu, b.nom_sci, b.auteur, n.nom_vernaculaire, NULL FROM bdtxa_v1_00 b LEFT JOIN nva_v2013_06 n ON (b.num_tax = n.num_taxon AND n.code_langue = 'fra' ) GROUP BY b.num_nom \ |
UNION \ |
SELECT "isfan", b.num_nom, b.num_nom_retenu, b.nom_sci, b.auteur, NULL FROM isfan_v2013 b; |
Mais évidemment, les noms communs n'existent que pour bdtfx[nvjfl], bdtxa[nva], de même que les données baseflor/baseveg. |
Plusieurs tables temporaires sont donc nécessaires en particulier puisque toutes les colonnes n'ont pas |
des indexes adaptés pour effectuer des JOIN efficaces dans le cadre de ce script d'intégration particulier. |
Une version plus aboutie, mais spécifique à bdtfx, après création préalable de T_nvjfl_v2007, était la suivante (présence des noms communs): |
INSERT INTO @dst (`referentiel`, `num_nom`, `num_nom_retenu`, `num_taxon`, `nom_sci`, `auteur`, `nom_commun`) \ |
SELECT "bdtfx", b.num_nom, b.num_nom_retenu, b.num_taxonomique, b.nom_sci, b.auteur, n.nom_vernaculaire FROM bdtfx_v1_01 b LEFT JOIN T_nvjfl_v2007 n ON (b.num_taxonomique = n.num_taxon ); |
À noter: |
SELECT b.num_nom, b.num_nom_retenu, b.num_taxonomique, b.nom_sci FROM bdtfx_v1_01 b where b.num_taxonomique = ''; |
# 3968, c'est à dire des num_taxon vides, pourtant INDEX et NOT NULL. |
Idem pour bdtxa |
3) à propos de baseveg/baseflor: |
Note au 16/07/2013: les schémas sont susceptibles de changer à l'avenir. |
La jointure entre bdtfx et baseflor se fait sur le référentiel ("bdtfx") et num_nom. |
À partir de là nous disposons d'un catminat_code qui correspond au code_catminat dans baseveg, afin d'obtenir le syntaxon. |
Quelques exemples: |
SELECT code_catminat, syntaxon, lumiere, hum_atmos, temperature, oceanite, ph_sol, hum_edaph, texture_sol FROM baseveg_v2013_01_09; |
SELECT * from baseflor_v2012_12_31 where cle = 1174; |
SELECT * from baseveg_v2013_01_09 where code_catminat = '05/3.0.1.0.2' AND niveau = 'ALL'; |
# 7 résultats |
SELECT f.num_nomen, f.num_taxon, f.catminat_code, f.ve_lumiere, f.ve_temperature, f.ve_continentalite, f.ve_humidite_atmos, f.ve_humidite_edaph, f.ve_reaction_sol, f.ve_nutriments_sol, f.ve_salinite, f.ve_texture_sol, f.ve_mat_org_sol FROM baseflor_v2012_12_31 f LEFT JOIN baseveg_v2013_01_09 v ON (f.catminat_code = v.code_catminat) WHERE f.BDNT = "BDTFX" and f.cle = 1174; |
# 7 résultats |
SELECT f.num_nomen, f.num_taxon, f.catminat_code, f.ve_lumiere, f.ve_temperature, f.ve_continentalite, f.ve_humidite_atmos, f.ve_humidite_edaph, f.ve_reaction_sol, f.ve_nutriments_sol, f.ve_salinite, f.ve_texture_sol, f.ve_mat_org_sol FROM baseflor_v2012_12_31 f LEFT JOIN baseveg_v2013_01_09 v ON (f.catminat_code = v.code_catminat AND v.niveau = 'ALL') WHERE f.BDNT = "BDTFX" and f.cle = 1174; |
# 1 résultat |
Nous utilisons v.niveau = ALL pour nous assurer la présence d'un seul f.num_nomen dans `T_basevegflor` et donc assurer l'unicité de la PRIMARY KEY de `cel_references` |
Property changes: |
Added: svn:eol-style |
+native |
\ No newline at end of property |
/tags/v5.7-arrayanal/scripts/modules/cel/redempteur.sql |
---|
New file |
0,0 → 1,114 |
/* |
À l'origine les observations nécessiteuses sont celles n'ayant pas de données génénées, |
Soit: nom_ret, nom_ret_nn, nt ou famille à NULL|0|'' |
Eg: |
SELECT id_observation, nom_sel |
FROM `BASEEDIT`.`cel_obs` |
WHERE ( |
nom_ret IS NULL or nom_ret = '' |
OR nom_ret_nn IS NULL or nom_ret_nn = 0 |
OR nt IS NULL or nt = 0 |
OR famille IS NULL or famille = '' |
) |
Sauf que: |
1) on exclue celles sans nom_sel (elles sont sans espoir): |
nom_sel IS NOT NULL AND nom_sel != '' |
2) on exclue celles qui on un nom_ret_nn à 0, car cela peut-être légal, cf maj-201307.sql à ce propos |
# donc pas de `nom_ret_nn = 0` dans la requête |
3) on exclue, dans un premier temps, celles dont le référentiel n'est pas défini |
AND (nom_referentiel IS NULL) |
D'où, les 3621 observations suivantes (2206 nom_sel distincts) |
SELECT id_observation, nom_sel |
FROM `BASEEDIT`.`cel_obs` |
WHERE ( |
nom_sel IS NOT NULL AND nom_sel != '' |
AND ( |
nom_ret IS NULL OR nom_ret = '' |
OR nom_ret_nn IS NULL |
OR nt IS NULL or nt = 0 |
OR famille IS NULL or famille = '' |
) |
AND (nom_referentiel IS NOT NULL) |
) |
Dans un premier temps nous travaillons avec le bdtfx, c'est à dire que |
AND (nom_referentiel IS NOT NULL) |
devient |
AND (nom_referentiel like 'bdtfx%') |
soit 3597/3621 observations: |
Et effectuons une jointure sur bdtfx: |
SELECT id_observation, nom_sel, b.num_nom, b.famille |
FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEBDTFX` b ON (b.nom_sci = c.nom_sel) |
WHERE ( |
nom_sel IS NOT NULL AND nom_sel != '' |
AND ( |
nom_ret IS NULL OR nom_ret = '' |
OR nom_ret_nn IS NULL |
OR nt IS NULL OR nt = 0 |
OR c.famille IS NULL OR c.famille = '' |
) |
AND (nom_referentiel like 'bdtfx%') |
) |
* Or nous observons que la famille est parfois légitimement NULL ! Ce n'est pas pertinent de l'utiliser |
comme critère de caractérisation d'une observation buggée, contentons-nous donc de empty ('') |
* Or nous observons que le numéro taxonomique est parfois légitimement 0 ! Ce n'est pas pertinent de l'utiliser |
comme critère de caractérisation d'une observation buggée, contentons-nous donc de NULL |
Soit 84 lignes, cependant, un nom_sel peut correspondre à plusieurs num_nom_retenu dans bdtfx ! (et oui, les suffixes latins et d'auteur). |
Il s'agit donc de ne pas traiter ceux qui risquerait d'être mal-corrigé (sans les 100% de certitude). |
Ainsi un ` GROUP BY id_observation HAVING count(id_observation) = 1 ` sera du meilleur effet. |
Nous obtenons donc ainsi les 69 observations à mettre à jour: |
SELECT id_observation, nom_sel, nom_ret, nom_ret_nn, nt, c.famille, b.num_nom, b.nom_sci, b.num_taxonomique, b.famille |
FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEBDTFX` b ON (b.nom_sci = c.nom_sel) |
WHERE ( |
nom_sel IS NOT NULL AND nom_sel != '' |
AND ( |
nom_ret IS NULL OR nom_ret = '' |
OR nom_ret_nn IS NULL |
OR nt IS NULL |
OR c.famille = '' |
) |
AND (nom_referentiel like 'bdtfx%') |
) |
GROUP BY id_observation HAVING count(id_observation) = 1 |
=== la mise à jour === |
Comme nous voulons utiliser UPDATE, nous devons remplacer le JOIN par des conditions du WHERE, mais le GROUP BY bloque de |
toute manière, un SUB-SELECT (table temporaire) est donc nécessaire: |
=== finale === |
*/ |
CREATE TEMPORARY TABLE T_bis ( INDEX(`id_observation`)) AS |
SELECT id_observation, b.num_nom, CONCAT(b.nom_sci, ' ', b.auteur), b.num_taxonomique, b.famille |
FROM `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b |
WHERE ( |
b.nom_sci = c.nom_sel |
AND nom_sel IS NOT NULL AND nom_sel != '' |
AND ( |
nom_ret IS NULL OR nom_ret = '' |
OR nom_ret_nn IS NULL |
OR nt IS NULL OR nt = 0 |
OR c.famille = '' |
) |
AND (nom_referentiel like 'bdtfx%') |
) |
GROUP BY id_observation HAVING count(id_observation) = 1 |
UPDATE `BASEEDIT`.`cel_obs` c, T_bis t SET |
c.nom_ret = t.nom_sci, |
c.nom_ret_nn = t.num_nom, |
c.nt = t.num_taxonomique, |
c.famille = t.famille |
WHERE (c.id_observation = t.id_observation); |
DROP TEMPORARY TABLE T_bis; |
/tags/v5.7-arrayanal/scripts/modules/cel/Makefile |
---|
New file |
0,0 → 1,195 |
# Ce Makefile effectue les substitutions de nom de base de données |
# nécessaire au préalable de l'application des scripts SQL |
# Cela est d'un part moins complexe: |
# - qu'un script PHP (interpréteur, getopt, framework, ...) |
# - qu'un shell-script (lancement avec make) |
# et d'autre part plus maintenable qu'un shell-script car |
# le versionnage des fichiers (inc ".current") permet certaines facilités. |
# TODO: |
# idéalement, ce Makefile devrait permettre une bonne gestion du jeu de dépendances |
# entre les scripts, seulement le lancement d'un script pouvant nécessiter un login/mdp |
# il est difficile de vouloir rester "simple". |
# Ce serait cependant la meilleure manière de procéder, ainsi "maj2" ne serait lancé qu'en |
# cas de succès de "maj1", celui-ci pouvant être détecté comme "déjà exécuté" ou non. |
# cf target "maj1" ci-dessous |
# à l'aide de, note certains de ces fichiers n'ont pas cours dans le cadre de la maj1 (septembre 2013) |
# echo $(egrep -l 'BASE(SOURCE|EDIT|ANNUAIRE)' *.sql) |
fichiers = cel_references.sql dedup-ordre-201307.sql fix-utilisateur-32.sql maj-cleanup-201307.sql maj-nom-ret.sql \ |
maj-referentiel-201307.sql maj-referentiel-und-201307.sql maj-struct-201307.sql redempteur.sql \ |
referonosaure.sql \ |
.current |
# la base de données à modifier |
alterdb ?= tb_cel_test |
# pour bdtfx, bdtxa, isfan, nvjfl, nva, baseflor, ... lecture seule; |
# utilisée pour actualiser les enregistrements de cel_obs dans referonosaure.sql |
sourcedb ?= tb_eflore |
# pour annuaire_tela, lecture seule; |
# utilisée pour initialiser cel_utilisateurs dans maj-struct-201307.sql |
annuairedb ?= tela_prod_v4 |
bdtfx ?= 1_01 |
bdtxa ?= 1_00 |
isfan ?= 2013 |
bdtfx_table = bdtfx_v$(bdtfx) |
bdtxa_table = bdtxa_v$(bdtxa) |
isfan_table = isfan_v$(isfan) |
# TODO: simply override bdd_user |
ifdef bdd_user |
bdd_user_h = -u$(bdd_user) |
endif |
ifneq ($(origin bdd_pass), undefined) |
bdd_pass_h = "-p$(bdd_pass)" |
endif |
mysqlbin ?= mysql |
mysqlcmd = $(mysqlbin) $(bdd_user_h) $(bdd_pass_h) |
# macro utilisable pour les targets nécessitant de tester la présence d'un couple (base,table) |
# exemples: |
# * $(call is_table,tb_eflore,bdtfx_v1_01) |
# * $(call is_table,$(annuairedb),annuaire_tela) |
# argument 1: base de données |
# argument 2: table |
is_table = $(mysqlcmd) -N $(1) <<<"DESC $(2)" &> /dev/null |
# macro utilisable pour effectuer des substitutions: |
do_subst = sed -e "1i--\n-- fichier d'origine: \"${1}\"\n" \ |
-e 's/`BASEEDIT`/`$(alterdb)`/g' \ |
-e 's/`BASEANNUAIRE`/`$(annuairedb)`/g' \ |
-e 's/`BASESOURCE`/`$(sourcedb)`/g' \ |
-e 's/`TABLEBDTFX`/`$(bdtfx_table)`/g' \ |
-e 's/`TABLEBDTXA`/`$(bdtxa_table)`/g' \ |
-e 's/`TABLEISFAN`/`$(isfan_table)`/g' \ |
-e 's/TABLEBDTFX/`$(bdtfx_table)`/g' \ |
-e 's/TABLEBDTXA/`$(bdtxa_table)`/g' \ |
-e 's/TABLEISFAN/`$(isfan_table)`/g' \ |
$(1) |
# default target |
help: |
@echo "make [alterdb=<$(alterdb)>] [sourcedb=<$(sourcedb)>] [annuairedb=<$(annuairedb)>] [bdtfx=<$(bdtfx)>] [bdtxa=<$(bdtxa)>] [isfan=$(isfan)] [bdd_user=\"\"] [bdd_pass=\"\"] [mysqlbin=mysql]" |
@echo "make o_maj1 mysqlbin=/usr/local/mysql/bin/mysql bdd_user=telabotap bdd_pass=XXX" |
# génère les fichiers avec les bases de données souhaitées |
compile: reset |
sed -i -e 's/`BASEEDIT`/`$(alterdb)`/g' \ |
-e 's/`BASEANNUAIRE`/`$(annuairedb)`/g' \ |
-e 's/`BASESOURCE`/`$(sourcedb)`/g' \ |
-e 's/TABLEBDTFX/`$(bdtfx_table)`/g' \ |
-e 's/TABLEBDTXA/`$(bdtxa_table)`/g' \ |
-e 's/`TABLEISFAN`/`$(isfan_table)`/g' \ |
$(fichiers) |
printf "Attention: les changements s'appliqueront sur la base \"%s\"\nLes sources utilisées seront: annuaire=\"%s\" , sources=\"%s\" (%s,%s,%s)\n(Ctrl+C pour interrompre, Enter pour continuer)\n" \ |
`grep ^BASEEDIT .current|cut -d '\`' -f2` \ |
`grep ^BASEANNUAIRE .current|cut -d '\`' -f2` \ |
`grep ^BASESOURCE .current|cut -d '\`' -f2` \ |
`grep ^TABLE_BDTFX .current|cut -d '=' -f2` \ |
`grep ^TABLE_BDTXA .current|cut -d '=' -f2` \ |
`grep ^TABLE_ISFAN .current|cut -d '=' -f2` |
read |
reset: |
svn revert -q $(fichiers) |
# supprime les fichiers "compilés" (concaténation de plusieurs scripts SQL substitués) |
clean: |
rm -f *.comp.sql |
### mises à jour |
# mise à jour de septembre 2013 |
# spécifier les targets dans l'ordre (cf A_LIRE.txt) |
# première version: substitution des fichiers: pas bon |
# attention, si un prérequis ne génère pas de SQL, cela n'empêchera pas le fichier |
# final de maj d'être généré, |
#maj1: compile cel_references maj-struct-201307 maj-cleanup-201307 fix-utilisateur-32 dedup-ordre-201307 maj-referentiel-201307 |
# echo done |
o_maj1: fichiers_generes = $(addsuffix .comp.sql,$(filter-out clean,$?)) |
o_maj1: clean o_cel_references o_maj-struct-201307 o_maj-cleanup-201307 o_fix-utilisateur-32 o_dedup-ordre-201307 o_maj-referentiel-201307 o_referonosaure |
cat $(fichiers_generes) > maj1.comp.sql |
echo done |
### fin: mises à jour |
### tools |
check_cel_obs: |
$(call is_table,$(alterdb),cel_obs) |
### fin: tools |
### mises à jour individuelles (scripts) |
### pour chacun d'entre-eux, deux versions existent, |
### 1) L'un compile (après substitution des noms dans le fichier SQL original) |
### et pipe vers mysql directement, ce qui suppose aussi un .my.cnf ou autre |
### 2) L'autre (préfixé par o_), renvoie le fichier substitué en sortie standard |
### et le target principal s'occupe de concaténer et de créer un fichier de destination |
### Cette méthode est de loin préférable et conforme à la philosophie Makefile |
cel_references: |
$(call is_table,$(sourcedb),$(bdtfx_table)) |
$(call is_table,$(sourcedb),nvjfl_v2007) |
$(call is_table,$(sourcedb),nva_index_v2_03) |
$(call is_table,$(alterdb),cel_references) || $(mysqlcmd) < cel_references.sql |
o_cel_references: |
$(call is_table,$(sourcedb),$(bdtfx_table)) |
$(call is_table,$(sourcedb),nvjfl_v2007) |
$(call is_table,$(sourcedb),nva_index_v2_03) |
$(call is_table,$(alterdb),cel_references) || $(call do_subst,cel_references.sql) > $@.comp.sql |
maj-struct-201307: check_cel_obs |
$(call is_table,$(annuairedb),annuaire_tela) |
$(mysqlcmd) -N $(alterdb) <<<"DESC cel_obs nom_sel"|grep -q 601 || $(mysqlcmd) < maj-struct-201307.sql |
o_maj-struct-201307: check_cel_obs |
$(call is_table,$(annuairedb),annuaire_tela) |
$(mysqlcmd) -N $(alterdb) <<<"DESC cel_obs nom_sel"|grep -q 601 || $(call do_subst,maj-struct-201307.sql) > $@.comp.sql |
maj-cleanup-201307: check_cel_obs |
! $(mysqlcmd) -N $(alterdb) <<<"SELECT 1 FROM cel_obs WHERE nom_ret = 'null' LIMIT 1"|grep -q 1 || $(mysqlcmd) < maj-cleanup-201307.sql |
o_maj-cleanup-201307: |
# tb_cel_test clean |
! $(mysqlcmd) -N $(alterdb) <<<"SELECT 1 FROM cel_obs WHERE nom_ret = 'null' LIMIT 1"|grep -q 1 || $(call do_subst,maj-cleanup-201307.sql) > $@.comp.sql |
fix-utilisateur-32: check_cel_obs |
$(mysqlcmd) -N $(alterdb) <<<"DESC cel_obs ce_utilisateur"|grep -q 255 || $(mysqlcmd) < fix-utilisateur-32.sql |
o_fix-utilisateur-32: check_cel_obs |
$(mysqlcmd) -N $(alterdb) <<<"DESC cel_obs ce_utilisateur"|grep -q 255 || $(call do_subst,fix-utilisateur-32.sql) > $@.comp.sql |
dedup-ordre-201307: check_cel_obs |
#$(mysqlcmd) -N $(alterdb) <<<'SELECT distinct ce_utilisateur FROM `cel_obs` GROUP BY ce_utilisateur, ordre HAVING COUNT(*) > 1'|grep -q . || $(mysqlcmd) < dedup-ordre-201307.sql |
$(mysqlcmd) -N $(alterdb) <<<"SHOW INDEX FROM cel_obs"|grep -q couple_user_ordre || $(mysqlcmd) < dedup-ordre-201307.sql |
o_dedup-ordre-201307: check_cel_obs |
# l'index doit sur cel_obs doit avoir deux lignes dont le champs "non_unique" = 0 |
$(mysqlcmd) -N $(alterdb) <<<"SHOW INDEX FROM cel_obs"|grep -w id_obs|awk '{print $$2}'|tr -d "\n"|grep -q 00 || $(call do_subst,dedup-ordre-201307.sql) > $@.comp.sql |
# maj-referentiel-201307.sql: # pas de test aisé et rapide |
# doit passer APRÈS o_maj-cleanup-201307 (pas de nom_ret_nn = 0) |
o_maj-referentiel-201307: check_cel_obs |
$(call do_subst,maj-referentiel-201307.sql) > $@.comp.sql |
# pas de test aisé non plus pour savoir s'il doit repasser |
# néanmoins c'est un script sur (peut-être invoqué répétivement) |
o_referonosaure: check_cel_obs |
$(call do_subst,referonosaure.sql) > $@.comp.sql |
# pour une prochaine maj |
maj-nom-ret: |
$(mysqlcmd) -N <<<'SELECT count(1) FROM `$(alterdb)`.`cel_obs` c LEFT JOIN `$(sourcedb)`.`$(bdtfx_table)` b on (c.nom_ret = b.nom_sci) WHERE nom_ret_nn = 0 AND c.nom_ret != "" AND id_observation NOT IN ( SELECT id_observation FROM `$(alterdb)`.`cel_obs` c, `$(sourcedb)`.`$(bdtfx_table)` b WHERE c.nom_ret = b.nom_sci AND c.nom_ret_nn = 0 );'|grep -q 0 |
o_maj-nom-ret: |
$(call do_subst,maj-nom-ret.sql) > $@.comp.sql |
Property changes: |
Added: svn:eol-style |
+native |
\ No newline at end of property |
/tags/v5.7-arrayanal/scripts/modules/cel/referonosaure.sql |
---|
New file |
0,0 → 1,116 |
/* |
Objectif: prendre les observations dont nom_sel_nn est défini |
(et donc dans laquelles les informations générées sont correctes) |
et mettre à jour ces dernières à partir de la dernière version du référentiel |
(bdtfx, bdtxa et isfan). |
Pour éviter un maximum de faux-positifs, nous vérifions aussi que la famille |
est conservée (même dans certains cas celle-ci a légitimement changé) et que |
la première partie du nom_sel correspond toujours à la première partie du nouveau nom_sci |
qui serait attribué. |
-- la requête -- |
-- SELECT id_observation, b.num_nom, CONCAT(b.nom_sci, ' ', b.auteur), b.num_taxonomique, b.famille |
SELECT id_observation, nom_ret, nom_ret_nn, nt, c.famille |
FROM `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b |
WHERE ( |
nom_sel_nn IS NOT NULL |
AND nom_referentiel like 'bdtfx%' |
AND nom_sel_nn = num_nom |
) |
ORDER BY id_observation asc; |
Cependant le nom_ret_nn n'est pas directement le num_num du taxon dont le nom est |
retenu. Pour cela, une jointure en bdtfx sur num_nom_retenu est nécessaire et c'est |
ce dernier taxon dont le num_nom est utilisé pour nom_ret_nn. |
Cependant il peut aussi être vide (si aucun nom_retenu "officiel" n'existe). |
Attention, les nom_sel_nn = 0 doivent avoir disparus de cel_obs *AU PRÉALABLE* car le test |
n'est pas effectué. |
cf: maj-cleanup-201307.sql |
Ici, contrairement à referonosaure_fromNomRet.sql, nous partons du nom_sel en admettant qu'il est |
toujours correct et c'est donc sur ce champ que s'effectue la jointure. |
Quelques exceptions notables existent cependant: |
- certaines observations issues de sauvages sont corrompues, leur nom_sel_nn n'est donc PAS fiable |
- il a été remarqué des observations pour lesquelles le nom_sel_nn était corrompu, impliquant une changement |
de nom de famille incohérent. Pour se prémunir de cela, la famille doit être identique ou presque. |
- enfin, la première partie du nom_sel doit matcher exactement la première partie du nom_sci |
Consulter referonosaure_fromNomRet.sql pour des informations complémentaires. |
*/ |
/* test: |
SELECT c.nom_ret_nn, c.nom_ret, bLAST.num_nom, bLAST.nom_sci, bLAST.auteur, c.famille, bLAST.famille, c.nt, bLAST.num_taxonomique |
FROM cel_obs c, tb_eflore.bdtfx_v1_01 b, tb_eflore.bdtfx_v1_01 bLAST |
WHERE ( |
bLAST.num_nom = b.num_nom_retenu |
AND nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0 AND nom_referentiel = 'bdtfx' |
AND nom_ret_nn = bLAST.num_nom |
AND (LOWER(c.famille) = LOWER(b.famille) OR c.famille IS NULL) |
AND (c.famille != b.famille OR c.nom_ret != CONCAT(bLAST.nom_sci, ' ', bLAST.auteur) OR c.nt != b.num_taxonomique OR c.nom_ret_nn != bLAST.num_nom) |
); |
*/ |
-- l'update BDTFX avec nom_sel_nn seul |
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b, `BASESOURCE`.`TABLEBDTFX` b_nom_ret SET |
c.nom_ret = CONCAT(b_nom_ret.nom_sci, ' ', b_nom_ret.auteur), |
c.nom_ret_nn = b_nom_ret.num_nom, |
c.nt = b.num_taxonomique, |
c.famille = b.famille, |
c.date_modification = NOW() -- a supprimer pour estimer le nombre de changements réel |
WHERE ( |
b_nom_ret.num_nom = b.num_nom_retenu |
AND nom_sel_nn IS NOT NULL |
AND nom_referentiel = 'bdtfx' |
AND nom_sel_nn = b.num_nom |
-- TODO: bug transferts multiples + mobile.js |
-- Note: SELECT IF(NULL NOT LIKE "%blah%", 1, 0) : 0 |
AND (c.mots_cles_texte IS NULL OR c.mots_cles_texte NOT LIKE '%WidgetFlorileges Sauvages%') |
AND (LOWER(c.famille) = LOWER(b.famille) OR c.famille IS NULL OR c.famille = 'Famille inconnue') |
AND SUBSTRING_INDEX(c.nom_sel, ' ', 1) = SUBSTRING_INDEX(b.nom_sci, ' ', 1) |
); |
-- 42315 avec indirection num_nom_retenu |
SELECT ROW_COUNT() AS "BDTFX upd après correction sur nom_sel_nn"; |
-- l'update BDTXA avec nom_sel_nn seul |
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTXA` a, `BASESOURCE`.`TABLEBDTXA` a_nom_ret SET |
c.nom_ret = CONCAT(a_nom_ret.nom_sci, ' ', a_nom_ret.auteur), |
c.nom_ret_nn = a_nom_ret.num_nom, |
c.nt = a.num_tax, |
c.famille = a.famille, |
c.date_modification = NOW() |
WHERE ( |
a_nom_ret.num_nom = a.num_nom_retenu |
AND nom_sel_nn IS NOT NULL |
AND nom_referentiel = 'bdtxa' |
AND nom_sel_nn = a.num_nom |
AND (LOWER(c.famille) = LOWER(a.famille) OR c.famille IS NULL) |
AND SUBSTRING_INDEX(c.nom_sel, ' ', 1) = SUBSTRING_INDEX(a.nom_sci, ' ', 1) |
); |
-- 49 avec les restrictions sur famille et SUBSTRING_INDEX() |
-- 48 sans les restrictions sur famille et SUBSTRING_INDEX() |
SELECT ROW_COUNT() AS "BDTXA upd après correction sur nom_sel_nn"; |
-- l'update ISFAN avec nom_sel_nn seul |
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEISFAN` i, `BASESOURCE`.`TABLEISFAN` i_nom_ret SET |
c.nom_ret = CONCAT(i_nom_ret.nom_sci, ' ', i_nom_ret.auteur), |
c.nom_ret_nn = IF(i_nom_ret.num_nom=0,NULL,i_nom_ret.num_nom), |
c.nt = i.num_taxonomique, |
c.famille = i.famille, |
c.date_modification = NOW() |
WHERE ( |
i_nom_ret.num_nom = i.num_nom_retenu |
AND nom_sel_nn IS NOT NULL |
AND nom_referentiel = 'isfan' |
AND nom_sel_nn = i.num_nom |
AND (LOWER(c.famille) = LOWER(i.famille) OR c.famille IS NULL) |
); |
-- 0 |
SELECT ROW_COUNT() AS "ISFAN upd après correction sur nom_sel_nn"; |
/tags/v5.7-arrayanal/scripts/modules/cel/fix-utilisateur-32.sql |
---|
New file |
0,0 → 1,26 |
-- corriger les addresses erronées: |
-- SELECT distinct ce_utilisateur FROM `BASEEDIT`.`cel_obs` WHERE LENGTH(ce_utilisateur) = 32 AND ce_utilisateur LIKE '%@%' AND ce_utilisateur NOT REGEXP '\.(fr|com)$'; |
ALTER TABLE `BASEEDIT`.`cel_obs` MODIFY ce_utilisateur VARCHAR(255) NOT NULL; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = CONCAT(SUBSTRING_INDEX(ce_utilisateur,'@', 1), '@apprenti.isa-lille.fr') WHERE ce_utilisateur LIKE '%@apprenti.isa-%'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'amardeilh.michel@club-internet.fr' WHERE ce_utilisateur = 'amardeilh.michel@club-internet.f'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'claude.figureau.plantnet@gmail.com' WHERE ce_utilisateur = 'claude.figureau.plantnet@gmail.c'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'francoise.delachaussee@dbmail.com' WHERE ce_utilisateur = 'francoise.delachaussee@dbmail.co'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'lucie.boust@proxalys-environnement.com' WHERE ce_utilisateur = 'lucie.boust@proxalys-environneme'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'alexis.cochereau@plante-et-cite.fr' WHERE ce_utilisateur = 'alexis.cochereau@plante-et-cite.'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'environnement@andernos-les-bains.fr' WHERE ce_utilisateur = 'environnement@andernos-les-bains'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'hugounenc.guilhem@mairie-perpignan.fr' WHERE ce_utilisateur = 'hugounenc.guilhem@mairie-perpign'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'jean-pierre-blanchet@club-internet.fr' WHERE ce_utilisateur = 'jean-pierre-blanchet@club-intern'; |
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'stephanie.grosset@ville-montpellier.fr' WHERE ce_utilisateur = 'stephanie.grosset@ville-montpell'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = CONCAT(SUBSTRING_INDEX(ce_utilisateur,'@', 1), '@apprenti.isa-lille.fr') WHERE ce_utilisateur LIKE '%@apprenti.isa-%'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'amardeilh.michel@club-internet.fr' WHERE ce_utilisateur = 'amardeilh.michel@club-internet.f'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'claude.figureau.plantnet@gmail.com' WHERE ce_utilisateur = 'claude.figureau.plantnet@gmail.c'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'francoise.delachaussee@dbmail.com' WHERE ce_utilisateur = 'francoise.delachaussee@dbmail.co'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'lucie.boust@proxalys-environnement.com' WHERE ce_utilisateur = 'lucie.boust@proxalys-environneme'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'alexis.cochereau@plante-et-cite.fr' WHERE ce_utilisateur = 'alexis.cochereau@plante-et-cite.'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'environnement@andernos-les-bains.fr' WHERE ce_utilisateur = 'environnement@andernos-les-bains'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'hugounenc.guilhem@mairie-perpignan.fr' WHERE ce_utilisateur = 'hugounenc.guilhem@mairie-perpign'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'jean-pierre-blanchet@club-internet.fr' WHERE ce_utilisateur = 'jean-pierre-blanchet@club-intern'; |
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'stephanie.grosset@ville-montpellier.fr' WHERE ce_utilisateur = 'stephanie.grosset@ville-montpell'; |
/tags/v5.7-arrayanal/scripts/modules/cel/cel.ini |
---|
New file |
0,0 → 1,31 |
version="1_00" |
dossierTsv = "{ref:dossierDonneesEflore}cel/2011-11-10/" |
dossierSql = "{ref:dossierTsv}" |
bdd_nom = "tb_cel" |
[tables] |
obs = cel_inventory |
obsImages = cel_obs_images |
images = cel_images |
motsClesImages = cel_mots_cles_images |
motsClesObs = cel_mots_cles_obs |
zoneGeo = locations |
[fichiers] |
structureSql = "cel_v{ref:version}.sql" |
obs = "{ref:tables.obs}.tsv" |
obsImages = "{ref:tables.obsImages}.tsv" |
images = "{ref:tables.images}.tsv" |
motsClesImages = "{ref:tables.motsClesImages}.tsv" |
motsClesObs = "{ref:tables.motsClesObs}.tsv" |
zoneGeo = "{ref:tables.zoneGeo}.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
obs = "{ref:dossierTsv}{ref:fichiers.obs}" |
obsImages = "{ref:dossierTsv}{ref:fichiers.obsImages}" |
images = "{ref:dossierTsv}{ref:fichiers.images}" |
motsClesImages = "{ref:dossierTsv}{ref:fichiers.motsClesImages}" |
motsClesObs = "{ref:dossierTsv}{ref:fichiers.motsClesObs}" |
zoneGeo = "{ref:dossierTsv}{ref:fichiers.zoneGeo}" |
/tags/v5.7-arrayanal/scripts/modules/cel/maj-struct-201307.sql |
---|
New file |
0,0 → 1,21 |
-- dépot "cel", r1739 |
ALTER TABLE `BASEEDIT`.`cel_obs` MODIFY nom_sel VARCHAR(601) NULL DEFAULT NULL; |
ALTER TABLE `BASEEDIT`.`cel_obs` MODIFY nom_ret VARCHAR(601) NULL DEFAULT NULL; |
-- dépot "cel", r1739 |
CREATE INDEX nom_referentiel ON `BASEEDIT`.`cel_obs` (`nom_referentiel`(5)); |
-- depot "cel", r1809 |
ALTER TABLE `BASEEDIT`.`cel_obs` MODIFY altitude INTEGER(5) DEFAULT NULL; |
-- depot "cel", r1811 |
CREATE OR REPLACE VIEW `BASEEDIT`.`cel_utilisateurs` AS |
SELECT at.U_ID AS id_utilisateur, at.U_SURNAME AS prenom, at.U_NAME AS nom, at.U_MAIL AS courriel, at.U_PASSWD AS mot_de_passe, |
ui.licence_acceptee, ui.admin, ui.preferences, ui.date_premiere_utilisation |
FROM `BASEANNUAIRE`.`annuaire_tela` AS at |
LEFT JOIN `BASEEDIT`.`cel_utilisateurs_infos` AS ui ON (ui.id_utilisateur = at.U_ID); |
-- MySQL 5.6.5 only: |
-- ALTER TABLE `BASEEDIT`.`cel_obs` CHANGE COLUMN `date_modification` `date_modification` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ; |
-- otherwise, convert `date_modification` to TIMESTAMP ? |
/tags/v5.7-arrayanal/scripts/modules/cel/sphinx-maj-nom-ret.php |
---|
New file |
0,0 → 1,203 |
<?php |
/* |
* @author Raphaël Droz <raphael@tela-botanica.org> |
* @copyright Copyright (c) 2011, 2013 Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* |
* Corrige les erreurs de saisie de nom à l'aide d'une recherche via un index sphinx |
* pour les observations ayant un nom saisi et dont l'un au moins de nom_ret[nn], |
* nt ou famille est NULL ou vide. |
* |
*/ |
// time php -d memory_limit=1024M sphinx-maj-nom-ret.php 0 > sphinx-maj.log |
// 23 secondes |
// settings |
define('USE_NVJFL', FALSE); |
define('ESCAPE_ON_SPHINX_SYNERROR', TRUE); |
define('TRY_FORCE_START_LINE', TRUE); |
define('TRY_SPLIT', TRUE); |
define('TRY_EXACT', TRUE); |
define('TRY_REF', TRUE); |
define('TRY_SPLIT_AND_AUTEUR', FALSE); |
define('TRY_REMOVE_L', TRUE); |
define('M_TRY_SPLIT', 0x01); |
define('M_TRY_EXACT', 0x02); |
define('M_TRY_REF', 0x04); |
define('M_TRY_SPLIT_AND_AUTEUR', 0x08); |
error_reporting(E_ALL); |
$db = mysql_connect('localhost', 'root', '') or die('no mysql'); |
mysql_select_db('tb_cel', $db); |
mysql_query("SET NAMES utf8", $db) or die('no sphinx'); |
$dbs = mysql_connect('127.0.0.1:9306', NULL, NULL, TRUE); |
$req = <<<EOF |
SELECT id_observation, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, famille, nom_referentiel |
FROM `cel_obs` |
WHERE nom_sel IS NOT NULL AND nom_sel != '' AND |
id_observation BETWEEN %d AND %d AND |
( nom_ret IS NULL or nom_ret = '' |
OR nt IS NULL or nt = 0 or nt = '' |
OR famille IS NULL or famille = '' ) |
LIMIT %d, %d |
EOF; |
// non: car nom_ret_nn peut-être légitimement à 0 [taxon identifié, sans nom_retenu] |
// OR nom_ret_nn IS NULL or nom_ret_nn = 0 or nom_ret_nn = '' |
array_shift($argv); |
$start = array_shift($argv); |
$max = array_shift($argv); |
$chunk_size = array_shift($argv); |
if(!$start) $start = 0; |
// 1036314 |
if(!$max) $max = intval(mysql_fetch_assoc(mysql_query("SELECT MAX(id_observation) AS max FROM cel_obs", $db))['max']) + 1; |
if(!$chunk_size) $chunk_size = 50000; |
// escape sphinx |
$from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=', "'", "\x00", "\n", "\r", "\x1a" ); |
$to = array ( '\\\\', '\\\(','\\\)','\\\|','\\\-','\\\!','\\\@','\\\~','\\\"', '\\\&', '\\\/', '\\\^', '\\\$', '\\\=', "\\'", "\\x00", "\\n", "\\r", "\\x1a" ); |
$stats = ['no_nom_sel' => ['count' => 0, 'data' => [] ], |
'not found' => ['count' => 0, 'data' => [] ], |
'too many' => ['count' => 0, 'data' => [] ], |
'fixable' => ['count' => 0, 'data' => [] ], |
'sauvages' => ['count' => 0, 'data' => [] ], |
'sphinx errors' => ['count' => 0, 'data' => [] ], |
'ref pb' => ['count' => 0, 'data' => [] ], ]; |
$sphinx_req = sprintf("SELECT * FROM i_bdtfx %s WHERE MATCH('%%s') LIMIT 5", USE_NVJFL ? ", i_nvjfl" : ""); |
for($current = 0; $current < intval($max/$chunk_size) + 1; $current++) { |
// printf("current = %d, chunk_size = %d, max = %d (rmax = %d) [real limit: %d]\n", $current, $chunk_size, $max, intval($max/$chunk_size) + 1, $current*$chunk_size); |
// printf(strtr($req, "\n", " ") . "\n", $start, $max, $current*$chunk_size, $chunk_size); |
$data = mysql_query(sprintf($req, $start, $max, $current*$chunk_size, $chunk_size), $db); |
if(!$data) { var_dump(mysql_error()); die('end'); } |
while($d = mysql_fetch_assoc($data)) { |
$n = trim($d['nom_sel']); |
//d: fprintf(STDERR, "$n\n"); |
if(!$n) { |
$stats['no_nom_sel']['count']++; |
// $stats['no_nom_sel']['data'][] = [$d['id_observation'], $n];*/ |
continue; |
} |
if($n == 'Autre(s) espèce(s) (écrire le/les nom(s) dans les notes)' || |
$n == '-') { |
$stats['sauvages']['count']++; |
// $stats['sauvages']['data'][] = [$d['id_observation'], $n]; |
continue; |
} |
$MASQUE = 0; |
if(TRY_REMOVE_L) { |
$n = str_replace(' L.','', $n); |
} |
$orig_n = $n; |
recherche: |
if(TRY_FORCE_START_LINE && !_has($MASQUE, M_TRY_EXACT)) { |
$n = '^' . $n; |
} |
$s = mysql_query(sprintf($sphinx_req, $n), $dbs); |
if(!$s && ESCAPE_ON_SPHINX_SYNERROR) { |
$s = mysql_query(sprintf($sphinx_req, str_replace($from,$to,$n)), $dbs); |
} |
if(!$s) { |
$stats['sphinx errors']['count']++; |
// $stats['sphinx errors']['data'][] = [$d['id_observation'], $orig_n]; |
continue; |
} |
$c = mysql_num_rows($s); |
//d: fprintf(STDERR, "\t search [nb:%d] \"%s\" (msk:%d)\n", $c, $n, $MASQUE); |
if($c == 0) { |
if(TRY_SPLIT && !_has($MASQUE, M_TRY_SPLIT)) { |
require_once('lib-split-auteur.php'); |
$MASQUE |= M_TRY_SPLIT; |
// $n = RechercheInfosTaxonBeta::supprimerAuteur($orig_n); |
// list($ret, $m) = RechercheInfosTaxonBeta::contientAuteur($orig_n); |
$ret = RechercheInfosTaxonBeta::supprimerAuteurBis($orig_n, $m); |
if($ret) { |
// printf("===================== SPLIT: contientAuteur \"%s\" [@%s @%s)\n", $orig_n, $ret, $m); |
$n = sprintf('%s @auteur %s', $ret, $m); |
goto recherche; |
} |
} |
if(TRY_SPLIT_AND_AUTEUR && !_has($MASQUE, M_TRY_SPLIT_AND_AUTEUR) && strpos($orig_n, ' ') !== FALSE) { |
require_once('lib-split-auteur.php'); |
$MASQUE |= M_TRY_SPLIT_AND_AUTEUR; |
$ns = RechercheInfosTaxonBeta::supprimerAuteur($orig_n); |
if($ns) { |
$a = trim(substr($orig_n, strlen($n))); |
$n = sprintf("%s @auteur %s", $ns, $a); |
// echo "===================== SPLIT N/A: $n\n"; |
goto recherche; |
} |
} |
$stats['not found']['count']++; |
// $stats['not found']['data'][] = [$d['id_observation'], $orig_n]; |
continue; |
} |
if($c > 1) { |
if($c == 2) { |
if(mysql_fetch_array($s)['group_id'] != |
mysql_fetch_array($s)['group_id']) { |
// recherche donne seulement 2 résultats dans 2 référentiels |
// potentiellement fixable si l'on peut se référer à $d['nom_referentiel'] |
$stats['ref pb']['count']++; |
// $stats['ref pb']['data'][] = [$d['id_observation'], $orig_n]; |
continue; |
} |
} |
if(TRY_EXACT && !_has($MASQUE, M_TRY_EXACT)) { |
$MASQUE |= M_TRY_EXACT; |
$n = '"^' . trim($orig_n) . '$"'; |
goto recherche; |
} |
if(TRY_REF && isset($d['nom_referentiel']) && !_has($MASQUE, M_TRY_REF)) { |
$MASQUE |= M_TRY_REF; |
$n = $orig_n . ' @group_id ' . $d['nom_referentiel']; |
goto recherche; |
} |
$stats['too many']['count']++; |
// $stats['too many']['data'][] = [$d['id_observation'], $orig_n]; |
continue; |
} |
ok: |
$stats['fixable']['count']++; |
// $stats['fixable']['data'][] = [$d['id_observation'], $orig_n]; |
} |
} |
function _has($v, $r) { |
return ($v & $r) == $r; |
} |
array_walk($stats, function(&$v) { unset($v['data']); }); |
print_r($stats); |
printf("total traité: %d\n", array_sum(array_map(function($v) { return $v['count']; }, $stats))); |
/tags/v5.7-arrayanal/scripts/modules/cel/maj-cleanup-201307.sql |
---|
New file |
0,0 → 1,62 |
-- date d'observation dans le futur |
UPDATE `BASEEDIT`.`cel_obs` SET date_observation = NULL WHERE date_observation > now(); |
-- cleanup |
UPDATE `BASEEDIT`.`cel_obs` SET date_observation = NULL WHERE date_observation = '0000-00-00 00:00:00'; |
-- cleanup |
UPDATE `BASEEDIT`.`cel_obs` SET latitude = NULL, longitude = NULL WHERE longitude = 0 and latitude = 0; |
-- referentiels: 65800 NULL, 13000 '' |
UPDATE `BASEEDIT`.`cel_obs` SET nom_referentiel = SUBSTRING_INDEX(nom_referentiel, ':', 1); |
UPDATE `BASEEDIT`.`cel_obs` SET nom_referentiel = 'bdtfx' WHERE nom_referentiel IN ('bdtfx_v1','bdnff'); |
-- pas de raison historique mémorisée à une différence '' vs NULL |
UPDATE `BASEEDIT`.`cel_obs` SET nom_referentiel = NULL where nom_referentiel = ''; |
-- uniformisation NULL / vide pour nom_sel |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = NULL WHERE nom_sel = ''; |
-- uniformisation NULL / vide pour nom_sel_nn |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel_nn = NULL WHERE nom_sel_nn = 0; |
-- restauration de nom_sel vraisemblablement valides, mais vides: 48 obs |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = nom_ret WHERE nom_sel IS NULL AND nom_ret IS NOT NULL AND nom_ret != '' AND nom_sel_nn IS NOT NULL; |
-- suppression des infos générées pour les observations dont le nom_sel à été supprimé par l'utilisateur |
-- 3380 |
UPDATE `BASEEDIT`.`cel_obs` c SET |
c.nom_ret = '', |
c.nom_sel_nn = NULL, |
c.nom_ret = NULL, |
c.nom_ret_nn = NULL, |
c.nt = NULL, |
c.famille = NULL |
WHERE nom_sel IS NULL OR nom_ret = 'undefined'; |
-- problème n°1: mauvais référentiel (bdtfx au lieu de bdtxa), on utilise les lieudit "bdtxa" pour |
-- corriger les observations qui pourraient être étiquetées avec un mauvais nom_referentiel: 49 obs |
CREATE TEMPORARY TABLE T_cleanref (lieu VARCHAR(255)) ENGINE=MEMORY AS ( SELECT DISTINCT TRIM(lieudit) FROM `BASEEDIT`.`cel_obs` WHERE nom_referentiel = 'bdtxa' ); |
UPDATE `BASEEDIT`.`cel_obs` SET nom_referentiel = 'bdtxa' WHERE nom_referentiel != 'bdtxa' AND lieudit != '' AND lieudit IN (SELECT lieu FROM T_cleanref); |
DROP TEMPORARY TABLE T_cleanref; |
-- problème n°2: backslashes + newline: 90 + 217 obs |
UPDATE `BASEEDIT`.`cel_obs` SET commentaire = REPLACE(commentaire, "\n\\\'", "'"); |
UPDATE `BASEEDIT`.`cel_obs` SET commentaire = REPLACE(commentaire, "\\\'", "'"); |
-- problème n°3: ce_zone_geo inutile: 57802 obs |
UPDATE `BASEEDIT`.`cel_obs` SET ce_zone_geo = NULL WHERE ce_zone_geo = 'INSEE-C:'; |
-- trim nom_sel |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = REPLACE(nom_sel, '\\', ''); |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = TRIM(LEADING "." FROM TRIM("\t" FROM TRIM(nom_sel))); |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = TRIM(TRIM('\\' FROM TRIM('‘' FROM TRIM('‘' FROM TRIM('"' FROM nom_sel))))) WHERE nom_sel REGEXP '^[\\"‘’].*[\\"‘’]$'; |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = TRIM("'" FROM nom_sel) WHERE nom_sel REGEXP "^'.*'$"; -- ' relax emacs |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = TRIM('"' FROM nom_sel) WHERE nom_sel REGEXP '^"[^"]+$'; |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = REPLACE(nom_sel, 'A©', 'é') WHERE nom_sel LIKE '%A©%'; |
-- nom_ret = "null" |
UPDATE `BASEEDIT`.`cel_obs` SET nom_ret = NULL WHERE nom_ret = 'null'; |
-- inconsistence de date_transmission avec transmission (cf r1860) |
UPDATE `BASEEDIT`.`cel_obs` SET date_transmission = date_creation WHERE date_transmission IS NULL AND transmission = 1; |
UPDATE `BASEEDIT`.`cel_obs` SET date_transmission = NULL WHERE date_transmission IS NOT NULL AND transmission = 0; |
/tags/v5.7-arrayanal/scripts/modules/cel/maj-nom-ret.sql |
---|
New file |
0,0 → 1,45 |
/* |
Cleanup des observation ayant un nom_ret_nn à 0 (mais un nom_ret défini...): |
En effet, on peut pour l'instant POSTer $nom_ret, d'où bien souvent nom_sel == nom_ret, cependant nom_ret_nn = 0 |
(pas d'autodétection). |
Nous pourrions donc les nullifier sans remord, ... mais ... |
nom_ret_nn == 0 est VALIDE (car bdtfx.num_nom_retenu == 0 est "valide", 3960 taxons sont "orphelins" de nom_retenu) |
1) créer un index pour les jointures: |
CREATE INDEX i_nom_ret ON `BASESOURCE`.`TABLEBDTFX` (`nom_sci`(8)) |
2) regarder les num_nom_ret orphelins de taxon en BDTFX: |
SELECT * FROM `BASESOURCE`.`TABLEBDTFX` WHERE num_nom_retenu = 0; # 3960 |
3) regarder les num_nom_ret orphelins de taxon en BDTXA: |
SELECT * FROM `BASESOURCE`.`TABLEBDTXA` WHERE num_nom_retenu = 0; # 0 |
4) regarder les orphelins équivalents dans `BASEEDIT`.`cel_obs`: |
SELECT date_observation, SUBSTRING(nom_sel, 1, 50), nom_ret_nn, nom_ret, b.nom_sci FROM `BASEEDIT`.`cel_obs` c LEFT JOIN `BASESOURCE`.`TABLEBDTFX` b on (c.nom_ret = b.nom_sci) WHERE nom_ret_nn = 0; # 7740 |
Donc ceux dont le nom_ret à été POSTé manuellement et qui matchent le nom_sci de BDTFX : on les conserve. |
Mais les autres, qui ont un nom_ret probablement erroné et un nom_ret_nn à 0, on NULLify les données car elles seront théoriquement correctement autoregénérées ! |
Cela concerne: |
SELECT date_observation, SUBSTRING(nom_sel, 1, 50), nom_ret_nn, nom_ret, b.nom_sci FROM `BASEEDIT`.`cel_obs` c LEFT JOIN `BASESOURCE`.`TABLEBDTFX` b ON (c.nom_ret = b.nom_sci) WHERE nom_ret_nn = 0 |
AND c.nom_ret != '' AND id_observation NOT IN ( SELECT id_observation FROM `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b WHERE c.nom_ret = b.nom_sci AND c.nom_ret_nn = 0 ); # 960 |
*/ |
-- D'où la requête : |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel_nn = NULL, nom_ret = NULL, nom_ret_nn = NULL, nt = NULL, famille = NULL WHERE id_observation IN |
( SELECT id_observation FROM `BASEEDIT`.`cel_obs` c LEFT JOIN `BASESOURCE`.`TABLEBDTFX` b on (c.nom_ret = b.nom_sci) WHERE nom_ret_nn = 0 |
AND c.nom_ret != '' AND id_observation NOT IN ( SELECT id_observation FROM `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b WHERE c.nom_ret = b.nom_sci AND c.nom_ret_nn = 0 ) ); |
-- TODO |
-- UPDATE `BASEEDIT`.`cel_obs` SET nom_ret_nn = NULL WHERE nom_ret_nn = 0; |
/* |
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = NULL, nom_sel_nn = NULL, nom_ret = NULL, nom_ret_nn = NULL, nt = NULL, famille = NULL, |
FROM `BASEEDIT`.`cel_obs` |
WHERE nom_sel IS NULL AND |
( |
(nom_ret IS NOT NULL AND nom_ret != '') OR |
(nt IS NOT NULL AND nt != 0 AND nt != '') OR |
(famille IS NOT NULL AND famille != '') |
) |
-- pas de test de nullité sur nom_ret_nn qui peut légitimement être NULL |
(nom_ret_nn IS NOT NULL AND nom_ret_nn != 0 AND nom_ret_nn != '') OR |
*/ |
/tags/v5.7-arrayanal/scripts/modules/cel/referonosaure_fromNomRet.sql |
---|
New file |
0,0 → 1,105 |
/* |
Ceci est une version dérivée de referonosaure.sql dans laquel est postulé que |
les nom_ret sont un critère tangible. |
En effet, sauf bug, il n'y a pas de raison qu'un num_nom_retenu soit moins fiable qu'un num_nom. |
Cependant un taxon peut changer de num_nom_retenu, et auquel cas c'est bien referonosaure.sql |
qu'il faut utiliser. |
Cependant pour un simple "rafraîchissement" des chaînes de caractères attribuées au noms retenus, |
ce script, referonosaure_fromNomRet.sql, doit suffire. |
Attention, les nom_sel_nn = 0 doivent avoir disparus de cel_obs *AU PRÉALABLE* car le test |
n'est pas effectué. |
cf: maj-cleanup-201307.sql |
*/ |
/* test: |
SELECT c.nom_ret_nn, c.nom_ret, b.nom_sci, b.auteur, c.famille, b.famille, c.nt, b.num_taxonomique |
FROM cel_obs c, tb_eflore.bdtfx_v1_01 b |
WHERE ( |
nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0 |
AND nom_referentiel = 'bdtfx' |
AND nom_ret_nn = num_nom |
AND (LOWER(c.famille) = LOWER(b.famille) OR c.famille IS NULL) |
AND (c.famille != b.famille OR c.nom_ret != CONCAT(b.nom_sci, ' ', b.auteur) OR c.nt != b.num_taxonomique) |
); |
= 2 taxons: 75134 et 75468 (changement de nt) |
*/ |
-- l'update BDTFX avec nom_sel_nn et nom_ret_nn corrects |
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b SET |
c.nom_ret = CONCAT(b.nom_sci, ' ', b.auteur), |
c.nt = b.num_taxonomique, |
c.famille = b.famille |
WHERE ( |
nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0 |
AND nom_referentiel = 'bdtfx' |
AND nom_ret_nn = num_nom |
AND (c.mots_cles_texte IS NULL OR c.mots_cles_texte NOT LIKE '%WidgetFlorileges Sauvages%') -- TODO: bug transferts multiples + mobile.js |
AND (LOWER(c.famille) = LOWER(b.famille) OR c.famille IS NULL OR c.famille = 'Famille inconnue') |
); |
-- 25584 |
SELECT ROW_COUNT() AS "BDTFX upd après correction sur nom_ret_nn + nom_sel_nn"; |
-- l'update BDTXA avec nom_sel_nn et nom_ret_nn corrects |
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTXA` a SET |
c.nom_ret = CONCAT(a.nom_sci, ' ', a.auteur), |
c.nt = a.num_tax, |
c.famille = a.famille |
WHERE ( |
nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0 |
AND nom_referentiel = 'bdtxa' |
AND nom_ret_nn = num_nom |
AND (LOWER(c.famille) = LOWER(a.famille) OR c.famille IS NULL) |
); |
-- 2 |
SELECT ROW_COUNT() AS "BDTXA upd après correction sur nom_ret_nn + nom_sel_nn"; |
-- l'update ISFAN avec nom_sel_nn et nom_ret_nn corrects -- |
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEISFAN` i SET |
c.nom_ret = CONCAT(i.nom_sci, ' ', i.auteur), |
c.nt = i.num_taxonomique, |
c.famille = i.famille |
WHERE ( |
nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0 |
AND nom_referentiel = 'isfan' |
AND nom_ret_nn = num_nom |
AND (LOWER(c.famille) = LOWER(i.famille) OR c.famille IS NULL) |
); |
-- 2 ou 0 |
SELECT ROW_COUNT() AS "ISFAN upd après correction sur nom_ret_nn + nom_sel_nn"; |
/* |
Pour observer les différences: |
wdiff -w '$(tput bold;tput setaf 1)' -x '$(tput sgr0)' -y '$(tput bold;tput setaf 2)' -z '$(tput sgr0)' pre.log post.log | \ |
ansi2html.sh --palette=solarized | \ |
sed '/^[0-9]/{/span/!d}' > diff.html |
# extract les familles ayant changé: sed '/^[0-9]/{/<\/span>$/!d}' |
# lowercase toutes les familles: awk '{ NF=tolower($NF); print }' |
# filtre sed: changements de famille "normaux" |
/aceraceae.*sapindaceae/d |
/scrophulariaceae.*plantaginaceae/d |
/globulariaceae.*plantaginaceae/d |
/Famille inconnue.*null/d |
# changement "anormaux" |
/rosaceae.*caprifoliaceae/d |
/valerianaceae.*caprifoliaceae/d |
SELECT nom_sel, nom_ret FROM cel_obs GROUP BY nom_sel, nom_ret INTO OUTFILE '/tmp/new.csv' ; |
SELECT id_observation, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn FROM cel_obs INTO OUTFILE '/tmp/id.csv' ; |
$ wdiff x y|sed -n "/\x1b/p"|less |
*/ |
/tags/v5.7-arrayanal/scripts/modules/cel/maj-referentiel-und-201307.sql |
---|
New file |
0,0 → 1,100 |
/* |
Mise à jour de réferentiels NULL ou vides pour les observations orphelines (sans nom_ret_nn) |
2722 observations trouvées au 2013/07/19 |
*/ |
DROP PROCEDURE IF EXISTS getNomSci; |
DROP PROCEDURE IF EXISTS getNomSciCount; |
DROP PROCEDURE IF EXISTS getNomSciAuteur; |
DROP PROCEDURE IF EXISTS getNomSciAuteurCount; |
DROP PROCEDURE IF EXISTS cur; |
delimiter | |
-- obtient le nombre de matches sur nom_sel = nom_sci |
CREATE PROCEDURE getNomSciCount(IN _nom varchar(500), OUT param1 INT) |
BEGIN |
SELECT sum(c) INTO param1 FROM (SELECT count(1) as c FROM `BASESOURCE`.`TABLEBDTFX` b WHERE nom_sci = _nom UNION ALL SELECT count(1) FROM `BASESOURCE`.`TABLEBDTXA` a WHERE nom_sci = _nom) AS req; |
END |
| |
-- retourne les paramètres d'une match |
CREATE PROCEDURE getNomSci(IN _nom varchar(500), OUT param1 char(5), OUT param2 varchar(601), OUT param3 INT, OUT param4 INT, OUT param5 varchar(255)) |
BEGIN |
SELECT * INTO param1, param2, param3, param4, param5 FROM |
(SELECT "bdtfx", CONCAT(b.nom_sci, ' ', b.auteur), b.num_nom, b.num_taxonomique, b.famille FROM `BASESOURCE`.`TABLEBDTFX` b WHERE nom_sci = _nom |
UNION ALL |
SELECT "bdtxa", CONCAT(a.nom_sci, ' ', a.auteur), a.num_nom, a.num_tax, a.famille FROM `BASESOURCE`.`TABLEBDTXA` a WHERE nom_sci = _nom) AS req; |
END |
| |
-- obtient le nombre de matches sur nom_sel = CONCAT(nom_sci, " ", auteur) |
-- quasiment identique à ci-dessus, sauf que nous excluons de la recherche de bdtfx et bdtxa les nom dont le nom d'auteur est '' |
CREATE PROCEDURE getNomSciAuteurCount(IN _nom varchar(500), OUT param1 INT) |
BEGIN |
SELECT sum(c) INTO param1 FROM (SELECT count(1) as c FROM `BASESOURCE`.`TABLEBDTFX` b WHERE CONCAT(nom_sci, ' ', auteur) = _nom UNION ALL SELECT count(1) FROM `BASESOURCE`.`TABLEBDTXA` a WHERE CONCAT(nom_sci, ' ', auteur) = _nom) AS req; |
END |
| |
-- retourne les paramètres d'une match |
CREATE PROCEDURE getNomSciAuteur(IN _nom varchar(500), OUT param1 char(5), OUT param2 varchar(601), OUT param3 INT, OUT param4 INT, OUT param5 varchar(255)) |
BEGIN |
SELECT * INTO param1, param2, param3, param4, param5 FROM |
(SELECT "bdtfx", CONCAT(b.nom_sci, ' ', b.auteur), b.num_nom, b.num_taxonomique, b.famille FROM `BASESOURCE`.`TABLEBDTFX` b WHERE CONCAT(nom_sci, ' ', auteur) = _nom AND auteur != '' |
UNION ALL |
SELECT "bdtxa", CONCAT(a.nom_sci, ' ', a.auteur), a.num_nom, a.num_tax, a.famille FROM `BASESOURCE`.`TABLEBDTXA` a WHERE CONCAT(nom_sci, ' ', auteur) = _nom AND auteur != '') AS req; |
END |
| |
CREATE PROCEDURE cur() |
BEGIN |
DECLARE done INT DEFAULT 0; |
DECLARE subst INT DEFAULT 0; |
DECLARE _id_observation bigint(20) DEFAULT 0; |
DECLARE _nom varchar(255) DEFAULT NULL; |
-- la requête principale de sélection des observations à mettre à jour |
DECLARE cur1 CURSOR FOR SELECT id_observation, nom_sel FROM `BASEEDIT`.`cel_obs` WHERE nom_referentiel IS NULL AND nom_sel != '' AND nom_sel IS NOT NULL AND nom_ret_nn IS NULL; -- 78149 |
-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; |
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; |
OPEN cur1; |
REPEAT |
FETCH cur1 INTO _id_observation, _nom; |
CALL getNomSciCount(_nom, @a); |
-- SELECT _id_observation, _nom, @a; |
IF @a = 1 THEN |
CALL getNomSci(_nom, @_ref, @_nom, @_num_nom, @_num_tax, @_famille); |
SELECT "updb: getNomSci", _id_observation, _nom, '=', @_ref, @_nom, @_num_nom, @_num_tax, @_famille; |
UPDATE `BASEEDIT`.`cel_obs` c SET |
c.nom_referentiel = @_ref, |
c.nom_ret = @_nom, |
c.nom_ret_nn = @_num_nom, |
c.nt = @_num_tax, |
c.famille = @_famille |
WHERE id_observation = _id_observation; |
SET subst = subst + 1; |
/* ELSE |
CALL getNomSciAuteurCount(_nom, @a); |
IF @a = 1 THEN |
CALL getNomSciAuteur(_nom, @_ref, @_nom, @_num_nom, @_num_tax, @_famille); |
SELECT "updb: getNomSciAuteur", _id_observation, _nom, '=', @_ref, @_nom, @_num_nom, @_num_tax, @_famille; |
UPDATE `BASEEDIT`.`cel_obs` c SET |
c.nom_referentiel = @_ref, |
c.nom_ret = @_nom, |
c.nom_ret_nn = @_num_nom, |
c.nt = @_num_tax, |
c.famille = @_famille |
WHERE id_observation = _id_observation; |
SET subst = subst + 1; |
END IF;*/ |
END IF; |
UNTIL done END REPEAT; |
select subst AS 'nombre de mises à jour effectuées'; |
CLOSE cur1; |
END |
| |
delimiter ; |
/tags/v5.7-arrayanal/scripts/modules/cel |
---|
New file |
Property changes: |
Added: svn:ignore |
+o_*.comp.sql |
/tags/v5.7-arrayanal/scripts/modules/insee_d/InseeD.php |
---|
New file |
0,0 → 1,75 |
<?php |
/** Exemple lancement: |
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php insee_d |
* -a chargerTous |
* Options : |
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes). |
*/ |
class InseeD extends EfloreScript { |
public function executer() { |
// Lancement de l'action demandée |
try { |
$this->initialiserProjet('insee-d'); |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerInseeD(); |
$this->chargerOntologies(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerInseeD' : |
$this->chargerInseeD(); |
break; |
case 'chargerOntologies' : |
$this->chargerOntologies(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function chargerInseeD() { |
$chemin = Config::get('chemins.inseeD'); |
$table = Config::get('tables.inseeD'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY ';' ". |
" ENCLOSED BY '\"' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 0 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function chargerOntologies() { |
$chemin = Config::get('chemins.ontologies'); |
$table = Config::get('tables.ontologies'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS insee_d_meta, insee_d_ontologies_v2011, insee_d_v2011"; |
$this->getBdd()->requeter($requete); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/insee_d/insee-d.ini |
---|
New file |
0,0 → 1,17 |
version="2011" |
dossierTsv = "{ref:dossierDonneesEflore}insee-d/2011/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
inseeD = "insee_d_v{ref:version}" |
ontologies = "insee_d_ontologies_v{ref:version}" |
[fichiers] |
structureSql = "insee-d_v{ref:version}.sql" |
inseeD = "insee-d_v{ref:version}.csv" |
ontologies = "insee-d_ontologies_v{ref:version}.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
inseeD = "{ref:dossierTsv}{ref:fichiers.inseeD}" |
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}" |
/tags/v5.7-arrayanal/scripts/modules/insee_d |
---|
New file |
Property changes: |
Added: svn:ignore |
+insee-d.ini |
/tags/v5.7-arrayanal/scripts/modules/bdtfx/Bdtfx.php |
---|
New file |
0,0 → 1,347 |
<?php |
//declare(encoding='UTF-8'); |
/** |
* Exemple de lancement du script : : |
* /opt/lampp/bin/php cli.php bdtfx -a chargerTous |
* |
* @category php 5.2 |
* @package eFlore/Scripts |
* @author Jennifer DHÉ <jennifer@tela-botanica.org> |
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org> |
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org) |
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL |
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL |
* @version $Id$ |
*/ |
class Bdtfx extends EfloreScript { |
private $table = null; |
private $pasInsertion = 1000; |
private $departInsertion = 0; |
protected $parametres_autorises = array( |
'-t' => array(false, false, 'Permet de tester le script sur un jeu réduit de données (indiquer le nombre de lignes).')); |
public function executer() { |
try { |
$this->initialiserProjet('bdtfx'); |
// Lancement de l'action demandée |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerBdtfx(); |
$this->genererChpNomSciHtml(); |
$this->genererChpFamille(); |
$this->genererDonneesTestMultiVersion(); |
$this->genererChpHierarchie(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerBdtfx' : |
$this->chargerBdtfx(); |
break; |
case 'genererNomSciHtml' : |
$this->genererChpNomSciHtml(); |
break; |
case 'genererChpFamille' : |
$this->genererChpFamille(); |
break; |
case 'genererChpHierarchie' : |
$this->genererChpHierarchie(); |
break; |
case 'genererDonneesTestMultiVersion' : |
$this->genererDonneesTestMultiVersion(); |
break; |
case 'supprimerDonneesTestMultiVersion' : |
$this->supprimerDonneesTestMultiVersion(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function chargerBdtfx() { |
$chemin = Config::get('chemins.bdtfx'); |
$table = Config::get('tables.bdtfx'); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function genererChpNomSciHtml() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpNomSciHtml(); |
$generateur = new GenerateurNomSciHtml(); |
$nbreTotal = $this->recupererNbTotalTuples(); |
$erreurs = array(); |
$this->departInsertion = 0; |
while ($this->departInsertion < $nbreTotal) { |
$resultat = $this->recupererTuplesPrChpNomSciHtml(); |
try { |
$nomsSciEnHtml = $generateur->generer($resultat); |
} catch (Exception $e) { |
$erreurs[] = $e->getMessage(); |
} |
$this->remplirChpNomSciHtm($nomsSciEnHtml); |
$this->departInsertion += $this->pasInsertion; |
$this->afficherAvancement("Insertion des noms scientifique au format HTML dans la base par paquet de {$this->pasInsertion} en cours"); |
if ($this->stopperLaBoucle($this->getParametre('t'))) break; |
} |
echo "\n"; |
$this->creerFichierLog('Erreurs lors de la génération HTML des noms scientifiques', $erreurs, 'erreurs_noms_sci_html'); |
} |
private function initialiserGenerationChamps() { |
$this->table = Config::get('tables.bdtfx'); |
} |
private function preparerTablePrChpNomSciHtml() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD nom_sci_html VARCHAR( 500 ) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function recupererNbTotalTuples(){ |
$requete = "SELECT count(*) AS nb FROM {$this->table} "; |
$resultat = $this->getBdd()->recuperer($requete); |
return $resultat['nb']; |
} |
private function recupererTuplesPrChpNomSciHtml() { |
$requete = 'SELECT num_nom, rang, nom_sci, nom_supra_generique, genre, epithete_infra_generique, '. |
' epithete_sp, type_epithete, epithete_infra_sp,cultivar_groupe, '. |
' nom_commercial, cultivar '. |
"FROM {$this->table} ". |
"LIMIT {$this->departInsertion},{$this->pasInsertion} "; |
$resultat = $this->getBdd()->recupererTous($requete); |
return $resultat; |
} |
private function remplirChpNomSciHtm($nomsSciHtm) { |
foreach ($nomsSciHtm as $id => $html) { |
$html = $this->getBdd()->proteger($html); |
$requete = "UPDATE {$this->table} SET nom_sci_html = $html WHERE num_nom = $id "; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
throw new Exception("Erreur d'insertion pour le tuple $id"); |
} |
} |
} |
private function traiterResultatsFamille(&$resultats, &$noms, &$introuvables, &$introuvablesSyno) { |
foreach ($resultats as $id => $nom) { |
$nn = $nom['num_nom']; |
$nnr = $nom['num_nom_retenu']; |
$nts = $nom['num_tax_sup']; |
$rg = $nom['rang']; |
if ($nnr != '') { |
if ($rg == '180') { |
$noms[$nn] = $nom['nom_sci']; |
} else { |
if ($nn == $nnr) {// nom retenu |
if (isset($noms[$nts])) { |
// signifie que recupererTuplesPrChpFamille() devrait |
// récupérer ce record *avant* |
$noms[$nn] = $noms[$nts]; |
} else { |
$introuvables[] = $nn; |
} |
} else {// nom synonyme |
if (isset($noms[$nnr])) { |
// signifie que recupererTuplesPrChpFamille() devrait |
// récupérer ce record *avant* |
$noms[$nn] = $noms[$nnr]; |
} else { |
$introuvablesSyno[] = $nom; |
} |
} |
} |
} |
unset($resultats[$id]); |
$this->afficherAvancement("Attribution de leur famille aux noms en cours"); |
if ($this->stopperLaBoucle($this->getParametre('t'))) break; |
} |
} |
private function genererChpFamille() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpFamille(); |
$resultats = $this->recupererTuplesPrChpFamille(); |
$noms = array(); |
$introuvables = array(); |
$introuvablesSyno = array(); |
$i = 1; |
while(true) { |
printf("passe n°%d:\n", $i); |
$this->traiterResultatsFamille($resultats, $noms, $introuvables, $introuvablesSyno); |
echo "\n\n"; |
// printf("noms: %d, introuvables: %d, introuvablesSyno: %d\n", count($noms), count($introuvables), count($introuvablesSyno)); |
// XXX, au 22/07/2013, 3 passes sont suffisantes |
// TODO: MySQL procédure stockée ! |
if($i++ == 3) break; |
$resultats = array_merge($resultats, $introuvables, $introuvablesSyno); |
$introuvables = $introuvablesSyno = array(); |
} |
foreach ($introuvablesSyno as $id => $nom) { |
$nn = $nom['num_nom']; |
$nnr = $nom['num_nom_retenu']; |
if (isset($noms[$nnr])) { |
$noms[$nn] = $noms[$nnr]; |
} else { |
$introuvables[] = $nn; |
} |
unset($introuvablesSyno[$id]); |
$this->afficherAvancement("Attribution de leur famille aux synonymes en cours"); |
} |
echo "\n"; |
$msg = 'Plusieurs familles sont introuvables'; |
$this->creerFichierLog($msg, $introuvables, 'famille_introuvable'); |
$this->remplirChpFamille($noms); |
} |
private function preparerTablePrChpFamille() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'famille' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD famille VARCHAR(255) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function recupererTuplesPrChpFamille() { |
$requete = 'SELECT num_nom, num_nom_retenu, num_tax_sup, rang, nom_sci '. |
"FROM {$this->table} ". |
"WHERE rang >= 180 ". |
"ORDER BY rang ASC, num_tax_sup ASC, num_nom_retenu DESC "; |
$resultat = $this->getBdd()->recupererTous($requete); |
return $resultat; |
} |
private function remplirChpFamille($noms) { |
foreach ($noms as $id => $famille) { |
$famille = $this->getBdd()->proteger($famille); |
$requete = "UPDATE {$this->table} SET famille = $famille WHERE num_nom = $id "; |
$resultat = $this->getBdd()->requeter($requete); |
if ($resultat === false) { |
throw new Exception("Erreur d'insertion pour le tuple $id"); |
} |
$this->afficherAvancement("Insertion des noms de famille dans la base en cours"); |
} |
echo "\n"; |
} |
private function genererChpHierarchie() { |
$this->initialiserGenerationChamps(); |
$this->preparerTablePrChpHierarchie(); |
$table = Config::get('tables.bdtfx'); |
$requete = "UPDATE $table SET hierarchie = NULL "; |
$mise_a_jour = $this->getBdd()->requeter($requete); |
$requete_hierarchie = "SELECT num_nom, num_nom_retenu, num_tax_sup FROM ".$table." ORDER BY rang DESC"; |
$resultat = $this->getBdd()->recupererTous($requete_hierarchie); |
$num_nom_a_num_sup = array(); |
foreach($resultat as &$taxon) { |
$num_nom_a_num_sup[$taxon['num_nom']] = $taxon['num_tax_sup']; |
} |
$chemin_taxo = ""; |
foreach($resultat as &$taxon) { |
$chemin_taxo = $this->traiterHierarchieNumTaxSup($taxon['num_nom_retenu'], $num_nom_a_num_sup).'-'; |
$requete = "UPDATE $table SET hierarchie = ".$this->getBdd()->proteger($chemin_taxo)." WHERE num_nom = ".$taxon['num_nom']." "; |
$mise_a_jour = $this->getBdd()->requeter($requete); |
$this->afficherAvancement("Insertion de la hierarchie taxonomique en cours"); |
} |
echo "\n"; |
} |
private function traiterHierarchieNumTaxSup($num_nom_retenu, &$num_nom_a_num_sup) { |
$chaine_hierarchie = ""; |
if(isset($num_nom_a_num_sup[$num_nom_retenu])) { |
$num_tax_sup = $num_nom_a_num_sup[$num_nom_retenu]; |
$chaine_hierarchie = '-'.$num_tax_sup; |
if($num_tax_sup != 0 && $num_tax_sup != '') { |
$chaine_hierarchie = $this->traiterHierarchieNumTaxSup($num_tax_sup, $num_nom_a_num_sup).$chaine_hierarchie; |
} |
} |
return $chaine_hierarchie; |
} |
private function preparerTablePrChpHierarchie() { |
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'hierarchie' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE {$this->table} ". |
'ADD hierarchie VARCHAR(1000) '. |
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL '; |
$this->getBdd()->requeter($requete); |
} |
} |
private function genererDonneesTestMultiVersion() { |
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSqlTest')); |
$this->executerScripSql($contenuSql); |
$table = Config::get('tables.bdtfx'); |
$tableTest = Config::get('tables.bdtfxTest'); |
$requete = "INSERT INTO $tableTest SELECT * FROM $table"; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerDonneesTestMultiVersion() { |
$tableMeta = Config::get('tables.bdtfxMeta'); |
$requete = "DELETE FROM $tableMeta WHERE guid = 'urn:lsid:tela-botanica.org:bdtfx:1.02'"; |
$this->getBdd()->requeter($requete); |
$tableTest = Config::get('tables.bdtfxTest'); |
$requete = "DROP TABLE IF EXISTS $tableTest"; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS bdtfx_meta, bdtfx_v1_01, bdtfx_v1_02"; |
$this->getBdd()->requeter($requete); |
} |
private function creerFichierLog($message, $lignes, $nomFichier) { |
$lignesNbre = count($lignes); |
if ($lignesNbre != 0) { |
echo "$message. Voir le log de $lignesNbre lignes :\n"; |
$logContenu = implode(", \n", $lignes); |
$logFichier = realpath(dirname(__FILE__))."/log/$nomFichier.log"; |
echo $logFichier."\n"; |
file_put_contents($logFichier, $logContenu); |
} |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/bdtfx/bdtfx.ini |
---|
New file |
0,0 → 1,19 |
version="2_01" |
dossierTsv = "{ref:dossierDonneesEflore}bdtfx/2.01/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
bdtfxMeta = "bdtfx_meta" |
bdtfx = "bdtfx_v{ref:version}" |
bdtfxTest = "bdtfx_v2_02" |
[fichiers] |
structureSql = "bdtfx_v{ref:version}.sql" |
structureSqlTest = "bdtfx_v2_02_test.sql" |
bdtfx = "bdtfx_v{ref:version}_ref.txt" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
structureSqlTest = "{ref:dossierSql}{ref:fichiers.structureSqlTest}" |
bdtfx = "{ref:dossierTsv}{ref:fichiers.bdtfx}" |
bdtfxTest = "{ref:dossierTsv}{ref:fichiers.bdtfxTest}" |
/tags/v5.7-arrayanal/scripts/modules/bdtfx |
---|
New file |
Property changes: |
Added: svn:ignore |
+bdtfx.ini |
/tags/v5.7-arrayanal/scripts/modules/sptb/sptb.ini |
---|
New file |
0,0 → 1,19 |
version="2012" |
dossierTsv = "{ref:dossierDonneesEflore}sptb/{ref:version}/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
especes = "sptb_especes_v2012" |
lois = "sptb_lois_v2012" |
referentielTaxo = "bdtfx_v1_02" |
[fichiers] |
structureSql = "sptb_v2012.sql" |
especes = "sptb_especes_v2012.tsv" |
lois = "sptb_lois_v2012.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
especes = "{ref:dossierTsv}{ref:fichiers.especes}" |
lois = "{ref:dossierTsv}{ref:fichiers.lois}" |
numNomRetenus = "{ref:dossierTsv}{ref:fichiers.numNomRetenus}" |
/tags/v5.7-arrayanal/scripts/modules/sptb/Sptb.php |
---|
New file |
0,0 → 1,90 |
<?php |
/** Exemple lancement: |
* /opt/lampp/bin/php -d memory_limit=3500M cli.php sptb -a chargerTous |
*/ |
class Sptb extends EfloreScript { |
public function executer() { |
// Lancement de l'action demandée |
try { |
$this->initialiserProjet('sptb'); |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerDonnees('especes'); |
$this->chargerDonnees('lois'); |
$this->genererChampNumNomRetenu(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerDonnees' : |
$this->chargerDonnees('especes'); |
$this->chargerDonnees('lois'); |
$this->genererChampNumNomRetenu(); |
break; |
case 'genererChampNumNomRetenu' : |
$this->genererChampNumNomRetenu(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function chargerDonnees($type) { |
$chemin = Config::get('chemins.'.$type); |
$table = Config::get('tables.'.$type); |
$requete = "LOAD DATA INFILE '$chemin' ". |
"REPLACE INTO TABLE $table ". |
'CHARACTER SET utf8 '. |
'FIELDS '. |
" TERMINATED BY '\t' ". |
" ENCLOSED BY '' ". |
" ESCAPED BY '\\\' ". |
'IGNORE 1 LINES'; |
$this->getBdd()->requeter($requete); |
} |
private function genererChampNumNomRetenu() { |
$this->preparerTablePrChpNumNomRetenu(); |
$this->genererNumNomRetenu(); |
} |
private function preparerTablePrChpNumNomRetenu() { |
$table = Config::get('tables.especes'); |
$requete = "SHOW COLUMNS FROM $table LIKE 'num_nom_retenu' "; |
$resultat = $this->getBdd()->recuperer($requete); |
if ($resultat === false) { |
$requete = "ALTER TABLE $table ". |
'ADD num_nom_retenu INT(10) '. |
'NULL DEFAULT NULL AFTER num_nom'; |
$this->getBdd()->requeter($requete); |
} |
} |
private function genererNumNomRetenu() { |
$table = Config::get('tables.especes'); |
$table_referentiel = Config::get('tables.referentielTaxo'); |
$requete = 'UPDATE '.$table.' s, '.$table_referentiel.' r '. |
'SET s.num_nom_retenu = r.num_nom_retenu '. |
' WHERE s.num_nom = r.num_nom '; |
$this->getBdd()->requeter($requete); |
} |
private function supprimerTous() { |
$requete = "DROP TABLE IF EXISTS sptb_meta, sptb_especes_v2012, sptb_lois_v2012"; |
$this->getBdd()->requeter($requete); |
Debug::printr('suppression'); |
} |
} |
?> |
/tags/v5.7-arrayanal/scripts/modules/sptba/sptba.ini |
---|
New file |
0,0 → 1,19 |
version="2012" |
dossierTsv = "{ref:dossierDonneesEflore}sptba/{ref:version}/" |
dossierSql = "{ref:dossierTsv}" |
[tables] |
especes = "sptba_especes_v2012" |
lois = "sptba_lois_v2012" |
referentielTaxo = "bdtxa_v1_00" |
[fichiers] |
structureSql = "sptba_v2012.sql" |
especes = "sptba_especes_v2012.tsv" |
lois = "sptba_lois_v2012.tsv" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
especes = "{ref:dossierTsv}{ref:fichiers.especes}" |
lois = "{ref:dossierTsv}{ref:fichiers.lois}" |
numNomRetenus = "{ref:dossierTsv}{ref:fichiers.numNomRetenus}" |
/tags/v5.7-arrayanal/scripts/modules/sptba/Sptba.php |
---|
New file |
0,0 → 1,90 |
<?php |
/** Exemple lancement: |
* /opt/lampp/bin/php -d memory_limit=3500M cli.php sptba -a chargerTous |
*/ |
class Sptba extends EfloreScript { |
public function executer() { |
// Lancement de l'action demandée |
try { |
$this->initialiserProjet('sptba'); |
$cmd = $this->getParametre('a'); |
switch ($cmd) { |
case 'chargerTous' : |
$this->chargerStructureSql(); |
$this->chargerDonnees('especes'); |
$this->chargerDonnees('lois'); |
$this->genererChampNumNomRetenu(); |
break; |
case 'chargerStructureSql' : |
$this->chargerStructureSql(); |
break; |
case 'chargerDonnees' : |
$this->chargerDonnees('especes'); |
$this->chargerDonnees('lois'); |
$this->genererChampNumNomRetenu(); |
break; |
case 'genererChampNumNomRetenu' : |
$this->genererChampNumNomRetenu(); |
break; |
case 'supprimerTous' : |
$this->supprimerTous(); |
break; |
default : |
throw new Exception("Erreur : la commande '$cmd' n'existe pas!"); |
} |
} catch (Exception $e) { |
$this->traiterErreur($e->getMessage()); |
} |
} |
private function chargerDonnees($type) { |
$chemin = Config::get('chemins.'.$type); |
$table = Conf |