/tags/v5.4-arboretum/initialiserBddSurServeur.sh |
---|
New file |
0,0 → 1,53 |
#!/bin/bash |
############################################################################################################## |
# But : Script permettant d'initialiser en une seule commande l'ensemble de la base de données eFlore. |
# Auteur : Jean-Pascal Milcent <jpm@tela-botanica.org> (translate bat file to shell script) |
# Encodage : ISO-8859-15 |
# License : GPL v3 |
# Création : 07 decembre 2011 |
# Version: 0.1 |
# 2012-03-21 : Création de la version serveur en ISO-8859-15, modification des chemins, suppression des scripts inutiles. |
# 2011-12-07 : Création de la version originale en UTF-8 |
# $Id$ |
############################################################################################################## |
# Constante |
APPDIR_ABSOLU=`pwd`; |
# |
CHEMIN_PHP="sudo -u telabotap /usr/local/bin" |
CHEMIN_TBF_CLI="$APPDIR_ABSOLU" |
MEMORY_LIMIT="4000M |
echo -e "\033[31m`tput blink`ATTENTION :`tput sgr0` Nécessite la création préalable de la base de données \033[31mtb_eflore\033[00m" |
echo "Nettoyage et chargement en cours..."; |
echo "BASEFLOR :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php baseflor -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php baseflor -a chargerTous |
echo "BDNT :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php bdnt -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php bdnt -a chargerTous |
echo "BDTFX :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php bdtfx -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php bdtfx -a chargerTous |
echo "CHORODEP :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php chorodep -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php chorodep -a chargerTous |
echo "EFLORE :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php eflore -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php eflore -a chargerTous |
echo "INSEE-D :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php insee_d -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php insee_d -a chargerTous |
echo "ISO-3166-1 :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php iso_3166_1 -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php iso_3166_1 -a chargerTous |
echo "ISO-639-1 :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php iso_639_1 -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php iso_639_1 -a chargerTous |
echo "NVJFL :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php nvjfl -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php nvjfl -a chargerTous |
echo "NVA :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php nva -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php nva -a chargerTous |
echo "PHOTOFLORA :"; |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php photoflora -a supprimerTous |
$CHEMIN_PHP/php -d memory_limit=$MEMORY_LIMIT $CHEMIN_TBF_CLI/cli.php photoflora -a chargerTous |
Property changes: |
Added: svn:eol-style |
+native |
\ No newline at end of property |
Added: svn:executable |
+* |
\ No newline at end of property |
/tags/v5.4-arboretum/Changelog |
---|
New file |
0,0 → 1,71 |
Changements <next>: |
Changements 2014-02-11 [création de la branche "v5.4-Arboretum"]: |
* nouvelle version baseflor |
* Les services Noms des trois référentiels (bdtfx, bdtxa, isfan) retournent maintenant en plus du libellé du rang, le code du rang dans "rang.code" lorsqu'on leur demande "champs.retour=rang" |
* script de création données ifn et vue tapir |
* script transformant les données des tables de tb_moissonnage à une table _tapir et une table meta dans tb_eflore |
* ajout du moissonage de l'ifn |
* interrogation ifn et baznat par num_nom et plus par nom_sci |
Changements 2014-01-06 [création de la branche "v5.3-Amandaie"]: |
* service presencemuseum |
* Protection du graphique Baseflor contre les données NULL |
* ajout de version chorodep |
* Coste/textes : REDIRECT_QUERY_STRING => QUERY_STRING |
* array_unique() sur les courriels de la carte de répartition |
Changements 20130912 [création de la branche "Acheb"]: |
* API change: coste |
* référentiels: bdtfx 2.00, ontologies 4.40 |
* config: |
- directives inutiles supprimées pour Coste [r857] |
- bdnt: ontologie: 4_40 |
* coste: réécriture du webservice |
Changements [[http://svn.tela-botanica.net/websvn/filedetails.php?repname=eFlore%2FProjets.eflore-projets&path=%2Ftrunk%2FChangelog&peg=839 v5.0-agropyraie-20130829]] : |
- tenue du Changelog |
- config: directives modifiées: |
- cache.miseEnCache |
- cache.dureeDeVie |
- cache.stockageChemin |
- ontologies: |
- support critères multiples bdnt |
- support critères multiples nvjfl |
- support critères multiples baseflor |
- cache d'appels pour bdtfx/meta-donnees |
- SQL hard-codé en place du HTTP dans certains cas |
- tests: nombreux ajouts et quelques changements de prototypes |
- scripts: |
- upgrades pour Cel |
- Makefile pour configuration/ |
- renommage de noms de classes en conflit: Cartes et Ontologies |
- améliorations dans l'usage du cache |
Changements v0.1-20130830-1: |
* nvjfl: fix notices |
* cache: correction du cache des synonymes (noms à 255 caractères) |
* cel/images: déduplication de auteurs au préalable de la requête d'identités |
* Note: erreur de tag sur "v0.1-20130830" |
Changements v0.1-20130829: |
* tenue du Changelog |
* config: directives modifiées: |
- cache.miseEnCache |
- cache.dureeDeVie |
- cache.stockageChemin |
* ontologies: |
* support critères multiples bdnt |
* support critères multiples nvjfl |
* support critères multiples baseflor |
* support critères multiples eflore |
* cache d'appels pour bdtfx/meta-donnees |
* SQL hard-codé en place du HTTP dans certains cas |
* tests: nombreux ajouts et quelques changements de prototypes |
* scripts: |
* upgrades pour Cel |
* Makefile pour configuration/ |
* renommage de noms de classes en conflit: Cartes et Ontologies |
* améliorations dans l'usage du cache |
v0.1-20130600 |
/tags/v5.4-arboretum/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.4-arboretum/scripts/configurations |
---|
New file |
Property changes: |
Added: svn:ignore |
+config.ini |
/tags/v5.4-arboretum/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.4-arboretum/scripts/.htaccess |
---|
New file |
0,0 → 1,2 |
order deny,allow |
deny from all |
/tags/v5.4-arboretum/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.4-arboretum/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.4-arboretum/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> </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 = " "; |
} 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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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 à à ÿ et œ |
protected $maj = "[A-Z'\x{C0}-\x{DF}\x{152}]";// Lettres majuscules : A à Z, ' et À à ß et Œ |
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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/scripts/tests/tmp |
---|
New file |
Property changes: |
Added: svn:ignore |
+test.defaut.ini |
+test.ini |
/tags/v5.4-arboretum/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.4-arboretum/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.4-arboretum/scripts/modules/baseflor/log |
---|
New file |
Property changes: |
Added: svn:ignore |
+test |
/tags/v5.4-arboretum/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.4-arboretum/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.4-arboretum/scripts/modules/baseflor/baseflor.ini |
---|
New file |
0,0 → 1,52 |
version="2014_01_06" |
dossierTsv = "{ref:dossierDonneesEflore}baseflor/2014-01-06/" |
dossierSql = "{ref:dossierTsv}" |
dossierRangSup = "{ref:dossierDonneesEflore}baseflor/2014-01-06/rang_sup/" |
dossierIndex = "{ref:dossierDonneesEflore}baseflor/2014-01-06/index/" |
[tables] |
donnees = "baseflor_v{ref:version}" |
ontologies = "baseflor_ontologies" |
metadonnees = "baseflor_meta" |
rang_sup = "baseflor_rang_sup_ecologie_v{ref:version}" |
taxons = "bdtfx_v2_00"; |
index = "baseflor_index_v{ref:version}"; |
[fichiers] |
structureSql = "baseflor.sql" |
metadonnees = "insertion_baseflor_meta.sql" |
donnees = "baseflor_v{ref:version}.tsv" |
donnees_verif = "baseflor_verif.txt" |
ontologies = "baseflor_ontologies.tsv" |
rang_sup_sql = "baseflor_rang_sup_ecologie.sql" |
index_sql = "baseflor_index.sql" |
[chemins] |
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}" |
donnees = "{ref:dossierTsv}{ref:fichiers.donnees}" |
donnees_verif = "{ref:dossierTsv}{ref:fichiers.donnees_verif}" |
ontologies ="{ref:dossierTsv}{ref:fichiers.ontologies}" |
metadonnees = "{ref:dossierSql}{ref:fichiers.metadonnees}" |
rang_sup_sql = "{ref:dossierRangSup}{ref:fichiers.rang_sup_sql}" |
index_sql = "{ref:dossierIndex}{ref:fichiers.index_sql}" |
[services] |
url_base="http://localhost/" |
url_service_base="{ref:url_base}service:eflore:0.1/" |
[Parametres] |
typesBio = "A,a,B,b,C,c,Cfru,cfru,Csuf,csuf,Ccou,ccou,H,h,Heri,heri,Hsto,hsto,Hces,hces,Hros,hros,Hrub,hrub,Hbis,hbis,G,g,Gbul,gbul,Gtub,gtub,Grhi,grhi,T,t,Tver,tver,Test,test" |
sousTypesBio = "aqua,lia,épi,hpar,par,suc,semp,cad,car" |
signesSeuls = "?, x, x~, x=, xb, xB, -" |
signesNonSeuls = "~, =, b, B" |
intervalles = "1-9 = 23;24;25;26;28;29;31;32;33;34;35;37;38, |
1-12 = 27;36, |
0-9 = 30;39" |
motifs = "/(^[0-9]*\/)|(inconnu)/ = 1, |
/(^[AB]?[0-9]+$)|(^nc$)/ = 2;3, |
/[^0-9]+/ = 4;5;6;7;8;9;10;11;12;13;16;19;20;21;22;40;41;42;43;44;45;46;47;48;49;50;51;52;53;54;55, |
/^([1-9]|1[0-2])(\-([1-9]|1[0-2]))*$/ = 14" |
champsEcologiques = "ve_lumiere,ve_temperature,ve_continentalite,ve_humidite_atmos,ve_humidite_edaph,ve_reaction_sol,ve_nutriments_sol,ve_salinite,ve_texture_sol,ve_mat_org_sol" |
/tags/v5.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/scripts/modules/sitemap/sitemap.ini |
---|
New file |
0,0 → 1,2 |
; Encodage : UTF-8 |
; ici mettre les variables du module |
/tags/v5.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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.4-arboretum/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 |
( |