Subversion Repositories eFlore/Projets.eflore-projets

Compare Revisions

No changes between revisions

Ignore whitespace Rev 995 → Rev 996

/tags/v5.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/scripts/tests/tmp
New file
Property changes:
Added: svn:ignore
+test.defaut.ini
+test.ini
/tags/v5.3-amandaie/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.3-amandaie/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.3-amandaie/scripts/modules/iso_3166_1
New file
Property changes:
Added: svn:ignore
+iso-3166-1.ini
/tags/v5.3-amandaie/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.3-amandaie/scripts/modules/baseflor/baseflor.ini
New file
0,0 → 1,52
version="2013_09_23"
dossierTsv = "{ref:dossierDonneesEflore}baseflor/2013-09-23/"
dossierSql = "{ref:dossierTsv}"
dossierRangSup = "{ref:dossierDonneesEflore}baseflor/2013-09-23/rang_sup/"
dossierIndex = "{ref:dossierDonneesEflore}baseflor/2013-09-23/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.3-amandaie/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.3-amandaie/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.3-amandaie/scripts/modules/baseflor/log
New file
Property changes:
Added: svn:ignore
+test
/tags/v5.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/scripts/modules/sitemap/sitemap.ini
New file
0,0 → 1,2
; Encodage : UTF-8
; ici mettre les variables du module
/tags/v5.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</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>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</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>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</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>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</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>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/scripts/modules/cel
New file
Property changes:
Added: svn:ignore
+o_*.comp.sql
/tags/v5.3-amandaie/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.3-amandaie/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.3-amandaie/scripts/modules/insee_d
New file
Property changes:
Added: svn:ignore
+insee-d.ini
/tags/v5.3-amandaie/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.3-amandaie/scripts/modules/bdtfx/bdtfx.ini
New file
0,0 → 1,19
version="2_00"
dossierTsv = "{ref:dossierDonneesEflore}bdtfx/2.00/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
bdtfxMeta = "bdtfx_meta"
bdtfx = "bdtfx_v{ref:version}"
bdtfxTest = "bdtfx_v2_00"
 
[fichiers]
structureSql = "bdtfx_v{ref:version}.sql"
structureSqlTest = "bdtfx_v2_01_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.3-amandaie/scripts/modules/bdtfx
New file
Property changes:
Added: svn:ignore
+bdtfx.ini
/tags/v5.3-amandaie/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.3-amandaie/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.3-amandaie/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 = 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 sptba_meta, sptba_especes_v2012, sptba_lois_v2012";
$this->getBdd()->requeter($requete);
Debug::printr('suppression');
}
}
?>
/tags/v5.3-amandaie/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.3-amandaie/scripts/modules/iso_639_1/Iso6391.php
New file
0,0 → 1,64
<?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 Iso6391 extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('iso-639-1');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerIso6391();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerIso6391' :
$this->chargerIso6391();
break;
case 'test' :
$this->tester();
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 tester() {
echo Config::get('test');
}
 
private function chargerIso6391() {
$chemin = Config::get('chemins.iso6391');
$table = Config::get('tables.iso6391');
$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 supprimerTous() {
$requete = "DROP TABLE IF EXISTS iso_639_1_meta, iso_639_1_v2002";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/iso_639_1/iso-639-1.ini
New file
0,0 → 1,14
version="2002"
dossierTsv = "{ref:dossierDonneesEflore}iso-639-1/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
iso6391 = "iso_639_1_v{ref:version}"
 
[fichiers]
structureSql = "iso-639-1_v{ref:version}.sql"
iso6391 = "iso-639-1_v{ref:version}.csv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
iso6391 = "{ref:dossierTsv}{ref:fichiers.iso6391}"
/tags/v5.3-amandaie/scripts/modules/iso_639_1
New file
Property changes:
Added: svn:ignore
+iso-639-1.ini
/tags/v5.3-amandaie/scripts/modules/eflore/Eflore.php
New file
0,0 → 1,54
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M cli.php eflore -a chargerTous
*/
class Eflore extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('eflore');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerOntologies();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
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 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 eflore_meta, eflore_ontologies";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/eflore/get-donnees-fiches-eflore.php
New file
0,0 → 1,181
<?php
/**
* @category PHP 5.2
* @package Framework
* @author Raphaël Droz <raphael@tela-botanica.org>
* @copyright Copyright (c) 2013, 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
*/
 
/*
- bootstrap le framework
- bootstrap une fiche
- puis, pour un ou plusieurs onglet (automatique ou manuellement),
obtient les données correspondante.
 
L'objectif est de pouvoir générer un flux de données exhaustive pour une Fiche donnée
tout en restant assez indépendant des (lourds) appels à l'API.
Une finalité est de pouvoir s'orienter vers un cron pour index Sphinx, tout en
permettant d'identifier les limites de l'API.
*/
 
 
define('_DIR_FRAMEWORK', '/home/raphael/TBF/trunk/framework');
define('_DIR_CONSULT', '/home/raphael/eflore/consultation');
define('_DIR_SERVICES', '/home/raphael/eflore/projets/services/modules/0.1');
 
//require_once __DIR__ . '/../../framework.php';
set_include_path(_DIR_FRAMEWORK . PATH_SEPARATOR .
_DIR_CONSULT . '/controleurs' . PATH_SEPARATOR .
_DIR_CONSULT . '/bibliotheque' . PATH_SEPARATOR .
_DIR_CONSULT . '/modules/fiche' . PATH_SEPARATOR .
_DIR_CONSULT . '/metier/api_0.1' . PATH_SEPARATOR .
_DIR_SERVICES . '/commun' . PATH_SEPARATOR .
_DIR_SERVICES . '/bdtfx' . PATH_SEPARATOR .
_DIR_CONSULT . '/modules/fiche/formateurs' . PATH_SEPARATOR .
get_include_path());
spl_autoload_extensions('.php');
spl_autoload_register();
 
/*require_once _DIR_FRAMEWORK . '/Controleur.php';
require_once _DIR_CONSULT . '/controleurs/AppControleur.php';
require_once _DIR_CONSULT . '/bibliotheque/AppUrls.php';
require_once _DIR_CONSULT . '/controleurs/aControleur.php';
require_once _DIR_CONSULT . '/bibliotheque/Conteneur.php';
require_once _DIR_CONSULT . '/modules/fiche/Fiche.php';*/
 
 
// require_once _DIR_CONSULT . '/modules/fiche/Fiche.php'
require_once('Framework.php');
Framework::setCheminAppli(__FILE__);
Framework::setInfoAppli(Config::get('info'));
// idéalement
// $a = new Fiche(new Conteneur(array()));
 
 
require_once('Config.php');
require_once('Controleur.php');
require_once('aControleur.php');
require_once('AppControleur.php');
require_once('AppUrls.php');
require_once('Conteneur.php');
 
AppControleur::initialiser();
 
require_once('Commun.php');
require_once('CommunNomsTaxons.php');
require_once('Eflore.php');
require_once('Taxons.php');
require_once('Noms.php');
 
require_once('NomCourant.php');
require_once('Nom.php');
 
Config::charger(_DIR_FRAMEWORK . '/config.ini');
Config::charger(_DIR_CONSULT . '/configurations/config.ini');
 
 
require_once('Fiche.php');
$a = new Fiche();
$_GET['num_nom'] = 141;
$_GET['referentiel'] = 'bdtfx';
 
$a->initialiser();
 
$classes = array(
// 'illustrations',
// 'repartition',
// 'ecologie', // fait main (mais peu utile)
 
// 'nomenclature', // TODO
// 'description', // fait main
// 'ethnobotanique', // fait main
// 'bibliographie', // fait main
// 'statut', // TODO
);
 
// pour nomenclature
require_once('MetaDonnees.php');
require_once('Wikini.php');
 
// pour description
require_once('Textes.php');
require_once('Informations.php');
 
// pour ethnobotanique
require_once('NomsVernaculaires.php');
 
// pour bibliographie
require_once('BiblioBota.php');
 
// pour statuts
require_once('Statuts.php');
 
// pour ecologie
require_once('Graphiques.php');
require_once('Syntaxons.php');
 
// pour repartition
require_once('Cartes.php'); // TODO
 
// way 1
foreach($classes as $c) {
$a->onglet = $c;
$b = $a->obtenirDonnees();
var_dump($b);die();
}
 
 
// non-nécessaire si l'on peut récupérer le conteneur
// initialisé par new Fiche()
// $conteneur = new Conteneur($a->parametres);
 
// description
$onglet = new Description($a->conteneur);
$onglet->obtenirDonnees();
$onglet->getCoste();
echo implode('; ', $onglet->donnees['wikini']['description']);
echo implode('; ', $onglet->donnees['coste']['description']);
 
// bibliographie
Config::charger(_DIR_CONSULT . '/configurations/bdtfx.ini');
$onglet = new Bibliographie($a->conteneur);
$onglet->obtenirDonnees();
echo implode('; ', $onglet->donnees['flores']['liste_flores']);
echo implode('; ', $onglet->donnees['bibliobota']['references']);
 
// ethnobota
Config::charger(_DIR_CONSULT . '/configurations/bdtfx.ini');
$onglet = new Ethnobotanique($a->conteneur);
$onglet->obtenirDonnees();
echo implode('; ', array_map(function($v) { return $v['nom_vernaculaire']; }, $onglet->donnees['nvjfl']['noms'])) . '; ' .
implode('; ', array_map(function($v) { return $v['nom_vernaculaire']; }, $onglet->donnees['nvps']['noms']));
 
// ecologie
Config::charger(_DIR_CONSULT . '/configurations/bdtfx.ini');
$onglet = new Ecologie($a->conteneur);
// $onglet->obtenirDonnees(); // slow !
// var_dump($onglet->donnees['baseflor']['legende']);
 
 
 
/*
API: TODO:
- Chaque service de /consultation/formateur/ doit définir en en-tête:
* référentiels supportés
* fichiers/directives de configuration nécessaire
* class utilisées (namespace "use")
 
- obtenirDonnees() doit prendre ses paramètres [optionnels] par argument, sans compter
sur l'instanciation et la définition d'attributs
- obtenirDonnees() doit retourner les valeurs générées
- obtenirDonnees() ne doit pas traiter le formattage des résultats (getBloc() oui)
- si $this->données reste nécessaire pour une quelconque raison, celui-ci doit être public
 
- pour Fiche.php
- onglets ne doit plus être un attribut (pas même public)
- executerFiche(), executerOnglet() et obtenirDonnees() doivent prendre un $onglet comme paramètre
- $parametre et $conteneur doivent être "public"
 
*/
/tags/v5.3-amandaie/scripts/modules/eflore/eflore.ini
New file
0,0 → 1,14
version="2011"
dossierTsv = "{ref:dossierDonneesEflore}eflore/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
ontologies = "eflore_ontologies"
 
[fichiers]
structureSql = "eflore_v2011.sql"
ontologies = "eflore_ontologies_v2011.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.3-amandaie/scripts/modules/sauvages/Sauvages.php
New file
0,0 → 1,258
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php sauvages -a chargerTous
*/
class Sauvages extends EfloreScript {
private $contenu_fichier = array();
protected $parametres_autorises = array(
'-f' => array(true, true, 'Nom du fichier ou du dossier à traiter'));
private $caracteresAccentues = array(
'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î',
'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß',
'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î',
'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā',
'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď',
'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ',
'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ',
'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ',
'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ',
'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ',
'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ',
'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż',
'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ',
'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
private $caracteresNormaux = array(
'A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I',
'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's',
'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i',
'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a',
'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd',
'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g',
'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i',
'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l',
'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R',
'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't',
'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y',
'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I',
'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('sauvages');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->creerXmlTaxons();
$this->creerXmlCriteres();
break;
case 'creerXmlCriteres' :
$this->creerXmlCriteres();
break;
case 'creerXmlTaxons' :
$this->creerXmlTaxons();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
public function creerXmlCriteres() {
$this->recupererContenuFichier();
$criteres_nom = $this->contenu_fichier[0];
unset($this->contenu_fichier[0]);
$criteres_label = $this->contenu_fichier[1];
unset($this->contenu_fichier[1]);
$description_label = $this->contenu_fichier[2];
unset($this->contenu_fichier[2]);
$criteres_valeurs = $this->extraireValeurs();
$xml = $this->formerXmlCriteres($criteres_nom, $criteres_label, $description_label, $criteres_valeurs);//print_r($xml);
file_put_contents("./xml_criteres.xml", $xml);
}
public function formerXmlCriteres($nom, $label, $description, $valeurs) {
$xml='<keys>
<groupe id="1">
<nom>Arbres</nom>
<media>images/pictos/icone_arbre.png</media>
<criteres>';
foreach ($label as $id=>$criteres) {
if ($id > 2) {
$xml .= '<critere id="1.'.$id.'">
<label>'.$criteres.'</label>
<description>'.$description[$id].'</description>
<valeurs>';
foreach ($valeurs[$id] as $id_val=>$valeur) {
if ($valeur != "0") {
$crit = str_replace(" ", "_", $this->supprimerAccents($nom[$id]));
$val = str_replace(" ", "_", $this->supprimerAccents($valeur));
$image = $crit."_".$val;
$xml .= '<valeur code="1.'.$id.'.'.$id_val.'" media="images/pictos/'.$image.'.png">'.$valeur.'</valeur>';
}
}
$xml .= '</valeurs></critere>';
}
}
$xml .= "</criteres>
</groupe>
</keys>";
return $xml;
}
private function extraireValeurs() {
$valeurs = array();
foreach ($this->contenu_fichier as $ligne) {
$i = 0;
foreach ($ligne as $critere) {
if (!isset($valeurs[$i]) || !in_array(trim($critere), $valeurs[$i])) {
$valeurs[$i][] = trim($critere);
}
$i++;
}
}
return $valeurs;
}
public function creerXmlTaxons() {
$this->recupererContenuFichier();
$criteres_label = array_flip($this->contenu_fichier[0]);
unset($this->contenu_fichier[0]);
unset($this->contenu_fichier[1]);
unset($this->contenu_fichier[2]);
$criteres_valeurs = $this->extraireValeurs();
$xml = $this->formerXmlTaxons($criteres_label, $criteres_valeurs); //print_r($xml);
file_put_contents("./xml_taxons.xml", $xml);
}
public function formerXmlTaxons($criteres_label, $criteres_valeurs) {
$xml='<?xml version="1.0" ?><TAXONS SUBJECT="XML">';
$rest = new RestClient();
foreach ($this->contenu_fichier as $id=>$taxon) {
$infos_taxon = $this->rechercherInfosTaxon($rest, $taxon[$criteres_label["nom scientifique"]]);
$xml .= '<TAXON id="'.$id.'" value="'.
ucfirst($taxon[$criteres_label["nom vernaculaire"]]).'" sciName="'.trim($taxon[$criteres_label["nom scientifique"]]).'" groupe="1">
<DESCRIPTION>'.$infos_taxon["description"].'</DESCRIPTION>
<PICTURES>';
if ($infos_taxon["images"] != array()) {
foreach ($infos_taxon["images"] as $image) {
$xml .= '<PICTURE media="'.$image["binaire.href"].'"><author>'.$image["auteur.libelle"].'</author></PICTURE>';
}
}
$xml .= '</PICTURES><CRITERIAS>';
for ($i=3; $i < count($taxon); $i++) {
if (trim($taxon[$i]) !== "0") {
$xml .= '<VALUE code="1.'.$i.'.'.array_search(trim($taxon[$i]), $criteres_valeurs[$i]).'"/>';
}
}
$xml .= '</CRITERIAS></TAXON>';
}
$xml .= "</TAXONS>";
return $xml;
}
private function rechercherInfosTaxon($rest, $ns) {
$info = array("description" => "", "images" => array());
$reponse = $this->consulterWebService($rest, "bdtfx",
"noms", "?retour.champs=nom_retenu.id,num_taxonomique&retour.tri=retenu&masque=".urlencode(trim($ns)));
if (is_array($reponse["resultat"])) {
$num_nom = $reponse["resultat"][key($reponse["resultat"])]["nom_retenu.id"];
$num_taxon = $reponse["resultat"][key($reponse["resultat"])]['num_taxonomique'];
}
$url_wiki = "http://www.tela-botanica.org/wikini/eFloreRedaction/api/rest/0.5/pages/SmartFloreBDTFXnt".
$num_taxon."?txt.format=text/plain&txt.section.titre=Comment%20la%20reconnaître%20%3F";
$wiki = $rest->consulter($url_wiki); $wiki = json_decode($wiki, true);
if ($wiki['texte'] != ""){
$info["description"] = $this->formaterSmatflore($wiki['texte']);
} else {
$coste = $this->consulterWebService($rest, "coste", "textes", "/bdtfx.nn:".$num_nom);
if ($coste['resultats'] != array() && $coste['resultats'][key($coste["resultats"])]['texte'] != "") {
$texte = str_replace("**", "", $coste['resultats'][key($coste["resultats"])]['texte']);
$texte = str_replace("//", "", $texte);
$texte = explode(" – ", $texte);
unset($texte[0],$texte[1]);
if (strpos($texte[2], ";") === false) {unset($texte[2]);} //else {print_r($texte[2]);}
if (preg_match('/^[\w|\s|\-|,]*\.*\s*$/', $texte[2]) == true) {print_r($texte[2]); unset($texte[2]);}
$info["description"] = implode(" – ", $texte);
} else {
$baseflor = $this->consulterWebService($rest, "baseflor", "informations", "/bdtfx.nn:".$num_nom);
$info["description"] = $this->formaterBaseflor($baseflor);
}
}
if ($info["description"] == "En cours de rédaction.") {echo $num_nom." ".$ns;
print_r($coste);
}
$reponse = $this->consulterWebService($rest, "cel", "images", "?navigation.limite=5&retour.format=CRS&masque.nn=".$num_nom);
$info["images"] = $reponse["resultats"];
return $info;
}
 
private function formaterSmatflore($texte) {
$a_enlever = array(Chr(10).'=', '='.Chr(10), Chr(10).''.Chr(10));
$texte = str_replace($a_enlever, '', $texte);
$texte = str_replace(Chr(10), '<br />', $texte);
return $texte;
}
private function formaterBaseflor($reponse) {
$description = "En cours de rédaction.";
if ($reponse["nom_sci"] != "") {
$description = "Formation végétale : ".$reponse["form_vegetale"]."; ".
"Inflorescence : ".$reponse["inflorescence"]."; ".
"Couleur de la fleur : ".$reponse["couleur_fleur"]."; ".
"Sexualité : ".$reponse["sexualite"]."; ".
"Fruit : ".$reponse["fruit"]."; ".
"Pollinisation : ".$reponse["pollinisation"]."; ".
"Dissémination : ".$reponse["dissemination"]."; ".
"Ecologie : ".$reponse["carac_ecolo"]." – ".
"Chorologie : ".$reponse["chorologie"]."; ".
"Floraison : ".$reponse["floraison"];
}
return $description;
}
private function consulterWebService($rest, $projet,$resssource,$parametres) {
$url_id = "http://www.tela-botanica.org/service:eflore:0.1/".$projet."/".$resssource.$parametres;
$reponse = $rest->consulter($url_id);
return json_decode($reponse, true);
}
private function recupererContenuFichier() {
$nomFichier = Config::get('dossierCsv').Config::get('projet');
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 du fichier : ";
while (!$file->eof()){
$ligne_csv = $file->fgetcsv($delimiter = ';');
$this->contenu_fichier[$i] = $ligne_csv;
echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++;
}
echo "\n";
} else {
$this->traiterErreur("Le fichier : $nomFichier n'est pas au format csv.");
}
} else {
$this->traiterErreur("Le fichier : $nomFichier n'existe pas.");
}
}
public function supprimerAccents($chaine) {
return str_replace($this->caracteresAccentues, $this->caracteresNormaux, $chaine);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/sauvages/sauvages.ini
New file
0,0 → 1,5
version="1"
projet="cles_sauvages.csv"
dossierCsv = "{ref:dossierDonneesEflore}sauvages/1/"
chemin_appli = "php:Framework::getCheminAppli()"
 
/tags/v5.3-amandaie/scripts/modules/nvjfl/nvjfl.ini
New file
0,0 → 1,23
version = "2007"
dossierTsv = "{ref:dossierDonneesEflore}nvjfl/2007-10-29/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
nvjfl = "nvjfl_v{ref:version}"
nvjflLienBiblio = "nvjfl_lien_biblio_v{ref:version}"
nvjflBiblio = "nvjfl_biblio_v{ref:version}"
ontologies = "nvjfl_ontologies_v{ref:version}"
 
[fichiers]
structureSql = "nvjfl_v{ref:version}.sql"
nvjfl = "{ref:tables.nvjfl}.tsv"
nvjflBiblio = "{ref:tables.nvjflBiblio}.tsv"
nvjflLienBiblio = "{ref:tables.nvjflLienBiblio}.tsv"
ontologies = "{ref:tables.ontologies}.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
nvjfl = "{ref:dossierTsv}{ref:fichiers.nvjfl}"
nvjflBiblio = "{ref:dossierTsv}{ref:fichiers.nvjflBiblio}"
nvjflLienBiblio = "{ref:dossierTsv}{ref:fichiers.nvjflLienBiblio}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.3-amandaie/scripts/modules/nvjfl/Nvjfl.php
New file
0,0 → 1,180
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php nvjfl
* -a chargerTous
* Options :
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).
*/
class Nvjfl 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('nvjfl');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerNvjfl();
$this->chargerBiblio();
$this->chargerBiblioLien();
$this->chargerOntologies();
break;
case 'chargerStructure' :
$this->chargerStructureSql();
break;
case 'chargerNvjfl' :
$this->chargerNvjfl();
break;
case 'chargerBiblio' :
$this->chargerBiblio();
break;
case 'chargerBiblioLien' :
$this->chargerBiblioLien();
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());
}
}
 
/**
* Charge le fichier en créant un id pour chaque nom vernaculaire.
*/
private function chargerNvjfl() {
//Debug::printr(Config::get('fichiers'));
$fichierOuvert = $this->ouvrirFichier(Config::get('chemins.nvjfl'));
$donnees = $this->analyserFichier($fichierOuvert);
fclose($fichierOuvert);
foreach ($donnees as $donnee) {
$requete = 'INSERT INTO '.Config::get('tables.nvjfl').' VALUES ('.implode(', ', $donnee).')';
$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 analyserFichier($fichierOuvert) {
$donnees = array();
$entetesCsv = fgets($fichierOuvert);
while ($ligneCsv = fgets($fichierOuvert)) {
$champs = explode("\t", trim($ligneCsv));
if (count($champs) > 0) {
if (isset($champs[2])) {
$nomVernaculaire = $champs[2];
$indexCourrant = $this->getIndexNomVernaculaire($nomVernaculaire);
$champs = array_merge(array($indexCourrant), $champs);
$donnees[] = $this->protegerValeursDesChamps($champs);
}
}
$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 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 protegerValeursDesChamps($champs) {
$champsProteges = array();
for ($i = 0; $i < 9; $i++) {
$valeur = isset($champs[$i]) ? $champs[$i] : '';
$champsProteges[] = $this->getBdd()->proteger($valeur);
}
return $champsProteges;
}
 
private function chargerBiblio() {
$cheminsNvjflBiblio = Config::get('chemins.nvjflBiblio');
$tableNvjflBiblio = Config::get('tables.nvjflBiblio');
$requete = "LOAD DATA INFILE '$cheminsNvjflBiblio' ".
"REPLACE INTO TABLE $tableNvjflBiblio ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerBiblioLien() {
$cheminNvjflLienBiblio = Config::get('chemins.nvjflLienBiblio');
$tableNvjflLienBiblio = Config::get('tables.nvjflLienBiblio');
$requete = "LOAD DATA INFILE '$cheminNvjflLienBiblio' ".
"REPLACE INTO TABLE $tableNvjflLienBiblio ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerOntologies() {
$cheminOntologies = Config::get('chemins.ontologies');
$tableOntologies = Config::get('tables.ontologies');
$requete = "LOAD DATA INFILE '$cheminOntologies' ".
"REPLACE INTO TABLE $tableOntologies ".
'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 nvjfl_biblio_v2007, nvjfl_lien_biblio_v2007, nvjfl_meta, nvjfl_ontologies_v2007, nvjfl_v2007";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/nvjfl
New file
Property changes:
Added: svn:ignore
+nvjfl.ini
/tags/v5.3-amandaie/scripts/modules/liste_rouge/ListeRouge.php
New file
0,0 → 1,114
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M cli.php sptb -a chargerTous
*/
class ListeRouge extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('liste_rouge');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerDonnees();
$this->genererChampNumNomRetenu();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerDonnees' :
$this->chargerDonnees();
$this->genererChampNumNomRetenu();
break;
case 'genererChampNumNomRetenu' :
$this->genererChampNumNomRetenu();
break;
case 'ajouterChampNumNomRetenu' :
$this->ajouterChampNumNomRetenu();
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 = Config::get('chemins.listeRouge');
$table = Config::get('tables.listeRouge');
$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();
$this->recupererNumNomNonTrouve();
}
private function preparerTablePrChpNumNomRetenu() {
$table = Config::get('tables.listeRouge');
$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` VARCHAR( 10 ) NOT NULL ,'.
' ADD `nom_sci` VARCHAR( 500 ) NOT NULL ,'.
' ADD INDEX ( `num_nom_retenu` ) ';
$this->getBdd()->requeter($requete);
}
}
private function genererNumNomRetenu() {
$table = Config::get('tables.listeRouge');
$table_referentiel = Config::get('tables.referentielTaxo');
$requete = 'UPDATE '.$table.' s, '.$table_referentiel.' r '.
'SET s.num_nom_retenu = r.num_nom_retenu, s.nom_sci = r.nom_complet '.
'WHERE s.nom_sci_orig = r.nom_complet ';
$this->getBdd()->requeter($requete);
}
private function recupererNumNomNonTrouve() {
$table = Config::get('tables.listeRouge');
$requete = 'SELECT `id`, `nom_sci_orig`'.
' FROM '.$table.
' WHERE `num_nom_retenu` = ""';
$noms = $this->getBdd()->recupererTous($requete);
$debug = "Noms sans correspondance avec bdtfx :\n";
foreach ($noms as $nom) {
$debug .= $nom['id']." ".$nom['nom_sci_orig']."\n";
}
Debug::printr($debug);
}
 
private function ajouterChampNumNomRetenu() {
$chemin = Config::get('chemins.listeRougeCorresp');
$table = Config::get('tables.listeRouge');
$requetes = $this->recupererContenu($chemin);
$this->executerScripSql($requetes);
}
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS liste_rouge_meta, liste_rouge_v2012";
$this->getBdd()->requeter($requete);
Debug::printr('suppression');
}
}
?>
/tags/v5.3-amandaie/scripts/modules/liste_rouge/liste_rouge.ini
New file
0,0 → 1,17
version="2012"
dossierTsv = "{ref:dossierDonneesEflore}liste_rouge/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
listeRouge = "liste_rouge_v{ref:version}"
referentielTaxo = "bdtfx_v2_00"
 
[fichiers]
structureSql = "liste_rouge_v{ref:version}.sql"
listeRouge = "liste_rouge_v{ref:version}.tsv"
listeRougeCorresp = "liste_rouge_correspondance_v{ref:version}.sql"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
listeRouge = "{ref:dossierTsv}{ref:fichiers.listeRouge}"
listeRougeCorresp = "{ref:dossierTsv}{ref:fichiers.listeRougeCorresp}"
/tags/v5.3-amandaie/scripts/modules/robot/Robot.php
New file
0,0 → 1,432
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Robots
*
* Description : classe permettant d'analyser les pages d'un site web.
* Notes : les noms des pages doivent être dans la bonne casse. http://fr.wikipedia.org/wiki/ambronay ne renvera rien alors que
* http://fr.wikipedia.org/wiki/Ambronay renvera un résultat (Notez le A ou a).
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Tela-Botanica 1999-2009
* @link http://www.tela-botanica.org/wikini/eflore
* @licence GPL v3 & CeCILL v2
* @version $Id: Robot.class.php 2057 2011-05-13 16:39:06Z Jean-Pascal MILCENT $
*/
// +-------------------------------------------------------------------------------------------------------------------+
class Robot extends ScriptCommande {
/**
* Indique le nom du Robot.
*/
private $robot_nom;
/**
* Indique le fichier de config de la gestion des cookies du Robot.
*/
private $cookie;
/**
* Indique l'url de départ du Robot.
*/
private $page;
/**
* Tableau des URLs à analyse
*/
private $pages = array();
/**
* Chemin vers un fichier contenant les noms des pages à analyser (un nom de page par ligne).
*/
private $page_fichier;
/**
* Contient soit False soit le chemin vers le dossier où mettre les pages en cache.
*/
private $cache = false;
/**
* Contient le squelette de l'url à utiliser pour récupérer les pages web.
*/
private $url_tpl = '';
/**
* Contient false ou l'encodage des pages d'un site web si celui-ci n'est pas en UTF-8.
*/
private $encodage = false;
/**
* Contient la chaine de caractères indiquant où commencer une recherche d'informations dans la page web.
*/
private $chaine_debut = '';
/**
* Contient la chaine de caractères indiquant où terminer une recherche d'informations dans la page web.
*/
private $chaine_fin = '';
/**
* Tableau des expressions régulières récupérant des données lors de l'analyse
*/
private $regexps = array();
/**
* Indique le dossier ou fichier où le Robot doit sotcker les informations collectées.
*/
private $sortie;
 
public $parametres = array( '-pgf' => array(false, '', 'Fichier contenant les pages que le Robot doit analyser'),
'-s' => array(false, '', 'Fichier où stocker les données récupérées par le Robot'),
'-pg' => array(false, '', 'Nom de la page que le Robot doit analyser'));
 
 
public function executer() {
$this->page = $this->getParam('pg');
$this->page_fichier = $this->getParam('pgf');
$this->cookie = dirname(__FILE__).DS.'configuration'.DS.'cookieconf.txt';
$this->sortie = $this->getParam('s');
 
// Construction du tableau contenant les noms des pages à analyser
if (empty($this->page_fichier)) {
$this->pages[] = $this->page;
} else {
$this->pages = $this->convertirFichierEnTableau($this->page_fichier);
}
 
// Création du chemin du cache si le fichier ini du projet l'indique
if ($this->getIni('cache_chemin')) {
$this->cache = $this->getIni('cache_chemin');
}
 
// Lancement du Robot demandé
$cmd = $this->getParam('a');
switch ($cmd) {
case 'wp' :
$this->lancerRobotWikipedia();
break;
case 'wp-pays' :
$this->lancerRobotWikipediaPays();
break;
case 'wp-liste-communes' :
$this->lancerRobotWikipediaListeCommunes();
break;
case 'ipni' :
$this->lancerRobotIpni();
break;
case 'cassini' :
$this->lancerRobotCassini();
break;
case 'utm' :
$this->lancerRobotUtmConverter();
break;
default :
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
}
}
 
/**
* Robot analysant les pages de Wikipedia correspondant à des communes.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pgf ~/importation/robots/eFloreBotWp_INSEE_C.txt -s ~/importation/robots/wp_communes.tsv
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pg Montpellier -s ~/importation/robots/wp_communes.tsv
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pg Montpellier
*
* @return unknown_type
*/
private function lancerRobotWikipedia() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotWp';
$this->url_tpl = 'http://fr.wikipedia.org/wiki/%s';
$this->regexp_ligne = '/<!-- bodytext -->(.*)<!-- \/bodytext -->/umsi';
$this->regexps = array( 'CodeInsee' => 'Code commune<\/a><\/th>(?:\n|\r\n)<td>(\d+)<\/td>',
'Nom' => 'class="entete map" style="[^"]+">(.*)<',
'Latitutde' => '<span class="geo-dec geo" title=".*"><span class="latitude">(.*)<\/span>',
'Longitude' => '<span class="geo-dec geo" title=".*">.*<\/span>, <span class="longitude">(.*)<\/span>',
'Superficie' => 'Superficie<\/a>(?:<\/b><\/td>|<\/th>)(?:\n|\r\n)<td>((?:[0-9]| |&#160;)+(?:,[0-9]+)?) km<sup>2<\/sup>',
'AltitudeMin' => 'Altitudes<\/a><\/th>(?:\n|\r\n)<td>mini. (-?[0-9]+) m — maxi. [ 0-9]+ m<\/td>',
'AltitudeMax' => 'Altitudes<\/a><\/th>(?:\n|\r\n)<td>mini. -?[0-9]+ m — maxi. ([ 0-9]+) m<\/td>',
'Population' => 'Population<\/a><\/th>(?:\n|\r\n)<td>(.*) hab.',
'PopulationAnnee' => 'Population<\/a><\/th>(?:\n|\r\n)<td>.* hab. <small>\(<a href="\/wiki\/[0-9]+"(?: title="[0-9]+")?>([0-9]+)<\/a>',
'CodePostal' => 'Code postal<\/a><\/th>(?:\n|\r\n)<td>([0-9]{5}).*<\/td>',
'PageWikipedia' => '(?:Ce document provient|Récupérée) de « <a href="http:\/\/fr.wikipedia.org\/wiki\/(.*)">'
);
// Préparation des noms des pages
foreach ($this->pages as $id => $nom) {
$this->pages[$id] = str_replace(' ', '_', $nom);
}
$this->analyserUrls();
}
 
/**
* Robot analysant les pages de Wikipedia correspondant à des pays.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp-pays -pgf ~/importation/robots/eFloreBotWp_pays.txt -s ~/importation/robots/wp-pays.tsv
*
* @return unknown_type
*/
private function lancerRobotWikipediaPays() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotWp';
$this->url_tpl = 'http://fr.wikipedia.org/wiki/%s';
$this->regexp_ligne = '/<!-- bodytext -->(.*)<!-- \/bodytext -->/umsi';
$this->regexps = array( 'Nom' => '<table class="infobox_v2" cellspacing="[^"]+" style="[^"]+">(?:\n|\r\n)<caption style="[^"]+"><b>(.*)<\/b>',
'Latitutde' => '<span class="geo-dec geo" title=".*"><span class="latitude">(.*)<\/span>',
'Longitude' => '<span class="geo-dec geo" title=".*">.*<\/span>, <span class="longitude">(.*)<\/span>',
'Superficie' => 'Superficie<\/a><\/b><\/td>(?:\n|\r\n)<td>((?:[0-9]|\s*|&#160;)+(?:,[0-9]+)?)(?:&#160;|\s*)km<sup>2<\/sup>',
'Population' => 'Population<\/a><\/b>(?:&#160;|\s)*<small>\([0-9]+\)<\/small><\/td>(?:\n|\r\n)<td>(.*)(?:&#160;|\s*)hab.',
'PopulationAnnee' => 'Population<\/a><\/b>(?:&#160;|\s)*<small>\(([0-9]+)\)',
'Capitale' => 'Capitale<\/a><\/b><\/td>(?:\n|\r\n)<td>(?:<a href="\/wiki\/[^"]+" title="[^"]+">|)(.+)<',
'PageWikipedia' => '(?:Ce document provient|Récupérée) de « <a href="http:\/\/fr.wikipedia.org\/wiki\/(.*)">'
);
// Préparation des noms des pages
foreach ($this->pages as $id => $nom) {
$this->pages[$id] = str_replace(' ', '_', $nom);
}
$this->analyserUrls();
}
 
/**
* Robot analysant une page de wikipedia à la recherche de plusieurs données par page.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pgf ~/importation/robots/eFloreBotWp_INSEE_C.txt -s ~/importation/robots/wp_communes.tsv
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pg Montpellier -s ~/importation/robots/wp_communes.tsv
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pg Montpellier
*
* @return unknown_type
*/
private function lancerRobotWikipediaListeCommunes() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotWpListe';
$this->url_tpl = 'http://fr.wikipedia.org/wiki/%s';
$this->regexp_ligne = '/<tr>(.*)?<\/tr>/Uumsi';
$this->mode = 'MULTI';
$this->regexps = array( 'PageWikipedia' => '^<td align="left"><a href="\/wiki\/([^"]+)"',
'CodeInsee' => '^<td>.+<\/td>(?:\n|\r\n)<td>(\d+)<\/td>',
'CodePostal' => '^(?:<td>.+<\/td>(?:\n|\r\n)){2}<td>(\d+)<\/td>',
'Superficie' => '^(?:<td>.+<\/td>(?:\n|\r\n)){4}<td><span.+span>((?:[0-9]| |&#160;)+(?:,[0-9]+)?)<\/td>',
'Population' => '^(?:<td>.+<\/td>(?:\n|\r\n)){5}<td><span.+span>((?:[0-9]| |&#160;)+)<\/td>'
);
// Préparation des noms des pages
foreach ($this->pages as $id => $nom) {
$this->pages[$id] = str_replace(' ', '_', $nom);
}
$this->analyserUrls();
}
 
/**
* Robot analysant les pages du site de l'IPNI.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p ipni_auteur -a wp -pgf ~/importation/robots/eFloreBotIpni_auteur.txt -s ~/importation/robots/ipni_auteurs.tsv
* /opt/lampp/bin/php script.php robot -p ipni_auteur -a wp -pg Z -s ~/importation/robots/ipni_auteurs.tsv
* /opt/lampp/bin/php script.php robot -p ipni_auteur -a wp -pg Z
*
* @return unknown_type
*/
private function lancerRobotIpni() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotIpni';
$this->url_tpl = 'http://ipni.org/ipni/advAuthorSearch.do?output_format=delimited&find_surname=%s*';
$this->regexp_ligne = '/^(.*)$/umi';
$this->regexps = array( 'Id' => '^([^%]+)%' ,
'Version' => '^(?:[^%]*%){1,}([^%]*)%' ,
'DefaultAuthorName' => '^(?:[^%]*%){2,}([^%]*)%' ,
'DefaultAuthorForename' => '^(?:[^%]*%){3,}([^%]*)%' ,
'DefaultAuthorSurname' => '^(?:[^%]*%){4,}([^%]*)%' ,
'StandardForm' => '^(?:[^%]*%){5,}([^%]*)%' ,
'NameNotes' => '^(?:[^%]*%){6,}([^%]*)%' ,
'NameSource' => '^(?:[^%]*%){7,}([^%]*)%' ,
'Dates' => '^(?:[^%]*%){8,}([^%]*)%' ,
'DateTypeCode' => '^(?:[^%]*%){9,}([^%]*)%' ,
'DateTypeString' => '^(?:[^%]*%){10,}([^%]*)%' ,
'AlternativeAbbreviations' => '^(?:[^%]*%){11,}([^%]*)%' ,
'AlternativeNames' => '^(?:[^%]*%){12,}([^%]*)%' ,
'TaxonGroups' => '^(?:[^%]*%){13,}([^%]*)%' ,
'ExampleOfNamePublished' => '^(?:[^%]*%){14,}([^%]*)$' );
$this->analyserUrls();
}
 
/**
* Robot analysant les pages du site de Cassini.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pgf ~/importation/robots/eFloreBotCassini.txt -s ~/importation/robots/cassini.tsv
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pg 1 -s ~/importation/robots/cassini.tsv
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pg 1
*
* @return unknown_type
*/
private function lancerRobotCassini() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotCassini';
$this->url_tpl = 'http://cassini.ehess.fr/cassini/fr/html/fiche.php?select_resultat=%s';
$this->encodage = 'ISO-8859-1';
$this->regexp_ligne = '/\s*var\s+chaine1\s+\t=\s+"(.*?)";/umsi';
$this->regexps = array( 'NomCommune' => '^([^\\\\]+)\\\\n' ,
'Superficie' => '\\\\nsuperficie;([^\\\\]+)\\\\n',
'AltitudeMin' => '\\\\naltitude;([^;]+);',
'AltitudeMax' => '\\\\naltitude;[^;]+;([^\\\\]+)\\\\n',
'LambertIIEtenduX' => '\\\\ncoordonnées;Lambert II étendu\\\\n;x;([^\\\\]+)\\\\n',
'LambertIIEtenduY' => '\\\\ncoordonnées;Lambert II étendu\\\\n;x;[^\\\\]+\\\\n;y;([^\\\\]+)\\\\n',
'Latitude' => '\\\\n;Latitude;(.+)?\\\\ncode',
'Longitude' => '\\\\n;Longitude;(.+?)\\\\n;Latitude',
'CodeInsee' => '\\\\ncode insee;([^\\\\]+)\\\\nstatut',
'Statut' => '\\\\nstatut\(s\);([^\\\\]+)\\\\n\\\\n');
$this->analyserUrls();
}
 
/**
* Robot analysant les pages du site de Cassini.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pgf ~/importation/robots/eFloreBotCassini.txt -s ~/importation/robots/cassini.tsv
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pg 1 -s ~/importation/robots/cassini.tsv
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pg 1
*
* @return unknown_type
*/
private function lancerRobotUtmConverter() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotUtmConverter';
$this->url_tpl = 'http://www.rcn.montana.edu/resources/tools/coordinates.aspx?nav=11&c=DD&md=83&mdt=NAD83/WGS84&lat=%s&lath=N&lon=%s&lonh=E';
$this->encodage = 'ISO-8859-1';
$this->regexp_ligne = '/Universal Transverse Mercator \(UTM\):<\/td>(.*?)<\/table><\/td>/umsi';
$this->regexps = array( 'UTM_Zone' => 'Zone: ([0-9]+)<' ,
'UTM_Est_x' => 'Easting: ([0-9]+)<',
'UTM_Nord_y' => 'Northing: ([0-9]+)<');
$this->analyserUrls();
}
 
private function analyserUrls() {
// Lancement de l'analyse
$heure_debut = date('c',time());
 
echo "Analyse de l'URL # : ";
$pagesNum = 0;// Pages
$lignesNum = 0;// Lignes
$sortie = '';
foreach ($this->pages as $paramsPage) {
$xhtml_page = $this->getHtml($this->url_tpl, $paramsPage);
$xhtml_lignes = $this->extraireChaine($this->regexp_ligne, $xhtml_page);
 
// Pour chaque chaine début/fin trouvées au sein de la page, nous recherchons les regexps des données.
if (count($xhtml_lignes) > 1 && $this->mode != 'MULTI') {
$this->traiterAttention("Plusieurs lignes correspondent à votre expression régulière de limitation du contenu :\n %s", array($this->regexp_ligne));
} else if ($xhtml_lignes) {
print_r($xhtml_lignes );
foreach ($xhtml_lignes as $xhtml) {
$champsNum = 1;// Champs
$ligne = '';
foreach ($this->regexps as $chp => $regexp) {
// Si nous traitons la première ligne nous ajoutons les noms des champs en début de fichier de sortie
if ($lignesNum == 0) {
$sortie .= $chp.(($champsNum == count($this->regexps)) ? "\n" : "\t");
$champsNum++;
}
// Ajout de la valeur trouvée grâce à l'expression régulière à la ligne de sortie
if (preg_match('/'.$regexp.'/Umsi', $xhtml, $match)) {
$ligne .= $this->nettoyer($match[1])."\t";
} else {
$ligne .= "\t";
}
}
$lignesNum++;
$ligne = trim($ligne);
$sortie .= $ligne."\n";
 
// Affichage en console...
if (empty($this->sortie)) {
echo "\t".$ligne."\n";
}
}
 
} else {
$this->traiterAttention("Impossible de trouver les chaines début et fin dans la page «%s» avec la regexp :\n%s", array($this->getNomPage($paramsPage), $this->regexp_ligne));
}
// Affichage en console...
echo str_repeat(chr(8), ( strlen( $pagesNum ) + 1 ))."\t".$pagesNum++;
}
echo "\n";
$heure_fin = date('c',time());
 
// Ajout de métadonnées
$metadonnees = "Début d'importation : $heure_debut\nFin d'importation : $heure_fin\n";
$metadonnees .= "Source des données : ".$this->url_tpl."\n";
$sortie = $metadonnees.$sortie;
 
// Écriture du fichier de sortie ou retour dans la console
if (!empty($this->sortie)) {
file_put_contents($this->sortie, $sortie);
}
}
 
private function nettoyer($txt) {
$txt = trim($txt);
$txt = preg_replace('/(?:&nbsp;|&#160;)/', ' ', $txt);
return $txt;
}
 
private function getHtml($url_tpl, $paramsPage) {
// Lancement en ligne de commande pour tester :
//curl -v --url "http://fr.wikipedia.org/wiki/Montpellier" --config /home/jpm/web/eflore_bp/consultation/scripts/modules/robot/configuration/cookieconf.txt
if ($this->cache && file_exists($fichier_cache = $this->cache.$this->getNomPage($paramsPage))) {
$html = file_get_contents($fichier_cache);
} else {
$url = vsprintf($url_tpl, $paramsPage);
$this->traiterAttention(" Url : ".$url);
// Initialisation CURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1');
 
$html = curl_exec($curl);
 
// Mise en cache
if ($this->cache) {
file_put_contents($fichier_cache, $html);
}
}
 
// Nettoyage des entités html
$html = $this->encoderUtf8($html, 'HTML-ENTITIES');
// Nettoyage de l'encodage des urls
$html = urldecode($html);
 
// Convertion en UTF-8 si nécessaire
if ($this->encodage) {
$html = $this->encoderUtf8($html, $this->encodage);
}
 
return $html;
}
 
/**
* Méthode récupérant seulement une partie du texte passé en paramétre.
*
* @param $debut chaine de caractère indiquant le début du texte à prendre en compte.
* @param $fin chaine de caractère indiquant la fin du texte à prendre en compte.
* @param $txt le texte duquel extraire une partie bornée par $debut et $fin.
* @return le texte extrait.
*/
private function extraireChaine($regexp, $txt) {
if (preg_match_all($regexp, $txt, $match)) {
return $match[1];
} else {
return false;
}
}
/**
* Charge les lignes d'un fichier dans un tableau et le retourne.
* Supprime les caractères blancs et les nouvelles lignes.
*
* @param $fichier
* @return unknown_type
*/
private function convertirFichierEnTableau($fichier) {
$tableau = array();
$handle = fopen($fichier,'r');
if ($handle) {
while ($ligne = fgets($handle)) {
$tableau[] = explode("\t", trim($ligne));
}
fclose($handle);
}
return $tableau;
}
 
private function getNomPage($paramsPage) {
return str_replace(' ', '_', implode('_', $paramsPage)).'.html';
}
 
}
?>
/tags/v5.3-amandaie/scripts/modules/robot/configuration/cassini.ini
New file
0,0 → 1,3
; Encodage : UTF-8
; Source des données : http://cassini.ehess.fr/
cache_chemin = "php:'/home/'.$_ENV['USER'].'/importation/robots/cassini.ehess.fr/'"
/tags/v5.3-amandaie/scripts/modules/robot/configuration/wp_commune.ini
New file
0,0 → 1,4
; Encodage : UTF-8
; Source des données : http://fr.wikipedia.org/wiki/
; Version des noms de commune utilisé pour intéroger Wikipedia: Code géographique de l'INSEE version 2008-01-01
cache_chemin = "php:'/home/'.$_ENV['USER'].'/importation/robots/fr.wikipedia.org/'"
/tags/v5.3-amandaie/scripts/modules/robot/configuration/utm_converter.ini
New file
0,0 → 1,3
; Encodage : UTF-8
; Source des données : http://www.rcn.montana.edu/resources/tools/coordinates.aspx
cache_chemin = "php:'/home/'.$_ENV['USER'].'/importation/robots/rcn.montana.edu/'"
/tags/v5.3-amandaie/scripts/modules/robot/configuration/cookieconf.txt
New file
0,0 → 1,4
-b ../../../../../../../importation/robots/cookie.txt
-c ../../../../../../../importation/robots/cookie.txt
 
--max-time 50
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.3-amandaie/scripts/modules/robot/configuration/ipni_auteur.ini
New file
0,0 → 1,3
; Encodage : UTF-8
; Source des données : http://ipni.org/
cache_chemin = "php:'/home/'.$_ENV['USER'].'/importation/robots/ipni.org/'"
/tags/v5.3-amandaie/scripts/modules/bdnt/Bdnt.php
New file
0,0 → 1,54
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php bdnt -a chargerTous
*/
class Bdnt extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('bdnt');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerOntologies();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
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 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 0 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS bdnt_meta, bdnt_ontologies_v4_30";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/bdnt/bdnt.ini
New file
0,0 → 1,14
version="4_40"
dossierTsv = "{ref:dossierDonneesEflore}bdnt/2013-07-01/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
ontologies = "bdnt_ontologies_v{ref:version}"
 
[fichiers]
structureSql = "bdnt_ontologies_v2013-07-01.sql"
ontologies = "bdnt_ontologies_v2013-07-01.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.3-amandaie/scripts/modules/bdnt
New file
Property changes:
Added: svn:ignore
+bdnt.ini
/tags/v5.3-amandaie/scripts/modules/fournier/fournier.ini
New file
0,0 → 1,15
version="1_00"
dossierTsv = "{ref:dossierDonneesEflore}fournier/1.00/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
fournierMeta = "fournier_meta"
fournier = "fournier_v{ref:version}"
 
[fichiers]
structureSql = "{ref:tables.fournier}.sql"
fournier = "{ref:tables.fournier}.csv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
fournier = "{ref:dossierTsv}{ref:fichiers.fournier}"
/tags/v5.3-amandaie/scripts/modules/fournier/Fournier.php
New file
0,0 → 1,138
<?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 Fournier extends EfloreScript {
 
private $table = null;
private $tableMeta = null;
private $pasInsertion = 1000;
private $departInsertion = 0;
 
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() {
try {
$this->initialiserProjet('fournier');
$this->initialiserTables();
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerFournier();
$this->genererNomSciHtml();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerFournier' :
$this->chargerFournier();
break;
case 'genererNomSciHtml' :
$this->genererNomSciHtml();
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 chargerFournier() {
$chemin = Config::get('chemins.fournier');
$table = Config::get('tables.fournier');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY ',' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function genererNomSciHtml() {
$this->preparerTable();
$generateur = new GenerateurNomSciHtml();
$nbreTotal = $this->recupererNbTotalTuples();
while ($this->departInsertion < $nbreTotal) {
$resultat = $this->recupererTuples();
$nomsSciEnHtml = $generateur->generer($resultat);
$this->lancerRequeteModification($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";
}
 
private function initialiserTables() {
$this->table = Config::get('tables.fournier');
$this->tableMeta = Config::get('tables.fournierMeta');
}
 
private function preparerTable() {
$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 recupererTuples() {
$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 lancerRequeteModification($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 supprimerTous() {
$requete = "DROP TABLE IF EXISTS {$this->tableMeta}, {$this->table}";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/prometheus/Prometheus.php
New file
0,0 → 1,639
<?php
/**
* Exemple de lancement du script : /opt/lampp/bin/php cli.php ontologie -a analyser
*
*/
require_once dirname(__FILE__).DS.'Traduction.php';
 
class Prometheus extends EfloreScript {
 
private $projetDossier = '';
private $lecteur = null;
private $fichier = '';
private $lotsTermes = array();
private $lotsRelations = array();
private $lotsImages = array();
private $lotsPublications = array();
private $lotsAuteurs = array();
private $lotsHierarchie = array();
private $baseIdGroupe = 10000;
private $baseIdSousGroupe = 20000;
private $types = array(
'FREQUENCY_MODIFIERS' => 2,
'QUALIFIERS' => 3,
'RELATIVE_MODIFIERS' => 4,
'RELATIVE_VALUES' => 5,
'SPATIAL_MODIFIERS' => 6,
'LOCATER_REGIONS' => 7,
'TEMPORAL_MODIFIERS' => 8,
'UNIT_TERMS' => 9,
'QUANTITATIVE_PROPERTIES' => 10,
'NEW_QUALITATIVE_PROPERTIES' => 11,
'DISALLOWED_TERMS' => 20,
'QUALITATIVE_STATES' => 13,
'TYPE_OF_STRUCTURE_TERMS' => 14,
'STRUCTURE_TERMS' => 15,
'REGION_TERMS' => 16,
'GENERIC_STRUCTURES' => 17);
 
public function executer() {
try {
$this->initialiserProjet('prometheus');
$this->projetDossier = Config::get('dossierTsv');
 
$this->fichier = $this->projetDossier.'Ontology.xml';
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->lireFichierXml();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'analyser' :
$this->vider();
$this->lireFichierXml();
break;
case 'chargerTraductions' :
$this->viderTraductions();
$this->chargerTraductions();
break;
case 'vider' :
$this->vider();
case 'viderTraductions' :
$this->viderTraductions();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
 
/**
* Lit le fichier OSM et lance l'analyse des noeuds xml en fonction de leur type.
*/
private function lireFichierXml() {
$termes = array_keys($this->types);
$this->lecteur = new XMLReader();
if ($this->ouvrirFichierXml()) {
while ($this->lecteur->read()) {
if ($this->lecteur->nodeType == XMLREADER::ELEMENT) {
if (in_array($this->lecteur->localName, $termes)) {
$noeud = $this->obtenirNoeudSimpleXml();
$type = $this->lecteur->localName;
$this->traiterTermes($this->types[$type], $noeud->children());
} else if ($this->lecteur->localName == 'STATE_GROUPS') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterGroupes($noeud->children());
} else if ($this->lecteur->localName == 'NewQualitativeProperties') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterNouvellesQualites($noeud->children());
} else if ($this->lecteur->localName == 'RELATIONSHIPS') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterRelations($noeud->children());
} else if ($this->lecteur->localName == 'PICTURES') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterImages($noeud->children());
} else if ($this->lecteur->localName == 'CITATIONS') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterCitations($noeud->children());
} else if ($this->lecteur->localName == 'AUTHORS') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterAuteurs($noeud->children());
} else if ($this->lecteur->localName == 'TreeNode') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterHierarchie($noeud);
}
}
}
if (count($this->lotsTermes) > 0) {
$this->insererLotDeTermes();
}
if (count($this->lotsRelations) > 0) {
$this->insererLotDeRelations();
}
if (count($this->lotsImages) > 0) {
$this->insererLotImages();
}
if (count($this->lotsPublications) > 0) {
$this->insererLotDePublications();
}
if (count($this->lotsAuteurs) > 0) {
$this->insererLotAuteurs();
}
if (count($this->lotsHierarchie) > 0) {
$this->insererLotHierarchie();
}
}
}
 
private function ouvrirFichierXml() {
if ($this->lecteur->open($this->fichier) === false) {
throw new Exception("Impossible d'ouvrir le fichier XML : $this->fichier");
}
return true;
}
 
private function obtenirNoeudSimpleXml() {
$doc = new DOMDocument;
$element = $this->lecteur->expand();
$noeud = simplexml_import_dom($doc->importNode($element, true));
return $noeud;
}
 
private function traiterTermes($type, $termes) {
foreach ($termes as $terme) {
$id = (int) $terme->attributes()->GLOBALID;
if (isset($this->lotsTermes[$id]) === false) {
$valeur = array();
$valeur[] = (int) $id;
$valeur[] = (int) $type;
$valeur[] = (string) $terme->attributes()->term;
$valeur[] = (string) $this->obtenirDefinition($terme);
$valeur[] = (int) $this->obtenirPreference($terme);
$valeur[] = (int) $this->obtenirAuteur($terme);
$valeur[] = (int) $this->obtenirCitation($terme);
$valeur[] = (int) $this->obtenirImage($terme);
$this->lotsTermes[$id] = $valeur;
}
if (isset($terme->attributes()->parentID)) {
$relation = array();
$relation[] = (int) $terme->attributes()->GLOBALID;
$relation[] = (int) $terme->attributes()->parentID;
$relation[] = 'A POUR PARENT';
$this->ajouterRelation($relation);
}
if (isset($terme->attributes()->PARENT_STRUCTURE_ID)) {
$relation = array();
$relation[] = (int) $terme->attributes()->GLOBALID;
$relation[] = (int) $terme->attributes()->PARENT_STRUCTURE_ID;
$relation[] = 'A POUR STRUCTURE PARENTE';
$this->ajouterRelation($relation);
}
if (isset($terme->attributes()->stateOfNEWPROPERTYID)) {
$relation = array();
$relation[] = (int) $terme->attributes()->GLOBALID;
$relation[] = (int) $terme->attributes()->stateOfNEWPROPERTYID;
$relation[] = 'A POUR NOUVELLE QUALITE';
$this->ajouterRelation($relation);
}
}
}
 
private function obtenirDefinition($terme) {
$definition = null;
if (isset($terme->DEFINITION)) {
$definition = $terme->DEFINITION;
}
return $definition;
}
 
private function obtenirPreference($terme) {
$preference = '1';
if (isset($terme->attributes()->PREFERRED_TERM)) {
$valeur = (string) $terme->attributes()->PREFERRED_TERM;
$preference = (trim($valeur) == 'Disallowed Term') ? '0' : '1';
}
return $preference;
}
 
private function obtenirAuteur($terme) {
$auteur = 0;
if (isset($terme->attributes()->authorID)) {
$auteur = $terme->attributes()->authorID;
} elseif (isset($terme->attributes()->authorREF)) {
$auteur = $terme->attributes()->authorREF;
}
return $auteur;
}
 
private function obtenirCitation($terme) {
$citation = 0;
if (isset($terme->attributes()->citationID)) {
$citation = $terme->attributes()->citationID;
} elseif (isset($terme->attributes()->citationREF)) {
$citation = $terme->attributes()->citationREF;
}
return $citation;
}
 
private function obtenirImage($terme) {
$image = 0;
if (isset($terme->attributes()->pictureREF)) {
$image = $terme->attributes()->pictureREF;
}
return $image;
}
 
private function traiterGroupes($groupes) {
foreach ($groupes as $groupe) {
$id = $this->baseIdGroupe + (int) $groupe->attributes()->GROUP_ID;
if (isset($this->lotsTermes[$id]) === false) {
$valeur = array();
$valeur[] = (int) $id;
$valeur[] = 18;
$valeur[] = (string) $groupe->attributes()->groupName;
$valeur[] = '';
$valeur[] = 1;
$valeur[] = 0;
$valeur[] = 0;
$valeur[] = 0;
$this->lotsTermes[$id] = $valeur;
}
if (isset($groupe->STRUCTURES_LINKED_TO_GROUP)) {
foreach ($groupe->STRUCTURES_LINKED_TO_GROUP->children() as $structure) {
$relation = array();
$relation[] = (int) $structure->attributes()->GLOBALID;
$relation[] = (int) $id;
$relation[] = 'A POUR GROUPE';
$this->ajouterRelation($relation);
}
}
if (isset($groupe->STATES_IN_GROUP)) {
foreach ($groupe->STATES_IN_GROUP->children() as $etat) {
$relation = array();
$relation[] = (int) $id;
$relation[] = (int) $etat->attributes()->GLOBALID;
$relation[] = 'A POUR ETAT';
$this->ajouterRelation($relation);
}
}
if (isset($groupe->STATESUBGROUPS)) {
$this->traiterSousGroupes($id, $groupe->STATESUBGROUPS->children());
}
}
}
 
private function traiterSousGroupes($idGroupe, $sousGroupes) {
foreach ($sousGroupes as $sg) {
$id = $this->baseIdSousGroupe + (int) $sg->attributes()->STATESUBGROUP_GLOBALID;
if (isset($this->lotsTermes[$id]) === false) {
$valeur = array();
$valeur[] = (int) $id;
$valeur[] = 19;
$valeur[] = (string) $sg->attributes()->subgGroupName;
$valeur[] = '';
$valeur[] = 1;
$valeur[] = 0;
$valeur[] = 0;
$valeur[] = 0;
$this->lotsTermes[$id] = $valeur;
 
$relation = array();
$relation[] = (int) $idGroupe;
$relation[] = (int) $id;
$relation[] = 'A POUR SOUS-GROUPE';
$this->ajouterRelation($relation);
}
if (isset($sg->STATES_IN_SUBGROUP)) {
foreach ($sg->STATES_IN_SUBGROUP->children() as $etat) {
$relation = array();
$relation[] = (int) $id;
$relation[] = (int) $etat->attributes()->GLOBALID;
$relation[] = 'A POUR ETAT';
$this->ajouterRelation($relation);
}
}
}
}
 
private function traiterNouvellesQualites($qualites) {
foreach ($qualites as $qualite) {
$id = (int) $qualite->attributes()->IDSEQ;
if (isset($this->lotsTermes[$id]) === false) {
$valeur = array();
$valeur[] = (int) $id;
$valeur[] = 11;
$valeur[] = (string) $qualite->attributes()->term;
$valeur[] = (string) $this->obtenirDefinition($terme);
$valeur[] = (int) $this->obtenirPreference($terme);
$valeur[] = (int) $this->obtenirAuteur($terme);
$valeur[] = (int) $this->obtenirCitation($terme);
$valeur[] = (int) $this->obtenirImage($terme);
$this->lotsTermes[$id] = $valeur;
}
if (isset($qualite->attributes()->ParentPropertyID)) {
$relation = array();
$relation[] = (int) $qualite->attributes()->IDSEQ;
$relation[] = (int) $qualite->attributes()->ParentPropertyID;
$relation[] = 'A POUR PARENT';
$this->ajouterRelation($relation);
}
if (isset($qualite->MemberStates)) {
$etats = $qualite->MemberStates->children();
$idParent = $qualite->attributes()->IDSEQ;
$this->traiterEtatsMembre($etats, $idParent);
}
if (isset($qualite->Structures_linked_to_Property)) {
$structures = $qualite->Structures_linked_to_Property->children();
$idParent = $qualite->attributes()->IDSEQ;
$this->traiterStructuresLiees($structures, $idParent);
}
if (isset($qualite->ContextGroups)) {
$contextes = $qualite->ContextGroups->children();
if (count($contextes) > 0) {
foreach ($contextes as $contexte) {
$idParent = $contexte->attributes()->ID;
$structures = $contexte->Structures_linked_to_Context->children();
$this->traiterStructuresLiees($structures, $idParent);
$etats = $contexte->MemberStates->children();
$this->traiterEtatsMembre($etats, $idParent);
}
}
}
}
}
 
private function ajouterRelation($relation) {
$id = implode('-', $relation);
if (isset($this->lotsRelations[$id]) === false) {
$this->lotsRelations[$id] = $relation;
}
}
 
private function traiterEtatsMembre($etats, $idParent) {
if (count($etats) > 0) {
foreach ($etats as $etat) {
$relation = array();
$relation[] = (int) $idParent;
$relation[] = (int) $etat->attributes()->RefID;
$relation[] = 'A POUR ETAT';
$this->ajouterRelation($relation);
}
}
}
 
private function traiterStructuresLiees($structures, $idParent) {
if (count($structures) > 0) {
foreach ($structures as $structure) {
$relation = array();
$relation[] = (int) $structure->attributes()->RefID;
$relation[] = (int) $idParent;
$relation[] = 'A POUR PROPRIETE';
$this->ajouterRelation($relation);
}
}
}
 
private function traiterRelations($relations) {
foreach ($relations as $rel) {
$relation = array();
$relation[] = (int) $rel->attributes()->term1REF;
$relation[] = (int) $rel->attributes()->term2REF;
$relation[] = (string) $this->obtenirTypeRelation($rel->attributes()->relationship);
$this->ajouterRelation($relation);
}
}
 
private function obtenirTypeRelation($type) {
switch ($type) {
case 'ASSOCIATED WITH' :
$relation = 'ASSOCIE AVEC';
break;
case 'IS A PART OF' :
$relation = 'EST UNE PARTIE DE';
break;
case 'IS A TYPE OF' :
$relation = 'EST UN TYPE DE';
break;
default :
$relation = '';
}
return $relation;
}
 
private function traiterImages($images) {
foreach ($images as $img) {
$valeur = array();
$valeur[] = (int) $img->attributes()->ID;
$valeur[] = (string) $img->attributes()->NAME;
$valeur[] = (int) $img->attributes()->CITATION_REFID;
$this->lotsImages[] = $valeur;
}
}
 
private function traiterCitations($citations) {
foreach ($citations as $publi) {
$valeur = array();
$valeur[] = (int) $publi->attributes()->ID;
$valeur[] = (int) $publi->attributes()->primaryAuthorREF;
$valeur[] = (string) $publi->PUBLICATION;
$valeur[] = (string) $publi->DATE;
$valeur[] = (string) $publi->PAGE;
$this->lotsPublications[] = $valeur;
}
}
 
private function traiterAuteurs($auteurs) {
foreach ($auteurs as $auteur) {
$valeur = array();
$valeur[] = (int) $auteur->attributes()->ID;
$valeur[] = (string) $auteur->attributes()->givenNames;
$valeur[] = (string) $auteur->attributes()->surname;
$valeur[] = $this->obtenirDateNaissance((string) $auteur->attributes()->born);
$valeur[] = (string) $auteur->attributes()->died;
$this->lotsAuteurs[] = $valeur;
}
}
 
private function obtenirDateNaissance($annee) {
$date = $annee.'-00-00';
return $date;
}
 
private function traiterHierarchie($noeud) {
$valeur = array();
$valeur[] = (int) $noeud->attributes()->ID;
$valeur[] = (int) $noeud->attributes()->ParentNodeID;
$valeur[] = (string) $noeud->attributes()->pathAsNames;
$valeur[] = (string) $noeud->attributes()->pathAsID;
$valeur[] = (int) $noeud->attributes()->TermID;
$this->lotsHierarchie[] = $valeur;
}
 
private function insererLotDeTermes() {
$champs = implode(',', array('id_terme', 'ce_type', 'nom_en', 'description_en', 'preference', 'ce_auteur', 'ce_publication', 'ce_image'));
$values = $this->creerValues($this->lotsTermes);
$requete = "INSERT INTO prometheus_ontologies_terme_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotDeRelations() {
$champs = implode(',', array('id_terme_01', 'id_terme_02', 'relation'));
$values = $this->creerValues($this->lotsRelations);
$requete = "INSERT INTO prometheus_ontologies_relation_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotImages() {
$champs = implode(',', array('id_image', 'uri', 'ce_publication'));
$values = $this->creerValues($this->lotsImages);
$requete = "INSERT INTO prometheus_ontologies_image_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotDePublications() {
$champs = implode(',', array('id_publication', 'ce_auteur_principal', 'titre', 'date', 'uri'));
$values = $this->creerValues($this->lotsPublications);
$requete = "INSERT INTO prometheus_ontologies_publication_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotAuteurs() {
$champs = implode(',', array('id_auteur', 'prenom', 'nom', 'naissance_date', 'deces_date'));
$values = $this->creerValues($this->lotsAuteurs);
$requete = "INSERT INTO prometheus_ontologies_auteur_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotHierarchie() {
$champs = implode(',', array('id_noeud', 'id_noeud_parent', 'chemin_noms', 'chemin_ids', 'ce_terme'));
$values = $this->creerValues($this->lotsHierarchie);
$requete = "INSERT INTO prometheus_ontologies_hierarchie_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function creerValues($valeurs) {
$values = array();
foreach ($valeurs as $valeur) {
foreach ($valeur as $id => $val) {
$valeur[$id] = $this->etreVide($val) ? 'NULL' : $this->proteger(trim($val));
}
$values[] = '('.implode(',', $valeur).')';
}
$values = implode(',', $values);
return $values;
}
 
private function etreVide($val) {
$vide = ($val === null || trim($val) === '') ? true : false;
return $vide;
}
 
private function executerSql($requete) {
$this->getBdd()->requeter($requete);
}
 
private function proteger($chaine) {
return $this->getBdd()->proteger($chaine);
}
 
private function viderTraductions() {
$requete = 'UPDATE prometheus_ontologies_terme_v1_00 '.
'SET nom = NULL, description = NULL, notes = NULL';
$this->executerSql($requete);
}
 
private function chargerTraductions() {
$dossier = $this->projetDossier.'traductions'.DS;
$pointeur = opendir($dossier);
while ($fichierNom = readdir($pointeur)) {
if (preg_match('/^[.]{1,2}/', $fichierNom) == false) {
$fichierChemin = $dossier.$fichierNom;
$lecteur = new LecteurExcel($fichierChemin);
//$this->verifierStructureFichierExcel($lecteur);
for ($ligne = 2; $ligne < $lecteur->getNbreLignes(); $ligne++) {
$traduction = new Traduction();
$traduction->type = $lecteur->getValeur($ligne, 1);
$traduction->en = $lecteur->getValeur($ligne, 2);
$traduction->fr = $lecteur->getValeur($ligne, 3);
$traduction->sourcesTraduction = $lecteur->getValeur($ligne, 4);
$traduction->remarques = $lecteur->getValeur($ligne, 5);
$traduction->sources = $lecteur->getValeur($ligne, 6);
$traduction->relectureRemarques = $lecteur->getValeur($ligne, 7);
$this->genererNotes($traduction);
 
$this->insererTraduction($traduction);
}
}
}
closedir($pointeur);
}
 
private function verifierStructureFichierExcel($lecteur) {
$messages = array();
$colonnes = array("Type d'élément", "Élément en anglais", "Traduction en français", "Sources de la traduction", "Remarques", "Sources", "Relecture/ Remarques");
foreach ($colonnes as $numero => $intitule) {
$valeurBrute = $lecteur->getValeur(1, ($numero + 1));
if ($valeurBrute != $intitule) {
$messages[] = "Le fichier {$lecteur->getFichier()} ne contient pas la bonne colonne #$numero : $intitule != $valeurBrute";
}
}
if (count($messages) > 0) {
throw new Exception(implode("\n", $messages));
}
}
 
private function genererNotes(Traduction $traduction) {
$notes = array();
if ($this->etreVide($traduction->sourcesTraduction) === false) {
$notes[] = "Sources de la traduction : ".$traduction->sourcesTraduction;
}
if ($this->etreVide($traduction->remarques) === false) {
$notes[] = "Remarques : ".$traduction->remarques;
}
if ($this->etreVide($traduction->sources) === false) {
$notes[] = "Sources : ".$traduction->sources;
}
if ($this->etreVide($traduction->relectureRemarques) === false) {
$notes[] = "Remarques sur la relecture : ".$traduction->relectureRemarques;
}
if (count($notes) > 0) {
$traduction->notes = implode("\n", $notes);
}
}
 
private function insererTraduction($traduction) {
$requete = null;
$notes = $traduction->notes;
if ($traduction->type == 'term') {
$notes = $this->proteger("Nom :\n".$notes);
$nom = $this->proteger($traduction->fr);
$nomEn = $this->proteger($traduction->en);
$requete = "UPDATE prometheus_ontologies_terme_v1_00 ".
"SET nom = $nom, notes = $notes ".
"WHERE nom_en = $nomEn ";
} else if ($traduction->type == 'DEFINITION') {
$notes = $this->proteger("Description :\n".$notes);
$description = $this->proteger($traduction->fr);
$descriptionEn = $this->proteger($traduction->en);
$requete = "UPDATE prometheus_ontologies_terme_v1_00 ".
"SET description = $description, notes = CONCAT(notes, '\n', $notes) ".
"WHERE description_en = $descriptionEn ";
}
if ($requete != null) {
$this->executerSql($requete);
}
}
 
private function vider() {
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_auteur_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_hierarchie_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_image_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_publication_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_relation_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_terme_v1_00';
$this->executerSql($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS prometheus_meta, prometheus_ontologies_auteur_v1_00, prometheus_ontologies_hierarchie_v1_00,
prometheus_ontologies_image_v1_00, prometheus_ontologies_publication_v1_00, prometheus_ontologies_relation_v1_00,
prometheus_ontologies_terme_v1_00, prometheus_ontologies_type_v1_00";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/prometheus/Traduction.php
New file
0,0 → 1,11
<?php
class Traduction {
public $type = null;
public $en = null;
public $fr = null;
public $sourcesTraduction = null;
public $remarques = null;
public $sources = null;
public $relectureRemarques = null;
public $notes = null;
}
/tags/v5.3-amandaie/scripts/modules/prometheus/prometheus.ini
New file
0,0 → 1,12
version="1_00"
dossierTsv = "{ref:dossierDonneesEflore}prometheus/v1.00_2003-02-18/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
ontologies = "prometheus_ontologies_v{ref:version}"
 
[fichiers]
structureSql = "prometheus_v1_00.sql"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
/tags/v5.3-amandaie/scripts/modules/bonnier/Bonnier.php
New file
0,0 → 1,508
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/* Importation des fichiers excel de Bonnier pour créer une version HTML pour PDA.
* Utilisation au préalable des utillitaire de traitement de fichier mdb sous Unix (voir ci après)
*
* Pré-requis :
* 1. Installer le paquet pour Perl nommé ParseExcel : urpmi perl-spreadsheet-parseexcel
* 2. Télécharger les fichiers Excel de Bonnier : http://www.tela-botanica.org/projets/74/documents/16211
* 3. Créer un dossier où vous dézipperez l'archive des fichiers Excel
* 4. Copier dans ce dossier les fichier xls2sql.pl et generer_sql.sh que vous trouverez dans le dossier shell de ce module
* 5. Donner les droits d'execution au fichier generer_sql.sh et lancer le : ./generer_sql.sh
* 6. Vous devez obtenir un fichier SQL par fichier Excel.
*
* Pour lancer ce script fichier par fichier :
* 1. Ouvrir une console et se positionner dans le dossier "scripts"
* 2. Pour charger le 1er fichier Excel, taper la commande : /opt/lampp/bin/php script.php bonnier -p bonnier -a charger -table renonculacees
* 3. Pour generer le html issu du chargement precedent :
* /opt/lampp/bin/php script.php bonnier -p bonnier -a html -dossier "menus/001-Renonculacees" -table renonculacees
*
* // Auteur original :
* @author David DELON <david@clapas.net>
* @copyright David DELON 2009
* @link http://www.tela-botanica.org/wikini/eflore
* @licence GPL v3 & CeCILL v2
* @version $Id$
*/
// +-------------------------------------------------------------------------------------------------------------------+
class Bonnier extends ScriptCommandeEflore {
 
/**
* Paramêtres disponible pour la ligne de commande
* le tableau se construit de la forme suivnate :
* - clé = nom du paramêtre '-foo'
* - value = contient un nouveau tableau composé de cette façaon :
* - booléen: true si le paramêtre est obligatoire
* - booléen ou var : true si le paramêtre nécessite un valeur à sa suite ou la valeur par défaut
* - string: description du contenu du paramêtre
* Les paramêtres optionels devraient être déclaré à la fin du tableau.
* Le dernier parametre du tableau peut avoir la valeur '...',
* il contiendra alors l'ensemble des paramêtres suivant trouvés sur la ligne de commande.
* @var array
*/
public $parametres = array( '-table' => array(true, true, "Nom de la table où seront stockées les données d'une famille"),
'-dossier' => array(true, true, "Dossier où sont générés les fichiers html pour la table"));
public function executer() {
 
error_reporting(E_ALL & ~E_DEPRECATED );
$table = $this->getParam('table');
$dossier = $this->getParam('dossier');
@mkdir($this->getIni('chemin_fichier_sortie').$dossier);
$cmd = $this->getParam('a');
switch ($cmd) {
// chargement des fichiers sql issus de la transformation xls dans la base de donnee, une table par fichir sql, 2 tables par
// familles : texte (navigation / clef) et plantes : description des plantes.
case 'charger' :
$this->creerTableBonnier($this->version, $table);
$this->chargerDonnees($table);
break;
case 'html' :
// tranformation sql vers html : pour la famille considerée : parcours de l'ensemble de ses clef et generation html pour
// les feuilles.
$this->realiserHtml($dossier, $table);
break;
default :
trigger_error('Erreur : la commande "'.$cmd.'" n\'existe pas!'."\n", E_USER_ERROR);
}
}
 
private function realiserHtml($dossier, $table) {
// Parcours de l'ensemble des données ? ou famille par famille ?
// on charge plante et texte dans des tableaux
$this->type_donnee = $table.'_texte';
$requete = 'SELECT * '.
'FROM '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.' '.
'ORDER BY uid';
$lignesTexte = $this->retournerDonneesRequete($requete);
// Analyse des données
echo "Analyse des données : ".$this->type_donnee."\n";
foreach ($lignesTexte as $ligneTexte) {
if (!isset($aso_lignes[$ligneTexte['identifiant']])) {
$aso_lignes[$ligneTexte['identifiant']] = $ligneTexte;
} else {
echo "identifiant en double : ".$ligneTexte['identifiant']."\n";
}
}
 
$this->type_donnee = $table.'_plante';
$requete = 'SELECT * '.
'FROM '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.' '.
'ORDER BY uid';
$lignesPlante = $this->retournerDonneesRequete($requete);
foreach ($lignesPlante as $lignePlante) {
if (!isset($aso_lignes[$lignePlante['identifiant']])) {
$aso_lignes[$lignePlante['identifiant']] = $lignePlante;
} else {
echo "identifiant en double : ".$lignePlante['identifiant']."\n";
}
}
//print_r($aso_lignes_texte[$lignesTexte[0]['identifiant']] ['titre']);
// $ariane : tableau des identifiants parcourus dans la branche
// $niveau : niveau dans l'arbre
$ariane = array();
$niveau = 0;
// Parcours de l'arbre des clefs depuis la racine
$this->genererHtmlTexte($lignesTexte[1]['identifiant'], $aso_lignes, $ariane, $niveau, $dossier);
}
// Generation des elements de navigation (clef)
private function genererHtmlTexte($identifiant, $lignesTexteIdentifiant, $ariane, $niveau, $dossier) {
 
$ariane[] = $identifiant;
$niveau++;
if (isset ($lignesTexteIdentifiant[$identifiant])) { // Si des identifiants sont en doubles
$ligneIdentifiant = $lignesTexteIdentifiant[$identifiant];
}
else {
// initialiser valeur par defaut indiquant une erreur
}
 
$f_html = fopen($this->getIni('chemin_fichier_sortie').$dossier.'/'.$identifiant.'.html', 'wb');
$html =
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n".
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n".
'<head>'."\n".
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n".
'<title>Flore BONNIER sur PDA</title>'."\n".
'<link rel="stylesheet" type="text/css" href="../../style/style640.css" media="screen" />'."\n".
'</head>'."\n";
$html .= '<body>'."\n";
$html .= '<div class="titre">'."\n";
$html .= '<p id="titre">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['titre'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
// print "identifiant : ".$ligneIdentifiant['identifiant']."\n";
// Destinations
// Branche niveau inferieur
$html.='<div class="fenetreMenu">'."\n";
for ($i = 1; $i < 6; $i++) {
if (isset($ligneIdentifiant['texte_'.$i]) && $ligneIdentifiant['texte_'.$i] != "") {
$html .= '<div class="menu'.($i-1).'">'."\n";
$html .= '<a href="'.$ligneIdentifiant['destination_'.$i].'.html">';
$html .= $ligneIdentifiant['texte_'.$i];
$html .= '</a>'."\n";
$html .= '</div>'."\n";
}
}
 
$html .= '</div>'."\n";
$html .= '<div class="espace" style="top:518px;">'."\n";
$html .= '</div>'."\n";
$html .= '<div class="navigation">'."\n";
$html .= '<p id="navigation">'."\n";
// Navigation
for ($i = 0; $i < $niveau; $i++) {
if (($ariane[$i]) && $ariane[$i] != '') {
$html .= '<a href="'.$ariane[$i].'.html">';
if (isset ($lignesTexteIdentifiant[$ariane[$i]])) { // Si des identifiants sont en doubles
$html .= $lignesTexteIdentifiant[$ariane[$i]]['titre'];
}
$html .= '</a>'."\n";
}
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
 
$html .= '<div class="retour">'."\n";
$html .= '<p id="retour">'."\n";
// Retour niveau superieur
if (isset($ariane[$niveau - 2]) && $ariane[$niveau - 2] != '') {
$html .= '<a href="'.$ariane[$niveau - 2].'.html">';
$html .= $lignesTexteIdentifiant[$ariane[$niveau - 2]]['titre'];
$html .= '</a>'."\n";
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="glossaire">'."\n";
$html .= '<p id="glossaire">'."\n";
$html .= '<a href="../000-general/glossaire0_640.html">'."\n";
$html .= 'Glossaire'."\n";
$html .= '</a>'."\n";
$html .= '</p></div><div class="text">'."\n";
$html .= '<p id="Text">'."\n";
$html .= '<a href="../000-general/accueil1_640.html">'."\n";
$html .= ' Top'."\n";
$html .= '</a>'."\n";
$html .= ' </p>'."\n";
$html .= '</div>'."\n";
 
$html .= '</body>'."\n";
$html .= '</html>'."\n";
fwrite($f_html, $html);
fclose($f_html);
// Ecriture des feuilles (description plantes)
for ($i = 1; $i < 6; $i++) {
if (isset($ligneIdentifiant['destination_'.$i]) && $ligneIdentifiant['destination_'.$i] != '') {
if (substr($ligneIdentifiant['destination_'.$i], 0, 1) == 'p') {
$this->genererHtmlPlante($ligneIdentifiant['destination_'.$i], $lignesTexteIdentifiant, $ariane, $niveau, $dossier);
} else {
$this->genererHtmlTexte($ligneIdentifiant['destination_'.$i], $lignesTexteIdentifiant, $ariane, $niveau, $dossier);
}
}
}
}
// Plante
private function genererHtmlPlante($identifiant, $lignesTexteIdentifiant, $ariane, $niveau, $dossier) {
$ariane[] = $identifiant;
$niveau++;
if (isset ($lignesTexteIdentifiant[$identifiant])) { // Au cas ou des identifiants sont en doubles
$ligneIdentifiant = $lignesTexteIdentifiant[$identifiant];
}
$nom_latin = '';
if (isset($ariane[($niveau - 2)]) && isset($lignesTexteIdentifiant[$ariane[($niveau - 2)]]['texte_1'])) {
$nom_latin = trim(strrchr($lignesTexteIdentifiant[$ariane[($niveau - 2)]]['texte_1'], ':'), ' :');
}
 
$f_html = fopen($this->getIni('chemin_fichier_sortie').$dossier.'/'.$identifiant.'.html', 'wb');
$html=
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n".
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n".
'<head>'."\n".
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n".
'<title>Flore BONNIER sur PDA</title>'."\n".
'<link rel="stylesheet" type="text/css" href="../../style/style_plante.css" media="screen" />'."\n".
'</head>'."\n";
$html .= '<body>'."\n";
$html .= '<div class="titre">'."\n";
$html .= '<p id="titre">';
$html .= $nom_latin;
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="famille">'."\n";
$html .= '<p id="famille1">Famille : </p>'."\n";
$html .= '<p id="famille2">';
$html .= $lignesTexteIdentifiant[$ariane[0]]['titre'];
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="genre">'."\n";
$html .= '<p id="genre1">Genre : </p>'."\n";
$html .= '<p id="genre2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['genre'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="nom_latin">'."\n";
$html .= '<p id="nom_latin1">Nom Latin : </p>'."\n";
$html .= '<p id="nom_latin2">';
$html .= $nom_latin;
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="nom_francais">'."\n";
$html .= '<p id="nom_francais1">Nom Francais : </p>'."\n";
$html .= '<p id="nom_francais2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['nom_francais'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="nom_commun">'."\n";
$html .= '<p id="nom_commun1">Nom Vulgaire : </p>'."\n";
$html .= '<p id="nom_commun2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['nom_vulgaire'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="caracteres">'."\n";
$html .= '<p id="caracteres1">Caractéristiques spécifiques : </p>'."\n";
$html .= '<p id="caracteres2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['description'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="habitat">'."\n";
$html .= '<p id="habitat1">Habitat / taille / floraison : </p>'."\n";
$html .= '<p id="habitat2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['habitat'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="aire">'."\n";
$html .= '<p id="aire1">Aire g&eacute;ographique : </p>'."\n";
$html .= '<p id="aire2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['geographie'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="identifiant">'."\n";
$html .= '<p id="identifiant">';
$html .= 'Bonnier : '.$identifiant;
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="planche">'."\n";
$html .= '<p id="planche">';
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="retour">'."\n";
$html .= '<p id="retour">'."\n";
if (($ariane[$niveau - 2]) && $ariane[$niveau - 2] != '') {
$html .= '<a href="'.$ariane[$niveau - 2].'.html">';
$html .= $lignesTexteIdentifiant[$ariane[$niveau - 2]]['titre'];
$html .= '</a>'."\n";
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="glossaire">'."\n";
$html .= '<p id="glossaire">'."\n";
$html .= '<a href="../000-general/glossaire0_640.html">'."\n";
$html .= 'Glossaire'."\n";
$html .= '</a>'."\n";
$html .= '</p></div><div class="text">'."\n";
$html .= '<p id="Text">'."\n";
$html .= '<a href="../000-general/accueil1_640.html">'."\n";
$html .= ' Top'."\n";
$html .= '</a>'."\n";
$html .= ' </p>'."\n";
$html .= '</div>'."\n";
 
$html .= '</body>'."\n";
$html .= '</html>'."\n";
fwrite($f_html, $html);
fclose($f_html);
}
 
 
private function creerTableBonnier($version, $table) {
//+------------------------------------------------------------------------------------------------------------+
// texte
$this->type_donnee = $table.'_texte';
$requete = 'DROP TABLE IF EXISTS '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee;
$this->traiterRequete($requete);
$requete = 'CREATE TABLE '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.' ('.
'uid int(11) not null auto_increment,'.
'identifiant varchar(25),'.
'titre varchar(100),'.
'texte_1 varchar(255),'.
'texte_2 varchar(255),'.
'texte_3 varchar(255),'.
'texte_4 varchar(255),'.
'texte_5 varchar(255),'.
'texte_6 varchar(255),'.
'destination_1 varchar(25),'.
'destination_2 varchar(25),'.
'destination_3 varchar(25),'.
'destination_4 varchar(25),'.
'destination_5 varchar(25),'.
'destination_6 varchar(25),'.
'planche_croquis varchar(25),'.
'PRIMARY KEY (uid)'.
') DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ' ;
$this->traiterRequete($requete);
//+------------------------------------------------------------------------------------------------------------+
//plante
$this->type_donnee = $table.'_plante';
$requete = 'DROP TABLE IF EXISTS '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee;
$this->traiterRequete($requete);
$requete = 'CREATE TABLE '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.' ('.
'uid int(11) not null auto_increment,'.
'identifiant varchar(25),'.
'genre varchar(100),'.
'nom_francais varchar(100),'.
'nom_vulgaire varchar(100),'.
'description varchar(512),'.
'habitat varchar(255),'.
'geographie varchar(255),'.
'planche_croquis varchar(25),'.
'PRIMARY KEY (uid)'.
') DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ' ;
$this->traiterRequete($requete);
}
 
protected function chargerDonnees($table) {
print "Chargements des données ...";
print "\n";
$this->type_donnee = $table.'_texte';
$this->chargerDonneesSql($table);
$this->type_donnee = $table.'_plante';
$this->chargerDonneesSql($table);
return;
}
protected function chargerDonneesSql($table) {
echo $this->type_donnee."\n";
$fichier_sql = $this->chemin_fichier_tab.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.'.sql';
print $fichier_sql."\n";
if (file_exists($fichier_sql)) {
// Des champs textes sont multilignes, d'ou la boucle sur INSERT, marqueur de fin de la requete precedente.
if ($lines = file($fichier_sql)) {
$i = 0;
$ligne_courante = $lines[$i];
if (($i + 1) >= count($lines)) {
$ligne_suivante = 'FIN';
} else {
$ligne_suivante = $lines[$i+1];
}
while ($i < count($lines)) {
$line_in = $ligne_courante;
while (($i < count($lines)) && (substr($ligne_suivante, 0, 6) != 'INSERT') && ($ligne_suivante != 'FIN')) {
$line_in .= $ligne_suivante;
$i++;
$ligne_courante = $lines[$i];
if (($i + 1) >= count($lines)) {
$ligne_suivante = 'FIN';
} else {
$ligne_suivante = $lines[$i + 1];
}
}
$requete = $line_in;
if (substr($requete, 0, 6) == 'INSERT') {
$requete = preg_replace('/ VALUES\(/',' VALUES(0,', $requete);
$this->traiterRequete(utf8_encode($requete));
}
$i++;
if (($i + 1) >= count($lines)) {
$ligne_suivante = 'FIN';
} else {
$ligne_courante = $lines[$i];
$ligne_suivante = $lines[$i + 1];
}
if ($i == (int) $this->getParam('t')) {
break;
}
}
}
} else {
echo 'Fichier sql introuvable'."\n";
}
}
}
?>
/tags/v5.3-amandaie/scripts/modules/bonnier/shell/generer_sql.sh
New file
0,0 → 1,298
perl xls2sql.pl file="001-Renonculacées-Plante.xls" skip=0 table="bonnier_v0_00_renonculacees_plante" > bonnier_v0_00_renonculacees_plante.sql
perl xls2sql.pl file="001-Renonculacées-Texte.xls" skip=0 table="bonnier_v0_00_renonculacees_texte" > bonnier_v0_00_renonculacees_texte.sql
perl xls2sql.pl file="002-Berbéridées-Plante.xls" skip=0 table="bonnier_v0_00_berberidees_plante" > bonnier_v0_00_berberidees_plante.sql
perl xls2sql.pl file="002-Berbéridées-Texte.xls" skip=0 table="bonnier_v0_00_berberidees_texte" > bonnier_v0_00_berberidees_texte.sql
perl xls2sql.pl file="003-Nymphéacées-Plante.xls" skip=0 table="bonnier_v0_00_nympheacees_plante" > bonnier_v0_00_nympheacees_plante.sql
perl xls2sql.pl file="003-Nymphéacées-Texte.xls" skip=0 table="bonnier_v0_00_nympheacees_texte" > bonnier_v0_00_nympheacees_texte.sql
perl xls2sql.pl file="004-Papavéracées-Plante.xls" skip=0 table="bonnier_v0_00_papaveracees_plante" > bonnier_v0_00_papaveracees_plante.sql
perl xls2sql.pl file="004-Papavéracées-Texte.xls" skip=0 table="bonnier_v0_00_papaveracees_texte" > bonnier_v0_00_papaveracees_texte.sql
perl xls2sql.pl file="005-Fumariacées-Plante.xls" skip=0 table="bonnier_v0_00_fumariacees_plante" > bonnier_v0_00_fumariacees_plante.sql
perl xls2sql.pl file="005-Fumariacées-Texte.xls" skip=0 table="bonnier_v0_00_fumariacees_texte" > bonnier_v0_00_fumariacees_texte.sql
perl xls2sql.pl file="006-Crucifères-Plante.xls" skip=0 table="bonnier_v0_00_cruciferes_plante" > bonnier_v0_00_cruciferes_plante.sql
perl xls2sql.pl file="006-Crucifères-Texte.xls" skip=0 table="bonnier_v0_00_cruciferes_texte" > bonnier_v0_00_cruciferes_texte.sql
perl xls2sql.pl file="007-Capparidées-Plante.xls" skip=0 table="bonnier_v0_00_capparidees_plante" > bonnier_v0_00_capparidees_plante.sql
perl xls2sql.pl file="007-Capparidées-Texte.xls" skip=0 table="bonnier_v0_00_capparidees_texte" > bonnier_v0_00_capparidees_texte.sql
perl xls2sql.pl file="008-Cistinées-Plante.xls" skip=0 table="bonnier_v0_00_cistinees_plante" > bonnier_v0_00_cistinees_plante.sql
perl xls2sql.pl file="008-Cistinées-Texte.xls" skip=0 table="bonnier_v0_00_cistinees_texte" > bonnier_v0_00_cistinees_texte.sql
perl xls2sql.pl file="009-Violariées-Plante.xls" skip=0 table="bonnier_v0_00_violariees_plante" > bonnier_v0_00_violariees_plante.sql
perl xls2sql.pl file="009-Violariées-Texte.xls" skip=0 table="bonnier_v0_00_violariees_texte" > bonnier_v0_00_violariees_texte.sql
perl xls2sql.pl file="010-Résédacées-Plante.xls" skip=0 table="bonnier_v0_00_résedacees_plante" > bonnier_v0_00_résedacees_plante.sql
perl xls2sql.pl file="010-Résédacées-Texte.xls" skip=0 table="bonnier_v0_00_résedacees_texte" > bonnier_v0_00_résedacees_texte.sql
perl xls2sql.pl file="011-Droséracées-Plante.xls" skip=0 table="bonnier_v0_00_droseracees_plante" > bonnier_v0_00_droseracees_plante.sql
perl xls2sql.pl file="011-Droséracées-Texte.xls" skip=0 table="bonnier_v0_00_droseracees_texte" > bonnier_v0_00_droseracees_texte.sql
perl xls2sql.pl file="012-Polygalées-Plante.xls" skip=0 table="bonnier_v0_00_polygalees_plante" > bonnier_v0_00_polygalees_plante.sql
perl xls2sql.pl file="012-Polygalées-Texte.xls" skip=0 table="bonnier_v0_00_polygalees_texte" > bonnier_v0_00_polygalees_texte.sql
perl xls2sql.pl file="013-Frankéniacées-Plante.xls" skip=0 table="bonnier_v0_00_frankeniacees_plante" > bonnier_v0_00_frankeniacees_plante.sql
perl xls2sql.pl file="013-Frankéniacées-Texte.xls" skip=0 table="bonnier_v0_00_frankeniacees_texte" > bonnier_v0_00_frankeniacees_texte.sql
perl xls2sql.pl file="014-Caryophyllées-Plante.xls" skip=0 table="bonnier_v0_00_caryophyllees_plante" > bonnier_v0_00_caryophyllees_plante.sql
perl xls2sql.pl file="014-Caryophyllées-Texte.xls" skip=0 table="bonnier_v0_00_caryophyllees_texte" > bonnier_v0_00_caryophyllees_texte.sql
perl xls2sql.pl file="015-Elatinées-Plante.xls" skip=0 table="bonnier_v0_00_elatinees_plante" > bonnier_v0_00_elatinees_plante.sql
perl xls2sql.pl file="015-Elatinées-Texte.xls" skip=0 table="bonnier_v0_00_elatinees_texte" > bonnier_v0_00_elatinees_texte.sql
perl xls2sql.pl file="016-Linées-Plante.xls" skip=0 table="bonnier_v0_00_linees_plante" > bonnier_v0_00_linees_plante.sql
perl xls2sql.pl file="016-Linées-Texte.xls" skip=0 table="bonnier_v0_00_linees_texte" > bonnier_v0_00_linees_texte.sql
perl xls2sql.pl file="017-Tiliacées-Plante.xls" skip=0 table="bonnier_v0_00_tiliacees_plante" > bonnier_v0_00_tiliacees_plante.sql
perl xls2sql.pl file="017-Tiliacées-Texte.xls" skip=0 table="bonnier_v0_00_tiliacees_texte" > bonnier_v0_00_tiliacees_texte.sql
perl xls2sql.pl file="018-Malvacées-Plante.xls" skip=0 table="bonnier_v0_00_malvacees_plante" > bonnier_v0_00_malvacees_plante.sql
perl xls2sql.pl file="018-Malvacées-Texte.xls" skip=0 table="bonnier_v0_00_malvacees_texte" > bonnier_v0_00_malvacees_texte.sql
perl xls2sql.pl file="019-Géraniées-Plante.xls" skip=0 table="bonnier_v0_00_geraniees_plante" > bonnier_v0_00_geraniees_plante.sql
perl xls2sql.pl file="019-Géraniées-Texte.xls" skip=0 table="bonnier_v0_00_geraniees_texte" > bonnier_v0_00_geraniees_texte.sql
perl xls2sql.pl file="020-Hypéricinées-Plante.xls" skip=0 table="bonnier_v0_00_hypericinees_plante" > bonnier_v0_00_hypericinees_plante.sql
perl xls2sql.pl file="020-Hypéricinées-Texte.xls" skip=0 table="bonnier_v0_00_hypericinees_texte" > bonnier_v0_00_hypericinees_texte.sql
perl xls2sql.pl file="021-Acérinées-Plante.xls" skip=0 table="bonnier_v0_00_acerinees_plante" > bonnier_v0_00_acerinees_plante.sql
perl xls2sql.pl file="021-Acérinées-Texte.xls" skip=0 table="bonnier_v0_00_acerinees_texte" > bonnier_v0_00_acerinees_texte.sql
perl xls2sql.pl file="022-Ampélidées-Plante.xls" skip=0 table="bonnier_v0_00_ampelidees_plante" > bonnier_v0_00_ampelidees_plante.sql
perl xls2sql.pl file="022-Ampélidées-Texte.xls" skip=0 table="bonnier_v0_00_ampelidees_texte" > bonnier_v0_00_ampelidees_texte.sql
perl xls2sql.pl file="023-Hippocastanées-Plante.xls" skip=0 table="bonnier_v0_00_hippocastanees_plante" > bonnier_v0_00_hippocastanees_plante.sql
perl xls2sql.pl file="023-Hippocastanées-Texte.xls" skip=0 table="bonnier_v0_00_hippocastanees_texte" > bonnier_v0_00_hippocastanees_texte.sql
perl xls2sql.pl file="024-Méliacées-Plante.xls" skip=0 table="bonnier_v0_00_meliacees_plante" > bonnier_v0_00_meliacees_plante.sql
perl xls2sql.pl file="024-Méliacées-Texte.xls" skip=0 table="bonnier_v0_00_meliacees_texte" > bonnier_v0_00_meliacees_texte.sql
perl xls2sql.pl file="025-Balsaminées-Plante.xls" skip=0 table="bonnier_v0_00_balsaminees_plante" > bonnier_v0_00_balsaminees_plante.sql
perl xls2sql.pl file="025-Balsaminées-Texte.xls" skip=0 table="bonnier_v0_00_balsaminees_texte" > bonnier_v0_00_balsaminees_texte.sql
perl xls2sql.pl file="026-Oxalidées-Plante.xls" skip=0 table="bonnier_v0_00_oxalidees_plante" > bonnier_v0_00_oxalidees_plante.sql
perl xls2sql.pl file="026-Oxalidées-Texte.xls" skip=0 table="bonnier_v0_00_oxalidees_texte" > bonnier_v0_00_oxalidees_texte.sql
perl xls2sql.pl file="027-Zygophyllées-Plante.xls" skip=0 table="bonnier_v0_00_zygophyllees_plante" > bonnier_v0_00_zygophyllees_plante.sql
perl xls2sql.pl file="027-Zygophyllées-Texte.xls" skip=0 table="bonnier_v0_00_zygophyllees_texte" > bonnier_v0_00_zygophyllees_texte.sql
perl xls2sql.pl file="028-Hespéridées-Plante.xls" skip=0 table="bonnier_v0_00_hesperidees_plante" > bonnier_v0_00_hesperidees_plante.sql
perl xls2sql.pl file="028-Hespéridées-Texte.xls" skip=0 table="bonnier_v0_00_hesperidees_texte" > bonnier_v0_00_hesperidees_texte.sql
perl xls2sql.pl file="029-Rutacées-Plante.xls" skip=0 table="bonnier_v0_00_rutacees_plante" > bonnier_v0_00_rutacees_plante.sql
perl xls2sql.pl file="029-Rutacées-Texte.xls" skip=0 table="bonnier_v0_00_rutacees_texte" > bonnier_v0_00_rutacees_texte.sql
perl xls2sql.pl file="030-Coriariées-Plante.xls" skip=0 table="bonnier_v0_00_coriariees_plante" > bonnier_v0_00_coriariees_plante.sql
perl xls2sql.pl file="030-Coriariées-Texte.xls" skip=0 table="bonnier_v0_00_coriariees_texte" > bonnier_v0_00_coriariees_texte.sql
perl xls2sql.pl file="031-Celastrinées-Plante.xls" skip=0 table="bonnier_v0_00_celastrinees_plante" > bonnier_v0_00_celastrinees_plante.sql
perl xls2sql.pl file="031-Celastrinées-Texte.xls" skip=0 table="bonnier_v0_00_celastrinees_texte" > bonnier_v0_00_celastrinees_texte.sql
perl xls2sql.pl file="032-Staphyléacées-Plante.xls" skip=0 table="bonnier_v0_00_staphyleacees_plante" > bonnier_v0_00_staphyleacees_plante.sql
perl xls2sql.pl file="032-Staphyléacées-Texte.xls" skip=0 table="bonnier_v0_00_staphyleacees_texte" > bonnier_v0_00_staphyleacees_texte.sql
perl xls2sql.pl file="033-Ilicinées-Plante.xls" skip=0 table="bonnier_v0_00_ilicinees_plante" > bonnier_v0_00_ilicinees_plante.sql
perl xls2sql.pl file="033-Ilicinées-Texte.xls" skip=0 table="bonnier_v0_00_ilicinees_texte" > bonnier_v0_00_ilicinees_texte.sql
perl xls2sql.pl file="034-Rhamnées-Plante.xls" skip=0 table="bonnier_v0_00_rhamnees_plante" > bonnier_v0_00_rhamnees_plante.sql
perl xls2sql.pl file="034-Rhamnées-Texte.xls" skip=0 table="bonnier_v0_00_rhamnees_texte" > bonnier_v0_00_rhamnees_texte.sql
perl xls2sql.pl file="035-Térébinthacées-Plante.xls" skip=0 table="bonnier_v0_00_térebinthacees_plante" > bonnier_v0_00_térebinthacees_plante.sql
perl xls2sql.pl file="035-Térébinthacées-Texte.xls" skip=0 table="bonnier_v0_00_térebinthacees_texte" > bonnier_v0_00_térebinthacees_texte.sql
perl xls2sql.pl file="036-Papilionacées-Plante.xls" skip=0 table="bonnier_v0_00_papilionacees_plante" > bonnier_v0_00_papilionacees_plante.sql
perl xls2sql.pl file="036-Papilionacées-Texte.xls" skip=0 table="bonnier_v0_00_papilionacees_texte" > bonnier_v0_00_papilionacees_texte.sql
perl xls2sql.pl file="037-Césalpiniées-Plante.xls" skip=0 table="bonnier_v0_00_cesalpiniees_plante" > bonnier_v0_00_cesalpiniees_plante.sql
perl xls2sql.pl file="037-Césalpiniées-Texte.xls" skip=0 table="bonnier_v0_00_cesalpiniees_texte" > bonnier_v0_00_cesalpiniees_texte.sql
perl xls2sql.pl file="038-Rosacées-Plante.xls" skip=0 table="bonnier_v0_00_rosacees_plante" > bonnier_v0_00_rosacees_plante.sql
perl xls2sql.pl file="038-Rosacées-Texte.xls" skip=0 table="bonnier_v0_00_rosacees_texte" > bonnier_v0_00_rosacees_texte.sql
perl xls2sql.pl file="039-Granatées-Plante.xls" skip=0 table="bonnier_v0_00_granatees_plante" > bonnier_v0_00_granatees_plante.sql
perl xls2sql.pl file="039-Granatées-Texte.xls" skip=0 table="bonnier_v0_00_granatees_texte" > bonnier_v0_00_granatees_texte.sql
perl xls2sql.pl file="040-Onagrariées-Plante.xls" skip=0 table="bonnier_v0_00_onagrariees_plante" > bonnier_v0_00_onagrariees_plante.sql
perl xls2sql.pl file="040-Onagrariées-Texte.xls" skip=0 table="bonnier_v0_00_onagrariees_texte" > bonnier_v0_00_onagrariees_texte.sql
perl xls2sql.pl file="041-Myriophyllées-Plante.xls" skip=0 table="bonnier_v0_00_myriophyllees_plante" > bonnier_v0_00_myriophyllees_plante.sql
perl xls2sql.pl file="041-Myriophyllées-Texte.xls" skip=0 table="bonnier_v0_00_myriophyllees_texte" > bonnier_v0_00_myriophyllees_texte.sql
perl xls2sql.pl file="042-Hippuridées-Plante.xls" skip=0 table="bonnier_v0_00_hippuridees_plante" > bonnier_v0_00_hippuridees_plante.sql
perl xls2sql.pl file="042-Hippuridées-Texte.xls" skip=0 table="bonnier_v0_00_hippuridees_texte" > bonnier_v0_00_hippuridees_texte.sql
perl xls2sql.pl file="043-Callitrichinées-Plante.xls" skip=0 table="bonnier_v0_00_callitrichinees_plante" > bonnier_v0_00_callitrichinees_plante.sql
perl xls2sql.pl file="043-Callitrichinées-Texte.xls" skip=0 table="bonnier_v0_00_callitrichinees_texte" > bonnier_v0_00_callitrichinees_texte.sql
perl xls2sql.pl file="044-Ceratophyllées-Plante.xls" skip=0 table="bonnier_v0_00_ceratophyllees_plante" > bonnier_v0_00_ceratophyllees_plante.sql
perl xls2sql.pl file="044-Ceratophyllées-Texte.xls" skip=0 table="bonnier_v0_00_ceratophyllees_texte" > bonnier_v0_00_ceratophyllees_texte.sql
perl xls2sql.pl file="045-Lythrariées-Plante.xls" skip=0 table="bonnier_v0_00_lythrariees_plante" > bonnier_v0_00_lythrariees_plante.sql
perl xls2sql.pl file="045-Lythrariées-Texte.xls" skip=0 table="bonnier_v0_00_lythrariees_texte" > bonnier_v0_00_lythrariees_texte.sql
perl xls2sql.pl file="046-Philadelphées-Plante.xls" skip=0 table="bonnier_v0_00_philadelphees_plante" > bonnier_v0_00_philadelphees_plante.sql
perl xls2sql.pl file="046-Philadelphées-Texte.xls" skip=0 table="bonnier_v0_00_philadelphees_texte" > bonnier_v0_00_philadelphees_texte.sql
perl xls2sql.pl file="047-Tamariscinées-Plante.xls" skip=0 table="bonnier_v0_00_tamariscinees_plante" > bonnier_v0_00_tamariscinees_plante.sql
perl xls2sql.pl file="047-Tamariscinées-Texte.xls" skip=0 table="bonnier_v0_00_tamariscinees_texte" > bonnier_v0_00_tamariscinees_texte.sql
perl xls2sql.pl file="048-Myrtacées-Plante.xls" skip=0 table="bonnier_v0_00_myrtacees_plante" > bonnier_v0_00_myrtacees_plante.sql
perl xls2sql.pl file="048-Myrtacées-Texte.xls" skip=0 table="bonnier_v0_00_myrtacees_texte" > bonnier_v0_00_myrtacees_texte.sql
perl xls2sql.pl file="049-Cucurbitacées-Plante.xls" skip=0 table="bonnier_v0_00_cucurbitacees_plante" > bonnier_v0_00_cucurbitacees_plante.sql
perl xls2sql.pl file="049-Cucurbitacées-Texte.xls" skip=0 table="bonnier_v0_00_cucurbitacees_texte" > bonnier_v0_00_cucurbitacees_texte.sql
perl xls2sql.pl file="050-Portulacées-Plante.xls" skip=0 table="bonnier_v0_00_portulacees_plante" > bonnier_v0_00_portulacees_plante.sql
perl xls2sql.pl file="050-Portulacées-Texte.xls" skip=0 table="bonnier_v0_00_portulacees_texte" > bonnier_v0_00_portulacees_texte.sql
perl xls2sql.pl file="051-Paronychiées-Plante.xls" skip=0 table="bonnier_v0_00_paronychiees_plante" > bonnier_v0_00_paronychiees_plante.sql
perl xls2sql.pl file="051-Paronychiées-Texte.xls" skip=0 table="bonnier_v0_00_paronychiees_texte" > bonnier_v0_00_paronychiees_texte.sql
perl xls2sql.pl file="052-Crassulacées-Plante.xls" skip=0 table="bonnier_v0_00_crassulacees_plante" > bonnier_v0_00_crassulacees_plante.sql
perl xls2sql.pl file="052-Crassulacées-Texte.xls" skip=0 table="bonnier_v0_00_crassulacees_texte" > bonnier_v0_00_crassulacees_texte.sql
perl xls2sql.pl file="053-Cactées-Plante.xls" skip=0 table="bonnier_v0_00_cactees_plante" > bonnier_v0_00_cactees_plante.sql
perl xls2sql.pl file="053-Cactées-Texte.xls" skip=0 table="bonnier_v0_00_cactees_texte" > bonnier_v0_00_cactees_texte.sql
perl xls2sql.pl file="054-Ficoïdées-Plante.xls" skip=0 table="bonnier_v0_00_ficoïdees_plante" > bonnier_v0_00_ficoïdees_plante.sql
perl xls2sql.pl file="054-Ficoïdées-Texte.xls" skip=0 table="bonnier_v0_00_ficoïdees_texte" > bonnier_v0_00_ficoïdees_texte.sql
perl xls2sql.pl file="055-Grossulariées-Plante.xls" skip=0 table="bonnier_v0_00_grossulariees_plante" > bonnier_v0_00_grossulariees_plante.sql
perl xls2sql.pl file="055-Grossulariées-Texte.xls" skip=0 table="bonnier_v0_00_grossulariees_texte" > bonnier_v0_00_grossulariees_texte.sql
perl xls2sql.pl file="056-Saxifragées-Plante.xls" skip=0 table="bonnier_v0_00_saxifragees_plante" > bonnier_v0_00_saxifragees_plante.sql
perl xls2sql.pl file="056-Saxifragées-Texte.xls" skip=0 table="bonnier_v0_00_saxifragees_texte" > bonnier_v0_00_saxifragees_texte.sql
perl xls2sql.pl file="057-Ombelliféres-Plante.xls" skip=0 table="bonnier_v0_00_ombelliferes_plante" > bonnier_v0_00_ombelliferes_plante.sql
perl xls2sql.pl file="057-Ombelliféres-Texte.xls" skip=0 table="bonnier_v0_00_ombelliferes_texte" > bonnier_v0_00_ombelliferes_texte.sql
perl xls2sql.pl file="058-Araliacées-Plante.xls" skip=0 table="bonnier_v0_00_araliacees_plante" > bonnier_v0_00_araliacees_plante.sql
perl xls2sql.pl file="058-Araliacées-Texte.xls" skip=0 table="bonnier_v0_00_araliacees_texte" > bonnier_v0_00_araliacees_texte.sql
perl xls2sql.pl file="059-Cornées-Plante.xls" skip=0 table="bonnier_v0_00_cornees_plante" > bonnier_v0_00_cornees_plante.sql
perl xls2sql.pl file="059-Cornées-Texte.xls" skip=0 table="bonnier_v0_00_cornees_texte" > bonnier_v0_00_cornees_texte.sql
perl xls2sql.pl file="060-Loranthacées-Plante.xls" skip=0 table="bonnier_v0_00_loranthacees_plante" > bonnier_v0_00_loranthacees_plante.sql
perl xls2sql.pl file="060-Loranthacées-Texte.xls" skip=0 table="bonnier_v0_00_loranthacees_texte" > bonnier_v0_00_loranthacees_texte.sql
perl xls2sql.pl file="061-Caprifoliacées-Plante.xls" skip=0 table="bonnier_v0_00_caprifoliacees_plante" > bonnier_v0_00_caprifoliacees_plante.sql
perl xls2sql.pl file="061-Caprifoliacées-Texte.xls" skip=0 table="bonnier_v0_00_caprifoliacees_texte" > bonnier_v0_00_caprifoliacees_texte.sql
perl xls2sql.pl file="062-Rubiacées-Plante.xls" skip=0 table="bonnier_v0_00_rubiacees_plante" > bonnier_v0_00_rubiacees_plante.sql
perl xls2sql.pl file="062-Rubiacées-Texte.xls" skip=0 table="bonnier_v0_00_rubiacees_texte" > bonnier_v0_00_rubiacees_texte.sql
perl xls2sql.pl file="063-Valérianées-Plante.xls" skip=0 table="bonnier_v0_00_valerianees_plante" > bonnier_v0_00_valerianees_plante.sql
perl xls2sql.pl file="063-Valérianées-Texte.xls" skip=0 table="bonnier_v0_00_valerianees_texte" > bonnier_v0_00_valerianees_texte.sql
perl xls2sql.pl file="064-Dipsacées-Plante.xls" skip=0 table="bonnier_v0_00_dipsacees_plante" > bonnier_v0_00_dipsacees_plante.sql
perl xls2sql.pl file="064-Dipsacées-Texte.xls" skip=0 table="bonnier_v0_00_dipsacees_texte" > bonnier_v0_00_dipsacees_texte.sql
perl xls2sql.pl file="065-Composées-Plante.xls" skip=0 table="bonnier_v0_00_composees_plante" > bonnier_v0_00_composees_plante.sql
perl xls2sql.pl file="065-Composées-Texte.xls" skip=0 table="bonnier_v0_00_composees_texte" > bonnier_v0_00_composees_texte.sql
perl xls2sql.pl file="066-Ambrosiacées-Plante.xls" skip=0 table="bonnier_v0_00_ambrosiacees_plante" > bonnier_v0_00_ambrosiacees_plante.sql
perl xls2sql.pl file="066-Ambrosiacées-Texte.xls" skip=0 table="bonnier_v0_00_ambrosiacees_texte" > bonnier_v0_00_ambrosiacees_texte.sql
perl xls2sql.pl file="067-Lobéliacées-Plante.xls" skip=0 table="bonnier_v0_00_lobeliacees_plante" > bonnier_v0_00_lobeliacees_plante.sql
perl xls2sql.pl file="067-Lobéliacées-Texte.xls" skip=0 table="bonnier_v0_00_lobeliacees_texte" > bonnier_v0_00_lobeliacees_texte.sql
perl xls2sql.pl file="068-Campanulacées-Plante.xls" skip=0 table="bonnier_v0_00_campanulacees_plante" > bonnier_v0_00_campanulacees_plante.sql
perl xls2sql.pl file="068-Campanulacées-Texte.xls" skip=0 table="bonnier_v0_00_campanulacees_texte" > bonnier_v0_00_campanulacees_texte.sql
perl xls2sql.pl file="069-Vacciniées-Plante.xls" skip=0 table="bonnier_v0_00_vacciniees_plante" > bonnier_v0_00_vacciniees_plante.sql
perl xls2sql.pl file="069-Vacciniées-Texte.xls" skip=0 table="bonnier_v0_00_vacciniees_texte" > bonnier_v0_00_vacciniees_texte.sql
perl xls2sql.pl file="070-Ericinées-Plante.xls" skip=0 table="bonnier_v0_00_ericinees_plante" > bonnier_v0_00_ericinees_plante.sql
perl xls2sql.pl file="070-Ericinées-Texte.xls" skip=0 table="bonnier_v0_00_ericinees_texte" > bonnier_v0_00_ericinees_texte.sql
perl xls2sql.pl file="071-Pyrolacées-Plante.xls" skip=0 table="bonnier_v0_00_pyrolacees_plante" > bonnier_v0_00_pyrolacees_plante.sql
perl xls2sql.pl file="071-Pyrolacées-Texte.xls" skip=0 table="bonnier_v0_00_pyrolacees_texte" > bonnier_v0_00_pyrolacees_texte.sql
perl xls2sql.pl file="072-Monotropées-Plante.xls" skip=0 table="bonnier_v0_00_monotropees_plante" > bonnier_v0_00_monotropees_plante.sql
perl xls2sql.pl file="072-Monotropées-Texte.xls" skip=0 table="bonnier_v0_00_monotropees_texte" > bonnier_v0_00_monotropees_texte.sql
perl xls2sql.pl file="073-Lentibulariées-Plante.xls" skip=0 table="bonnier_v0_00_lentibulariees_plante" > bonnier_v0_00_lentibulariees_plante.sql
perl xls2sql.pl file="073-Lentibulariées-Texte.xls" skip=0 table="bonnier_v0_00_lentibulariees_texte" > bonnier_v0_00_lentibulariees_texte.sql
perl xls2sql.pl file="074-Primulacées-Plante.xls" skip=0 table="bonnier_v0_00_primulacees_plante" > bonnier_v0_00_primulacees_plante.sql
perl xls2sql.pl file="074-Primulacées-Texte.xls" skip=0 table="bonnier_v0_00_primulacees_texte" > bonnier_v0_00_primulacees_texte.sql
perl xls2sql.pl file="075-Ebénacées-Plante.xls" skip=0 table="bonnier_v0_00_ebenacees_plante" > bonnier_v0_00_ebenacees_plante.sql
perl xls2sql.pl file="075-Ebénacées-Texte.xls" skip=0 table="bonnier_v0_00_ebenacees_texte" > bonnier_v0_00_ebenacees_texte.sql
perl xls2sql.pl file="076-Styracées-Plante.xls" skip=0 table="bonnier_v0_00_styracees_plante" > bonnier_v0_00_styracees_plante.sql
perl xls2sql.pl file="076-Styracées-Texte.xls" skip=0 table="bonnier_v0_00_styracees_texte" > bonnier_v0_00_styracees_texte.sql
perl xls2sql.pl file="077-Oléinées-Plante.xls" skip=0 table="bonnier_v0_00_oleinees_plante" > bonnier_v0_00_oleinees_plante.sql
perl xls2sql.pl file="077-Oléinées-Texte.xls" skip=0 table="bonnier_v0_00_oleinees_texte" > bonnier_v0_00_oleinees_texte.sql
perl xls2sql.pl file="078-Jasminées-Plante.xls" skip=0 table="bonnier_v0_00_jasminees_plante" > bonnier_v0_00_jasminees_plante.sql
perl xls2sql.pl file="078-Jasminées-Texte.xls" skip=0 table="bonnier_v0_00_jasminees_texte" > bonnier_v0_00_jasminees_texte.sql
perl xls2sql.pl file="079-Apocynées-Plante.xls" skip=0 table="bonnier_v0_00_apocynees_plante" > bonnier_v0_00_apocynees_plante.sql
perl xls2sql.pl file="079-Apocynées-Texte.xls" skip=0 table="bonnier_v0_00_apocynees_texte" > bonnier_v0_00_apocynees_texte.sql
perl xls2sql.pl file="080-Asclépiadées-Plante.xls" skip=0 table="bonnier_v0_00_asclepiadees_plante" > bonnier_v0_00_asclepiadees_plante.sql
perl xls2sql.pl file="080-Asclépiadées-Texte.xls" skip=0 table="bonnier_v0_00_asclepiadees_texte" > bonnier_v0_00_asclepiadees_texte.sql
perl xls2sql.pl file="081-Gentianées-Plante.xls" skip=0 table="bonnier_v0_00_gentianees_plante" > bonnier_v0_00_gentianees_plante.sql
perl xls2sql.pl file="081-Gentianées-Texte.xls" skip=0 table="bonnier_v0_00_gentianees_texte" > bonnier_v0_00_gentianees_texte.sql
perl xls2sql.pl file="082-Polémoniacées-Plante.xls" skip=0 table="bonnier_v0_00_polemoniacees_plante" > bonnier_v0_00_polemoniacees_plante.sql
perl xls2sql.pl file="082-Polémoniacées-Texte.xls" skip=0 table="bonnier_v0_00_polemoniacees_texte" > bonnier_v0_00_polemoniacees_texte.sql
perl xls2sql.pl file="083-Convolvulacées-Plante.xls" skip=0 table="bonnier_v0_00_convolvulacees_plante" > bonnier_v0_00_convolvulacees_plante.sql
perl xls2sql.pl file="083-Convolvulacées-Texte.xls" skip=0 table="bonnier_v0_00_convolvulacees_texte" > bonnier_v0_00_convolvulacees_texte.sql
perl xls2sql.pl file="084-Cuscutacées-Plante.xls" skip=0 table="bonnier_v0_00_cuscutacees_plante" > bonnier_v0_00_cuscutacees_plante.sql
perl xls2sql.pl file="084-Cuscutacées-Texte.xls" skip=0 table="bonnier_v0_00_cuscutacees_texte" > bonnier_v0_00_cuscutacees_texte.sql
perl xls2sql.pl file="085-Ramondiacées-Plante.xls" skip=0 table="bonnier_v0_00_ramondiacees_plante" > bonnier_v0_00_ramondiacees_plante.sql
perl xls2sql.pl file="085-Ramondiacées-Texte.xls" skip=0 table="bonnier_v0_00_ramondiacees_texte" > bonnier_v0_00_ramondiacees_texte.sql
perl xls2sql.pl file="086-Borraginées-Plante.xls" skip=0 table="bonnier_v0_00_borraginees_plante" > bonnier_v0_00_borraginees_plante.sql
perl xls2sql.pl file="086-Borraginées-Texte.xls" skip=0 table="bonnier_v0_00_borraginees_texte" > bonnier_v0_00_borraginees_texte.sql
perl xls2sql.pl file="087-Solanées-Plante.xls" skip=0 table="bonnier_v0_00_solanees_plante" > bonnier_v0_00_solanees_plante.sql
perl xls2sql.pl file="087-Solanées-Texte.xls" skip=0 table="bonnier_v0_00_solanees_texte" > bonnier_v0_00_solanees_texte.sql
perl xls2sql.pl file="088-Verbascées-Plante.xls" skip=0 table="bonnier_v0_00_verbascees_plante" > bonnier_v0_00_verbascees_plante.sql
perl xls2sql.pl file="088-Verbascées-Texte.xls" skip=0 table="bonnier_v0_00_verbascees_texte" > bonnier_v0_00_verbascees_texte.sql
perl xls2sql.pl file="089-Scrofularinées-Plante.xls" skip=0 table="bonnier_v0_00_scrofularinees_plante" > bonnier_v0_00_scrofularinees_plante.sql
perl xls2sql.pl file="089-Scrofularinées-Texte.xls" skip=0 table="bonnier_v0_00_scrofularinees_texte" > bonnier_v0_00_scrofularinees_texte.sql
perl xls2sql.pl file="090-Orobanchées-Plante.xls" skip=0 table="bonnier_v0_00_orobanchees_plante" > bonnier_v0_00_orobanchees_plante.sql
perl xls2sql.pl file="090-Orobanchées-Texte.xls" skip=0 table="bonnier_v0_00_orobanchees_texte" > bonnier_v0_00_orobanchees_texte.sql
perl xls2sql.pl file="091-Labiées-Plante.xls" skip=0 table="bonnier_v0_00_labiees_plante" > bonnier_v0_00_labiees_plante.sql
perl xls2sql.pl file="091-Labiées-Texte.xls" skip=0 table="bonnier_v0_00_labiees_texte" > bonnier_v0_00_labiees_texte.sql
perl xls2sql.pl file="092-Acanthacées-Plante.xls" skip=0 table="bonnier_v0_00_acanthacees_plante" > bonnier_v0_00_acanthacees_plante.sql
perl xls2sql.pl file="092-Acanthacées-Texte.xls" skip=0 table="bonnier_v0_00_acanthacees_texte" > bonnier_v0_00_acanthacees_texte.sql
perl xls2sql.pl file="093-Verbénacées-Plante.xls" skip=0 table="bonnier_v0_00_verbenacees_plante" > bonnier_v0_00_verbenacees_plante.sql
perl xls2sql.pl file="093-Verbénacées-Texte.xls" skip=0 table="bonnier_v0_00_verbenacees_texte" > bonnier_v0_00_verbenacees_texte.sql
perl xls2sql.pl file="094-Plantaginées-Plante.xls" skip=0 table="bonnier_v0_00_plantaginees_plante" > bonnier_v0_00_plantaginees_plante.sql
perl xls2sql.pl file="094-Plantaginées-Texte.xls" skip=0 table="bonnier_v0_00_plantaginees_texte" > bonnier_v0_00_plantaginees_texte.sql
perl xls2sql.pl file="095-Plombaginées-Plante.xls" skip=0 table="bonnier_v0_00_plombaginees_plante" > bonnier_v0_00_plombaginees_plante.sql
perl xls2sql.pl file="095-Plombaginées-Texte.xls" skip=0 table="bonnier_v0_00_plombaginees_texte" > bonnier_v0_00_plombaginees_texte.sql
perl xls2sql.pl file="096-Globulariées-Plante.xls" skip=0 table="bonnier_v0_00_globulariees_plante" > bonnier_v0_00_globulariees_plante.sql
perl xls2sql.pl file="096-Globulariées-Texte.xls" skip=0 table="bonnier_v0_00_globulariees_texte" > bonnier_v0_00_globulariees_texte.sql
perl xls2sql.pl file="097-Phytolaccées-Plante.xls" skip=0 table="bonnier_v0_00_phytolaccees_plante" > bonnier_v0_00_phytolaccees_plante.sql
perl xls2sql.pl file="097-Phytolaccées-Texte.xls" skip=0 table="bonnier_v0_00_phytolaccees_texte" > bonnier_v0_00_phytolaccees_texte.sql
perl xls2sql.pl file="098-Amarantacées-Plante.xls" skip=0 table="bonnier_v0_00_amarantacees_plante" > bonnier_v0_00_amarantacees_plante.sql
perl xls2sql.pl file="098-Amarantacées-Texte.xls" skip=0 table="bonnier_v0_00_amarantacees_texte" > bonnier_v0_00_amarantacees_texte.sql
perl xls2sql.pl file="099-Salsolacées-Plante.xls" skip=0 table="bonnier_v0_00_salsolacees_plante" > bonnier_v0_00_salsolacees_plante.sql
perl xls2sql.pl file="099-Salsolacées-Texte.xls" skip=0 table="bonnier_v0_00_salsolacees_texte" > bonnier_v0_00_salsolacees_texte.sql
perl xls2sql.pl file="100-Polygonées-Plante.xls" skip=0 table="bonnier_v0_00_polygonees_plante" > bonnier_v0_00_polygonees_plante.sql
perl xls2sql.pl file="100-Polygonées-Texte.xls" skip=0 table="bonnier_v0_00_polygonees_texte" > bonnier_v0_00_polygonees_texte.sql
perl xls2sql.pl file="101-Daphnoidées-Plante.xls" skip=0 table="bonnier_v0_00_daphnoidees_plante" > bonnier_v0_00_daphnoidees_plante.sql
perl xls2sql.pl file="101-Daphnoidées-Texte.xls" skip=0 table="bonnier_v0_00_daphnoidees_texte" > bonnier_v0_00_daphnoidees_texte.sql
perl xls2sql.pl file="102-Laurinées-Plante.xls" skip=0 table="bonnier_v0_00_laurinees_plante" > bonnier_v0_00_laurinees_plante.sql
perl xls2sql.pl file="102-Laurinées-Texte.xls" skip=0 table="bonnier_v0_00_laurinees_texte" > bonnier_v0_00_laurinees_texte.sql
perl xls2sql.pl file="103-Santalacées-Plante.xls" skip=0 table="bonnier_v0_00_santalacees_plante" > bonnier_v0_00_santalacees_plante.sql
perl xls2sql.pl file="103-Santalacées-Texte.xls" skip=0 table="bonnier_v0_00_santalacees_texte" > bonnier_v0_00_santalacees_texte.sql
perl xls2sql.pl file="104-Eléagnées-Plante.xls" skip=0 table="bonnier_v0_00_eleagnees_plante" > bonnier_v0_00_eleagnees_plante.sql
perl xls2sql.pl file="104-Eléagnées-Texte.xls" skip=0 table="bonnier_v0_00_eleagnees_texte" > bonnier_v0_00_eleagnees_texte.sql
perl xls2sql.pl file="105-Cytinées-Plante.xls" skip=0 table="bonnier_v0_00_cytinees_plante" > bonnier_v0_00_cytinees_plante.sql
perl xls2sql.pl file="105-Cytinées-Texte.xls" skip=0 table="bonnier_v0_00_cytinees_texte" > bonnier_v0_00_cytinees_texte.sql
perl xls2sql.pl file="106-Aristolochiées-Plante.xls" skip=0 table="bonnier_v0_00_aristolochiees_plante" > bonnier_v0_00_aristolochiees_plante.sql
perl xls2sql.pl file="106-Aristolochiées-Texte.xls" skip=0 table="bonnier_v0_00_aristolochiees_texte" > bonnier_v0_00_aristolochiees_texte.sql
perl xls2sql.pl file="107-Empétrées-Plante.xls" skip=0 table="bonnier_v0_00_empetrees_plante" > bonnier_v0_00_empetrees_plante.sql
perl xls2sql.pl file="107-Empétrées-Texte.xls" skip=0 table="bonnier_v0_00_empetrees_texte" > bonnier_v0_00_empetrees_texte.sql
perl xls2sql.pl file="108-Euphorbiacées-Plante.xls" skip=0 table="bonnier_v0_00_euphorbiacees_plante" > bonnier_v0_00_euphorbiacees_plante.sql
perl xls2sql.pl file="108-Euphorbiacées-Texte.xls" skip=0 table="bonnier_v0_00_euphorbiacees_texte" > bonnier_v0_00_euphorbiacees_texte.sql
perl xls2sql.pl file="109-Morées-Plante.xls" skip=0 table="bonnier_v0_00_morees_plante" > bonnier_v0_00_morees_plante.sql
perl xls2sql.pl file="109-Morées-Texte.xls" skip=0 table="bonnier_v0_00_morees_texte" > bonnier_v0_00_morees_texte.sql
perl xls2sql.pl file="110-Ficacées-Plante.xls" skip=0 table="bonnier_v0_00_ficacees_plante" > bonnier_v0_00_ficacees_plante.sql
perl xls2sql.pl file="110-Ficacées-Texte.xls" skip=0 table="bonnier_v0_00_ficacees_texte" > bonnier_v0_00_ficacees_texte.sql
perl xls2sql.pl file="111-Celtidées-Plante.xls" skip=0 table="bonnier_v0_00_celtidees_plante" > bonnier_v0_00_celtidees_plante.sql
perl xls2sql.pl file="111-Celtidées-Texte.xls" skip=0 table="bonnier_v0_00_celtidees_texte" > bonnier_v0_00_celtidees_texte.sql
perl xls2sql.pl file="112-Ulmacées-Plante.xls" skip=0 table="bonnier_v0_00_ulmacees_plante" > bonnier_v0_00_ulmacees_plante.sql
perl xls2sql.pl file="112-Ulmacées-Texte.xls" skip=0 table="bonnier_v0_00_ulmacees_texte" > bonnier_v0_00_ulmacees_texte.sql
perl xls2sql.pl file="113-Urticées-Plante.xls" skip=0 table="bonnier_v0_00_urticees_plante" > bonnier_v0_00_urticees_plante.sql
perl xls2sql.pl file="113-Urticées-Texte.xls" skip=0 table="bonnier_v0_00_urticees_texte" > bonnier_v0_00_urticees_texte.sql
perl xls2sql.pl file="114-Cannabinées-Plante.xls" skip=0 table="bonnier_v0_00_cannabinees_plante" > bonnier_v0_00_cannabinees_plante.sql
perl xls2sql.pl file="114-Cannabinées-Texte.xls" skip=0 table="bonnier_v0_00_cannabinees_texte" > bonnier_v0_00_cannabinees_texte.sql
perl xls2sql.pl file="115-Juglandées-Plante.xls" skip=0 table="bonnier_v0_00_juglandees_plante" > bonnier_v0_00_juglandees_plante.sql
perl xls2sql.pl file="115-Juglandées-Texte.xls" skip=0 table="bonnier_v0_00_juglandees_texte" > bonnier_v0_00_juglandees_texte.sql
perl xls2sql.pl file="116-Cupulifères-Plante.xls" skip=0 table="bonnier_v0_00_cupuliferes_plante" > bonnier_v0_00_cupuliferes_plante.sql
perl xls2sql.pl file="116-Cupulifères-Texte.xls" skip=0 table="bonnier_v0_00_cupuliferes_texte" > bonnier_v0_00_cupuliferes_texte.sql
perl xls2sql.pl file="117-Salicinées-Plante.xls" skip=0 table="bonnier_v0_00_salicinees_plante" > bonnier_v0_00_salicinees_plante.sql
perl xls2sql.pl file="117-Salicinées-Texte.xls" skip=0 table="bonnier_v0_00_salicinees_texte" > bonnier_v0_00_salicinees_texte.sql
perl xls2sql.pl file="118-Platanées-Plante.xls" skip=0 table="bonnier_v0_00_platanees_plante" > bonnier_v0_00_platanees_plante.sql
perl xls2sql.pl file="118-Platanées-Texte.xls" skip=0 table="bonnier_v0_00_platanees_texte" > bonnier_v0_00_platanees_texte.sql
perl xls2sql.pl file="119-Bétulinèes-Plante.xls" skip=0 table="bonnier_v0_00_betulinees_plante" > bonnier_v0_00_betulinees_plante.sql
perl xls2sql.pl file="119-Bétulinèes-Texte.xls" skip=0 table="bonnier_v0_00_betulinees_texte" > bonnier_v0_00_betulinees_texte.sql
perl xls2sql.pl file="120-Myricèes-Plante.xls" skip=0 table="bonnier_v0_00_myricees_plante" > bonnier_v0_00_myricees_plante.sql
perl xls2sql.pl file="120-Myricèes-Texte.xls" skip=0 table="bonnier_v0_00_myricees_texte" > bonnier_v0_00_myricees_texte.sql
perl xls2sql.pl file="121-Alismacées-Plante.xls" skip=0 table="bonnier_v0_00_alismacees_plante" > bonnier_v0_00_alismacees_plante.sql
perl xls2sql.pl file="121-Alismacées-Texte.xls" skip=0 table="bonnier_v0_00_alismacees_texte" > bonnier_v0_00_alismacees_texte.sql
perl xls2sql.pl file="122-Butomées-Plante.xls" skip=0 table="bonnier_v0_00_butomees_plante" > bonnier_v0_00_butomees_plante.sql
perl xls2sql.pl file="122-Butomées-Texte.xls" skip=0 table="bonnier_v0_00_butomees_texte" > bonnier_v0_00_butomees_texte.sql
perl xls2sql.pl file="123-Colchicacées-Plante.xls" skip=0 table="bonnier_v0_00_colchicacees_plante" > bonnier_v0_00_colchicacees_plante.sql
perl xls2sql.pl file="123-Colchicacées-Texte.xls" skip=0 table="bonnier_v0_00_colchicacees_texte" > bonnier_v0_00_colchicacees_texte.sql
perl xls2sql.pl file="124-Liliacées-Plante.xls" skip=0 table="bonnier_v0_00_liliacees_plante" > bonnier_v0_00_liliacees_plante.sql
perl xls2sql.pl file="124-Liliacées-Texte.xls" skip=0 table="bonnier_v0_00_liliacees_texte" > bonnier_v0_00_liliacees_texte.sql
perl xls2sql.pl file="125-Dioscorées-Plante.xls" skip=0 table="bonnier_v0_00_dioscorees_plante" > bonnier_v0_00_dioscorees_plante.sql
perl xls2sql.pl file="125-Dioscorées-Texte.xls" skip=0 table="bonnier_v0_00_dioscorees_texte" > bonnier_v0_00_dioscorees_texte.sql
perl xls2sql.pl file="126-Iridées-Plante.xls" skip=0 table="bonnier_v0_00_iridees_plante" > bonnier_v0_00_iridees_plante.sql
perl xls2sql.pl file="126-Iridées-Texte.xls" skip=0 table="bonnier_v0_00_iridees_texte" > bonnier_v0_00_iridees_texte.sql
perl xls2sql.pl file="127-Amaryllidées-Plante.xls" skip=0 table="bonnier_v0_00_amaryllidees_plante" > bonnier_v0_00_amaryllidees_plante.sql
perl xls2sql.pl file="127-Amaryllidées-Texte.xls" skip=0 table="bonnier_v0_00_amaryllidees_texte" > bonnier_v0_00_amaryllidees_texte.sql
perl xls2sql.pl file="128-Orchidées-Plante.xls" skip=0 table="bonnier_v0_00_orchidees_plante" > bonnier_v0_00_orchidees_plante.sql
perl xls2sql.pl file="128-Orchidées-Texte.xls" skip=0 table="bonnier_v0_00_orchidees_texte" > bonnier_v0_00_orchidees_texte.sql
perl xls2sql.pl file="129-Hydrocharidées-Plante.xls" skip=0 table="bonnier_v0_00_hydrocharidees_plante" > bonnier_v0_00_hydrocharidees_plante.sql
perl xls2sql.pl file="129-Hydrocharidées-Texte.xls" skip=0 table="bonnier_v0_00_hydrocharidees_texte" > bonnier_v0_00_hydrocharidees_texte.sql
perl xls2sql.pl file="130-Joncaginées-Plante.xls" skip=0 table="bonnier_v0_00_joncaginees_plante" > bonnier_v0_00_joncaginees_plante.sql
perl xls2sql.pl file="130-Joncaginées-Texte.xls" skip=0 table="bonnier_v0_00_joncaginees_texte" > bonnier_v0_00_joncaginees_texte.sql
perl xls2sql.pl file="131-Potamées-Plante.xls" skip=0 table="bonnier_v0_00_potamees_plante" > bonnier_v0_00_potamees_plante.sql
perl xls2sql.pl file="131-Potamées-Texte.xls" skip=0 table="bonnier_v0_00_potamees_texte" > bonnier_v0_00_potamees_texte.sql
perl xls2sql.pl file="132-Naiadees-Plante.xls" skip=0 table="bonnier_v0_00_naiadees_plante" > bonnier_v0_00_naiadees_plante.sql
perl xls2sql.pl file="132-Naiadees-Texte.xls" skip=0 table="bonnier_v0_00_naiadees_texte" > bonnier_v0_00_naiadees_texte.sql
perl xls2sql.pl file="133-Zosteracées-Plante.xls" skip=0 table="bonnier_v0_00_zosteracees_plante" > bonnier_v0_00_zosteracees_plante.sql
perl xls2sql.pl file="133-Zosteracées-Texte.xls" skip=0 table="bonnier_v0_00_zosteracees_texte" > bonnier_v0_00_zosteracees_texte.sql
perl xls2sql.pl file="134-Lemnacées-Plante.xls" skip=0 table="bonnier_v0_00_lemnacees_plante" > bonnier_v0_00_lemnacees_plante.sql
perl xls2sql.pl file="134-Lemnacées-Texte.xls" skip=0 table="bonnier_v0_00_lemnacees_texte" > bonnier_v0_00_lemnacees_texte.sql
perl xls2sql.pl file="135-Aroidées-Plante.xls" skip=0 table="bonnier_v0_00_aroidees_plante" > bonnier_v0_00_aroidees_plante.sql
perl xls2sql.pl file="135-Aroidées-Texte.xls" skip=0 table="bonnier_v0_00_aroidees_texte" > bonnier_v0_00_aroidees_texte.sql
perl xls2sql.pl file="136-Typhacées-Plante.xls" skip=0 table="bonnier_v0_00_typhacees_plante" > bonnier_v0_00_typhacees_plante.sql
perl xls2sql.pl file="136-Typhacées-Texte.xls" skip=0 table="bonnier_v0_00_typhacees_texte" > bonnier_v0_00_typhacees_texte.sql
perl xls2sql.pl file="137-Joncées-Plante.xls" skip=0 table="bonnier_v0_00_joncees_plante" > bonnier_v0_00_joncees_plante.sql
perl xls2sql.pl file="137-Joncées-Texte.xls" skip=0 table="bonnier_v0_00_joncees_texte" > bonnier_v0_00_joncees_texte.sql
perl xls2sql.pl file="138-Cyperacées-Plante.xls" skip=0 table="bonnier_v0_00_cyperacees_plante" > bonnier_v0_00_cyperacees_plante.sql
perl xls2sql.pl file="138-Cyperacées-Texte.xls" skip=0 table="bonnier_v0_00_cyperacees_texte" > bonnier_v0_00_cyperacees_texte.sql
perl xls2sql.pl file="139-Graminées-Plante.xls" skip=0 table="bonnier_v0_00_graminees_plante" > bonnier_v0_00_graminees_plante.sql
perl xls2sql.pl file="139-Graminées-Texte.xls" skip=0 table="bonnier_v0_00_graminees_texte" > bonnier_v0_00_graminees_texte.sql
perl xls2sql.pl file="140-Abietinées-Plante.xls" skip=0 table="bonnier_v0_00_abietinees_plante" > bonnier_v0_00_abietinees_plante.sql
perl xls2sql.pl file="140-Abietinées-Texte.xls" skip=0 table="bonnier_v0_00_abietinees_texte" > bonnier_v0_00_abietinees_texte.sql
perl xls2sql.pl file="141-Cupressinées-Plante.xls" skip=0 table="bonnier_v0_00_cupressinees_plante" > bonnier_v0_00_cupressinees_plante.sql
perl xls2sql.pl file="141-Cupressinées-Texte.xls" skip=0 table="bonnier_v0_00_cupressinees_texte" > bonnier_v0_00_cupressinees_texte.sql
perl xls2sql.pl file="142-Taxinées-Plante.xls" skip=0 table="bonnier_v0_00_taxinees_plante" > bonnier_v0_00_taxinees_plante.sql
perl xls2sql.pl file="142-Taxinées-Texte.xls" skip=0 table="bonnier_v0_00_taxinees_texte" > bonnier_v0_00_taxinees_texte.sql
perl xls2sql.pl file="143-Gnetacées-Plante.xls" skip=0 table="bonnier_v0_00_gnetacees_plante" > bonnier_v0_00_gnetacees_plante.sql
perl xls2sql.pl file="143-Gnetacées-Texte.xls" skip=0 table="bonnier_v0_00_gnetacees_texte" > bonnier_v0_00_gnetacees_texte.sql
perl xls2sql.pl file="144-Fougères-Plante.xls" skip=0 table="bonnier_v0_00_fougeres_plante" > bonnier_v0_00_fougeres_plante.sql
perl xls2sql.pl file="144-Fougères-Texte.xls" skip=0 table="bonnier_v0_00_fougeres_texte" > bonnier_v0_00_fougeres_texte.sql
perl xls2sql.pl file="145-Ophioglossées-Plante.xls" skip=0 table="bonnier_v0_00_ophioglossees_plante" > bonnier_v0_00_ophioglossees_plante.sql
perl xls2sql.pl file="145-Ophioglossées-Texte.xls" skip=0 table="bonnier_v0_00_ophioglossees_texte" > bonnier_v0_00_ophioglossees_texte.sql
perl xls2sql.pl file="146-Marsiliacées-Plante.xls" skip=0 table="bonnier_v0_00_marsiliacees_plante" > bonnier_v0_00_marsiliacees_plante.sql
perl xls2sql.pl file="146-Marsiliacées-Texte.xls" skip=0 table="bonnier_v0_00_marsiliacees_texte" > bonnier_v0_00_marsiliacees_texte.sql
perl xls2sql.pl file="147-Equisétacées-Plante.xls" skip=0 table="bonnier_v0_00_equisetacees_plante" > bonnier_v0_00_equisetacees_plante.sql
perl xls2sql.pl file="147-Equisétacées-Texte.xls" skip=0 table="bonnier_v0_00_equisetacees_texte" > bonnier_v0_00_equisetacees_texte.sql
perl xls2sql.pl file="148-Isoétées-Plante.xls" skip=0 table="bonnier_v0_00_isoetees_plante" > bonnier_v0_00_isoetees_plante.sql
perl xls2sql.pl file="148-Isoétées-Texte.xls" skip=0 table="bonnier_v0_00_isoetees_texte" > bonnier_v0_00_isoetees_texte.sql
perl xls2sql.pl file="149-Lycopodiacées-Plante.xls" skip=0 table="bonnier_v0_00_lycopodiacees_plante" > bonnier_v0_00_lycopodiacees_plante.sql
perl xls2sql.pl file="149-Lycopodiacées-Texte.xls" skip=0 table="bonnier_v0_00_lycopodiacees_texte" > bonnier_v0_00_lycopodiacees_texte.sql
Property changes:
Added: svn:executable
+*
\ No newline at end of property
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.3-amandaie/scripts/modules/bonnier/shell/xls2sql.pl
New file
0,0 → 1,205
#!/usr/bin/perl
 
# $Date: 2005/10/19 10:14:00 $
 
# Excel to SQL statements translator.
# Needs the Spreadsheet::ParseExcel module from CPAN
#
# Example usage:
#
# xls2sql.pl help
# xls2sql.pl file=6960_TS_Bressanone_Brixen.xls \
# coldefs="year INTEGER,MEAN1 DOUBLE PRECISION,MEAN2 DOUBLE PRECISION,MEAN3 DOUBLE PRECISION"
#
# Released under GPLv2.0
# by Daniel Calvelo Aros (dca@users.sf.net)
#
# few modifications by MN (why not reading 'Learning Perl' O'Reilly book)
 
#use strict;
use English;
use Spreadsheet::ParseExcel;
# gparser-like options:
# option label => [ref to var to hold opt value, "description", default value or undef for no default]
%gopts = ( file => [\$file, "Name of input excel spreadsheet file", undef],
skip => [\$skip, "Number of rows to skip at the beginning of sheet", 0],
table => [\$tablename,"Name of output table", "mytable"],
rows => [\$nrows, "Number of rows to extract", undef],
sheet => [\$sheetn, "Sheet number to convert from the workbook, counting from 1", 1],
coldefs=> [\$coldefs, "Column definitions as in SQL", "auto"],
nodata => [\$nodata, "No data character(s) used in the Excel table", ""],
help => [\$help, "Help, of course", undef],
debug => [\$DEBUG, "Debugging flag, for developers only", 0]);
#function defined below:
&parse_opts();
 
#-- Open and look for obvious errors
my $wkbk =
Spreadsheet::ParseExcel::Workbook->Parse($file);
if( !defined $wkbk->{Worksheet}) {die "Error:couldn't parse file $file\n"}
my($iR, $iC, $sheet, $ncols, $roffset, $rsize);
$sheet = @{$wkbk->{Worksheet}}[--$sheetn]; #-- Numbering starts at 1 for the user
$ncols = $sheet->{MaxCol} or die "Error:the specified sheet $sheetn does not contain data\n";
$ncols -= $sheet->{MinCol} if defined $sheet->{MinCol} ;
$roffset = $sheet->{MinRow}-1;
$rsize = $sheet->{MaxRow} - $sheet->{MinRow};
die "Error:the specified worksheet seems to contain only one line\n" if $rsize == 0;
$roffset += $skip;
$lastrow = ( defined $nrows
? $nrows + $roffset -1
: $sheet->{MaxRow} );
die "Invalid skip option: the sheet only has $rsize rows" if $roffset >= $rsize - 1;
my (@types, @sqltypes, @firstrow, @titlerow);
 
if($coldefs ne "auto"){
#-- We have user-defined column definitions
#-- Check them
$coldefs =~ s/^\s*//;
$coldefs =~ s/\s*$//;
@defs = split ",", $coldefs;
foreach $i (0..$#defs){
($colname, $typedef) = split /\s+/,$defs[$i],2;
die "Column specification $i: can't parse SQL type definition '$typedef' (should be INTEGER, DOUBLE PRECISION, CHAR).\n" if $typedef !~ /INTEGER|DOUBLE PRECISION|CHAR/i;
die "Column name '$colname' for column $i contains spurious characters (no spaces permitted in list).\n" if $colname !~ /[a-zA-Z][a-zA-Z_0-9]*/;
push @sqltypes, $typedef;
push @titles, $colname;
}
}else{
#-- Inspect file for types:
#-- First estimate initial types from the first row of data
@firstrow = @{$sheet->{Cells}[$roffset+1]};
@types = map { $_->{Type}} @firstrow;
%cvt = (Text=>'CHAR',Numeric=>'INTEGER',Date=>'DOUBLE');
@sqltypes = map { $cvt{$_} } @types;
@lens = map { 0 } @types;
print STDERR "\nTypes:", join ";", @types if $DEBUG;
print STDERR "\nInitial sqltypes:", join ";", @sqltypes if $DEBUG;
#-- Then adjust widths and numeric type from the data
for(my $iR = $roffset ; $iR <= $lastrow ; $iR++) {
for(my $iC = $sheet->{MinCol} ;$iC <= $sheet->{MaxCol} ; $iC++) {
$cell = $sheet->{Cells}[$iR][$iC];
next if !defined $cell;
$cellvalue = $cell->Value;
if($types[$iC] eq 'Text'){
$thislength = length( $cellvalue );
$lens[$iC] = $thislength if $thislength > $lens[$iC];
}else{
if( $cellvalue =~ /[\.,]/ ){
$sqltypes[$iC] = 'DOUBLE PRECISION';
}
if( $cellvalue =~ /[a-df-z]/ ){
$sqltypes[$iC] = 'CHAR'; $lens[$iC] = length( $cellvalue);
}
}
}
}
foreach $i (0..$#sqltypes){
if( $sqltypes[$i] eq 'CHAR' ){
$sqltypes[$i] .= "($lens[$i])";
}
}
print STDERR "\nAdjusted sqltypes:", join ";", @sqltypes if $DEBUG;
 
#-- Generate field names from the title row
@titlerow = @{$sheet->{Cells}[$roffset]};
print STDERR "\nTitlerow:", join ";", map { defined $_ ? $_->Value : "" } @titlerow if $DEBUG;
$varname = "V000";
@titles = map {
/^[^a-zA-Z]/ ? $varname++ : $_
} map {
if( defined $_ && length > 0 ) {$_=$_->Value;y/a-z/A-Z/;s/[^a-zA-Z_0-9]/_/g}
else { $_=$varname++ }
$_;
} @titlerow;
map { $istitle{$_}++ } @titles;
foreach $i (reverse 0..$#titles){
if( $istitle{$titles[$i]} > 1){
$titles[$i] .= --$istitle{$titles[$i]};
}
}
while( $#titles < $ncols ){ #Missing titles, according to the size of the sheet
push @titles, $varname++;
push @sqltypes, "CHAR(32)";
}
print STDERR "\nTitles:" ,join ";", @titles if $DEBUG;
print STDERR "\n" if $DEBUG;
}
 
#-- Write out
print "CREATE TABLE $tablename (";
print join ",", map {"$titles[$_] $sqltypes[$_]"} (0..$#titles);
print ");\n";
if($coldefs eq "auto"){
$lastcol = $sheet->{MaxCol};
}else{
$lastcol = $#sqltypes + $sheet->{MinCol};
foreach $i (reverse 0..$#sqltypes){
$sqltypes[$i + $sheet->{MinCol}] = $sqltypes[$i];
}
}
for(my $iR = $roffset+1 ; $iR <= $lastrow ; $iR++) {
print "INSERT INTO $tablename VALUES(";
print join ",", map {
my $c = $sheet->{Cells}[$iR][$_];
# defined $c ? '"'.&cast($c->Value,$sqltypes[$_]).'"' : NULL
defined $c ? ''.&cast($c->Value,$sqltypes[$_]).'' : NULL
} ($sheet->{MinCol}..$lastcol);
print ");\n"
}
 
sub cast($$){
my ($value, $sqltype) = @_;
if( length($value)>0 ){
if ($value eq $nodata){
$value = "NULL"; # no data coded with char
}else{
if( $sqltype =~ /CHAR\s*\((\d+)\)/i ){
$value =~ s/[\n\r]/ /gm;
$value =~ s/"/\\"/g;
$value =~ s/'/\\'/g;
# $value = substr( $value, 0, $1 );
$value = '\''.substr( $value, 0, $1 ).'\'';
}elsif( $sqltype =~ /DOUBLE PRECISION/i ){
$value += 0;
}elsif( $sqltype =~ /INTEGER/i ){
$value = int $value;
}else{
die "Unknown SQL type '$sqltype'; can't typecast '$value' to that type.\n";
}
}
}else{
$value = "NULL"; # no data
}
}
 
sub parse_opts(){
for $o (sort keys %gopts){
if( defined $gopts{$o}[2] ){
${$gopts{$o}[0]} = $gopts{$o}[2];
}
for $arg (@ARGV){
$arg =~ /^\Q$o\E(?:\s*=\s*(.+)$)?/;
if( length($1)>0 ){
${$gopts{$o}[0]} = $1;
}elsif( $& ){
${$gopts{$o}[0]} = 1;
}
}
}
if($help){
select STDERR;
print "\n$PROGRAM_NAME : extract sheets from an excel workbook and\n";
print "produce SQL statements that create the database\n";
print "\nArguments (use grass style, i.e. arg=value):\n";
foreach (keys %gopts){ $longest = $longest < length() ? length() : $longest }
foreach $arg (grep {!/help/} keys %gopts){
print " $arg".(" "x($longest+2-length $arg));
print $gopts{$arg}[1];
print " (default: ".$gopts{$arg}[2].")" if defined $gopts{$arg}[2];
print "\n";
}
select STDOUT;
die "\n";
}
}
 
/tags/v5.3-amandaie/scripts/modules/bonnier/shell/charger_sql.sh
New file
0,0 → 1,149
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/001-Renonculacees" -table renonculacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/002-Berberidees" -table berberidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/003-Nympheacees" -table nympheacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/004-Papaveracees" -table papaveracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/005-Fumariacees" -table fumariacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/006-Cruciferes" -table cruciferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/007-Capparidees" -table capparidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/008-Cistinees" -table cistinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/009-Violariees" -table violariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/010-Resedacees" -table resedacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/011-Droseracees" -table droseracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/012-Polygalees" -table polygalees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/013-Frankeniacees" -table frankeniacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/014-Caryophyllees" -table caryophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/015-Elatinees" -table elatinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/016-Linees" -table linees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/017-Tiliacees" -table tiliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/018-Malvacees" -table malvacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/019-Geraniees" -table geraniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/020-Hypericinees" -table hypericinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/021-Acerinees" -table acerinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/022-Ampelidees" -table ampelidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/023-Hippocastanees" -table hippocastanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/024-Meliacees" -table meliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/025-Balsaminees" -table balsaminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/026-tablexalidees" -table oxalidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/027-Zygophyllees" -table zygophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/028-Hesperidees" -table hesperidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/029-Rutacees" -table rutacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/030-Coriariees" -table coriariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/031-Celastrinees" -table celastrinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/032-Staphyleacees" -table staphyleacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/033-Ilicinees" -table ilicinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/034-Rhamnees" -table rhamnees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/035-Terebinthacees" -table terebinthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/036-Papilionacees" -table papilionacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/037-Cesalpiniees" -table cesalpiniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/038-Rosacees" -table rosacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/039-Granatees" -table granatees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/040-tablenagrariees" -table onagrariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/041-Myriophyllees" -table myriophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/042-Hippuridees" -table hippuridees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/043-Callitrichinees" -table callitrichinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/044-Ceratophyllees" -table ceratophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/045-Lythrariees" -table lythrariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/046-Philadelphees" -table philadelphees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/047-Tamariscinees" -table tamariscinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/048-Myrtacees" -table myrtacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/049-Cucurbitacees" -table cucurbitacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/050-Portulacees" -table portulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/051-Paronychiees" -table paronychiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/052-Crassulacees" -table crassulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/053-Cactees" -table cactees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/054-Ficoïdees" -table ficoïdees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/055-Grossulariees" -table grossulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/056-Saxifragees" -table saxifragees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/057-tablembelliferes" -table ombelliferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/058-Araliacees" -table araliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/059-Cornees" -table cornees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/060-Loranthacees" -table loranthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/061-Caprifoliacees" -table caprifoliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/062-Rubiacees" -table rubiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/063-Valerianees" -table valerianees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/064-Dipsacees" -table dipsacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/065-Composees" -table composees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/066-Ambrosiacees" -table ambrosiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/067-Lobeliacees" -table lobeliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/068-Campanulacees" -table campanulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/069-Vacciniees" -table vacciniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/070-Ericinees" -table ericinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/071-Pyrolacees" -table pyrolacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/072-Monotropees" -table monotropees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/073-Lentibulariees" -table lentibulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/074-Primulacees" -table primulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/075-Ebenacees" -table ebenacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/076-Styracees" -table styracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/077-tableleinees" -table oleinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/078-Jasminees" -table jasminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/079-Apocynees" -table apocynees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/080-Asclepiadees" -table asclepiadees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/081-Gentianees" -table gentianees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/082-Polemoniacees" -table polemoniacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/083-Convolvulacees" -table convolvulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/084-Cuscutacees" -table cuscutacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/085-Ramondiacees" -table ramondiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/086-Borraginees" -table borraginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/087-Solanees" -table solanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/088-Verbascees" -table verbascees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/089-Scrofularinees" -table scrofularinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/090-tablerobanchees" -table orobanchees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/091-Labiees" -table labiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/092-Acanthacees" -table acanthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/093-Verbenacees" -table verbenacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/094-Plantaginees" -table plantaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/095-Plombaginees" -table plombaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/096-Globulariees" -table globulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/097-Phytolaccees" -table phytolaccees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/098-Amarantacees" -table amarantacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/099-Salsolacees" -table salsolacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/100-Polygonees" -table polygonees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/101-Daphnoidees" -table daphnoidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/102-Laurinees" -table laurinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/103-Santalacees" -table santalacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/104-Eleagnees" -table eleagnees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/105-Cytinees" -table cytinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/106-Aristolochiees" -table aristolochiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/107-Empetrees" -table empetrees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/108-Euphorbiacees" -table euphorbiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/109-Morees" -table morees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/110-Ficacees" -table ficacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/111-Celtidees" -table celtidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/112-Ulmacees" -table ulmacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/113-Urticees" -table urticees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/114-Cannabinees" -table cannabinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/115-Juglandees" -table juglandees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/116-Cupuliferes" -table cupuliferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/117-Salicinees" -table salicinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/118-Platanees" -table platanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/119-Betulinees" -table betulinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/120-Myricees" -table myricees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/121-Alismacees" -table alismacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/122-Butomees" -table butomees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/123-Colchicacees" -table colchicacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/124-Liliacees" -table liliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/125-Dioscorees" -table dioscorees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/126-Iridees" -table iridees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/127-Amaryllidees" -table amaryllidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/128-tablerchidees" -table orchidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/129-Hydrocharidees" -table hydrocharidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/130-Joncaginees" -table joncaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/131-Potamees" -table potamees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/132-Naiadees" -table naiadees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/133-Zosteracees" -table zosteracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/134-Lemnacees" -table lemnacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/135-Aroidees" -table aroidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/136-Typhacees" -table typhacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/137-Joncees" -table joncees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/138-Cyperacees" -table cyperacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/139-Graminees" -table graminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/140-Abietinees" -table abietinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/141-Cupressinees" -table cupressinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/142-Taxinees" -table taxinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/143-Gnetacees" -table gnetacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/144-Fougeres" -table fougeres
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/145-tablephioglossees" -table ophioglossees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/146-Marsiliacees" -table marsiliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/147-Equisetacees" -table equisetacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/148-Isoetees" -table isoetees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/149-Lycopodiacees" -table lycopodiacees
Property changes:
Added: svn:executable
+*
\ No newline at end of property
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.3-amandaie/scripts/modules/bonnier/shell/generer_html.sh
New file
0,0 → 1,149
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/001-Renonculacees" -table renonculacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/002-Berberidees" -table berberidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/003-Nympheacees" -table nympheacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/004-Papaveracees" -table papaveracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/005-Fumariacees" -table fumariacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/006-Cruciferes" -table cruciferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/007-Capparidees" -table capparidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/008-Cistinees" -table cistinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/009-Violariees" -table violariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/010-Resedacees" -table resedacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/011-Droseracees" -table droseracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/012-Polygalees" -table polygalees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/013-Frankeniacees" -table frankeniacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/014-Caryophyllees" -table caryophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/015-Elatinees" -table elatinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/016-Linees" -table linees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/017-Tiliacees" -table tiliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/018-Malvacees" -table malvacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/019-Geraniees" -table geraniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/020-Hypericinees" -table hypericinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/021-Acerinees" -table acerinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/022-Ampelidees" -table ampelidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/023-Hippocastanees" -table hippocastanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/024-Meliacees" -table meliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/025-Balsaminees" -table balsaminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/026-tablexalidees" -table oxalidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/027-Zygophyllees" -table zygophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/028-Hesperidees" -table hesperidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/029-Rutacees" -table rutacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/030-Coriariees" -table coriariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/031-Celastrinees" -table celastrinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/032-Staphyleacees" -table staphyleacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/033-dossierlicinees" -table ilicinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/034-Rhamnees" -table rhamnees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/035-Terebinthacees" -table terebinthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/036-Papilionacees" -table papilionacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/037-Cesalpiniees" -table cesalpiniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/038-Rosacees" -table rosacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/039-Granatees" -table granatees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/040-tablenagrariees" -table onagrariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/041-Myriophyllees" -table myriophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/042-Hippuridees" -table hippuridees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/043-Callitrichinees" -table callitrichinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/044-Ceratophyllees" -table ceratophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/045-Lythrariees" -table lythrariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/046-Philadelphees" -table philadelphees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/047-Tamariscinees" -table tamariscinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/048-Myrtacees" -table myrtacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/049-Cucurbitacees" -table cucurbitacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/050-Portulacees" -table portulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/051-Paronychiees" -table paronychiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/052-Crassulacees" -table crassulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/053-Cactees" -table cactees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/054-Ficoïdees" -table ficoïdees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/055-Grossulariees" -table grossulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/056-Saxifragees" -table saxifragees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/057-tablembelliferes" -table ombelliferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/058-Araliacees" -table araliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/059-Cornees" -table cornees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/060-Loranthacees" -table loranthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/061-Caprifoliacees" -table caprifoliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/062-Rubiacees" -table rubiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/063-Valerianees" -table valerianees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/064-Dipsacees" -table dipsacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/065-Composees" -table composees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/066-Ambrosiacees" -table ambrosiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/067-Lobeliacees" -table lobeliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/068-Campanulacees" -table campanulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/069-Vacciniees" -table vacciniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/070-Ericinees" -table ericinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/071-Pyrolacees" -table pyrolacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/072-Monotropees" -table monotropees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/073-Lentibulariees" -table lentibulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/074-Primulacees" -table primulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/075-Ebenacees" -table ebenacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/076-Styracees" -table styracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/077-tableleinees" -table oleinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/078-Jasminees" -table jasminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/079-Apocynees" -table apocynees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/080-Asclepiadees" -table asclepiadees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/081-Gentianees" -table gentianees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/082-Polemoniacees" -table polemoniacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/083-Convolvulacees" -table convolvulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/084-Cuscutacees" -table cuscutacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/085-Ramondiacees" -table ramondiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/086-Borraginees" -table borraginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/087-Solanees" -table solanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/088-Verbascees" -table verbascees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/089-Scrofularinees" -table scrofularinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/090-tablerobanchees" -table orobanchees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/091-Labiees" -table labiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/092-Acanthacees" -table acanthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/093-Verbenacees" -table verbenacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/094-Plantaginees" -table plantaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/095-Plombaginees" -table plombaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/096-Globulariees" -table globulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/097-Phytolaccees" -table phytolaccees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/098-Amarantacees" -table amarantacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/099-Salsolacees" -table salsolacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/100-Polygonees" -table polygonees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/101-Daphnoidees" -table daphnoidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/102-Laurinees" -table laurinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/103-Santalacees" -table santalacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/104-Eleagnees" -table eleagnees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/105-Cytinees" -table cytinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/106-Aristolochiees" -table aristolochiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/107-Empetrees" -table empetrees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/108-Euphorbiacees" -table euphorbiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/109-Morees" -table morees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/110-Ficacees" -table ficacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/111-Celtidees" -table celtidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/112-Ulmacees" -table ulmacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/113-Urticees" -table urticees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/114-Cannabinees" -table cannabinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/115-Juglandees" -table juglandees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/116-Cupuliferes" -table cupuliferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/117-Salicinees" -table salicinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/118-Platanees" -table platanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/119-Betulinees" -table betulinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/120-Myricees" -table myricees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/121-Alismacees" -table alismacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/122-Butomees" -table butomees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/123-Colchicacees" -table colchicacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/124-Liliacees" -table liliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/125-Dioscorees" -table dioscorees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/126-dossierridees" -table iridees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/127-Amaryllidees" -table amaryllidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/128-tablerchidees" -table orchidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/129-Hydrocharidees" -table hydrocharidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/130-Joncaginees" -table joncaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/131-Potamees" -table potamees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/132-Naiadees" -table naiadees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/133-Zosteracees" -table zosteracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/134-Lemnacees" -table lemnacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/135-Aroidees" -table aroidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/136-Typhacees" -table typhacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/137-Joncees" -table joncees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/138-Cyperacees" -table cyperacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/139-Graminees" -table graminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/140-Abietinees" -table abietinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/141-Cupressinees" -table cupressinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/142-Taxinees" -table taxinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/143-Gnetacees" -table gnetacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/144-Fougeres" -table fougeres
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/145-tablephioglossees" -table ophioglossees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/146-Marsiliacees" -table marsiliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/147-Equisetacees" -table equisetacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/148-dossiersoetees" -table isoetees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/149-Lycopodiacees" -table lycopodiacees
Property changes:
Added: svn:executable
+*
\ No newline at end of property
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.3-amandaie/scripts/modules/bonnier/bonnier.ini
New file
0,0 → 1,20
; Encodage : UTF-8
; Exemple de fichier de configuration d'un projet
; Les commentaires commencent par ';', comme dans php.ini
 
; Indique le nom du projet
projet_nom = bonnier
; Indique le nombre sur un chiffre de la version du projet
version = 0
; Indique le nombre sur deux chiffres de la sous version du projet
sous_version = 00
; Indique la date de début de cette version du projet
date_debut = "2009-12-11 00:00:00"
; Indique la date de fin de cette version du projet
date_fin = NULL
; Indique le chemin où les fichier html vont être générés
chemin_fichier_sortie = "php:'/home/'.'david'.'/Bureau/bonnierhtml/'"
; Indique le chemin où trouver le fichier du projet contenant les données à charger puis standardiser
chemin_fichier_tab = "php:'/home/'.'david'.'/Bureau/bonnierhtml/'"
; Indique le chemin où stocker le fichier de log
log_chemin = "php:'/home/'.'david'.'/Bureau/bonnierhtml/'"
/tags/v5.3-amandaie/scripts/modules/osm/carto-osm-maj.sh
New file
0,0 → 1,79
#!/bin/bash
# Mohcen BENMOUNAH & Jean-Pascal MILCENT [19 juillet 2011]
# Script de lancement de l'integration des donnees OSM pour le geocodage inverse
#
# Serveur
#CHEMIN_JAVA="/usr/local/jdk/bin/java"
#CHEMIN_PHP="/usr/local/bin/php"
#CHEMIN_SCRIPT="/home/telabotap/www/eflore/scripts/carto-osm/actuel"
#CHEMIN_OSMOSIS="/usr/local/sbin/osmosis-0.39/bin/osmosis"
#CHEMIN_FICHIER_OSM="/home/telabotap/www/eflore/donnees/osm"
# Local
CHEMIN_JAVA="/usr/bin/java"
CHEMIN_SCRIPT="/home/jpm/web/eflore/eflore-projets/scripts"
CHEMIN_OSMOSIS="/home/jpm/Applications/osmosis-0.39/bin/osmosis"
CHEMIN_FICHIER_OSM="/home/jpm/Documents/osm"
CHEMIN_PHP="/opt/lampp/bin/php"
 
CHEMIN_LOG="$CHEMIN_SCRIPT/logs"
MEMORY_LIMIT_PHP="4000M"
 
echo "Telechargement du nouveau fichier OSM ...";
wget -r http://download.geofabrik.de/osm/europe/france.osm.bz2 -O "$CHEMIN_FICHIER_OSM/france.osm.bz2"
 
echo "Export de l'emplacement du binaire Java dans la variable d'environnement JAVACMD";
export JAVACMD="$CHEMIN_JAVA"
 
echo "Filtrage du fichier en cours ...";
$CHEMIN_OSMOSIS \
--fast-read-xml "$CHEMIN_FICHIER_OSM/france.osm.bz2" \
--tf accept-relations admin_level=8 \
--tf accept-relations type=boundary \
--tf accept-relations ref:INSEE=* \
--used-way \
--used-node \
--wx $CHEMIN_FICHIER_OSM/france_communes_new.osm
 
if [ ! -f "$CHEMIN_FICHIER_OSM/france_communes_old.osm" ] ; then
echo "Analyse du fichier osm en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/parseur_osm -a analyser -m manuel -f "$CHEMIN_FICHIER_OSM/france_communes_new.osm" > $CHEMIN_LOG/analyse.log
else
echo "Suppression du fichier DIFF existant en cours ...";
rm -f "$CHEMIN_FICHIER_OSM/france_communes_diff.osm"
echo "Déduction de la différence en cours ...";
$CHEMIN_OSMOSIS\
--read-xml file="$CHEMIN_FICHIER_OSM/france_communes_new.osm" \
--read-xml file="$CHEMIN_FICHIER_OSM/france_communes_old.osm" \
--derive-change \
--write-xml-change file="$CHEMIN_FICHIER_OSM/france_communes_diff.osm"
echo "Debut de la mise a jour de base ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/mise_a_jour -a MAJ -f "$CHEMIN_FICHIER_OSM/france_communes_diff.osm" > $CHEMIN_LOG/analyse.log
fi
 
echo "Renommage du fichier NEW en OLD en cours ...";
mv "$CHEMIN_FICHIER_OSM/france_communes_new.osm" "$CHEMIN_FICHIER_OSM/france_communes_old.osm"
 
echo Traitement de l\'ordre en cours ...;
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/parseur_osm -a ordre
 
echo "Remplissage des polygones en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/parseur_osm -a polygone
 
echo Remise de l\'ordre a zero en cours ...;
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/parseur_osm -a zero
 
echo Traitement de l\'ordre des polygones incomplets en cours ...;
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/parseur_osm -a ordonnerPolygoneInc
 
echo "Remplissage des polygones incomplets en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/parseur_osm -a remplirPolygoneInc
 
echo "Renommage des polygones incomplets en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/parseur_osm -a renommer
 
echo "Definition des centroids en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm/parseur_osm -a centre
 
echo "FIN DE LA MISE A JOUR !";
Property changes:
Added: svn:executable
+*
\ No newline at end of property
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.3-amandaie/scripts/modules/osm/carto-osm-cron
New file
0,0 → 1,22
#!/bin/bash
#
# Mohcen BENMOUNAH & Jean-Pascal MILCENT [19 juillet 2011]
# /etc/init.d/carto-osm : demarage/arrete/etat du cron de l'integration des donnees OSM pour le Geocodage Inverse (carto-osm)
# Lancement toutes les semaines le samedi matin après 3h00
 
while true
do
JOUR=$(date "+%u")
HEURE=$(date "+%H")
# Si nous sommes samedi (=6) et après 3 heures du matin
if [ $JOUR -eq 6 ] && [ $HEURE -gt 3 ] ; then
logger "Lancement script carto-osm-maj.sh"
sudo -u telabotap /usr/local/sbin/carto-osm-maj.sh
logger "Arret script carto-osm-maj.sh"
# Nous retenterons de vérifier jour et heure dans 6 jours
sleep 6d
else
# Tentative toutes les 2h de vérification du jour et de l'heure
sleep 2h
fi
done
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.3-amandaie/scripts/modules/osm/MiseAJour.php
New file
0,0 → 1,397
<?php
/**
* Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M cli.php osm/mise_a_jour -a MAJ -f fichier_osm_a_analyser
*/
class MiseAjour extends Script {
private $communes = array();
private $relations_communes = array();
private $relation_a_chemins = array();
private $chemin_a_noeuds = array();
private $noeuds = array();
private $pas = 10000;
private $pas_commune = 1000;
 
protected $parametres_autorises = array(
'-f' => array(true, null, 'Chemin du fichier osm à analyser'));
 
public function executer() {
$this->bdd = new Bdd();
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'MAJ' :
$this->MettreAjour();
break;
default :
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
}
}
 
 
/**
* Fonction permettant de traiter et d'analyser le fichier de différence et de mettre à jour la base de données
* en tenant compte des trois cas:Suppression, Création ,modification
*/
private function MettreAjour() {
$lecteur = new XMLReader();
if ($lecteur->open($this->getParametre('f'))) {
$dom = new DomDocument();
while ($lecteur->read()) {
if ($lecteur->nodeType == XMLREADER::ELEMENT) {
if ($lecteur->localName == 'create') {
$creations = $lecteur->expand();
$this-> analyserCreations($creations);
}
if ($lecteur->localName == 'modify') {
$modifications = $lecteur->expand();
$this-> analyserModifications($modifications);
}
if ($lecteur->localName == 'delete') {
$suppressions = $lecteur->expand();
$this-> analyserSuppressions($suppressions);
}
}
}
} else {
$e = "Impossible d'ouvrir le fichier osm : %s";
$this->traiterErreur($e, array($this->getParametre('f')));
}
}
 
/**
* Fonction permettant le traitement du cas création concernant les relations, ways et les noeuds.
*/
private function analyserCreations($creations) {
$relations = $creations->getElementsByTagName('relation');
foreach ($relations as $relation) {
$this-> analyserRelation($relation);
if (count($this->relation_a_chemins) > $this->pas) {
$this->insererRelationAChemins();
}
if (count($this->relations_communes) > $this->pas_commune) {
$this->insererRelationsCommunes();
}
}
$ways = $creations->getElementsByTagName('way');
foreach ($ways as $way) {
$this->analyserWay($way);
if (count($this->chemin_a_noeuds) > $this->pas) {
$this->insererCheminANoeuds();
}
}
$noeuds = $creations->getElementsByTagName('node');
foreach ($noeuds as $noeud) {
$this->analyserNode($noeud);
if (count($this->noeuds) > $this->pas) {
$this->insererNoeuds();
}
}
$this->insererRelationsCommunes();
$this->insererRelationAChemins();
$this->insererCheminANoeuds();
$this->insererNoeuds();
}
 
/**
* Fonction permettant le traitement du cas modification concernant les relations, ways et les noeuds.
*/
private function analyserModifications($modifications) {
$relations = $modifications->getElementsByTagName('relation');
foreach ($relations as $relation) {
$this-> analyserRelation($relation);
if (count($this->relation_a_chemins) > $this->pas) {
$this->modifierRelationAChemins();
}
if (count($this->relations_communes) > $this->pas_commune) {
$this->modifierRelationsCommunes();
}
}
$ways = $modifications->getElementsByTagName('way');
foreach ($ways as $way) {
$this->analyserWay($way);
if (count($this->chemin_a_noeuds) > $this->pas) {
$this->modifierCheminANoeuds();
}
}
$noeuds = $modifications->getElementsByTagName('node');
foreach ($noeuds as $noeud) {
$this->analyserNode($noeud);
if (count($this->noeuds) > $this->pas) {
$this->modifierNoeuds();
}
}
$this->modifierRelationsCommunes();
$this->modifierRelationAChemins();
$this->modifierCheminANoeuds();
$this->modifierNoeuds();
}
 
/**
* Fonction permettant le traitement du cas suppression concernant les relations, ways et les noeuds.
*/
private function analyserSuppressions($suppressions) {
$relations = $suppressions->getElementsByTagName('relation');
foreach ($relations as $relation) {
$this-> analyserRelation($relation);
if (count($this->relation_a_chemins) > $this->pas) {
$this->supprimerRelationAChemins();
}
if (count($this->relations_communes) > $this->pas_commune) {
$this->supprimerRelationsCommunes();
}
}
$ways = $suppressions->getElementsByTagName('way');
foreach ($ways as $way) {
$this->analyserWay($way);
if (count($this->chemin_a_noeuds) > $this->pas) {
$this->supprimerCheminANoeuds();
}
}
$noeuds = $suppressions->getElementsByTagName('node');
foreach ($noeuds as $noeud) {
$this->analyserNode($noeud);
if (count($this->noeuds) > $this->pas) {
$this->supprimerNoeuds();
}
}
$this->supprimerRelationsCommunes();
$this->supprimerRelationAChemins();
$this->supprimerCheminANoeuds();
$this->supprimerNoeuds();
}
 
 
/**
* Récupère l'id commune, nom commune et le code INSEE et remplie la table `osm_relations`
*/
private function analyserRelation($relation) {
$relation_id = $this->proteger($relation->getAttribute('id'));
$chemins = $relation->getElementsByTagName('member');
foreach ($chemins as $chemin) {
if ($chemin->getAttribute('type') == 'way') { //écarter le noeud centrale
$chemin_id = $this->proteger($chemin->getAttribute('ref'));
$role = $this->proteger($chemin->getAttribute('role'));//role: null, inner, outer, exclave et enclave.
$this->relation_a_chemins[] = array($relation_id, $chemin_id, $role);
}
}
$commune_nom = null;
$commune_insee = null;
$tags = $relation->getElementsByTagName('tag');
foreach ($tags as $tag) {
$tag_cle = $tag->getAttribute('k');
$tag_val = $tag->getAttribute('v');
switch ($tag_cle) {
case 'name' :
$commune_nom = $this->proteger($tag_val);
break;
case 'ref:INSEE' :
$commune_insee = $this->proteger($tag_val);
break;
}
if (!is_null($commune_nom) && !is_null($commune_insee)) {
$this->relations_communes[] = array($relation_id, $commune_nom, $commune_insee);
if (!isset($this->communes[$commune_insee])) {
$this->communes[$commune_insee] = $relation_id;
} else {
$e = "La relation #%s contient déjà le tag ref:INSEE avec la valeur %s.".
"Veuillez corriger la carte OSM.";
$this->traiterErreur($e, array($this->communes[$commune_insee], $commune_insee, $relation_id));
}
break;
}
}
}
 
/**
* Récupère l'id_way et tous les id_node de chaque way et remplie la table `osm_chemin_a_noeuds`
*/
private function analyserWay($way) {
$chemin_id = $this->proteger($way->getAttribute('id'));
$ordre = 0;
$noeuds = $way->getElementsByTagName('nd');
$chemin_a_noeuds = array();
foreach ($noeuds as $noeud) {
$noeud_id = $this->proteger($noeud->getAttribute('ref'));
$ordre++;
$this->chemin_a_noeuds[] = array($chemin_id, $noeud_id, $ordre);
}
}
 
/**
* Fonction qui récupère tous les l'id_node et les valeurs(Lat/Lon) correspondantes et remplie la table `osm_noeuds`
*/
private function analyserNode($node) {
$noeud_id = $this->proteger($node->getAttribute('id'));
$lat = $this->proteger($node->getAttribute('lat'));
$lon = $this->proteger($node->getAttribute('lon'));
$this->noeuds[] = array($noeud_id, $lat, $lon);
}
 
//Insertion des relations
private function insererRelationsCommunes() {
$requete = 'INSERT INTO osm_relations (id_relation, nom, code_insee) '.
'VALUES '.$this->creerValuesMultiple($this->relations_communes);
$this->inserer($requete);
$this->relations_communes = array();
}
 
//Insertion des relations à chemins
private function insererRelationAChemins() {
$requete = 'INSERT INTO osm_relation_a_chemins (id_relation, id_chemin, role) '.
'VALUES '.$this->creerValuesMultiple($this->relation_a_chemins);
$this->inserer($requete);
$this->relation_a_chemins = array();
}
 
//Insertion des chemins à noeuds
private function insererCheminANoeuds() {
$requete = 'INSERT INTO osm_chemin_a_noeuds (id_chemin, id_noeud, ordre) '.
'VALUES '.$this->creerValuesMultiple($this->chemin_a_noeuds);
$this->inserer($requete);
$this->chemin_a_noeuds = array();
}
 
//Insertion des noeuds
private function insererNoeuds() {
$requete = 'INSERT INTO osm_noeuds (id_noeud, lat, `long`) '.
'VALUES '.$this->creerValuesMultiple($this->noeuds);
$this->inserer($requete);
$this->noeuds = array();
}
 
//Update des relations
private function modifierRelationsCommunes() {
$donnees = $this->relations_communes;
foreach ($donnees as $donnee) {
$requete = 'UPDATE osm_relations '.
"SET id_relation = $donnee[0], nom = $donnee[1], code_insee = $donnee[2] ".
"WHERE id_relation = $donnee[0]";
$this->inserer($requete);
}
$this->relations_communes = array();
}
 
/*
*Update des relations à chemins en supprimant l'ancienne relation et tous ses chemins
*de la table osm_relation_a_chemins et insérer la nouvelle
*/
private function modifierRelationAChemins() {
$relations_a_chemins_a_supp = array();
$donnees = $this->relation_a_chemins;
foreach ($donnees as $donnee) {
$relations_a_chemins_a_supp[] = $donnee[0];
}
$values_chaine = '('.implode(',',array_unique($relations_a_chemins_a_supp)).')';
$requete = 'DELETE FROM osm_relation_a_chemins '.
"WHERE id_relation IN $values_chaine";
$this->inserer($requete);
foreach ($donnees as $donnee) {
$requete = 'INSERT INTO osm_relation_a_chemins (id_relation, id_chemin, role) '.
"VALUES ($donnee[0], $donnee[1], $donnee[2]);";
$this->inserer($requete);
}
$this->relation_a_chemins = array();
}
 
/*
*Update des chemins à noeuds en supprimant l'ancien chemin et tous ses noeuds
*de la table osm_chemins_a_noeuds et insérer le nouveau
*/
private function modifierCheminANoeuds() {
$chemin_a_noeuds_a_supp = array();
$donnees = $this->chemin_a_noeuds;
foreach ($donnees as $donnee) {
$chemin_a_noeuds_a_supp[] = $donnee[0];
}
$values_chaine = '('.implode(',',array_unique($chemin_a_noeuds_a_supp)).')';
$requete = 'DELETE FROM osm_chemin_a_noeuds '.
"WHERE id_chemin IN $values_chaine";
$this->inserer($requete);
foreach ($donnees as $donnee) {
$requete = 'INSERT INTO osm_chemin_a_noeuds (id_chemin, id_noeud, ordre) '.
"VALUES ($donnee[0], $donnee[1], $donnee[2]);";
$this->inserer($requete);
}
$this->chemin_a_noeuds = array();
}
 
 
//Update des noeuds
private function modifierNoeuds() {
$donnees = $this->noeuds;
foreach ($donnees as $donnee) {
$requete = 'UPDATE osm_noeuds '.
"SET id_noeud = $donnee[0], lat = $donnee[1], `long` = $donnee[2] ".
"WHERE id_noeud = $donnee[0]";
$this->inserer($requete);
}
$this->noeuds = array();
}
 
 
//Suppressions des relations
private function supprimerRelationsCommunes() {
$donnees = $this->relations_communes;
foreach ($donnees as $donnee) {
$requete = 'DELETE FROM osm_relations '.
"WHERE id_relation = $donnee[0]";
$this->inserer($requete);
}
$this->relations_communes = array();
}
 
//Suppressions des relations à chemins
private function supprimerRelationAChemins() {
$donnees = $this->relations_communes;
foreach ($donnees as $donnee) {
$donnees = $this->relation_a_chemins;
$requete = 'DELETE FROM osm_relation_a_chemins '.
"WHERE id_relation = $donnee[0]";
$this->inserer($requete);
}
$this->relation_a_chemins = array();
}
 
//Suppressions des chemins à noeuds
private function supprimerCheminANoeuds() {
$donnees = $this->chemin_a_noeuds;
foreach ($donnees as $donnee) {
$donnees = $this->relation_a_chemins;
$requete = 'DELETE FROM osm_chemin_a_noeuds '.
"WHERE id_chemin = $donnee[0]";
$this->inserer($requete);
}
$this->chemin_a_noeuds = array();
}
 
//Suppressions des chemins à noeuds
private function supprimerNoeuds() {
$donnees = $this->noeuds;
foreach ($donnees as $donnee) {
$requete = 'DELETE FROM osm_noeuds '.
"WHERE id_noeud = $donnee[0]";
$this->inserer($requete);
}
$this->noeuds = array();
}
 
private function inserer($requete) {
$this->bdd->requeter($requete);
}
 
private function proteger($chaine) {
return $this->bdd->proteger($chaine);
}
 
private function creerValuesMultiple($donnees) {
$values = array();
foreach ($donnees as $donnee) {
$values[] = implode(',', $donnee);
}
$values_chaine = '('.implode('),(', $values).')';
return $values_chaine;
}
}
?>
/tags/v5.3-amandaie/scripts/modules/osm/carto-osm
New file
0,0 → 1,41
#!/bin/sh
#/etc/rc.d/init.d/
#
# Jean-Pascal MILCENT & Mohcen BENMOUNAH [19 juillet 2011]
# Service de lancement des scripts d'integration des donnees OSM pour le service de Geocadage Inverse
#
case "$1" in
 
start)
 
echo "Demarrage de carto-osm-cron :"
nohup /usr/local/sbin/carto-osm-cron 1>/dev/null 2>/dev/null &
 
;;
 
stop)
 
echo "Arret de carto-osm-cron"
PID=`ps -eaf | grep carto-osm-cron | grep -v grep | tr -s ' ' | cut -d' ' -f2 | head -n1`
kill -9 ${PID}
 
;;
 
status)
 
echo -n "Voici les PID du processus carto-osm-cron :"
PID=`ps -eaf | grep carto-osm-cron | grep -v grep | tr -s ' ' | cut -d' ' -f2 | head -n1`
echo ${PID}
 
;;
 
 
*)
 
echo "Usage: {start|stop|status}"
 
exit 1
 
;;
 
esac
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.3-amandaie/scripts/modules/osm/ParseurOsm.php
New file
0,0 → 1,667
<?php
/**
* Exemple de lancement du script :
* /opt/lampp/bin/php cli.php osm/parseur_osm -a compter -f "/home/jpm/Stockage/osm/languedoc-roussillon-communes.osm"
*
*/
class ParseurOsm extends Script {
 
private $communes = array();
private $relations_communes = array();
private $relation_a_chemins = array();
private $chemin_a_noeuds = array();
private $noeuds = array();
private $pas = 10000;
private $pas_commune = 1000;
 
protected $parametres_autorises = array(
'-f' => array(true, null, 'Chemin du fichier osm à analyser'),
'-m' => array(false, 'auto', 'Mode «auto» ou «manuel». En manuel, les compteurs dans les boucles sont affichés.'));
 
public function executer() {
$this->bdd = new Bdd();
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'analyser' :
$this->lireFichierOsm();
break;
case 'ordre' :
$this->ordonnerWays();
break;
case 'polygone' :
$this->remplirPolygone();
break;
case 'zero' :
$this->remettreOrdreAZero();
break;
case 'ordonnerPolygoneInc' :
$this->relationsPolygoneIncomplet(1, 0);
break;
case 'remplirPolygoneInc' :
$this->remplirCommunesPolygoneIncomplet();
break;
case 'renommer' :
$this->renommerEnPolygoneIncomplet();
break;
case 'centre' :
$this->centroid();
break;
default :
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
}
}
 
 
/**
* Lit le fichier OSM et lance l'analyse des noeuds xml en fonction de leur type.
*/
private function lireFichierOsm() {
$lecteur = new XMLReader();
if ($lecteur->open($this->getParametre('f'))) {
$dom = new DomDocument();
while ($lecteur->read()) {
if ($lecteur->nodeType == XMLREADER::ELEMENT) {
if ($lecteur->localName == 'relation') {
$relation = $lecteur->expand();
$this->analyserRelation($relation);
 
if (count($this->relation_a_chemins) > $this->pas) {
$this->insererRelationAChemins();
}
if (count($this->relations_communes) > $this->pas_commune) {
$this->insererRelationsCommunes();
}
} else if ($lecteur->localName == 'way') {
$way = $lecteur->expand();
$this->analyserWay($way);
 
if (count($this->chemin_a_noeuds) > $this->pas) {
$this->insererCheminANoeuds();
}
} else if ($lecteur->localName == 'node') {
$node = $lecteur->expand();
$this->analyserNode($node);
if (count($this->noeuds) > $this->pas) {
$this->insererNoeuds();
}
}
}
if (count($this->noeuds) > $this->pas) {
$this->insererNoeuds();
$this->insererCheminANoeuds();
}
if ($this->getParametre('m') == 'manuel') {
$this->afficherAvancement("Analyse de la ligne du fichier OSM : ", 1);
}
}
$this->insererRelationsCommunes();
$this->insererRelationAChemins();
$this->insererCheminANoeuds();
$this->insererNoeuds();
} else {
$e = "Impossible d'ouvrir le fichier osm : %s";
$this->traiterErreur($e, array($this->getParametre('f')));
}
}
 
/**
* Récupère l'id commune, nom commune et le code INSEE et remplie la table `CommuneOSM`
*/
private function analyserRelation($relation) {
$relation_id = $this->proteger($relation->getAttribute('id'));
$chemins = $relation->getElementsByTagName('member');
foreach ($chemins as $chemin) {
if ($chemin->getAttribute('type') == 'way') { //écarter le noeud centrale
$chemin_id = $this->proteger($chemin->getAttribute('ref'));
$role = $this->proteger($chemin->getAttribute('role'));//role: null, inner, outer, exclave et enclave.
$this->relation_a_chemins[] = array($relation_id, $chemin_id, $role);
}
}
$commune_nom = null;
$commune_insee = null;
$tags = $relation->getElementsByTagName('tag');
foreach ($tags as $tag) {
$tag_cle = $tag->getAttribute('k');
$tag_val = $tag->getAttribute('v');
switch ($tag_cle) {
case 'name' :
$commune_nom = $this->proteger($tag_val);
break;
case 'ref:INSEE' :
$commune_insee = $this->proteger($tag_val);
break;
}
if (!is_null($commune_nom) && !is_null($commune_insee)) {
$this->relations_communes[] = array($relation_id, $commune_nom, $commune_insee);
if (!isset($this->communes[$commune_insee])) {
$this->communes[$commune_insee] = $relation_id;
} else {
$e = "La relation #%s contient déjà le tag ref:INSEE avec la valeur %s.".
"Veuillez corriger la carte OSM.";
$this->traiterErreur($e, array($this->communes[$commune_insee], $commune_insee, $relation_id));
}
break;
}
}
}
 
/**
* Récupère l'id_way et tous les id_node de chaque way et remplie la table `osm_chemin_a_noeuds`
*/
private function analyserWay($way) {
$chemin_id = $this->proteger($way->getAttribute('id'));
$ordre = 0;
$noeuds = $way->getElementsByTagName('nd');
$chemin_a_noeuds = array();
foreach ($noeuds as $noeud) {
$noeud_id = $this->proteger($noeud->getAttribute('ref'));
$ordre++;
$this->chemin_a_noeuds[] = array($chemin_id, $noeud_id, $ordre);
}
}
 
/**
* Fonction qui récupère tous les l'id_node et les valeurs(Lat/Lon) correspondantes et remplie la table `osm_noeuds`
*/
private function analyserNode($node) {
$noeud_id = $this->proteger($node->getAttribute('id'));
$lat = $this->proteger($node->getAttribute('lat'));
$lon = $this->proteger($node->getAttribute('lon'));
$this->noeuds[] = array($noeud_id, $lat, $lon);
}
 
private function insererRelationsCommunes() {
$requete = 'INSERT INTO osm_relations (id_relation, nom, code_insee) '.
'VALUES '.$this->creerValuesMultiple($this->relations_communes);
$this->inserer($requete);
$this->relations_communes = array();
}
 
private function insererRelationAChemins() {
$requete = 'INSERT INTO osm_relation_a_chemins (id_relation, id_chemin, role) '.
'VALUES '.$this->creerValuesMultiple($this->relation_a_chemins);
$this->inserer($requete);
$this->relation_a_chemins = array();
}
 
private function insererCheminANoeuds() {
$requete = 'INSERT INTO osm_chemin_a_noeuds (id_chemin, id_noeud, ordre) '.
'VALUES '.$this->creerValuesMultiple($this->chemin_a_noeuds);
$this->inserer($requete);
$this->chemin_a_noeuds = array();
}
 
private function insererNoeuds() {
$requete = 'INSERT INTO osm_noeuds (id_noeud, lat, `long`) '.
'VALUES '.$this->creerValuesMultiple($this->noeuds);
$this->inserer($requete);
$this->noeuds = array();
}
 
/**
* Fonction qui rajoute l'ordre et le sens de chaque way d'une relation dans la table `osm_relation_a_chemins`
* ALGO:
* -On fait un select de toutes les ways d'une relation.
* -On fait un count sur le tableau ways resutlant.
* -On met l'ordre du premier Way à 0.
* -On met : Actuelway = id_premier_way
* -Select dans table nodes, les nodes du way actuel
* -On prend le dernier noeud
* -On met : ActuelNoeud = id_dernier_noeud
* -Boucle for (i = 0; i < count(tabeau_way); i++) { sur le nombre de ways
* -On sélectionne id_way suivant qui contient le dernier_noeud du précédent
* (En écartant l'id_way déja existant )
* -On recherche les noeuds du nouveau way
* -On teste sur les extrémités du way précédent(dernier noeud) et suivant(premier noeud)
* -si égalité: $nombrePolygone=1;
* -sens:directe
* -ordre++
* -ActuelNoeud = id_dernier_noeud
* sinon
* -sens:indirecte
* -ordre++
* -ActuelNoeud = id_premier_noeud
* }
*/
private function ordonnerWays() {
$requete = 'SELECT DISTINCT id_relation '.
'FROM osm_relation_a_chemins ';
$relations = $this->bdd->recupererTous($requete);
foreach ($relations as $relation) {
$idRelation = $relation['id_relation'];
$requete = 'SELECT id_chemin '.
'FROM osm_relation_a_chemins '.
"WHERE id_relation = $idRelation";
$ways = $this->bdd->recupererTous($requete);
$nombreWays = count($ways);
// premier élément du tableau
$idPremierWay = $ways[0]['id_chemin'];
$wayActuel = $idPremierWay;
$requete = 'UPDATE osm_relation_a_chemins '.
'SET ordre = 0, sens = "directe" '.
"WHERE id_relation = $idRelation ".
"AND id_chemin = $wayActuel ";
$this->inserer($requete);
// selection dernier noeud
$requete = 'SELECT id_noeud '.
'FROM osm_chemin_a_noeuds '.
"WHERE id_chemin = $wayActuel ORDER BY ordre";
$nodes = $this->bdd->recupererTous($requete);
$nombreNodes = count($nodes);
$dernierNoeud = $nodes[$nombreNodes - 1]['id_noeud'];
$noeudActuel = $dernierNoeud;
for ($ordre = 1; $ordre < $nombreWays; $ordre++) {
//selectionner le way qui possède le dernier noeud du précédent way et écarter l'actuel
$requete = 'SELECT WN.id_chemin '.
'FROM osm_relation_a_chemins AS RW LEFT JOIN osm_chemin_a_noeuds AS WN ON (RW.id_chemin = WN.id_chemin) '.
"WHERE WN.id_noeud = $noeudActuel ".
"AND WN.id_chemin != $wayActuel ".
"AND RW.id_relation = $idRelation ";
$ways = $this->bdd->recupererTous($requete);
if (isset($ways[0])) {
$wayActuel = $ways[0]['id_chemin'];
$requete = 'SELECT id_noeud '.
'FROM osm_chemin_a_noeuds '.
"WHERE id_chemin = $wayActuel ORDER BY ordre ";
$nodes = $this->bdd->recupererTous($requete);
$nombreNodes = count($nodes);
if ( strcmp($nodes[0]['id_noeud'], $noeudActuel ) == 0 ) {
$requete = 'UPDATE osm_relation_a_chemins '.
"SET ordre = '$ordre', sens = 'directe' ".
"WHERE id_relation = $idRelation ".
"AND id_chemin = $wayActuel ";
$this->inserer($requete);
$noeudActuel = $nodes[$nombreNodes-1]['id_noeud'];
} else {
$requete = 'UPDATE osm_relation_a_chemins '.
"SET ordre = '$ordre', sens = 'indirecte' ".
"WHERE id_relation = $idRelation ".
"AND id_chemin = $wayActuel";
$this->inserer($requete);
$noeudActuel = $nodes[0]['id_noeud'];
}
}
}
}
}
 
/**
* Fonction qui parcourt tous les ways les noeuds de chaque relation en prenant en considération l'ordre et
* le sens de chaque ways concaténés ensemble(séparés par des virgules). Update du champ polygone de chaque
* relation dans la table `osm_relations`
*/
private function remplirPolygone() {
$polygone = array();
$idNodes = array();
$String = '';
$requete = 'SELECT id_relation, nom, code_insee FROM osm_relations ';
$relations = $this->bdd->recupererTous($requete);
foreach ($relations as $relation) {
$idCommune = $relation['id_relation'];
$nomCommune = $relation['nom'];
$INSEE = $relation['code_insee'];
$requete = 'SELECT id_chemin FROM osm_relation_a_chemins '.
"WHERE id_relation = $idCommune ".
'ORDER BY ordre';
$ways = $this->bdd->recupererTous($requete);
foreach ($ways as $way) {
$idWay = $way['id_chemin'];
$requeteSensWay= "SELECT sens FROM osm_relation_a_chemins WHERE id_relation = $idCommune
AND id_chemin = $idWay";
$sens = $this->bdd->recupererTous($requeteSensWay);
$requeteNodes = "SELECT id_noeud FROM osm_chemin_a_noeuds WHERE id_chemin= $idWay ORDER BY ordre ";
$nodes = $this->bdd->recupererTous($requeteNodes);
if($sens[0]['sens'] == "directe") {
foreach ($nodes as $node) {
$idNodes[] = $node['id_noeud'];
}
$noeuds = implode(", ", $idNodes);
//requête IN qui gère l'ordre des noeuds de chaque way (CAS ASC)
$requeteLatitudeLongitude = 'SELECT NLL.id_noeud, NLL.lat, NLL.`long` '.
'FROM osm_chemin_a_noeuds WN, osm_noeuds NLL '.
"WHERE NLL.id_noeud IN ($noeuds) ".
'AND WN.id_noeud = NLL.id_noeud '.
"AND WN.id_chemin = $idWay ORDER BY WN.ordre ASC";
unset($noeuds);
unset($idNodes);
$LatLons = $this->bdd->recupererTous($requeteLatitudeLongitude);
foreach ($LatLons as $LatLon) {
$Latitude = $LatLon['lat'];
$Longitude = $LatLon['long'];
$String = "$Latitude $Longitude";
$polygone[] = $String;
}
} else {
foreach ($nodes as $node) {
$idNodes[] = $node['id_noeud'];
}
$noeuds = implode(", ", $idNodes);
//requête IN qui gère l'ordre des noeuds de chaque way (CAS DESC)
$requeteLatitudeLongitude = 'SELECT NLL.id_noeud, NLL.lat, NLL.`long` '.
'FROM osm_chemin_a_noeuds WN ,osm_noeuds NLL '.
"WHERE NLL.id_noeud IN ($noeuds) ".
'AND WN.id_noeud = NLL.id_noeud '.
"AND WN.id_chemin = $idWay ORDER BY WN.ordre DESC";
unset($noeuds);
unset($idNodes);
$LatLons = $this->bdd->recupererTous($requeteLatitudeLongitude);
foreach ($LatLons as $LatLon) {
$Latitude = $LatLon['lat'];
$Longitude = $LatLon['long'];
$String = "$Latitude $Longitude";
$polygone[] = $String;
}
}
}
$this->etatPolygone($polygone, $idCommune, $nomCommune, $INSEE);
unset($separationVirgule);
unset($requeteNodes);
unset($String);
unset($polygone);
}
}
 
private function etatPolygone($polygone, $idCommune, $nomCommune, $INSEE) {
$separationVirgulePolygone = implode(', ', $polygone);
$nomCommuneProtege = $this->bdd->proteger($nomCommune);
$InseeProtege = $this->bdd->proteger($INSEE);
if ($polygone[0] == $polygone[count($polygone)-1]) { //test sur début et fin du polygone
//requête replace pour gérer la mise à jour à la suite
$requete = 'REPLACE INTO osm_communes (id_relation, nom, code_insee, polygon, note ) '.
"VALUES ($idCommune, $nomCommuneProtege, $InseeProtege, ".
"POLYFROMTEXT('MULTIPOLYGON ((($separationVirgulePolygone)))'),'Polygone complet');";
} else {
$requete = 'REPLACE INTO osm_communes (id_relation, nom, code_insee, polygon, note ) '.
"VALUES ($idCommune, $nomCommuneProtege, $InseeProtege, ".
"POLYFROMTEXT('MULTIPOLYGON ((($separationVirgulePolygone)))'),'Polygone incomplet');";
}
$this->inserer($requete);
}
 
//Fonction qui remet à zéro l'ordre des ways des communes des polygones incomplets fait précédement
private function remettreOrdreAZero() {
$requeteRelations = "SELECT id_relation FROM osm_communes WHERE note LIKE 'Polygone incomplet'";
$relations = $this->bdd->recupererTous($requeteRelations);
foreach ($relations as $relation) {
$idRelation = $relation['id_relation'];
$requeteWays = "SELECT id_chemin FROM osm_relation_a_chemins WHERE id_relation= $idRelation";
$ways = $this->bdd->recupererTous($requeteWays);
foreach ($ways as $way) {
$idWay = $way['id_chemin'];
$this-> inserer('UPDATE osm_relation_a_chemins SET ordre = NULL '.
"WHERE id_relation = $idRelation AND id_chemin = $idWay ;");
}
}
 
}
 
/**
* Fonction qui récupère les relations des polygones incomplets et appelle pour chaque relation la fonction
* ordonnerPolygoneIncomplet($ordre,$tour,$idRelation,$nombrePolygone)
*/
private function relationsPolygoneIncomplet($ordre, $tour) {
$nombrePolygone = 1;
$requeteRelations = "SELECT id_relation FROM osm_communes WHERE note LIKE 'Polygone incomplet'";
$relations = $this->bdd->recupererTous($requeteRelations);
foreach ($relations as $relation) {
$nombrePolygone = 1;
$idRelation = $relation['id_relation'];
$this->ordonnerPolygoneIncomplet($ordre,$tour,$idRelation,$nombrePolygone);
}
}
 
/**
* Fonction récursive qui exécute la même tâche que la fonction ordonnerWays() pour chaque polygone d'un
* multipolygone et remplie le champ NbPoly dans la table `osm_relation_a_chemins` qui correspond au nombre de polygone fermé
* dans le multipolygone
*/
private function ordonnerPolygoneIncomplet($ordre, $tour, $idRelation, $nombrePolygone) {
$requeteWays = 'SELECT id_chemin FROM osm_relation_a_chemins '.
"WHERE id_relation = $idRelation AND ordre = 'NULL'";
$ways = $this->bdd->recupererTous($requeteWays);
$tempWays = $ways;
$nombreWays = count($ways);
// premier élément du tableau
$idPremierWay = $ways[0]['id_chemin'];
$wayActuel = $idPremierWay;
$this-> inserer('UPDATE osm_relation_a_chemins '.
"SET ordre = $ordre, sens = 'directe', nbre_poly = $nombrePolygone ".
"WHERE id_relation = $idRelation ".
"AND id_chemin = $wayActuel ;");
//selection dernier noeud
$requeteNodes = "SELECT id_noeud FROM osm_chemin_a_noeuds WHERE id_chemin = $wayActuel ORDER BY ordre;";
$nodes = $this->bdd->recupererTous($requeteNodes);
$nombreNodes = count($nodes);
$premierNoeud = $nodes[0]['id_noeud'];
$dernierNoeud = $nodes[$nombreNodes-1]['id_noeud'];
$noeudActuel = $dernierNoeud;
$tour++;
//Condition pour laquelle la boucle while continue à tourner; tant que le premier noeud du polygone n'est
//égale au dernier et tant qu'il reste des ways à gérer
while (($premierNoeud != $noeudActuel) && (($ordre % 1000) < count($tempWays))) {
//select le way qui possède le dernier noeud du précédent way et écarter l'actuel
$nombrePolygone;
$ordre++;
//select des ways qui n'ont pas été ordonnés: on obtient à chaque itération les ways qui restent à ordonner
$requeteWays = 'SELECT WN.id_chemin FROM (osm_chemin_a_noeuds WN, osm_relation_a_chemins RW) '.
"WHERE WN.id_noeud = $noeudActuel AND WN.id_chemin != $wayActuel ".
"AND RW.id_chemin = WN.id_chemin AND RW.id_relation = $idRelation ".
"AND RW.ordre = 'NULL' ;";
$ways = $this->bdd->recupererTous($requeteWays);
 
if (isset($ways[0])) {
$wayActuel = $ways[0]['id_chemin'];
$requeteNodes = "SELECT id_noeud FROM osm_chemin_a_noeuds WHERE id_chemin = $wayActuel ORDER BY ordre;";
$nodes = $this->bdd->recupererTous($requeteNodes);
$nombreNodes = count($nodes);
if (strcmp($nodes[0]['id_noeud'], $noeudActuel ) == 0) {
$this-> inserer("UPDATE osm_relation_a_chemins SET ordre = '$ordre', sens = 'directe', ".
"nbre_poly = $nombrePolygone ".
"WHERE osm_relation_a_chemins.id_relation = $idRelation ".
"AND osm_relation_a_chemins.id_chemin = $wayActuel");
$noeudActuel = $nodes[$nombreNodes-1]['id_noeud'];
} else {
$this-> inserer('UPDATE osm_relation_a_chemins '.
"SET ordre = '$ordre', sens = 'indirecte', ".
"nbre_poly = $nombrePolygone ".
"WHERE id_relation = $idRelation ".
"AND id_chemin = $wayActuel");
$noeudActuel = $nodes[0]['id_noeud'];
}
}
}
$ordre = 1000 * $tour; //différencier chaque polygone: pour chaque polygone on a un multiple de mille
$requeteCount = "SELECT ordre FROM osm_relation_a_chemins WHERE id_relation = $idRelation AND ordre = 0";
$count = $this->bdd->recupererTous($requeteCount);
if ((count($count)) != 0) { // s'ils en restent des ways à gérer
$nombrePolygone++;
//appelle de la fonction récursive
$this->ordonnerPolygoneIncomplet($ordre, $tour, $idRelation, $nombrePolygone);
}
}
 
/**
* Fonction qui récupère les relations des polygones incomplets et appelle pour chaque relation la fonction
* remplirPolygoneIncomplet($idRelation);
*/
private function remplirCommunesPolygoneIncomplet() {
$nombrePolygone = 1;
$requeteRelations = "SELECT id_relation FROM osm_communes WHERE note LIKE 'Polygone incomplet'";
$relations = $this->bdd->recupererTous($requeteRelations);
foreach ($relations as $relation) {
$idRelation = $relation['id_relation'];
$this->remplirPolygoneIncomplet($idRelation);//appel de la fonction avec comme paramètre ID-commune
}
}
 
/**
* Fonction qui exécute la même tâche que la fonction remplirPolygone() pour chaque polygone d'un multipolygone
* et renvoie un tableau MultiPolygone[] où chaque case contient un polygone fermé et appelle la fonction
* etatMultiPolygone($multiPolygone, $idCommune) qui remplie le Multipolygone de la commune correspondante
*/
private function remplirPolygoneIncomplet($idCommune) {
$polygone = array();
$multiPolygone = array();//tableau multipolygone qui contient tous les polygones d'un multipolygone
$idNodes = array();
$roles = array();//tableau roles qui contient les roles des ways
$String = "";
//sélectionner le nombre de polygones qui existe dans un multipolygone
$requete = 'SELECT MAX(nbre_poly) AS nbre_poly '.
'FROM osm_relation_a_chemins '.
"WHERE id_relation = $idCommune";
$nombrePolygone = $this->bdd->recupererTous($requete);
$nbPoly = $nombrePolygone[0]['nbre_poly'];
for ($tour = 1; $tour <= $nbPoly; $tour++) {//boucle for qui parcourt chaque polygone du multipolygone
$requeteWays = 'SELECT id_chemin FROM osm_relation_a_chemins '.
"WHERE id_relation = $idCommune ".
"AND nbre_poly = $tour ORDER BY ordre";
$ways = $this->bdd->recupererTous($requeteWays);
foreach ($ways as $way) {
$idWay = $way['id_chemin'];
$requeteSensWay = 'SELECT sens FROM osm_relation_a_chemins '.
"WHERE id_relation = $idCommune ".
"AND id_chemin = $idWay";//sélection de l'orientation du way
$sens= $this->bdd->recupererTous($requeteSensWay);
$requeteNodes = "SELECT id_noeud FROM osm_chemin_a_noeuds WHERE id_chemin= $idWay ORDER BY ordre";
$nodes = $this->bdd->recupererTous($requeteNodes);
if ($sens[0]['sens'] == "directe") {//test sur le sens des ways
foreach ($nodes as $node) {
$idNodes[] = $node['id_noeud'];
}
$noeuds = implode(", ", $idNodes);
//requête IN qui gère l'ordre des noeuds de chaque way (CAS ASC)
$requeteLatitudeLongitude = 'SELECT NLL.id_noeud, NLL.lat, NLL.`long` '.
'FROM osm_chemin_a_noeuds WN, osm_noeuds NLL '.
"WHERE NLL.id_noeud IN ($noeuds) ".
'AND WN.id_noeud = NLL.id_noeud '.
"AND WN.id_chemin= $idWay ORDER BY WN.ordre ASC";
unset($noeuds);
unset($idNodes);
$LatLons = $this->bdd->recupererTous($requeteLatitudeLongitude);
foreach ($LatLons as $LatLon) {
$Latitude = $LatLon['lat'];
$Longitude = $LatLon['long'];
$String = "$Latitude $Longitude";
$polygone[] = $String;
}
} else {
foreach ($nodes as $node) {
$idNodes[] = $node['id_noeud'];
}
$noeuds = implode(", ", $idNodes);
//requête IN qui gère l'ordre des noeuds de chaque way (CAS DESC)
$requeteLatitudeLongitude = 'SELECT NLL.id_noeud, NLL.lat, NLL.`long` '.
'FROM osm_chemin_a_noeuds WN, osm_noeuds NLL '.
"WHERE NLL.id_noeud IN ($noeuds) ".
'AND WN.id_noeud = NLL.id_noeud '.
"AND WN.id_chemin= $idWay ORDER BY WN.ordre DESC";
unset($noeuds);
unset($idNodes);
$LatLons = $this->bdd->recupererTous($requeteLatitudeLongitude);
foreach ($LatLons as $LatLon) {
$Latitude = $LatLon['lat'];
$Longitude = $LatLon['long'];
$String = "$Latitude $Longitude";
$polygone[] = $String;
}
}
}
$requeteRole = 'SELECT DISTINCT role '.
'FROM osm_relation_a_chemins '.
"WHERE id_relation = $idCommune ".
"AND nbre_poly = $tour ";
$role = $this->bdd->recupererTous($requeteRole);
$role = $role[0]['role'];
$separationVirgulePolygone = implode(", ", $polygone);
$multiPolygone[] = $separationVirgulePolygone;
$roles[] = $role;
unset($separationVirgulePolygone);
unset($polygone);
}
$this->etatMultiPolygone($multiPolygone, $roles, $idCommune, $nbPoly);//appel de la fonction de remplissage
}
 
/**
* Remplie le champ polygone à partir du tableau MultiPolygone
*/
private function etatMultiPolygone($multiPolygone, $roles, $idCommune, $nbPoly) {
$note = $this->proteger('Polygone complet');
if ($nbPoly == 2 && ((in_array('inner', $roles)) || (in_array('enclave', $roles)))) {//cas Outer Inner à deux polygones
$multiPoly = implode('),(', $multiPolygone);
$requete = 'UPDATE osm_communes '.
"SET polygon = MPOLYFROMTEXT('MULTIPOLYGON((($multiPoly)))'), ".
"note = $note ".
"WHERE id_relation = $idCommune ";
$this->inserer($requete);
}
if ((in_array('inner', $roles)) || (in_array('enclave', $roles)) != 1) { //tous les autres cas
$multiPoly = implode(')),((', $multiPolygone);
$requete = 'UPDATE osm_communes '.
"SET polygon = MPOLYFROMTEXT('MULTIPOLYGON((($multiPoly)))'), ".
"note = $note ".
"WHERE id_relation = $idCommune ";
$this->inserer($requete);
}
}
 
/**
* Renomme la note des polygones vides d'un polygone complet en polygone incomplet
*/
private function renommerEnPolygoneIncomplet() {
$requete = 'SELECT id_relation, ASTEXT(polygon) AS poly '.
'FROM osm_communes ';
$etatPolygones = $this->bdd->recupererTous($requete);
foreach ($etatPolygones as $etatPolygone ) {
if (isset($etatPolygone['poly']) == 0) {//test si le polygone est vide
$idCommune = $this->proteger($etatPolygone['id_relation']);
$note = $this->proteger('Polygone incomplet');
$requete = 'UPDATE osm_communes '.
"SET note = $note ".
"WHERE id_relation = $idCommune ";
$this->inserer($requete);
}
}
}
 
 
/**
* Récupère le point centre de chaque polygone et remplie la colonne "centre"
*/
private function centroid() {
$requete = 'SELECT id_relation, ASTEXT(polygon) AS poly '.
'FROM osm_communes ';
$communes = $this->bdd->recupererTous($requete);
foreach ($communes as $commune) {
$multipolygone = $commune['poly'];
$requete = "SELECT ASTEXT(CENTROID(MPOLYFROMTEXT('$multipolygone'))) AS centre ";
$point = $this->bdd->recupererTous($requete);
$centre = $this->proteger($point[0]['centre']);
$idCom = $this->proteger($commune['id_relation']);
$requete = 'UPDATE osm_communes '.
"SET centre = POINTFROMTEXT($centre) ".
"WHERE id_relation = $idCom ";
$this->inserer($requete);
}
}
 
private function creerValuesMultiple($donnees) {
$values = array();
foreach ($donnees as $donnee) {
$values[] = implode(',', $donnee);
}
$values_chaine = '('.implode('),(', $values).')';
return $values_chaine;
}
 
private function inserer($requete) {
$this->bdd->requeter($requete);
}
 
private function proteger($chaine) {
return $this->bdd->proteger($chaine);
}
 
}
?>
/tags/v5.3-amandaie/scripts/modules/biblio_bota/biblio_bota.ini
New file
0,0 → 1,84
version="2009-10-05"
dossierTsv = "{ref:dossierDonneesEflore}biblio_bota/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
prefixe = "biblio_"
 
[tables]
article = "{ref:prefixe}article"
article_sauv = "{ref:prefixe}article_sauv"
aut_saisie = "{ref:prefixe}aut_saisie"
collection = "{ref:prefixe}collection"
domaine = "{ref:prefixe}domaine"
domaine_lier = "{ref:prefixe}domaine_lier"
domaine_lier_sauv = "{ref:prefixe}domaine_lier_sauv"
fasc = "{ref:prefixe}fasc"
fasc_sauv = "{ref:prefixe}fasc_sauv"
item = "{ref:prefixe}item"
item_sauv = "{ref:prefixe}item_sauv"
item_typlog = "{ref:prefixe}item_typlog"
item_typphy = "{ref:prefixe}item_typphy"
link = "{ref:prefixe}link"
link_categ = "{ref:prefixe}link_categ"
link_categoriser = "{ref:prefixe}link_categoriser"
link_sauv = "{ref:prefixe}link_sauv"
media = "{ref:prefixe}media"
modif = "{ref:prefixe}modif"
serie = "{ref:prefixe}serie"
spy = "{ref:prefixe}spy"
str = "{ref:prefixe}str"
str_sauve = "{ref:prefixe}str_sauve"
str_type = "{ref:prefixe}str_type"
 
[fichiers]
structureSql = "biblio_bota.sql"
article = "{ref:prefixe}article.tsv"
article_sauv = "{ref:prefixe}article_sauv.tsv"
aut_saisie = "{ref:prefixe}aut_saisie.tsv"
collection = "{ref:prefixe}collection.tsv"
domaine = "{ref:prefixe}domaine.tsv"
domaine_lier = "{ref:prefixe}domaine_lier.tsv"
domaine_lier_sauv = "{ref:prefixe}domaine_lier_sauv.tsv"
fasc = "{ref:prefixe}fasc.tsv"
fasc_sauv = "{ref:prefixe}fasc_sauv.tsv"
item = "{ref:prefixe}item.tsv"
item_sauv = "{ref:prefixe}item_sauv.tsv"
item_typlog = "{ref:prefixe}item_typlog.tsv"
item_typphy = "{ref:prefixe}item_typphy.tsv"
link = "{ref:prefixe}link.tsv"
link_categ = "{ref:prefixe}link_categ.tsv"
link_categoriser = "{ref:prefixe}link_categoriser.tsv"
link_sauv = "{ref:prefixe}link_sauv.tsv"
media = "{ref:prefixe}media.tsv"
modif = "{ref:prefixe}modif.tsv"
serie = "{ref:prefixe}serie.tsv"
spy = "{ref:prefixe}spy.tsv"
str = "{ref:prefixe}str.tsv"
str_sauve = "{ref:prefixe}str_sauve.tsv"
str_type = "{ref:prefixe}str_type.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
article = "{ref:dossierSql}{ref:fichiers.article}"
article_sauv = "{ref:dossierSql}{ref:fichiers.article_sauv}"
aut_saisie = "{ref:dossierSql}{ref:fichiers.aut_saisie}"
collection = "{ref:dossierSql}{ref:fichiers.collection}"
domaine = "{ref:dossierSql}{ref:fichiers.domaine}"
domaine_lier = "{ref:dossierSql}{ref:fichiers.domaine_lier}"
domaine_lier_sauv = "{ref:dossierSql}{ref:fichiers.domaine_lier_sauv}"
fasc = "{ref:dossierSql}{ref:fichiers.fasc}"
fasc_sauv = "{ref:dossierSql}{ref:fichiers.fasc_sauv}"
item = "{ref:dossierSql}{ref:fichiers.item}"
item_sauv = "{ref:dossierSql}{ref:fichiers.item_sauv}"
item_typlog = "{ref:dossierSql}{ref:fichiers.item_typlog}"
item_typphy = "{ref:dossierSql}{ref:fichiers.item_typphy}"
link = "{ref:dossierSql}{ref:fichiers.link}"
link_categ = "{ref:dossierSql}{ref:fichiers.link_categ}"
link_categoriser = "{ref:dossierSql}{ref:fichiers.link_categoriser}"
link_sauv = "{ref:dossierSql}{ref:fichiers.link_sauv}"
media = "{ref:dossierSql}{ref:fichiers.media}"
modif = "{ref:dossierSql}{ref:fichiers.modif}"
serie = "{ref:dossierSql}{ref:fichiers.serie}"
spy = "{ref:dossierSql}{ref:fichiers.spy}"
str = "{ref:dossierSql}{ref:fichiers.str}"
str_sauve = "{ref:dossierSql}{ref:fichiers.str_sauve}"
str_type = "{ref:dossierSql}{ref:fichiers.str_type}"
/tags/v5.3-amandaie/scripts/modules/biblio_bota/BiblioBota.php
New file
0,0 → 1,70
<?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 BiblioBota extends EfloreScript {
 
public function executer() {
try {
$this->initialiserProjet('biblio_bota');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerBiblioBota();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
public function chargerBiblioBota() {
$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 '\\\' ";
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS biblio_article, biblio_article_sauv, biblio_aut_saisie, ".
"biblio_collection, biblio_domaine, biblio_domaine_lier, biblio_domaine_lier_sauv, biblio_fasc, ".
"biblio_fasc_sauv, biblio_item, biblio_item_sauv, biblio_item_typlog, biblio_item_typphy, ".
"biblio_link, biblio_link_categ, biblio_link_categoriser, biblio_link_sauv, biblio_media, ".
"biblio_modif, biblio_serie, biblio_spy, biblio_str, biblio_str_sauve, biblio_str_type, ".
"biblio_meta";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/wikipedia/wikipedia.ini
New file
0,0 → 1,21
version="2011"
dossierDonnees = "{ref:dossierDonneesEflore}wikipedia/"
 
[dossiers]
structure = "{ref:dossierDonnees}"
meta = "{ref:dossierDonnees}"
communes = "{ref:dossierDonnees}communes/2011-05-13/"
[tables]
wikipediaMeta = "wikipedia_meta"
wikipediaCommunes = "wikipedia_communes_v{ref:version}"
 
[fichiers]
structureSql = "wikipedia.sql"
wikipediaMeta = "wikipedia_meta.sql"
wikipediaCommunes = "communes_tom_com_v2011.csv"
 
[chemins]
structureSql = "{ref:dossiers.structure}{ref:fichiers.structureSql}"
wikipediaMeta = "{ref:dossiers.meta}{ref:fichiers.wikipediaMeta}"
wikipediaCommunes = "{ref:dossiers.communes}{ref:fichiers.wikipediaCommunes}"
/tags/v5.3-amandaie/scripts/modules/wikipedia/Wikipedia.php
New file
0,0 → 1,115
<?php
//declare(encoding='UTF-8');
/**
* Classe permettant de :
* - rajouter l'objet point centroide de la commune.
* - charger la bdd
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php wikipedia -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 Wikipedia extends EfloreScript {
private $tableMeta = '';
private $cheminFichierMeta = '';
private $tableCommunes = '';
private $cheminFichierCommunes = '';
 
public function executer() {
try {
$this->initialiserProjet('wikipedia');
$this->tableMeta = Config::get('tables.wikipediaMeta');
$this->cheminFichierMeta = Config::get('chemins.wikipediaMeta');
$this->tableCommunes = Config::get('tables.wikipediaCommunes');
$this->cheminFichierCommunes = Config::get('chemins.wikipediaCommunes');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerMetaDonnees();
$this->chargerWikipediaCommunes();
$this->preparerTable();
$this->recupererPoints();
case 'points' :
$this->preparerTable();
$this->recupererPoints();
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($this->cheminFichierMeta);
$this->executerScripSql($contenuSql);
}
 
private function chargerWikipediaCommunes() {
$requete = "LOAD DATA INFILE '{$this->cheminFichierCommunes}' ".
"REPLACE INTO TABLE {$this->tableCommunes} ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY ',' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function preparerTable() {
$requete = "ALTER TABLE {$this->tableCommunes} ".
'DROP centroide ';
$this->getBdd()->requeter($requete);
 
$requete = "ALTER TABLE {$this->tableCommunes} ".
' ADD centroide point NOT NULL ';
$this->getBdd()->requeter($requete);
 
$requete = "ALTER TABLE {$this->tableCommunes} ".
' ADD INDEX (centroide) ';
$this->getBdd()->requeter($requete);
}
 
private function recupererPoints() {
$requete = 'SELECT * '.
"FROM {$this->tableCommunes} ";
$LatLons = $this->getBdd()->recupererTous($requete);
 
foreach ($LatLons as $LatLon) {
$latitude_degre = $LatLon['latitude'];
$longitude_degre = $LatLon['longitude'];
$insee = $LatLon['code_insee'];
$this->formerPointCentre($latitude_degre, $longitude_degre, $insee);
$this->afficherAvancement('Analyse des communes Wikipedia');
}
}
 
private function formerPointCentre($latitude_degre, $longitude_degre, $insee) {
$centre = "$latitude_degre $longitude_degre";
$requete = "UPDATE {$this->tableCommunes} ".
"SET centroide = POINTFROMTEXT('POINT($centre)') ".
"WHERE code_insee = $insee ";
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS {$this->tableMeta}, {$this->tableCommunes}";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.3-amandaie/scripts/modules/baseveg/BasevegVerif.php
New file
0,0 → 1,94
<?php
 
class BasevegVerif extends VerificateurDonnees {
 
private $synonymes;
private $niveaux;
private $motifs;
 
//obligatoire
public function definirTraitementsColonnes() {
$this->initialiserParametresVerif();
if ($this->colonne_num == 1 ) {
$this->verifierColonne();
} elseif ($this->colonne_num == 2 ) {
$this->verifierColonne();
} elseif ($this->colonne_num == 4 ) {
$this->verifierNiveaux();
}
}
public function initialiserParametresVerif() {
$this->niveaux = array('CLA','ALL','ORD','ASS','GRPT','SUBORD','SUBASS','BC','SUBCLA','DC','SUBALL');
$this->synonymes = array('incl','=','?','illeg','pp','pmaxp','pminp','compl','ambig','non','inval','nn','ined');
$this->motifs= $this->inverserTableau(array('/^[0-9]+$/' => 1,
'/(?:[0-9]{2}\/$|[0-9]{2}\/[0-9]\.$|[0-9]{2}\/(?:[0-9]\.){1,5}[0-9]$|[0-9]{2}\/(?:[0-9]\.){4,5}[0-9]\/[0-9]+(?:bis|ter|quater){0,1}$)|incertae sedis/' => 2));
//présence de '=' , '= ?' et ',' dans les valeurs des paramètres. ne pas utiliser getParametresTableau.
}
//++---------------------------------traitements des colonnes baseveg------------------------------------++
/**
*
* verifie le champ niveau
*/
public function verifierNiveaux(){
if (preg_match("/^syn(.+)$/", $this->colonne_valeur, $retour) == 1) {
$synonymes = explode(' ', trim($retour[1]));
foreach($synonymes as $syn){
if (!in_array($syn, $this->synonymes)) {
$this->noterErreur();
}
}
} elseif($this->colonne_valeur != '') {
if (!in_array($this->colonne_valeur , $this->niveaux)) {
$this->noterErreur();
}
}
}
 
/**
*
* vérifie un motif sur la valeur entière d'une colonne par expression régulière
*
*/
public function verifierColonne(){
$motif = $this->motifs[$this->colonne_num];
if (preg_match($motif, $this->colonne_valeur) == 0 && $this->verifierSiVide() == false){
$this->noterErreur();
}
}
 
/**
*
* vérifie si une colonne est vide ou non de valeurs
*
*/
public function verifierSiVide(){
$vide = ($this->colonne_valeur == '') ? true : false;
return $vide;
}
/*--------------------------------------------OUtils-------------------------------------------*/
//attention , dans les motifs !!
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.3-amandaie/scripts/modules/baseveg/Baseveg.php
New file
0,0 → 1,111
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php baseveg -a chargerTous
*/
 
class Baseveg extends EfloreScript {
 
 
 
 
public function executer() {
try {
$this->initialiserProjet('baseveg');
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'supprimerTous' :
$this->supprimerTous();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerMetadonnees' :
$this->chargerMetadonnees();
break;
case 'chargerDonnees' :
$this->chargerDonnees();
break;
case 'verifierFichier' :
//cette étape met en avant les valeurs qui vont poser des problèmes (ontologies..)
$this->verifierFichier();
break;
case 'supprimerOntologies' :
$this->supprimerOntologies();
break;
case 'chargerOntologies' :
$this->chargerOntologies();
break;
case 'chargerTous' :
$this->supprimerTous();
$this->chargerStructureSql();
$this->chargerMetadonnees();
$this->chargerDonnees();
$this->chargerOntologies();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
private function getClasseBasevegVerif() {
$conteneur = new Conteneur();
require_once dirname(__FILE__)."/BasevegVerif.php";
$verif = new BasevegVerif($conteneur,'baseveg');
return $verif;
}
private function verifierFichier() {
$verif = $this->getClasseBasevegVerif();
$verif->verifierFichier(Config::get('chemins.donnees'));
}
private function supprimerOntologies() {
$chemin = Config::get('chemins.ontologies');
$table = Config::get('tables.ontologies');
$requete = "TRUNCATE TABLE $table ;";
$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 '\\\' "
;
$this->getBdd()->requeter($requete);
}
 
private function chargerDonnees() {
$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);
}
protected function chargerMetadonnees() {
$contenuSql = $this->recupererContenu(Config::get('chemins.metadonnees'));
$this->executerScripSql($contenuSql);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS baseveg_meta, baseveg_ontologies, baseveg_v".Config::get('version');
$this->getBdd()->requeter($requete);
}
 
}
?>
/tags/v5.3-amandaie/scripts/modules/baseveg/baseveg.ini
New file
0,0 → 1,26
version="2013_09_23"
dossierTsv = "{ref:dossierDonneesEflore}baseveg/2013-09-23/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
donnees = "baseveg_v{ref:version}"
metadonnees = "baseveg_meta"
ontologies = "baseveg_ontologies"
 
[fichiers]
structureSql = "baseveg_v{ref:version}.sql"
metadonnees = "baseveg_insertion_meta_v{ref:version}.sql"
donnees = "baseveg_v{ref:version}.tsv"
ontologies = "baseveg_ontologies.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
donnees = "{ref:dossierTsv}{ref:fichiers.donnees}"
metadonnees = "{ref:dossierSql}{ref:fichiers.metadonnees}"
ontologies ="{ref:dossierTsv}{ref:fichiers.ontologies}"
 
[Parametres]
niveaux = "'CLA';'ALL';'ORD';'ASS';'GRPT';'SUBORD';'SUBASS';'BC';'SUBCLA';'DC';'SUBALL'"
synonymes = "'incl';'=';'= ?';'illeg';'pp';'pmaxp';'pminp';'compl';'ambig';'non';'inval';'nn';'ined'"
motifs = "/^[0-9]+$/=1;
/(?:[0-9]{2}\/$|[0-9]{2}\/[0-9]\.$|[0-9]{2}\/(?:[0-9]\.){1,5}[0-9]$|[0-9]{2}\/(?:[0-9]\.){4,5}[0-9]\/[0-9]+(?:bis|ter){0,1}$)|incertae sedis/=2"
/tags/v5.3-amandaie/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.3-amandaie/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.3-amandaie/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('&#173;', '', $txt);
$txt = str_ireplace('&nbsp;', ' ', $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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/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.3-amandaie/scripts/modules
New file
Property changes:
Added: svn:ignore
+tempsexecution
/tags/v5.3-amandaie/scripts/configurations/config.defaut.ini
New file
0,0 → 1,42
; Encodage : UTF-8
; +------------------------------------------------------------------------------------------------------+
; Info sur l'application
info.nom = Scripts de tests
; Abréviation de l'application
info.abr = SCRIPTS
; Version du Framework nécessaire au fonctionnement de cette application
info.framework.version = 0.3
; Encodage de l'application
encodage_appli = "UTF-8"
; Chemin de l'application (pour l'utiliser dans ce fichier)
chemin_scripts = "php:Framework::getCheminAppli()"
; +------------------------------------------------------------------------------------------------------+
; Débogage
; Indique si oui ou non on veut afficher le débogage.
debogage = true
; Indique si oui ou non on veut lancer le chronométrage
chronometrage = false
 
+------------------------------------------------------------------------------------------------------+
; Paramètrage de la base de données.
; bdd_abstraction : abstraction de la base de données.
; bdd_protocole : Protocole de la base de données.
; bdd_serveur : Nom du serveur de bases de données.
; bdd_utilisateur : Nom de l'utilisateur de la base de données.
; bdd_mot_de_passe : Mot de passe de l'utilisateur de la base de données.
; bdd_nom : Nom de la base de données principale.
; bdd_encodage : Encodage de la base de données principale. Normalement le même que l'application mais au format base de
; données : voir ici : http://dev.mysql.com/doc/refman/5.0/en/charset-charsets.html
; et là: http://www.postgresql.org/docs/8.1/static/multibyte.html pour les correspondances
bdd_abstraction = pdo
bdd_protocole = mysql
bdd_serveur = localhost
bdd_utilisateur = "root"
bdd_mot_de_passe = ""
bdd_nom = ""
bdd_encodage = "utf8"
 
 
; Dossier de base contenant les données d'eFlore (Fichiers TSV et SQL)
dossierDonneesEflore = "/home/telabotap/www/eflore/donnees/"
/tags/v5.3-amandaie/scripts/configurations
New file
Property changes:
Added: svn:ignore
+config.ini
/tags/v5.3-amandaie/scripts/framework.defaut.php
New file
0,0 → 1,6
<?php
// Inclusion du Framework
// Renomer ce fichier en "framework.php"
// Indiquer ci-dessous le chemin absolu vers le fichier autoload.inc.php de la bonne version du Framework
require_once '/home/www/commun/framework/0.3/Framework.php';
?>
/tags/v5.3-amandaie/scripts/.htaccess
New file
0,0 → 1,2
order deny,allow
deny from all
/tags/v5.3-amandaie/scripts/bibliotheque/LecteurExcel.php
New file
0,0 → 1,64
<?php
require_once dirname(__FILE__).DS.'excel_reader'.DS.'excel_reader2.php';
 
class LecteurExcel {
 
private $lecteur = null;
private $fichier = '';
private $feuille = 0;
 
public function __construct($fichierExcel) {
error_reporting(E_ALL ^ E_NOTICE);
$this->fichier = $fichierExcel;
$this->lecteur = new Spreadsheet_Excel_Reader();
$this->lecteur->setUTFEncoder('mb');
$this->lecteur->setOutputEncoding('UTF-8');
$this->lecteur->read($this->fichier);
}
 
public function getFichier() {
return $this->fichier;
}
 
public function getFeuille() {
return $this->feuille;
}
 
public function setFeuille($feuille) {
return $this->feuille = $feuille;
}
 
public function getValeur($ligne, $colonne) {
$val = $this->lecteur->val($ligne, $colonne, $this->feuille);
return $val;
}
 
public function getValeurBrute($ligne, $colonne) {
return $this->lecteur->raw($ligne, $colonne, $this->feuille);
}
 
public function getNbreLignes() {
return $this->lecteur->rowcount($this->feuille);
}
 
public function getNbreColonne() {
return $this->lecteur->colcount($this->feuille);
}
 
public function getDonnees() {
return $this->lecteur->sheets[$this->feuille];
}
 
public function afficherTxt() {
foreach ($this->lecteur->sheets as $k => $data) {
echo "Fichier : {$this->fichier}.\nFeuille $k\n";
foreach ($data['cells'] as $idRow => $row) {
foreach ($row as $idCol => $cell) {
echo $this->getValeur($idRow, $idCol)."\t";
}
echo "\n";
}
}
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/VerificateurDonnees.php
New file
0,0 → 1,135
<?php
/**
*
* regroupement de fonctions de vérification des fichiers de données .tsv qui créé des fichiers log
* les classes qui vérifie des données pour des projets peuvent l'étendre
* @author mathilde
*
*/
abstract class VerificateurDonnees {
private $projet;
private $Message;
private $Conteneur;
private $ligne_num; //numéro de la ligne parcourue
private $log = ''; //texte du journal
protected $colonne_valeur; //valeur d'une colonne
protected $colonne_num; // numéro d'un colonne
private $nb_erreurs = 0; // nombre total
private $erreurs_ligne; // consigne les erreurs d'une ligne : $erreurs_ligne[$num_col] = $valeur_erronnee
 
public function __construct(Conteneur $conteneur, $projet) {
$this->Conteneur = $conteneur;
$this->Message = $this->Conteneur->getMessages();
$this->projet = $projet;
}
 
/**
*
* fonction principale qui parcourt chaque ligne du fichier pour en vérifier la cohérence
* et déclenche l'écriture du fichier log
* @param chaine, nom du fichier de données à vérifier
*/
public function verifierFichier($fichierDonnees){
$lignes = file($fichierDonnees, FILE_IGNORE_NEW_LINES);
if ($lignes != false) {
foreach ($lignes as $this->ligne_num => $ligne) {
$this->verifierErreursLigne($ligne);
$this->Message->afficherAvancement("Vérification des lignes");
}
echo "\n";
} else {
$this->Message->traiterErreur("Le fichier $fichierDonnees ne peut pas être ouvert.");
}
if ($this->nb_erreurs == 0) {
$this->ajouterAuLog("Il n'y a pas d'erreurs.");
}
$this->Message->traiterInfo($this->nb_erreurs." erreurs");
$this->ecrireFichierLog();
return $this->nb_erreurs;
}
/**
*
* découpe une ligne en colonnes pour en vérifier le contenu
* @param chaine, une ligne du fichier
*/
private function verifierErreursLigne($ligne){
$this->erreurs_ligne = array();
$colonnes = explode("\t", $ligne);
if (isset($colonnes)) {
foreach ($colonnes as $this->colonne_num => $this->colonne_valeur) {
$this->definirTraitementsColonnes();
}
} else {
$message = "Ligne {$this->ligne_num} : pas de tabulation";
$this->ajouterAuLog($message);
}
$this->consignerErreursLigne();
}
/**
*
* pour le traitement spécifique colonne par colonne
*
*/
 
abstract protected function definirTraitementsColonnes();
/**
*
* note dans le log s'il y a des erreurs dans une ligne
*/
private function consignerErreursLigne() {
$nbreErreursLigne = count($this->erreurs_ligne);
$this->nb_erreurs += $nbreErreursLigne;
if ($nbreErreursLigne != 0) {
$this->ajouterAuLog("Erreurs sur la ligne {$this->ligne_num}");
$ligneLog = '';
foreach ($this->erreurs_ligne as $cle => $v){
$ligneLog .= "colonne $cle : $v - ";
}
$this->ajouterAuLog($ligneLog);
}
}
/**
* garde la trace d'une erreur dans une ligne
*
*/
protected function noterErreur() {
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur;
}
//+------------------------------------------------------------------------------------------------------+
// Gestion du Log
private function ajouterAuLog($txt) {
$this->log .= "$txt\n";
}
private function ecrireFichierLog() {
$base = Config::get('chemin_scripts');
$fichierLog = $base.'/modules/'.$this->projet.'/log/verification.log';
file_put_contents($fichierLog, $this->log);
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/Messages.php
New file
0,0 → 1,125
<?php
class Messages {
/** Niveau de message de type LOG */
const MSG_LOG = 0;
/** Niveau de message de type ERREUR */
const MSG_ERREUR = 1;
/** Niveau de message de type AVERTISSEMENT */
const MSG_AVERTISSEMENT = 2;
/** Niveau de message de type INFORMATION */
const MSG_INFO = 3;
 
/** Inititulé des différents types de message. */
private static $msg_niveaux_txt = array('LOG', 'ERREUR','AVERTISSEMENT', 'INFO');
private $verbosite = '';
 
public function __construct($verbosite = 0) {
$this->verbosite = $verbosite;
}
 
/**
* Affiche un message d'erreur formaté.
* Si le paramétre de verbosité (-v) vaut 1 ou plus, le message est écrit dans le fichier de log et afficher dans la console.
*
* @param string le message d'erreur avec des %s.
* @param array le tableau des paramêtres à insérer dans le message d'erreur.
* @return void.
*/
public function traiterErreur($message, $tab_arguments = array()) {
$this->traiterMessage($message, $tab_arguments, self::MSG_ERREUR);
}
 
/**
* Affiche un message d'avertissement formaté.
* Si le paramétre de verbosité (-v) vaut 1, le message est écrit dans le fichier de log.
* Si le paramétre de verbosité (-v) vaut 2 ou plus, le message est écrit dans le fichier de log et afficher dans la console.
*
* @param string le message d'erreur avec des %s.
* @param array le tableau des paramêtres à insérer dans le message d'erreur.
* @return void.
*/
public function traiterAvertissement($message, $tab_arguments = array()) {
$this->traiterMessage($message, $tab_arguments, self::MSG_AVERTISSEMENT);
}
 
/**
* Retourne un message d'information formaté.
* Si le paramétre de verbosité (-v) vaut 1 ou 2 , le message est écrit dans le fichier de log.
* Si le paramétre de verbosité (-v) vaut 3 ou plus, le message est écrit dans le fichier de log et afficher dans la console.
*
* @param string le message d'information avec des %s.
* @param array le tableau des paramêtres à insérer dans le message d'erreur.
* @return void.
*/
public function traiterInfo($message, $tab_arguments = array()) {
$this->traiterMessage($message, $tab_arguments, self::MSG_INFO);
}
 
/**
* Retourne un message formaté en le stockant dans un fichier de log si nécessaire.
*
* @param string le message d'erreur avec des %s.
* @param array le tableau des paramêtres à insérer dans le message d'erreur.
* @param int le niveau de verbosité à dépasser pour afficher les messages.
* @return void.
*/
private function traiterMessage($message, $tab_arguments, $niveau = self::MSG_LOG) {
$log = $this->formaterMsg($message, $tab_arguments, $niveau);
if ($this->verbosite > ($niveau - 1)) {
echo $log;
if (Config::get('log_script')) {
// TODO : lancer le log
}
}
}
 
/**
* Retourne un message d'information formaté.
*
* @param string le message d'information avec des %s.
* @param array le tableau des paramêtres à insérer dans le message d'erreur.
* @return string le message d'erreur formaté.
*/
public function formaterMsg($message, $tab_arguments = array(), $niveau = null) {
$texte = vsprintf($message, $tab_arguments);
$prefixe = date('Y-m-j_H:i:s', time());
$prefixe .= is_null($niveau) ? ' : ' : ' - '.self::getMsgNiveauTxt($niveau).' : ';
$log = $prefixe.$texte."\n";
return $log;
}
 
private static function getMsgNiveauTxt($niveau) {
return self::$msg_niveaux_txt[$niveau];
}
 
/**
* Utiliser cette méthode dans une boucle pour afficher un message suivi du nombre de tour de boucle effectué.
* Vous devrez vous même gérer le retour à la ligne à la sortie de la boucle.
*
* @param string le message d'information.
* @param int le nombre de départ à afficher.
* @return void le message est affiché dans la console.
*/
public static function afficherAvancement($message, $depart = 0) {
static $avancement = array();
if (! array_key_exists($message, $avancement)) {
$avancement[$message] = $depart;
echo "$message : ";
 
$actuel =& $avancement[$message];
echo $actuel++;
} else {
$actuel =& $avancement[$message];
 
// Cas du passage de 99 (= 2 caractères) à 100 (= 3 caractères)
$passage = 0;
if (strlen((string) ($actuel - 1)) < strlen((string) ($actuel))) {
$passage = 1;
}
 
echo str_repeat(chr(8), (strlen((string) $actuel) - $passage));
echo $actuel++;
}
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/EfloreCommun.php
New file
0,0 → 1,66
<?php
/**
*
* fonctions
* @author mathilde
*
*/
class EfloreCommun {
 
private $Conteneur = null;
private $Bdd = null;
private $projetNom = '';
private $scriptChemin = '';
 
public function __construct($conteneur) {
$this->Conteneur = $conteneur;
$this->Bdd = $this->Conteneur->getBdd();
}
 
public function initialiserProjet($projetNom) {
$this->projetNom = $projetNom;
$this->chargerConfigDuProjet();
}
 
//+------------------------------------------------------------------------------------------------------+
// Méthodes communes aux projets d'eFlore
 
public function chargerConfigDuProjet() {
$scriptChemin = $this->Conteneur->getParametre('scriptChemin');
$fichierIni = $scriptChemin.$this->projetNom.'.ini';
if (file_exists($fichierIni)) {
Config::charger($fichierIni);
} else {
$m = "Veuillez configurer le projet en créant le fichier '{$this->projetNom}.ini' ".
"dans le dossier du module de script du projet à partir du fichier '{$this->projetNom}.defaut.ini'.";
throw new Exception($m);
}
}
 
//changée
public function chargerStructureSql() {
$this->chargerFichierSql('chemins.structureSql');
}
 
public function chargerFichierSql($param_chemin) {
$fichierStructureSql = $this->Conteneur->getParametre($param_chemin);
$contenuSql = $this->recupererContenu($fichierStructureSql);
$this->executerScriptSql($contenuSql);
}
 
public function executerScriptSql($sql) {
$requetes = Outils::extraireRequetes($sql);
foreach ($requetes as $requete) {
$this->Bdd->requeter($requete);
}
}
 
public function recupererContenu($chemin) {
$contenu = file_get_contents($chemin);
if ($contenu === false){
throw new Exception("Impossible d'ouvrir le fichier SQL : $chemin");
}
return $contenu;
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/excel_reader/excel_reader2.php
New file
0,0 → 1,1610
<?php
/**
* A class for reading Microsoft Excel (97/2003) Spreadsheets.
*
* Version 2.22
*
* Enhanced and maintained by Alex Frenkel < excell2@frenkel-online.com >
* Maintained at http://code.google.com/p/php-excel-reader2/
*
* Previosly mantained by Matt Kruse < http://mattkruse.com >
* Maintained at http://code.google.com/p/php-excel-reader/
*
* Format parsing and MUCH more contributed by:
* Matt Roxburgh < http://www.roxburgh.me.uk >
*
* DOCUMENTATION
* =============
* http://code.google.com/p/php-excel-reader2/wiki/Documentation
*
* CHANGE LOG
* ==========
* http://code.google.com/p/php-excel-reader2/wiki/ChangeHistory
*
*
* --------------------------------------------------------------------------
*
* Originally developed by Vadim Tkachenko under the name PHPExcelReader.
* (http://sourceforge.net/projects/phpexcelreader)
* Based on the Java version by Andy Khan (http://www.andykhan.com). Now
* maintained by David Sanders. Reads only Biff 7 and Biff 8 formats.
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category Spreadsheet
* @package Spreadsheet_Excel_Reader
* @author Vadim Tkachenko <vt@apachephp.com>
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id: reader.php 19 2007-03-13 12:42:41Z shangxiao $
* @link http://pear.php.net/package/Spreadsheet_Excel_Reader
* @see OLE, Spreadsheet_Excel_Writer
* --------------------------------------------------------------------------
*/
 
define ( 'NUM_BIG_BLOCK_DEPOT_BLOCKS_POS', 0x2c );
define ( 'SMALL_BLOCK_DEPOT_BLOCK_POS', 0x3c );
define ( 'ROOT_START_BLOCK_POS', 0x30 );
define ( 'BIG_BLOCK_SIZE', 0x200 );
define ( 'SMALL_BLOCK_SIZE', 0x40 );
define ( 'EXTENSION_BLOCK_POS', 0x44 );
define ( 'NUM_EXTENSION_BLOCK_POS', 0x48 );
define ( 'PROPERTY_STORAGE_BLOCK_SIZE', 0x80 );
define ( 'BIG_BLOCK_DEPOT_BLOCKS_POS', 0x4c );
define ( 'SMALL_BLOCK_THRESHOLD', 0x1000 );
// property storage offsets
define ( 'SIZE_OF_NAME_POS', 0x40 );
define ( 'TYPE_POS', 0x42 );
define ( 'START_BLOCK_POS', 0x74 );
define ( 'SIZE_POS', 0x78 );
define ( 'IDENTIFIER_OLE', pack ( "CCCCCCCC", 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1 ) );
 
function GetInt4d($data, $pos) {
$value = ord ( $data [$pos] ) | (ord ( $data [$pos + 1] ) << 8) | (ord ( $data [$pos + 2] ) << 16) | (ord ( $data [$pos + 3] ) << 24);
if ($value >= 4294967294) {
$value = - 2;
}
return $value;
}
 
// http://uk.php.net/manual/en/function.getdate.php
function gmgetdate($ts = null) {
$k = array ('seconds', 'minutes', 'hours', 'mday', 'wday', 'mon', 'year', 'yday', 'weekday', 'month', 0 );
return (array_comb ( $k, explode ( ":", gmdate ( 's:i:G:j:w:n:Y:z:l:F:U', is_null ( $ts ) ? time () : $ts ) ) ));
}
 
// Added for PHP4 compatibility
function array_comb($array1, $array2) {
$out = array ();
foreach ( $array1 as $key => $value ) {
$out [$value] = $array2 [$key];
}
return $out;
}
 
function v($data, $pos) {
return ord ( $data [$pos] ) | ord ( $data [$pos + 1] ) << 8;
}
 
class OLERead {
var $data = '';
function OLERead() {
}
function read($sFileName) {
// check if file exist and is readable (Darko Miljanovic)
if (! is_readable ( $sFileName )) {
$this->error = 1;
return false;
}
$this->data = @file_get_contents ( $sFileName );
if (! $this->data) {
$this->error = 1;
return false;
}
if (substr ( $this->data, 0, 8 ) != IDENTIFIER_OLE) {
$this->error = 1;
return false;
}
$this->numBigBlockDepotBlocks = GetInt4d ( $this->data, NUM_BIG_BLOCK_DEPOT_BLOCKS_POS );
$this->sbdStartBlock = GetInt4d ( $this->data, SMALL_BLOCK_DEPOT_BLOCK_POS );
$this->rootStartBlock = GetInt4d ( $this->data, ROOT_START_BLOCK_POS );
$this->extensionBlock = GetInt4d ( $this->data, EXTENSION_BLOCK_POS );
$this->numExtensionBlocks = GetInt4d ( $this->data, NUM_EXTENSION_BLOCK_POS );
$bigBlockDepotBlocks = array ();
$pos = BIG_BLOCK_DEPOT_BLOCKS_POS;
$bbdBlocks = $this->numBigBlockDepotBlocks;
if ($this->numExtensionBlocks != 0) {
$bbdBlocks = (BIG_BLOCK_SIZE - BIG_BLOCK_DEPOT_BLOCKS_POS) / 4;
}
for($i = 0; $i < $bbdBlocks; $i ++) {
$bigBlockDepotBlocks [$i] = GetInt4d ( $this->data, $pos );
$pos += 4;
}
for($j = 0; $j < $this->numExtensionBlocks; $j ++) {
$pos = ($this->extensionBlock + 1) * BIG_BLOCK_SIZE;
$blocksToRead = min ( $this->numBigBlockDepotBlocks - $bbdBlocks, BIG_BLOCK_SIZE / 4 - 1 );
for($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; $i ++) {
$bigBlockDepotBlocks [$i] = GetInt4d ( $this->data, $pos );
$pos += 4;
}
$bbdBlocks += $blocksToRead;
if ($bbdBlocks < $this->numBigBlockDepotBlocks) {
$this->extensionBlock = GetInt4d ( $this->data, $pos );
}
}
// readBigBlockDepot
$pos = 0;
$index = 0;
$this->bigBlockChain = array ();
for($i = 0; $i < $this->numBigBlockDepotBlocks; $i ++) {
$pos = ($bigBlockDepotBlocks [$i] + 1) * BIG_BLOCK_SIZE;
//echo "pos = $pos";
for($j = 0; $j < BIG_BLOCK_SIZE / 4; $j ++) {
$this->bigBlockChain [$index] = GetInt4d ( $this->data, $pos );
$pos += 4;
$index ++;
}
}
// readSmallBlockDepot();
$pos = 0;
$index = 0;
$sbdBlock = $this->sbdStartBlock;
$this->smallBlockChain = array ();
while ( $sbdBlock != - 2 ) {
$pos = ($sbdBlock + 1) * BIG_BLOCK_SIZE;
for($j = 0; $j < BIG_BLOCK_SIZE / 4; $j ++) {
$this->smallBlockChain [$index] = GetInt4d ( $this->data, $pos );
$pos += 4;
$index ++;
}
$sbdBlock = $this->bigBlockChain [$sbdBlock];
}
// readData(rootStartBlock)
$block = $this->rootStartBlock;
$pos = 0;
$this->entry = $this->__readData ( $block );
$this->__readPropertySets ();
}
function __readData($bl) {
$block = $bl;
$pos = 0;
$data = '';
while ( $block != - 2 ) {
$pos = ($block + 1) * BIG_BLOCK_SIZE;
$data = $data . substr ( $this->data, $pos, BIG_BLOCK_SIZE );
$block = $this->bigBlockChain [$block];
}
return $data;
}
function __readPropertySets() {
$offset = 0;
while ( $offset < strlen ( $this->entry ) ) {
$d = substr ( $this->entry, $offset, PROPERTY_STORAGE_BLOCK_SIZE );
$nameSize = ord ( $d [SIZE_OF_NAME_POS] ) | (ord ( $d [SIZE_OF_NAME_POS + 1] ) << 8);
$type = ord ( $d [TYPE_POS] );
$startBlock = GetInt4d ( $d, START_BLOCK_POS );
$size = GetInt4d ( $d, SIZE_POS );
$name = '';
for($i = 0; $i < $nameSize; $i ++) {
$name .= $d [$i];
}
$name = str_replace ( "\x00", "", $name );
$this->props [] = array ('name' => $name, 'type' => $type, 'startBlock' => $startBlock, 'size' => $size );
if ((strtolower ( $name ) == "workbook") || (strtolower ( $name ) == "book")) {
$this->wrkbook = count ( $this->props ) - 1;
}
if ($name == "Root Entry") {
$this->rootentry = count ( $this->props ) - 1;
}
$offset += PROPERTY_STORAGE_BLOCK_SIZE;
}
}
function getWorkBook() {
if ($this->props [$this->wrkbook] ['size'] < SMALL_BLOCK_THRESHOLD) {
$rootdata = $this->__readData ( $this->props [$this->rootentry] ['startBlock'] );
$streamData = '';
$block = $this->props [$this->wrkbook] ['startBlock'];
$pos = 0;
while ( $block != - 2 ) {
$pos = $block * SMALL_BLOCK_SIZE;
$streamData .= substr ( $rootdata, $pos, SMALL_BLOCK_SIZE );
$block = $this->smallBlockChain [$block];
}
return $streamData;
} else {
$numBlocks = $this->props [$this->wrkbook] ['size'] / BIG_BLOCK_SIZE;
if ($this->props [$this->wrkbook] ['size'] % BIG_BLOCK_SIZE != 0) {
$numBlocks ++;
}
if ($numBlocks == 0)
return '';
$streamData = '';
$block = $this->props [$this->wrkbook] ['startBlock'];
$pos = 0;
while ( $block != - 2 ) {
$pos = ($block + 1) * BIG_BLOCK_SIZE;
$streamData .= substr ( $this->data, $pos, BIG_BLOCK_SIZE );
$block = $this->bigBlockChain [$block];
}
return $streamData;
}
}
 
}
 
define ( 'SPREADSHEET_EXCEL_READER_BIFF8', 0x600 );
define ( 'SPREADSHEET_EXCEL_READER_BIFF7', 0x500 );
define ( 'SPREADSHEET_EXCEL_READER_WORKBOOKGLOBALS', 0x5 );
define ( 'SPREADSHEET_EXCEL_READER_WORKSHEET', 0x10 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_BOF', 0x809 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_EOF', 0x0a );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_BOUNDSHEET', 0x85 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_DIMENSION', 0x200 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_ROW', 0x208 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_DBCELL', 0xd7 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FILEPASS', 0x2f );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_NOTE', 0x1c );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_TXO', 0x1b6 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_RK', 0x7e );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_RK2', 0x27e );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_MULRK', 0xbd );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_MULBLANK', 0xbe );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_INDEX', 0x20b );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_SST', 0xfc );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_EXTSST', 0xff );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_CONTINUE', 0x3c );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_LABEL', 0x204 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_LABELSST', 0xfd );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_NUMBER', 0x203 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_NAME', 0x18 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_ARRAY', 0x221 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_STRING', 0x207 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FORMULA', 0x406 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FORMULA2', 0x6 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FORMAT', 0x41e );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_XF', 0xe0 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_BOOLERR', 0x205 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FONT', 0x0031 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_PALETTE', 0x0092 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_UNKNOWN', 0xffff );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_NINETEENFOUR', 0x22 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_MERGEDCELLS', 0xE5 );
define ( 'SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS', 25569 );
define ( 'SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS1904', 24107 );
define ( 'SPREADSHEET_EXCEL_READER_MSINADAY', 86400 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_HYPER', 0x01b8 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_COLINFO', 0x7d );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_DEFCOLWIDTH', 0x55 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_STANDARDWIDTH', 0x99 );
define ( 'SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT', "%s" );
 
/*
* Main Class
*/
class Spreadsheet_Excel_Reader {
// MK: Added to make data retrieval easier
var $colnames = array ();
var $colindexes = array ();
var $standardColWidth = 0;
var $defaultColWidth = 0;
function myHex($d) {
if ($d < 16)
return "0" . dechex ( $d );
return dechex ( $d );
}
function dumpHexData($data, $pos, $length) {
$info = "";
for($i = 0; $i <= $length; $i ++) {
$info .= ($i == 0 ? "" : " ") . $this->myHex ( ord ( $data [$pos + $i] ) ) . (ord ( $data [$pos + $i] ) > 31 ? "[" . $data [$pos + $i] . "]" : '');
}
return $info;
}
function getCol($col) {
if (is_string ( $col )) {
$col = strtolower ( $col );
if (array_key_exists ( $col, $this->colnames )) {
$col = $this->colnames [$col];
}
}
return $col;
}
// PUBLIC API FUNCTIONS
// --------------------
 
function val($row, $col, $sheet = 0) {
$col = $this->getCol ( $col );
if (array_key_exists ( $row, $this->sheets [$sheet] ['cells'] ) && array_key_exists ( $col, $this->sheets [$sheet] ['cells'] [$row] )) {
return $this->sheets [$sheet] ['cells'] [$row] [$col];
}
return "";
}
function value($row, $col, $sheet = 0) {
return $this->val ( $row, $col, $sheet );
}
function info($row, $col, $type = '', $sheet = 0) {
$col = $this->getCol ( $col );
if (array_key_exists ( 'cellsInfo', $this->sheets [$sheet] ) && array_key_exists ( $row, $this->sheets [$sheet] ['cellsInfo'] ) && array_key_exists ( $col, $this->sheets [$sheet] ['cellsInfo'] [$row] ) && array_key_exists ( $type, $this->sheets [$sheet] ['cellsInfo'] [$row] [$col] )) {
return $this->sheets [$sheet] ['cellsInfo'] [$row] [$col] [$type];
}
return "";
}
function type($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'type', $sheet );
}
function raw($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'raw', $sheet );
}
function rowspan($row, $col, $sheet = 0) {
$val = $this->info ( $row, $col, 'rowspan', $sheet );
if ($val == "") {
return 1;
}
return $val;
}
function colspan($row, $col, $sheet = 0) {
$val = $this->info ( $row, $col, 'colspan', $sheet );
if ($val == "") {
return 1;
}
return $val;
}
function hyperlink($row, $col, $sheet = 0) {
$link = $this->sheets [$sheet] ['cellsInfo'] [$row] [$col] ['hyperlink'];
if ($link) {
return $link ['link'];
}
return '';
}
function rowcount($sheet = 0) {
return $this->sheets [$sheet] ['numRows'];
}
function colcount($sheet = 0) {
return $this->sheets [$sheet] ['numCols'];
}
function colwidth($col, $sheet = 0) {
// Col width is actually the width of the number 0. So we have to estimate and come close
return $this->colInfo [$sheet] [$col] ['width'] / 9142 * 200;
}
function colhidden($col, $sheet = 0) {
return ! ! $this->colInfo [$sheet] [$col] ['hidden'];
}
function rowheight($row, $sheet = 0) {
return $this->rowInfo [$sheet] [$row] ['height'];
}
function rowhidden($row, $sheet = 0) {
return ! ! $this->rowInfo [$sheet] [$row] ['hidden'];
}
// GET THE CSS FOR FORMATTING
// ==========================
function style($row, $col, $sheet = 0, $properties = '') {
$css = "";
$font = $this->font ( $row, $col, $sheet );
if ($font != "") {
$css .= "font-family:$font;";
}
$align = $this->align ( $row, $col, $sheet );
if ($align != "") {
$css .= "text-align:$align;";
}
$height = $this->height ( $row, $col, $sheet );
if ($height != "") {
$css .= "font-size:$height" . "px;";
}
$bgcolor = $this->bgColor ( $row, $col, $sheet );
if ($bgcolor != "") {
$bgcolor = $this->colors [$bgcolor];
$css .= "background-color:$bgcolor;";
}
$color = $this->color ( $row, $col, $sheet );
if ($color != "") {
$css .= "color:$color;";
}
$bold = $this->bold ( $row, $col, $sheet );
if ($bold) {
$css .= "font-weight:bold;";
}
$italic = $this->italic ( $row, $col, $sheet );
if ($italic) {
$css .= "font-style:italic;";
}
$underline = $this->underline ( $row, $col, $sheet );
if ($underline) {
$css .= "text-decoration:underline;";
}
// Borders
$bLeft = $this->borderLeft ( $row, $col, $sheet );
$bRight = $this->borderRight ( $row, $col, $sheet );
$bTop = $this->borderTop ( $row, $col, $sheet );
$bBottom = $this->borderBottom ( $row, $col, $sheet );
$bLeftCol = $this->borderLeftColor ( $row, $col, $sheet );
$bRightCol = $this->borderRightColor ( $row, $col, $sheet );
$bTopCol = $this->borderTopColor ( $row, $col, $sheet );
$bBottomCol = $this->borderBottomColor ( $row, $col, $sheet );
// Try to output the minimal required style
if ($bLeft != "" && $bLeft == $bRight && $bRight == $bTop && $bTop == $bBottom) {
$css .= "border:" . $this->lineStylesCss [$bLeft] . ";";
} else {
if ($bLeft != "") {
$css .= "border-left:" . $this->lineStylesCss [$bLeft] . ";";
}
if ($bRight != "") {
$css .= "border-right:" . $this->lineStylesCss [$bRight] . ";";
}
if ($bTop != "") {
$css .= "border-top:" . $this->lineStylesCss [$bTop] . ";";
}
if ($bBottom != "") {
$css .= "border-bottom:" . $this->lineStylesCss [$bBottom] . ";";
}
}
// Only output border colors if there is an actual border specified
if ($bLeft != "" && $bLeftCol != "") {
$css .= "border-left-color:" . $bLeftCol . ";";
}
if ($bRight != "" && $bRightCol != "") {
$css .= "border-right-color:" . $bRightCol . ";";
}
if ($bTop != "" && $bTopCol != "") {
$css .= "border-top-color:" . $bTopCol . ";";
}
if ($bBottom != "" && $bBottomCol != "") {
$css .= "border-bottom-color:" . $bBottomCol . ";";
}
return $css;
}
// FORMAT PROPERTIES
// =================
function format($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'format', $sheet );
}
function formatIndex($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'formatIndex', $sheet );
}
function formatColor($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'formatColor', $sheet );
}
// CELL (XF) PROPERTIES
// ====================
function xfRecord($row, $col, $sheet = 0) {
$xfIndex = $this->info ( $row, $col, 'xfIndex', $sheet );
if ($xfIndex != "") {
return $this->xfRecords [$xfIndex];
}
return null;
}
function xfProperty($row, $col, $sheet, $prop) {
$xfRecord = $this->xfRecord ( $row, $col, $sheet );
if ($xfRecord != null) {
return $xfRecord [$prop];
}
return "";
}
function align($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'align' );
}
function bgColor($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'bgColor' );
}
function borderLeft($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'borderLeft' );
}
function borderRight($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'borderRight' );
}
function borderTop($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'borderTop' );
}
function borderBottom($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'borderBottom' );
}
function borderLeftColor($row, $col, $sheet = 0) {
return $this->colors [$this->xfProperty ( $row, $col, $sheet, 'borderLeftColor' )];
}
function borderRightColor($row, $col, $sheet = 0) {
return $this->colors [$this->xfProperty ( $row, $col, $sheet, 'borderRightColor' )];
}
function borderTopColor($row, $col, $sheet = 0) {
return $this->colors [$this->xfProperty ( $row, $col, $sheet, 'borderTopColor' )];
}
function borderBottomColor($row, $col, $sheet = 0) {
return $this->colors [$this->xfProperty ( $row, $col, $sheet, 'borderBottomColor' )];
}
// FONT PROPERTIES
// ===============
function fontRecord($row, $col, $sheet = 0) {
$xfRecord = $this->xfRecord ( $row, $col, $sheet );
if ($xfRecord != null) {
$font = $xfRecord ['fontIndex'];
if ($font != null) {
return $this->fontRecords [$font];
}
}
return null;
}
function fontProperty($row, $col, $sheet = 0, $prop) {
$font = $this->fontRecord ( $row, $col, $sheet );
if ($font != null) {
return $font [$prop];
}
return false;
}
function fontIndex($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'fontIndex' );
}
function color($row, $col, $sheet = 0) {
$formatColor = $this->formatColor ( $row, $col, $sheet );
if ($formatColor != "") {
return $formatColor;
}
$ci = $this->fontProperty ( $row, $col, $sheet, 'color' );
return $this->rawColor ( $ci );
}
function rawColor($ci) {
if (($ci != 0x7FFF) && ($ci != '')) {
return $this->colors [$ci];
}
return "";
}
function bold($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'bold' );
}
function italic($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'italic' );
}
function underline($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'under' );
}
function height($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'height' );
}
function font($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'font' );
}
// DUMP AN HTML TABLE OF THE ENTIRE XLS DATA
// =========================================
function dump($row_numbers = false, $col_letters = false, $sheet = 0, $table_class = 'excel') {
$out = "<table class=\"$table_class\" cellspacing=0>";
if ($col_letters) {
$out .= "<thead>\n\t<tr>";
if ($row_numbers) {
$out .= "\n\t\t<th>&nbsp</th>";
}
for($i = 1; $i <= $this->colcount ( $sheet ); $i ++) {
$style = "width:" . ($this->colwidth ( $i, $sheet ) * 1) . "px;";
if ($this->colhidden ( $i, $sheet )) {
$style .= "display:none;";
}
$out .= "\n\t\t<th style=\"$style\">" . strtoupper ( $this->colindexes [$i] ) . "</th>";
}
$out .= "</tr></thead>\n";
}
$out .= "<tbody>\n";
for($row = 1; $row <= $this->rowcount ( $sheet ); $row ++) {
$rowheight = $this->rowheight ( $row, $sheet );
$style = "height:" . ($rowheight * (4 / 3)) . "px;";
if ($this->rowhidden ( $row, $sheet )) {
$style .= "display:none;";
}
$out .= "\n\t<tr style=\"$style\">";
if ($row_numbers) {
$out .= "\n\t\t<th>$row</th>";
}
for($col = 1; $col <= $this->colcount ( $sheet ); $col ++) {
// Account for Rowspans/Colspans
$rowspan = $this->rowspan ( $row, $col, $sheet );
$colspan = $this->colspan ( $row, $col, $sheet );
for($i = 0; $i < $rowspan; $i ++) {
for($j = 0; $j < $colspan; $j ++) {
if ($i > 0 || $j > 0) {
$this->sheets [$sheet] ['cellsInfo'] [$row + $i] [$col + $j] ['dontprint'] = 1;
}
}
}
if (! $this->sheets [$sheet] ['cellsInfo'] [$row] [$col] ['dontprint']) {
$style = $this->style ( $row, $col, $sheet );
if ($this->colhidden ( $col, $sheet )) {
$style .= "display:none;";
}
$out .= "\n\t\t<td style=\"$style\"" . ($colspan > 1 ? " colspan=$colspan" : "") . ($rowspan > 1 ? " rowspan=$rowspan" : "") . ">";
$val = $this->val ( $row, $col, $sheet );
if ($val == '') {
$val = "&nbsp;";
} else {
$val = htmlentities ( $val, ENT_COMPAT, $this->_defaultEncoding );
$link = $this->hyperlink ( $row, $col, $sheet );
if ($link != '') {
$val = "<a href=\"$link\">$val</a>";
}
}
$out .= "<nobr>" . nl2br ( $val ) . "</nobr>";
$out .= "</td>";
}
}
$out .= "</tr>\n";
}
$out .= "</tbody></table>";
return $out;
}
// --------------
// END PUBLIC API
 
var $boundsheets = array ();
var $formatRecords = array ();
var $fontRecords = array ();
var $xfRecords = array ();
var $colInfo = array ();
var $rowInfo = array ();
var $sst = array ();
var $sheets = array ();
var $data;
var $_ole;
var $_defaultEncoding = "UTF-8";
var $_defaultFormat = SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT;
var $_columnsFormat = array ();
var $_rowoffset = 1;
var $_coloffset = 1;
/**
* List of default date formats used by Excel
*/
var $dateFormats = array (0xe => "m/d/Y", 0xf => "M-d-Y", 0x10 => "d-M", 0x11 => "M-Y", 0x12 => "h:i a", 0x13 => "h:i:s a", 0x14 => "H:i", 0x15 => "H:i:s", 0x16 => "d/m/Y H:i", 0x2d => "i:s", 0x2e => "H:i:s", 0x2f => "i:s.S" );
/**
* Default number formats used by Excel
*/
var $numberFormats = array (0x1 => "0", 0x2 => "0.00", 0x3 => "#,##0", 0x4 => "#,##0.00", 0x5 => "\$#,##0;(\$#,##0)", 0x6 => "\$#,##0;[Red](\$#,##0)", 0x7 => "\$#,##0.00;(\$#,##0.00)", 0x8 => "\$#,##0.00;[Red](\$#,##0.00)", 0x9 => "0%", 0xa => "0.00%", 0xb => "0.00E+00", 0x25 => "#,##0;(#,##0)", 0x26 => "#,##0;[Red](#,##0)", 0x27 => "#,##0.00;(#,##0.00)", 0x28 => "#,##0.00;[Red](#,##0.00)", 0x29 => "#,##0;(#,##0)", // Not exactly
0x2a => "\$#,##0;(\$#,##0)", // Not exactly
0x2b => "#,##0.00;(#,##0.00)", // Not exactly
0x2c => "\$#,##0.00;(\$#,##0.00)", // Not exactly
0x30 => "##0.0E+0" );
var $colors = Array (0x00 => "#000000", 0x01 => "#FFFFFF", 0x02 => "#FF0000", 0x03 => "#00FF00", 0x04 => "#0000FF", 0x05 => "#FFFF00", 0x06 => "#FF00FF", 0x07 => "#00FFFF", 0x08 => "#000000", 0x09 => "#FFFFFF", 0x0A => "#FF0000", 0x0B => "#00FF00", 0x0C => "#0000FF", 0x0D => "#FFFF00", 0x0E => "#FF00FF", 0x0F => "#00FFFF", 0x10 => "#800000", 0x11 => "#008000", 0x12 => "#000080", 0x13 => "#808000", 0x14 => "#800080", 0x15 => "#008080", 0x16 => "#C0C0C0", 0x17 => "#808080", 0x18 => "#9999FF", 0x19 => "#993366", 0x1A => "#FFFFCC", 0x1B => "#CCFFFF", 0x1C => "#660066", 0x1D => "#FF8080", 0x1E => "#0066CC", 0x1F => "#CCCCFF", 0x20 => "#000080", 0x21 => "#FF00FF", 0x22 => "#FFFF00", 0x23 => "#00FFFF", 0x24 => "#800080", 0x25 => "#800000", 0x26 => "#008080", 0x27 => "#0000FF", 0x28 => "#00CCFF", 0x29 => "#CCFFFF", 0x2A => "#CCFFCC", 0x2B => "#FFFF99", 0x2C => "#99CCFF", 0x2D => "#FF99CC", 0x2E => "#CC99FF", 0x2F => "#FFCC99", 0x30 => "#3366FF", 0x31 => "#33CCCC", 0x32 => "#99CC00", 0x33 => "#FFCC00", 0x34 => "#FF9900", 0x35 => "#FF6600", 0x36 => "#666699", 0x37 => "#969696", 0x38 => "#003366", 0x39 => "#339966", 0x3A => "#003300", 0x3B => "#333300", 0x3C => "#993300", 0x3D => "#993366", 0x3E => "#333399", 0x3F => "#333333", 0x40 => "#000000", 0x41 => "#FFFFFF",
 
0x43 => "#000000", 0x4D => "#000000", 0x4E => "#FFFFFF", 0x4F => "#000000", 0x50 => "#FFFFFF", 0x51 => "#000000",
 
0x7FFF => "#000000" );
var $lineStyles = array (0x00 => "", 0x01 => "Thin", 0x02 => "Medium", 0x03 => "Dashed", 0x04 => "Dotted", 0x05 => "Thick", 0x06 => "Double", 0x07 => "Hair", 0x08 => "Medium dashed", 0x09 => "Thin dash-dotted", 0x0A => "Medium dash-dotted", 0x0B => "Thin dash-dot-dotted", 0x0C => "Medium dash-dot-dotted", 0x0D => "Slanted medium dash-dotted" );
var $lineStylesCss = array ("Thin" => "1px solid", "Medium" => "2px solid", "Dashed" => "1px dashed", "Dotted" => "1px dotted", "Thick" => "3px solid", "Double" => "double", "Hair" => "1px solid", "Medium dashed" => "2px dashed", "Thin dash-dotted" => "1px dashed", "Medium dash-dotted" => "2px dashed", "Thin dash-dot-dotted" => "1px dashed", "Medium dash-dot-dotted" => "2px dashed", "Slanted medium dash-dotte" => "2px dashed" );
function read16bitstring($data, $start) {
$len = 0;
while ( ord ( $data [$start + $len] ) + ord ( $data [$start + $len + 1] ) > 0 )
$len ++;
return substr ( $data, $start, $len );
}
// ADDED by Matt Kruse for better formatting
function _format_value($format, $num, $f) {
// 49==TEXT format
// http://code.google.com/p/php-excel-reader/issues/detail?id=7
if ((! $f && $format == "%s") || ($f == 49) || ($format == "GENERAL")) {
return array ('string' => $num, 'formatColor' => null );
}
// Custom pattern can be POSITIVE;NEGATIVE;ZERO
// The "text" option as 4th parameter is not handled
$parts = explode ( ";", $format );
$pattern = $parts [0];
// Negative pattern
if (count ( $parts ) > 2 && $num == 0) {
$pattern = $parts [2];
}
// Zero pattern
if (count ( $parts ) > 1 && $num < 0) {
$pattern = $parts [1];
$num = abs ( $num );
}
$color = "";
$matches = array ();
$color_regex = "/^\[(BLACK|BLUE|CYAN|GREEN|MAGENTA|RED|WHITE|YELLOW)\]/i";
if (preg_match ( $color_regex, $pattern, $matches )) {
$color = strtolower ( $matches [1] );
$pattern = preg_replace ( $color_regex, "", $pattern );
}
// In Excel formats, "_" is used to add spacing, which we can't do in HTML
$pattern = preg_replace ( "/_./", "", $pattern );
// Some non-number characters are escaped with \, which we don't need
$pattern = preg_replace ( "/\\\/", "", $pattern );
// Some non-number strings are quoted, so we'll get rid of the quotes
$pattern = preg_replace ( "/\"/", "", $pattern );
// TEMPORARY - Convert # to 0
$pattern = preg_replace ( "/\#/", "0", $pattern );
// Find out if we need comma formatting
$has_commas = preg_match ( "/,/", $pattern );
if ($has_commas) {
$pattern = preg_replace ( "/,/", "", $pattern );
}
// Handle Percentages
if (preg_match ( "/\d(\%)([^\%]|$)/", $pattern, $matches )) {
$num = $num * 100;
$pattern = preg_replace ( "/(\d)(\%)([^\%]|$)/", "$1%$3", $pattern );
}
// Handle the number itself
$number_regex = "/(\d+)(\.?)(\d*)/";
if (preg_match ( $number_regex, $pattern, $matches )) {
$left = $matches [1];
$dec = $matches [2];
$right = $matches [3];
if ($has_commas) {
$formatted = number_format ( $num, strlen ( $right ) );
} else {
$sprintf_pattern = "%1." . strlen ( $right ) . "f";
$formatted = sprintf ( $sprintf_pattern, $num );
}
$pattern = preg_replace ( $number_regex, $formatted, $pattern );
}
return array ('string' => $pattern, 'formatColor' => $color );
}
/**
* Constructor
*
* Some basic initialisation
*/
function Spreadsheet_Excel_Reader($file = '', $store_extended_info = true, $outputEncoding = '') {
$this->_ole = new OLERead ( );
$this->setUTFEncoder ( 'iconv' );
if ($outputEncoding != '') {
$this->setOutputEncoding ( $outputEncoding );
}
for($i = 1; $i < 245; $i ++) {
$name = strtolower ( ((($i - 1) / 26 >= 1) ? chr ( ($i - 1) / 26 + 64 ) : '') . chr ( ($i - 1) % 26 + 65 ) );
$this->colnames [$name] = $i;
$this->colindexes [$i] = $name;
}
$this->store_extended_info = $store_extended_info;
if ($file != "") {
$this->read ( $file );
}
}
/**
* Set the encoding method
*/
function setOutputEncoding($encoding) {
$this->_defaultEncoding = $encoding;
}
/**
* $encoder = 'iconv' or 'mb'
* set iconv if you would like use 'iconv' for encode UTF-16LE to your encoding
* set mb if you would like use 'mb_convert_encoding' for encode UTF-16LE to your encoding
*/
function setUTFEncoder($encoder = 'iconv') {
$this->_encoderFunction = '';
if ($encoder == 'iconv') {
$this->_encoderFunction = function_exists ( 'iconv' ) ? 'iconv' : '';
} elseif ($encoder == 'mb') {
$this->_encoderFunction = function_exists ( 'mb_convert_encoding' ) ? 'mb_convert_encoding' : '';
}
}
function setRowColOffset($iOffset) {
$this->_rowoffset = $iOffset;
$this->_coloffset = $iOffset;
}
/**
* Set the default number format
*/
function setDefaultFormat($sFormat) {
$this->_defaultFormat = $sFormat;
}
/**
* Force a column to use a certain format
*/
function setColumnFormat($column, $sFormat) {
$this->_columnsFormat [$column] = $sFormat;
}
/**
* Read the spreadsheet file using OLE, then parse
*/
function read($sFileName) {
$res = $this->_ole->read ( $sFileName );
// oops, something goes wrong (Darko Miljanovic)
if ($res === false) {
// check error code
if ($this->_ole->error == 1) {
// bad file
die ( 'The filename ' . $sFileName . ' is not readable' );
}
// check other error codes here (eg bad fileformat, etc...)
}
$this->data = $this->_ole->getWorkBook ();
$this->_parse ();
}
/**
* Parse a workbook
*
* @access private
* @return bool
*/
function _parse() {
$pos = 0;
$data = $this->data;
$code = v ( $data, $pos );
$length = v ( $data, $pos + 2 );
$version = v ( $data, $pos + 4 );
$substreamType = v ( $data, $pos + 6 );
$this->version = $version;
if (($version != SPREADSHEET_EXCEL_READER_BIFF8) && ($version != SPREADSHEET_EXCEL_READER_BIFF7)) {
return false;
}
if ($substreamType != SPREADSHEET_EXCEL_READER_WORKBOOKGLOBALS) {
return false;
}
$pos += $length + 4;
$code = v ( $data, $pos );
$length = v ( $data, $pos + 2 );
while ( $code != SPREADSHEET_EXCEL_READER_TYPE_EOF ) {
switch ($code) {
case SPREADSHEET_EXCEL_READER_TYPE_SST :
$spos = $pos + 4;
$limitpos = $spos + $length;
$uniqueStrings = $this->_GetInt4d ( $data, $spos + 4 );
$spos += 8;
for($i = 0; $i < $uniqueStrings; $i ++) {
// Read in the number of characters
if ($spos == $limitpos) {
$opcode = v ( $data, $spos );
$conlength = v ( $data, $spos + 2 );
if ($opcode != 0x3c) {
return - 1;
}
$spos += 4;
$limitpos = $spos + $conlength;
}
$numChars = ord ( $data [$spos] ) | (ord ( $data [$spos + 1] ) << 8);
$spos += 2;
$optionFlags = ord ( $data [$spos] );
$spos ++;
$asciiEncoding = (($optionFlags & 0x01) == 0);
$extendedString = (($optionFlags & 0x04) != 0);
// See if string contains formatting information
$richString = (($optionFlags & 0x08) != 0);
if ($richString) {
// Read in the crun
$formattingRuns = v ( $data, $spos );
$spos += 2;
}
if ($extendedString) {
// Read in cchExtRst
$extendedRunLength = $this->_GetInt4d ( $data, $spos );
$spos += 4;
}
$len = ($asciiEncoding) ? $numChars : $numChars * 2;
if ($spos + $len < $limitpos) {
$retstr = substr ( $data, $spos, $len );
$spos += $len;
} else {
// found countinue
$retstr = substr ( $data, $spos, $limitpos - $spos );
$bytesRead = $limitpos - $spos;
$charsLeft = $numChars - (($asciiEncoding) ? $bytesRead : ($bytesRead / 2));
$spos = $limitpos;
while ( $charsLeft > 0 ) {
$opcode = v ( $data, $spos );
$conlength = v ( $data, $spos + 2 );
if ($opcode != 0x3c) {
return - 1;
}
$spos += 4;
$limitpos = $spos + $conlength;
$option = ord ( $data [$spos] );
$spos += 1;
if ($asciiEncoding && ($option == 0)) {
$len = min ( $charsLeft, $limitpos - $spos ); // min($charsLeft, $conlength);
$retstr .= substr ( $data, $spos, $len );
$charsLeft -= $len;
$asciiEncoding = true;
} elseif (! $asciiEncoding && ($option != 0)) {
$len = min ( $charsLeft * 2, $limitpos - $spos ); // min($charsLeft, $conlength);
$retstr .= substr ( $data, $spos, $len );
$charsLeft -= $len / 2;
$asciiEncoding = false;
} elseif (! $asciiEncoding && ($option == 0)) {
// Bummer - the string starts off as Unicode, but after the
// continuation it is in straightforward ASCII encoding
$len = min ( $charsLeft, $limitpos - $spos ); // min($charsLeft, $conlength);
for($j = 0; $j < $len; $j ++) {
$retstr .= $data [$spos + $j] . chr ( 0 );
}
$charsLeft -= $len;
$asciiEncoding = false;
} else {
$newstr = '';
for($j = 0; $j < strlen ( $retstr ); $j ++) {
$newstr = $retstr [$j] . chr ( 0 );
}
$retstr = $newstr;
$len = min ( $charsLeft * 2, $limitpos - $spos ); // min($charsLeft, $conlength);
$retstr .= substr ( $data, $spos, $len );
$charsLeft -= $len / 2;
$asciiEncoding = false;
}
$spos += $len;
}
}
if ($asciiEncoding)
$retstr = preg_replace ( "/(.)/s", "$1\0", $retstr );
$retstr = $this->_encodeUTF16 ( $retstr );
if ($richString) {
$spos += 4 * $formattingRuns;
}
// For extended strings, skip over the extended string data
if ($extendedString) {
$spos += $extendedRunLength;
}
$this->sst [] = $retstr;
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_FILEPASS :
return false;
break;
case SPREADSHEET_EXCEL_READER_TYPE_NAME :
break;
case SPREADSHEET_EXCEL_READER_TYPE_FORMAT :
$indexCode = v ( $data, $pos + 4 );
if ($version == SPREADSHEET_EXCEL_READER_BIFF8) {
$numchars = v ( $data, $pos + 6 );
if (ord ( $data [$pos + 8] ) == 0) {
$formatString = substr ( $data, $pos + 9, $numchars );
} else {
$formatString = substr ( $data, $pos + 9, $numchars * 2 );
}
} else {
$numchars = ord ( $data [$pos + 6] );
$formatString = substr ( $data, $pos + 7, $numchars * 2 );
}
$this->formatRecords [$indexCode] = $formatString;
break;
case SPREADSHEET_EXCEL_READER_TYPE_FONT :
$height = v ( $data, $pos + 4 );
$option = v ( $data, $pos + 6 );
$color = v ( $data, $pos + 8 );
$weight = v ( $data, $pos + 10 );
$under = ord ( $data [$pos + 14] );
$font = "";
// Font name
$numchars = ord ( $data [$pos + 18] );
if ((ord ( $data [$pos + 19] ) & 1) == 0) {
$font = substr ( $data, $pos + 20, $numchars );
} else {
$font = substr ( $data, $pos + 20, $numchars * 2 );
$font = $this->_encodeUTF16 ( $font );
}
$this->fontRecords [] = array ('height' => $height / 20, 'italic' => ! ! ($option & 2), 'color' => $color, 'under' => ! ($under == 0), 'bold' => ($weight == 700), 'font' => $font, 'raw' => $this->dumpHexData ( $data, $pos + 3, $length ) );
break;
case SPREADSHEET_EXCEL_READER_TYPE_PALETTE :
$colors = ord ( $data [$pos + 4] ) | ord ( $data [$pos + 5] ) << 8;
for($coli = 0; $coli < $colors; $coli ++) {
$colOff = $pos + 2 + ($coli * 4);
$colr = ord ( $data [$colOff] );
$colg = ord ( $data [$colOff + 1] );
$colb = ord ( $data [$colOff + 2] );
$this->colors [0x07 + $coli] = '#' . $this->myhex ( $colr ) . $this->myhex ( $colg ) . $this->myhex ( $colb );
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_XF :
$fontIndexCode = (ord ( $data [$pos + 4] ) | ord ( $data [$pos + 5] ) << 8) - 1;
$fontIndexCode = max ( 0, $fontIndexCode );
$indexCode = ord ( $data [$pos + 6] ) | ord ( $data [$pos + 7] ) << 8;
$alignbit = ord ( $data [$pos + 10] ) & 3;
$bgi = (ord ( $data [$pos + 22] ) | ord ( $data [$pos + 23] ) << 8) & 0x3FFF;
$bgcolor = ($bgi & 0x7F);
// $bgcolor = ($bgi & 0x3f80) >> 7;
$align = "";
if ($alignbit == 3) {
$align = "right";
}
if ($alignbit == 2) {
$align = "center";
}
$fillPattern = (ord ( $data [$pos + 21] ) & 0xFC) >> 2;
if ($fillPattern == 0) {
$bgcolor = "";
}
$xf = array ();
$xf ['formatIndex'] = $indexCode;
$xf ['align'] = $align;
$xf ['fontIndex'] = $fontIndexCode;
$xf ['bgColor'] = $bgcolor;
$xf ['fillPattern'] = $fillPattern;
$border = ord ( $data [$pos + 14] ) | (ord ( $data [$pos + 15] ) << 8) | (ord ( $data [$pos + 16] ) << 16) | (ord ( $data [$pos + 17] ) << 24);
$xf ['borderLeft'] = $this->lineStyles [($border & 0xF)];
$xf ['borderRight'] = $this->lineStyles [($border & 0xF0) >> 4];
$xf ['borderTop'] = $this->lineStyles [($border & 0xF00) >> 8];
$xf ['borderBottom'] = $this->lineStyles [($border & 0xF000) >> 12];
$xf ['borderLeftColor'] = ($border & 0x7F0000) >> 16;
$xf ['borderRightColor'] = ($border & 0x3F800000) >> 23;
$border = (ord ( $data [$pos + 18] ) | ord ( $data [$pos + 19] ) << 8);
$xf ['borderTopColor'] = ($border & 0x7F);
$xf ['borderBottomColor'] = ($border & 0x3F80) >> 7;
if (array_key_exists ( $indexCode, $this->dateFormats )) {
$xf ['type'] = 'date';
$xf ['format'] = $this->dateFormats [$indexCode];
if ($align == '') {
$xf ['align'] = 'right';
}
} elseif (array_key_exists ( $indexCode, $this->numberFormats )) {
$xf ['type'] = 'number';
$xf ['format'] = $this->numberFormats [$indexCode];
if ($align == '') {
$xf ['align'] = 'right';
}
} else {
$isdate = FALSE;
$formatstr = '';
if ($indexCode > 0) {
if (isset ( $this->formatRecords [$indexCode] ))
$formatstr = $this->formatRecords [$indexCode];
if ($formatstr != "") {
$tmp = preg_replace ( "/\;.*/", "", $formatstr );
$tmp = preg_replace ( "/^\[[^\]]*\]/", "", $tmp );
if (preg_match ( "/[^hmsday\/\-:\s\\\,AMP]/i", $tmp ) == 0) { // found day and time format
$isdate = TRUE;
$formatstr = $tmp;
$formatstr = str_replace ( array ('AM/PM', 'mmmm', 'mmm' ), array ('a', 'F', 'M' ), $formatstr );
// m/mm are used for both minutes and months - oh SNAP!
// This mess tries to fix for that.
// 'm' == minutes only if following h/hh or preceding s/ss
$formatstr = preg_replace ( "/(h:?)mm?/", "$1i", $formatstr );
$formatstr = preg_replace ( "/mm?(:?s)/", "i$1", $formatstr );
// A single 'm' = n in PHP
$formatstr = preg_replace ( "/(^|[^m])m([^m]|$)/", '$1n$2', $formatstr );
$formatstr = preg_replace ( "/(^|[^m])m([^m]|$)/", '$1n$2', $formatstr );
// else it's months
$formatstr = str_replace ( 'mm', 'm', $formatstr );
// Convert single 'd' to 'j'
$formatstr = preg_replace ( "/(^|[^d])d([^d]|$)/", '$1j$2', $formatstr );
$formatstr = str_replace ( array ('dddd', 'ddd', 'dd', 'yyyy', 'yy', 'hh', 'h' ), array ('l', 'D', 'd', 'Y', 'y', 'H', 'g' ), $formatstr );
$formatstr = preg_replace ( "/ss?/", 's', $formatstr );
}
}
}
if ($isdate) {
$xf ['type'] = 'date';
$xf ['format'] = $formatstr;
if ($align == '') {
$xf ['align'] = 'right';
}
} else {
// If the format string has a 0 or # in it, we'll assume it's a number
if (preg_match ( "/[0#]/", $formatstr )) {
$xf ['type'] = 'number';
if ($align == '') {
$xf ['align'] = 'right';
}
} else {
$xf ['type'] = 'other';
}
$xf ['format'] = $formatstr;
$xf ['code'] = $indexCode;
}
}
$this->xfRecords [] = $xf;
break;
case SPREADSHEET_EXCEL_READER_TYPE_NINETEENFOUR :
$this->nineteenFour = (ord ( $data [$pos + 4] ) == 1);
break;
case SPREADSHEET_EXCEL_READER_TYPE_BOUNDSHEET :
$rec_offset = $this->_GetInt4d ( $data, $pos + 4 );
$rec_typeFlag = ord ( $data [$pos + 8] );
$rec_visibilityFlag = ord ( $data [$pos + 9] );
$rec_length = ord ( $data [$pos + 10] );
if ($version == SPREADSHEET_EXCEL_READER_BIFF8) {
$chartype = ord ( $data [$pos + 11] );
if ($chartype == 0) {
$rec_name = substr ( $data, $pos + 12, $rec_length );
} else {
$rec_name = $this->_encodeUTF16 ( substr ( $data, $pos + 12, $rec_length * 2 ) );
}
} elseif ($version == SPREADSHEET_EXCEL_READER_BIFF7) {
$rec_name = substr ( $data, $pos + 11, $rec_length );
}
$this->boundsheets [] = array ('name' => $rec_name, 'offset' => $rec_offset );
break;
}
$pos += $length + 4;
$code = ord ( $data [$pos] ) | ord ( $data [$pos + 1] ) << 8;
$length = ord ( $data [$pos + 2] ) | ord ( $data [$pos + 3] ) << 8;
}
foreach ( $this->boundsheets as $key => $val ) {
$this->sn = $key;
$this->_parsesheet ( $val ['offset'] );
}
return true;
}
/**
* Parse a worksheet
*/
function _parsesheet($spos) {
$cont = true;
$data = $this->data;
// read BOF
$code = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$length = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$version = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
$substreamType = ord ( $data [$spos + 6] ) | ord ( $data [$spos + 7] ) << 8;
if (($version != SPREADSHEET_EXCEL_READER_BIFF8) && ($version != SPREADSHEET_EXCEL_READER_BIFF7)) {
return - 1;
}
if ($substreamType != SPREADSHEET_EXCEL_READER_WORKSHEET) {
return - 2;
}
$spos += $length + 4;
while ( $cont ) {
$lowcode = ord ( $data [$spos] );
if ($lowcode == SPREADSHEET_EXCEL_READER_TYPE_EOF)
break;
$code = $lowcode | ord ( $data [$spos + 1] ) << 8;
$length = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$spos += 4;
$this->sheets [$this->sn] ['maxrow'] = $this->_rowoffset - 1;
$this->sheets [$this->sn] ['maxcol'] = $this->_coloffset - 1;
unset ( $this->rectype );
switch ($code) {
case SPREADSHEET_EXCEL_READER_TYPE_DIMENSION :
if (! isset ( $this->numRows )) {
if (($length == 10) || ($version == SPREADSHEET_EXCEL_READER_BIFF7)) {
$this->sheets [$this->sn] ['numRows'] = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$this->sheets [$this->sn] ['numCols'] = ord ( $data [$spos + 6] ) | ord ( $data [$spos + 7] ) << 8;
} else {
$this->sheets [$this->sn] ['numRows'] = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
$this->sheets [$this->sn] ['numCols'] = ord ( $data [$spos + 10] ) | ord ( $data [$spos + 11] ) << 8;
}
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_MERGEDCELLS :
$cellRanges = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
for($i = 0; $i < $cellRanges; $i ++) {
$fr = ord ( $data [$spos + 8 * $i + 2] ) | ord ( $data [$spos + 8 * $i + 3] ) << 8;
$lr = ord ( $data [$spos + 8 * $i + 4] ) | ord ( $data [$spos + 8 * $i + 5] ) << 8;
$fc = ord ( $data [$spos + 8 * $i + 6] ) | ord ( $data [$spos + 8 * $i + 7] ) << 8;
$lc = ord ( $data [$spos + 8 * $i + 8] ) | ord ( $data [$spos + 8 * $i + 9] ) << 8;
if ($lr - $fr > 0) {
$this->sheets [$this->sn] ['cellsInfo'] [$fr + 1] [$fc + 1] ['rowspan'] = $lr - $fr + 1;
}
if ($lc - $fc > 0) {
$this->sheets [$this->sn] ['cellsInfo'] [$fr + 1] [$fc + 1] ['colspan'] = $lc - $fc + 1;
}
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_RK :
case SPREADSHEET_EXCEL_READER_TYPE_RK2 :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$rknum = $this->_GetInt4d ( $data, $spos + 6 );
$numValue = $this->_GetIEEE754 ( $rknum );
$info = $this->_getCellDetails ( $spos, $numValue, $column );
$this->addcell ( $row, $column, $info ['string'], $info );
break;
case SPREADSHEET_EXCEL_READER_TYPE_LABELSST :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$xfindex = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
$index = $this->_GetInt4d ( $data, $spos + 6 );
$this->addcell ( $row, $column, $this->sst [$index], array ('xfIndex' => $xfindex ) );
break;
case SPREADSHEET_EXCEL_READER_TYPE_MULRK :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$colFirst = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$colLast = ord ( $data [$spos + $length - 2] ) | ord ( $data [$spos + $length - 1] ) << 8;
$columns = $colLast - $colFirst + 1;
$tmppos = $spos + 4;
for($i = 0; $i < $columns; $i ++) {
$numValue = $this->_GetIEEE754 ( $this->_GetInt4d ( $data, $tmppos + 2 ) );
$info = $this->_getCellDetails ( $tmppos - 4, $numValue, $colFirst + $i + 1 );
$tmppos += 6;
$this->addcell ( $row, $colFirst + $i, $info ['string'], $info );
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_NUMBER :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$tmp = unpack ( "ddouble", substr ( $data, $spos + 6, 8 ) ); // It machine machine dependent
if ($this->isDate ( $spos )) {
$numValue = $tmp ['double'];
} else {
$numValue = $this->createNumber ( $spos );
}
$info = $this->_getCellDetails ( $spos, $numValue, $column );
$this->addcell ( $row, $column, $info ['string'], $info );
break;
case SPREADSHEET_EXCEL_READER_TYPE_FORMULA :
case SPREADSHEET_EXCEL_READER_TYPE_FORMULA2 :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
if ((ord ( $data [$spos + 6] ) == 0) && (ord ( $data [$spos + 12] ) == 255) && (ord ( $data [$spos + 13] ) == 255)) {
//String formula. Result follows in a STRING record
// This row/col are stored to be referenced in that record
// http://code.google.com/p/php-excel-reader/issues/detail?id=4
$previousRow = $row;
$previousCol = $column;
} elseif ((ord ( $data [$spos + 6] ) == 1) && (ord ( $data [$spos + 12] ) == 255) && (ord ( $data [$spos + 13] ) == 255)) {
//Boolean formula. Result is in +2; 0=false,1=true
// http://code.google.com/p/php-excel-reader/issues/detail?id=4
if (ord ( $this->data [$spos + 8] ) == 1) {
$this->addcell ( $row, $column, "TRUE" );
} else {
$this->addcell ( $row, $column, "FALSE" );
}
} elseif ((ord ( $data [$spos + 6] ) == 2) && (ord ( $data [$spos + 12] ) == 255) && (ord ( $data [$spos + 13] ) == 255)) {
//Error formula. Error code is in +2;
} elseif ((ord ( $data [$spos + 6] ) == 3) && (ord ( $data [$spos + 12] ) == 255) && (ord ( $data [$spos + 13] ) == 255)) {
//Formula result is a null string.
$this->addcell ( $row, $column, '' );
} else {
// result is a number, so first 14 bytes are just like a _NUMBER record
$tmp = unpack ( "ddouble", substr ( $data, $spos + 6, 8 ) ); // It machine machine dependent
if ($this->isDate ( $spos )) {
$numValue = $tmp ['double'];
} else {
$numValue = $this->createNumber ( $spos );
}
$info = $this->_getCellDetails ( $spos, $numValue, $column );
$this->addcell ( $row, $column, $info ['string'], $info );
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_BOOLERR :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$string = ord ( $data [$spos + 6] );
$this->addcell ( $row, $column, $string );
break;
case SPREADSHEET_EXCEL_READER_TYPE_STRING :
// http://code.google.com/p/php-excel-reader/issues/detail?id=4
if ($version == SPREADSHEET_EXCEL_READER_BIFF8) {
// Unicode 16 string, like an SST record
$xpos = $spos;
$numChars = ord ( $data [$xpos] ) | (ord ( $data [$xpos + 1] ) << 8);
$xpos += 2;
$optionFlags = ord ( $data [$xpos] );
$xpos ++;
$asciiEncoding = (($optionFlags & 0x01) == 0);
$extendedString = (($optionFlags & 0x04) != 0);
// See if string contains formatting information
$richString = (($optionFlags & 0x08) != 0);
if ($richString) {
// Read in the crun
$formattingRuns = ord ( $data [$xpos] ) | (ord ( $data [$xpos + 1] ) << 8);
$xpos += 2;
}
if ($extendedString) {
// Read in cchExtRst
$extendedRunLength = $this->_GetInt4d ( $this->data, $xpos );
$xpos += 4;
}
$len = ($asciiEncoding) ? $numChars : $numChars * 2;
$retstr = substr ( $data, $xpos, $len );
$xpos += $len;
if ($asciiEncoding)
$retstr = preg_replace ( "/(.)/s", "$1\0", $retstr );
$retstr = $this->_encodeUTF16 ( $retstr );
} elseif ($version == SPREADSHEET_EXCEL_READER_BIFF7) {
// Simple byte string
$xpos = $spos;
$numChars = ord ( $data [$xpos] ) | (ord ( $data [$xpos + 1] ) << 8);
$xpos += 2;
$retstr = substr ( $data, $xpos, $numChars );
}
$this->addcell ( $previousRow, $previousCol, $retstr );
break;
case SPREADSHEET_EXCEL_READER_TYPE_ROW :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$rowInfo = ord ( $data [$spos + 6] ) | ((ord ( $data [$spos + 7] ) << 8) & 0x7FFF);
if (($rowInfo & 0x8000) > 0) {
$rowHeight = - 1;
} else {
$rowHeight = $rowInfo & 0x7FFF;
}
$rowHidden = (ord ( $data [$spos + 12] ) & 0x20) >> 5;
$this->rowInfo [$this->sn] [$row + 1] = Array ('height' => $rowHeight / 20, 'hidden' => $rowHidden );
break;
case SPREADSHEET_EXCEL_READER_TYPE_DBCELL :
break;
case SPREADSHEET_EXCEL_READER_TYPE_MULBLANK :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$cols = ($length / 2) - 3;
for($c = 0; $c < $cols; $c ++) {
$xfindex = ord ( $data [$spos + 4 + ($c * 2)] ) | ord ( $data [$spos + 5 + ($c * 2)] ) << 8;
$this->addcell ( $row, $column + $c, "", array ('xfIndex' => $xfindex ) );
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_LABEL :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$this->addcell ( $row, $column, substr ( $data, $spos + 8, ord ( $data [$spos + 6] ) | ord ( $data [$spos + 7] ) << 8 ) );
break;
case SPREADSHEET_EXCEL_READER_TYPE_EOF :
$cont = false;
break;
case SPREADSHEET_EXCEL_READER_TYPE_HYPER :
// Only handle hyperlinks to a URL
$row = ord ( $this->data [$spos] ) | ord ( $this->data [$spos + 1] ) << 8;
$row2 = ord ( $this->data [$spos + 2] ) | ord ( $this->data [$spos + 3] ) << 8;
$column = ord ( $this->data [$spos + 4] ) | ord ( $this->data [$spos + 5] ) << 8;
$column2 = ord ( $this->data [$spos + 6] ) | ord ( $this->data [$spos + 7] ) << 8;
$linkdata = Array ();
$flags = ord ( $this->data [$spos + 28] );
$udesc = "";
$ulink = "";
$uloc = 32;
$linkdata ['flags'] = $flags;
if (($flags & 1) > 0) { // is a type we understand
// is there a description ?
if (($flags & 0x14) == 0x14) { // has a description
$uloc += 4;
$descLen = ord ( $this->data [$spos + 32] ) | ord ( $this->data [$spos + 33] ) << 8;
$udesc = substr ( $this->data, $spos + $uloc, $descLen * 2 );
$uloc += 2 * $descLen;
}
$ulink = $this->read16bitstring ( $this->data, $spos + $uloc + 20 );
if ($udesc == "") {
$udesc = $ulink;
}
}
$linkdata ['desc'] = $udesc;
$linkdata ['link'] = $this->_encodeUTF16 ( $ulink );
for($r = $row; $r <= $row2; $r ++) {
for($c = $column; $c <= $column2; $c ++) {
$this->sheets [$this->sn] ['cellsInfo'] [$r + 1] [$c + 1] ['hyperlink'] = $linkdata;
}
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_DEFCOLWIDTH :
$this->defaultColWidth = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
break;
case SPREADSHEET_EXCEL_READER_TYPE_STANDARDWIDTH :
$this->standardColWidth = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
break;
case SPREADSHEET_EXCEL_READER_TYPE_COLINFO :
$colfrom = ord ( $data [$spos + 0] ) | ord ( $data [$spos + 1] ) << 8;
$colto = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$cw = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
$cxf = ord ( $data [$spos + 6] ) | ord ( $data [$spos + 7] ) << 8;
$co = ord ( $data [$spos + 8] );
for($coli = $colfrom; $coli <= $colto; $coli ++) {
$this->colInfo [$this->sn] [$coli + 1] = Array ('width' => $cw, 'xf' => $cxf, 'hidden' => ($co & 0x01), 'collapsed' => ($co & 0x1000) >> 12 );
}
break;
default :
break;
}
$spos += $length;
}
if (! isset ( $this->sheets [$this->sn] ['numRows'] ))
$this->sheets [$this->sn] ['numRows'] = $this->sheets [$this->sn] ['maxrow'];
if (! isset ( $this->sheets [$this->sn] ['numCols'] ))
$this->sheets [$this->sn] ['numCols'] = $this->sheets [$this->sn] ['maxcol'];
}
function isDate($spos) {
$xfindex = ord ( $this->data [$spos + 4] ) | ord ( $this->data [$spos + 5] ) << 8;
return ($this->xfRecords [$xfindex] ['type'] == 'date');
}
// Get the details for a particular cell
function _getCellDetails($spos, $numValue, $column) {
$xfindex = ord ( $this->data [$spos + 4] ) | ord ( $this->data [$spos + 5] ) << 8;
$xfrecord = $this->xfRecords [$xfindex];
$type = $xfrecord ['type'];
$format = $xfrecord ['format'];
$formatIndex = $xfrecord ['formatIndex'];
$fontIndex = $xfrecord ['fontIndex'];
$formatColor = "";
$rectype = '';
$string = '';
$raw = '';
if (isset ( $this->_columnsFormat [$column + 1] )) {
$format = $this->_columnsFormat [$column + 1];
}
if ($type == 'date') {
// See http://groups.google.com/group/php-excel-reader-discuss/browse_frm/thread/9c3f9790d12d8e10/f2045c2369ac79de
$rectype = 'date';
// Convert numeric value into a date
$utcDays = floor ( $numValue - ($this->nineteenFour ? SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS1904 : SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS) );
$utcValue = ($utcDays) * SPREADSHEET_EXCEL_READER_MSINADAY;
$dateinfo = gmgetdate ( $utcValue );
$raw = $numValue;
$fractionalDay = $numValue - floor ( $numValue ) + .0000001; // The .0000001 is to fix for php/excel fractional diffs
 
$totalseconds = floor ( SPREADSHEET_EXCEL_READER_MSINADAY * $fractionalDay );
$secs = $totalseconds % 60;
$totalseconds -= $secs;
$hours = floor ( $totalseconds / (60 * 60) );
$mins = floor ( $totalseconds / 60 ) % 60;
$string = date ( $format, mktime ( $hours, $mins, $secs, $dateinfo ["mon"], $dateinfo ["mday"], $dateinfo ["year"] ) );
} else if ($type == 'number') {
$rectype = 'number';
$formatted = $this->_format_value ( $format, $numValue, $formatIndex );
$string = $formatted ['string'];
$formatColor = $formatted ['formatColor'];
$raw = $numValue;
} else {
if ($format == "") {
$format = $this->_defaultFormat;
}
$rectype = 'unknown';
$formatted = $this->_format_value ( $format, $numValue, $formatIndex );
$string = $formatted ['string'];
$formatColor = $formatted ['formatColor'];
$raw = $numValue;
}
return array ('string' => $string, 'raw' => $raw, 'rectype' => $rectype, 'format' => $format, 'formatIndex' => $formatIndex, 'fontIndex' => $fontIndex, 'formatColor' => $formatColor, 'xfIndex' => $xfindex );
}
function createNumber($spos) {
$rknumhigh = $this->_GetInt4d ( $this->data, $spos + 10 );
$rknumlow = $this->_GetInt4d ( $this->data, $spos + 6 );
$sign = ($rknumhigh & 0x80000000) >> 31;
$exp = ($rknumhigh & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknumhigh & 0x000fffff));
$mantissalow1 = ($rknumlow & 0x80000000) >> 31;
$mantissalow2 = ($rknumlow & 0x7fffffff);
$value = $mantissa / pow ( 2, (20 - ($exp - 1023)) );
if ($mantissalow1 != 0)
$value += 1 / pow ( 2, (21 - ($exp - 1023)) );
$value += $mantissalow2 / pow ( 2, (52 - ($exp - 1023)) );
if ($sign) {
$value = - 1 * $value;
}
return $value;
}
function addcell($row, $col, $string, $info = null) {
$this->sheets [$this->sn] ['maxrow'] = max ( $this->sheets [$this->sn] ['maxrow'], $row + $this->_rowoffset );
$this->sheets [$this->sn] ['maxcol'] = max ( $this->sheets [$this->sn] ['maxcol'], $col + $this->_coloffset );
$this->sheets [$this->sn] ['cells'] [$row + $this->_rowoffset] [$col + $this->_coloffset] = $string;
if ($this->store_extended_info && $info) {
foreach ( $info as $key => $val ) {
$this->sheets [$this->sn] ['cellsInfo'] [$row + $this->_rowoffset] [$col + $this->_coloffset] [$key] = $val;
}
}
}
function _GetIEEE754($rknum) {
if (($rknum & 0x02) != 0) {
$value = $rknum >> 2;
} else {
//mmp
// I got my info on IEEE754 encoding from
// http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
// The RK format calls for using only the most significant 30 bits of the
// 64 bit floating point value. The other 34 bits are assumed to be 0
// So, we use the upper 30 bits of $rknum as follows...
$sign = ($rknum & 0x80000000) >> 31;
$exp = ($rknum & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknum & 0x000ffffc));
$value = $mantissa / pow ( 2, (20 - ($exp - 1023)) );
if ($sign) {
$value = - 1 * $value;
}
//end of changes by mmp
}
if (($rknum & 0x01) != 0) {
$value /= 100;
}
return $value;
}
function _encodeUTF16($string) {
$result = $string;
if ($this->_defaultEncoding) {
switch ($this->_encoderFunction) {
case 'iconv' :
$result = iconv ( 'UTF-16LE', $this->_defaultEncoding, $string );
break;
case 'mb_convert_encoding' :
$result = mb_convert_encoding ( $string, $this->_defaultEncoding, 'UTF-16LE' );
break;
}
}
return $result;
}
function _GetInt4d($data, $pos) {
$value = ord ( $data [$pos] ) | (ord ( $data [$pos + 1] ) << 8) | (ord ( $data [$pos + 2] ) << 16) | (ord ( $data [$pos + 3] ) << 24);
if ($value >= 4294967294) {
$value = - 2;
}
return $value;
}
 
}
 
?>
/tags/v5.3-amandaie/scripts/bibliotheque/GenerateurNomSciHtml.php
New file
0,0 → 1,283
<?php
class GenerateurNomSciHtml {
protected $bdd = null;
protected $table = null;
 
protected $num = null;
protected $compo_nom = array();
 
protected $abbr = array (
'infra-gen.' => 'Infra-Genre',
'sect.' => 'Section',
'subsect.' => 'Sous-Section',
'ser.' => 'Série',
'subser.' => 'Sous-Série',
'gr.' => 'Groupe',
'agg.' => 'Agrégat',
'sp.' => 'Espèce',
'subsp.' => 'Sous-Espèce',
'infra-sp.' => 'Infra-Espèce',
'var.' => 'Variété',
'subvar.' => 'Sous-Variété',
'fa' => 'Forme',
'subf.' => 'Sous-Forme',
'f. sp.' => 'Forma species',
'proles' => 'Race prole'
);
 
private $nomSciTpl = '<span class="sci">%s</span>';
 
private $nomSupraGenTpl = '<span class="supra_gen">%s</span>';
private $genTpl = '<span class="gen">%s</span>';
private $infraGenTpl = '<span class="infra-gen">%s</span>';
private $spFHTpl = '<span class="gen">%s</span> <span class="sp">%s</span>';
private $typeEpitheteTpl = '<abbr class="type_epithete" title="%s">%s</abbr>';
private $infraSpFHTpl = '<span class="gen">%s</span> <span class="sp">%s</span> <abbr class="type-epithete" title="%s">%s</abbr> <span class="infra-sp">%s</span>';
 
private $hybrideTpl = '<span class="hyb">× <span class="%s">%s</span></span>';
private $chimereTpl = '<span class="chimere">+ <span class="%s">%s</span></span>';
private $formuleHybTpl = '<span class="formule-hyb">%s</span>';
private $hybriditeTpl = '<span class="%s">%s</span>';
 
private $gpGxAvecCvarTpl = '<span class="gp">%s <abbr title="grex">gx</abbr>(%s <abbr title="groupe">Gp</abbr>)</span>';
private $gpGxSansCvarTpl = '<span class="gp">%s <abbr title="grex">gx</abbr>%s <abbr title="groupe">Gp</abbr></span>';
private $gxTpl = '<span class="gp">%s <abbr title="grex">gx</abbr></span>';
private $gpAvecCvarTpl = '<span class="gp">(%s <abbr title="groupe">Gp</abbr>)</span>';
private $gpSansCvarTpl = '<span class="gp">%s <abbr title="groupe">Gp</abbr></span>';
private $commTpl = '<span class="commercial">%s</span>';
private $cvarTpl = '<span class="cultivar">\'%s\'</span>';
 
public function generer(Array $nomsDecomposes) {
$nomsSciHtml = array();
foreach ($nomsDecomposes as $infos) {
$nom = $this->genererNomSciHtml($infos);
if ($nom != '') {
$nomsSciHtml[$this->num] = $nom;
}
}
return $nomsSciHtml;
}
 
public function genererNomSciHtml(Array $nomDecomposes) {
$this->initialiserVariables($nomDecomposes);
 
$nomSciHtml = '';
$nomSciHtml .= $this->ajouterBaliseNomSupraGen();
$nomSciHtml .= $this->verifierHybridite($this->compo_nom['genre'], 'gen');
$nomSciHtml .= $this->ajouterBaliseInfraGen();
$nomSciHtml .= $this->verifierHybridite($this->compo_nom['epithete_sp'], 'sp');
$nomSciHtml .= $this->ajouterBaliseTypeInfraSp();
$nomSciHtml .= $this->verifierHybridite($this->compo_nom['epithete_infra_sp'], 'infra-sp');
$nomSciHtml .= $this->ajouterCultivarGpComm();
 
if ($nomSciHtml != '') {
$nomSciHtml = sprintf($this->nomSciTpl, trim($nomSciHtml));
} else {
$nomSciHtml = $this->verifierHybridite($this->compo_nom['nom_sci'], 'infra-sp');
}
return $nomSciHtml;
}
 
private function initialiserVariables($infos) {
$this->num = $infos['num_nom'];
$this->compo_nom = $infos;
}
 
private function ajouterBaliseNomSupraGen() {
$html = '';
if ($this->compo_nom['nom_supra_generique'] != '') {
$html = sprintf($this->nomSupraGenTpl, $this->compo_nom['nom_supra_generique']);
}
return $html;
}
 
private function ajouterTypeEpithete($type) {
if (!array_key_exists($type, $this->abbr)) {
$this->abbr[$type] = $type;
}
}
 
private function ajouterBaliseInfraGen() {
$html = '';
if ($this->verifierTypeInfraGen()) {
$html = $this->ajouterBaliseTypeInfraGen();
} else {
if ($this->avoirInfo('epithete_infra_generique')) {
$html = sprintf($this->infraGenTpl, $this->compo_nom['epithete_infra_generique']);
}
}
return $html;
}
 
private function verifierTypeInfraGen() {
$ok = false;
if ($this->compo_nom['type_epithete'] != '' && $this->compo_nom['epithete_infra_generique'] != '') {
$this->ajouterTypeEpithete($this->compo_nom['type_epithete']);
$ok = true;
}
return $ok;
}
 
private function ajouterBaliseTypeInfraGen() {
$html = '';
$type = $this->compo_nom['type_epithete'];
 
if ($type == 'agg.') {
// Ajout de l'infra gen avant le type s'il est égal à agg.
$html = ' '.$this->ajouterBaliseInfraGen().
' '.sprintf($this->typeEpitheteTpl, $this->abbr[$type], $type);
} else {
$html = ' '.sprintf($this->typeEpitheteTpl, $this->abbr[$type], $type).
' '.$this->ajouterBaliseInfraGen();
}
return $html;
}
 
private function ajouterBaliseTypeInfraSp() {
$html = '';
$type = $this->compo_nom['type_epithete'];
$infraSp = $this->compo_nom['epithete_infra_sp'];
 
if ($infraSp != '') {
if ($type != '') {
$this->ajouterTypeEpithete($type);
$html = ' '.sprintf($this->typeEpitheteTpl, $this->abbr[$type], $type);
} else {
$message = "Nom #{$this->num} contient un épithète infra-spécifique mais son type n'est pas renseigné.";
throw new Exception($message);
}
}
return $html;
}
 
private function ajouterCultivarGpComm() {
$html = '';
if ($this->avoirInfo('cultivar_groupe')) {
$html .= ' '.$this->ajouterCultivarGroupe();
}
if ($this->avoirInfo('nom_commercial')) {
$html .= ' '.sprintf($this->commTpl, $this->compo_nom['nom_commercial']);
}
if ($this->avoirInfo('cultivar')) {
$html .= ' '.sprintf($this->cvarTpl, $this->compo_nom['cultivar']);
}
return $html;
}
 
private function avoirInfo($valeur) {
return (isset($this->compo_nom[$valeur]) && $this->compo_nom[$valeur] != '') ? true : false;
}
 
/**
* Permet d'ajouter les groupes de cultivar en fonction de la présence d'un cultivar et de la présence d'un grex
*
* L'ensemble des individus obtenu par une fécondation particulière s'appelle un le Grex (que pour les orchidées).
* Au sein du grex, certains individus peuvent se distinguer par des formes, des coloris ou autres qui font que
* l'obtenteur du grex va les sélectionner.
* les noms de groupes de cultivars sont suivis de l'abréviation « Gp » et placés entre parenthèses
* les noms de grex, s'ils sont utilisés devant une épithète de cultivar, ne se mettent pas entre parenthèses
* ex : Cymbidium Alexanderi gx 'Westonbirt' (cultivar_groupe = Alexanderi gx) ;
* les noms de groupe se mettent entre parenthèses s'ils sont devant une épithète de cultivar
* ex : Dracaena fragrans (Deremenis Gp) 'Christianne' (cultivar_groupe = Deremenis)
* Un grex peut contenir des groupes (rédaction d'un exemple de l'ICNCP)
* ex : × Rhyncosophrocattleya Marie Lemon Stick grex Francis Suzuki Group
* ou : × Rhyncosophrocattleya Marie Lemon Stick gx Francis Suzuki Gp
* @param unknown_type $val
*
*/
private function ajouterCultivarGroupe() {
$html = '';
// si le champ cultivar_groupe n'est pas vide
if ($this->avoirInfo('cultivar_groupe')) {
$groupe = trim($this->compo_nom['cultivar_groupe']);
 
// Sélection des templates
$tplGx = $this->gxTpl;
$tplGpGx = $this->gpGxSansCvarTpl;
$tplGp = $this->gpSansCvarTpl;
// s'il y a un cultivar, on ajoute des parenthèses au groupe (mais pas au grex)
if ($this->avoirInfo('cultivar')) {
$tplGpGx = $this->gpGxAvecCvarTpl;
$tplGp = $this->gpAvecCvarTpl;
}
 
// Création du HTML du groupe de cultivar
if (strrpos($groupe, ' gx ') !== false) {//si le grex est composé de groupe
$gpEtGx = explode(' gx ', $groupe);
$html = sprintf($tplGpGx, $gpEtGx[0], $gpEtGx[1]);
} else if (preg_match('/ gx$/', $groupe)) {//s'il y a un grex et pas de groupe
$gx = str_replace(' gx', '', $groupe);
$html = sprintf($tplGx, $gx);
} else { //s'il n'y a pas de grex mais un groupe
$html = sprintf($tplGp, $groupe);
}
}
return $html;
}
 
/**
*
* Permet de repérer s'il s'agit d'un hybride (infra-sp, genre, sp) ou d'une chimère.
* @param unknown_type $val
* @param unknown_type $type
*/
private function verifierHybridite($epithete, $type) {
$html = '';
if ($epithete != '') {
if (substr($epithete, 0, 2) == 'x ') {
$hybride = str_replace('x ', '', $epithete);
$html = ' '.sprintf($this->hybrideTpl, $type, $hybride);
} elseif (substr($epithete, 0, 2) == '+ ') {
$hybride = str_replace('+ ', '', $epithete);
$html = ' '.sprintf($this->chimereTpl, $type, $hybride);
} else if (substr_count($epithete, ' x ') > 1) {// Cas d'une formule d'hybridité comprenant des parents hybrides
$html = ' '.$this->insererBaliseFormuleHyb($epithete);
} elseif (substr_count($epithete, ' x ') == 1) {// Cas d'une formule d'hybridité simple
$html = ' '.$this->ajouterFomuleHybridite($epithete, $type);
} else {// Autre cas...
$html = ' '.sprintf($this->hybriditeTpl, $type, $epithete);
}
}
return $html;
}
 
private function ajouterFomuleHybridite($formule, $type) {
$tab_x = explode(' x ', $formule);
$formule_hyb = array();
switch ($type) {
case 'gen' :
foreach ($tab_x as $hyb) {
$formule_hyb[] = sprintf($this->genTpl, $hyb);
}
break;
case 'sp' :
foreach ($tab_x as $hyb) {
if (substr_count($hyb, ' ') >= 1) {
list($gen, $sp) = explode(' ', $hyb);
$formule_hyb[] = sprintf($this->spFHTpl, $gen, $sp);
} else if (preg_match('/^[A-Z]/', $hyb)) {
$gen = $hyb;
$formule_hyb[] = sprintf($this->genTpl, $gen);
}
}
break;
case 'infra-sp' :
foreach ($tab_x as $hyb) {
list($gen, $sp, $typeEpithete, $infraSp) = explode (' ', $hyb);
if (isset($infraSp)) {
$formule_hyb[] = sprintf($this->infraSpFHTpl, $gen, $sp, $this->abbr[$typeEpithete], $typeEpithete, $infraSp);
} else {
$formule_hyb[] = sprintf($this->spFHTpl, $gen, $sp);
}
}
break;
default : break;
}
return $this->insererBaliseFormuleHyb(implode(' x ', $formule_hyb));
}
 
private function insererBaliseFormuleHyb($formule) {
return sprintf($this->formuleHybTpl, $formule);
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/Outils.php
New file
0,0 → 1,86
<?php
class Outils {
 
public static function recupererTableauConfig($parametres) {
$tableau = array();
$tableauPartiel = explode(',', $parametres);
$tableauPartiel = array_map('trim', $tableauPartiel);
foreach ($tableauPartiel as $champ) {
if (strpos($champ, '=') === false) {
$tableau[] = $champ;
} else {
list($cle, $val) = explode('=', $champ);
$clePropre = trim($cle);
$valeurPropre = trim($val);
$tableau[$clePropre] = $valeurPropre;
}
}
return $tableau;
}
 
public static function extraireRequetes($contenuSql) {
$requetesExtraites = preg_split("/;\e*\t*\r*\n/", $contenuSql);
if (count($requetesExtraites) == 0){
throw new Exception("Aucune requête n'a été trouvée dans le fichier SQL : $cheminFichierSql");
}
 
$requetes = array();
foreach ($requetesExtraites as $requete) {
if (trim($requete) != '') {
$requetes[] = rtrim(trim($requete), ';');
}
}
return $requetes;
}
 
/**
* Utiliser cette méthode dans une boucle pour afficher un message suivi du nombre de tour de boucle effectué.
* Vous devrez vous même gérer le retour à la ligne à la sortie de la boucle.
*
* @param string le message d'information.
* @param int le nombre de départ à afficher.
* @return void le message est affiché dans la console.
*/
public static function afficherAvancement($message, $depart = 0) {
static $avancement = array();
if (! array_key_exists($message, $avancement)) {
$avancement[$message] = $depart;
echo "$message : ";
 
$actuel =& $avancement[$message];
echo $actuel++;
} else {
$actuel =& $avancement[$message];
 
// Cas du passage de 99 (= 2 caractères) à 100 (= 3 caractères)
$passage = 0;
if (strlen((string) ($actuel - 1)) < strlen((string) ($actuel))) {
$passage = 1;
}
 
echo str_repeat(chr(8), (strlen((string) $actuel) - $passage));
echo $actuel++;
}
}
 
/**
* @link http://gist.github.com/385876
*/
public function transformerTxtTsvEnTableau($file = '', $delimiter = "\t") {
$str = file_get_contents($file);
$lines = explode("\n", $str);
$field_names = explode($delimiter, array_shift($lines));
foreach ($lines as $line) {
// Skip the empty line
if (empty($line)) continue;
$fields = explode($delimiter, $line);
$_res = array();
foreach ($field_names as $key => $f) {
$_res[$f] = isset($fields[$key]) ? $fields[$key] : '';
}
$res[] = $_res;
}
return $res;
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/EfloreScript.php
New file
0,0 → 1,89
<?php
// declare(encoding='UTF-8');
/**
* EfloreScript est une classe abstraite qui doit être implémenté par les classes éxecutant des scripts
* en ligne de commande pour les projets d'eFlore.
*
* @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.gnu.org/licenses/gpl.html Licence GNU-GPL-v3
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2
* @since 0.3
* @version $Id$
* @link /doc/framework/
*/
abstract class EfloreScript extends Script {
 
private $Bdd = null;
private $projetNom = null;
 
public function getProjetNom() {
return $this->projetNom;
}
 
protected function initialiserProjet($projetNom) {
$this->projetNom = $projetNom;
$this->chargerConfigDuProjet();
}
 
//+------------------------------------------------------------------------------------------------------+
// Méthodes d'accès aux objets du Framework
/**
* Méthode de connection à la base de données sur demande.
* Tous les scripts n'ont pas besoin de s'y connecter.
*/
protected function getBdd() {
if (! isset($this->Bdd)) {
$this->Bdd = new Bdd();
}
return $this->Bdd;
}
 
//+------------------------------------------------------------------------------------------------------+
// Méthodes communes aux projets d'eFlore
 
protected function chargerConfigDuProjet() {
$fichierIni = $this->getScriptChemin().$this->getProjetNom().'.ini';
if (file_exists($fichierIni)) {
Config::charger($fichierIni);
} else {
$m = "Veuillez configurer le projet en créant le fichier '{$this->projetNom}.ini' ".
"dans le dossier du module de script du projet à partir du fichier '{$this->projetNom}.defaut.ini'.";
throw new Exception($m);
}
}
 
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);
}
}
 
protected function recupererContenu($chemin) {
$contenu = file_get_contents($chemin);
if ($contenu === false){
throw new Exception("Impossible d'ouvrir le fichier SQL : $chemin");
}
return $contenu;
}
 
protected function stopperLaBoucle($limite = false) {
$stop = false;
if ($limite) {
static $ligneActuelle = 1;
if ($limite == $ligneActuelle++) {
$stop = true;
}
}
return $stop;
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/nom_sci/Decoupage.php
New file
0,0 → 1,160
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Découpage
*
* Description : classe abstraite mettant en comun des expressions régulière pour le découpage des noms latins.
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Tela-Botanica 1999-2009
* @licence GPL v3 & CeCILL v2
* @version $Id: Decoupage.class.php 1873 2009-03-31 10:07:24Z Jean-Pascal MILCENT $
*/
// +-------------------------------------------------------------------------------------------------------------------+
abstract class Decoupage {
protected $min = '[a-z\x{E0}-\x{FF}\x{153}]';// Lettres minuscules : a à z et &#224; à &#255 et &#339;
protected $maj = "[A-Z'\x{C0}-\x{DF}\x{152}]";// Lettres majuscules : A à Z, ' et &#192; à &#223; et &#338;
protected $hyb = '[+xX]';
protected $SupraSp;// Nom de type suprasp.
protected $GenHy;// Hybride intergénérique
protected $Gen;// Genre
protected $Dou = '(?:\(\?\)|\?)';// Doute
protected $Epi_cv;// Epithete de cultivar
protected $Epi_nn_hy = '(?:nsp\.|)';// Epithète non nommé hybride
protected $Epi_nn = '(?:sp\.[1-9]?|spp\.|)';// Epithète non nommé
protected $Epi;// Epithete
//------------------------------------------------------------------------------------------------------------//
protected $Ran_ig = '[Ss]ect\.|subg(?:en|)\.|ser\.|subser\.';// Rang taxonomique infragénérique de type : sous-genre
protected $Ran_ig_gr = 'gr\.';// Rang taxonomique infragénérique de type : groupe
protected $Ran_ig_agg = 'agg\.';// Rang taxonomique infragénérique de type : aggrégat
protected $Ran_bo_i1 = 'subsp\.';// Rang taxonomique infraspécifique de niveau 1
protected $Ran_bo_i2 = 'var\.|subvar\.';// Rang taxonomique infraspécifique de niveau 2
protected $Ran_bo_i3 = 'f\.|fa\.|fa|forma';// Rang taxonomique infraspécifique de niveau 3
protected $Ran_bo_i4 = 'race|prole|proles|prol\.';// Rang taxonomique infraspécifique de niveau 4
protected $Ran_bo;// Rang taxonomique infraspécifique botanique non hybride
protected $Ran_hy_i1 = 'n-subsp\.|\[subsp\.\]|\[n-subsp\.\]';// Rang taxonomique infraspécifique hybride de niveau 1
protected $Ran_hy_i2 = '\[var\.\]|n-var\.|\[n-var\.\]';// Rang taxonomique infraspécifique hybride de niveau 2
protected $Ran_hy_i3 = '';// Rang taxonomique infraspécifique hybride de niveau 3
protected $Ran_hy_i4 = 'n-proles\.';// Rang taxonomique infraspécifique hybride de niveau 4
protected $Ran_hy;// Rang taxonomique infraspécifique hybridre
protected $Ran_ht = 'convar\.|[cC]v\.';// Rang taxonomique horticole
protected $Ran;// Rang taxonomique infraspécifique non hybride, hybride et horticole
//------------------------------------------------------------------------------------------------------------//
protected $Ini;// Initiale de prénoms
protected $Pre;// Prénoms
protected $Par = '(?i:de|des|le|la|de la|von|van|st\.|el)';// Particules
protected $ParSsEs = "(?i:st\.-|d)";// Particules sans espace après
protected $Nom; // Abreviation d'un nom d'auteur. Le "f." c'est pour "filius" et c'est collé au nom
protected $NomSpe = '(?:[A-Z]\. (?:DC\.|St\.-Hil\.))|\(?hort\.\)?|al\.';// Prénom + nom spéciaux : "hort." est utilisé comme un nom d'auteur mais cela signifie "des jardins". "DC." est une exception deux majuscule suivi d'un point.
protected $Int;// Intitulé d'auteurs (Prénom + Nom)
//------------------------------------------------------------------------------------------------------------//
protected $AutNo;// Intitulé auteur sans "ex", ni "&", ni "et", ni parenthèses
protected $AutNoTa;// Intitulé auteur sans "ex", ni "&", ni "et" mais avec parenthèses possible pour la nomenclature
protected $AutEx;// Intitulé auteur avec "ex"
protected $et = '(?:&|et)';
protected $AutExEt;// Intitulé auteur avec "ex" et "&" ou "et"
protected $AutEt;// Intitulé auteur avec "&" ou "et" et sans parenthèse spécifique à la nomenclature
protected $AutEtTa;// Intitulé auteur avec "&" ou "et" et avec ou sans parenthèse spécifique à la nomenclature
protected $AutBib;// Intitulés auteurs pour la biblio
protected $AutInc = 'AUTEUR\?';// Intitulé auteur spéciaux pouvant être trouvés entre parenthèses
protected $AutSpe;// Intitulé auteur spéciaux pouvant être trouvés entre parenthèses
protected $AutSpeSe;// Intitulé auteur spéciaux type "sensu"
protected $AutSpeTa;// Intitulé auteur spéciaux propre à la nomenclature
protected $Aut;// Tous les intitulés auteurs possibles
protected $Auteur;// Tous les intitulés auteurs possibles
//------------------------------------------------------------------------------------------------------------//
protected $ComEmend;// Commentaires nomenclaturaux
protected $ComPp = 'p\.p\.';// Commentaires nomenclaturaux
protected $Com;// Intitulé auteur spéciaux type "sensu"
protected $ComNom = '\(?(?:hort\. non .*|sensu .*|auct\..*|comb\.\s*(?:nov\.|ined\.)|comb?\.\s*nov\.\s*provis\.|stat\.\s*provis\.|nov\.\s*stat\.|stat\.\s*nov\.|p\.p\.|emend\.)\)?';
//------------------------------------------------------------------------------------------------------------//
protected $In;// In auteur
protected $AneMoCo = 'janvier|fevrier|mars|avril|mai|juin|juillet|ao\x{FB}t|septembre|octobre|novembre|decembre'; //Mois devant l'année
protected $AneMoAb = 'janv\.|f[e\x{E9}]v\.|sept\.|oct\.|d\x{E9}c\.'; //Mois devant l'année
protected $AneBaSi = '(?:\d{4}|\d{4} ?\?|DATE \?)';// Date
protected $AneBaCo = '(?:\d{4}-\d{4}|\d{4}-\d{2})';// Date
protected $AneDo = '\?';// Doute
protected $AneBa;// Date
protected $AneSpe;// Date
protected $Ane;// Date
//------------------------------------------------------------------------------------------------------------//
// Spécial BDNFF :
protected $Date = ' \[.*\]';
protected $Num = '[0-9]|3\*|4\*';# Gestion des numéros de flore
protected $NumAuteur;# Gestion des numéros de flore mélangés ou pas au nom d'auteur
//------------------------------------------------------------------------------------------------------------//
protected $BibBa;// Biblio de base : \x{B0} = ° \x{AB}\x{BB} = «» \x{26} = &
protected $Bib;// Biblio de taxon
protected $BibAu = '.+';// Biblio supplémentaire
//------------------------------------------------------------------------------------------------------------//
protected $ErrDet;// Biblio à exclure base
//------------------------------------------------------------------------------------------------------------//
protected $HomNon = 'non';// Homonymes à exclure : négation
protected $HomBa;// Homonymes à exclure base
protected $Hom;// Homonymes à exclure avec non et nec
protected $HomCourt;// Homonymes à exclure avec non et nec avec expression régulière plus courte!
//------------------------------------------------------------------------------------------------------------//
protected $Inf = '.*';// Informations supplémentaires
public function __construct()
{
//mb_internal_encoding('UTF-8');
//mb_regex_encoding('UTF-8');
//setlocale(LC_ALL, 'fr-fr');
$this->SupraSp = '(?:'.$this->maj.$this->min.'+|'.$this->maj.$this->min.'+-'.$this->maj.$this->min.'+)';// Nom de type suprasp.
$this->GenHy = "[Xx] $this->SupraSp";// Hybride intergénérique
$this->Gen = "$this->SupraSp|$this->GenHy";
$this->Epi_cv = "$this->maj.(?:$this->min|-)+";// Epithete de cultivar
$this->Epi_nn = $this->Epi_nn.$this->Epi_nn_hy;
$this->Epi = "(?:(?:$this->min|-|')+|$this->Epi_nn)";// Epithete
$this->Ran_ig = $this->Ran_ig.'|'.$this->Ran_ig_gr;
$this->Ran_bo = "$this->Ran_bo_i1|$this->Ran_bo_i2|$this->Ran_bo_i3|$this->Ran_bo_i4";// Rang taxonomique infraspécifique botanique non hybride
$this->Ran_hy = "$this->Ran_hy_i1|$this->Ran_hy_i2|$this->Ran_hy_i3|$this->Ran_hy_i4";// Rang taxonomique infraspécifique hybridre
$this->Ran = "(?:$this->Ran_ig|$this->Ran_bo|$this->Ran_hy|$this->Ran_ht)";// Rang taxonomique infraspécifique non hybride, hybride et horticole
$this->Ini = '(?:'.$this->maj.'[.]|'.$this->maj.$this->min.'+[.]?)';// Initiale de prénoms
$this->Pre = $this->Ini.'{1,3}|'.$this->Ini.'[\- ]'.$this->Ini;// Prénoms
$this->Nom = '(?:'.$this->maj."'".$this->maj.'|'.$this->maj.'|'.$this->maj.$this->min."+'".$this->min.'+)'.$this->min.'*[.]?(?: ?f\.|)';
$this->Int = "(?:(?:$this->Pre ?|)(?:$this->Par |$this->ParSsEs|)(?:$this->Nom|$this->Nom".'[\- .]'."$this->Nom)|$this->NomSpe)";// Intitulé d'auteurs (Prénom + Nom)
$this->AutNo = "$this->Int";// Intitulé auteur sans "ex", ni "&", ni "et", ni parenthèses
$this->AutNoTa = "$this->AutNo|$this->NomSpe $this->Int|\($this->Int\) $this->Int";// Intitulé auteur sans "ex", ni "&", ni "et" mais avec parenthèses possible pour la nomenclature
$this->AutEx = "\($this->Int\) $this->Int ex $this->Int|\($this->Int ex $this->Int\) $this->Int|$this->Int ex $this->Int";// Intitulé auteur avec "ex"
$this->AutExEt = "$this->Int $this->et $this->Int ex $this->Int|$this->Int $this->et $this->Int ex $this->Int $this->et $this->Int|$this->Int ex $this->Int $this->et $this->Int|\($this->Int ex $this->Int $this->et $this->Int\) $this->Int|\($this->Int ex $this->Int\) $this->Int $this->et $this->Int|\($this->Int $this->et $this->Int\) $this->Int ex $this->Int|$this->NomSpe $this->Int ex $this->Int";// Intitulé auteur avec "ex" et "&" ou "et"
$this->AutEt = "$this->Int $this->et $this->Int";// Intitulé auteur avec "&" ou "et" et sans parenthèse spécifique à la nomenclature
$this->AutEtTa = "\($this->Int\) $this->Int $this->et $this->Int|\($this->Int $this->et $this->Int\) $this->Int|$this->AutEt";// Intitulé auteur avec "&" ou "et" et avec ou sans parenthèse spécifique à la nomenclature
$this->AutBib = "(?:$this->AutNo|$this->AutEt)";// Intitulés auteurs pour la biblio
$this->AutSpe = "(?:sensu |)auct\.|auct\. mult\.|$this->AutInc";// Intitulé auteur spéciaux pouvant être trouvés entre parenthèses
$this->AutSpeSe = "sensu $this->AutBib";// Intitulé auteur spéciaux type "sensu"
$this->AutSpeTa = "$this->AutSpe|\((?:$this->AutSpe)\)|$this->AutSpeSe";// Intitulé auteur spéciaux propre à la nomenclature
$this->Aut = "(?:$this->AutExEt|$this->AutEx|$this->AutEtTa|$this->AutSpeTa|$this->AutNoTa)";// Tous les intitulés auteurs possibles
$this->Auteur = $this->Int.'|'.$this->Int.' '.$this->et.' '.$this->Int.'|(?:'.$this->Int.', )+'.$this->Int.' '.$this->et.' '.$this->Int;// Intitulé auteur avec "&" ou "et";
$this->ComEmend = "emend\. $this->AutBib";// Commentaires nomenclaturaux
$this->Com = "$this->ComEmend|$this->ComPp";// Intitulé auteur spéciaux type "sensu"
$this->In = "[iI]n $this->AutBib";// In auteur
$this->AneBa = "$this->AneBaSi|$this->AneBaCo";// Date
$this->AneSpe = "(?:$this->AneBa ?\[$this->AneBa\]|(?:$this->AneMoCo|$this->AneMoAb) $this->AneBaSi|$this->AneBaSi $this->AneBaSi)";// Date
$this->Ane = "$this->AneBa||$this->AneDo|$this->AneSpe";// Date
$this->BibBa = "(?:$this->maj$this->min*[.]?|in|hort\.)(?:$this->min*[.]?|[\d\/\- ,()'\x{B0}\x{26}\x{AB}\x{BB}[\]?])*";// Biblio de base : \x{B0} = ° \x{AB}\x{BB} = «» \x{26} = &
$this->Bib = "([^:]+):(.+?)\(($this->Ane)\)";// Biblio de taxon
$this->ErrDet = "($this->AutSpe,? non $this->Aut): ($this->Bib;?)+";// Biblio à exclure base
$this->HomBa = "$this->Aut \($this->Ane\)";// Homonymes à exclure base
$this->Hom = "$this->HomNon $this->HomBa(?: nec $this->HomBa)*?";// Homonymes à exclure avec non et nec
$this->HomCourt = "$this->HomNon .+?(?: nec .+?)*?";// Homonymes à exclure avec non et nec avec expression régulière plus courte!
$this->NumAuteur = $this->Num.'|(?:(?:'.$this->Num.'|'.$this->Auteur.'), )+(?:'.$this->Num.'|'.$this->Auteur.')';# Gestion des numéros de flore mélangés ou pas au nom d'auteur
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/nom_sci/DecoupageNomLatin.php
New file
0,0 → 1,378
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Découpage des noms latins
*
* Description : classe permettant de découper les noms latins.
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Tela-Botanica 1999-2009
* @licence GPL v3 & CeCILL v2
* @version $Id: DecoupageNomLatin.class.php 1873 2009-03-31 10:07:24Z Jean-Pascal MILCENT $
*/
// +-------------------------------------------------------------------------------------------------------------------+
class DecoupageNomLatin extends Decoupage {
 
private $expression_principale = array();
private $expression_complement = array();
 
function DecoupageNomLatin()
{
parent::__construct();
 
// Genre et nom supragénérique
$this->expression_principale[1] = "/^((?:$this->hyb |)$this->Gen)(?:( $this->Inf)|)$/u";
// Sp
$this->expression_principale[2] = "/^((?:$this->hyb |)$this->Gen) ((?:($this->hyb) |$this->Dou|)(?:$this->Epi|$this->Dou))(?:((?:,| $this->Ran) $this->Inf)| agg\.|)$/u";
// Rang infragénérique et supraspécifique
$this->expression_principale[3] = '/^('.$this->Gen.') ('.$this->Ran.') ('.$this->Gen.'|.'.$this->Epi.')(?:(, '.$this->Inf.')|)$/u';
// Hybride interspécifique
$this->expression_principale[4] = "/^((?:$this->Gen) $this->Epi (?:($this->Ran) $this->Epi )?x $this->Epi(?: ($this->Ran) $this->Epi)?)$/u";
// Aggrégat
$this->expression_principale[5] = "/^($this->Gen) ($this->Epi) (agg\.)(?:( $this->Inf)|)$/u";//
// Epithète infra-spécifique
$this->expression_complement[1] = "/^ ($this->Ran) ((?:($this->hyb) |$this->Dou|)(?:$this->Epi|$this->Dou))(?:((?:,| $this->Ran) $this->Inf)|)$/Uu";
// Cultivar
$this->expression_complement[5] = "/^ ($this->Ran_ht) ((?:(?:$this->Epi_cv) ?)+)$/u";
}
public function decouper($nom_latin)
{
$aso_nom_decompo = array( 'nom_genre' => '', 'nom_sp' => '', 'auteur_sp' => '', 'nom_complement' => '',
'type_infrasp' => '', 'nom_infrasp' => '',
'num_nomenc' => '', 'num_taxo' => '', 'rang_taxonomique' => '',
'nom_courant' => '', 'nom_superieur' => '', 'agg' => '');
$aso_nom_decompo['nom_complet'] = $nom_latin;
while ($nom_latin != '') {
$morceau = array();
if (preg_match($this->expression_principale[4], $nom_latin, $morceau)) {// Formule d'hybridation
// Nous tentons de déterminer le rang de l'hybride
if (isset($morceau[2]) && isset($morceau[3]) && $morceau[2] == $morceau[3]) {
$aso_nom_decompo['rang_taxonomique'] = $this->attribuerCodeRang('n-'.$morceau[2]);
} else {
$aso_nom_decompo['rang_taxonomique'] = 260;// Hybride instersp.
}
$aso_nom_decompo['mark_hybride_interspecifique'] = 'x';
$aso_nom_decompo['formule_hybridation'] = $morceau[0];
$nom_latin = '';
} else if (preg_match($this->expression_principale[5], $nom_latin, $morceau)) {// agg.
$aso_nom_decompo['rang_taxonomique'] = 240;// agg.
$aso_nom_decompo['nom_genre'] = $morceau[1];
$aso_nom_decompo['nom_sp'] = $morceau[2];
$aso_nom_decompo['agg'] = $morceau[3];
$nom_latin = $morceau[4];
$aso_nom_decompo['nom_superieur'] = $morceau[1];
$aso_nom_decompo['nom_courant'] = $morceau[2];
} else if (preg_match($this->expression_principale[2], $nom_latin, $morceau)) {// Nom d'sp.
// Nous regardons si nous avons à faire à un hybride
if (preg_match('/^'.$this->hyb.'$/', $morceau[3])) {
$aso_nom_decompo['rang_taxonomique'] = 260;// hybride intersp.
$aso_nom_decompo['mark_hybride_interspecifique'] = strtolower($morceau[3]);
} else if (preg_match('/^'.$this->Epi_nn_hy.'$/', $morceau[2])) {
$aso_nom_decompo['rang_taxonomique'] = 260;// hybride intersp.
$aso_nom_decompo['mark_hybride_interspecifique'] = 'x';
} else {
$aso_nom_decompo['rang_taxonomique'] = 250;// sp.
}
// Nous atribuons le genre
$aso_nom_decompo['nom_genre'] = $morceau[1];
// Nous regardons si nous avons à faire à une phrase non nommé (ex : sp.1, spp., nsp.)
if (preg_match('/^'.$this->Epi_nn.'$/', $morceau[2])) {
$aso_nom_decompo['phrase_nom_non_nomme'] = $morceau[2];// hybride intersp.
$aso_nom_decompo['nom_sp'] = '';
} else {
$aso_nom_decompo['nom_sp'] = $morceau[2];
}
$nom_latin = $morceau[4];
$aso_nom_decompo['nom_superieur'] = $morceau[1];
$aso_nom_decompo['nom_courant'] = $morceau[2];
} else if (preg_match($this->expression_principale[3], $nom_latin, $morceau)) {// Nom infragénérique et supraspécifique
$aso_nom_decompo['nom_genre'] = $morceau[1];
$aso_nom_decompo['rang_taxonomique'] = $this->attribuerCodeRang($morceau[2]);
// Nous regardons si nous avons à faire à un groupe
if (preg_match('/^'.$this->Ran_ig_gr.'$/', $morceau[2])) {
$aso_nom_decompo['nom_sp'] = $morceau[3];
} else {
$aso_nom_decompo['nom_infra_genre'] = $morceau[3];
}
$nom_latin = $morceau[4];
$aso_nom_decompo['nom_superieur'] = $morceau[1];
$aso_nom_decompo['nom_courant'] = $morceau[3];
} else if (preg_match($this->expression_principale[1], $nom_latin, $morceau)) {// Nom de genre et supragénérique
$aso_nom_decompo['rang_taxonomique'] = $this->verifierTerminaisonLatine($nom_latin);
$aso_nom_decompo['nom_suprasp'] = $morceau[1];
$nom_latin = $morceau[2];
$aso_nom_decompo['nom_superieur'] = null;
$aso_nom_decompo['nom_courant'] = $morceau[1];
} else if (preg_match($this->expression_complement[5], $nom_latin, $morceau)) {// Cultivar
$aso_nom_decompo['rang_cultivar'] = $this->attribuerCodeRang($morceau[1]);
// Nous vérifions si nous avons à faire à un cultivar d'hybride
if ($aso_nom_decompo['mark_hybride_interspecifique'] == 'x' && $aso_nom_decompo['rang_cultivar'] == 460) {
$aso_nom_decompo['rang_cultivar'] = 470;
}
$aso_nom_decompo['cultivar'] = $morceau[2];
$nom_latin = '';
} else if (preg_match($this->expression_complement[1], $nom_latin, $morceau)) {// Nom infrasp.
if (preg_match('/^'.$this->hyb.'$/', $morceau[3])) {
$aso_nom_decompo['mark_hybride_interspecifique'] = strtolower($morceau[3]);
}
$aso_nom_decompo['rang_taxonomique'] = $this->attribuerCodeRang($morceau[1]);
$aso_nom_decompo['type_infrasp'] = $morceau[1];
$aso_nom_decompo['nom_infrasp'] = $morceau[2];
$nom_latin = $morceau[4];
$aso_nom_decompo['nom_superieur'] = $aso_nom_decompo['nom_courant'];
$aso_nom_decompo['nom_courant'] = $morceau[2];
} else {// Erreurs
$aso_nom_decompo['erreur_mark'] = 'erreur';
$aso_nom_decompo['erreur_notes'] = $nom_latin;
$nom_latin = '';
}
}
return $aso_nom_decompo;
}
public function verifierTerminaisonLatine($nom_latin)
{
if (preg_match('/^Plantae$/', $nom_latin)) {// Règne
return 10;
} else if (preg_match('/phyta$/', $nom_latin)) {// Embranchement ou Division
return 30;
} else if (preg_match('/phytina$/', $nom_latin)) {// Sous-Embranchement ou Sous-Division
return 40;
} if (preg_match('/opsida$/', $nom_latin)) {// Classe
return 70;
} else if (preg_match('/idae$/', $nom_latin)) {// Sous-Classe
return 80;
} else if (preg_match('/ales$/', $nom_latin)) {// Ordre
return 100;
} else if (preg_match('/ineae$/', $nom_latin)) {// Sous-Ordre
return 110;
} else if (preg_match('/aceae$/', $nom_latin)) {// Famille
return 120;
} else if (preg_match('/oideae$/', $nom_latin)) {// Sous-Famille
return 130;
} else if (preg_match('/eae$/', $nom_latin)) {// Tribu
return 140;
} else if (preg_match('/inae$/', $nom_latin)) {// Sous-Tribu
return 150;
} else if (preg_match('/^[A-Z]/', $nom_latin)) {// Genre
return 160;
} else {
return 1;
}
}
static function fournirTableauAbreviationRang($type = 'tout')
{
$rang_supra_sp = array('subgen.', 'subg.', 'sect.');// l'abréviation du rang est suivi par un nom supra spécifique commençant par une majuscule
$rang_supra_gr = array('gr.');// l'abréviation du rang est suivi par un nom ne commençant pas par une majuscule
$rang_supra_agg = array('agg.');// le nom latin est terminé par l'abréviation du rang
$rang_infra_sp = array( 'subsp.', 'n-subsp.', '[subsp.]', '[n-subsp.]',
'var.', 'nvar.', '[var.]',
'prol.', 'proles', 'n-proles.',
'f.', 'fa', 'fa.', 'forma',
'subvar.', 'convar.',
'cv.', 'Cv.',
'n-f.', 'n-fa', 'n-fa.',
'subf.', 'subfa', 'subfa.');
if ($type == 'supra') {
return $rang_supra_sp;
} else if ($type == 'supra-gr') {
return $rang_supra_gr;
} else if ($type == 'supra-agg') {
return $rang_supra_agg;
} else if ($type == 'infra') {
return $rang_infra_sp;
} else if ($type == 'tout') {
return array_merge($rang_supra_sp, $rang_supra_gr, $rang_supra_agg, $rang_infra_sp);
}
}
 
static function actualiserCodeRang($code_rang)
{
$aso_rang = array( '1' => '10', // Règne
'3' => '20', // Sous-Règne
'5' => '30', // Phylum
'7' => '40', // Sub-Phylum
'9' => '50', // division
'15' => '60', // sous-division
'20' => '70', // classe
'25' => '80', // sous-classe
'30' => '100', // ordre
'35' => '110', // sous-ordre
'40' => '120', // famille
'45' => '130', // sous-famille
'50' => '140', // tribu
'55' => '150', // sous-tribu
'60' => '160', // genre
'62' => '170', // genre hybride (nouveau compatibilité flore Réunion)
'65' => '180', // sous-genre
'65' => '190', // section
'75' => '200', // sous-section
'80' => '210', // série
'85' => '220', // sous-série
'90' => '230', // groupe
'95' => '240', // aggrégat
'100' => '250', // espèce
'102' => '260', // espèce hybride intragénérique
'104' => '260', // espèce hybride intergénérique
'110' => '280', // sous-espèce
'112' => '300', // sous-espèce hybride : hybride entre deux sous-espèces d'une espèce non hybride ; exemple : Polypodium vulgare L. nsubsp. mantoniae (Rothm.) Schidlay (Polypodium vulgare L. subsp. vulgare x Polypodium vulgare L. subsp. prionodes (Aschers.) Rothm.).
'113' => '310', // sous-espèce hybride : sous-espèce d'espèce hybride sans spécification du rang parental (subspecies) (voir ICBN, art. H.12.1).
'114' => '300', // sous-espèce hybride : sous-espèce hybride d'espèce hybride (nothosubspecies) (voir ICBN, art. H.12.1) ; exemple : Mentha x piperita L. nsubsp. piperita (Mentha aquatica L. x Mentha spicata L. subsp. glabrata (Lej. et Court.) Lebeau).
'115' => '300', // sous-espèce hybride
'120' => '1', // infra2
'122' => '330', // prole, race : peu employé souvent issu de nom ancien (antérieur au code).
'124' => '340', // prole, race hybride : peu employé souvent issu de nom ancien (antérieur au code).
'132' => '350', // convarietas : si on le conscidère comme un rang intermédiaire entre la sous-espèce et la variété. Voir aussi n°200.
'130' => '1', // infra3 : niveau infra-spécifique de troisième niveau, sans plus de précision.
'140' => '360', // variété
'142' => '380', // variété : hybride entre deux variétés d'une espèce non hybride.
'143' => '390', // variété : variété d'espèce hybride sans spécification du rang parental (varietas) (voir ICBN, art. H.12.1); exemple : Populus x canadensis Moench var. marilandica (Poir.) Rehder.
'144' => '380', // variété : variété hybride d'espèce hybride (nothovarietas) ; exemple : Salix x sepulcralis Simonk. nvar. chrysocoma (Dode) Meikle.
'145' => '380', // variété hybride
'150' => '410', // sous-variété
'160' => '420', // forme
'162' => '430', // forme : hybride entre deux formes d'une espèce non hybride.
'163' => '430', // forme : forme d'espèce hybride sans spécification du rang parental (forma) (voir ICBN, art. H.12.1); exemple : Mentha x piperita L. f. hirsuta Sole.
'164' => '430', // forme : forme hybride d'espèce hybride (nothoforma).
'170' => '440', // sous-forme
'200' => '450', // groupe de cultivar
'210' => '460', // cultivar
'220' => '470', // cultivar d'hybride
'0' => '480' // clade
);
return $aso_rang[$code_rang];
}
 
public function attribuerCodeInfra($str_abreviation_type_infra)
{
$aso_code_infra = array('type' => '', 'code' => 0, 'rang' => 2 );
switch ($str_abreviation_type_infra) {
case 'subgen.' :
case 'subg.' :
$aso_code_infra['rang'] = 180;
break;
case 'sect.' :
$aso_code_infra['rang'] = 190;
break;
case 'gr.' :
$aso_code_infra['rang'] = 230;
break;
case 'subsp.' :
$aso_code_infra['type'] = 'infra1';
$aso_code_infra['code'] = 1;
$aso_code_infra['rang'] = 280;
break;
case 'n-subsp.' :
$aso_code_infra['type'] = 'infra1';
$aso_code_infra['code'] = 2;
$aso_code_infra['rang'] = 300;
break;
case '[subsp.]' :
$aso_code_infra['type'] = 'infra1';
$aso_code_infra['code'] = 3;
$aso_code_infra['rang'] = 290;
break;
case '[n-subsp.]' :
$aso_code_infra['type'] = 'infra1';
$aso_code_infra['code'] = 4;
$aso_code_infra['rang'] = 310;
break;
case 'var.' :
$aso_code_infra['type'] = 'infra2';
$aso_code_infra['code'] = 1;
$aso_code_infra['rang'] = 360;
break;
case '[var.]' :
$aso_code_infra['type'] = 'infra2';
$aso_code_infra['code'] = 2;
$aso_code_infra['rang'] = 370;
break;
case 'n-var.' :
$aso_code_infra['type'] = 'infra2';
$aso_code_infra['code'] = 3;
$aso_code_infra['rang'] = 380;
break;
case 'nvar.' :
$aso_code_infra['type'] = 'infra2';
$aso_code_infra['code'] = 3;
$aso_code_infra['rang'] = 384;
break;
case '[n-var.]' :
$aso_code_infra['type'] = 'infra2';
$aso_code_infra['code'] = 5;
$aso_code_infra['rang'] = 390;
break;
case 'prol.' :
case 'proles' :
$aso_code_infra['type'] = 'infra3';
$aso_code_infra['code'] = 2;
$aso_code_infra['rang'] = 330;
break;
case 'n-proles' :
case 'n-proles.' :
$aso_code_infra['type'] = 'infra3';
$aso_code_infra['code'] = 1;
$aso_code_infra['rang'] = 340;
break;
case 'f.':
case 'fa':
case 'fa.':
case 'forma':
$aso_code_infra['type'] = 'infra3';
$aso_code_infra['code'] = 3;
$aso_code_infra['rang'] = 420;
break;
case 'subvar.' :
$aso_code_infra['type'] = 'infra3';
$aso_code_infra['code'] = 4;
$aso_code_infra['rang'] = 410;
break;
case 'convar.' :
$aso_code_infra['type'] = 'infra3';
$aso_code_infra['code'] = 5;
$aso_code_infra['rang'] = 350;
break;
case 'cv.':
case 'Cv.':
$aso_code_infra['type'] = 'infra3';
$aso_code_infra['code'] = 6;
$aso_code_infra['rang'] = 460;
break;
case 'n-f.':
case 'n-fa':
case 'n-fa.':
$aso_code_infra['type'] = 'infra3';
$aso_code_infra['code'] = 7;
$aso_code_infra['rang'] = 430;
break;
case 'subf.':
case 'subfa':
case 'subfa.':
$aso_code_infra['type'] = 'infra3';
$aso_code_infra['code'] = 8;
$aso_code_infra['rang'] = 440;
break;
default:
$aso_code_infra['erreur_mark'] = 'erreur';
$aso_code_infra['erreur_notes'] = $str_abreviation_type_infra;
$aso_code_infra['rang'] = 2;
}
return $aso_code_infra;
}
public function attribuerCodeRang($str_abreviation_type_infra)
{
$aso_code_infra = $this->attribuerCodeInfra($str_abreviation_type_infra);
return $aso_code_infra['rang'];
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/nom_sci/DecoupageAuteur.php
New file
0,0 → 1,189
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Découpage des intitulés auteurs
*
* Description : classe permettant de découper les intitulés d'auteurs.
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Tela-Botanica 1999-2009
* @licence GPL v3 & CeCILL v2
* @version $Id: DecoupageAuteur.class.php 1873 2009-03-31 10:07:24Z Jean-Pascal MILCENT $
*/
// +-------------------------------------------------------------------------------------------------------------------+
class DecoupageAuteur extends Decoupage {
private $expression = array();
private $expression_in = array();
public function __construct()
{
parent::__construct();
$this->expresion[2] = '/^\s*\(([^)]+?)\) ('.$this->Auteur.') ex ('.$this->Auteur.')('.$this->Date.')?\s*$/u';
$this->expresion[3] = '/^\s*\(([^)]+?)\) ('.$this->Auteur.')('.$this->Date.')?\s*$/u';
$this->expresion[5] = '/^\s*('.$this->Auteur.') ex ('.$this->Auteur.')('.$this->Date.')?\s*$/u';
$this->expresion[6] = '/^\s*('.$this->Auteur.')('.$this->Date.')?\s*$/u';
$this->expresion[7] = '/^\s*\(([^)]+?)\) ('.$this->Auteur.'),? ('.$this->ComNom.')\s*$/u';
$this->expresion[8] = '/^\s*\(('.$this->Auteur.') ex ('.$this->Auteur.')\) ('.$this->ComNom.')\s*$/u';
$this->expresion[9] = '/^\s*('.$this->Auteur.') ex ('.$this->Auteur.'),? ('.$this->ComNom.')\s*$/u';
$this->expresion[10] = '/^\s*\(('.$this->Auteur.')\) ('.$this->ComNom.')\s*$/u';
$this->expresion[11] = '/^\s*('.$this->Auteur.'),? ('.$this->ComNom.')\s*$/u';
$this->expresion[12] = '/^\s*('.$this->ComNom.')\s*$/u';
$this->expresion[13] = '/^\s*\(('.$this->Auteur.')\) ('.$this->Auteur.'),? ('.$this->InAut.')\s*$/u';
$this->expresion[14] = '/^\s*\(('.$this->Auteur.') ex ('.$this->Auteur.')\) ('.$this->InAut.')\s*$/u';
$this->expresion[15] = '/^\s*('.$this->Auteur.') ex ('.$this->Auteur.'),? ('.$this->InAut.')\s*$/u';
$this->expresion[16] = '/^\s*\(('.$this->Auteur.')\) ('.$this->InAut.')\s*$/u';
$this->expresion[17] = '/^\s*('.$this->Auteur.') ('.$this->InAut.')\s*$/u';
$this->expresion[18] = '/^\s*('.$this->Auteur.'),? ('.$this->InAut.')\s*$/u';
$this->expresion[19] = '/^\s*('.$this->InAut.')\s*$/u';
$this->expresion_in[1] = '/^\s*[iI]n ('.$this->Auteur.') ?('.$this->ComNom.')?\s*$/u';
$this->expresion_in[2] = '/^\s*[iI]n ('.$this->NumAuteur.') ?('.$this->ComNom.')?\s*$/u';
}
public function decouper($str_intitule)
{
$aso_intitule = array( 'auteur_basio_ex' => '', 'auteur_basio' => '',
'auteur_modif_ex' => '', 'auteur_modif' => '',
'date' => '', 'annee' => '', 'commentaires_nomenclaturaux' => '',
'citation_in_auteur' => '', 'integration_ok' => 1,
'erreur_mark' => '', 'erreur_notes' => '');
if ($str_intitule != '') {
$morceau = array();
//Gestion des intitulés auteurs SANS commentaires nomenclaturaux
if (preg_match($this->expresion[6], $str_intitule, $morceau)) {
$aso_intitule['auteur_basio'] = $morceau[1];
$aso_intitule['date'] = $morceau[2];
$aso_date = $this->decouperDate($aso_intitule['date']);
$aso_intitule['annee'] = $aso_date['annee'];
} else if (preg_match($this->expresion[5], $str_intitule, $morceau)) {
$aso_intitule['auteur_basio_ex'] = $morceau[1];
$aso_intitule['auteur_basio'] = $morceau[2];
$aso_intitule['date'] = $morceau[3];
$aso_date = $this->decouperDate($aso_intitule['date']);
$aso_intitule['annee'] = $aso_date['annee'];
} else if (preg_match($this->expresion[3], $str_intitule, $morceau)) {
$aso_auteur = $this->decouperAuteurEx($morceau[1]);
$aso_intitule{'auteur_basio_ex'} = $aso_auteur['auteur_ex'];
$aso_intitule{'auteur_basio'} = $aso_auteur['auteur'];
$aso_intitule['erreur_mark'] = $aso_auteur['erreur_mark'];
$aso_intitule['erreur_notes'] = $str_intitule;
$aso_intitule{'auteur_modif'} = $morceau[2];
$aso_intitule{'date'} = $morceau[3];
$aso_date = $this->decouperDate($aso_intitule['date']);
$aso_intitule['annee'] = $aso_date['annee'];
} else if (preg_match($this->expresion[2], $str_intitule, $morceau)) {
$aso_auteur = $this->decouperAuteurEx($morceau[1]);
$aso_intitule{'auteur_basio_ex'} = $aso_auteur['auteur_ex'];
$aso_intitule{'auteur_basio'} = $aso_auteur['auteur'];
$aso_intitule['erreur_mark'] = $aso_auteur['erreur_mark'];
$aso_intitule['erreur_notes'] = $str_intitule;
$aso_intitule{'auteur_modif_ex'} = $morceau[2];
$aso_intitule{'auteur_modif'} = $morceau[3];
$aso_intitule{'date'} = $morceau[4];
$aso_date = $this->decouperDate($aso_intitule['date']);
$aso_intitule['annee'] = $aso_date['annee'];
} else if (preg_match($this->expresion[7], $str_intitule, $morceau)) {
// Gestion des intitulés auteurs AVEC commentaires nomenclaturaux
$aso_auteur = $this->decouperAuteurEx($morceau[1]);
$aso_intitule{'auteur_basio_ex'} = $aso_auteur['auteur_ex'];
$aso_intitule{'auteur_basio'} = $aso_auteur['auteur'];
$aso_intitule['erreur_mark'] = $aso_auteur['erreur_mark'];
$aso_intitule['erreur_notes'] = $str_intitule;
$aso_intitule{'auteur_modif'} = $morceau[2];
$aso_intitule{'commentaires_nomenclaturaux'} = $morceau[3];
} else if (preg_match($this->expresion[8], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio_ex'} = $morceau[1];
$aso_intitule{'auteur_basio'} = $morceau[2];
$aso_intitule{'commentaires_nomenclaturaux'} = $morceau[3];
} else if (preg_match($this->expresion[9], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio_ex'} = $morceau[1];
$aso_intitule{'auteur_basio'} = $morceau[2];
$aso_intitule{'commentaires_nomenclaturaux'} = $morceau[3];
} else if (preg_match($this->expresion[10], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio'} = $morceau[1];
$aso_intitule{'commentaires_nomenclaturaux'} = $morceau[2];
} else if (preg_match($this->expresion[11], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio'} = $morceau[1];
$aso_intitule{'commentaires_nomenclaturaux'} = $morceau[2];
} else if (preg_match($this->expresion[12], $str_intitule, $morceau)) {
$aso_intitule{'commentaires_nomenclaturaux'} = $morceau[1];
} else if (preg_match($this->expresion[13], $str_intitule, $morceau)) {
// Gestion des intitulés auteurs AVEC "in"
$aso_intitule{'auteur_basio'} = $morceau[1];
$aso_intitule{'auteur_modif'} = $morceau[2];
$aso_intitule{'citation_in_auteur'} = $morceau[3];
} else if (preg_match($this->expresion[14], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio_ex'} = $morceau[1];
$aso_intitule{'auteur_basio'} = $morceau[2];
$aso_intitule{'citation_in_auteur'} = $morceau[3];
} else if (preg_match($this->expresion[15], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio_ex'} = $morceau[1];
$aso_intitule{'auteur_basio'} = $morceau[2];
$aso_intitule{'citation_in_auteur'} = $morceau[3];
} else if (preg_match($this->expresion[16], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio'} = $morceau[1];
$aso_intitule{'citation_in_auteur'} = $morceau[2];
} else if (preg_match($this->expresion[17], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio'} = $morceau[1];
$aso_intitule{'citation_in_auteur'} = $morceau[2];
} else if (preg_match($this->expresion[18], $str_intitule, $morceau)) {
$aso_intitule{'auteur_basio'} = $morceau[1];
$aso_intitule{'citation_in_auteur'} = $morceau[2];
} else if (preg_match($this->expresion[19], $str_intitule, $morceau)) {
$aso_intitule{'citation_in_auteur'} = $morceau[1];
} else {
$aso_intitule['erreur_mark'] = 'erreur';
$aso_intitule['erreur_notes'] .= $str_intitule;
}
}
return $aso_intitule;
}
public function decouperIn($str_intitule)
{
$aso_intitule = array( 'in_intitule_auteur' => '', 'in_commentaire_nomenclatural' => '',
'erreur_mark' => '', 'erreur_notes' => '');
if ($str_intitule != '') {
$morceau = array();
if (preg_match($this->expresion_in[1], $str_intitule, $morceau)) {
$aso_intitule{'in_intitule_auteur'} = $morceau[1];
$aso_intitule{'in_commentaire_nomenclatural'} = $morceau[2];
} else if (preg_match($this->expresion_in[2], $str_intitule, $morceau)) {
$aso_intitule{'in_intitule_auteur'} = $morceau[1];
$aso_intitule{'in_commentaire_nomenclatural'} = $morceau[2];
} else {
$aso_intitule['erreur_mark'] = 'erreur';
$aso_intitule['erreur_notes'] .= $str_intitule;
}
}
return $aso_intitule;
}
private function decouperAuteurEx($chaine) {
$aso_retour = array('auteur_ex' => '', 'auteur' => '', 'erreur_mark' => '', 'erreur_notes' => '');
if (preg_match($this->expresion[5], $chaine, $morceau)) {
$aso_retour['auteur_ex'] = $morceau[1];
$aso_retour['auteur'] = $morceau[2];
} else if (preg_match($this->expresion[6], $chaine, $morceau)) {
$aso_retour['auteur'] = $morceau[1];
} else {
$aso_retour['erreur_mark'] = 'erreur';
$aso_retour['erreur_notes'] = $chaine;
}
return $aso_retour;
}
private function decouperDate($chaine)
{
$aso_retour = array('annee' => '');
if (preg_match('/^\[(\d{4})]\$/', $chaine, $morceau = array())) {
$aso_retour['annee'] = $morceau[1];
}
return $aso_retour;
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/nom_sci/DecoupageCitation.php
New file
0,0 → 1,106
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Découpage des citations bibliographiques.
*
* Description : classe permettant de découper les citations.
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Tela-Botanica 1999-2009
* @licence GPL v3 & CeCILL v2
* @version $Id: DecoupageCitation.class.php 1873 2009-03-31 10:07:24Z Jean-Pascal MILCENT $
*/
// +-------------------------------------------------------------------------------------------------------------------+
class DecoupageCitation extends Decoupage {
 
private $expression_principale = array();
private $expression_page = array();
 
function DecoupageCitation()
{
parent::__construct();
 
// Biblio
$this->expression_principale[1] = '/^(?:, |)(?:('.$this->Com.')|)(?:('.$this->In.'), |)(?:'.$this->Bib.'|)(?: ('.$this->Inf.')|)$/u';
// Biblio à exclure
$this->expression_principale[2] = '/^,? ('.$this->HomCourt.')$/u';
// Biblio : abréviation publi et précision (volume, tome, édition...)
$this->expression_ref[1] = '/^([^,$]+)(.*)$/u';//
// Pages début et fin
$this->expression_page[1] = '/^(\d+)-(\d+)$/u';//
// Page unique
$this->expression_page[2] = '/^(\d+)(?:\.|)$/u';//
}
public function decouper($citation)
{
$aso_nom_decompo = array( 'num_nomenc' => '', 'num_taxo' => '',
'in_auteur' => '', 'abreviation' => '', 'precision' => '',
'annee' => '', 'source_biblio_exclure' => '',
'info_combinaison' => '', 'page_debut' => null,'page_fin' => null,
'page_erreur_mark' => '', 'page_erreur_notes' => '');
$aso_nom_decompo['citation_complete'] = $citation;
while ($citation != '') {
$morceau = array();
if (preg_match($this->expression_principale[1], $citation, $morceau)) {// Biblio
$aso_nom_decompo['info_combinaison'] = $morceau[1];
$aso_nom_decompo['in_auteur'] = $morceau[2];
$aso_publi = $this->decouperPubli($morceau[3]);
$aso_nom_decompo['abreviation'] = $aso_publi['abreviation'];
$aso_nom_decompo['precision'] = $aso_publi['precision'];
$aso_nom_decompo['pages'] = $morceau[4];
$aso_pages = $this->decouperPages($morceau[4]);
$aso_nom_decompo['page_debut'] = $aso_pages['page_debut'];
$aso_nom_decompo['page_fin'] = $aso_pages['page_fin'];
$aso_nom_decompo['page_erreur_mark'] = $aso_pages['erreur_mark'];
$aso_nom_decompo['page_erreur_notes'] = $aso_pages['erreur_notes'];
$aso_nom_decompo['annee'] = $morceau[5];
$citation = $morceau[6];
} else if (preg_match($this->expression_principale[2], $citation, $morceau)) {// Nom d'sp.
$aso_nom_decompo['source_biblio_exclure'] = $morceau[1];
$citation = $morceau[2];
} else {// Erreurs
$aso_nom_decompo['erreur_mark'] = 'erreur';
$aso_nom_decompo['erreur_notes'] = $citation;
$citation = '';
}
}
return $aso_nom_decompo;
}
public function decouperPubli($ref)
{
$ref = trim($ref);
$aso_ref = array('abreviaton' => null,'precision' => null, 'erreur_mark' => '', 'erreur_notes' => '');
if (preg_match($this->expression_ref[1], $ref, $morceau)) {
$aso_ref['abreviation'] = $morceau[1];
$aso_ref['precision'] = preg_replace('/^\s*,\s*/', '', $morceau[2]);
} else {// Erreurs
$aso_ref['erreur_mark'] = 'erreur';
$aso_ref['erreur_notes'] = $ref;
}
return $aso_ref;
}
public function decouperPages($pages)
{
$pages = trim($pages);
$aso_pages = array('page_debut' => null,'page_fin' => null, 'erreur_mark' => '', 'erreur_notes' => '');
if (preg_match($this->expression_page[1], $pages, $morceau)) {
$aso_pages['page_debut'] = $morceau[1];
$aso_pages['page_fin'] = $morceau[2];
} else if (preg_match($this->expression_page[2], $pages, $morceau)) {
$aso_pages['page_debut'] = $morceau[1];
} else {// Erreurs
$aso_pages['erreur_mark'] = 'erreur';
$aso_pages['erreur_notes'] = $pages;
}
return $aso_pages;
}
}
?>
/tags/v5.3-amandaie/scripts/bibliotheque/Conteneur.php
New file
0,0 → 1,79
<?php
class Conteneur {
protected $parametres = array();
protected $partages = array();
 
public function __construct(array $parametres = null) {
$this->parametres = is_null($parametres) ? array() : $parametres;
}
 
public function getParametre($cle) {
$valeur = isset($this->parametres[$cle]) ? $this->parametres[$cle] : Config::get($cle);
return $valeur;
}
 
public function getParametreTableau($cle) {
$tableau = array();
$parametre = $this->getParametre($cle);
if (empty($parametre) === false) {
$tableauPartiel = explode(',', $parametre);
$tableauPartiel = array_map('trim', $tableauPartiel);
foreach ($tableauPartiel as $champ) {
if (strpos($champ, '=') === false) {
$tableau[] = trim($champ);
} else {
list($cle, $val) = explode('=', $champ);
$tableau[trim($cle)] = trim($val);
}
}
}
return $tableau;
}
 
public function setParametre($cle, $valeur) {
$this->parametres[$cle] = $valeur;
}
 
public function getOutils() {
if (!isset($this->partages['Outils'])){
$this->partages['Outils'] = new Outils();
}
return $this->partages['Outils'];
}
 
public function getEfloreCommun() {
if (!isset($this->partages['EfloreCommun'])){
$this->partages['EfloreCommun'] = new EfloreCommun($this);
}
return $this->partages['EfloreCommun'];
}
 
public function getMessages() {
if (!isset($this->partages['Messages'])){
$this->partages['Messages'] = new Messages($this->getParametre('-v'));
}
return $this->partages['Messages'];
}
 
public function getGenerateurNomSciHtml() {
if (!isset($this->partages['GenerateurNomSciHtml'])){
$this->partages['GenerateurNomSciHtml'] = new GenerateurNomSciHtml();
}
return $this->partages['GenerateurNomSciHtml'];
}
 
public function getRestClient() {
if (!isset($this->partages['RestClient'])){
$this->partages['RestClient'] = new RestClient();
}
return $this->partages['RestClient'];
}
 
public function getBdd() {
if (!isset($this->partages['Bdd'])){
$this->partages['Bdd'] = new Bdd();
}
return $this->partages['Bdd'];
}
}
?>
/tags/v5.3-amandaie/scripts/cli.php
New file
0,0 → 1,37
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Initialise le chargement et l'exécution des scripts
*
* Lancer ce fichier en ligne de commande avec :
* <code>/opt/lampp/bin/php cli.php mon_script -a test</code>
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @author Delphine CAUQUIL <delphine@tela-botanica.org>
* @copyright Tela-Botanica 1999-2008
* @licence GPL v3 & CeCILL v2
* @version $Id$
*/
// +-------------------------------------------------------------------------------------------------------------------+
 
// Le fichier Framework.php du Framework de Tela Botanica doit être appelée avant tout autre chose dans l'application.
// Sinon, rien ne sera chargé.
// Chemin du fichier chargeant le framework requis
$framework = dirname(__FILE__).DIRECTORY_SEPARATOR.'framework.php';
if (!file_exists($framework)) {
$e = "Veuillez paramétrer l'emplacement et la version du Framework dans le fichier $framework";
trigger_error($e, E_USER_ERROR);
} else {
// Inclusion du Framework
require_once $framework;
 
// Ajout d'information concernant cette application
Framework::setCheminAppli(__FILE__);// Obligatoire
Framework::setInfoAppli(Config::get('info'));
 
// Initialisation et lancement du script appelé en ligne de commande
Cli::executer();
}
?>
/tags/v5.3-amandaie/scripts/.
New file
Property changes:
Added: svn:ignore
+framework.php