Subversion Repositories eFlore/Projets.eflore-projets

Compare Revisions

No changes between revisions

Ignore whitespace Rev 1048 → Rev 1049

/tags/v5.7-arrayanal/scripts/.htaccess
New file
0,0 → 1,2
order deny,allow
deny from all
/tags/v5.7-arrayanal/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.7-arrayanal/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.7-arrayanal/scripts/bibliotheque/excel_reader/excel_reader2.php
New file
0,0 → 1,1610
<?php
/**
* A class for reading Microsoft Excel (97/2003) Spreadsheets.
*
* Version 2.22
*
* Enhanced and maintained by Alex Frenkel < excell2@frenkel-online.com >
* Maintained at http://code.google.com/p/php-excel-reader2/
*
* Previosly mantained by Matt Kruse < http://mattkruse.com >
* Maintained at http://code.google.com/p/php-excel-reader/
*
* Format parsing and MUCH more contributed by:
* Matt Roxburgh < http://www.roxburgh.me.uk >
*
* DOCUMENTATION
* =============
* http://code.google.com/p/php-excel-reader2/wiki/Documentation
*
* CHANGE LOG
* ==========
* http://code.google.com/p/php-excel-reader2/wiki/ChangeHistory
*
*
* --------------------------------------------------------------------------
*
* Originally developed by Vadim Tkachenko under the name PHPExcelReader.
* (http://sourceforge.net/projects/phpexcelreader)
* Based on the Java version by Andy Khan (http://www.andykhan.com). Now
* maintained by David Sanders. Reads only Biff 7 and Biff 8 formats.
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category Spreadsheet
* @package Spreadsheet_Excel_Reader
* @author Vadim Tkachenko <vt@apachephp.com>
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id: reader.php 19 2007-03-13 12:42:41Z shangxiao $
* @link http://pear.php.net/package/Spreadsheet_Excel_Reader
* @see OLE, Spreadsheet_Excel_Writer
* --------------------------------------------------------------------------
*/
 
define ( 'NUM_BIG_BLOCK_DEPOT_BLOCKS_POS', 0x2c );
define ( 'SMALL_BLOCK_DEPOT_BLOCK_POS', 0x3c );
define ( 'ROOT_START_BLOCK_POS', 0x30 );
define ( 'BIG_BLOCK_SIZE', 0x200 );
define ( 'SMALL_BLOCK_SIZE', 0x40 );
define ( 'EXTENSION_BLOCK_POS', 0x44 );
define ( 'NUM_EXTENSION_BLOCK_POS', 0x48 );
define ( 'PROPERTY_STORAGE_BLOCK_SIZE', 0x80 );
define ( 'BIG_BLOCK_DEPOT_BLOCKS_POS', 0x4c );
define ( 'SMALL_BLOCK_THRESHOLD', 0x1000 );
// property storage offsets
define ( 'SIZE_OF_NAME_POS', 0x40 );
define ( 'TYPE_POS', 0x42 );
define ( 'START_BLOCK_POS', 0x74 );
define ( 'SIZE_POS', 0x78 );
define ( 'IDENTIFIER_OLE', pack ( "CCCCCCCC", 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1 ) );
 
function GetInt4d($data, $pos) {
$value = ord ( $data [$pos] ) | (ord ( $data [$pos + 1] ) << 8) | (ord ( $data [$pos + 2] ) << 16) | (ord ( $data [$pos + 3] ) << 24);
if ($value >= 4294967294) {
$value = - 2;
}
return $value;
}
 
// http://uk.php.net/manual/en/function.getdate.php
function gmgetdate($ts = null) {
$k = array ('seconds', 'minutes', 'hours', 'mday', 'wday', 'mon', 'year', 'yday', 'weekday', 'month', 0 );
return (array_comb ( $k, explode ( ":", gmdate ( 's:i:G:j:w:n:Y:z:l:F:U', is_null ( $ts ) ? time () : $ts ) ) ));
}
 
// Added for PHP4 compatibility
function array_comb($array1, $array2) {
$out = array ();
foreach ( $array1 as $key => $value ) {
$out [$value] = $array2 [$key];
}
return $out;
}
 
function v($data, $pos) {
return ord ( $data [$pos] ) | ord ( $data [$pos + 1] ) << 8;
}
 
class OLERead {
var $data = '';
function OLERead() {
}
function read($sFileName) {
// check if file exist and is readable (Darko Miljanovic)
if (! is_readable ( $sFileName )) {
$this->error = 1;
return false;
}
$this->data = @file_get_contents ( $sFileName );
if (! $this->data) {
$this->error = 1;
return false;
}
if (substr ( $this->data, 0, 8 ) != IDENTIFIER_OLE) {
$this->error = 1;
return false;
}
$this->numBigBlockDepotBlocks = GetInt4d ( $this->data, NUM_BIG_BLOCK_DEPOT_BLOCKS_POS );
$this->sbdStartBlock = GetInt4d ( $this->data, SMALL_BLOCK_DEPOT_BLOCK_POS );
$this->rootStartBlock = GetInt4d ( $this->data, ROOT_START_BLOCK_POS );
$this->extensionBlock = GetInt4d ( $this->data, EXTENSION_BLOCK_POS );
$this->numExtensionBlocks = GetInt4d ( $this->data, NUM_EXTENSION_BLOCK_POS );
$bigBlockDepotBlocks = array ();
$pos = BIG_BLOCK_DEPOT_BLOCKS_POS;
$bbdBlocks = $this->numBigBlockDepotBlocks;
if ($this->numExtensionBlocks != 0) {
$bbdBlocks = (BIG_BLOCK_SIZE - BIG_BLOCK_DEPOT_BLOCKS_POS) / 4;
}
for($i = 0; $i < $bbdBlocks; $i ++) {
$bigBlockDepotBlocks [$i] = GetInt4d ( $this->data, $pos );
$pos += 4;
}
for($j = 0; $j < $this->numExtensionBlocks; $j ++) {
$pos = ($this->extensionBlock + 1) * BIG_BLOCK_SIZE;
$blocksToRead = min ( $this->numBigBlockDepotBlocks - $bbdBlocks, BIG_BLOCK_SIZE / 4 - 1 );
for($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; $i ++) {
$bigBlockDepotBlocks [$i] = GetInt4d ( $this->data, $pos );
$pos += 4;
}
$bbdBlocks += $blocksToRead;
if ($bbdBlocks < $this->numBigBlockDepotBlocks) {
$this->extensionBlock = GetInt4d ( $this->data, $pos );
}
}
// readBigBlockDepot
$pos = 0;
$index = 0;
$this->bigBlockChain = array ();
for($i = 0; $i < $this->numBigBlockDepotBlocks; $i ++) {
$pos = ($bigBlockDepotBlocks [$i] + 1) * BIG_BLOCK_SIZE;
//echo "pos = $pos";
for($j = 0; $j < BIG_BLOCK_SIZE / 4; $j ++) {
$this->bigBlockChain [$index] = GetInt4d ( $this->data, $pos );
$pos += 4;
$index ++;
}
}
// readSmallBlockDepot();
$pos = 0;
$index = 0;
$sbdBlock = $this->sbdStartBlock;
$this->smallBlockChain = array ();
while ( $sbdBlock != - 2 ) {
$pos = ($sbdBlock + 1) * BIG_BLOCK_SIZE;
for($j = 0; $j < BIG_BLOCK_SIZE / 4; $j ++) {
$this->smallBlockChain [$index] = GetInt4d ( $this->data, $pos );
$pos += 4;
$index ++;
}
$sbdBlock = $this->bigBlockChain [$sbdBlock];
}
// readData(rootStartBlock)
$block = $this->rootStartBlock;
$pos = 0;
$this->entry = $this->__readData ( $block );
$this->__readPropertySets ();
}
function __readData($bl) {
$block = $bl;
$pos = 0;
$data = '';
while ( $block != - 2 ) {
$pos = ($block + 1) * BIG_BLOCK_SIZE;
$data = $data . substr ( $this->data, $pos, BIG_BLOCK_SIZE );
$block = $this->bigBlockChain [$block];
}
return $data;
}
function __readPropertySets() {
$offset = 0;
while ( $offset < strlen ( $this->entry ) ) {
$d = substr ( $this->entry, $offset, PROPERTY_STORAGE_BLOCK_SIZE );
$nameSize = ord ( $d [SIZE_OF_NAME_POS] ) | (ord ( $d [SIZE_OF_NAME_POS + 1] ) << 8);
$type = ord ( $d [TYPE_POS] );
$startBlock = GetInt4d ( $d, START_BLOCK_POS );
$size = GetInt4d ( $d, SIZE_POS );
$name = '';
for($i = 0; $i < $nameSize; $i ++) {
$name .= $d [$i];
}
$name = str_replace ( "\x00", "", $name );
$this->props [] = array ('name' => $name, 'type' => $type, 'startBlock' => $startBlock, 'size' => $size );
if ((strtolower ( $name ) == "workbook") || (strtolower ( $name ) == "book")) {
$this->wrkbook = count ( $this->props ) - 1;
}
if ($name == "Root Entry") {
$this->rootentry = count ( $this->props ) - 1;
}
$offset += PROPERTY_STORAGE_BLOCK_SIZE;
}
}
function getWorkBook() {
if ($this->props [$this->wrkbook] ['size'] < SMALL_BLOCK_THRESHOLD) {
$rootdata = $this->__readData ( $this->props [$this->rootentry] ['startBlock'] );
$streamData = '';
$block = $this->props [$this->wrkbook] ['startBlock'];
$pos = 0;
while ( $block != - 2 ) {
$pos = $block * SMALL_BLOCK_SIZE;
$streamData .= substr ( $rootdata, $pos, SMALL_BLOCK_SIZE );
$block = $this->smallBlockChain [$block];
}
return $streamData;
} else {
$numBlocks = $this->props [$this->wrkbook] ['size'] / BIG_BLOCK_SIZE;
if ($this->props [$this->wrkbook] ['size'] % BIG_BLOCK_SIZE != 0) {
$numBlocks ++;
}
if ($numBlocks == 0)
return '';
$streamData = '';
$block = $this->props [$this->wrkbook] ['startBlock'];
$pos = 0;
while ( $block != - 2 ) {
$pos = ($block + 1) * BIG_BLOCK_SIZE;
$streamData .= substr ( $this->data, $pos, BIG_BLOCK_SIZE );
$block = $this->bigBlockChain [$block];
}
return $streamData;
}
}
 
}
 
define ( 'SPREADSHEET_EXCEL_READER_BIFF8', 0x600 );
define ( 'SPREADSHEET_EXCEL_READER_BIFF7', 0x500 );
define ( 'SPREADSHEET_EXCEL_READER_WORKBOOKGLOBALS', 0x5 );
define ( 'SPREADSHEET_EXCEL_READER_WORKSHEET', 0x10 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_BOF', 0x809 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_EOF', 0x0a );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_BOUNDSHEET', 0x85 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_DIMENSION', 0x200 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_ROW', 0x208 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_DBCELL', 0xd7 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FILEPASS', 0x2f );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_NOTE', 0x1c );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_TXO', 0x1b6 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_RK', 0x7e );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_RK2', 0x27e );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_MULRK', 0xbd );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_MULBLANK', 0xbe );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_INDEX', 0x20b );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_SST', 0xfc );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_EXTSST', 0xff );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_CONTINUE', 0x3c );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_LABEL', 0x204 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_LABELSST', 0xfd );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_NUMBER', 0x203 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_NAME', 0x18 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_ARRAY', 0x221 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_STRING', 0x207 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FORMULA', 0x406 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FORMULA2', 0x6 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FORMAT', 0x41e );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_XF', 0xe0 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_BOOLERR', 0x205 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_FONT', 0x0031 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_PALETTE', 0x0092 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_UNKNOWN', 0xffff );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_NINETEENFOUR', 0x22 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_MERGEDCELLS', 0xE5 );
define ( 'SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS', 25569 );
define ( 'SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS1904', 24107 );
define ( 'SPREADSHEET_EXCEL_READER_MSINADAY', 86400 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_HYPER', 0x01b8 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_COLINFO', 0x7d );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_DEFCOLWIDTH', 0x55 );
define ( 'SPREADSHEET_EXCEL_READER_TYPE_STANDARDWIDTH', 0x99 );
define ( 'SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT', "%s" );
 
/*
* Main Class
*/
class Spreadsheet_Excel_Reader {
// MK: Added to make data retrieval easier
var $colnames = array ();
var $colindexes = array ();
var $standardColWidth = 0;
var $defaultColWidth = 0;
function myHex($d) {
if ($d < 16)
return "0" . dechex ( $d );
return dechex ( $d );
}
function dumpHexData($data, $pos, $length) {
$info = "";
for($i = 0; $i <= $length; $i ++) {
$info .= ($i == 0 ? "" : " ") . $this->myHex ( ord ( $data [$pos + $i] ) ) . (ord ( $data [$pos + $i] ) > 31 ? "[" . $data [$pos + $i] . "]" : '');
}
return $info;
}
function getCol($col) {
if (is_string ( $col )) {
$col = strtolower ( $col );
if (array_key_exists ( $col, $this->colnames )) {
$col = $this->colnames [$col];
}
}
return $col;
}
// PUBLIC API FUNCTIONS
// --------------------
 
function val($row, $col, $sheet = 0) {
$col = $this->getCol ( $col );
if (array_key_exists ( $row, $this->sheets [$sheet] ['cells'] ) && array_key_exists ( $col, $this->sheets [$sheet] ['cells'] [$row] )) {
return $this->sheets [$sheet] ['cells'] [$row] [$col];
}
return "";
}
function value($row, $col, $sheet = 0) {
return $this->val ( $row, $col, $sheet );
}
function info($row, $col, $type = '', $sheet = 0) {
$col = $this->getCol ( $col );
if (array_key_exists ( 'cellsInfo', $this->sheets [$sheet] ) && array_key_exists ( $row, $this->sheets [$sheet] ['cellsInfo'] ) && array_key_exists ( $col, $this->sheets [$sheet] ['cellsInfo'] [$row] ) && array_key_exists ( $type, $this->sheets [$sheet] ['cellsInfo'] [$row] [$col] )) {
return $this->sheets [$sheet] ['cellsInfo'] [$row] [$col] [$type];
}
return "";
}
function type($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'type', $sheet );
}
function raw($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'raw', $sheet );
}
function rowspan($row, $col, $sheet = 0) {
$val = $this->info ( $row, $col, 'rowspan', $sheet );
if ($val == "") {
return 1;
}
return $val;
}
function colspan($row, $col, $sheet = 0) {
$val = $this->info ( $row, $col, 'colspan', $sheet );
if ($val == "") {
return 1;
}
return $val;
}
function hyperlink($row, $col, $sheet = 0) {
$link = $this->sheets [$sheet] ['cellsInfo'] [$row] [$col] ['hyperlink'];
if ($link) {
return $link ['link'];
}
return '';
}
function rowcount($sheet = 0) {
return $this->sheets [$sheet] ['numRows'];
}
function colcount($sheet = 0) {
return $this->sheets [$sheet] ['numCols'];
}
function colwidth($col, $sheet = 0) {
// Col width is actually the width of the number 0. So we have to estimate and come close
return $this->colInfo [$sheet] [$col] ['width'] / 9142 * 200;
}
function colhidden($col, $sheet = 0) {
return ! ! $this->colInfo [$sheet] [$col] ['hidden'];
}
function rowheight($row, $sheet = 0) {
return $this->rowInfo [$sheet] [$row] ['height'];
}
function rowhidden($row, $sheet = 0) {
return ! ! $this->rowInfo [$sheet] [$row] ['hidden'];
}
// GET THE CSS FOR FORMATTING
// ==========================
function style($row, $col, $sheet = 0, $properties = '') {
$css = "";
$font = $this->font ( $row, $col, $sheet );
if ($font != "") {
$css .= "font-family:$font;";
}
$align = $this->align ( $row, $col, $sheet );
if ($align != "") {
$css .= "text-align:$align;";
}
$height = $this->height ( $row, $col, $sheet );
if ($height != "") {
$css .= "font-size:$height" . "px;";
}
$bgcolor = $this->bgColor ( $row, $col, $sheet );
if ($bgcolor != "") {
$bgcolor = $this->colors [$bgcolor];
$css .= "background-color:$bgcolor;";
}
$color = $this->color ( $row, $col, $sheet );
if ($color != "") {
$css .= "color:$color;";
}
$bold = $this->bold ( $row, $col, $sheet );
if ($bold) {
$css .= "font-weight:bold;";
}
$italic = $this->italic ( $row, $col, $sheet );
if ($italic) {
$css .= "font-style:italic;";
}
$underline = $this->underline ( $row, $col, $sheet );
if ($underline) {
$css .= "text-decoration:underline;";
}
// Borders
$bLeft = $this->borderLeft ( $row, $col, $sheet );
$bRight = $this->borderRight ( $row, $col, $sheet );
$bTop = $this->borderTop ( $row, $col, $sheet );
$bBottom = $this->borderBottom ( $row, $col, $sheet );
$bLeftCol = $this->borderLeftColor ( $row, $col, $sheet );
$bRightCol = $this->borderRightColor ( $row, $col, $sheet );
$bTopCol = $this->borderTopColor ( $row, $col, $sheet );
$bBottomCol = $this->borderBottomColor ( $row, $col, $sheet );
// Try to output the minimal required style
if ($bLeft != "" && $bLeft == $bRight && $bRight == $bTop && $bTop == $bBottom) {
$css .= "border:" . $this->lineStylesCss [$bLeft] . ";";
} else {
if ($bLeft != "") {
$css .= "border-left:" . $this->lineStylesCss [$bLeft] . ";";
}
if ($bRight != "") {
$css .= "border-right:" . $this->lineStylesCss [$bRight] . ";";
}
if ($bTop != "") {
$css .= "border-top:" . $this->lineStylesCss [$bTop] . ";";
}
if ($bBottom != "") {
$css .= "border-bottom:" . $this->lineStylesCss [$bBottom] . ";";
}
}
// Only output border colors if there is an actual border specified
if ($bLeft != "" && $bLeftCol != "") {
$css .= "border-left-color:" . $bLeftCol . ";";
}
if ($bRight != "" && $bRightCol != "") {
$css .= "border-right-color:" . $bRightCol . ";";
}
if ($bTop != "" && $bTopCol != "") {
$css .= "border-top-color:" . $bTopCol . ";";
}
if ($bBottom != "" && $bBottomCol != "") {
$css .= "border-bottom-color:" . $bBottomCol . ";";
}
return $css;
}
// FORMAT PROPERTIES
// =================
function format($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'format', $sheet );
}
function formatIndex($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'formatIndex', $sheet );
}
function formatColor($row, $col, $sheet = 0) {
return $this->info ( $row, $col, 'formatColor', $sheet );
}
// CELL (XF) PROPERTIES
// ====================
function xfRecord($row, $col, $sheet = 0) {
$xfIndex = $this->info ( $row, $col, 'xfIndex', $sheet );
if ($xfIndex != "") {
return $this->xfRecords [$xfIndex];
}
return null;
}
function xfProperty($row, $col, $sheet, $prop) {
$xfRecord = $this->xfRecord ( $row, $col, $sheet );
if ($xfRecord != null) {
return $xfRecord [$prop];
}
return "";
}
function align($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'align' );
}
function bgColor($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'bgColor' );
}
function borderLeft($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'borderLeft' );
}
function borderRight($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'borderRight' );
}
function borderTop($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'borderTop' );
}
function borderBottom($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'borderBottom' );
}
function borderLeftColor($row, $col, $sheet = 0) {
return $this->colors [$this->xfProperty ( $row, $col, $sheet, 'borderLeftColor' )];
}
function borderRightColor($row, $col, $sheet = 0) {
return $this->colors [$this->xfProperty ( $row, $col, $sheet, 'borderRightColor' )];
}
function borderTopColor($row, $col, $sheet = 0) {
return $this->colors [$this->xfProperty ( $row, $col, $sheet, 'borderTopColor' )];
}
function borderBottomColor($row, $col, $sheet = 0) {
return $this->colors [$this->xfProperty ( $row, $col, $sheet, 'borderBottomColor' )];
}
// FONT PROPERTIES
// ===============
function fontRecord($row, $col, $sheet = 0) {
$xfRecord = $this->xfRecord ( $row, $col, $sheet );
if ($xfRecord != null) {
$font = $xfRecord ['fontIndex'];
if ($font != null) {
return $this->fontRecords [$font];
}
}
return null;
}
function fontProperty($row, $col, $sheet = 0, $prop) {
$font = $this->fontRecord ( $row, $col, $sheet );
if ($font != null) {
return $font [$prop];
}
return false;
}
function fontIndex($row, $col, $sheet = 0) {
return $this->xfProperty ( $row, $col, $sheet, 'fontIndex' );
}
function color($row, $col, $sheet = 0) {
$formatColor = $this->formatColor ( $row, $col, $sheet );
if ($formatColor != "") {
return $formatColor;
}
$ci = $this->fontProperty ( $row, $col, $sheet, 'color' );
return $this->rawColor ( $ci );
}
function rawColor($ci) {
if (($ci != 0x7FFF) && ($ci != '')) {
return $this->colors [$ci];
}
return "";
}
function bold($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'bold' );
}
function italic($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'italic' );
}
function underline($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'under' );
}
function height($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'height' );
}
function font($row, $col, $sheet = 0) {
return $this->fontProperty ( $row, $col, $sheet, 'font' );
}
// DUMP AN HTML TABLE OF THE ENTIRE XLS DATA
// =========================================
function dump($row_numbers = false, $col_letters = false, $sheet = 0, $table_class = 'excel') {
$out = "<table class=\"$table_class\" cellspacing=0>";
if ($col_letters) {
$out .= "<thead>\n\t<tr>";
if ($row_numbers) {
$out .= "\n\t\t<th>&nbsp</th>";
}
for($i = 1; $i <= $this->colcount ( $sheet ); $i ++) {
$style = "width:" . ($this->colwidth ( $i, $sheet ) * 1) . "px;";
if ($this->colhidden ( $i, $sheet )) {
$style .= "display:none;";
}
$out .= "\n\t\t<th style=\"$style\">" . strtoupper ( $this->colindexes [$i] ) . "</th>";
}
$out .= "</tr></thead>\n";
}
$out .= "<tbody>\n";
for($row = 1; $row <= $this->rowcount ( $sheet ); $row ++) {
$rowheight = $this->rowheight ( $row, $sheet );
$style = "height:" . ($rowheight * (4 / 3)) . "px;";
if ($this->rowhidden ( $row, $sheet )) {
$style .= "display:none;";
}
$out .= "\n\t<tr style=\"$style\">";
if ($row_numbers) {
$out .= "\n\t\t<th>$row</th>";
}
for($col = 1; $col <= $this->colcount ( $sheet ); $col ++) {
// Account for Rowspans/Colspans
$rowspan = $this->rowspan ( $row, $col, $sheet );
$colspan = $this->colspan ( $row, $col, $sheet );
for($i = 0; $i < $rowspan; $i ++) {
for($j = 0; $j < $colspan; $j ++) {
if ($i > 0 || $j > 0) {
$this->sheets [$sheet] ['cellsInfo'] [$row + $i] [$col + $j] ['dontprint'] = 1;
}
}
}
if (! $this->sheets [$sheet] ['cellsInfo'] [$row] [$col] ['dontprint']) {
$style = $this->style ( $row, $col, $sheet );
if ($this->colhidden ( $col, $sheet )) {
$style .= "display:none;";
}
$out .= "\n\t\t<td style=\"$style\"" . ($colspan > 1 ? " colspan=$colspan" : "") . ($rowspan > 1 ? " rowspan=$rowspan" : "") . ">";
$val = $this->val ( $row, $col, $sheet );
if ($val == '') {
$val = "&nbsp;";
} else {
$val = htmlentities ( $val, ENT_COMPAT, $this->_defaultEncoding );
$link = $this->hyperlink ( $row, $col, $sheet );
if ($link != '') {
$val = "<a href=\"$link\">$val</a>";
}
}
$out .= "<nobr>" . nl2br ( $val ) . "</nobr>";
$out .= "</td>";
}
}
$out .= "</tr>\n";
}
$out .= "</tbody></table>";
return $out;
}
// --------------
// END PUBLIC API
 
var $boundsheets = array ();
var $formatRecords = array ();
var $fontRecords = array ();
var $xfRecords = array ();
var $colInfo = array ();
var $rowInfo = array ();
var $sst = array ();
var $sheets = array ();
var $data;
var $_ole;
var $_defaultEncoding = "UTF-8";
var $_defaultFormat = SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT;
var $_columnsFormat = array ();
var $_rowoffset = 1;
var $_coloffset = 1;
/**
* List of default date formats used by Excel
*/
var $dateFormats = array (0xe => "m/d/Y", 0xf => "M-d-Y", 0x10 => "d-M", 0x11 => "M-Y", 0x12 => "h:i a", 0x13 => "h:i:s a", 0x14 => "H:i", 0x15 => "H:i:s", 0x16 => "d/m/Y H:i", 0x2d => "i:s", 0x2e => "H:i:s", 0x2f => "i:s.S" );
/**
* Default number formats used by Excel
*/
var $numberFormats = array (0x1 => "0", 0x2 => "0.00", 0x3 => "#,##0", 0x4 => "#,##0.00", 0x5 => "\$#,##0;(\$#,##0)", 0x6 => "\$#,##0;[Red](\$#,##0)", 0x7 => "\$#,##0.00;(\$#,##0.00)", 0x8 => "\$#,##0.00;[Red](\$#,##0.00)", 0x9 => "0%", 0xa => "0.00%", 0xb => "0.00E+00", 0x25 => "#,##0;(#,##0)", 0x26 => "#,##0;[Red](#,##0)", 0x27 => "#,##0.00;(#,##0.00)", 0x28 => "#,##0.00;[Red](#,##0.00)", 0x29 => "#,##0;(#,##0)", // Not exactly
0x2a => "\$#,##0;(\$#,##0)", // Not exactly
0x2b => "#,##0.00;(#,##0.00)", // Not exactly
0x2c => "\$#,##0.00;(\$#,##0.00)", // Not exactly
0x30 => "##0.0E+0" );
var $colors = Array (0x00 => "#000000", 0x01 => "#FFFFFF", 0x02 => "#FF0000", 0x03 => "#00FF00", 0x04 => "#0000FF", 0x05 => "#FFFF00", 0x06 => "#FF00FF", 0x07 => "#00FFFF", 0x08 => "#000000", 0x09 => "#FFFFFF", 0x0A => "#FF0000", 0x0B => "#00FF00", 0x0C => "#0000FF", 0x0D => "#FFFF00", 0x0E => "#FF00FF", 0x0F => "#00FFFF", 0x10 => "#800000", 0x11 => "#008000", 0x12 => "#000080", 0x13 => "#808000", 0x14 => "#800080", 0x15 => "#008080", 0x16 => "#C0C0C0", 0x17 => "#808080", 0x18 => "#9999FF", 0x19 => "#993366", 0x1A => "#FFFFCC", 0x1B => "#CCFFFF", 0x1C => "#660066", 0x1D => "#FF8080", 0x1E => "#0066CC", 0x1F => "#CCCCFF", 0x20 => "#000080", 0x21 => "#FF00FF", 0x22 => "#FFFF00", 0x23 => "#00FFFF", 0x24 => "#800080", 0x25 => "#800000", 0x26 => "#008080", 0x27 => "#0000FF", 0x28 => "#00CCFF", 0x29 => "#CCFFFF", 0x2A => "#CCFFCC", 0x2B => "#FFFF99", 0x2C => "#99CCFF", 0x2D => "#FF99CC", 0x2E => "#CC99FF", 0x2F => "#FFCC99", 0x30 => "#3366FF", 0x31 => "#33CCCC", 0x32 => "#99CC00", 0x33 => "#FFCC00", 0x34 => "#FF9900", 0x35 => "#FF6600", 0x36 => "#666699", 0x37 => "#969696", 0x38 => "#003366", 0x39 => "#339966", 0x3A => "#003300", 0x3B => "#333300", 0x3C => "#993300", 0x3D => "#993366", 0x3E => "#333399", 0x3F => "#333333", 0x40 => "#000000", 0x41 => "#FFFFFF",
 
0x43 => "#000000", 0x4D => "#000000", 0x4E => "#FFFFFF", 0x4F => "#000000", 0x50 => "#FFFFFF", 0x51 => "#000000",
 
0x7FFF => "#000000" );
var $lineStyles = array (0x00 => "", 0x01 => "Thin", 0x02 => "Medium", 0x03 => "Dashed", 0x04 => "Dotted", 0x05 => "Thick", 0x06 => "Double", 0x07 => "Hair", 0x08 => "Medium dashed", 0x09 => "Thin dash-dotted", 0x0A => "Medium dash-dotted", 0x0B => "Thin dash-dot-dotted", 0x0C => "Medium dash-dot-dotted", 0x0D => "Slanted medium dash-dotted" );
var $lineStylesCss = array ("Thin" => "1px solid", "Medium" => "2px solid", "Dashed" => "1px dashed", "Dotted" => "1px dotted", "Thick" => "3px solid", "Double" => "double", "Hair" => "1px solid", "Medium dashed" => "2px dashed", "Thin dash-dotted" => "1px dashed", "Medium dash-dotted" => "2px dashed", "Thin dash-dot-dotted" => "1px dashed", "Medium dash-dot-dotted" => "2px dashed", "Slanted medium dash-dotte" => "2px dashed" );
function read16bitstring($data, $start) {
$len = 0;
while ( ord ( $data [$start + $len] ) + ord ( $data [$start + $len + 1] ) > 0 )
$len ++;
return substr ( $data, $start, $len );
}
// ADDED by Matt Kruse for better formatting
function _format_value($format, $num, $f) {
// 49==TEXT format
// http://code.google.com/p/php-excel-reader/issues/detail?id=7
if ((! $f && $format == "%s") || ($f == 49) || ($format == "GENERAL")) {
return array ('string' => $num, 'formatColor' => null );
}
// Custom pattern can be POSITIVE;NEGATIVE;ZERO
// The "text" option as 4th parameter is not handled
$parts = explode ( ";", $format );
$pattern = $parts [0];
// Negative pattern
if (count ( $parts ) > 2 && $num == 0) {
$pattern = $parts [2];
}
// Zero pattern
if (count ( $parts ) > 1 && $num < 0) {
$pattern = $parts [1];
$num = abs ( $num );
}
$color = "";
$matches = array ();
$color_regex = "/^\[(BLACK|BLUE|CYAN|GREEN|MAGENTA|RED|WHITE|YELLOW)\]/i";
if (preg_match ( $color_regex, $pattern, $matches )) {
$color = strtolower ( $matches [1] );
$pattern = preg_replace ( $color_regex, "", $pattern );
}
// In Excel formats, "_" is used to add spacing, which we can't do in HTML
$pattern = preg_replace ( "/_./", "", $pattern );
// Some non-number characters are escaped with \, which we don't need
$pattern = preg_replace ( "/\\\/", "", $pattern );
// Some non-number strings are quoted, so we'll get rid of the quotes
$pattern = preg_replace ( "/\"/", "", $pattern );
// TEMPORARY - Convert # to 0
$pattern = preg_replace ( "/\#/", "0", $pattern );
// Find out if we need comma formatting
$has_commas = preg_match ( "/,/", $pattern );
if ($has_commas) {
$pattern = preg_replace ( "/,/", "", $pattern );
}
// Handle Percentages
if (preg_match ( "/\d(\%)([^\%]|$)/", $pattern, $matches )) {
$num = $num * 100;
$pattern = preg_replace ( "/(\d)(\%)([^\%]|$)/", "$1%$3", $pattern );
}
// Handle the number itself
$number_regex = "/(\d+)(\.?)(\d*)/";
if (preg_match ( $number_regex, $pattern, $matches )) {
$left = $matches [1];
$dec = $matches [2];
$right = $matches [3];
if ($has_commas) {
$formatted = number_format ( $num, strlen ( $right ) );
} else {
$sprintf_pattern = "%1." . strlen ( $right ) . "f";
$formatted = sprintf ( $sprintf_pattern, $num );
}
$pattern = preg_replace ( $number_regex, $formatted, $pattern );
}
return array ('string' => $pattern, 'formatColor' => $color );
}
/**
* Constructor
*
* Some basic initialisation
*/
function Spreadsheet_Excel_Reader($file = '', $store_extended_info = true, $outputEncoding = '') {
$this->_ole = new OLERead ( );
$this->setUTFEncoder ( 'iconv' );
if ($outputEncoding != '') {
$this->setOutputEncoding ( $outputEncoding );
}
for($i = 1; $i < 245; $i ++) {
$name = strtolower ( ((($i - 1) / 26 >= 1) ? chr ( ($i - 1) / 26 + 64 ) : '') . chr ( ($i - 1) % 26 + 65 ) );
$this->colnames [$name] = $i;
$this->colindexes [$i] = $name;
}
$this->store_extended_info = $store_extended_info;
if ($file != "") {
$this->read ( $file );
}
}
/**
* Set the encoding method
*/
function setOutputEncoding($encoding) {
$this->_defaultEncoding = $encoding;
}
/**
* $encoder = 'iconv' or 'mb'
* set iconv if you would like use 'iconv' for encode UTF-16LE to your encoding
* set mb if you would like use 'mb_convert_encoding' for encode UTF-16LE to your encoding
*/
function setUTFEncoder($encoder = 'iconv') {
$this->_encoderFunction = '';
if ($encoder == 'iconv') {
$this->_encoderFunction = function_exists ( 'iconv' ) ? 'iconv' : '';
} elseif ($encoder == 'mb') {
$this->_encoderFunction = function_exists ( 'mb_convert_encoding' ) ? 'mb_convert_encoding' : '';
}
}
function setRowColOffset($iOffset) {
$this->_rowoffset = $iOffset;
$this->_coloffset = $iOffset;
}
/**
* Set the default number format
*/
function setDefaultFormat($sFormat) {
$this->_defaultFormat = $sFormat;
}
/**
* Force a column to use a certain format
*/
function setColumnFormat($column, $sFormat) {
$this->_columnsFormat [$column] = $sFormat;
}
/**
* Read the spreadsheet file using OLE, then parse
*/
function read($sFileName) {
$res = $this->_ole->read ( $sFileName );
// oops, something goes wrong (Darko Miljanovic)
if ($res === false) {
// check error code
if ($this->_ole->error == 1) {
// bad file
die ( 'The filename ' . $sFileName . ' is not readable' );
}
// check other error codes here (eg bad fileformat, etc...)
}
$this->data = $this->_ole->getWorkBook ();
$this->_parse ();
}
/**
* Parse a workbook
*
* @access private
* @return bool
*/
function _parse() {
$pos = 0;
$data = $this->data;
$code = v ( $data, $pos );
$length = v ( $data, $pos + 2 );
$version = v ( $data, $pos + 4 );
$substreamType = v ( $data, $pos + 6 );
$this->version = $version;
if (($version != SPREADSHEET_EXCEL_READER_BIFF8) && ($version != SPREADSHEET_EXCEL_READER_BIFF7)) {
return false;
}
if ($substreamType != SPREADSHEET_EXCEL_READER_WORKBOOKGLOBALS) {
return false;
}
$pos += $length + 4;
$code = v ( $data, $pos );
$length = v ( $data, $pos + 2 );
while ( $code != SPREADSHEET_EXCEL_READER_TYPE_EOF ) {
switch ($code) {
case SPREADSHEET_EXCEL_READER_TYPE_SST :
$spos = $pos + 4;
$limitpos = $spos + $length;
$uniqueStrings = $this->_GetInt4d ( $data, $spos + 4 );
$spos += 8;
for($i = 0; $i < $uniqueStrings; $i ++) {
// Read in the number of characters
if ($spos == $limitpos) {
$opcode = v ( $data, $spos );
$conlength = v ( $data, $spos + 2 );
if ($opcode != 0x3c) {
return - 1;
}
$spos += 4;
$limitpos = $spos + $conlength;
}
$numChars = ord ( $data [$spos] ) | (ord ( $data [$spos + 1] ) << 8);
$spos += 2;
$optionFlags = ord ( $data [$spos] );
$spos ++;
$asciiEncoding = (($optionFlags & 0x01) == 0);
$extendedString = (($optionFlags & 0x04) != 0);
// See if string contains formatting information
$richString = (($optionFlags & 0x08) != 0);
if ($richString) {
// Read in the crun
$formattingRuns = v ( $data, $spos );
$spos += 2;
}
if ($extendedString) {
// Read in cchExtRst
$extendedRunLength = $this->_GetInt4d ( $data, $spos );
$spos += 4;
}
$len = ($asciiEncoding) ? $numChars : $numChars * 2;
if ($spos + $len < $limitpos) {
$retstr = substr ( $data, $spos, $len );
$spos += $len;
} else {
// found countinue
$retstr = substr ( $data, $spos, $limitpos - $spos );
$bytesRead = $limitpos - $spos;
$charsLeft = $numChars - (($asciiEncoding) ? $bytesRead : ($bytesRead / 2));
$spos = $limitpos;
while ( $charsLeft > 0 ) {
$opcode = v ( $data, $spos );
$conlength = v ( $data, $spos + 2 );
if ($opcode != 0x3c) {
return - 1;
}
$spos += 4;
$limitpos = $spos + $conlength;
$option = ord ( $data [$spos] );
$spos += 1;
if ($asciiEncoding && ($option == 0)) {
$len = min ( $charsLeft, $limitpos - $spos ); // min($charsLeft, $conlength);
$retstr .= substr ( $data, $spos, $len );
$charsLeft -= $len;
$asciiEncoding = true;
} elseif (! $asciiEncoding && ($option != 0)) {
$len = min ( $charsLeft * 2, $limitpos - $spos ); // min($charsLeft, $conlength);
$retstr .= substr ( $data, $spos, $len );
$charsLeft -= $len / 2;
$asciiEncoding = false;
} elseif (! $asciiEncoding && ($option == 0)) {
// Bummer - the string starts off as Unicode, but after the
// continuation it is in straightforward ASCII encoding
$len = min ( $charsLeft, $limitpos - $spos ); // min($charsLeft, $conlength);
for($j = 0; $j < $len; $j ++) {
$retstr .= $data [$spos + $j] . chr ( 0 );
}
$charsLeft -= $len;
$asciiEncoding = false;
} else {
$newstr = '';
for($j = 0; $j < strlen ( $retstr ); $j ++) {
$newstr = $retstr [$j] . chr ( 0 );
}
$retstr = $newstr;
$len = min ( $charsLeft * 2, $limitpos - $spos ); // min($charsLeft, $conlength);
$retstr .= substr ( $data, $spos, $len );
$charsLeft -= $len / 2;
$asciiEncoding = false;
}
$spos += $len;
}
}
if ($asciiEncoding)
$retstr = preg_replace ( "/(.)/s", "$1\0", $retstr );
$retstr = $this->_encodeUTF16 ( $retstr );
if ($richString) {
$spos += 4 * $formattingRuns;
}
// For extended strings, skip over the extended string data
if ($extendedString) {
$spos += $extendedRunLength;
}
$this->sst [] = $retstr;
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_FILEPASS :
return false;
break;
case SPREADSHEET_EXCEL_READER_TYPE_NAME :
break;
case SPREADSHEET_EXCEL_READER_TYPE_FORMAT :
$indexCode = v ( $data, $pos + 4 );
if ($version == SPREADSHEET_EXCEL_READER_BIFF8) {
$numchars = v ( $data, $pos + 6 );
if (ord ( $data [$pos + 8] ) == 0) {
$formatString = substr ( $data, $pos + 9, $numchars );
} else {
$formatString = substr ( $data, $pos + 9, $numchars * 2 );
}
} else {
$numchars = ord ( $data [$pos + 6] );
$formatString = substr ( $data, $pos + 7, $numchars * 2 );
}
$this->formatRecords [$indexCode] = $formatString;
break;
case SPREADSHEET_EXCEL_READER_TYPE_FONT :
$height = v ( $data, $pos + 4 );
$option = v ( $data, $pos + 6 );
$color = v ( $data, $pos + 8 );
$weight = v ( $data, $pos + 10 );
$under = ord ( $data [$pos + 14] );
$font = "";
// Font name
$numchars = ord ( $data [$pos + 18] );
if ((ord ( $data [$pos + 19] ) & 1) == 0) {
$font = substr ( $data, $pos + 20, $numchars );
} else {
$font = substr ( $data, $pos + 20, $numchars * 2 );
$font = $this->_encodeUTF16 ( $font );
}
$this->fontRecords [] = array ('height' => $height / 20, 'italic' => ! ! ($option & 2), 'color' => $color, 'under' => ! ($under == 0), 'bold' => ($weight == 700), 'font' => $font, 'raw' => $this->dumpHexData ( $data, $pos + 3, $length ) );
break;
case SPREADSHEET_EXCEL_READER_TYPE_PALETTE :
$colors = ord ( $data [$pos + 4] ) | ord ( $data [$pos + 5] ) << 8;
for($coli = 0; $coli < $colors; $coli ++) {
$colOff = $pos + 2 + ($coli * 4);
$colr = ord ( $data [$colOff] );
$colg = ord ( $data [$colOff + 1] );
$colb = ord ( $data [$colOff + 2] );
$this->colors [0x07 + $coli] = '#' . $this->myhex ( $colr ) . $this->myhex ( $colg ) . $this->myhex ( $colb );
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_XF :
$fontIndexCode = (ord ( $data [$pos + 4] ) | ord ( $data [$pos + 5] ) << 8) - 1;
$fontIndexCode = max ( 0, $fontIndexCode );
$indexCode = ord ( $data [$pos + 6] ) | ord ( $data [$pos + 7] ) << 8;
$alignbit = ord ( $data [$pos + 10] ) & 3;
$bgi = (ord ( $data [$pos + 22] ) | ord ( $data [$pos + 23] ) << 8) & 0x3FFF;
$bgcolor = ($bgi & 0x7F);
// $bgcolor = ($bgi & 0x3f80) >> 7;
$align = "";
if ($alignbit == 3) {
$align = "right";
}
if ($alignbit == 2) {
$align = "center";
}
$fillPattern = (ord ( $data [$pos + 21] ) & 0xFC) >> 2;
if ($fillPattern == 0) {
$bgcolor = "";
}
$xf = array ();
$xf ['formatIndex'] = $indexCode;
$xf ['align'] = $align;
$xf ['fontIndex'] = $fontIndexCode;
$xf ['bgColor'] = $bgcolor;
$xf ['fillPattern'] = $fillPattern;
$border = ord ( $data [$pos + 14] ) | (ord ( $data [$pos + 15] ) << 8) | (ord ( $data [$pos + 16] ) << 16) | (ord ( $data [$pos + 17] ) << 24);
$xf ['borderLeft'] = $this->lineStyles [($border & 0xF)];
$xf ['borderRight'] = $this->lineStyles [($border & 0xF0) >> 4];
$xf ['borderTop'] = $this->lineStyles [($border & 0xF00) >> 8];
$xf ['borderBottom'] = $this->lineStyles [($border & 0xF000) >> 12];
$xf ['borderLeftColor'] = ($border & 0x7F0000) >> 16;
$xf ['borderRightColor'] = ($border & 0x3F800000) >> 23;
$border = (ord ( $data [$pos + 18] ) | ord ( $data [$pos + 19] ) << 8);
$xf ['borderTopColor'] = ($border & 0x7F);
$xf ['borderBottomColor'] = ($border & 0x3F80) >> 7;
if (array_key_exists ( $indexCode, $this->dateFormats )) {
$xf ['type'] = 'date';
$xf ['format'] = $this->dateFormats [$indexCode];
if ($align == '') {
$xf ['align'] = 'right';
}
} elseif (array_key_exists ( $indexCode, $this->numberFormats )) {
$xf ['type'] = 'number';
$xf ['format'] = $this->numberFormats [$indexCode];
if ($align == '') {
$xf ['align'] = 'right';
}
} else {
$isdate = FALSE;
$formatstr = '';
if ($indexCode > 0) {
if (isset ( $this->formatRecords [$indexCode] ))
$formatstr = $this->formatRecords [$indexCode];
if ($formatstr != "") {
$tmp = preg_replace ( "/\;.*/", "", $formatstr );
$tmp = preg_replace ( "/^\[[^\]]*\]/", "", $tmp );
if (preg_match ( "/[^hmsday\/\-:\s\\\,AMP]/i", $tmp ) == 0) { // found day and time format
$isdate = TRUE;
$formatstr = $tmp;
$formatstr = str_replace ( array ('AM/PM', 'mmmm', 'mmm' ), array ('a', 'F', 'M' ), $formatstr );
// m/mm are used for both minutes and months - oh SNAP!
// This mess tries to fix for that.
// 'm' == minutes only if following h/hh or preceding s/ss
$formatstr = preg_replace ( "/(h:?)mm?/", "$1i", $formatstr );
$formatstr = preg_replace ( "/mm?(:?s)/", "i$1", $formatstr );
// A single 'm' = n in PHP
$formatstr = preg_replace ( "/(^|[^m])m([^m]|$)/", '$1n$2', $formatstr );
$formatstr = preg_replace ( "/(^|[^m])m([^m]|$)/", '$1n$2', $formatstr );
// else it's months
$formatstr = str_replace ( 'mm', 'm', $formatstr );
// Convert single 'd' to 'j'
$formatstr = preg_replace ( "/(^|[^d])d([^d]|$)/", '$1j$2', $formatstr );
$formatstr = str_replace ( array ('dddd', 'ddd', 'dd', 'yyyy', 'yy', 'hh', 'h' ), array ('l', 'D', 'd', 'Y', 'y', 'H', 'g' ), $formatstr );
$formatstr = preg_replace ( "/ss?/", 's', $formatstr );
}
}
}
if ($isdate) {
$xf ['type'] = 'date';
$xf ['format'] = $formatstr;
if ($align == '') {
$xf ['align'] = 'right';
}
} else {
// If the format string has a 0 or # in it, we'll assume it's a number
if (preg_match ( "/[0#]/", $formatstr )) {
$xf ['type'] = 'number';
if ($align == '') {
$xf ['align'] = 'right';
}
} else {
$xf ['type'] = 'other';
}
$xf ['format'] = $formatstr;
$xf ['code'] = $indexCode;
}
}
$this->xfRecords [] = $xf;
break;
case SPREADSHEET_EXCEL_READER_TYPE_NINETEENFOUR :
$this->nineteenFour = (ord ( $data [$pos + 4] ) == 1);
break;
case SPREADSHEET_EXCEL_READER_TYPE_BOUNDSHEET :
$rec_offset = $this->_GetInt4d ( $data, $pos + 4 );
$rec_typeFlag = ord ( $data [$pos + 8] );
$rec_visibilityFlag = ord ( $data [$pos + 9] );
$rec_length = ord ( $data [$pos + 10] );
if ($version == SPREADSHEET_EXCEL_READER_BIFF8) {
$chartype = ord ( $data [$pos + 11] );
if ($chartype == 0) {
$rec_name = substr ( $data, $pos + 12, $rec_length );
} else {
$rec_name = $this->_encodeUTF16 ( substr ( $data, $pos + 12, $rec_length * 2 ) );
}
} elseif ($version == SPREADSHEET_EXCEL_READER_BIFF7) {
$rec_name = substr ( $data, $pos + 11, $rec_length );
}
$this->boundsheets [] = array ('name' => $rec_name, 'offset' => $rec_offset );
break;
}
$pos += $length + 4;
$code = ord ( $data [$pos] ) | ord ( $data [$pos + 1] ) << 8;
$length = ord ( $data [$pos + 2] ) | ord ( $data [$pos + 3] ) << 8;
}
foreach ( $this->boundsheets as $key => $val ) {
$this->sn = $key;
$this->_parsesheet ( $val ['offset'] );
}
return true;
}
/**
* Parse a worksheet
*/
function _parsesheet($spos) {
$cont = true;
$data = $this->data;
// read BOF
$code = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$length = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$version = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
$substreamType = ord ( $data [$spos + 6] ) | ord ( $data [$spos + 7] ) << 8;
if (($version != SPREADSHEET_EXCEL_READER_BIFF8) && ($version != SPREADSHEET_EXCEL_READER_BIFF7)) {
return - 1;
}
if ($substreamType != SPREADSHEET_EXCEL_READER_WORKSHEET) {
return - 2;
}
$spos += $length + 4;
while ( $cont ) {
$lowcode = ord ( $data [$spos] );
if ($lowcode == SPREADSHEET_EXCEL_READER_TYPE_EOF)
break;
$code = $lowcode | ord ( $data [$spos + 1] ) << 8;
$length = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$spos += 4;
$this->sheets [$this->sn] ['maxrow'] = $this->_rowoffset - 1;
$this->sheets [$this->sn] ['maxcol'] = $this->_coloffset - 1;
unset ( $this->rectype );
switch ($code) {
case SPREADSHEET_EXCEL_READER_TYPE_DIMENSION :
if (! isset ( $this->numRows )) {
if (($length == 10) || ($version == SPREADSHEET_EXCEL_READER_BIFF7)) {
$this->sheets [$this->sn] ['numRows'] = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$this->sheets [$this->sn] ['numCols'] = ord ( $data [$spos + 6] ) | ord ( $data [$spos + 7] ) << 8;
} else {
$this->sheets [$this->sn] ['numRows'] = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
$this->sheets [$this->sn] ['numCols'] = ord ( $data [$spos + 10] ) | ord ( $data [$spos + 11] ) << 8;
}
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_MERGEDCELLS :
$cellRanges = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
for($i = 0; $i < $cellRanges; $i ++) {
$fr = ord ( $data [$spos + 8 * $i + 2] ) | ord ( $data [$spos + 8 * $i + 3] ) << 8;
$lr = ord ( $data [$spos + 8 * $i + 4] ) | ord ( $data [$spos + 8 * $i + 5] ) << 8;
$fc = ord ( $data [$spos + 8 * $i + 6] ) | ord ( $data [$spos + 8 * $i + 7] ) << 8;
$lc = ord ( $data [$spos + 8 * $i + 8] ) | ord ( $data [$spos + 8 * $i + 9] ) << 8;
if ($lr - $fr > 0) {
$this->sheets [$this->sn] ['cellsInfo'] [$fr + 1] [$fc + 1] ['rowspan'] = $lr - $fr + 1;
}
if ($lc - $fc > 0) {
$this->sheets [$this->sn] ['cellsInfo'] [$fr + 1] [$fc + 1] ['colspan'] = $lc - $fc + 1;
}
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_RK :
case SPREADSHEET_EXCEL_READER_TYPE_RK2 :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$rknum = $this->_GetInt4d ( $data, $spos + 6 );
$numValue = $this->_GetIEEE754 ( $rknum );
$info = $this->_getCellDetails ( $spos, $numValue, $column );
$this->addcell ( $row, $column, $info ['string'], $info );
break;
case SPREADSHEET_EXCEL_READER_TYPE_LABELSST :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$xfindex = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
$index = $this->_GetInt4d ( $data, $spos + 6 );
$this->addcell ( $row, $column, $this->sst [$index], array ('xfIndex' => $xfindex ) );
break;
case SPREADSHEET_EXCEL_READER_TYPE_MULRK :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$colFirst = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$colLast = ord ( $data [$spos + $length - 2] ) | ord ( $data [$spos + $length - 1] ) << 8;
$columns = $colLast - $colFirst + 1;
$tmppos = $spos + 4;
for($i = 0; $i < $columns; $i ++) {
$numValue = $this->_GetIEEE754 ( $this->_GetInt4d ( $data, $tmppos + 2 ) );
$info = $this->_getCellDetails ( $tmppos - 4, $numValue, $colFirst + $i + 1 );
$tmppos += 6;
$this->addcell ( $row, $colFirst + $i, $info ['string'], $info );
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_NUMBER :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$tmp = unpack ( "ddouble", substr ( $data, $spos + 6, 8 ) ); // It machine machine dependent
if ($this->isDate ( $spos )) {
$numValue = $tmp ['double'];
} else {
$numValue = $this->createNumber ( $spos );
}
$info = $this->_getCellDetails ( $spos, $numValue, $column );
$this->addcell ( $row, $column, $info ['string'], $info );
break;
case SPREADSHEET_EXCEL_READER_TYPE_FORMULA :
case SPREADSHEET_EXCEL_READER_TYPE_FORMULA2 :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
if ((ord ( $data [$spos + 6] ) == 0) && (ord ( $data [$spos + 12] ) == 255) && (ord ( $data [$spos + 13] ) == 255)) {
//String formula. Result follows in a STRING record
// This row/col are stored to be referenced in that record
// http://code.google.com/p/php-excel-reader/issues/detail?id=4
$previousRow = $row;
$previousCol = $column;
} elseif ((ord ( $data [$spos + 6] ) == 1) && (ord ( $data [$spos + 12] ) == 255) && (ord ( $data [$spos + 13] ) == 255)) {
//Boolean formula. Result is in +2; 0=false,1=true
// http://code.google.com/p/php-excel-reader/issues/detail?id=4
if (ord ( $this->data [$spos + 8] ) == 1) {
$this->addcell ( $row, $column, "TRUE" );
} else {
$this->addcell ( $row, $column, "FALSE" );
}
} elseif ((ord ( $data [$spos + 6] ) == 2) && (ord ( $data [$spos + 12] ) == 255) && (ord ( $data [$spos + 13] ) == 255)) {
//Error formula. Error code is in +2;
} elseif ((ord ( $data [$spos + 6] ) == 3) && (ord ( $data [$spos + 12] ) == 255) && (ord ( $data [$spos + 13] ) == 255)) {
//Formula result is a null string.
$this->addcell ( $row, $column, '' );
} else {
// result is a number, so first 14 bytes are just like a _NUMBER record
$tmp = unpack ( "ddouble", substr ( $data, $spos + 6, 8 ) ); // It machine machine dependent
if ($this->isDate ( $spos )) {
$numValue = $tmp ['double'];
} else {
$numValue = $this->createNumber ( $spos );
}
$info = $this->_getCellDetails ( $spos, $numValue, $column );
$this->addcell ( $row, $column, $info ['string'], $info );
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_BOOLERR :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$string = ord ( $data [$spos + 6] );
$this->addcell ( $row, $column, $string );
break;
case SPREADSHEET_EXCEL_READER_TYPE_STRING :
// http://code.google.com/p/php-excel-reader/issues/detail?id=4
if ($version == SPREADSHEET_EXCEL_READER_BIFF8) {
// Unicode 16 string, like an SST record
$xpos = $spos;
$numChars = ord ( $data [$xpos] ) | (ord ( $data [$xpos + 1] ) << 8);
$xpos += 2;
$optionFlags = ord ( $data [$xpos] );
$xpos ++;
$asciiEncoding = (($optionFlags & 0x01) == 0);
$extendedString = (($optionFlags & 0x04) != 0);
// See if string contains formatting information
$richString = (($optionFlags & 0x08) != 0);
if ($richString) {
// Read in the crun
$formattingRuns = ord ( $data [$xpos] ) | (ord ( $data [$xpos + 1] ) << 8);
$xpos += 2;
}
if ($extendedString) {
// Read in cchExtRst
$extendedRunLength = $this->_GetInt4d ( $this->data, $xpos );
$xpos += 4;
}
$len = ($asciiEncoding) ? $numChars : $numChars * 2;
$retstr = substr ( $data, $xpos, $len );
$xpos += $len;
if ($asciiEncoding)
$retstr = preg_replace ( "/(.)/s", "$1\0", $retstr );
$retstr = $this->_encodeUTF16 ( $retstr );
} elseif ($version == SPREADSHEET_EXCEL_READER_BIFF7) {
// Simple byte string
$xpos = $spos;
$numChars = ord ( $data [$xpos] ) | (ord ( $data [$xpos + 1] ) << 8);
$xpos += 2;
$retstr = substr ( $data, $xpos, $numChars );
}
$this->addcell ( $previousRow, $previousCol, $retstr );
break;
case SPREADSHEET_EXCEL_READER_TYPE_ROW :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$rowInfo = ord ( $data [$spos + 6] ) | ((ord ( $data [$spos + 7] ) << 8) & 0x7FFF);
if (($rowInfo & 0x8000) > 0) {
$rowHeight = - 1;
} else {
$rowHeight = $rowInfo & 0x7FFF;
}
$rowHidden = (ord ( $data [$spos + 12] ) & 0x20) >> 5;
$this->rowInfo [$this->sn] [$row + 1] = Array ('height' => $rowHeight / 20, 'hidden' => $rowHidden );
break;
case SPREADSHEET_EXCEL_READER_TYPE_DBCELL :
break;
case SPREADSHEET_EXCEL_READER_TYPE_MULBLANK :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$cols = ($length / 2) - 3;
for($c = 0; $c < $cols; $c ++) {
$xfindex = ord ( $data [$spos + 4 + ($c * 2)] ) | ord ( $data [$spos + 5 + ($c * 2)] ) << 8;
$this->addcell ( $row, $column + $c, "", array ('xfIndex' => $xfindex ) );
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_LABEL :
$row = ord ( $data [$spos] ) | ord ( $data [$spos + 1] ) << 8;
$column = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$this->addcell ( $row, $column, substr ( $data, $spos + 8, ord ( $data [$spos + 6] ) | ord ( $data [$spos + 7] ) << 8 ) );
break;
case SPREADSHEET_EXCEL_READER_TYPE_EOF :
$cont = false;
break;
case SPREADSHEET_EXCEL_READER_TYPE_HYPER :
// Only handle hyperlinks to a URL
$row = ord ( $this->data [$spos] ) | ord ( $this->data [$spos + 1] ) << 8;
$row2 = ord ( $this->data [$spos + 2] ) | ord ( $this->data [$spos + 3] ) << 8;
$column = ord ( $this->data [$spos + 4] ) | ord ( $this->data [$spos + 5] ) << 8;
$column2 = ord ( $this->data [$spos + 6] ) | ord ( $this->data [$spos + 7] ) << 8;
$linkdata = Array ();
$flags = ord ( $this->data [$spos + 28] );
$udesc = "";
$ulink = "";
$uloc = 32;
$linkdata ['flags'] = $flags;
if (($flags & 1) > 0) { // is a type we understand
// is there a description ?
if (($flags & 0x14) == 0x14) { // has a description
$uloc += 4;
$descLen = ord ( $this->data [$spos + 32] ) | ord ( $this->data [$spos + 33] ) << 8;
$udesc = substr ( $this->data, $spos + $uloc, $descLen * 2 );
$uloc += 2 * $descLen;
}
$ulink = $this->read16bitstring ( $this->data, $spos + $uloc + 20 );
if ($udesc == "") {
$udesc = $ulink;
}
}
$linkdata ['desc'] = $udesc;
$linkdata ['link'] = $this->_encodeUTF16 ( $ulink );
for($r = $row; $r <= $row2; $r ++) {
for($c = $column; $c <= $column2; $c ++) {
$this->sheets [$this->sn] ['cellsInfo'] [$r + 1] [$c + 1] ['hyperlink'] = $linkdata;
}
}
break;
case SPREADSHEET_EXCEL_READER_TYPE_DEFCOLWIDTH :
$this->defaultColWidth = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
break;
case SPREADSHEET_EXCEL_READER_TYPE_STANDARDWIDTH :
$this->standardColWidth = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
break;
case SPREADSHEET_EXCEL_READER_TYPE_COLINFO :
$colfrom = ord ( $data [$spos + 0] ) | ord ( $data [$spos + 1] ) << 8;
$colto = ord ( $data [$spos + 2] ) | ord ( $data [$spos + 3] ) << 8;
$cw = ord ( $data [$spos + 4] ) | ord ( $data [$spos + 5] ) << 8;
$cxf = ord ( $data [$spos + 6] ) | ord ( $data [$spos + 7] ) << 8;
$co = ord ( $data [$spos + 8] );
for($coli = $colfrom; $coli <= $colto; $coli ++) {
$this->colInfo [$this->sn] [$coli + 1] = Array ('width' => $cw, 'xf' => $cxf, 'hidden' => ($co & 0x01), 'collapsed' => ($co & 0x1000) >> 12 );
}
break;
default :
break;
}
$spos += $length;
}
if (! isset ( $this->sheets [$this->sn] ['numRows'] ))
$this->sheets [$this->sn] ['numRows'] = $this->sheets [$this->sn] ['maxrow'];
if (! isset ( $this->sheets [$this->sn] ['numCols'] ))
$this->sheets [$this->sn] ['numCols'] = $this->sheets [$this->sn] ['maxcol'];
}
function isDate($spos) {
$xfindex = ord ( $this->data [$spos + 4] ) | ord ( $this->data [$spos + 5] ) << 8;
return ($this->xfRecords [$xfindex] ['type'] == 'date');
}
// Get the details for a particular cell
function _getCellDetails($spos, $numValue, $column) {
$xfindex = ord ( $this->data [$spos + 4] ) | ord ( $this->data [$spos + 5] ) << 8;
$xfrecord = $this->xfRecords [$xfindex];
$type = $xfrecord ['type'];
$format = $xfrecord ['format'];
$formatIndex = $xfrecord ['formatIndex'];
$fontIndex = $xfrecord ['fontIndex'];
$formatColor = "";
$rectype = '';
$string = '';
$raw = '';
if (isset ( $this->_columnsFormat [$column + 1] )) {
$format = $this->_columnsFormat [$column + 1];
}
if ($type == 'date') {
// See http://groups.google.com/group/php-excel-reader-discuss/browse_frm/thread/9c3f9790d12d8e10/f2045c2369ac79de
$rectype = 'date';
// Convert numeric value into a date
$utcDays = floor ( $numValue - ($this->nineteenFour ? SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS1904 : SPREADSHEET_EXCEL_READER_UTCOFFSETDAYS) );
$utcValue = ($utcDays) * SPREADSHEET_EXCEL_READER_MSINADAY;
$dateinfo = gmgetdate ( $utcValue );
$raw = $numValue;
$fractionalDay = $numValue - floor ( $numValue ) + .0000001; // The .0000001 is to fix for php/excel fractional diffs
 
$totalseconds = floor ( SPREADSHEET_EXCEL_READER_MSINADAY * $fractionalDay );
$secs = $totalseconds % 60;
$totalseconds -= $secs;
$hours = floor ( $totalseconds / (60 * 60) );
$mins = floor ( $totalseconds / 60 ) % 60;
$string = date ( $format, mktime ( $hours, $mins, $secs, $dateinfo ["mon"], $dateinfo ["mday"], $dateinfo ["year"] ) );
} else if ($type == 'number') {
$rectype = 'number';
$formatted = $this->_format_value ( $format, $numValue, $formatIndex );
$string = $formatted ['string'];
$formatColor = $formatted ['formatColor'];
$raw = $numValue;
} else {
if ($format == "") {
$format = $this->_defaultFormat;
}
$rectype = 'unknown';
$formatted = $this->_format_value ( $format, $numValue, $formatIndex );
$string = $formatted ['string'];
$formatColor = $formatted ['formatColor'];
$raw = $numValue;
}
return array ('string' => $string, 'raw' => $raw, 'rectype' => $rectype, 'format' => $format, 'formatIndex' => $formatIndex, 'fontIndex' => $fontIndex, 'formatColor' => $formatColor, 'xfIndex' => $xfindex );
}
function createNumber($spos) {
$rknumhigh = $this->_GetInt4d ( $this->data, $spos + 10 );
$rknumlow = $this->_GetInt4d ( $this->data, $spos + 6 );
$sign = ($rknumhigh & 0x80000000) >> 31;
$exp = ($rknumhigh & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknumhigh & 0x000fffff));
$mantissalow1 = ($rknumlow & 0x80000000) >> 31;
$mantissalow2 = ($rknumlow & 0x7fffffff);
$value = $mantissa / pow ( 2, (20 - ($exp - 1023)) );
if ($mantissalow1 != 0)
$value += 1 / pow ( 2, (21 - ($exp - 1023)) );
$value += $mantissalow2 / pow ( 2, (52 - ($exp - 1023)) );
if ($sign) {
$value = - 1 * $value;
}
return $value;
}
function addcell($row, $col, $string, $info = null) {
$this->sheets [$this->sn] ['maxrow'] = max ( $this->sheets [$this->sn] ['maxrow'], $row + $this->_rowoffset );
$this->sheets [$this->sn] ['maxcol'] = max ( $this->sheets [$this->sn] ['maxcol'], $col + $this->_coloffset );
$this->sheets [$this->sn] ['cells'] [$row + $this->_rowoffset] [$col + $this->_coloffset] = $string;
if ($this->store_extended_info && $info) {
foreach ( $info as $key => $val ) {
$this->sheets [$this->sn] ['cellsInfo'] [$row + $this->_rowoffset] [$col + $this->_coloffset] [$key] = $val;
}
}
}
function _GetIEEE754($rknum) {
if (($rknum & 0x02) != 0) {
$value = $rknum >> 2;
} else {
//mmp
// I got my info on IEEE754 encoding from
// http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
// The RK format calls for using only the most significant 30 bits of the
// 64 bit floating point value. The other 34 bits are assumed to be 0
// So, we use the upper 30 bits of $rknum as follows...
$sign = ($rknum & 0x80000000) >> 31;
$exp = ($rknum & 0x7ff00000) >> 20;
$mantissa = (0x100000 | ($rknum & 0x000ffffc));
$value = $mantissa / pow ( 2, (20 - ($exp - 1023)) );
if ($sign) {
$value = - 1 * $value;
}
//end of changes by mmp
}
if (($rknum & 0x01) != 0) {
$value /= 100;
}
return $value;
}
function _encodeUTF16($string) {
$result = $string;
if ($this->_defaultEncoding) {
switch ($this->_encoderFunction) {
case 'iconv' :
$result = iconv ( 'UTF-16LE', $this->_defaultEncoding, $string );
break;
case 'mb_convert_encoding' :
$result = mb_convert_encoding ( $string, $this->_defaultEncoding, 'UTF-16LE' );
break;
}
}
return $result;
}
function _GetInt4d($data, $pos) {
$value = ord ( $data [$pos] ) | (ord ( $data [$pos + 1] ) << 8) | (ord ( $data [$pos + 2] ) << 16) | (ord ( $data [$pos + 3] ) << 24);
if ($value >= 4294967294) {
$value = - 2;
}
return $value;
}
 
}
 
?>
/tags/v5.7-arrayanal/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.7-arrayanal/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.7-arrayanal/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.7-arrayanal/scripts/bibliotheque/nom_sci/Decoupage.php
New file
0,0 → 1,160
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Découpage
*
* Description : classe abstraite mettant en comun des expressions régulière pour le découpage des noms latins.
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Tela-Botanica 1999-2009
* @licence GPL v3 & CeCILL v2
* @version $Id: Decoupage.class.php 1873 2009-03-31 10:07:24Z Jean-Pascal MILCENT $
*/
// +-------------------------------------------------------------------------------------------------------------------+
abstract class Decoupage {
protected $min = '[a-z\x{E0}-\x{FF}\x{153}]';// Lettres minuscules : a à z et &#224; à &#255 et &#339;
protected $maj = "[A-Z'\x{C0}-\x{DF}\x{152}]";// Lettres majuscules : A à Z, ' et &#192; à &#223; et &#338;
protected $hyb = '[+xX]';
protected $SupraSp;// Nom de type suprasp.
protected $GenHy;// Hybride intergénérique
protected $Gen;// Genre
protected $Dou = '(?:\(\?\)|\?)';// Doute
protected $Epi_cv;// Epithete de cultivar
protected $Epi_nn_hy = '(?:nsp\.|)';// Epithète non nommé hybride
protected $Epi_nn = '(?:sp\.[1-9]?|spp\.|)';// Epithète non nommé
protected $Epi;// Epithete
//------------------------------------------------------------------------------------------------------------//
protected $Ran_ig = '[Ss]ect\.|subg(?:en|)\.|ser\.|subser\.';// Rang taxonomique infragénérique de type : sous-genre
protected $Ran_ig_gr = 'gr\.';// Rang taxonomique infragénérique de type : groupe
protected $Ran_ig_agg = 'agg\.';// Rang taxonomique infragénérique de type : aggrégat
protected $Ran_bo_i1 = 'subsp\.';// Rang taxonomique infraspécifique de niveau 1
protected $Ran_bo_i2 = 'var\.|subvar\.';// Rang taxonomique infraspécifique de niveau 2
protected $Ran_bo_i3 = 'f\.|fa\.|fa|forma';// Rang taxonomique infraspécifique de niveau 3
protected $Ran_bo_i4 = 'race|prole|proles|prol\.';// Rang taxonomique infraspécifique de niveau 4
protected $Ran_bo;// Rang taxonomique infraspécifique botanique non hybride
protected $Ran_hy_i1 = 'n-subsp\.|\[subsp\.\]|\[n-subsp\.\]';// Rang taxonomique infraspécifique hybride de niveau 1
protected $Ran_hy_i2 = '\[var\.\]|n-var\.|\[n-var\.\]';// Rang taxonomique infraspécifique hybride de niveau 2
protected $Ran_hy_i3 = '';// Rang taxonomique infraspécifique hybride de niveau 3
protected $Ran_hy_i4 = 'n-proles\.';// Rang taxonomique infraspécifique hybride de niveau 4
protected $Ran_hy;// Rang taxonomique infraspécifique hybridre
protected $Ran_ht = 'convar\.|[cC]v\.';// Rang taxonomique horticole
protected $Ran;// Rang taxonomique infraspécifique non hybride, hybride et horticole
//------------------------------------------------------------------------------------------------------------//
protected $Ini;// Initiale de prénoms
protected $Pre;// Prénoms
protected $Par = '(?i:de|des|le|la|de la|von|van|st\.|el)';// Particules
protected $ParSsEs = "(?i:st\.-|d)";// Particules sans espace après
protected $Nom; // Abreviation d'un nom d'auteur. Le "f." c'est pour "filius" et c'est collé au nom
protected $NomSpe = '(?:[A-Z]\. (?:DC\.|St\.-Hil\.))|\(?hort\.\)?|al\.';// Prénom + nom spéciaux : "hort." est utilisé comme un nom d'auteur mais cela signifie "des jardins". "DC." est une exception deux majuscule suivi d'un point.
protected $Int;// Intitulé d'auteurs (Prénom + Nom)
//------------------------------------------------------------------------------------------------------------//
protected $AutNo;// Intitulé auteur sans "ex", ni "&", ni "et", ni parenthèses
protected $AutNoTa;// Intitulé auteur sans "ex", ni "&", ni "et" mais avec parenthèses possible pour la nomenclature
protected $AutEx;// Intitulé auteur avec "ex"
protected $et = '(?:&|et)';
protected $AutExEt;// Intitulé auteur avec "ex" et "&" ou "et"
protected $AutEt;// Intitulé auteur avec "&" ou "et" et sans parenthèse spécifique à la nomenclature
protected $AutEtTa;// Intitulé auteur avec "&" ou "et" et avec ou sans parenthèse spécifique à la nomenclature
protected $AutBib;// Intitulés auteurs pour la biblio
protected $AutInc = 'AUTEUR\?';// Intitulé auteur spéciaux pouvant être trouvés entre parenthèses
protected $AutSpe;// Intitulé auteur spéciaux pouvant être trouvés entre parenthèses
protected $AutSpeSe;// Intitulé auteur spéciaux type "sensu"
protected $AutSpeTa;// Intitulé auteur spéciaux propre à la nomenclature
protected $Aut;// Tous les intitulés auteurs possibles
protected $Auteur;// Tous les intitulés auteurs possibles
//------------------------------------------------------------------------------------------------------------//
protected $ComEmend;// Commentaires nomenclaturaux
protected $ComPp = 'p\.p\.';// Commentaires nomenclaturaux
protected $Com;// Intitulé auteur spéciaux type "sensu"
protected $ComNom = '\(?(?:hort\. non .*|sensu .*|auct\..*|comb\.\s*(?:nov\.|ined\.)|comb?\.\s*nov\.\s*provis\.|stat\.\s*provis\.|nov\.\s*stat\.|stat\.\s*nov\.|p\.p\.|emend\.)\)?';
//------------------------------------------------------------------------------------------------------------//
protected $In;// In auteur
protected $AneMoCo = 'janvier|fevrier|mars|avril|mai|juin|juillet|ao\x{FB}t|septembre|octobre|novembre|decembre'; //Mois devant l'année
protected $AneMoAb = 'janv\.|f[e\x{E9}]v\.|sept\.|oct\.|d\x{E9}c\.'; //Mois devant l'année
protected $AneBaSi = '(?:\d{4}|\d{4} ?\?|DATE \?)';// Date
protected $AneBaCo = '(?:\d{4}-\d{4}|\d{4}-\d{2})';// Date
protected $AneDo = '\?';// Doute
protected $AneBa;// Date
protected $AneSpe;// Date
protected $Ane;// Date
//------------------------------------------------------------------------------------------------------------//
// Spécial BDNFF :
protected $Date = ' \[.*\]';
protected $Num = '[0-9]|3\*|4\*';# Gestion des numéros de flore
protected $NumAuteur;# Gestion des numéros de flore mélangés ou pas au nom d'auteur
//------------------------------------------------------------------------------------------------------------//
protected $BibBa;// Biblio de base : \x{B0} = ° \x{AB}\x{BB} = «» \x{26} = &
protected $Bib;// Biblio de taxon
protected $BibAu = '.+';// Biblio supplémentaire
//------------------------------------------------------------------------------------------------------------//
protected $ErrDet;// Biblio à exclure base
//------------------------------------------------------------------------------------------------------------//
protected $HomNon = 'non';// Homonymes à exclure : négation
protected $HomBa;// Homonymes à exclure base
protected $Hom;// Homonymes à exclure avec non et nec
protected $HomCourt;// Homonymes à exclure avec non et nec avec expression régulière plus courte!
//------------------------------------------------------------------------------------------------------------//
protected $Inf = '.*';// Informations supplémentaires
public function __construct()
{
//mb_internal_encoding('UTF-8');
//mb_regex_encoding('UTF-8');
//setlocale(LC_ALL, 'fr-fr');
$this->SupraSp = '(?:'.$this->maj.$this->min.'+|'.$this->maj.$this->min.'+-'.$this->maj.$this->min.'+)';// Nom de type suprasp.
$this->GenHy = "[Xx] $this->SupraSp";// Hybride intergénérique
$this->Gen = "$this->SupraSp|$this->GenHy";
$this->Epi_cv = "$this->maj.(?:$this->min|-)+";// Epithete de cultivar
$this->Epi_nn = $this->Epi_nn.$this->Epi_nn_hy;
$this->Epi = "(?:(?:$this->min|-|')+|$this->Epi_nn)";// Epithete
$this->Ran_ig = $this->Ran_ig.'|'.$this->Ran_ig_gr;
$this->Ran_bo = "$this->Ran_bo_i1|$this->Ran_bo_i2|$this->Ran_bo_i3|$this->Ran_bo_i4";// Rang taxonomique infraspécifique botanique non hybride
$this->Ran_hy = "$this->Ran_hy_i1|$this->Ran_hy_i2|$this->Ran_hy_i3|$this->Ran_hy_i4";// Rang taxonomique infraspécifique hybridre
$this->Ran = "(?:$this->Ran_ig|$this->Ran_bo|$this->Ran_hy|$this->Ran_ht)";// Rang taxonomique infraspécifique non hybride, hybride et horticole
$this->Ini = '(?:'.$this->maj.'[.]|'.$this->maj.$this->min.'+[.]?)';// Initiale de prénoms
$this->Pre = $this->Ini.'{1,3}|'.$this->Ini.'[\- ]'.$this->Ini;// Prénoms
$this->Nom = '(?:'.$this->maj."'".$this->maj.'|'.$this->maj.'|'.$this->maj.$this->min."+'".$this->min.'+)'.$this->min.'*[.]?(?: ?f\.|)';
$this->Int = "(?:(?:$this->Pre ?|)(?:$this->Par |$this->ParSsEs|)(?:$this->Nom|$this->Nom".'[\- .]'."$this->Nom)|$this->NomSpe)";// Intitulé d'auteurs (Prénom + Nom)
$this->AutNo = "$this->Int";// Intitulé auteur sans "ex", ni "&", ni "et", ni parenthèses
$this->AutNoTa = "$this->AutNo|$this->NomSpe $this->Int|\($this->Int\) $this->Int";// Intitulé auteur sans "ex", ni "&", ni "et" mais avec parenthèses possible pour la nomenclature
$this->AutEx = "\($this->Int\) $this->Int ex $this->Int|\($this->Int ex $this->Int\) $this->Int|$this->Int ex $this->Int";// Intitulé auteur avec "ex"
$this->AutExEt = "$this->Int $this->et $this->Int ex $this->Int|$this->Int $this->et $this->Int ex $this->Int $this->et $this->Int|$this->Int ex $this->Int $this->et $this->Int|\($this->Int ex $this->Int $this->et $this->Int\) $this->Int|\($this->Int ex $this->Int\) $this->Int $this->et $this->Int|\($this->Int $this->et $this->Int\) $this->Int ex $this->Int|$this->NomSpe $this->Int ex $this->Int";// Intitulé auteur avec "ex" et "&" ou "et"
$this->AutEt = "$this->Int $this->et $this->Int";// Intitulé auteur avec "&" ou "et" et sans parenthèse spécifique à la nomenclature
$this->AutEtTa = "\($this->Int\) $this->Int $this->et $this->Int|\($this->Int $this->et $this->Int\) $this->Int|$this->AutEt";// Intitulé auteur avec "&" ou "et" et avec ou sans parenthèse spécifique à la nomenclature
$this->AutBib = "(?:$this->AutNo|$this->AutEt)";// Intitulés auteurs pour la biblio
$this->AutSpe = "(?:sensu |)auct\.|auct\. mult\.|$this->AutInc";// Intitulé auteur spéciaux pouvant être trouvés entre parenthèses
$this->AutSpeSe = "sensu $this->AutBib";// Intitulé auteur spéciaux type "sensu"
$this->AutSpeTa = "$this->AutSpe|\((?:$this->AutSpe)\)|$this->AutSpeSe";// Intitulé auteur spéciaux propre à la nomenclature
$this->Aut = "(?:$this->AutExEt|$this->AutEx|$this->AutEtTa|$this->AutSpeTa|$this->AutNoTa)";// Tous les intitulés auteurs possibles
$this->Auteur = $this->Int.'|'.$this->Int.' '.$this->et.' '.$this->Int.'|(?:'.$this->Int.', )+'.$this->Int.' '.$this->et.' '.$this->Int;// Intitulé auteur avec "&" ou "et";
$this->ComEmend = "emend\. $this->AutBib";// Commentaires nomenclaturaux
$this->Com = "$this->ComEmend|$this->ComPp";// Intitulé auteur spéciaux type "sensu"
$this->In = "[iI]n $this->AutBib";// In auteur
$this->AneBa = "$this->AneBaSi|$this->AneBaCo";// Date
$this->AneSpe = "(?:$this->AneBa ?\[$this->AneBa\]|(?:$this->AneMoCo|$this->AneMoAb) $this->AneBaSi|$this->AneBaSi $this->AneBaSi)";// Date
$this->Ane = "$this->AneBa||$this->AneDo|$this->AneSpe";// Date
$this->BibBa = "(?:$this->maj$this->min*[.]?|in|hort\.)(?:$this->min*[.]?|[\d\/\- ,()'\x{B0}\x{26}\x{AB}\x{BB}[\]?])*";// Biblio de base : \x{B0} = ° \x{AB}\x{BB} = «» \x{26} = &
$this->Bib = "([^:]+):(.+?)\(($this->Ane)\)";// Biblio de taxon
$this->ErrDet = "($this->AutSpe,? non $this->Aut): ($this->Bib;?)+";// Biblio à exclure base
$this->HomBa = "$this->Aut \($this->Ane\)";// Homonymes à exclure base
$this->Hom = "$this->HomNon $this->HomBa(?: nec $this->HomBa)*?";// Homonymes à exclure avec non et nec
$this->HomCourt = "$this->HomNon .+?(?: nec .+?)*?";// Homonymes à exclure avec non et nec avec expression régulière plus courte!
$this->NumAuteur = $this->Num.'|(?:(?:'.$this->Num.'|'.$this->Auteur.'), )+(?:'.$this->Num.'|'.$this->Auteur.')';# Gestion des numéros de flore mélangés ou pas au nom d'auteur
}
}
?>
/tags/v5.7-arrayanal/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.7-arrayanal/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.7-arrayanal/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.7-arrayanal/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.7-arrayanal/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.7-arrayanal/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.7-arrayanal/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.7-arrayanal/scripts/tests/bibliotheque/GenerateurNomSciHtmlTest.php
New file
0,0 → 1,82
<?php
class GenerateurNomSciHtmlTest extends PHPUnit_Framework_TestCase {
 
public static function setUpBeforeClass() {
error_reporting(E_ALL);
define('DS', DIRECTORY_SEPARATOR);
require_once dirname(__FILE__).DS.'..'.DS.'..'.DS.'bibliotheque'.DS.'GenerateurNomSciHtml.php';
}
 
public function testGenerer() {
$nomsDecomposes[] = array(
'num_nom' => 1009,
'rang' => 340,
'nom_supra_generique' => '',
'genre' => 'Aegilops',
'epithete_infra_generique' => '',
'epithete_sp' => 'triuncialis',
'type_epithete' => 'var.',
'epithete_infra_sp' => 'nigroferruginea',
'cultivar_groupe' => '',
'nom_commercial' => '',
'cultivar' => '',
'annee' => '1923',
'auteur' => 'Popova',
'biblio_origine' => 'Trudy Prikl. Bot. Selekc., 13 : 476');
$generateur = new GenerateurNomSciHtml();
$nomsSciHtml = $generateur->generer($nomsDecomposes);
$nomSciHtmlGenere = $nomsSciHtml[1009];
$nomSciHtmlAttendu = '<span class="sci"><span class="gen">Aegilops</span> <span class="sp">triuncialis</span> <abbr class="type_epithete" title="Variété">var.</abbr> <span class="infra-sp">nigroferruginea</span></span>';
$this->assertEquals($nomSciHtmlAttendu, $nomSciHtmlGenere);
}
 
public function testGenererHybride() {
$nomsDecomposes[] = array(
'num_nom' => 179,
'rang' => 290,
'nom_supra_generique' => '',
'genre' => 'Acer',
'epithete_infra_generique' => '',
'epithete_sp' => 'x martinii',
'type_epithete' => '',
'epithete_infra_sp' => '',
'cultivar_groupe' => '',
'nom_commercial' => '',
'cultivar' => '',
'annee' => '1852',
'auteur' => 'Jord.',
'biblio_origine' => 'Pugill. Pl. Nov., 52'
);
$generateur = new GenerateurNomSciHtml();
$nomsSciHtml = $generateur->generer($nomsDecomposes);
$nomSciHtmlGenere = $nomsSciHtml[179];
$nomSciHtmlAttendu = '<span class="sci"><span class="gen">Acer</span> <span class="hyb">x <span class="sp">martinii</span></span></span>';
$this->assertEquals($nomSciHtmlAttendu, $nomSciHtmlGenere);
}
 
public function testGenererChimere() {
 
$nomsDecomposes[] = array(
'num_nom' => 80380,
'rang' => 290,
'nom_supra_generique' => '',
'genre' => '+ Cytisus',
'epithete_infra_generique' => '',
'epithete_sp' => 'adami',
'type_epithete' => '',
'epithete_infra_sp' => '',
'cultivar_groupe' => '',
'nom_commercial' => '',
'cultivar' => '',
'annee' => '1830',
'auteur' => 'Poit.',
'biblio_origine' => 'Ann. Soc. Hort. Paris, 7 : 96'
);
$generateur = new GenerateurNomSciHtml();
$nomsSciHtml = $generateur->generer($nomsDecomposes);
$nomSciHtmlGenere = $nomsSciHtml[80380];
$nomSciHtmlAttendu = '<span class="sci"><span class="chimere">+ <span class="gen">Cytisus</span></span> <span class="sp">adami</span></span>';
$this->assertEquals($nomSciHtmlAttendu, $nomSciHtmlGenere);
}
}
?>
/tags/v5.7-arrayanal/scripts/tests/bibliotheque/OutilsTest.php
New file
0,0 → 1,63
<?php
require_once dirname(__FILE__).'/../ScriptEflorePhpUnit.php';
 
class OutilsTest extends ScriptEflorePhpUnit {
 
public function testRecupererTableauConfigAssociatif() {
$chaineDeParametres = "param1=valeur1,\nparam2=valeur2";
$tableauDeParametres = Outils::recupererTableauConfig($chaineDeParametres);
$tableauDeParametresAttendus = array('param1' => 'valeur1','param2' => 'valeur2');
$this->assertEquals($tableauDeParametresAttendus, $tableauDeParametres);
}
 
public function testRecupererTableauConfigAssociatifAvecEspace() {
$chaineDeParametres = "param1 =valeur1 , \nparam2 = valeur2";
$tableauDeParametres = Outils::recupererTableauConfig($chaineDeParametres);
$tableauDeParametresAttendus = array('param1' => 'valeur1','param2' => 'valeur2');
$this->assertEquals($tableauDeParametresAttendus, $tableauDeParametres);
}
 
public function testRecupererTableauConfigSimple() {
$chaineDeParametres = "param1,\nparam2";
$tableauDeParametres = Outils::recupererTableauConfig($chaineDeParametres);
$tableauDeParametresAttendus = array('param1', 'param2');
$this->assertEquals($tableauDeParametresAttendus, $tableauDeParametres);
}
 
public function testRecupererTableauConfigSimpleAvecEspace() {
$chaineDeParametres = " param1 ,\n param2 ";
$tableauDeParametres = Outils::recupererTableauConfig($chaineDeParametres);
$tableauDeParametresAttendus = array('param1', 'param2');
$this->assertEquals($tableauDeParametresAttendus, $tableauDeParametres);
}
 
public function testExtraireRequetes() {
$contenuSql = "CREATE TABLE IF NOT EXISTS bdtfx_v1_01 (".
"num_nom int(9) NOT NULL DEFAULT '0',".
"num_nom_retenu varchar(9) CHARACTER SET utf8 DEFAULT NULL,".
") ENGINE=MyISAM DEFAULT CHARSET=utf8;\n\n".
"INSERT INTO bdtfx_meta (guid) VALUES".
"('urn:lsid:tela-botanica.org:bdtfx:1.01');\n".
"SELECT * FROM ma_table;";
$tableauDeRequetes = Outils::extraireRequetes($contenuSql);
$tableauDeRequetesAttendus = array("CREATE TABLE IF NOT EXISTS bdtfx_v1_01 (".
"num_nom int(9) NOT NULL DEFAULT '0',".
"num_nom_retenu varchar(9) CHARACTER SET utf8 DEFAULT NULL,".
") ENGINE=MyISAM DEFAULT CHARSET=utf8",
"INSERT INTO bdtfx_meta (guid) VALUES".
"('urn:lsid:tela-botanica.org:bdtfx:1.01')",
"SELECT * FROM ma_table");
$this->assertEquals($tableauDeRequetesAttendus, $tableauDeRequetes);
}
 
public function testAfficherAvancement() {
ob_start();
for ($i = 0; $i < 10; $i++) {
$tableauDeRequetes = Outils::afficherAvancement("Test");
}
$messageFinal = ob_get_clean();
$messageFinalAttendu = 'Test : 0'.chr(8).'1'.chr(8).'2'.chr(8).'3'.chr(8).'4'.chr(8).'5'.chr(8).'6'.chr(8).'7'.chr(8).'8'.chr(8).'9';
$this->assertEquals($messageFinalAttendu, $messageFinal);
}
}
?>
/tags/v5.7-arrayanal/scripts/tests/bibliotheque/EfloreScriptTest.php
New file
0,0 → 1,48
<?php
require_once dirname(__FILE__).'/../ScriptEflorePhpUnit.php';
 
class EfloreScriptTest extends ScriptEflorePhpUnit {
 
public function testChargerConfigDuProjetAvecFichiersIni() {
$cheminRacine = realpath(dirname(__FILE__).'/../tmp/').'/';
if (!file_exists($cheminRacine.'test.ini')) {
file_put_contents($cheminRacine.'test.ini', "[tables]\ntest=OK");
}
 
$script = $this->getMock('EfloreScript', array('getScriptChemin', 'getProjetNom', 'executer'));
$script->expects($this->any())->method('getScriptChemin')->will($this->returnValue($cheminRacine));
$script->expects($this->any())->method('getProjetNom')->will($this->returnValue('test'));
$chargerConfigDuProjet = self::getProtectedMethode($script, 'chargerConfigDuProjet');
$chargerConfigDuProjet->invoke($script);
 
$parametreConfig = Config::get('tables.test');
$this->assertEquals('OK', $parametreConfig);
}
 
public function testGetBdd() {
$nomDuScript = 'Test';
$parametresCli = array('-a' => 'tester', '-v' => '3');
$script = $this->getClasseAbstraite('EfloreScript', array($nomDuScript, $parametresCli));
$getBdd = self::getProtectedMethode($script, 'getBdd');
$bdd = $getBdd->invoke($script);
 
$this->assertTrue(is_object($bdd));
$this->assertEquals('Bdd', get_class($bdd));
}
 
public function testStopperLaBoucle() {
$nomDuScript = 'Test';
$parametresCli = array('-a' => 'tester', '-v' => '3');
$script = $this->getClasseAbstraite('EfloreScript', array($nomDuScript, $parametresCli));
$stopperLaBoucle = self::getProtectedMethode($script, 'stopperLaBoucle');
for ($i = 0; $i < 100; $i++) {
if ($stopperLaBoucle->invoke($script, '10')) {
break;
}
}
$this->assertEquals('9', $i);
}
 
}
 
?>
/tags/v5.7-arrayanal/scripts/tests/ScriptEflorePhpUnit.php
New file
0,0 → 1,92
<?php
// declare(encoding='UTF-8');
/**
* Classe contenant des méthodes :
* - d'intialisation des tests,
* - refactorisant le code des tests,
* - facilitant les tests.
*
* @category php 5.3
* @package Tests/Scripts
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
abstract class ScriptEflorePhpUnit extends PHPUnit_Framework_TestCase {
 
public static function setUpBeforeClass() {
error_reporting(E_ALL);
 
self::chargerFramework();
}
 
private static function chargerFramework() {
$cheminRacine = realpath(dirname(__FILE__).'/../').'/';
$framework = $cheminRacine.'framework.php';
if (!file_exists($framework)) {
$e = "Veuillez paramétrer l'emplacement et la version du Framework dans le fichier $framework";
trigger_error($e, E_USER_ERROR);
} else {
// Inclusion du Framework
require_once $framework;
 
// Ajout d'information concernant cette application
Framework::setCheminAppli($cheminRacine);// Obligatoire
}
}
 
//+------------------------------------------------------------------------------------------------------+
// Méthodes facilitant les tests
 
/**
* Récupère un bouchon de classe abstraite.
* Comment l'utiliser :
* $classeAstraite = $this->getClasseAbstraite('MaClasse', array('param1', 'param2'));
* $foo = $classeAstraite->methodeConcretePublique();
*
* @param String $classeNom Le nom de la classe
* @param Array $parametres Les paramètres à passer au constructeur.
* @return Object Le bouchon de la classe abstraite
*/
public function getClasseAbstraite($classeNom, Array $parametres) {
$efloreScript = $this->getMockForAbstractClass($classeNom, $parametres);
return $efloreScript;
}
 
/**
* Récupère une méthode privée d'une classe pour tester/documenter.
* Comment l'utiliser :
* MyClass->foo():
* $cls = new MyClass();
* $foo = self::getPrivateMethode($cls, 'foo');
* $foo->invoke($cls, $...);
*
* @param object $objet Une instance de votre classe
* @param string $methode Le nom de la méthode private
* @return ReflectionMethod La méthode demandée
*/
public static function getPrivateMethode($objet, $nomMethode) {
$classe = new ReflectionClass($objet);
$methode = $classe->getMethod($nomMethode);
$methode->setAccessible(true);
return $methode;
}
 
/**
* Récupère une méthode protégée d'une classe pour tester/documenter.
* Comment l'utiliser :
* MyClass->foo():
* $cls = new MyClass();
* $foo = self::getProtectedMethode($cls, 'foo');
* $foo->invoke($cls, $...);
* @param object $objet Une instance de votre classe
* @param string $methode Le nom de la méthode protected
* @return ReflectionMethod La méthode demandée
*/
public static function getProtectedMethode($objet, $nomMethode) {
return self::getPrivateMethode($objet, $nomMethode);
}
}
?>
/tags/v5.7-arrayanal/scripts/tests/tmp
New file
Property changes:
Added: svn:ignore
+test.defaut.ini
+test.ini
/tags/v5.7-arrayanal/scripts/modules/prometheus/prometheus.ini
New file
0,0 → 1,12
version="1_00"
dossierTsv = "{ref:dossierDonneesEflore}prometheus/v1.00_2003-02-18/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
ontologies = "prometheus_ontologies_v{ref:version}"
 
[fichiers]
structureSql = "prometheus_v1_00.sql"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
/tags/v5.7-arrayanal/scripts/modules/prometheus/Prometheus.php
New file
0,0 → 1,639
<?php
/**
* Exemple de lancement du script : /opt/lampp/bin/php cli.php ontologie -a analyser
*
*/
require_once dirname(__FILE__).DS.'Traduction.php';
 
class Prometheus extends EfloreScript {
 
private $projetDossier = '';
private $lecteur = null;
private $fichier = '';
private $lotsTermes = array();
private $lotsRelations = array();
private $lotsImages = array();
private $lotsPublications = array();
private $lotsAuteurs = array();
private $lotsHierarchie = array();
private $baseIdGroupe = 10000;
private $baseIdSousGroupe = 20000;
private $types = array(
'FREQUENCY_MODIFIERS' => 2,
'QUALIFIERS' => 3,
'RELATIVE_MODIFIERS' => 4,
'RELATIVE_VALUES' => 5,
'SPATIAL_MODIFIERS' => 6,
'LOCATER_REGIONS' => 7,
'TEMPORAL_MODIFIERS' => 8,
'UNIT_TERMS' => 9,
'QUANTITATIVE_PROPERTIES' => 10,
'NEW_QUALITATIVE_PROPERTIES' => 11,
'DISALLOWED_TERMS' => 20,
'QUALITATIVE_STATES' => 13,
'TYPE_OF_STRUCTURE_TERMS' => 14,
'STRUCTURE_TERMS' => 15,
'REGION_TERMS' => 16,
'GENERIC_STRUCTURES' => 17);
 
public function executer() {
try {
$this->initialiserProjet('prometheus');
$this->projetDossier = Config::get('dossierTsv');
 
$this->fichier = $this->projetDossier.'Ontology.xml';
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->lireFichierXml();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'analyser' :
$this->vider();
$this->lireFichierXml();
break;
case 'chargerTraductions' :
$this->viderTraductions();
$this->chargerTraductions();
break;
case 'vider' :
$this->vider();
case 'viderTraductions' :
$this->viderTraductions();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
 
/**
* Lit le fichier OSM et lance l'analyse des noeuds xml en fonction de leur type.
*/
private function lireFichierXml() {
$termes = array_keys($this->types);
$this->lecteur = new XMLReader();
if ($this->ouvrirFichierXml()) {
while ($this->lecteur->read()) {
if ($this->lecteur->nodeType == XMLREADER::ELEMENT) {
if (in_array($this->lecteur->localName, $termes)) {
$noeud = $this->obtenirNoeudSimpleXml();
$type = $this->lecteur->localName;
$this->traiterTermes($this->types[$type], $noeud->children());
} else if ($this->lecteur->localName == 'STATE_GROUPS') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterGroupes($noeud->children());
} else if ($this->lecteur->localName == 'NewQualitativeProperties') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterNouvellesQualites($noeud->children());
} else if ($this->lecteur->localName == 'RELATIONSHIPS') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterRelations($noeud->children());
} else if ($this->lecteur->localName == 'PICTURES') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterImages($noeud->children());
} else if ($this->lecteur->localName == 'CITATIONS') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterCitations($noeud->children());
} else if ($this->lecteur->localName == 'AUTHORS') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterAuteurs($noeud->children());
} else if ($this->lecteur->localName == 'TreeNode') {
$noeud = $this->obtenirNoeudSimpleXml();
$this->traiterHierarchie($noeud);
}
}
}
if (count($this->lotsTermes) > 0) {
$this->insererLotDeTermes();
}
if (count($this->lotsRelations) > 0) {
$this->insererLotDeRelations();
}
if (count($this->lotsImages) > 0) {
$this->insererLotImages();
}
if (count($this->lotsPublications) > 0) {
$this->insererLotDePublications();
}
if (count($this->lotsAuteurs) > 0) {
$this->insererLotAuteurs();
}
if (count($this->lotsHierarchie) > 0) {
$this->insererLotHierarchie();
}
}
}
 
private function ouvrirFichierXml() {
if ($this->lecteur->open($this->fichier) === false) {
throw new Exception("Impossible d'ouvrir le fichier XML : $this->fichier");
}
return true;
}
 
private function obtenirNoeudSimpleXml() {
$doc = new DOMDocument;
$element = $this->lecteur->expand();
$noeud = simplexml_import_dom($doc->importNode($element, true));
return $noeud;
}
 
private function traiterTermes($type, $termes) {
foreach ($termes as $terme) {
$id = (int) $terme->attributes()->GLOBALID;
if (isset($this->lotsTermes[$id]) === false) {
$valeur = array();
$valeur[] = (int) $id;
$valeur[] = (int) $type;
$valeur[] = (string) $terme->attributes()->term;
$valeur[] = (string) $this->obtenirDefinition($terme);
$valeur[] = (int) $this->obtenirPreference($terme);
$valeur[] = (int) $this->obtenirAuteur($terme);
$valeur[] = (int) $this->obtenirCitation($terme);
$valeur[] = (int) $this->obtenirImage($terme);
$this->lotsTermes[$id] = $valeur;
}
if (isset($terme->attributes()->parentID)) {
$relation = array();
$relation[] = (int) $terme->attributes()->GLOBALID;
$relation[] = (int) $terme->attributes()->parentID;
$relation[] = 'A POUR PARENT';
$this->ajouterRelation($relation);
}
if (isset($terme->attributes()->PARENT_STRUCTURE_ID)) {
$relation = array();
$relation[] = (int) $terme->attributes()->GLOBALID;
$relation[] = (int) $terme->attributes()->PARENT_STRUCTURE_ID;
$relation[] = 'A POUR STRUCTURE PARENTE';
$this->ajouterRelation($relation);
}
if (isset($terme->attributes()->stateOfNEWPROPERTYID)) {
$relation = array();
$relation[] = (int) $terme->attributes()->GLOBALID;
$relation[] = (int) $terme->attributes()->stateOfNEWPROPERTYID;
$relation[] = 'A POUR NOUVELLE QUALITE';
$this->ajouterRelation($relation);
}
}
}
 
private function obtenirDefinition($terme) {
$definition = null;
if (isset($terme->DEFINITION)) {
$definition = $terme->DEFINITION;
}
return $definition;
}
 
private function obtenirPreference($terme) {
$preference = '1';
if (isset($terme->attributes()->PREFERRED_TERM)) {
$valeur = (string) $terme->attributes()->PREFERRED_TERM;
$preference = (trim($valeur) == 'Disallowed Term') ? '0' : '1';
}
return $preference;
}
 
private function obtenirAuteur($terme) {
$auteur = 0;
if (isset($terme->attributes()->authorID)) {
$auteur = $terme->attributes()->authorID;
} elseif (isset($terme->attributes()->authorREF)) {
$auteur = $terme->attributes()->authorREF;
}
return $auteur;
}
 
private function obtenirCitation($terme) {
$citation = 0;
if (isset($terme->attributes()->citationID)) {
$citation = $terme->attributes()->citationID;
} elseif (isset($terme->attributes()->citationREF)) {
$citation = $terme->attributes()->citationREF;
}
return $citation;
}
 
private function obtenirImage($terme) {
$image = 0;
if (isset($terme->attributes()->pictureREF)) {
$image = $terme->attributes()->pictureREF;
}
return $image;
}
 
private function traiterGroupes($groupes) {
foreach ($groupes as $groupe) {
$id = $this->baseIdGroupe + (int) $groupe->attributes()->GROUP_ID;
if (isset($this->lotsTermes[$id]) === false) {
$valeur = array();
$valeur[] = (int) $id;
$valeur[] = 18;
$valeur[] = (string) $groupe->attributes()->groupName;
$valeur[] = '';
$valeur[] = 1;
$valeur[] = 0;
$valeur[] = 0;
$valeur[] = 0;
$this->lotsTermes[$id] = $valeur;
}
if (isset($groupe->STRUCTURES_LINKED_TO_GROUP)) {
foreach ($groupe->STRUCTURES_LINKED_TO_GROUP->children() as $structure) {
$relation = array();
$relation[] = (int) $structure->attributes()->GLOBALID;
$relation[] = (int) $id;
$relation[] = 'A POUR GROUPE';
$this->ajouterRelation($relation);
}
}
if (isset($groupe->STATES_IN_GROUP)) {
foreach ($groupe->STATES_IN_GROUP->children() as $etat) {
$relation = array();
$relation[] = (int) $id;
$relation[] = (int) $etat->attributes()->GLOBALID;
$relation[] = 'A POUR ETAT';
$this->ajouterRelation($relation);
}
}
if (isset($groupe->STATESUBGROUPS)) {
$this->traiterSousGroupes($id, $groupe->STATESUBGROUPS->children());
}
}
}
 
private function traiterSousGroupes($idGroupe, $sousGroupes) {
foreach ($sousGroupes as $sg) {
$id = $this->baseIdSousGroupe + (int) $sg->attributes()->STATESUBGROUP_GLOBALID;
if (isset($this->lotsTermes[$id]) === false) {
$valeur = array();
$valeur[] = (int) $id;
$valeur[] = 19;
$valeur[] = (string) $sg->attributes()->subgGroupName;
$valeur[] = '';
$valeur[] = 1;
$valeur[] = 0;
$valeur[] = 0;
$valeur[] = 0;
$this->lotsTermes[$id] = $valeur;
 
$relation = array();
$relation[] = (int) $idGroupe;
$relation[] = (int) $id;
$relation[] = 'A POUR SOUS-GROUPE';
$this->ajouterRelation($relation);
}
if (isset($sg->STATES_IN_SUBGROUP)) {
foreach ($sg->STATES_IN_SUBGROUP->children() as $etat) {
$relation = array();
$relation[] = (int) $id;
$relation[] = (int) $etat->attributes()->GLOBALID;
$relation[] = 'A POUR ETAT';
$this->ajouterRelation($relation);
}
}
}
}
 
private function traiterNouvellesQualites($qualites) {
foreach ($qualites as $qualite) {
$id = (int) $qualite->attributes()->IDSEQ;
if (isset($this->lotsTermes[$id]) === false) {
$valeur = array();
$valeur[] = (int) $id;
$valeur[] = 11;
$valeur[] = (string) $qualite->attributes()->term;
$valeur[] = (string) $this->obtenirDefinition($terme);
$valeur[] = (int) $this->obtenirPreference($terme);
$valeur[] = (int) $this->obtenirAuteur($terme);
$valeur[] = (int) $this->obtenirCitation($terme);
$valeur[] = (int) $this->obtenirImage($terme);
$this->lotsTermes[$id] = $valeur;
}
if (isset($qualite->attributes()->ParentPropertyID)) {
$relation = array();
$relation[] = (int) $qualite->attributes()->IDSEQ;
$relation[] = (int) $qualite->attributes()->ParentPropertyID;
$relation[] = 'A POUR PARENT';
$this->ajouterRelation($relation);
}
if (isset($qualite->MemberStates)) {
$etats = $qualite->MemberStates->children();
$idParent = $qualite->attributes()->IDSEQ;
$this->traiterEtatsMembre($etats, $idParent);
}
if (isset($qualite->Structures_linked_to_Property)) {
$structures = $qualite->Structures_linked_to_Property->children();
$idParent = $qualite->attributes()->IDSEQ;
$this->traiterStructuresLiees($structures, $idParent);
}
if (isset($qualite->ContextGroups)) {
$contextes = $qualite->ContextGroups->children();
if (count($contextes) > 0) {
foreach ($contextes as $contexte) {
$idParent = $contexte->attributes()->ID;
$structures = $contexte->Structures_linked_to_Context->children();
$this->traiterStructuresLiees($structures, $idParent);
$etats = $contexte->MemberStates->children();
$this->traiterEtatsMembre($etats, $idParent);
}
}
}
}
}
 
private function ajouterRelation($relation) {
$id = implode('-', $relation);
if (isset($this->lotsRelations[$id]) === false) {
$this->lotsRelations[$id] = $relation;
}
}
 
private function traiterEtatsMembre($etats, $idParent) {
if (count($etats) > 0) {
foreach ($etats as $etat) {
$relation = array();
$relation[] = (int) $idParent;
$relation[] = (int) $etat->attributes()->RefID;
$relation[] = 'A POUR ETAT';
$this->ajouterRelation($relation);
}
}
}
 
private function traiterStructuresLiees($structures, $idParent) {
if (count($structures) > 0) {
foreach ($structures as $structure) {
$relation = array();
$relation[] = (int) $structure->attributes()->RefID;
$relation[] = (int) $idParent;
$relation[] = 'A POUR PROPRIETE';
$this->ajouterRelation($relation);
}
}
}
 
private function traiterRelations($relations) {
foreach ($relations as $rel) {
$relation = array();
$relation[] = (int) $rel->attributes()->term1REF;
$relation[] = (int) $rel->attributes()->term2REF;
$relation[] = (string) $this->obtenirTypeRelation($rel->attributes()->relationship);
$this->ajouterRelation($relation);
}
}
 
private function obtenirTypeRelation($type) {
switch ($type) {
case 'ASSOCIATED WITH' :
$relation = 'ASSOCIE AVEC';
break;
case 'IS A PART OF' :
$relation = 'EST UNE PARTIE DE';
break;
case 'IS A TYPE OF' :
$relation = 'EST UN TYPE DE';
break;
default :
$relation = '';
}
return $relation;
}
 
private function traiterImages($images) {
foreach ($images as $img) {
$valeur = array();
$valeur[] = (int) $img->attributes()->ID;
$valeur[] = (string) $img->attributes()->NAME;
$valeur[] = (int) $img->attributes()->CITATION_REFID;
$this->lotsImages[] = $valeur;
}
}
 
private function traiterCitations($citations) {
foreach ($citations as $publi) {
$valeur = array();
$valeur[] = (int) $publi->attributes()->ID;
$valeur[] = (int) $publi->attributes()->primaryAuthorREF;
$valeur[] = (string) $publi->PUBLICATION;
$valeur[] = (string) $publi->DATE;
$valeur[] = (string) $publi->PAGE;
$this->lotsPublications[] = $valeur;
}
}
 
private function traiterAuteurs($auteurs) {
foreach ($auteurs as $auteur) {
$valeur = array();
$valeur[] = (int) $auteur->attributes()->ID;
$valeur[] = (string) $auteur->attributes()->givenNames;
$valeur[] = (string) $auteur->attributes()->surname;
$valeur[] = $this->obtenirDateNaissance((string) $auteur->attributes()->born);
$valeur[] = (string) $auteur->attributes()->died;
$this->lotsAuteurs[] = $valeur;
}
}
 
private function obtenirDateNaissance($annee) {
$date = $annee.'-00-00';
return $date;
}
 
private function traiterHierarchie($noeud) {
$valeur = array();
$valeur[] = (int) $noeud->attributes()->ID;
$valeur[] = (int) $noeud->attributes()->ParentNodeID;
$valeur[] = (string) $noeud->attributes()->pathAsNames;
$valeur[] = (string) $noeud->attributes()->pathAsID;
$valeur[] = (int) $noeud->attributes()->TermID;
$this->lotsHierarchie[] = $valeur;
}
 
private function insererLotDeTermes() {
$champs = implode(',', array('id_terme', 'ce_type', 'nom_en', 'description_en', 'preference', 'ce_auteur', 'ce_publication', 'ce_image'));
$values = $this->creerValues($this->lotsTermes);
$requete = "INSERT INTO prometheus_ontologies_terme_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotDeRelations() {
$champs = implode(',', array('id_terme_01', 'id_terme_02', 'relation'));
$values = $this->creerValues($this->lotsRelations);
$requete = "INSERT INTO prometheus_ontologies_relation_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotImages() {
$champs = implode(',', array('id_image', 'uri', 'ce_publication'));
$values = $this->creerValues($this->lotsImages);
$requete = "INSERT INTO prometheus_ontologies_image_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotDePublications() {
$champs = implode(',', array('id_publication', 'ce_auteur_principal', 'titre', 'date', 'uri'));
$values = $this->creerValues($this->lotsPublications);
$requete = "INSERT INTO prometheus_ontologies_publication_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotAuteurs() {
$champs = implode(',', array('id_auteur', 'prenom', 'nom', 'naissance_date', 'deces_date'));
$values = $this->creerValues($this->lotsAuteurs);
$requete = "INSERT INTO prometheus_ontologies_auteur_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function insererLotHierarchie() {
$champs = implode(',', array('id_noeud', 'id_noeud_parent', 'chemin_noms', 'chemin_ids', 'ce_terme'));
$values = $this->creerValues($this->lotsHierarchie);
$requete = "INSERT INTO prometheus_ontologies_hierarchie_v1_00 ($champs) VALUES $values";
$this->executerSql($requete);
}
 
private function creerValues($valeurs) {
$values = array();
foreach ($valeurs as $valeur) {
foreach ($valeur as $id => $val) {
$valeur[$id] = $this->etreVide($val) ? 'NULL' : $this->proteger(trim($val));
}
$values[] = '('.implode(',', $valeur).')';
}
$values = implode(',', $values);
return $values;
}
 
private function etreVide($val) {
$vide = ($val === null || trim($val) === '') ? true : false;
return $vide;
}
 
private function executerSql($requete) {
$this->getBdd()->requeter($requete);
}
 
private function proteger($chaine) {
return $this->getBdd()->proteger($chaine);
}
 
private function viderTraductions() {
$requete = 'UPDATE prometheus_ontologies_terme_v1_00 '.
'SET nom = NULL, description = NULL, notes = NULL';
$this->executerSql($requete);
}
 
private function chargerTraductions() {
$dossier = $this->projetDossier.'traductions'.DS;
$pointeur = opendir($dossier);
while ($fichierNom = readdir($pointeur)) {
if (preg_match('/^[.]{1,2}/', $fichierNom) == false) {
$fichierChemin = $dossier.$fichierNom;
$lecteur = new LecteurExcel($fichierChemin);
//$this->verifierStructureFichierExcel($lecteur);
for ($ligne = 2; $ligne < $lecteur->getNbreLignes(); $ligne++) {
$traduction = new Traduction();
$traduction->type = $lecteur->getValeur($ligne, 1);
$traduction->en = $lecteur->getValeur($ligne, 2);
$traduction->fr = $lecteur->getValeur($ligne, 3);
$traduction->sourcesTraduction = $lecteur->getValeur($ligne, 4);
$traduction->remarques = $lecteur->getValeur($ligne, 5);
$traduction->sources = $lecteur->getValeur($ligne, 6);
$traduction->relectureRemarques = $lecteur->getValeur($ligne, 7);
$this->genererNotes($traduction);
 
$this->insererTraduction($traduction);
}
}
}
closedir($pointeur);
}
 
private function verifierStructureFichierExcel($lecteur) {
$messages = array();
$colonnes = array("Type d'élément", "Élément en anglais", "Traduction en français", "Sources de la traduction", "Remarques", "Sources", "Relecture/ Remarques");
foreach ($colonnes as $numero => $intitule) {
$valeurBrute = $lecteur->getValeur(1, ($numero + 1));
if ($valeurBrute != $intitule) {
$messages[] = "Le fichier {$lecteur->getFichier()} ne contient pas la bonne colonne #$numero : $intitule != $valeurBrute";
}
}
if (count($messages) > 0) {
throw new Exception(implode("\n", $messages));
}
}
 
private function genererNotes(Traduction $traduction) {
$notes = array();
if ($this->etreVide($traduction->sourcesTraduction) === false) {
$notes[] = "Sources de la traduction : ".$traduction->sourcesTraduction;
}
if ($this->etreVide($traduction->remarques) === false) {
$notes[] = "Remarques : ".$traduction->remarques;
}
if ($this->etreVide($traduction->sources) === false) {
$notes[] = "Sources : ".$traduction->sources;
}
if ($this->etreVide($traduction->relectureRemarques) === false) {
$notes[] = "Remarques sur la relecture : ".$traduction->relectureRemarques;
}
if (count($notes) > 0) {
$traduction->notes = implode("\n", $notes);
}
}
 
private function insererTraduction($traduction) {
$requete = null;
$notes = $traduction->notes;
if ($traduction->type == 'term') {
$notes = $this->proteger("Nom :\n".$notes);
$nom = $this->proteger($traduction->fr);
$nomEn = $this->proteger($traduction->en);
$requete = "UPDATE prometheus_ontologies_terme_v1_00 ".
"SET nom = $nom, notes = $notes ".
"WHERE nom_en = $nomEn ";
} else if ($traduction->type == 'DEFINITION') {
$notes = $this->proteger("Description :\n".$notes);
$description = $this->proteger($traduction->fr);
$descriptionEn = $this->proteger($traduction->en);
$requete = "UPDATE prometheus_ontologies_terme_v1_00 ".
"SET description = $description, notes = CONCAT(notes, '\n', $notes) ".
"WHERE description_en = $descriptionEn ";
}
if ($requete != null) {
$this->executerSql($requete);
}
}
 
private function vider() {
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_auteur_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_hierarchie_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_image_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_publication_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_relation_v1_00';
$this->executerSql($requete);
$requete = 'TRUNCATE TABLE IF EXISTS prometheus_ontologies_terme_v1_00';
$this->executerSql($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS prometheus_meta, prometheus_ontologies_auteur_v1_00, prometheus_ontologies_hierarchie_v1_00,
prometheus_ontologies_image_v1_00, prometheus_ontologies_publication_v1_00, prometheus_ontologies_relation_v1_00,
prometheus_ontologies_terme_v1_00, prometheus_ontologies_type_v1_00";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/prometheus/Traduction.php
New file
0,0 → 1,11
<?php
class Traduction {
public $type = null;
public $en = null;
public $fr = null;
public $sourcesTraduction = null;
public $remarques = null;
public $sources = null;
public $relectureRemarques = null;
public $notes = null;
}
/tags/v5.7-arrayanal/scripts/modules/bonnier/Bonnier.php
New file
0,0 → 1,508
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/* Importation des fichiers excel de Bonnier pour créer une version HTML pour PDA.
* Utilisation au préalable des utillitaire de traitement de fichier mdb sous Unix (voir ci après)
*
* Pré-requis :
* 1. Installer le paquet pour Perl nommé ParseExcel : urpmi perl-spreadsheet-parseexcel
* 2. Télécharger les fichiers Excel de Bonnier : http://www.tela-botanica.org/projets/74/documents/16211
* 3. Créer un dossier où vous dézipperez l'archive des fichiers Excel
* 4. Copier dans ce dossier les fichier xls2sql.pl et generer_sql.sh que vous trouverez dans le dossier shell de ce module
* 5. Donner les droits d'execution au fichier generer_sql.sh et lancer le : ./generer_sql.sh
* 6. Vous devez obtenir un fichier SQL par fichier Excel.
*
* Pour lancer ce script fichier par fichier :
* 1. Ouvrir une console et se positionner dans le dossier "scripts"
* 2. Pour charger le 1er fichier Excel, taper la commande : /opt/lampp/bin/php script.php bonnier -p bonnier -a charger -table renonculacees
* 3. Pour generer le html issu du chargement precedent :
* /opt/lampp/bin/php script.php bonnier -p bonnier -a html -dossier "menus/001-Renonculacees" -table renonculacees
*
* // Auteur original :
* @author David DELON <david@clapas.net>
* @copyright David DELON 2009
* @link http://www.tela-botanica.org/wikini/eflore
* @licence GPL v3 & CeCILL v2
* @version $Id$
*/
// +-------------------------------------------------------------------------------------------------------------------+
class Bonnier extends ScriptCommandeEflore {
 
/**
* Paramêtres disponible pour la ligne de commande
* le tableau se construit de la forme suivnate :
* - clé = nom du paramêtre '-foo'
* - value = contient un nouveau tableau composé de cette façaon :
* - booléen: true si le paramêtre est obligatoire
* - booléen ou var : true si le paramêtre nécessite un valeur à sa suite ou la valeur par défaut
* - string: description du contenu du paramêtre
* Les paramêtres optionels devraient être déclaré à la fin du tableau.
* Le dernier parametre du tableau peut avoir la valeur '...',
* il contiendra alors l'ensemble des paramêtres suivant trouvés sur la ligne de commande.
* @var array
*/
public $parametres = array( '-table' => array(true, true, "Nom de la table où seront stockées les données d'une famille"),
'-dossier' => array(true, true, "Dossier où sont générés les fichiers html pour la table"));
public function executer() {
 
error_reporting(E_ALL & ~E_DEPRECATED );
$table = $this->getParam('table');
$dossier = $this->getParam('dossier');
@mkdir($this->getIni('chemin_fichier_sortie').$dossier);
$cmd = $this->getParam('a');
switch ($cmd) {
// chargement des fichiers sql issus de la transformation xls dans la base de donnee, une table par fichir sql, 2 tables par
// familles : texte (navigation / clef) et plantes : description des plantes.
case 'charger' :
$this->creerTableBonnier($this->version, $table);
$this->chargerDonnees($table);
break;
case 'html' :
// tranformation sql vers html : pour la famille considerée : parcours de l'ensemble de ses clef et generation html pour
// les feuilles.
$this->realiserHtml($dossier, $table);
break;
default :
trigger_error('Erreur : la commande "'.$cmd.'" n\'existe pas!'."\n", E_USER_ERROR);
}
}
 
private function realiserHtml($dossier, $table) {
// Parcours de l'ensemble des données ? ou famille par famille ?
// on charge plante et texte dans des tableaux
$this->type_donnee = $table.'_texte';
$requete = 'SELECT * '.
'FROM '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.' '.
'ORDER BY uid';
$lignesTexte = $this->retournerDonneesRequete($requete);
// Analyse des données
echo "Analyse des données : ".$this->type_donnee."\n";
foreach ($lignesTexte as $ligneTexte) {
if (!isset($aso_lignes[$ligneTexte['identifiant']])) {
$aso_lignes[$ligneTexte['identifiant']] = $ligneTexte;
} else {
echo "identifiant en double : ".$ligneTexte['identifiant']."\n";
}
}
 
$this->type_donnee = $table.'_plante';
$requete = 'SELECT * '.
'FROM '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.' '.
'ORDER BY uid';
$lignesPlante = $this->retournerDonneesRequete($requete);
foreach ($lignesPlante as $lignePlante) {
if (!isset($aso_lignes[$lignePlante['identifiant']])) {
$aso_lignes[$lignePlante['identifiant']] = $lignePlante;
} else {
echo "identifiant en double : ".$lignePlante['identifiant']."\n";
}
}
//print_r($aso_lignes_texte[$lignesTexte[0]['identifiant']] ['titre']);
// $ariane : tableau des identifiants parcourus dans la branche
// $niveau : niveau dans l'arbre
$ariane = array();
$niveau = 0;
// Parcours de l'arbre des clefs depuis la racine
$this->genererHtmlTexte($lignesTexte[1]['identifiant'], $aso_lignes, $ariane, $niveau, $dossier);
}
// Generation des elements de navigation (clef)
private function genererHtmlTexte($identifiant, $lignesTexteIdentifiant, $ariane, $niveau, $dossier) {
 
$ariane[] = $identifiant;
$niveau++;
if (isset ($lignesTexteIdentifiant[$identifiant])) { // Si des identifiants sont en doubles
$ligneIdentifiant = $lignesTexteIdentifiant[$identifiant];
}
else {
// initialiser valeur par defaut indiquant une erreur
}
 
$f_html = fopen($this->getIni('chemin_fichier_sortie').$dossier.'/'.$identifiant.'.html', 'wb');
$html =
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n".
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n".
'<head>'."\n".
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n".
'<title>Flore BONNIER sur PDA</title>'."\n".
'<link rel="stylesheet" type="text/css" href="../../style/style640.css" media="screen" />'."\n".
'</head>'."\n";
$html .= '<body>'."\n";
$html .= '<div class="titre">'."\n";
$html .= '<p id="titre">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['titre'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
// print "identifiant : ".$ligneIdentifiant['identifiant']."\n";
// Destinations
// Branche niveau inferieur
$html.='<div class="fenetreMenu">'."\n";
for ($i = 1; $i < 6; $i++) {
if (isset($ligneIdentifiant['texte_'.$i]) && $ligneIdentifiant['texte_'.$i] != "") {
$html .= '<div class="menu'.($i-1).'">'."\n";
$html .= '<a href="'.$ligneIdentifiant['destination_'.$i].'.html">';
$html .= $ligneIdentifiant['texte_'.$i];
$html .= '</a>'."\n";
$html .= '</div>'."\n";
}
}
 
$html .= '</div>'."\n";
$html .= '<div class="espace" style="top:518px;">'."\n";
$html .= '</div>'."\n";
$html .= '<div class="navigation">'."\n";
$html .= '<p id="navigation">'."\n";
// Navigation
for ($i = 0; $i < $niveau; $i++) {
if (($ariane[$i]) && $ariane[$i] != '') {
$html .= '<a href="'.$ariane[$i].'.html">';
if (isset ($lignesTexteIdentifiant[$ariane[$i]])) { // Si des identifiants sont en doubles
$html .= $lignesTexteIdentifiant[$ariane[$i]]['titre'];
}
$html .= '</a>'."\n";
}
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
 
$html .= '<div class="retour">'."\n";
$html .= '<p id="retour">'."\n";
// Retour niveau superieur
if (isset($ariane[$niveau - 2]) && $ariane[$niveau - 2] != '') {
$html .= '<a href="'.$ariane[$niveau - 2].'.html">';
$html .= $lignesTexteIdentifiant[$ariane[$niveau - 2]]['titre'];
$html .= '</a>'."\n";
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="glossaire">'."\n";
$html .= '<p id="glossaire">'."\n";
$html .= '<a href="../000-general/glossaire0_640.html">'."\n";
$html .= 'Glossaire'."\n";
$html .= '</a>'."\n";
$html .= '</p></div><div class="text">'."\n";
$html .= '<p id="Text">'."\n";
$html .= '<a href="../000-general/accueil1_640.html">'."\n";
$html .= ' Top'."\n";
$html .= '</a>'."\n";
$html .= ' </p>'."\n";
$html .= '</div>'."\n";
 
$html .= '</body>'."\n";
$html .= '</html>'."\n";
fwrite($f_html, $html);
fclose($f_html);
// Ecriture des feuilles (description plantes)
for ($i = 1; $i < 6; $i++) {
if (isset($ligneIdentifiant['destination_'.$i]) && $ligneIdentifiant['destination_'.$i] != '') {
if (substr($ligneIdentifiant['destination_'.$i], 0, 1) == 'p') {
$this->genererHtmlPlante($ligneIdentifiant['destination_'.$i], $lignesTexteIdentifiant, $ariane, $niveau, $dossier);
} else {
$this->genererHtmlTexte($ligneIdentifiant['destination_'.$i], $lignesTexteIdentifiant, $ariane, $niveau, $dossier);
}
}
}
}
// Plante
private function genererHtmlPlante($identifiant, $lignesTexteIdentifiant, $ariane, $niveau, $dossier) {
$ariane[] = $identifiant;
$niveau++;
if (isset ($lignesTexteIdentifiant[$identifiant])) { // Au cas ou des identifiants sont en doubles
$ligneIdentifiant = $lignesTexteIdentifiant[$identifiant];
}
$nom_latin = '';
if (isset($ariane[($niveau - 2)]) && isset($lignesTexteIdentifiant[$ariane[($niveau - 2)]]['texte_1'])) {
$nom_latin = trim(strrchr($lignesTexteIdentifiant[$ariane[($niveau - 2)]]['texte_1'], ':'), ' :');
}
 
$f_html = fopen($this->getIni('chemin_fichier_sortie').$dossier.'/'.$identifiant.'.html', 'wb');
$html=
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n".
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n".
'<head>'."\n".
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n".
'<title>Flore BONNIER sur PDA</title>'."\n".
'<link rel="stylesheet" type="text/css" href="../../style/style_plante.css" media="screen" />'."\n".
'</head>'."\n";
$html .= '<body>'."\n";
$html .= '<div class="titre">'."\n";
$html .= '<p id="titre">';
$html .= $nom_latin;
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="famille">'."\n";
$html .= '<p id="famille1">Famille : </p>'."\n";
$html .= '<p id="famille2">';
$html .= $lignesTexteIdentifiant[$ariane[0]]['titre'];
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="genre">'."\n";
$html .= '<p id="genre1">Genre : </p>'."\n";
$html .= '<p id="genre2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['genre'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="nom_latin">'."\n";
$html .= '<p id="nom_latin1">Nom Latin : </p>'."\n";
$html .= '<p id="nom_latin2">';
$html .= $nom_latin;
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="nom_francais">'."\n";
$html .= '<p id="nom_francais1">Nom Francais : </p>'."\n";
$html .= '<p id="nom_francais2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['nom_francais'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="nom_commun">'."\n";
$html .= '<p id="nom_commun1">Nom Vulgaire : </p>'."\n";
$html .= '<p id="nom_commun2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['nom_vulgaire'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="caracteres">'."\n";
$html .= '<p id="caracteres1">Caractéristiques spécifiques : </p>'."\n";
$html .= '<p id="caracteres2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['description'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="habitat">'."\n";
$html .= '<p id="habitat1">Habitat / taille / floraison : </p>'."\n";
$html .= '<p id="habitat2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['habitat'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="aire">'."\n";
$html .= '<p id="aire1">Aire g&eacute;ographique : </p>'."\n";
$html .= '<p id="aire2">';
if (isset($ligneIdentifiant)) {
$html .= $ligneIdentifiant['geographie'];
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="identifiant">'."\n";
$html .= '<p id="identifiant">';
$html .= 'Bonnier : '.$identifiant;
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="planche">'."\n";
$html .= '<p id="planche">';
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="retour">'."\n";
$html .= '<p id="retour">'."\n";
if (($ariane[$niveau - 2]) && $ariane[$niveau - 2] != '') {
$html .= '<a href="'.$ariane[$niveau - 2].'.html">';
$html .= $lignesTexteIdentifiant[$ariane[$niveau - 2]]['titre'];
$html .= '</a>'."\n";
}
$html .= '</p>'."\n";
$html .= '</div>'."\n";
$html .= '<div class="glossaire">'."\n";
$html .= '<p id="glossaire">'."\n";
$html .= '<a href="../000-general/glossaire0_640.html">'."\n";
$html .= 'Glossaire'."\n";
$html .= '</a>'."\n";
$html .= '</p></div><div class="text">'."\n";
$html .= '<p id="Text">'."\n";
$html .= '<a href="../000-general/accueil1_640.html">'."\n";
$html .= ' Top'."\n";
$html .= '</a>'."\n";
$html .= ' </p>'."\n";
$html .= '</div>'."\n";
 
$html .= '</body>'."\n";
$html .= '</html>'."\n";
fwrite($f_html, $html);
fclose($f_html);
}
 
 
private function creerTableBonnier($version, $table) {
//+------------------------------------------------------------------------------------------------------------+
// texte
$this->type_donnee = $table.'_texte';
$requete = 'DROP TABLE IF EXISTS '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee;
$this->traiterRequete($requete);
$requete = 'CREATE TABLE '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.' ('.
'uid int(11) not null auto_increment,'.
'identifiant varchar(25),'.
'titre varchar(100),'.
'texte_1 varchar(255),'.
'texte_2 varchar(255),'.
'texte_3 varchar(255),'.
'texte_4 varchar(255),'.
'texte_5 varchar(255),'.
'texte_6 varchar(255),'.
'destination_1 varchar(25),'.
'destination_2 varchar(25),'.
'destination_3 varchar(25),'.
'destination_4 varchar(25),'.
'destination_5 varchar(25),'.
'destination_6 varchar(25),'.
'planche_croquis varchar(25),'.
'PRIMARY KEY (uid)'.
') DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ' ;
$this->traiterRequete($requete);
//+------------------------------------------------------------------------------------------------------------+
//plante
$this->type_donnee = $table.'_plante';
$requete = 'DROP TABLE IF EXISTS '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee;
$this->traiterRequete($requete);
$requete = 'CREATE TABLE '.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.' ('.
'uid int(11) not null auto_increment,'.
'identifiant varchar(25),'.
'genre varchar(100),'.
'nom_francais varchar(100),'.
'nom_vulgaire varchar(100),'.
'description varchar(512),'.
'habitat varchar(255),'.
'geographie varchar(255),'.
'planche_croquis varchar(25),'.
'PRIMARY KEY (uid)'.
') DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ' ;
$this->traiterRequete($requete);
}
 
protected function chargerDonnees($table) {
print "Chargements des données ...";
print "\n";
$this->type_donnee = $table.'_texte';
$this->chargerDonneesSql($table);
$this->type_donnee = $table.'_plante';
$this->chargerDonneesSql($table);
return;
}
protected function chargerDonneesSql($table) {
echo $this->type_donnee."\n";
$fichier_sql = $this->chemin_fichier_tab.$this->projet_nom.'_v'.$this->version.'_'.$this->sous_version.'_'.$this->type_donnee.'.sql';
print $fichier_sql."\n";
if (file_exists($fichier_sql)) {
// Des champs textes sont multilignes, d'ou la boucle sur INSERT, marqueur de fin de la requete precedente.
if ($lines = file($fichier_sql)) {
$i = 0;
$ligne_courante = $lines[$i];
if (($i + 1) >= count($lines)) {
$ligne_suivante = 'FIN';
} else {
$ligne_suivante = $lines[$i+1];
}
while ($i < count($lines)) {
$line_in = $ligne_courante;
while (($i < count($lines)) && (substr($ligne_suivante, 0, 6) != 'INSERT') && ($ligne_suivante != 'FIN')) {
$line_in .= $ligne_suivante;
$i++;
$ligne_courante = $lines[$i];
if (($i + 1) >= count($lines)) {
$ligne_suivante = 'FIN';
} else {
$ligne_suivante = $lines[$i + 1];
}
}
$requete = $line_in;
if (substr($requete, 0, 6) == 'INSERT') {
$requete = preg_replace('/ VALUES\(/',' VALUES(0,', $requete);
$this->traiterRequete(utf8_encode($requete));
}
$i++;
if (($i + 1) >= count($lines)) {
$ligne_suivante = 'FIN';
} else {
$ligne_courante = $lines[$i];
$ligne_suivante = $lines[$i + 1];
}
if ($i == (int) $this->getParam('t')) {
break;
}
}
}
} else {
echo 'Fichier sql introuvable'."\n";
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/bonnier/shell/generer_sql.sh
New file
0,0 → 1,298
perl xls2sql.pl file="001-Renonculacées-Plante.xls" skip=0 table="bonnier_v0_00_renonculacees_plante" > bonnier_v0_00_renonculacees_plante.sql
perl xls2sql.pl file="001-Renonculacées-Texte.xls" skip=0 table="bonnier_v0_00_renonculacees_texte" > bonnier_v0_00_renonculacees_texte.sql
perl xls2sql.pl file="002-Berbéridées-Plante.xls" skip=0 table="bonnier_v0_00_berberidees_plante" > bonnier_v0_00_berberidees_plante.sql
perl xls2sql.pl file="002-Berbéridées-Texte.xls" skip=0 table="bonnier_v0_00_berberidees_texte" > bonnier_v0_00_berberidees_texte.sql
perl xls2sql.pl file="003-Nymphéacées-Plante.xls" skip=0 table="bonnier_v0_00_nympheacees_plante" > bonnier_v0_00_nympheacees_plante.sql
perl xls2sql.pl file="003-Nymphéacées-Texte.xls" skip=0 table="bonnier_v0_00_nympheacees_texte" > bonnier_v0_00_nympheacees_texte.sql
perl xls2sql.pl file="004-Papavéracées-Plante.xls" skip=0 table="bonnier_v0_00_papaveracees_plante" > bonnier_v0_00_papaveracees_plante.sql
perl xls2sql.pl file="004-Papavéracées-Texte.xls" skip=0 table="bonnier_v0_00_papaveracees_texte" > bonnier_v0_00_papaveracees_texte.sql
perl xls2sql.pl file="005-Fumariacées-Plante.xls" skip=0 table="bonnier_v0_00_fumariacees_plante" > bonnier_v0_00_fumariacees_plante.sql
perl xls2sql.pl file="005-Fumariacées-Texte.xls" skip=0 table="bonnier_v0_00_fumariacees_texte" > bonnier_v0_00_fumariacees_texte.sql
perl xls2sql.pl file="006-Crucifères-Plante.xls" skip=0 table="bonnier_v0_00_cruciferes_plante" > bonnier_v0_00_cruciferes_plante.sql
perl xls2sql.pl file="006-Crucifères-Texte.xls" skip=0 table="bonnier_v0_00_cruciferes_texte" > bonnier_v0_00_cruciferes_texte.sql
perl xls2sql.pl file="007-Capparidées-Plante.xls" skip=0 table="bonnier_v0_00_capparidees_plante" > bonnier_v0_00_capparidees_plante.sql
perl xls2sql.pl file="007-Capparidées-Texte.xls" skip=0 table="bonnier_v0_00_capparidees_texte" > bonnier_v0_00_capparidees_texte.sql
perl xls2sql.pl file="008-Cistinées-Plante.xls" skip=0 table="bonnier_v0_00_cistinees_plante" > bonnier_v0_00_cistinees_plante.sql
perl xls2sql.pl file="008-Cistinées-Texte.xls" skip=0 table="bonnier_v0_00_cistinees_texte" > bonnier_v0_00_cistinees_texte.sql
perl xls2sql.pl file="009-Violariées-Plante.xls" skip=0 table="bonnier_v0_00_violariees_plante" > bonnier_v0_00_violariees_plante.sql
perl xls2sql.pl file="009-Violariées-Texte.xls" skip=0 table="bonnier_v0_00_violariees_texte" > bonnier_v0_00_violariees_texte.sql
perl xls2sql.pl file="010-Résédacées-Plante.xls" skip=0 table="bonnier_v0_00_résedacees_plante" > bonnier_v0_00_résedacees_plante.sql
perl xls2sql.pl file="010-Résédacées-Texte.xls" skip=0 table="bonnier_v0_00_résedacees_texte" > bonnier_v0_00_résedacees_texte.sql
perl xls2sql.pl file="011-Droséracées-Plante.xls" skip=0 table="bonnier_v0_00_droseracees_plante" > bonnier_v0_00_droseracees_plante.sql
perl xls2sql.pl file="011-Droséracées-Texte.xls" skip=0 table="bonnier_v0_00_droseracees_texte" > bonnier_v0_00_droseracees_texte.sql
perl xls2sql.pl file="012-Polygalées-Plante.xls" skip=0 table="bonnier_v0_00_polygalees_plante" > bonnier_v0_00_polygalees_plante.sql
perl xls2sql.pl file="012-Polygalées-Texte.xls" skip=0 table="bonnier_v0_00_polygalees_texte" > bonnier_v0_00_polygalees_texte.sql
perl xls2sql.pl file="013-Frankéniacées-Plante.xls" skip=0 table="bonnier_v0_00_frankeniacees_plante" > bonnier_v0_00_frankeniacees_plante.sql
perl xls2sql.pl file="013-Frankéniacées-Texte.xls" skip=0 table="bonnier_v0_00_frankeniacees_texte" > bonnier_v0_00_frankeniacees_texte.sql
perl xls2sql.pl file="014-Caryophyllées-Plante.xls" skip=0 table="bonnier_v0_00_caryophyllees_plante" > bonnier_v0_00_caryophyllees_plante.sql
perl xls2sql.pl file="014-Caryophyllées-Texte.xls" skip=0 table="bonnier_v0_00_caryophyllees_texte" > bonnier_v0_00_caryophyllees_texte.sql
perl xls2sql.pl file="015-Elatinées-Plante.xls" skip=0 table="bonnier_v0_00_elatinees_plante" > bonnier_v0_00_elatinees_plante.sql
perl xls2sql.pl file="015-Elatinées-Texte.xls" skip=0 table="bonnier_v0_00_elatinees_texte" > bonnier_v0_00_elatinees_texte.sql
perl xls2sql.pl file="016-Linées-Plante.xls" skip=0 table="bonnier_v0_00_linees_plante" > bonnier_v0_00_linees_plante.sql
perl xls2sql.pl file="016-Linées-Texte.xls" skip=0 table="bonnier_v0_00_linees_texte" > bonnier_v0_00_linees_texte.sql
perl xls2sql.pl file="017-Tiliacées-Plante.xls" skip=0 table="bonnier_v0_00_tiliacees_plante" > bonnier_v0_00_tiliacees_plante.sql
perl xls2sql.pl file="017-Tiliacées-Texte.xls" skip=0 table="bonnier_v0_00_tiliacees_texte" > bonnier_v0_00_tiliacees_texte.sql
perl xls2sql.pl file="018-Malvacées-Plante.xls" skip=0 table="bonnier_v0_00_malvacees_plante" > bonnier_v0_00_malvacees_plante.sql
perl xls2sql.pl file="018-Malvacées-Texte.xls" skip=0 table="bonnier_v0_00_malvacees_texte" > bonnier_v0_00_malvacees_texte.sql
perl xls2sql.pl file="019-Géraniées-Plante.xls" skip=0 table="bonnier_v0_00_geraniees_plante" > bonnier_v0_00_geraniees_plante.sql
perl xls2sql.pl file="019-Géraniées-Texte.xls" skip=0 table="bonnier_v0_00_geraniees_texte" > bonnier_v0_00_geraniees_texte.sql
perl xls2sql.pl file="020-Hypéricinées-Plante.xls" skip=0 table="bonnier_v0_00_hypericinees_plante" > bonnier_v0_00_hypericinees_plante.sql
perl xls2sql.pl file="020-Hypéricinées-Texte.xls" skip=0 table="bonnier_v0_00_hypericinees_texte" > bonnier_v0_00_hypericinees_texte.sql
perl xls2sql.pl file="021-Acérinées-Plante.xls" skip=0 table="bonnier_v0_00_acerinees_plante" > bonnier_v0_00_acerinees_plante.sql
perl xls2sql.pl file="021-Acérinées-Texte.xls" skip=0 table="bonnier_v0_00_acerinees_texte" > bonnier_v0_00_acerinees_texte.sql
perl xls2sql.pl file="022-Ampélidées-Plante.xls" skip=0 table="bonnier_v0_00_ampelidees_plante" > bonnier_v0_00_ampelidees_plante.sql
perl xls2sql.pl file="022-Ampélidées-Texte.xls" skip=0 table="bonnier_v0_00_ampelidees_texte" > bonnier_v0_00_ampelidees_texte.sql
perl xls2sql.pl file="023-Hippocastanées-Plante.xls" skip=0 table="bonnier_v0_00_hippocastanees_plante" > bonnier_v0_00_hippocastanees_plante.sql
perl xls2sql.pl file="023-Hippocastanées-Texte.xls" skip=0 table="bonnier_v0_00_hippocastanees_texte" > bonnier_v0_00_hippocastanees_texte.sql
perl xls2sql.pl file="024-Méliacées-Plante.xls" skip=0 table="bonnier_v0_00_meliacees_plante" > bonnier_v0_00_meliacees_plante.sql
perl xls2sql.pl file="024-Méliacées-Texte.xls" skip=0 table="bonnier_v0_00_meliacees_texte" > bonnier_v0_00_meliacees_texte.sql
perl xls2sql.pl file="025-Balsaminées-Plante.xls" skip=0 table="bonnier_v0_00_balsaminees_plante" > bonnier_v0_00_balsaminees_plante.sql
perl xls2sql.pl file="025-Balsaminées-Texte.xls" skip=0 table="bonnier_v0_00_balsaminees_texte" > bonnier_v0_00_balsaminees_texte.sql
perl xls2sql.pl file="026-Oxalidées-Plante.xls" skip=0 table="bonnier_v0_00_oxalidees_plante" > bonnier_v0_00_oxalidees_plante.sql
perl xls2sql.pl file="026-Oxalidées-Texte.xls" skip=0 table="bonnier_v0_00_oxalidees_texte" > bonnier_v0_00_oxalidees_texte.sql
perl xls2sql.pl file="027-Zygophyllées-Plante.xls" skip=0 table="bonnier_v0_00_zygophyllees_plante" > bonnier_v0_00_zygophyllees_plante.sql
perl xls2sql.pl file="027-Zygophyllées-Texte.xls" skip=0 table="bonnier_v0_00_zygophyllees_texte" > bonnier_v0_00_zygophyllees_texte.sql
perl xls2sql.pl file="028-Hespéridées-Plante.xls" skip=0 table="bonnier_v0_00_hesperidees_plante" > bonnier_v0_00_hesperidees_plante.sql
perl xls2sql.pl file="028-Hespéridées-Texte.xls" skip=0 table="bonnier_v0_00_hesperidees_texte" > bonnier_v0_00_hesperidees_texte.sql
perl xls2sql.pl file="029-Rutacées-Plante.xls" skip=0 table="bonnier_v0_00_rutacees_plante" > bonnier_v0_00_rutacees_plante.sql
perl xls2sql.pl file="029-Rutacées-Texte.xls" skip=0 table="bonnier_v0_00_rutacees_texte" > bonnier_v0_00_rutacees_texte.sql
perl xls2sql.pl file="030-Coriariées-Plante.xls" skip=0 table="bonnier_v0_00_coriariees_plante" > bonnier_v0_00_coriariees_plante.sql
perl xls2sql.pl file="030-Coriariées-Texte.xls" skip=0 table="bonnier_v0_00_coriariees_texte" > bonnier_v0_00_coriariees_texte.sql
perl xls2sql.pl file="031-Celastrinées-Plante.xls" skip=0 table="bonnier_v0_00_celastrinees_plante" > bonnier_v0_00_celastrinees_plante.sql
perl xls2sql.pl file="031-Celastrinées-Texte.xls" skip=0 table="bonnier_v0_00_celastrinees_texte" > bonnier_v0_00_celastrinees_texte.sql
perl xls2sql.pl file="032-Staphyléacées-Plante.xls" skip=0 table="bonnier_v0_00_staphyleacees_plante" > bonnier_v0_00_staphyleacees_plante.sql
perl xls2sql.pl file="032-Staphyléacées-Texte.xls" skip=0 table="bonnier_v0_00_staphyleacees_texte" > bonnier_v0_00_staphyleacees_texte.sql
perl xls2sql.pl file="033-Ilicinées-Plante.xls" skip=0 table="bonnier_v0_00_ilicinees_plante" > bonnier_v0_00_ilicinees_plante.sql
perl xls2sql.pl file="033-Ilicinées-Texte.xls" skip=0 table="bonnier_v0_00_ilicinees_texte" > bonnier_v0_00_ilicinees_texte.sql
perl xls2sql.pl file="034-Rhamnées-Plante.xls" skip=0 table="bonnier_v0_00_rhamnees_plante" > bonnier_v0_00_rhamnees_plante.sql
perl xls2sql.pl file="034-Rhamnées-Texte.xls" skip=0 table="bonnier_v0_00_rhamnees_texte" > bonnier_v0_00_rhamnees_texte.sql
perl xls2sql.pl file="035-Térébinthacées-Plante.xls" skip=0 table="bonnier_v0_00_térebinthacees_plante" > bonnier_v0_00_térebinthacees_plante.sql
perl xls2sql.pl file="035-Térébinthacées-Texte.xls" skip=0 table="bonnier_v0_00_térebinthacees_texte" > bonnier_v0_00_térebinthacees_texte.sql
perl xls2sql.pl file="036-Papilionacées-Plante.xls" skip=0 table="bonnier_v0_00_papilionacees_plante" > bonnier_v0_00_papilionacees_plante.sql
perl xls2sql.pl file="036-Papilionacées-Texte.xls" skip=0 table="bonnier_v0_00_papilionacees_texte" > bonnier_v0_00_papilionacees_texte.sql
perl xls2sql.pl file="037-Césalpiniées-Plante.xls" skip=0 table="bonnier_v0_00_cesalpiniees_plante" > bonnier_v0_00_cesalpiniees_plante.sql
perl xls2sql.pl file="037-Césalpiniées-Texte.xls" skip=0 table="bonnier_v0_00_cesalpiniees_texte" > bonnier_v0_00_cesalpiniees_texte.sql
perl xls2sql.pl file="038-Rosacées-Plante.xls" skip=0 table="bonnier_v0_00_rosacees_plante" > bonnier_v0_00_rosacees_plante.sql
perl xls2sql.pl file="038-Rosacées-Texte.xls" skip=0 table="bonnier_v0_00_rosacees_texte" > bonnier_v0_00_rosacees_texte.sql
perl xls2sql.pl file="039-Granatées-Plante.xls" skip=0 table="bonnier_v0_00_granatees_plante" > bonnier_v0_00_granatees_plante.sql
perl xls2sql.pl file="039-Granatées-Texte.xls" skip=0 table="bonnier_v0_00_granatees_texte" > bonnier_v0_00_granatees_texte.sql
perl xls2sql.pl file="040-Onagrariées-Plante.xls" skip=0 table="bonnier_v0_00_onagrariees_plante" > bonnier_v0_00_onagrariees_plante.sql
perl xls2sql.pl file="040-Onagrariées-Texte.xls" skip=0 table="bonnier_v0_00_onagrariees_texte" > bonnier_v0_00_onagrariees_texte.sql
perl xls2sql.pl file="041-Myriophyllées-Plante.xls" skip=0 table="bonnier_v0_00_myriophyllees_plante" > bonnier_v0_00_myriophyllees_plante.sql
perl xls2sql.pl file="041-Myriophyllées-Texte.xls" skip=0 table="bonnier_v0_00_myriophyllees_texte" > bonnier_v0_00_myriophyllees_texte.sql
perl xls2sql.pl file="042-Hippuridées-Plante.xls" skip=0 table="bonnier_v0_00_hippuridees_plante" > bonnier_v0_00_hippuridees_plante.sql
perl xls2sql.pl file="042-Hippuridées-Texte.xls" skip=0 table="bonnier_v0_00_hippuridees_texte" > bonnier_v0_00_hippuridees_texte.sql
perl xls2sql.pl file="043-Callitrichinées-Plante.xls" skip=0 table="bonnier_v0_00_callitrichinees_plante" > bonnier_v0_00_callitrichinees_plante.sql
perl xls2sql.pl file="043-Callitrichinées-Texte.xls" skip=0 table="bonnier_v0_00_callitrichinees_texte" > bonnier_v0_00_callitrichinees_texte.sql
perl xls2sql.pl file="044-Ceratophyllées-Plante.xls" skip=0 table="bonnier_v0_00_ceratophyllees_plante" > bonnier_v0_00_ceratophyllees_plante.sql
perl xls2sql.pl file="044-Ceratophyllées-Texte.xls" skip=0 table="bonnier_v0_00_ceratophyllees_texte" > bonnier_v0_00_ceratophyllees_texte.sql
perl xls2sql.pl file="045-Lythrariées-Plante.xls" skip=0 table="bonnier_v0_00_lythrariees_plante" > bonnier_v0_00_lythrariees_plante.sql
perl xls2sql.pl file="045-Lythrariées-Texte.xls" skip=0 table="bonnier_v0_00_lythrariees_texte" > bonnier_v0_00_lythrariees_texte.sql
perl xls2sql.pl file="046-Philadelphées-Plante.xls" skip=0 table="bonnier_v0_00_philadelphees_plante" > bonnier_v0_00_philadelphees_plante.sql
perl xls2sql.pl file="046-Philadelphées-Texte.xls" skip=0 table="bonnier_v0_00_philadelphees_texte" > bonnier_v0_00_philadelphees_texte.sql
perl xls2sql.pl file="047-Tamariscinées-Plante.xls" skip=0 table="bonnier_v0_00_tamariscinees_plante" > bonnier_v0_00_tamariscinees_plante.sql
perl xls2sql.pl file="047-Tamariscinées-Texte.xls" skip=0 table="bonnier_v0_00_tamariscinees_texte" > bonnier_v0_00_tamariscinees_texte.sql
perl xls2sql.pl file="048-Myrtacées-Plante.xls" skip=0 table="bonnier_v0_00_myrtacees_plante" > bonnier_v0_00_myrtacees_plante.sql
perl xls2sql.pl file="048-Myrtacées-Texte.xls" skip=0 table="bonnier_v0_00_myrtacees_texte" > bonnier_v0_00_myrtacees_texte.sql
perl xls2sql.pl file="049-Cucurbitacées-Plante.xls" skip=0 table="bonnier_v0_00_cucurbitacees_plante" > bonnier_v0_00_cucurbitacees_plante.sql
perl xls2sql.pl file="049-Cucurbitacées-Texte.xls" skip=0 table="bonnier_v0_00_cucurbitacees_texte" > bonnier_v0_00_cucurbitacees_texte.sql
perl xls2sql.pl file="050-Portulacées-Plante.xls" skip=0 table="bonnier_v0_00_portulacees_plante" > bonnier_v0_00_portulacees_plante.sql
perl xls2sql.pl file="050-Portulacées-Texte.xls" skip=0 table="bonnier_v0_00_portulacees_texte" > bonnier_v0_00_portulacees_texte.sql
perl xls2sql.pl file="051-Paronychiées-Plante.xls" skip=0 table="bonnier_v0_00_paronychiees_plante" > bonnier_v0_00_paronychiees_plante.sql
perl xls2sql.pl file="051-Paronychiées-Texte.xls" skip=0 table="bonnier_v0_00_paronychiees_texte" > bonnier_v0_00_paronychiees_texte.sql
perl xls2sql.pl file="052-Crassulacées-Plante.xls" skip=0 table="bonnier_v0_00_crassulacees_plante" > bonnier_v0_00_crassulacees_plante.sql
perl xls2sql.pl file="052-Crassulacées-Texte.xls" skip=0 table="bonnier_v0_00_crassulacees_texte" > bonnier_v0_00_crassulacees_texte.sql
perl xls2sql.pl file="053-Cactées-Plante.xls" skip=0 table="bonnier_v0_00_cactees_plante" > bonnier_v0_00_cactees_plante.sql
perl xls2sql.pl file="053-Cactées-Texte.xls" skip=0 table="bonnier_v0_00_cactees_texte" > bonnier_v0_00_cactees_texte.sql
perl xls2sql.pl file="054-Ficoïdées-Plante.xls" skip=0 table="bonnier_v0_00_ficoïdees_plante" > bonnier_v0_00_ficoïdees_plante.sql
perl xls2sql.pl file="054-Ficoïdées-Texte.xls" skip=0 table="bonnier_v0_00_ficoïdees_texte" > bonnier_v0_00_ficoïdees_texte.sql
perl xls2sql.pl file="055-Grossulariées-Plante.xls" skip=0 table="bonnier_v0_00_grossulariees_plante" > bonnier_v0_00_grossulariees_plante.sql
perl xls2sql.pl file="055-Grossulariées-Texte.xls" skip=0 table="bonnier_v0_00_grossulariees_texte" > bonnier_v0_00_grossulariees_texte.sql
perl xls2sql.pl file="056-Saxifragées-Plante.xls" skip=0 table="bonnier_v0_00_saxifragees_plante" > bonnier_v0_00_saxifragees_plante.sql
perl xls2sql.pl file="056-Saxifragées-Texte.xls" skip=0 table="bonnier_v0_00_saxifragees_texte" > bonnier_v0_00_saxifragees_texte.sql
perl xls2sql.pl file="057-Ombelliféres-Plante.xls" skip=0 table="bonnier_v0_00_ombelliferes_plante" > bonnier_v0_00_ombelliferes_plante.sql
perl xls2sql.pl file="057-Ombelliféres-Texte.xls" skip=0 table="bonnier_v0_00_ombelliferes_texte" > bonnier_v0_00_ombelliferes_texte.sql
perl xls2sql.pl file="058-Araliacées-Plante.xls" skip=0 table="bonnier_v0_00_araliacees_plante" > bonnier_v0_00_araliacees_plante.sql
perl xls2sql.pl file="058-Araliacées-Texte.xls" skip=0 table="bonnier_v0_00_araliacees_texte" > bonnier_v0_00_araliacees_texte.sql
perl xls2sql.pl file="059-Cornées-Plante.xls" skip=0 table="bonnier_v0_00_cornees_plante" > bonnier_v0_00_cornees_plante.sql
perl xls2sql.pl file="059-Cornées-Texte.xls" skip=0 table="bonnier_v0_00_cornees_texte" > bonnier_v0_00_cornees_texte.sql
perl xls2sql.pl file="060-Loranthacées-Plante.xls" skip=0 table="bonnier_v0_00_loranthacees_plante" > bonnier_v0_00_loranthacees_plante.sql
perl xls2sql.pl file="060-Loranthacées-Texte.xls" skip=0 table="bonnier_v0_00_loranthacees_texte" > bonnier_v0_00_loranthacees_texte.sql
perl xls2sql.pl file="061-Caprifoliacées-Plante.xls" skip=0 table="bonnier_v0_00_caprifoliacees_plante" > bonnier_v0_00_caprifoliacees_plante.sql
perl xls2sql.pl file="061-Caprifoliacées-Texte.xls" skip=0 table="bonnier_v0_00_caprifoliacees_texte" > bonnier_v0_00_caprifoliacees_texte.sql
perl xls2sql.pl file="062-Rubiacées-Plante.xls" skip=0 table="bonnier_v0_00_rubiacees_plante" > bonnier_v0_00_rubiacees_plante.sql
perl xls2sql.pl file="062-Rubiacées-Texte.xls" skip=0 table="bonnier_v0_00_rubiacees_texte" > bonnier_v0_00_rubiacees_texte.sql
perl xls2sql.pl file="063-Valérianées-Plante.xls" skip=0 table="bonnier_v0_00_valerianees_plante" > bonnier_v0_00_valerianees_plante.sql
perl xls2sql.pl file="063-Valérianées-Texte.xls" skip=0 table="bonnier_v0_00_valerianees_texte" > bonnier_v0_00_valerianees_texte.sql
perl xls2sql.pl file="064-Dipsacées-Plante.xls" skip=0 table="bonnier_v0_00_dipsacees_plante" > bonnier_v0_00_dipsacees_plante.sql
perl xls2sql.pl file="064-Dipsacées-Texte.xls" skip=0 table="bonnier_v0_00_dipsacees_texte" > bonnier_v0_00_dipsacees_texte.sql
perl xls2sql.pl file="065-Composées-Plante.xls" skip=0 table="bonnier_v0_00_composees_plante" > bonnier_v0_00_composees_plante.sql
perl xls2sql.pl file="065-Composées-Texte.xls" skip=0 table="bonnier_v0_00_composees_texte" > bonnier_v0_00_composees_texte.sql
perl xls2sql.pl file="066-Ambrosiacées-Plante.xls" skip=0 table="bonnier_v0_00_ambrosiacees_plante" > bonnier_v0_00_ambrosiacees_plante.sql
perl xls2sql.pl file="066-Ambrosiacées-Texte.xls" skip=0 table="bonnier_v0_00_ambrosiacees_texte" > bonnier_v0_00_ambrosiacees_texte.sql
perl xls2sql.pl file="067-Lobéliacées-Plante.xls" skip=0 table="bonnier_v0_00_lobeliacees_plante" > bonnier_v0_00_lobeliacees_plante.sql
perl xls2sql.pl file="067-Lobéliacées-Texte.xls" skip=0 table="bonnier_v0_00_lobeliacees_texte" > bonnier_v0_00_lobeliacees_texte.sql
perl xls2sql.pl file="068-Campanulacées-Plante.xls" skip=0 table="bonnier_v0_00_campanulacees_plante" > bonnier_v0_00_campanulacees_plante.sql
perl xls2sql.pl file="068-Campanulacées-Texte.xls" skip=0 table="bonnier_v0_00_campanulacees_texte" > bonnier_v0_00_campanulacees_texte.sql
perl xls2sql.pl file="069-Vacciniées-Plante.xls" skip=0 table="bonnier_v0_00_vacciniees_plante" > bonnier_v0_00_vacciniees_plante.sql
perl xls2sql.pl file="069-Vacciniées-Texte.xls" skip=0 table="bonnier_v0_00_vacciniees_texte" > bonnier_v0_00_vacciniees_texte.sql
perl xls2sql.pl file="070-Ericinées-Plante.xls" skip=0 table="bonnier_v0_00_ericinees_plante" > bonnier_v0_00_ericinees_plante.sql
perl xls2sql.pl file="070-Ericinées-Texte.xls" skip=0 table="bonnier_v0_00_ericinees_texte" > bonnier_v0_00_ericinees_texte.sql
perl xls2sql.pl file="071-Pyrolacées-Plante.xls" skip=0 table="bonnier_v0_00_pyrolacees_plante" > bonnier_v0_00_pyrolacees_plante.sql
perl xls2sql.pl file="071-Pyrolacées-Texte.xls" skip=0 table="bonnier_v0_00_pyrolacees_texte" > bonnier_v0_00_pyrolacees_texte.sql
perl xls2sql.pl file="072-Monotropées-Plante.xls" skip=0 table="bonnier_v0_00_monotropees_plante" > bonnier_v0_00_monotropees_plante.sql
perl xls2sql.pl file="072-Monotropées-Texte.xls" skip=0 table="bonnier_v0_00_monotropees_texte" > bonnier_v0_00_monotropees_texte.sql
perl xls2sql.pl file="073-Lentibulariées-Plante.xls" skip=0 table="bonnier_v0_00_lentibulariees_plante" > bonnier_v0_00_lentibulariees_plante.sql
perl xls2sql.pl file="073-Lentibulariées-Texte.xls" skip=0 table="bonnier_v0_00_lentibulariees_texte" > bonnier_v0_00_lentibulariees_texte.sql
perl xls2sql.pl file="074-Primulacées-Plante.xls" skip=0 table="bonnier_v0_00_primulacees_plante" > bonnier_v0_00_primulacees_plante.sql
perl xls2sql.pl file="074-Primulacées-Texte.xls" skip=0 table="bonnier_v0_00_primulacees_texte" > bonnier_v0_00_primulacees_texte.sql
perl xls2sql.pl file="075-Ebénacées-Plante.xls" skip=0 table="bonnier_v0_00_ebenacees_plante" > bonnier_v0_00_ebenacees_plante.sql
perl xls2sql.pl file="075-Ebénacées-Texte.xls" skip=0 table="bonnier_v0_00_ebenacees_texte" > bonnier_v0_00_ebenacees_texte.sql
perl xls2sql.pl file="076-Styracées-Plante.xls" skip=0 table="bonnier_v0_00_styracees_plante" > bonnier_v0_00_styracees_plante.sql
perl xls2sql.pl file="076-Styracées-Texte.xls" skip=0 table="bonnier_v0_00_styracees_texte" > bonnier_v0_00_styracees_texte.sql
perl xls2sql.pl file="077-Oléinées-Plante.xls" skip=0 table="bonnier_v0_00_oleinees_plante" > bonnier_v0_00_oleinees_plante.sql
perl xls2sql.pl file="077-Oléinées-Texte.xls" skip=0 table="bonnier_v0_00_oleinees_texte" > bonnier_v0_00_oleinees_texte.sql
perl xls2sql.pl file="078-Jasminées-Plante.xls" skip=0 table="bonnier_v0_00_jasminees_plante" > bonnier_v0_00_jasminees_plante.sql
perl xls2sql.pl file="078-Jasminées-Texte.xls" skip=0 table="bonnier_v0_00_jasminees_texte" > bonnier_v0_00_jasminees_texte.sql
perl xls2sql.pl file="079-Apocynées-Plante.xls" skip=0 table="bonnier_v0_00_apocynees_plante" > bonnier_v0_00_apocynees_plante.sql
perl xls2sql.pl file="079-Apocynées-Texte.xls" skip=0 table="bonnier_v0_00_apocynees_texte" > bonnier_v0_00_apocynees_texte.sql
perl xls2sql.pl file="080-Asclépiadées-Plante.xls" skip=0 table="bonnier_v0_00_asclepiadees_plante" > bonnier_v0_00_asclepiadees_plante.sql
perl xls2sql.pl file="080-Asclépiadées-Texte.xls" skip=0 table="bonnier_v0_00_asclepiadees_texte" > bonnier_v0_00_asclepiadees_texte.sql
perl xls2sql.pl file="081-Gentianées-Plante.xls" skip=0 table="bonnier_v0_00_gentianees_plante" > bonnier_v0_00_gentianees_plante.sql
perl xls2sql.pl file="081-Gentianées-Texte.xls" skip=0 table="bonnier_v0_00_gentianees_texte" > bonnier_v0_00_gentianees_texte.sql
perl xls2sql.pl file="082-Polémoniacées-Plante.xls" skip=0 table="bonnier_v0_00_polemoniacees_plante" > bonnier_v0_00_polemoniacees_plante.sql
perl xls2sql.pl file="082-Polémoniacées-Texte.xls" skip=0 table="bonnier_v0_00_polemoniacees_texte" > bonnier_v0_00_polemoniacees_texte.sql
perl xls2sql.pl file="083-Convolvulacées-Plante.xls" skip=0 table="bonnier_v0_00_convolvulacees_plante" > bonnier_v0_00_convolvulacees_plante.sql
perl xls2sql.pl file="083-Convolvulacées-Texte.xls" skip=0 table="bonnier_v0_00_convolvulacees_texte" > bonnier_v0_00_convolvulacees_texte.sql
perl xls2sql.pl file="084-Cuscutacées-Plante.xls" skip=0 table="bonnier_v0_00_cuscutacees_plante" > bonnier_v0_00_cuscutacees_plante.sql
perl xls2sql.pl file="084-Cuscutacées-Texte.xls" skip=0 table="bonnier_v0_00_cuscutacees_texte" > bonnier_v0_00_cuscutacees_texte.sql
perl xls2sql.pl file="085-Ramondiacées-Plante.xls" skip=0 table="bonnier_v0_00_ramondiacees_plante" > bonnier_v0_00_ramondiacees_plante.sql
perl xls2sql.pl file="085-Ramondiacées-Texte.xls" skip=0 table="bonnier_v0_00_ramondiacees_texte" > bonnier_v0_00_ramondiacees_texte.sql
perl xls2sql.pl file="086-Borraginées-Plante.xls" skip=0 table="bonnier_v0_00_borraginees_plante" > bonnier_v0_00_borraginees_plante.sql
perl xls2sql.pl file="086-Borraginées-Texte.xls" skip=0 table="bonnier_v0_00_borraginees_texte" > bonnier_v0_00_borraginees_texte.sql
perl xls2sql.pl file="087-Solanées-Plante.xls" skip=0 table="bonnier_v0_00_solanees_plante" > bonnier_v0_00_solanees_plante.sql
perl xls2sql.pl file="087-Solanées-Texte.xls" skip=0 table="bonnier_v0_00_solanees_texte" > bonnier_v0_00_solanees_texte.sql
perl xls2sql.pl file="088-Verbascées-Plante.xls" skip=0 table="bonnier_v0_00_verbascees_plante" > bonnier_v0_00_verbascees_plante.sql
perl xls2sql.pl file="088-Verbascées-Texte.xls" skip=0 table="bonnier_v0_00_verbascees_texte" > bonnier_v0_00_verbascees_texte.sql
perl xls2sql.pl file="089-Scrofularinées-Plante.xls" skip=0 table="bonnier_v0_00_scrofularinees_plante" > bonnier_v0_00_scrofularinees_plante.sql
perl xls2sql.pl file="089-Scrofularinées-Texte.xls" skip=0 table="bonnier_v0_00_scrofularinees_texte" > bonnier_v0_00_scrofularinees_texte.sql
perl xls2sql.pl file="090-Orobanchées-Plante.xls" skip=0 table="bonnier_v0_00_orobanchees_plante" > bonnier_v0_00_orobanchees_plante.sql
perl xls2sql.pl file="090-Orobanchées-Texte.xls" skip=0 table="bonnier_v0_00_orobanchees_texte" > bonnier_v0_00_orobanchees_texte.sql
perl xls2sql.pl file="091-Labiées-Plante.xls" skip=0 table="bonnier_v0_00_labiees_plante" > bonnier_v0_00_labiees_plante.sql
perl xls2sql.pl file="091-Labiées-Texte.xls" skip=0 table="bonnier_v0_00_labiees_texte" > bonnier_v0_00_labiees_texte.sql
perl xls2sql.pl file="092-Acanthacées-Plante.xls" skip=0 table="bonnier_v0_00_acanthacees_plante" > bonnier_v0_00_acanthacees_plante.sql
perl xls2sql.pl file="092-Acanthacées-Texte.xls" skip=0 table="bonnier_v0_00_acanthacees_texte" > bonnier_v0_00_acanthacees_texte.sql
perl xls2sql.pl file="093-Verbénacées-Plante.xls" skip=0 table="bonnier_v0_00_verbenacees_plante" > bonnier_v0_00_verbenacees_plante.sql
perl xls2sql.pl file="093-Verbénacées-Texte.xls" skip=0 table="bonnier_v0_00_verbenacees_texte" > bonnier_v0_00_verbenacees_texte.sql
perl xls2sql.pl file="094-Plantaginées-Plante.xls" skip=0 table="bonnier_v0_00_plantaginees_plante" > bonnier_v0_00_plantaginees_plante.sql
perl xls2sql.pl file="094-Plantaginées-Texte.xls" skip=0 table="bonnier_v0_00_plantaginees_texte" > bonnier_v0_00_plantaginees_texte.sql
perl xls2sql.pl file="095-Plombaginées-Plante.xls" skip=0 table="bonnier_v0_00_plombaginees_plante" > bonnier_v0_00_plombaginees_plante.sql
perl xls2sql.pl file="095-Plombaginées-Texte.xls" skip=0 table="bonnier_v0_00_plombaginees_texte" > bonnier_v0_00_plombaginees_texte.sql
perl xls2sql.pl file="096-Globulariées-Plante.xls" skip=0 table="bonnier_v0_00_globulariees_plante" > bonnier_v0_00_globulariees_plante.sql
perl xls2sql.pl file="096-Globulariées-Texte.xls" skip=0 table="bonnier_v0_00_globulariees_texte" > bonnier_v0_00_globulariees_texte.sql
perl xls2sql.pl file="097-Phytolaccées-Plante.xls" skip=0 table="bonnier_v0_00_phytolaccees_plante" > bonnier_v0_00_phytolaccees_plante.sql
perl xls2sql.pl file="097-Phytolaccées-Texte.xls" skip=0 table="bonnier_v0_00_phytolaccees_texte" > bonnier_v0_00_phytolaccees_texte.sql
perl xls2sql.pl file="098-Amarantacées-Plante.xls" skip=0 table="bonnier_v0_00_amarantacees_plante" > bonnier_v0_00_amarantacees_plante.sql
perl xls2sql.pl file="098-Amarantacées-Texte.xls" skip=0 table="bonnier_v0_00_amarantacees_texte" > bonnier_v0_00_amarantacees_texte.sql
perl xls2sql.pl file="099-Salsolacées-Plante.xls" skip=0 table="bonnier_v0_00_salsolacees_plante" > bonnier_v0_00_salsolacees_plante.sql
perl xls2sql.pl file="099-Salsolacées-Texte.xls" skip=0 table="bonnier_v0_00_salsolacees_texte" > bonnier_v0_00_salsolacees_texte.sql
perl xls2sql.pl file="100-Polygonées-Plante.xls" skip=0 table="bonnier_v0_00_polygonees_plante" > bonnier_v0_00_polygonees_plante.sql
perl xls2sql.pl file="100-Polygonées-Texte.xls" skip=0 table="bonnier_v0_00_polygonees_texte" > bonnier_v0_00_polygonees_texte.sql
perl xls2sql.pl file="101-Daphnoidées-Plante.xls" skip=0 table="bonnier_v0_00_daphnoidees_plante" > bonnier_v0_00_daphnoidees_plante.sql
perl xls2sql.pl file="101-Daphnoidées-Texte.xls" skip=0 table="bonnier_v0_00_daphnoidees_texte" > bonnier_v0_00_daphnoidees_texte.sql
perl xls2sql.pl file="102-Laurinées-Plante.xls" skip=0 table="bonnier_v0_00_laurinees_plante" > bonnier_v0_00_laurinees_plante.sql
perl xls2sql.pl file="102-Laurinées-Texte.xls" skip=0 table="bonnier_v0_00_laurinees_texte" > bonnier_v0_00_laurinees_texte.sql
perl xls2sql.pl file="103-Santalacées-Plante.xls" skip=0 table="bonnier_v0_00_santalacees_plante" > bonnier_v0_00_santalacees_plante.sql
perl xls2sql.pl file="103-Santalacées-Texte.xls" skip=0 table="bonnier_v0_00_santalacees_texte" > bonnier_v0_00_santalacees_texte.sql
perl xls2sql.pl file="104-Eléagnées-Plante.xls" skip=0 table="bonnier_v0_00_eleagnees_plante" > bonnier_v0_00_eleagnees_plante.sql
perl xls2sql.pl file="104-Eléagnées-Texte.xls" skip=0 table="bonnier_v0_00_eleagnees_texte" > bonnier_v0_00_eleagnees_texte.sql
perl xls2sql.pl file="105-Cytinées-Plante.xls" skip=0 table="bonnier_v0_00_cytinees_plante" > bonnier_v0_00_cytinees_plante.sql
perl xls2sql.pl file="105-Cytinées-Texte.xls" skip=0 table="bonnier_v0_00_cytinees_texte" > bonnier_v0_00_cytinees_texte.sql
perl xls2sql.pl file="106-Aristolochiées-Plante.xls" skip=0 table="bonnier_v0_00_aristolochiees_plante" > bonnier_v0_00_aristolochiees_plante.sql
perl xls2sql.pl file="106-Aristolochiées-Texte.xls" skip=0 table="bonnier_v0_00_aristolochiees_texte" > bonnier_v0_00_aristolochiees_texte.sql
perl xls2sql.pl file="107-Empétrées-Plante.xls" skip=0 table="bonnier_v0_00_empetrees_plante" > bonnier_v0_00_empetrees_plante.sql
perl xls2sql.pl file="107-Empétrées-Texte.xls" skip=0 table="bonnier_v0_00_empetrees_texte" > bonnier_v0_00_empetrees_texte.sql
perl xls2sql.pl file="108-Euphorbiacées-Plante.xls" skip=0 table="bonnier_v0_00_euphorbiacees_plante" > bonnier_v0_00_euphorbiacees_plante.sql
perl xls2sql.pl file="108-Euphorbiacées-Texte.xls" skip=0 table="bonnier_v0_00_euphorbiacees_texte" > bonnier_v0_00_euphorbiacees_texte.sql
perl xls2sql.pl file="109-Morées-Plante.xls" skip=0 table="bonnier_v0_00_morees_plante" > bonnier_v0_00_morees_plante.sql
perl xls2sql.pl file="109-Morées-Texte.xls" skip=0 table="bonnier_v0_00_morees_texte" > bonnier_v0_00_morees_texte.sql
perl xls2sql.pl file="110-Ficacées-Plante.xls" skip=0 table="bonnier_v0_00_ficacees_plante" > bonnier_v0_00_ficacees_plante.sql
perl xls2sql.pl file="110-Ficacées-Texte.xls" skip=0 table="bonnier_v0_00_ficacees_texte" > bonnier_v0_00_ficacees_texte.sql
perl xls2sql.pl file="111-Celtidées-Plante.xls" skip=0 table="bonnier_v0_00_celtidees_plante" > bonnier_v0_00_celtidees_plante.sql
perl xls2sql.pl file="111-Celtidées-Texte.xls" skip=0 table="bonnier_v0_00_celtidees_texte" > bonnier_v0_00_celtidees_texte.sql
perl xls2sql.pl file="112-Ulmacées-Plante.xls" skip=0 table="bonnier_v0_00_ulmacees_plante" > bonnier_v0_00_ulmacees_plante.sql
perl xls2sql.pl file="112-Ulmacées-Texte.xls" skip=0 table="bonnier_v0_00_ulmacees_texte" > bonnier_v0_00_ulmacees_texte.sql
perl xls2sql.pl file="113-Urticées-Plante.xls" skip=0 table="bonnier_v0_00_urticees_plante" > bonnier_v0_00_urticees_plante.sql
perl xls2sql.pl file="113-Urticées-Texte.xls" skip=0 table="bonnier_v0_00_urticees_texte" > bonnier_v0_00_urticees_texte.sql
perl xls2sql.pl file="114-Cannabinées-Plante.xls" skip=0 table="bonnier_v0_00_cannabinees_plante" > bonnier_v0_00_cannabinees_plante.sql
perl xls2sql.pl file="114-Cannabinées-Texte.xls" skip=0 table="bonnier_v0_00_cannabinees_texte" > bonnier_v0_00_cannabinees_texte.sql
perl xls2sql.pl file="115-Juglandées-Plante.xls" skip=0 table="bonnier_v0_00_juglandees_plante" > bonnier_v0_00_juglandees_plante.sql
perl xls2sql.pl file="115-Juglandées-Texte.xls" skip=0 table="bonnier_v0_00_juglandees_texte" > bonnier_v0_00_juglandees_texte.sql
perl xls2sql.pl file="116-Cupulifères-Plante.xls" skip=0 table="bonnier_v0_00_cupuliferes_plante" > bonnier_v0_00_cupuliferes_plante.sql
perl xls2sql.pl file="116-Cupulifères-Texte.xls" skip=0 table="bonnier_v0_00_cupuliferes_texte" > bonnier_v0_00_cupuliferes_texte.sql
perl xls2sql.pl file="117-Salicinées-Plante.xls" skip=0 table="bonnier_v0_00_salicinees_plante" > bonnier_v0_00_salicinees_plante.sql
perl xls2sql.pl file="117-Salicinées-Texte.xls" skip=0 table="bonnier_v0_00_salicinees_texte" > bonnier_v0_00_salicinees_texte.sql
perl xls2sql.pl file="118-Platanées-Plante.xls" skip=0 table="bonnier_v0_00_platanees_plante" > bonnier_v0_00_platanees_plante.sql
perl xls2sql.pl file="118-Platanées-Texte.xls" skip=0 table="bonnier_v0_00_platanees_texte" > bonnier_v0_00_platanees_texte.sql
perl xls2sql.pl file="119-Bétulinèes-Plante.xls" skip=0 table="bonnier_v0_00_betulinees_plante" > bonnier_v0_00_betulinees_plante.sql
perl xls2sql.pl file="119-Bétulinèes-Texte.xls" skip=0 table="bonnier_v0_00_betulinees_texte" > bonnier_v0_00_betulinees_texte.sql
perl xls2sql.pl file="120-Myricèes-Plante.xls" skip=0 table="bonnier_v0_00_myricees_plante" > bonnier_v0_00_myricees_plante.sql
perl xls2sql.pl file="120-Myricèes-Texte.xls" skip=0 table="bonnier_v0_00_myricees_texte" > bonnier_v0_00_myricees_texte.sql
perl xls2sql.pl file="121-Alismacées-Plante.xls" skip=0 table="bonnier_v0_00_alismacees_plante" > bonnier_v0_00_alismacees_plante.sql
perl xls2sql.pl file="121-Alismacées-Texte.xls" skip=0 table="bonnier_v0_00_alismacees_texte" > bonnier_v0_00_alismacees_texte.sql
perl xls2sql.pl file="122-Butomées-Plante.xls" skip=0 table="bonnier_v0_00_butomees_plante" > bonnier_v0_00_butomees_plante.sql
perl xls2sql.pl file="122-Butomées-Texte.xls" skip=0 table="bonnier_v0_00_butomees_texte" > bonnier_v0_00_butomees_texte.sql
perl xls2sql.pl file="123-Colchicacées-Plante.xls" skip=0 table="bonnier_v0_00_colchicacees_plante" > bonnier_v0_00_colchicacees_plante.sql
perl xls2sql.pl file="123-Colchicacées-Texte.xls" skip=0 table="bonnier_v0_00_colchicacees_texte" > bonnier_v0_00_colchicacees_texte.sql
perl xls2sql.pl file="124-Liliacées-Plante.xls" skip=0 table="bonnier_v0_00_liliacees_plante" > bonnier_v0_00_liliacees_plante.sql
perl xls2sql.pl file="124-Liliacées-Texte.xls" skip=0 table="bonnier_v0_00_liliacees_texte" > bonnier_v0_00_liliacees_texte.sql
perl xls2sql.pl file="125-Dioscorées-Plante.xls" skip=0 table="bonnier_v0_00_dioscorees_plante" > bonnier_v0_00_dioscorees_plante.sql
perl xls2sql.pl file="125-Dioscorées-Texte.xls" skip=0 table="bonnier_v0_00_dioscorees_texte" > bonnier_v0_00_dioscorees_texte.sql
perl xls2sql.pl file="126-Iridées-Plante.xls" skip=0 table="bonnier_v0_00_iridees_plante" > bonnier_v0_00_iridees_plante.sql
perl xls2sql.pl file="126-Iridées-Texte.xls" skip=0 table="bonnier_v0_00_iridees_texte" > bonnier_v0_00_iridees_texte.sql
perl xls2sql.pl file="127-Amaryllidées-Plante.xls" skip=0 table="bonnier_v0_00_amaryllidees_plante" > bonnier_v0_00_amaryllidees_plante.sql
perl xls2sql.pl file="127-Amaryllidées-Texte.xls" skip=0 table="bonnier_v0_00_amaryllidees_texte" > bonnier_v0_00_amaryllidees_texte.sql
perl xls2sql.pl file="128-Orchidées-Plante.xls" skip=0 table="bonnier_v0_00_orchidees_plante" > bonnier_v0_00_orchidees_plante.sql
perl xls2sql.pl file="128-Orchidées-Texte.xls" skip=0 table="bonnier_v0_00_orchidees_texte" > bonnier_v0_00_orchidees_texte.sql
perl xls2sql.pl file="129-Hydrocharidées-Plante.xls" skip=0 table="bonnier_v0_00_hydrocharidees_plante" > bonnier_v0_00_hydrocharidees_plante.sql
perl xls2sql.pl file="129-Hydrocharidées-Texte.xls" skip=0 table="bonnier_v0_00_hydrocharidees_texte" > bonnier_v0_00_hydrocharidees_texte.sql
perl xls2sql.pl file="130-Joncaginées-Plante.xls" skip=0 table="bonnier_v0_00_joncaginees_plante" > bonnier_v0_00_joncaginees_plante.sql
perl xls2sql.pl file="130-Joncaginées-Texte.xls" skip=0 table="bonnier_v0_00_joncaginees_texte" > bonnier_v0_00_joncaginees_texte.sql
perl xls2sql.pl file="131-Potamées-Plante.xls" skip=0 table="bonnier_v0_00_potamees_plante" > bonnier_v0_00_potamees_plante.sql
perl xls2sql.pl file="131-Potamées-Texte.xls" skip=0 table="bonnier_v0_00_potamees_texte" > bonnier_v0_00_potamees_texte.sql
perl xls2sql.pl file="132-Naiadees-Plante.xls" skip=0 table="bonnier_v0_00_naiadees_plante" > bonnier_v0_00_naiadees_plante.sql
perl xls2sql.pl file="132-Naiadees-Texte.xls" skip=0 table="bonnier_v0_00_naiadees_texte" > bonnier_v0_00_naiadees_texte.sql
perl xls2sql.pl file="133-Zosteracées-Plante.xls" skip=0 table="bonnier_v0_00_zosteracees_plante" > bonnier_v0_00_zosteracees_plante.sql
perl xls2sql.pl file="133-Zosteracées-Texte.xls" skip=0 table="bonnier_v0_00_zosteracees_texte" > bonnier_v0_00_zosteracees_texte.sql
perl xls2sql.pl file="134-Lemnacées-Plante.xls" skip=0 table="bonnier_v0_00_lemnacees_plante" > bonnier_v0_00_lemnacees_plante.sql
perl xls2sql.pl file="134-Lemnacées-Texte.xls" skip=0 table="bonnier_v0_00_lemnacees_texte" > bonnier_v0_00_lemnacees_texte.sql
perl xls2sql.pl file="135-Aroidées-Plante.xls" skip=0 table="bonnier_v0_00_aroidees_plante" > bonnier_v0_00_aroidees_plante.sql
perl xls2sql.pl file="135-Aroidées-Texte.xls" skip=0 table="bonnier_v0_00_aroidees_texte" > bonnier_v0_00_aroidees_texte.sql
perl xls2sql.pl file="136-Typhacées-Plante.xls" skip=0 table="bonnier_v0_00_typhacees_plante" > bonnier_v0_00_typhacees_plante.sql
perl xls2sql.pl file="136-Typhacées-Texte.xls" skip=0 table="bonnier_v0_00_typhacees_texte" > bonnier_v0_00_typhacees_texte.sql
perl xls2sql.pl file="137-Joncées-Plante.xls" skip=0 table="bonnier_v0_00_joncees_plante" > bonnier_v0_00_joncees_plante.sql
perl xls2sql.pl file="137-Joncées-Texte.xls" skip=0 table="bonnier_v0_00_joncees_texte" > bonnier_v0_00_joncees_texte.sql
perl xls2sql.pl file="138-Cyperacées-Plante.xls" skip=0 table="bonnier_v0_00_cyperacees_plante" > bonnier_v0_00_cyperacees_plante.sql
perl xls2sql.pl file="138-Cyperacées-Texte.xls" skip=0 table="bonnier_v0_00_cyperacees_texte" > bonnier_v0_00_cyperacees_texte.sql
perl xls2sql.pl file="139-Graminées-Plante.xls" skip=0 table="bonnier_v0_00_graminees_plante" > bonnier_v0_00_graminees_plante.sql
perl xls2sql.pl file="139-Graminées-Texte.xls" skip=0 table="bonnier_v0_00_graminees_texte" > bonnier_v0_00_graminees_texte.sql
perl xls2sql.pl file="140-Abietinées-Plante.xls" skip=0 table="bonnier_v0_00_abietinees_plante" > bonnier_v0_00_abietinees_plante.sql
perl xls2sql.pl file="140-Abietinées-Texte.xls" skip=0 table="bonnier_v0_00_abietinees_texte" > bonnier_v0_00_abietinees_texte.sql
perl xls2sql.pl file="141-Cupressinées-Plante.xls" skip=0 table="bonnier_v0_00_cupressinees_plante" > bonnier_v0_00_cupressinees_plante.sql
perl xls2sql.pl file="141-Cupressinées-Texte.xls" skip=0 table="bonnier_v0_00_cupressinees_texte" > bonnier_v0_00_cupressinees_texte.sql
perl xls2sql.pl file="142-Taxinées-Plante.xls" skip=0 table="bonnier_v0_00_taxinees_plante" > bonnier_v0_00_taxinees_plante.sql
perl xls2sql.pl file="142-Taxinées-Texte.xls" skip=0 table="bonnier_v0_00_taxinees_texte" > bonnier_v0_00_taxinees_texte.sql
perl xls2sql.pl file="143-Gnetacées-Plante.xls" skip=0 table="bonnier_v0_00_gnetacees_plante" > bonnier_v0_00_gnetacees_plante.sql
perl xls2sql.pl file="143-Gnetacées-Texte.xls" skip=0 table="bonnier_v0_00_gnetacees_texte" > bonnier_v0_00_gnetacees_texte.sql
perl xls2sql.pl file="144-Fougères-Plante.xls" skip=0 table="bonnier_v0_00_fougeres_plante" > bonnier_v0_00_fougeres_plante.sql
perl xls2sql.pl file="144-Fougères-Texte.xls" skip=0 table="bonnier_v0_00_fougeres_texte" > bonnier_v0_00_fougeres_texte.sql
perl xls2sql.pl file="145-Ophioglossées-Plante.xls" skip=0 table="bonnier_v0_00_ophioglossees_plante" > bonnier_v0_00_ophioglossees_plante.sql
perl xls2sql.pl file="145-Ophioglossées-Texte.xls" skip=0 table="bonnier_v0_00_ophioglossees_texte" > bonnier_v0_00_ophioglossees_texte.sql
perl xls2sql.pl file="146-Marsiliacées-Plante.xls" skip=0 table="bonnier_v0_00_marsiliacees_plante" > bonnier_v0_00_marsiliacees_plante.sql
perl xls2sql.pl file="146-Marsiliacées-Texte.xls" skip=0 table="bonnier_v0_00_marsiliacees_texte" > bonnier_v0_00_marsiliacees_texte.sql
perl xls2sql.pl file="147-Equisétacées-Plante.xls" skip=0 table="bonnier_v0_00_equisetacees_plante" > bonnier_v0_00_equisetacees_plante.sql
perl xls2sql.pl file="147-Equisétacées-Texte.xls" skip=0 table="bonnier_v0_00_equisetacees_texte" > bonnier_v0_00_equisetacees_texte.sql
perl xls2sql.pl file="148-Isoétées-Plante.xls" skip=0 table="bonnier_v0_00_isoetees_plante" > bonnier_v0_00_isoetees_plante.sql
perl xls2sql.pl file="148-Isoétées-Texte.xls" skip=0 table="bonnier_v0_00_isoetees_texte" > bonnier_v0_00_isoetees_texte.sql
perl xls2sql.pl file="149-Lycopodiacées-Plante.xls" skip=0 table="bonnier_v0_00_lycopodiacees_plante" > bonnier_v0_00_lycopodiacees_plante.sql
perl xls2sql.pl file="149-Lycopodiacées-Texte.xls" skip=0 table="bonnier_v0_00_lycopodiacees_texte" > bonnier_v0_00_lycopodiacees_texte.sql
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/bonnier/shell/xls2sql.pl
New file
0,0 → 1,205
#!/usr/bin/perl
 
# $Date: 2005/10/19 10:14:00 $
 
# Excel to SQL statements translator.
# Needs the Spreadsheet::ParseExcel module from CPAN
#
# Example usage:
#
# xls2sql.pl help
# xls2sql.pl file=6960_TS_Bressanone_Brixen.xls \
# coldefs="year INTEGER,MEAN1 DOUBLE PRECISION,MEAN2 DOUBLE PRECISION,MEAN3 DOUBLE PRECISION"
#
# Released under GPLv2.0
# by Daniel Calvelo Aros (dca@users.sf.net)
#
# few modifications by MN (why not reading 'Learning Perl' O'Reilly book)
 
#use strict;
use English;
use Spreadsheet::ParseExcel;
# gparser-like options:
# option label => [ref to var to hold opt value, "description", default value or undef for no default]
%gopts = ( file => [\$file, "Name of input excel spreadsheet file", undef],
skip => [\$skip, "Number of rows to skip at the beginning of sheet", 0],
table => [\$tablename,"Name of output table", "mytable"],
rows => [\$nrows, "Number of rows to extract", undef],
sheet => [\$sheetn, "Sheet number to convert from the workbook, counting from 1", 1],
coldefs=> [\$coldefs, "Column definitions as in SQL", "auto"],
nodata => [\$nodata, "No data character(s) used in the Excel table", ""],
help => [\$help, "Help, of course", undef],
debug => [\$DEBUG, "Debugging flag, for developers only", 0]);
#function defined below:
&parse_opts();
 
#-- Open and look for obvious errors
my $wkbk =
Spreadsheet::ParseExcel::Workbook->Parse($file);
if( !defined $wkbk->{Worksheet}) {die "Error:couldn't parse file $file\n"}
my($iR, $iC, $sheet, $ncols, $roffset, $rsize);
$sheet = @{$wkbk->{Worksheet}}[--$sheetn]; #-- Numbering starts at 1 for the user
$ncols = $sheet->{MaxCol} or die "Error:the specified sheet $sheetn does not contain data\n";
$ncols -= $sheet->{MinCol} if defined $sheet->{MinCol} ;
$roffset = $sheet->{MinRow}-1;
$rsize = $sheet->{MaxRow} - $sheet->{MinRow};
die "Error:the specified worksheet seems to contain only one line\n" if $rsize == 0;
$roffset += $skip;
$lastrow = ( defined $nrows
? $nrows + $roffset -1
: $sheet->{MaxRow} );
die "Invalid skip option: the sheet only has $rsize rows" if $roffset >= $rsize - 1;
my (@types, @sqltypes, @firstrow, @titlerow);
 
if($coldefs ne "auto"){
#-- We have user-defined column definitions
#-- Check them
$coldefs =~ s/^\s*//;
$coldefs =~ s/\s*$//;
@defs = split ",", $coldefs;
foreach $i (0..$#defs){
($colname, $typedef) = split /\s+/,$defs[$i],2;
die "Column specification $i: can't parse SQL type definition '$typedef' (should be INTEGER, DOUBLE PRECISION, CHAR).\n" if $typedef !~ /INTEGER|DOUBLE PRECISION|CHAR/i;
die "Column name '$colname' for column $i contains spurious characters (no spaces permitted in list).\n" if $colname !~ /[a-zA-Z][a-zA-Z_0-9]*/;
push @sqltypes, $typedef;
push @titles, $colname;
}
}else{
#-- Inspect file for types:
#-- First estimate initial types from the first row of data
@firstrow = @{$sheet->{Cells}[$roffset+1]};
@types = map { $_->{Type}} @firstrow;
%cvt = (Text=>'CHAR',Numeric=>'INTEGER',Date=>'DOUBLE');
@sqltypes = map { $cvt{$_} } @types;
@lens = map { 0 } @types;
print STDERR "\nTypes:", join ";", @types if $DEBUG;
print STDERR "\nInitial sqltypes:", join ";", @sqltypes if $DEBUG;
#-- Then adjust widths and numeric type from the data
for(my $iR = $roffset ; $iR <= $lastrow ; $iR++) {
for(my $iC = $sheet->{MinCol} ;$iC <= $sheet->{MaxCol} ; $iC++) {
$cell = $sheet->{Cells}[$iR][$iC];
next if !defined $cell;
$cellvalue = $cell->Value;
if($types[$iC] eq 'Text'){
$thislength = length( $cellvalue );
$lens[$iC] = $thislength if $thislength > $lens[$iC];
}else{
if( $cellvalue =~ /[\.,]/ ){
$sqltypes[$iC] = 'DOUBLE PRECISION';
}
if( $cellvalue =~ /[a-df-z]/ ){
$sqltypes[$iC] = 'CHAR'; $lens[$iC] = length( $cellvalue);
}
}
}
}
foreach $i (0..$#sqltypes){
if( $sqltypes[$i] eq 'CHAR' ){
$sqltypes[$i] .= "($lens[$i])";
}
}
print STDERR "\nAdjusted sqltypes:", join ";", @sqltypes if $DEBUG;
 
#-- Generate field names from the title row
@titlerow = @{$sheet->{Cells}[$roffset]};
print STDERR "\nTitlerow:", join ";", map { defined $_ ? $_->Value : "" } @titlerow if $DEBUG;
$varname = "V000";
@titles = map {
/^[^a-zA-Z]/ ? $varname++ : $_
} map {
if( defined $_ && length > 0 ) {$_=$_->Value;y/a-z/A-Z/;s/[^a-zA-Z_0-9]/_/g}
else { $_=$varname++ }
$_;
} @titlerow;
map { $istitle{$_}++ } @titles;
foreach $i (reverse 0..$#titles){
if( $istitle{$titles[$i]} > 1){
$titles[$i] .= --$istitle{$titles[$i]};
}
}
while( $#titles < $ncols ){ #Missing titles, according to the size of the sheet
push @titles, $varname++;
push @sqltypes, "CHAR(32)";
}
print STDERR "\nTitles:" ,join ";", @titles if $DEBUG;
print STDERR "\n" if $DEBUG;
}
 
#-- Write out
print "CREATE TABLE $tablename (";
print join ",", map {"$titles[$_] $sqltypes[$_]"} (0..$#titles);
print ");\n";
if($coldefs eq "auto"){
$lastcol = $sheet->{MaxCol};
}else{
$lastcol = $#sqltypes + $sheet->{MinCol};
foreach $i (reverse 0..$#sqltypes){
$sqltypes[$i + $sheet->{MinCol}] = $sqltypes[$i];
}
}
for(my $iR = $roffset+1 ; $iR <= $lastrow ; $iR++) {
print "INSERT INTO $tablename VALUES(";
print join ",", map {
my $c = $sheet->{Cells}[$iR][$_];
# defined $c ? '"'.&cast($c->Value,$sqltypes[$_]).'"' : NULL
defined $c ? ''.&cast($c->Value,$sqltypes[$_]).'' : NULL
} ($sheet->{MinCol}..$lastcol);
print ");\n"
}
 
sub cast($$){
my ($value, $sqltype) = @_;
if( length($value)>0 ){
if ($value eq $nodata){
$value = "NULL"; # no data coded with char
}else{
if( $sqltype =~ /CHAR\s*\((\d+)\)/i ){
$value =~ s/[\n\r]/ /gm;
$value =~ s/"/\\"/g;
$value =~ s/'/\\'/g;
# $value = substr( $value, 0, $1 );
$value = '\''.substr( $value, 0, $1 ).'\'';
}elsif( $sqltype =~ /DOUBLE PRECISION/i ){
$value += 0;
}elsif( $sqltype =~ /INTEGER/i ){
$value = int $value;
}else{
die "Unknown SQL type '$sqltype'; can't typecast '$value' to that type.\n";
}
}
}else{
$value = "NULL"; # no data
}
}
 
sub parse_opts(){
for $o (sort keys %gopts){
if( defined $gopts{$o}[2] ){
${$gopts{$o}[0]} = $gopts{$o}[2];
}
for $arg (@ARGV){
$arg =~ /^\Q$o\E(?:\s*=\s*(.+)$)?/;
if( length($1)>0 ){
${$gopts{$o}[0]} = $1;
}elsif( $& ){
${$gopts{$o}[0]} = 1;
}
}
}
if($help){
select STDERR;
print "\n$PROGRAM_NAME : extract sheets from an excel workbook and\n";
print "produce SQL statements that create the database\n";
print "\nArguments (use grass style, i.e. arg=value):\n";
foreach (keys %gopts){ $longest = $longest < length() ? length() : $longest }
foreach $arg (grep {!/help/} keys %gopts){
print " $arg".(" "x($longest+2-length $arg));
print $gopts{$arg}[1];
print " (default: ".$gopts{$arg}[2].")" if defined $gopts{$arg}[2];
print "\n";
}
select STDOUT;
die "\n";
}
}
 
/tags/v5.7-arrayanal/scripts/modules/bonnier/shell/charger_sql.sh
New file
0,0 → 1,149
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/001-Renonculacees" -table renonculacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/002-Berberidees" -table berberidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/003-Nympheacees" -table nympheacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/004-Papaveracees" -table papaveracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/005-Fumariacees" -table fumariacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/006-Cruciferes" -table cruciferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/007-Capparidees" -table capparidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/008-Cistinees" -table cistinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/009-Violariees" -table violariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/010-Resedacees" -table resedacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/011-Droseracees" -table droseracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/012-Polygalees" -table polygalees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/013-Frankeniacees" -table frankeniacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/014-Caryophyllees" -table caryophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/015-Elatinees" -table elatinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/016-Linees" -table linees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/017-Tiliacees" -table tiliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/018-Malvacees" -table malvacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/019-Geraniees" -table geraniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/020-Hypericinees" -table hypericinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/021-Acerinees" -table acerinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/022-Ampelidees" -table ampelidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/023-Hippocastanees" -table hippocastanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/024-Meliacees" -table meliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/025-Balsaminees" -table balsaminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/026-tablexalidees" -table oxalidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/027-Zygophyllees" -table zygophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/028-Hesperidees" -table hesperidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/029-Rutacees" -table rutacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/030-Coriariees" -table coriariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/031-Celastrinees" -table celastrinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/032-Staphyleacees" -table staphyleacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/033-Ilicinees" -table ilicinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/034-Rhamnees" -table rhamnees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/035-Terebinthacees" -table terebinthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/036-Papilionacees" -table papilionacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/037-Cesalpiniees" -table cesalpiniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/038-Rosacees" -table rosacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/039-Granatees" -table granatees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/040-tablenagrariees" -table onagrariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/041-Myriophyllees" -table myriophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/042-Hippuridees" -table hippuridees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/043-Callitrichinees" -table callitrichinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/044-Ceratophyllees" -table ceratophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/045-Lythrariees" -table lythrariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/046-Philadelphees" -table philadelphees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/047-Tamariscinees" -table tamariscinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/048-Myrtacees" -table myrtacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/049-Cucurbitacees" -table cucurbitacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/050-Portulacees" -table portulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/051-Paronychiees" -table paronychiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/052-Crassulacees" -table crassulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/053-Cactees" -table cactees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/054-Ficoïdees" -table ficoïdees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/055-Grossulariees" -table grossulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/056-Saxifragees" -table saxifragees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/057-tablembelliferes" -table ombelliferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/058-Araliacees" -table araliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/059-Cornees" -table cornees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/060-Loranthacees" -table loranthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/061-Caprifoliacees" -table caprifoliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/062-Rubiacees" -table rubiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/063-Valerianees" -table valerianees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/064-Dipsacees" -table dipsacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/065-Composees" -table composees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/066-Ambrosiacees" -table ambrosiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/067-Lobeliacees" -table lobeliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/068-Campanulacees" -table campanulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/069-Vacciniees" -table vacciniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/070-Ericinees" -table ericinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/071-Pyrolacees" -table pyrolacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/072-Monotropees" -table monotropees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/073-Lentibulariees" -table lentibulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/074-Primulacees" -table primulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/075-Ebenacees" -table ebenacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/076-Styracees" -table styracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/077-tableleinees" -table oleinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/078-Jasminees" -table jasminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/079-Apocynees" -table apocynees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/080-Asclepiadees" -table asclepiadees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/081-Gentianees" -table gentianees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/082-Polemoniacees" -table polemoniacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/083-Convolvulacees" -table convolvulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/084-Cuscutacees" -table cuscutacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/085-Ramondiacees" -table ramondiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/086-Borraginees" -table borraginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/087-Solanees" -table solanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/088-Verbascees" -table verbascees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/089-Scrofularinees" -table scrofularinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/090-tablerobanchees" -table orobanchees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/091-Labiees" -table labiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/092-Acanthacees" -table acanthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/093-Verbenacees" -table verbenacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/094-Plantaginees" -table plantaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/095-Plombaginees" -table plombaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/096-Globulariees" -table globulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/097-Phytolaccees" -table phytolaccees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/098-Amarantacees" -table amarantacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/099-Salsolacees" -table salsolacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/100-Polygonees" -table polygonees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/101-Daphnoidees" -table daphnoidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/102-Laurinees" -table laurinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/103-Santalacees" -table santalacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/104-Eleagnees" -table eleagnees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/105-Cytinees" -table cytinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/106-Aristolochiees" -table aristolochiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/107-Empetrees" -table empetrees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/108-Euphorbiacees" -table euphorbiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/109-Morees" -table morees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/110-Ficacees" -table ficacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/111-Celtidees" -table celtidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/112-Ulmacees" -table ulmacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/113-Urticees" -table urticees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/114-Cannabinees" -table cannabinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/115-Juglandees" -table juglandees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/116-Cupuliferes" -table cupuliferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/117-Salicinees" -table salicinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/118-Platanees" -table platanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/119-Betulinees" -table betulinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/120-Myricees" -table myricees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/121-Alismacees" -table alismacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/122-Butomees" -table butomees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/123-Colchicacees" -table colchicacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/124-Liliacees" -table liliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/125-Dioscorees" -table dioscorees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/126-Iridees" -table iridees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/127-Amaryllidees" -table amaryllidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/128-tablerchidees" -table orchidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/129-Hydrocharidees" -table hydrocharidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/130-Joncaginees" -table joncaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/131-Potamees" -table potamees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/132-Naiadees" -table naiadees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/133-Zosteracees" -table zosteracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/134-Lemnacees" -table lemnacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/135-Aroidees" -table aroidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/136-Typhacees" -table typhacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/137-Joncees" -table joncees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/138-Cyperacees" -table cyperacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/139-Graminees" -table graminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/140-Abietinees" -table abietinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/141-Cupressinees" -table cupressinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/142-Taxinees" -table taxinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/143-Gnetacees" -table gnetacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/144-Fougeres" -table fougeres
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/145-tablephioglossees" -table ophioglossees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/146-Marsiliacees" -table marsiliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/147-Equisetacees" -table equisetacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/148-Isoetees" -table isoetees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a charger -dossier "menus/149-Lycopodiacees" -table lycopodiacees
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/bonnier/shell/generer_html.sh
New file
0,0 → 1,149
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/001-Renonculacees" -table renonculacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/002-Berberidees" -table berberidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/003-Nympheacees" -table nympheacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/004-Papaveracees" -table papaveracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/005-Fumariacees" -table fumariacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/006-Cruciferes" -table cruciferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/007-Capparidees" -table capparidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/008-Cistinees" -table cistinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/009-Violariees" -table violariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/010-Resedacees" -table resedacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/011-Droseracees" -table droseracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/012-Polygalees" -table polygalees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/013-Frankeniacees" -table frankeniacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/014-Caryophyllees" -table caryophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/015-Elatinees" -table elatinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/016-Linees" -table linees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/017-Tiliacees" -table tiliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/018-Malvacees" -table malvacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/019-Geraniees" -table geraniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/020-Hypericinees" -table hypericinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/021-Acerinees" -table acerinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/022-Ampelidees" -table ampelidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/023-Hippocastanees" -table hippocastanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/024-Meliacees" -table meliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/025-Balsaminees" -table balsaminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/026-tablexalidees" -table oxalidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/027-Zygophyllees" -table zygophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/028-Hesperidees" -table hesperidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/029-Rutacees" -table rutacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/030-Coriariees" -table coriariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/031-Celastrinees" -table celastrinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/032-Staphyleacees" -table staphyleacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/033-dossierlicinees" -table ilicinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/034-Rhamnees" -table rhamnees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/035-Terebinthacees" -table terebinthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/036-Papilionacees" -table papilionacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/037-Cesalpiniees" -table cesalpiniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/038-Rosacees" -table rosacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/039-Granatees" -table granatees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/040-tablenagrariees" -table onagrariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/041-Myriophyllees" -table myriophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/042-Hippuridees" -table hippuridees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/043-Callitrichinees" -table callitrichinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/044-Ceratophyllees" -table ceratophyllees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/045-Lythrariees" -table lythrariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/046-Philadelphees" -table philadelphees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/047-Tamariscinees" -table tamariscinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/048-Myrtacees" -table myrtacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/049-Cucurbitacees" -table cucurbitacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/050-Portulacees" -table portulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/051-Paronychiees" -table paronychiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/052-Crassulacees" -table crassulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/053-Cactees" -table cactees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/054-Ficoïdees" -table ficoïdees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/055-Grossulariees" -table grossulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/056-Saxifragees" -table saxifragees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/057-tablembelliferes" -table ombelliferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/058-Araliacees" -table araliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/059-Cornees" -table cornees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/060-Loranthacees" -table loranthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/061-Caprifoliacees" -table caprifoliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/062-Rubiacees" -table rubiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/063-Valerianees" -table valerianees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/064-Dipsacees" -table dipsacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/065-Composees" -table composees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/066-Ambrosiacees" -table ambrosiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/067-Lobeliacees" -table lobeliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/068-Campanulacees" -table campanulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/069-Vacciniees" -table vacciniees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/070-Ericinees" -table ericinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/071-Pyrolacees" -table pyrolacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/072-Monotropees" -table monotropees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/073-Lentibulariees" -table lentibulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/074-Primulacees" -table primulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/075-Ebenacees" -table ebenacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/076-Styracees" -table styracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/077-tableleinees" -table oleinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/078-Jasminees" -table jasminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/079-Apocynees" -table apocynees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/080-Asclepiadees" -table asclepiadees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/081-Gentianees" -table gentianees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/082-Polemoniacees" -table polemoniacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/083-Convolvulacees" -table convolvulacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/084-Cuscutacees" -table cuscutacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/085-Ramondiacees" -table ramondiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/086-Borraginees" -table borraginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/087-Solanees" -table solanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/088-Verbascees" -table verbascees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/089-Scrofularinees" -table scrofularinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/090-tablerobanchees" -table orobanchees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/091-Labiees" -table labiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/092-Acanthacees" -table acanthacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/093-Verbenacees" -table verbenacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/094-Plantaginees" -table plantaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/095-Plombaginees" -table plombaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/096-Globulariees" -table globulariees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/097-Phytolaccees" -table phytolaccees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/098-Amarantacees" -table amarantacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/099-Salsolacees" -table salsolacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/100-Polygonees" -table polygonees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/101-Daphnoidees" -table daphnoidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/102-Laurinees" -table laurinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/103-Santalacees" -table santalacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/104-Eleagnees" -table eleagnees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/105-Cytinees" -table cytinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/106-Aristolochiees" -table aristolochiees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/107-Empetrees" -table empetrees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/108-Euphorbiacees" -table euphorbiacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/109-Morees" -table morees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/110-Ficacees" -table ficacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/111-Celtidees" -table celtidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/112-Ulmacees" -table ulmacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/113-Urticees" -table urticees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/114-Cannabinees" -table cannabinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/115-Juglandees" -table juglandees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/116-Cupuliferes" -table cupuliferes
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/117-Salicinees" -table salicinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/118-Platanees" -table platanees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/119-Betulinees" -table betulinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/120-Myricees" -table myricees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/121-Alismacees" -table alismacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/122-Butomees" -table butomees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/123-Colchicacees" -table colchicacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/124-Liliacees" -table liliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/125-Dioscorees" -table dioscorees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/126-dossierridees" -table iridees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/127-Amaryllidees" -table amaryllidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/128-tablerchidees" -table orchidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/129-Hydrocharidees" -table hydrocharidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/130-Joncaginees" -table joncaginees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/131-Potamees" -table potamees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/132-Naiadees" -table naiadees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/133-Zosteracees" -table zosteracees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/134-Lemnacees" -table lemnacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/135-Aroidees" -table aroidees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/136-Typhacees" -table typhacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/137-Joncees" -table joncees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/138-Cyperacees" -table cyperacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/139-Graminees" -table graminees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/140-Abietinees" -table abietinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/141-Cupressinees" -table cupressinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/142-Taxinees" -table taxinees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/143-Gnetacees" -table gnetacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/144-Fougeres" -table fougeres
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/145-tablephioglossees" -table ophioglossees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/146-Marsiliacees" -table marsiliacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/147-Equisetacees" -table equisetacees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/148-dossiersoetees" -table isoetees
/opt/lampp/bin/php ../../../script.php bonnier -p bonnier -a html -dossier "menus/149-Lycopodiacees" -table lycopodiacees
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/bonnier/bonnier.ini
New file
0,0 → 1,20
; Encodage : UTF-8
; Exemple de fichier de configuration d'un projet
; Les commentaires commencent par ';', comme dans php.ini
 
; Indique le nom du projet
projet_nom = bonnier
; Indique le nombre sur un chiffre de la version du projet
version = 0
; Indique le nombre sur deux chiffres de la sous version du projet
sous_version = 00
; Indique la date de début de cette version du projet
date_debut = "2009-12-11 00:00:00"
; Indique la date de fin de cette version du projet
date_fin = NULL
; Indique le chemin où les fichier html vont être générés
chemin_fichier_sortie = "php:'/home/'.'david'.'/Bureau/bonnierhtml/'"
; Indique le chemin où trouver le fichier du projet contenant les données à charger puis standardiser
chemin_fichier_tab = "php:'/home/'.'david'.'/Bureau/bonnierhtml/'"
; Indique le chemin où stocker le fichier de log
log_chemin = "php:'/home/'.'david'.'/Bureau/bonnierhtml/'"
/tags/v5.7-arrayanal/scripts/modules/osm/OrdonneurDeChemins.php
New file
0,0 → 1,162
<?php
/**
* Traitement de l'ordre :
*
* Fonction qui rajoute l'ordre et le sens de chaque way d'une relation dans la table `osm_relation_a_chemins`
*
* Exemple de lancement du script :
* /opt/lampp/bin/php -d memory_limit=8000M cli.php osm -a ordre -m manuel
*
*/
class OrdonneurDeChemins {
private $conteneur;
private $bdd;
private $messages;
private $mode;
 
private $infosRel = array();
private $infosNoeuds = array();
private $idRelation = null;
private $idChemin = null;
private $idNoeud = null;
private $ordre = 0;
 
public function __construct($conteneur) {
$this->conteneur = $conteneur;
$this->bdd = $this->conteneur->getBdd();
$this->messages = $this->conteneur->getMessages();
$this->mode = $this->conteneur->getParametre('m');
}
 
public function executer() {
$relations = $this->getToutesRelationsAChemins();
if ($this->mode == 'manuel') {
$this->messages->traiterInfo("Nombre de relations : %s", array(count($relations)));
}
foreach ($relations as $relation) {
// Traitement de la relation courante
$this->idRelation = $relation['id_relation'];
 
$this->chargerDonneesRelationActuelle();
 
// Selection du premier chemin comme chemin actuel
$this->idChemin = $this->getIdPremierChemin();
$this->mettreAJourChemin('directe', __LINE__);
 
// Selection du dernier noeud comme noeud actuel
$idDernierNoeud = $this->getIdDernierNoeud();
if ($idDernierNoeud) {
$this->idNoeud = $idDernierNoeud;
$this->ordonnerChemins();
}
 
// Affichage de l'avancement
if ($this->mode == 'manuel') {
$this->messages->afficherAvancement("Ordone les chemins de la relation : ", 1);
}
}
}
 
private function getToutesRelationsAChemins() {
$requete = 'SELECT DISTINCT id_relation '.
'FROM osm_relation_a_chemins '.
' -- '.__FILE__.' : '.__LINE__;
$relations = $this->bdd->recupererTous($requete);
return $relations;
}
 
private function chargerDonneesRelationActuelle() {
$requete = 'SELECT cn.id_chemin, cn.id_noeud, cn.ordre '.
'FROM osm_relation_a_chemins AS rc '.
' INNER JOIN osm_chemin_a_noeuds AS cn ON (rc.id_chemin = cn.id_chemin) '.
"WHERE rc.id_relation = {$this->idRelation} ".
"ORDER BY cn.ordre ASC ".
' -- '.__FILE__.' : '.__LINE__;
$infos = $this->bdd->recupererTous($requete);
foreach ($infos as $info) {
$this->infosRel[$info['id_chemin']][$info['id_noeud']] = $info['ordre'];
if (! isset($this->infosNoeuds[$info['id_noeud']][$info['id_chemin']])) {
$this->infosNoeuds[$info['id_noeud']][$info['id_chemin']] = 1;
} else {
$this->infosNoeuds[$info['id_noeud']][$info['id_chemin']]++;
}
}
//print_r($this->infosNoeuds);exit();
$this->ordre = 0;
}
 
private function getIdPremierChemin() {
$idChemin = null;
if (count($this->infosRel) > 0) {
reset($this->infosRel);
$idChemin = key($this->infosRel);
}
return $idChemin;
}
 
private function mettreAJourChemin($sens, $ligne, $fichier = __FILE__) {
$ordre = $this->ordre++;
$requete = 'UPDATE osm_relation_a_chemins '.
"SET ordre = '$ordre', sens = '$sens' ".
"WHERE id_relation = {$this->idRelation} ".
"AND id_chemin = {$this->idChemin} ".
" -- $fichier : $ligne";
$retour = $this->bdd->requeter($requete);
return $retour;
}
 
private function getIdDernierNoeud() {
$idNoeud = false;
if (count($this->infosRel[$this->idChemin]) > 0) {
end($this->infosRel[$this->idChemin]);
$idNoeud = key($this->infosRel[$this->idChemin]);
}
return $idNoeud;
}
 
private function ordonnerChemins() {
foreach ($this->infosRel as $chemin) {
// Selection du chemin qui possède le dernier noeud du précédent chemin et écarter l'actuel
$idCheminSuivant = $this->getIdCheminSuivant();
if ($idCheminSuivant) {
$this->idChemin = $idCheminSuivant;
$idPremierNoeud = $this->getIdPremierNoeud();
$idDernierNoeud = $this->getIdDernierNoeud();
$sens = $this->getSens($idPremierNoeud);
$this->mettreAJourChemin($sens, __LINE__);
$this->idNoeud = ($sens == 'directe') ? $idDernierNoeud : $idPremierNoeud;
}
}
}
 
private function getIdCheminSuivant() {
$idCheminSuivant = false;
if (isset($this->infosNoeuds[$this->idNoeud])) {
$cheminsIds = array_keys($this->infosNoeuds[$this->idNoeud]);
foreach ($cheminsIds as $idChemin) {
if ($idChemin != $this->idChemin) {
$idCheminSuivant = $idChemin;
break;
}
}
} else {
$msg = "Impossible de trouver le chemin suivant pour la relation : %s, le chemin %s et le noeud %s";
$this->messages->traiterAvertissement($msg, array($this->idRelation, $this->idChemin, $this->idNoeud));
}
return $idCheminSuivant;
}
 
private function getSens($idPremierNoeud) {
$sens = ( strcmp($idPremierNoeud, $this->idNoeud ) == 0 ) ? 'directe' : 'indirecte';
return $sens;
}
 
private function getIdPremierNoeud() {
$idNoeud = false;
if (count($this->infosRel[$this->idChemin]) > 0) {
reset($this->infosRel[$this->idChemin]);
$idNoeud = key($this->infosRel[$this->idChemin]);
}
return $idNoeud;
}
}
/tags/v5.7-arrayanal/scripts/modules/osm/config.ini
New file
0,0 → 1,9
; Ajouter les nouvelles version à la suite dans versions et versionsDonnees.
version = "1.0"
dossierSql = "{ref:dossierDonneesEflore}osm/"
 
[fichiers]
structureSql = "osm.sql"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:version}/{ref:fichiers.structureSql}"
/tags/v5.7-arrayanal/scripts/modules/osm/MiseAJour.php
New file
0,0 → 1,417
<?php
/**
* Permet de mettre à jour les contours à partir d'un fichier de diff.
*
* Exemple de lancement du script :
* /opt/lampp/bin/php -d memory_limit=3500M cli.php osm -a maj -f fichier_osm_change -e fichier_osm_nouveau
*/
class MiseAJour {
private $conteneur;
private $bdd;
private $messages;
private $mode;
 
private $communes = array();
private $relations_communes = array();
private $relation_a_chemins = array();
private $chemin_a_noeuds = array();
private $noeuds = array();
private $pas = 10000;
private $pas_commune = 1000;
private $elementType = '';
 
public function __construct($conteneur) {
$this->conteneur = $conteneur;
$this->bdd = $this->conteneur->getBdd();
$this->messages = $this->conteneur->getMessages();
$this->mode = $this->conteneur->getParametre('m');
}
 
/**
* Fonction qui parcourt tous les ways les noeuds de chaque relation en prenant en considération l'ordre et
* le sens de chaque ways concaténés ensemble (séparés par des virgules). Update du champ polygone de chaque
* relation dans la table `osm_relations`
*/
public function executer() {
// Lancement de l'action demandée
$cmd = $this->conteneur->getParametre('a');
switch ($cmd) {
case 'maj' :
$this->mettreAjour();
break;
default :
$msgTpl = "Erreur : la commande '%s' n'est pas prise en compte par la classe %s !";
$msg = sprintf($msgTpl, $cmd, get_class($this));
throw new Exception($msg);
}
print "\n";// Pour ramener à la ligne en fin de script
}
 
/**
* Fonction permettant de traiter et d'analyser le fichier de différence et de mettre à jour la base de données
* en tenant compte des trois cas:Suppression, Création ,modification
*/
private function mettreAjour() {
$lecteur = $this->getLecteurXml();
while ($lecteur->read()) {
if ($lecteur->nodeType == XMLREADER::ELEMENT) {
$this->elementType = $lecteur->localName;
$this->analyserElementXml($lecteur->localName, $lecteur->expand());
}
 
if ($this->mode == 'manuel') {
$this->messages->afficherAvancement("Analyse de la ligne du fichier de diff OSM : ", 1);
}
}
}
 
private function getLecteurXml() {
$fichierOsm = $this->conteneur->getParametre('f');
$lecteur = new XMLReader();
$ouvertureXmlOk = $lecteur->open($fichierOsm);
if ($ouvertureXmlOk === false) {
$msgTpl = "Impossible d'ouvrir le fichier osm : %s";
$msg = sprintf($msgTpl, $this->conteneur->getParametre('f'));
new Exception($msg);
}
return $lecteur;
}
 
private function analyserElementXml($noeudDom) {
$relations = $noeudDom->getElementsByTagName('relation');
if ($relations->length > 0) {
foreach ($relations as $relation) {
$this->analyserRelation($relation);
$this->traiterRelations();
}
}
 
$ways = $creations->getElementsByTagName('way');
if ($ways->length > 0) {
foreach ($ways as $way) {
$this->analyserWay($way);
$this->traiterCheminANoeuds();
}
}
 
$noeuds = $creations->getElementsByTagName('node');
if ($noeuds->length > 0) {
foreach ($noeuds as $noeud) {
$this->analyserNode($noeud);
$this->traiterNoeuds();
}
}
 
$this->traiterElementsOrphelins();
}
 
private function traiterRelations() {
if (count($this->relation_a_chemins) > $this->pas) {
switch ($this->elementType) {
case 'create' :
$this->insererRelationAChemins();
break;
case 'modify' :
$this->modifierRelationAChemins();
break;
case 'delete' :
$this->supprimerRelationAChemins();
break;
}
}
if (count($this->relations_communes) > $this->pas_commune) {
switch ($this->elementType) {
case 'create' :
$this->insererRelationsCommunes();
break;
case 'modify' :
$this->modifierRelationsCommunes();
break;
case 'delete' :
$this->supprimerRelationsCommunes();
break;
}
}
}
 
private function traiterChemins() {
if (count($this->chemin_a_noeuds) > $this->pas) {
switch ($this->elementType) {
case 'create' :
$this->insererCheminANoeuds();
break;
case 'modify' :
$this->modifierCheminANoeuds();
break;
case 'delete' :
$this->supprimerCheminANoeuds();
break;
}
}
}
 
private function traiterNoeuds() {
if (count($this->noeuds) > $this->pas) {
switch ($this->elementType) {
case 'create' :
$this->insererNoeuds();
break;
case 'modify' :
$this->modifierNoeuds();
break;
case 'delete' :
$this->supprimerNoeuds();
break;
}
}
}
 
private function traiterElementsOrphelins() {
switch ($this->elementType) {
case 'create' :
$this->insererRelationsCommunes();
$this->insererRelationAChemins();
$this->insererCheminANoeuds();
$this->insererNoeuds();
break;
case 'modify' :
$this->modifierRelationsCommunes();
$this->modifierRelationAChemins();
$this->modifierCheminANoeuds();
$this->modifierNoeuds();
break;
case 'delete' :
$this->supprimerRelationsCommunes();
$this->supprimerRelationAChemins();
$this->supprimerCheminANoeuds();
$this->supprimerNoeuds();
break;
}
}
 
/**
* Récupère l'id commune, nom commune et le code INSEE et remplie la table `osm_relations`
*/
private function analyserRelation($relation) {
$relation_id = $relation->getAttribute('id');
$chemins = $relation->getElementsByTagName('member');
foreach ($chemins as $chemin) {
if ($chemin->getAttribute('type') == 'way') { //écarter le noeud centrale
$chemin_id = $chemin->getAttribute('ref');
$role = $chemin->getAttribute('role');//role: null, inner, outer, exclave et enclave.
$this->relation_a_chemins[] = array($relation_id, $chemin_id, $role);
}
}
 
$tags = $relation->getElementsByTagName('tag');
if ($tags->length > 0) {
$this->analyserTags($relation_id, $tags);
}
}
 
private function analyserTags($relation_id, $tags) {
$commune_nom = null;
$commune_insee = null;
foreach ($tags as $tag) {
$tag_cle = $tag->getAttribute('k');
$tag_val = $tag->getAttribute('v');
switch ($tag_cle) {
case 'name' :
$commune_nom = $tag_val;
break;
case 'ref:INSEE' :
$commune_insee = $tag_val;
break;
}
if (!is_null($commune_nom) && !is_null($commune_insee)) {
$this->relations_communes[] = array($relation_id, $commune_nom, $commune_insee);
if (!isset($this->communes[$commune_insee])) {
$this->communes[$commune_insee] = $relation_id;
} else {
$e = "La relation #%s contient déjà le tag ref:INSEE avec la valeur %s.".
"Veuillez corriger la carte OSM.";
$this->traiterErreur($e, array($this->communes[$commune_insee], $commune_insee, $relation_id));
}
break;
}
}
}
 
/**
* Récupère l'id_way et tous les id_node de chaque way et remplie la table `osm_chemin_a_noeuds`
*/
private function analyserWay($way) {
$chemin_id = $way->getAttribute('id');
$noeuds = $way->getElementsByTagName('nd');
$ordre = 0;
foreach ($noeuds as $noeud) {
$noeud_id = $noeud->getAttribute('ref');
$this->chemin_a_noeuds[] = array($chemin_id, $noeud_id, ++$ordre);
}
}
 
/**
* Fonction qui récupère tous les l'id_node et les valeurs(Lat/Lon) correspondantes et remplie la table `osm_noeuds`
*/
private function analyserNode($node) {
$this->noeuds[] = array(
$node->getAttribute('id'),
$node->getAttribute('lat'),
$node->getAttribute('lon')
);
}
 
//Insertion des relations
private function insererRelationsCommunes() {
$requete = 'INSERT INTO osm_relations (id_relation, nom, code_insee) '.
'VALUES '.$this->creerValuesMultiple($this->relations_communes).
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
$this->relations_communes = array();
}
 
//Insertion des relations à chemins
private function insererRelationAChemins() {
$requete = 'INSERT INTO osm_relation_a_chemins (id_relation, id_chemin, role) '.
'VALUES '.$this->creerValuesMultiple($this->relation_a_chemins).
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
$this->relation_a_chemins = array();
}
 
//Insertion des chemins à noeuds
private function insererCheminANoeuds() {
$requete = 'INSERT INTO osm_chemin_a_noeuds (id_chemin, id_noeud, ordre) '.
'VALUES '.$this->creerValuesMultiple($this->chemin_a_noeuds).
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
$this->chemin_a_noeuds = array();
}
 
//Insertion des noeuds
private function insererNoeuds() {
$requete = 'INSERT INTO osm_noeuds (id_noeud, lat, `long`) '.
'VALUES '.$this->creerValuesMultiple($this->noeuds).
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
$this->noeuds = array();
}
 
//Update des relations
private function modifierRelationsCommunes() {
foreach ($this->relations_communes as $donnee) {
$infosP = $this->bdd->proteger($donnee);
$requete = 'UPDATE osm_relations '.
"SET id_relation = $infosP[0], nom = $infosP[1], code_insee = $infosP[2] ".
"WHERE id_relation = $infosP[0] ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
$this->relations_communes = array();
}
 
/*
*Update des relations à chemins en supprimant l'ancienne relation et tous ses chemins
*de la table osm_relation_a_chemins et insérer la nouvelle
*/
private function modifierRelationAChemins() {
$this->supprimerRelationAChemins();
foreach ($this->relation_a_chemins as $donnee) {
$infosP = $this->bdd->proteger($donnee);
$requete = 'INSERT INTO osm_relation_a_chemins (id_relation, id_chemin, role) '.
"VALUES ($infosP[0], $infosP[1], $infosP[2]) ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
$this->relation_a_chemins = array();
}
 
/*
*Update des chemins à noeuds en supprimant l'ancien chemin et tous ses noeuds
*de la table osm_chemins_a_noeuds et insérer le nouveau
*/
private function modifierCheminANoeuds() {
$this->supprimerCheminANoeuds();
foreach ($this->chemin_a_noeuds as $donnee) {
$infosP = $this->bdd->proteger($donnee);
$requete = 'INSERT INTO osm_chemin_a_noeuds (id_chemin, id_noeud, ordre) '.
"VALUES ($infosP[0], $infosP[1], $infosP[2]) ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
$this->chemin_a_noeuds = array();
}
 
//Update des noeuds
private function modifierNoeuds() {
foreach ($this->noeuds as $donnee) {
$infosP = $this->bdd->proteger($donnee);
$requete = 'UPDATE osm_noeuds '.
"SET id_noeud = $infosP[0], lat = $infosP[1], `long` = $infosP[2] ".
"WHERE id_noeud = $infosP[0] ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
$this->noeuds = array();
}
 
//Suppressions des relations
private function supprimerRelationsCommunes() {
$idsIn = $this->getIds($this->relations_communes);
$this->relations_communes = array();
$requete = 'DELETE FROM osm_relations '.
"WHERE id_relation IN ($idsIn) ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
 
//Suppressions des relations à chemins
private function supprimerRelationAChemins() {
$idsIn = $this->getIds($this->relation_a_chemins);
$this->relation_a_chemins = array();
$requete = 'DELETE FROM osm_relation_a_chemins '.
"WHERE id_relation IN ($idsIn) ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
 
//Suppressions des chemins à noeuds
private function supprimerCheminANoeuds() {
$idsIn = $this->getIds($this->chemin_a_noeuds);
$this->chemin_a_noeuds = array();
$requete = 'DELETE FROM osm_chemin_a_noeuds '.
"WHERE id_chemin IN ($idsIn) ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
 
//Suppressions des chemins à noeuds
private function supprimerNoeuds() {
$idsIn = $this->getIds($this->noeuds);
$this->noeuds = array();
$requete = 'DELETE FROM osm_noeuds '.
"WHERE id_noeud IN ($idsIn) ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
 
private function getIds(&$tableau) {
$ids = array();
foreach ($tableau as $info) {
$ids[] = $this->bdd->proteger($info[0]);
}
$idsSansDoublon = array_unique($ids);
$idsIn = implode(',', $idsSansDoublon);
return $idsIn;
}
 
private function creerValuesMultiple($donnees) {
$values = array();
foreach ($donnees as $infos) {
$infosP = $this->bdd->proteger($infos);
$values[] = implode(',', $infosP);
}
$valuesClause = '('.implode('),(', $values).')';
return $valuesClause;
}
}
/tags/v5.7-arrayanal/scripts/modules/osm/Osm.php
New file
0,0 → 1,104
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* 1. Création de la base de données :
* /opt/lampp/bin/php cli.php osm -a chargerStructureSql -m manuel -v 3
*
* 2. Analyse du fichir OSM :
* /opt/lampp/bin/php cli.php osm -a analyser -f "../donnees/osm/fr_communes_new.osm" -m manuel -v 3
*
* 3. Traitement de l'ordre :
* /opt/lampp/bin/php cli.php osm -a ordre -m manuel -v 3
*
* 4. Remplissage des polygones :
* /opt/lampp/bin/php cli.php osm -a polygone -m manuel -v 3
*
* Définition des centroïdes pour les polygones déjà complets:
* /opt/lampp/bin/php cli.php osm -a centre -m manuel -v 3
*
* 5. Remise de l'ordre à zéro :
* /opt/lampp/bin/php cli.php osm -a zero -m manuel -v 3
*
* 6. Traitement de l'ordre des polygones incomplets :
* /opt/lampp/bin/php cli.php osm -a ordonnerPolygoneInc -m manuel -v 3
*
* 7. Remplissage des polygones incomplets :
* /opt/lampp/bin/php cli.php osm -a remplirPolygoneInc -m manuel -v 3
*
* 8. Renommage des polygones incomplets :
* /opt/lampp/bin/php cli.php osm -a renommer -m manuel -v 3
*
* 9. Définition des centroïdes :
* /opt/lampp/bin/php cli.php osm -a centre -m manuel -v 3
*
* @category php 5.4
* @package DEL
* @subpackage Scripts
* @author Aurélien PERONNET <aurelien@tela-botanica.org>
* @copyright Copyright (c) 2012, Tela Botanica (accueil@tela-botanica.org)
* @license CeCILL v2 http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt
* @license GNU-GPL http://www.gnu.org/licenses/gpl.html
*/
// TODO : Améliorer la gestion de l'ordre des chemins pour éviter de prendre en compte des chemins inexistants
class Osm extends EfloreScript {
 
const PROJET_NOM = 'osm';
 
protected $parametres_autorises = array(
'-f' => array(true, null, 'Chemin du fichier osm à analyser'),
'-m' => array(false, 'auto', 'Mode «auto» ou «manuel». En manuel, les compteurs dans les boucles sont affichés.'));
 
public function executer() {
try {
$this->initialiserProjet(self::PROJET_NOM);
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'analyser' :
$script = $this->chargerClasse('ParseurOsm');
$script->executer();
break;
case 'ordre' :
$script = $this->chargerClasse('OrdonneurDeChemins');
$script->executer();
break;
case 'polygone' :
case 'centre' :
case 'zero' :
$script = $this->chargerClasse('PolygoneCreateur');
$script->executer();
break;
case 'ordonnerPolygoneInc' :
case 'remplirPolygoneInc' :
case 'renommer' :
$script = $this->chargerClasse('PolygoneReparateur');
$script->executer();
break;
case 'maj' :
$script = $this->chargerClasse('MiseAJour');
$script->executer();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
print "\n";// Pour ramener à la ligne en fin de script
}
 
protected function initialiserProjet($projetNom) {
$this->projetNom = $projetNom;
}
 
private function chargerClasse($classe) {
require_once $classe.'.php';
$conteneur = new Conteneur($this->parametres);
return new $classe($conteneur);
}
}
/tags/v5.7-arrayanal/scripts/modules/osm/ParseurOsm.php
New file
0,0 → 1,244
<?php
/**
* Exemple de lancement du script :
*
* Analyse du fichir OSM :
* /opt/lampp/bin/php cli.php osm -a analyser -f "../donnees/osm/france_communes_new.osm" -m manuel
*
*/
class ParseurOsm {
 
private $conteneur;
private $bdd;
private $messages;
private $mode;
 
private $communes = array();
private $relations_communes = array();
private $relation_a_chemins = array();
private $chemin_a_noeuds = array();
private $noeuds = array();
private $pas = 10000;
private $pas_commune = 1000;
 
public function __construct($conteneur) {
$this->conteneur = $conteneur;
$this->bdd = $this->conteneur->getBdd();
$this->messages = $this->conteneur->getMessages();
$this->mode = $this->conteneur->getParametre('m');
}
 
public function executer() {
// Lancement de l'action demandée
$cmd = $this->conteneur->getParametre('a');
switch ($cmd) {
case 'analyser' :
$this->lireFichierOsm();
break;
case 'polygone' :
$this->remplirPolygone();
break;
case 'zero' :
$this->remettreOrdreAZero();
break;
default :
$this->messages->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
}
}
 
/**
* Lit le fichier OSM et lance l'analyse des noeuds xml en fonction de leur type.
*/
private function lireFichierOsm() {
$lecteur = $this->getLecteurXml();
while ($lecteur->read()) {
if ($lecteur->nodeType == XMLREADER::ELEMENT) {
$this->analyserElementXml($lecteur->localName, $lecteur->expand());
}
if ($this->mode == 'manuel') {
$this->messages->afficherAvancement("Analyse de la ligne du fichier OSM : ", 1);
}
}
$this->insererElementsOrphelins();
}
 
private function analyserElementXml($elementNom, $noeudDom) {
switch ($elementNom) {
case 'relation' :
$this->analyserRelation($noeudDom);
break;
case 'way' :
$this->analyserWay($noeudDom);
break;
case 'node' :
$this->analyserNode($noeudDom);
break;
}
}
 
private function insererElementsOrphelins() {
$this->insererRelationsCommunes();
$this->insererRelationAChemins();
$this->insererCheminANoeuds();
$this->insererNoeuds();
}
 
private function getLecteurXml() {
$fichierOsm = $this->conteneur->getParametre('f');
$lecteur = new XMLReader();
$ouvertureXmlOk = $lecteur->open($fichierOsm);
if ($ouvertureXmlOk === false) {
$msgTpl = "Impossible d'ouvrir le fichier osm : %s";
$msg = sprintf($msgTpl, $this->conteneur->getParametre('f'));
new Exception($msg);
}
return $lecteur;
}
 
/**
* Récupère l'id commune, nom commune et le code INSEE et remplie la table `CommuneOSM`
*/
private function analyserRelation($relation) {
$idRelation = $relation->getAttribute('id');
 
$chemins = $relation->getElementsByTagName('member');
$this->analyserChemins($idRelation, $chemins);
if (count($this->relation_a_chemins) > $this->pas) {
$this->insererRelationAChemins();
}
 
$tags = $relation->getElementsByTagName('tag');
$this->analyserTags($idRelation, $tags);
if (count($this->relations_communes) > $this->pas_commune) {
$this->insererRelationsCommunes();
}
}
 
private function analyserChemins($relation_id, $chemins) {
foreach ($chemins as $chemin) {
if ($chemin->getAttribute('type') == 'way') { //écarter le noeud centrale
$chemin_id = $chemin->getAttribute('ref');
$role = $chemin->getAttribute('role');//role: null, inner, outer, exclave et enclave.
$this->relation_a_chemins[] = array($relation_id, $chemin_id, $role);
}
}
}
 
private function analyserTags($relation_id, $tags) {
$commune_nom = null;
$commune_insee = null;
foreach ($tags as $tag) {
$tag_cle = $tag->getAttribute('k');
$tag_val = $tag->getAttribute('v');
 
switch ($tag_cle) {
case 'name' :
$commune_nom = $tag_val;
break;
case 'ref:INSEE' :
$commune_insee = $tag_val;
break;
}
 
if (!is_null($commune_nom) && !is_null($commune_insee)) {
 
if (!isset($this->relations_communes[$relation_id])) {
$this->relations_communes[$relation_id] = array($relation_id, $commune_nom, $commune_insee);
} else {
$e = "La relation #%s possédant le tag ref:INSEE «%s» est déjà prise en compte.";
$this->messages->traiterErreur($e, array($relation_id, $commune_insee));
}
 
if (!isset($this->communes[$commune_insee])) {
$this->communes[$commune_insee] = $relation_id;
} else {
$e = "La relation #%s contient déjà le tag ref:INSEE avec la valeur %s.".
"Veuillez corriger la carte OSM.";
$this->messages->traiterErreur($e, array($this->communes[$commune_insee], $commune_insee, $relation_id));
}
break;// Stoppe le foreach car nous avons les infos nécessaires
}
}
}
 
/**
* Récupère l'id_way et tous les id_node de chaque way et remplie la table `osm_chemin_a_noeuds`
*/
private function analyserWay($way) {
$chemin_id = $way->getAttribute('id');
$ordre = 1;
$noeuds = $way->getElementsByTagName('nd');
foreach ($noeuds as $noeud) {
$noeud_id = $noeud->getAttribute('ref');
$this->chemin_a_noeuds[] = array($chemin_id, $noeud_id, $ordre++);
}
 
if (count($this->chemin_a_noeuds) > $this->pas) {
$this->insererCheminANoeuds();
}
}
 
/**
* Fonction qui récupère tous les l'id_node et les valeurs(Lat/Lon) correspondantes et remplie la table `osm_noeuds`
*/
private function analyserNode($node) {
$noeud_id = $node->getAttribute('id');
$lat = $node->getAttribute('lat');
$lon = $node->getAttribute('lon');
$this->noeuds[] = array($noeud_id, $lat, $lon);
 
if (count($this->noeuds) > $this->pas) {
$this->insererNoeuds();
}
}
 
private function insererRelationsCommunes() {
if (count($this->relations_communes) > 0) {
$requete = 'INSERT INTO osm_relations (id_relation, nom, code_insee) '.
'VALUES '.$this->creerValuesMultiple($this->relations_communes).
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
$this->relations_communes = array();
}
 
private function insererRelationAChemins() {
if (count($this->relation_a_chemins) > 0) {
$requete = 'INSERT INTO osm_relation_a_chemins (id_relation, id_chemin, role) '.
'VALUES '.$this->creerValuesMultiple($this->relation_a_chemins).
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
$this->relation_a_chemins = array();
}
 
private function insererCheminANoeuds() {
if (count($this->chemin_a_noeuds) > 0) {
$requete = 'INSERT INTO osm_chemin_a_noeuds (id_chemin, id_noeud, ordre) '.
'VALUES '.$this->creerValuesMultiple($this->chemin_a_noeuds).
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
$this->chemin_a_noeuds = array();
}
 
private function insererNoeuds() {
if (count($this->noeuds) > 0) {
$requete = 'INSERT INTO osm_noeuds (id_noeud, lat, `long`) '.
'VALUES '.$this->creerValuesMultiple($this->noeuds).
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
$this->noeuds = array();
}
 
private function creerValuesMultiple($donnees) {
$values = array();
foreach ($donnees as $infos) {
$infosP = $this->bdd->proteger($infos);
$values[] = implode(',', $infosP);
}
$valuesClause = '('.implode('),(', $values).')';
return $valuesClause;
}
}
/tags/v5.7-arrayanal/scripts/modules/osm/shell/carto-osm-maj
New file
0,0 → 1,91
#!/bin/bash
#
# Script de lancement de l'integration des donnees OSM pour le geocodage inverse
# Mohcen BENMOUNAH & Jean-Pascal MILCENT [19 juillet 2011]
#
ageEnSeconde(){ expr `date +%s` - `stat -c %Y $1`; };
 
if [ -f config.cfg ] ; then
source config.cfg
echo $DATE;
else
echo "Veuillez paramétrer le script en renommant le fichier 'config.defaut.cfg' en 'config.cfg'."
exit;
fi
 
echo "Export de l'emplacement du binaire Java dans la variable d'environnement JAVACMD";
export JAVACMD="$CHEMIN_JAVA"
 
echo "Export de l'emplacement du dossier tmp pour Osmosis"
export JAVACMD_OPTIONS="-Djava.io.tmpdir=$OSMOSIS_DOSSIER_TMP -Xmx4G"
 
if [ ! -f "$DOSSIER_OSM/$FICHIER_OSM" ] || [ `ageEnSeconde "$DOSSIER_OSM/$FICHIER_OSM"` -gt 86000 ] ; then
echo "Téléchargement du nouveau fichier PBF ...";
wget $URL_FICHIER_OSM -O "$DOSSIER_OSM/$FICHIER_OSM"
else
echo "Fichier $FICHIER_OSM existant à moins d'un jour.";
fi
 
if [ ! -f "$DOSSIER_OSM/$FICHIER_ZG_NEW" ] || [ `ageEnSeconde "$DOSSIER_OSM/$FICHIER_ZG_NEW"` -gt 86000 ] ; then
echo "Filtrage du fichier en cours ...";
$CHEMIN_OSMOSIS \
-v \
--read-pbf-fast "$DOSSIER_OSM/$FICHIER_OSM" workers=6 \
--tf accept-relations admin_level=8 \
--tf accept-relations type=boundary \
--tf accept-relations ref:INSEE=* \
--used-way \
--used-node \
--wx "$DOSSIER_OSM/$FICHIER_ZG_NEW"
fi
 
HEURE_DEBUT=`date +"%F %X"`;
echo "Début éxecution scripts php : $HEURE_DEBUT";
 
if [ ! -f "$DOSSIER_OSM/$FICHIER_ZG_OLD" ] ; then
echo "Création des tables osm en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a chargerStructureSql -v $VERBOSITE > $FICHIER_LOG
 
echo "Analyse du fichier osm en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a analyser -v $VERBOSITE -f "$DOSSIER_OSM/$FICHIER_ZG_NEW" >> $FICHIER_LOG
else
echo "Suppression du fichier DIFF existant en cours ...";
rm -f "$DOSSIER_OSM/$FICHIER_ZG_DIFF"
 
echo "Déduction de la différence en cours ...";
$CHEMIN_OSMOSIS\
--read-xml file="$DOSSIER_OSM/$FICHIER_ZG_NEW" \
--read-xml file="$DOSSIER_OSM/$FICHIER_ZG_OLD" \
--derive-change \
--write-xml-change file="$DOSSIER_OSM/$FICHIER_ZG_DIFF"
 
echo "Début de la mise à jour de base ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php mise_a_jour -a MAJ -f "$DOSSIER_OSM/$FICHIER_ZG_DIFF" > $FICHIER_LOG
fi
 
echo "Renommage du fichier NEW en OLD en cours ...";
mv "$DOSSIER_OSM/$FICHIER_ZG_NEW" "$DOSSIER_OSM/$FICHIER_ZG_OLD" >> $FICHIER_LOG
 
echo "Traitement de l'ordre en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a ordre -v $VERBOSITE >> $FICHIER_LOG
 
echo "Remplissage des polygones en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a polygone -v $VERBOSITE >> $FICHIER_LOG
 
echo "Remise de l'ordre à zéro en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a zero -v $VERBOSITE >> $FICHIER_LOG
 
echo "Traitement de l'ordre des polygones incomplets en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a ordonnerPolygoneInc -v $VERBOSITE >> $FICHIER_LOG
 
echo "Remplissage des polygones incomplets en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a remplirPolygoneInc -v $VERBOSITE >> $FICHIER_LOG
 
echo "Renommage des polygones incomplets en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a renommer -v $VERBOSITE >> $FICHIER_LOG
 
echo "Definition des centroïdes en cours ...";
$CHEMIN_PHP -d memory_limit=$MEMORY_LIMIT_PHP $CHEMIN_SCRIPT/cli.php osm -a centre -v $VERBOSITE >> $FICHIER_LOG
 
HEURE_FIN=`date +"%F %X"`;
echo "Fin éxecution scripts php : $HEURE_FIN";
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/osm/shell/config.defaut.cfg
New file
0,0 → 1,26
# Binaires
CHEMIN_JAVA="/usr/local/jre/bin/java"
CHEMIN_PHP="/usr/local/php/5.5/bin/php"
CHEMIN_SCRIPT="/home/apitela/www/scripts/eflore"
 
# Dossiers, fichiers & urls
# Pour tester : http://download.geofabrik.de/europe/france/languedoc-roussillon-latest.osm.pbf
URL_FICHIER_OSM="http://download.geofabrik.de/europe/france-latest.osm.pbf"
DOSSIER_OSM="/home/jpm/web/eflore/eflore-projets/donnees/osm"
FICHIER_OSM="fr.osm.pbf"
FICHIER_ZG_NEW="fr_communes_new.osm"
FICHIER_ZG_OLD="fr_communes_old.osm"
FICHIER_ZG_DIFF="fr_communes_diff.osm"
 
# Osmosis
CHEMIN_OSMOSIS="/usr/local/sbin/osmosis-0.43.1/bin"
OSMOSIS_DOSSIER_TMP="$DOSSIER_OSM/tmp"
 
# Logs
VERBOSITE=3
DATE=`date +"%F"`
CHEMIN_LOG="$DOSSIER_OSM/logs"
FICHIER_LOG="$CHEMIN_LOG/analyse_${DATE}.log"
 
# Paramètres PHP
MEMORY_LIMIT_PHP="8000M"
/tags/v5.7-arrayanal/scripts/modules/osm/shell/extract-poly
New file
0,0 → 1,29
#!/bin/bash
# Utilisation : ./extract-poly fr-p.osm.pbf fr-14
# Paramètres : .
# - 1 : nom du fichier .pbf dont on veut extraire une portion avec un fichier .poly
# - 2 : nom du fichier .poly sans extenssion (l'extrait aura le même nom avec l'extenssion .pbf)
#
if [ -f config.cfg ] ; then
source config.cfg
echo $DATE;
else
echo "Veuillez paramétrer le script en renommant le fichier 'config.defaut.cfg' en 'config.cfg'."
exit;
fi
 
FICHIER_OSM=$1
FICHIER=$2
 
echo "Export de l'emplacement du binaire Java dans la variable d'environnement JAVACMD";
export JAVACMD="$CHEMIN_JAVA"
 
echo "Export de l'emplacement du dossier tmp pour Osmosis"
export JAVACMD_OPTIONS="-Djava.io.tmpdir=$OSMOSIS_DOSSIER_TMP -Xmx4G"
 
echo "Filtrage du fichier en cours ...";
$CHEMIN_OSMOSIS \
-v \
--read-pbf-fast "$DOSSIER_OSM/$FICHIER_OSM" workers=6 \
--bounding-polygon file="$DOSSIER_OSM/$FICHIER.poly" \
--write-pbf file="$DOSSIER_OSM/$FICHIER.pbf"
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/osm/shell/extract-communes
New file
0,0 → 1,34
#!/bin/bash
# Utilisation : ./extract-communes fr-14
# Paramètres : .
# - 1 : nom du fichier .pbf dont on veut extraire les communes (sans extenssion)
# Sortie : nom du fichier .pbf suffixé par "_new" et avec l'extenssion .osm
#
ageEnSeconde(){ expr `date +%s` - `stat -c %Y $1`; };
 
if [ -f config.cfg ] ; then
source config.cfg
echo $DATE;
else
echo "Veuillez paramétrer le script en renommant le fichier 'config.defaut.cfg' en 'config.cfg'."
exit;
fi
 
FICHIER=$1
 
echo "Export de l'emplacement du binaire Java dans la variable d'environnement JAVACMD";
export JAVACMD="$CHEMIN_JAVA"
 
echo "Export de l'emplacement du dossier tmp pour Osmosis"
export JAVACMD_OPTIONS="-Djava.io.tmpdir=$OSMOSIS_DOSSIER_TMP -Xmx4G"
 
echo "Filtrage du fichier en cours ...";
$CHEMIN_OSMOSIS \
-v \
--read-pbf-fast "$DOSSIER_OSM/$FICHIER.pbf" workers=6 \
--tf accept-relations admin_level=8 \
--tf accept-relations type=boundary \
--tf accept-relations ref:INSEE=* \
--used-way \
--used-node \
--wx "$DOSSIER_OSM/${FICHIER}_new.osm"
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/osm/shell/carto-osm-service
New file
0,0 → 1,41
#!/bin/sh
#/etc/rc.d/init.d/
#
# Jean-Pascal MILCENT & Mohcen BENMOUNAH [19 juillet 2011]
# Service de lancement des scripts d'integration des donnees OSM pour le service de Geocadage Inverse
#
case "$1" in
 
start)
 
echo "Demarrage de carto-osm-cron :"
nohup /usr/local/sbin/carto-osm-cron 1>/dev/null 2>/dev/null &
 
;;
 
stop)
 
echo "Arret de carto-osm-cron"
PID=`ps -eaf | grep carto-osm-cron | grep -v grep | tr -s ' ' | cut -d' ' -f2 | head -n1`
kill -9 ${PID}
 
;;
 
status)
 
echo -n "Voici les PID du processus carto-osm-cron :"
PID=`ps -eaf | grep carto-osm-cron | grep -v grep | tr -s ' ' | cut -d' ' -f2 | head -n1`
echo ${PID}
 
;;
 
 
*)
 
echo "Usage: {start|stop|status}"
 
exit 1
 
;;
 
esac
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/osm/shell/carto-osm-cron
New file
0,0 → 1,30
#!/bin/bash
#
# Mohcen BENMOUNAH & Jean-Pascal MILCENT [19 juillet 2011]
# /etc/init.d/carto-osm : demarage/arrete/etat du cron de l'integration des donnees OSM pour le Geocodage Inverse (carto-osm)
# Lancement toutes les semaines le samedi matin après 3h00
 
while true
do
JOUR=$(date "+%u")
# Si nous sommes samedi (=6)
if [ $JOUR -eq 6 ] ; then
HEURE=$(date "+%H")
# Si nous sommes à 3 heures du matin
if [ $HEURE -eq 3 ] ; then
logger "carto-osm-maj : lancement script"
sudo -u telabotap /usr/local/sbin/carto-osm-maj
logger "carto-osm-maj : arret script"
# Nous retenterons de vérifier jour et heure dans 6 jours
sleep 6d
else
# Tentative toutes les heures
logger "carto-osm-maj : tentative heure $HEURE"
sleep 1h
fi
else
# Tentative tous les jours
logger "carto-osm-maj : tentative jour $JOUR"
sleep 1d
fi
done
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/osm/shell
New file
Property changes:
Added: svn:ignore
+config.cfg
/tags/v5.7-arrayanal/scripts/modules/osm/PolygoneCreateur.php
New file
0,0 → 1,143
<?php
/**
* Traitement de l'ordre :
*
* Fonction qui rajoute l'ordre et le sens de chaque way d'une relation dans la table `osm_relation_a_chemins`
*
* Exemple de lancement du script :
* /opt/lampp/bin/php -d memory_limit=8000M cli.php osm -a ordre -m manuel
*
*/
class PolygoneCreateur {
private $conteneur;
private $bdd;
private $messages;
private $mode;
 
public function __construct($conteneur) {
$this->conteneur = $conteneur;
$this->bdd = $this->conteneur->getBdd();
$this->messages = $this->conteneur->getMessages();
$this->mode = $this->conteneur->getParametre('m');
}
 
/**
* Fonction qui parcourt tous les ways les noeuds de chaque relation en prenant en considération l'ordre et
* le sens de chaque ways concaténés ensemble (séparés par des virgules). Update du champ polygone de chaque
* relation dans la table `osm_relations`
*/
public function executer() {
// Lancement de l'action demandée
$cmd = $this->conteneur->getParametre('a');
switch ($cmd) {
case 'polygone' :
$this->genererPolygones();
break;
case 'centre' :
$this->mettreAJourCentroide();
break;
case 'zero' :
$this->remettreOrdreAZero();
break;
default :
$msgTpl = "Erreur : la commande '%s' n'est pas prise en compte par la classe %s !";
$msg = sprintf($msgTpl, $cmd, get_class($this));
throw new Exception($msg);
}
print "\n";// Pour ramener à la ligne en fin de script
}
 
private function genererPolygones() {
$relations = $this->getRelations();
foreach ($relations as $relation) {
$chemins = $this->getChemins($relation['id_relation']);
$noeuds = array();
foreach ($chemins as $chemin) {
$noeuds = array_merge($noeuds, $this->getNoeuds($chemin['id_chemin'], $chemin['sens']));
}
$this->creerPolygone($relation, $noeuds);
 
if ($this->mode == 'manuel') {
$this->messages->afficherAvancement("Création du polygone pour la relation : ", 1);
}
}
}
 
private function getRelations() {
$requete = 'SELECT id_relation, nom, code_insee '.
'FROM osm_relations '.
' -- '.__FILE__.' : '.__LINE__;
$relations = $this->bdd->recupererTous($requete);
return $relations;
}
 
private function getChemins($idRelation) {
$requete = 'SELECT id_chemin, sens '.
'FROM osm_relation_a_chemins '.
"WHERE id_relation = $idRelation ".
'ORDER BY ordre '.
' -- '.__FILE__.' : '.__LINE__;
$chemins = $this->bdd->recupererTous($requete);
return $chemins;
}
 
private function getNoeuds($idChemin, $sens) {
$tri = ($sens == 'directe') ? 'ASC' : 'DESC';
$requete = 'SELECT NLL.id_noeud, NLL.lat, NLL.`long` '.
'FROM osm_chemin_a_noeuds AS WN '.
' INNER JOIN osm_noeuds AS NLL ON (WN.id_noeud = NLL.id_noeud) '.
"WHERE WN.id_chemin = $idChemin ".
"ORDER BY WN.ordre $tri ".
' -- '.__FILE__.' : '.__LINE__;
$noeuds = $this->bdd->recupererTous($requete);
$latLng = array();
foreach ($noeuds as $noeud) {
$latLng[] = $noeud['lat'].' '.$noeud['long'];
}
return $latLng;
}
 
private function creerPolygone($relation, $noeuds) {
$polygone = implode(', ', $noeuds);
$idRelation = $relation['id_relation'];
$nomCommuneP = $this->bdd->proteger($relation['nom']);
$InseeP = $this->bdd->proteger($relation['code_insee']);
$note = ($noeuds[0] == $noeuds[count($noeuds) - 1]) ? 'Polygone complet' : 'Polygone incomplet';
 
$requete = 'REPLACE INTO osm_communes (id_relation, nom, code_insee, polygone, notes ) '.
"VALUES ($idRelation, $nomCommuneP, $InseeP, ".
"POLYFROMTEXT('MULTIPOLYGON ((($polygone)))'), '$note') ".
' -- '.__FILE__.' : '.__LINE__;
unset($polygone);
 
$this->bdd->requeter($requete);
}
 
/**
* Pour chaque commune, renseigne le champe "centre" avec un point centroïde du polygone (si non null).
*/
private function mettreAJourCentroide() {
$requete = 'UPDATE osm_communes '.
'SET centre = CENTROID(polygone) '.
"WHERE polygone IS NOT NULL ".
' -- '.__FILE__.' : '.__LINE__;
$retour = $this->bdd->requeter($requete);
$this->messages->traiterInfo("Nombre de centroïde mis à jour : ".$retour->rowCount());
}
 
/**
* Pour chaque commune, remet à zéro l'ordre des chemins si le polygone est incomplet.
*/
private function remettreOrdreAZero() {
$sousRequeteRelations = 'SELECT DISTINCT id_relation '.
'FROM osm_communes '.
"WHERE notes = 'Polygone incomplet' ";
 
$requete = 'UPDATE osm_relation_a_chemins '.
'SET ordre = NULL '.
"WHERE id_relation IN ($sousRequeteRelations) ".
' -- '.__FILE__.' : '.__LINE__;
$retour = $this->bdd->requeter($requete);
$this->messages->traiterInfo("Nombre de chemins remis à zéro : ".$retour->rowCount());
}
}
/tags/v5.7-arrayanal/scripts/modules/osm/PolygoneReparateur.php
New file
0,0 → 1,300
<?php
/**
* Réparation des polygones incomplets :
*
* Exemple de lancement du script :
* /opt/lampp/bin/php -d memory_limit=8000M cli.php osm -a ordonnerPolygoneInc -m manuel -v 3
*
* /opt/lampp/bin/php -d memory_limit=8000M cli.php osm -a remplirPolygoneInc -m manuel -v 3
*
* /opt/lampp/bin/php -d memory_limit=8000M cli.php osm -a renommer -m manuel -v 3
*
*/
class PolygoneReparateur {
private $conteneur;
private $bdd;
private $messages;
private $mode;
 
public function __construct($conteneur) {
$this->conteneur = $conteneur;
$this->bdd = $this->conteneur->getBdd();
$this->messages = $this->conteneur->getMessages();
$this->mode = $this->conteneur->getParametre('m');
}
 
/**
* Fonction qui parcourt tous les ways les noeuds de chaque relation en prenant en considération l'ordre et
* le sens de chaque ways concaténés ensemble (séparés par des virgules). Update du champ polygone de chaque
* relation dans la table `osm_relations`
*/
public function executer() {
// Lancement de l'action demandée
$cmd = $this->conteneur->getParametre('a');
switch ($cmd) {
case 'ordonnerPolygoneInc' :
$this->ordonnerRelationsAuPolygoneIncomplet();
break;
case 'remplirPolygoneInc' :
$this->remplirRelationsAuPolygoneIncomplet();
break;
case 'renommer' :
$this->renommerEnPolygoneIncomplet();
break;
default :
$msgTpl = "Erreur : la commande '%s' n'est pas prise en compte par la classe %s !";
$msg = sprintf($msgTpl, $cmd, get_class($this));
throw new Exception($msg);
}
print "\n";// Pour ramener à la ligne en fin de script
}
 
/**
* Fonction qui récupère les relations des polygones incomplets et appelle pour chaque relation la fonction
* ordonnerPolygoneIncomplet($ordre,$tour,$idRelation,$nombrePolygone)
*/
private function ordonnerRelationsAuPolygoneIncomplet() {
$relations = $this->getRelationsAuPolygoneIncomplet();
foreach ($relations as $relation) {
$idRelation = $relation['id_relation'];
$this->ordonnerCheminsMultiPolygone($idRelation);
 
if ($this->mode == 'manuel') {
$this->messages->afficherAvancement("Réparation du polygone incomplet : ", 1);
}
}
}
 
/**
* Fonction récursive qui exécute la même tâche que la fonction ordonnerWays() pour chaque polygone d'un
* multipolygone et remplie le champ NbPoly dans la table `osm_relation_a_chemins` qui correspond au nombre de polygone fermé
* dans le multipolygone
*/
private function ordonnerCheminsMultiPolygone($idRelation, $numPolygone = 1, $ordre = 1, $tour = 1) {
$chemins = $this->getChemins($idRelation);
$nbreCheminsTotal = count($chemins);
 
// premier élément du tableau
$idPremierChemin = $chemins[0]['id_chemin'];
$idChemin = $idPremierChemin;
 
$this->mettreAJourChemin($idRelation, $idPremierChemin, $ordre, 'directe', $numPolygone);
//selection dernier noeud
$nodes = $this->getNoeuds($idPremierChemin);
$nombreNodes = count($nodes);
$premierNoeud = $nodes[0]['id_noeud'];
$dernierNoeud = $nodes[$nombreNodes - 1]['id_noeud'];
$noeudActuel = $dernierNoeud;
 
//Condition pour laquelle la boucle while continue à tourner; tant que le premier noeud du polygone n'est
//égale au dernier et tant qu'il reste des ways à gérer
while (($premierNoeud != $noeudActuel) && (($ordre % 1000) < $nbreCheminsTotal)) {
//select le way qui possède le dernier noeud du précédent way et écarter l'actuel
$ordre++;
 
$chemins = $this->getCheminsAOrdonner($idRelation, $idChemin, $noeudActuel);
if (isset($chemins[0])) {
$idChemin = $chemins[0]['id_chemin'];
$nodes = $this->getNoeuds($idChemin);
$nombreNodes = count($nodes);
if (strcmp($nodes[0]['id_noeud'], $noeudActuel ) == 0) {
$sens = 'directe';
$noeudActuel = $nodes[$nombreNodes-1]['id_noeud'];
} else {
$sens = 'indirecte';
$noeudActuel = $nodes[0]['id_noeud'];
}
$this->mettreAJourChemin($idRelation, $idChemin, $ordre, $sens, $numPolygone);
}
}
$ordre = 1000 * $tour; //différencier chaque polygone: pour chaque polygone on a un multiple de mille
if ($this->getNombreChemins($idRelation) != 0) {
//appelle de la méthode récursivement
$this->ordonnerCheminsMultiPolygone($idRelation, ++$numPolygone, $ordre, ++$tour);
}
}
 
private function getRelationsAuPolygoneIncomplet() {
$requete = 'SELECT id_relation '.
'FROM osm_communes '.
"WHERE notes = 'Polygone incomplet' ".
' -- '.__FILE__.' : '.__LINE__;
$relations = $this->bdd->recupererTous($requete);
return $relations;
}
 
private function getChemins($idRelation) {
$requete = 'SELECT id_chemin '.
'FROM osm_relation_a_chemins '.
"WHERE id_relation = $idRelation ".
"AND ordre IS NULL ".
' -- '.__FILE__.' : '.__LINE__;
$chemins = $this->bdd->recupererTous($requete);
return $chemins;
}
/**
* Select des ways qui n'ont pas été ordonnés: on obtient à chaque itération les ways qui restent à ordonner
*/
private function getCheminsAOrdonner($idRelation, $idChemin, $idNoeud) {
$requete = 'SELECT cn.id_chemin '.
'FROM osm_relation_a_chemins AS rc '.
' INNER JOIN osm_chemin_a_noeuds AS cn ON (rc.id_chemin = cn.id_chemin) '.
"WHERE cn.id_noeud = $idNoeud ".
"AND cn.id_chemin != $idChemin ".
"AND rc.id_relation = $idRelation ".
"AND rc.ordre IS NULL ".
' -- '.__FILE__.' : '.__LINE__;
$chemins = $this->bdd->recupererTous($requete);
return $chemins;
}
 
private function getNoeuds($idChemin) {
$requete = 'SELECT id_noeud '.
'FROM osm_chemin_a_noeuds '.
"WHERE id_chemin = $idChemin ".
'ORDER BY ordre '.
' -- '.__FILE__.' : '.__LINE__;
$noeuds = $this->bdd->recupererTous($requete);
return $noeuds;
}
 
private function getNombreChemins($idRelation) {
$requete = 'SELECT COUNT(id_chemin) AS nbre '.
'FROM osm_relation_a_chemins '.
"WHERE id_relation = $idRelation ".
'AND ordre = 0 '.
' -- '.__FILE__.' : '.__LINE__;
$infos = $this->bdd->recuperer($requete);
return $infos['nbre'];
}
 
private function mettreAJourChemin($idRelation, $idChemin, $ordre, $sens, $nbrePoly) {
$requete = 'UPDATE osm_relation_a_chemins '.
"SET ordre = '$ordre', sens = '$sens', num_poly = $nbrePoly ".
"WHERE id_relation = $idRelation ".
"AND id_chemin = $idChemin ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
 
/**
* Fonction qui récupère les relations des polygones incomplets et appelle pour chaque relation la fonction
* remplirPolygoneIncomplet($idRelation);
*/
private function remplirRelationsAuPolygoneIncomplet() {
$relations = $this->getRelationsAuPolygoneIncomplet();
foreach ($relations as $relation) {
$this->remplirPolygoneIncomplet($relation['id_relation']);
if ($this->mode == 'manuel') {
$this->messages->afficherAvancement("Création du polygone incomplet : ", 1);
}
}
}
 
/**
* Fonction qui exécute la même tâche que la fonction remplirPolygone() pour chaque polygone d'un multipolygone
* et renvoie un tableau MultiPolygone[] où chaque case contient un polygone fermé. Puis met à jour le polygone
* de la commune.
*/
private function remplirPolygoneIncomplet($idRelation) {
// Tableau multipolygone qui contient tous les polygones d'un multipolygone
$multiPolygone = array();
// Tableau roles qui contient les différents roles des chemins de la relation
$roles = array();
// Sélectionner le nombre de polygones qui existe dans un multipolygone
$nbPoly = $this->getNombrePoly($idRelation);
//boucle for qui parcourt chaque polygone du multipolygone
for ($numPoly = 1; $numPoly <= $nbPoly; $numPoly++) {
$polygone = array();
$chemins = $this->getCheminsParPolygone($idRelation, $numPoly);
foreach ($chemins as $chemin) {
$role = $chemin['role'];
$roles[$role] = (isset($roles[$role])) ? $roles[$role]++ : 1;
$noeuds = $this->getNoeudsPourCheminEtSens($chemin['id_chemin'], $chemin['sens']);
$polygone = array_merge($polygone, $noeuds);
}
$multiPolygone[] = implode(', ', $polygone);
}
$this->mettreAJourMultiPolygone($multiPolygone, $roles, $idRelation, $nbPoly);
}
 
private function getNombrePoly($idRelation) {
$requete = 'SELECT MAX(num_poly) AS num_poly '.
'FROM osm_relation_a_chemins '.
"WHERE id_relation = $idRelation ".
' -- '.__FILE__.' : '.__LINE__;
$resultat = $this->bdd->recuperer($requete);
return $resultat['num_poly'];
}
 
private function getCheminsParPolygone($idRelation, $numPoly) {
$requete = 'SELECT id_chemin, sens, role '.
'FROM osm_relation_a_chemins '.
"WHERE id_relation = $idRelation ".
"AND num_poly = $numPoly ".
'ORDER BY ordre '.
' -- '.__FILE__.' : '.__LINE__;
$chemins = $this->bdd->recupererTous($requete);
return $chemins;
}
 
private function getNoeudsPourCheminEtSens($idChemin, $sens) {
$tri = ($sens == 'directe') ? 'ASC' : 'DESC';
$requete = 'SELECT NLL.id_noeud, NLL.lat, NLL.`long` '.
'FROM osm_chemin_a_noeuds AS WN '.
' INNER JOIN osm_noeuds AS NLL ON (WN.id_noeud = NLL.id_noeud) '.
"WHERE WN.id_chemin = $idChemin ".
"ORDER BY WN.ordre $tri ".
' -- '.__FILE__.' : '.__LINE__;
$noeuds = $this->bdd->recupererTous($requete);
$latLng = array();
foreach ($noeuds as $noeud) {
$latLng[] = $noeud['lat'].' '.$noeud['long'];
}
return $latLng;
}
 
/**
* Remplie le champ polygone à partir du tableau MultiPolygone
*/
private function mettreAJourMultiPolygone($multiPolygone, $roles, $idRelation, $nbPoly) {
// Présence d'une enclave contenue dans cette entité administrative mais qui appartient à une autre entité administrative
if ((isset($roles['inner']) || isset($roles['enclave']))) {
if ($nbPoly == 2) {
$multiPoly = implode('),(', $multiPolygone);
} else {
$multiPoly = null;
$msgTpl = "La relation '%s' possède plus de 2 polygones de type enclaves.";
$this->messages->traiterErreur($msgTpl, array($idRelation));
}
} else {
// Tous les autres cas
$multiPoly = implode(')),((', $multiPolygone);
}
if (isset($multiPoly)) {
$this->mettreAJourCommune($idRelation, $multiPoly);
}
}
 
private function mettreAJourCommune($idRelation, $multiPoly) {
$requete = 'UPDATE osm_communes '.
"SET polygone = MPOLYFROMTEXT('MULTIPOLYGON((($multiPoly)))'), ".
"notes = 'Polygone complet' ".
"WHERE id_relation = $idRelation ".
' -- '.__FILE__.' : '.__LINE__;
$this->bdd->requeter($requete);
}
 
/**
* Renomme la note des polygones vides d'un polygone complet en polygone incomplet
*/
private function renommerEnPolygoneIncomplet() {
$requete = 'UPDATE osm_communes '.
"SET notes = 'Polygone incomplet' ".
"WHERE ASTEXT(polygone) IS NULL ".
' -- '.__FILE__.' : '.__LINE__;
 
$retour = $this->bdd->requeter($requete);
$this->messages->traiterInfo("Nombre de polygones définis à incomplet : ".$retour->rowCount());
}
}
/tags/v5.7-arrayanal/scripts/modules/osm
New file
Property changes:
Added: svn:ignore
+.config.ini.swp
/tags/v5.7-arrayanal/scripts/modules/apd/Apd.php
New file
0,0 → 1,719
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php apd -a chargerTous
*
* Base de données des Trachéophytes (trachéo...quoi ?? C'est le truc avec le stylo Bic ?)
* d'Afrique de l'Ouest (et Centrale mais faut pas le dire)
*
* @category php 5.2
* @package eFlore/Scripts
* @author Mathias CHOUET <mathias@tela-botanica.org>
* @copyright Copyright (c) 2014, 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
*/
class Apd extends EfloreScript {
 
private $table = null;
private $tableMeta = null;
private $pasInsertion = 1000;
private $departInsertion = 0;
 
protected $parametres_autorises = array();
 
// Entêtes du nouveau fichier Rtax à produire
protected $entetesRtax = array("num_nom","num_nom_retenu","num_tax_sup","rang","nom_sci",
"nom_supra_generique","genre","epithete_infra_generique","epithete_sp",
"type_epithete","epithete_infra_sp","cultivar_groupe","cultivar","nom_commercial",
"auteur","annee","biblio_origine","notes","nom_addendum","homonyme","num_type",
"num_basionyme","synonyme_proparte","synonyme_douteux","synonyme_mal_applique",
"synonyme_orthographique","orthographe_originelle","hybride_parent_01",
"hybride_parent_01_notes","hybride_parent_02","hybride_parent_02_notes",
"nom_francais","presence","statut_origine ","statut_introduction","statut_culture","exclure_taxref");
 
public function initialiserProjet($projetNom) {
parent::initialiserProjet($projetNom);
$this->table = Config::get("apd");
$this->tableMeta = Config::get("apdMeta");
}
 
public function executer() {
try {
$this->initialiserProjet('apd');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'tout' :
$ok = $this->productionCsvPourReferentiels();
if ($ok === true) {
$this->integrationEFlore();
}
break;
case 'ref' : // partie 1 : "referentiels"
$this->productionCsvPourReferentiels();
break;
case 'eflore' : // partie 2 : "eFlore"
$this->integrationEFlore();
break;
case 'nettoyage' :
$this->nettoyage();
break;
case 'chargerStructureSql' :
//$this->creerStructure();
$this->chargerStructureSql();
break;
case 'verifierEtGenererCsvRtax' :
$this->verifierEtGenererCsvRtax();
break;
case 'chargerCsvRtax' :
$this->chargerCsvRtax();
break;
case 'changerRangs' :
$this->changerRangs();
break;
case 'completerNumNomRetenu' :
$this->completerNumNomRetenu();
break;
case 'supprimerNumTaxSupPourSynonymes' :
$this->supprimerNumTaxSupPourSynonymes();
break;
case 'subspAutonymes' :
$this->subspAutonymes();
break;
case 'genererNomSupraGenerique' :
$this->genererNomSupraGenerique();
break;
case 'genererEpitheteInfraGenerique' :
$this->genererEpitheteInfraGenerique();
break;
case 'exporterCSVModifie' :
$this->exporterCSVModifie();
break;
case 'genererChpNumTax' :
$this->genererChpNumTax();
break;
case 'genererNomSciHtml' :
$this->genererChpNomSciHtml();
break;
case 'genererChpNomComplet' :
$this->genererChpNomComplet();
break;
case 'genererChpFamille' :
$this->genererChpFamille();
break;
case 'genererChpHierarchie' :
$this->genererChpHierarchie();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
// Lance la première moitié du boulot, et s'arrête lorsque le fichier CSV
// au format Rtax est rempli avec les données amendées - il est prêt à rentrer dans Rtxß.
// Retourne true si tout s'est bien passé, false sinon
protected function productionCsvPourReferentiels() {
$retour = false;
$this->nettoyage();
$this->chargerStructureSql();
$verifOk = $this->verifierEtGenererCsvRtax();
if ($verifOk === true) {
$chgtOk = $this->chargerCsvRtax();
if ($chgtOk) {
$this->changerRangs();
$this->completerNumNomRetenu();
$this->supprimerNumTaxSupPourSynonymes();
$this->subspAutonymes();
$this->genererNomSupraGenerique();
$this->genererEpitheteInfraGenerique();
$this->exporterCSVModifie();
$retour = true;
}
}
return $retour;
}
 
// Lance la seconde moitié du boulot, et s'arrête lorsque le référentiel
// est inséré dans la base eFlore.
// Retourne true si tout s'est bien passé, false sinon
protected function integrationEFlore() {
$retour = false;
$this->genererChpNumTax();
$this->genererChpNomSciHtml();
$this->genererChpFamille();
$this->genererChpNomComplet();
$this->genererChpHierarchie();
$retour = true;
return $retour;
}
 
// -------------- partie Rtax -------------
 
// Dézingue tout le bousin
protected function nettoyage() {
echo "---- suppression des tables\n";
$req = "DROP TABLE IF EXISTS `" . $this->table . "`";
$this->getBdd()->requeter($req);
$req = "DROP TABLE IF EXISTS `" . $this->tableMeta . "`;";
$this->getBdd()->requeter($req);
}
 
// Analyse le fichier CSV fourni par le CJBG, le vérifie et écrit un CSV minimal au format Rtax
function verifierEtGenererCsvRtax() {
$cheminCsvRtax = Config::get('chemins.csvRtax');
$cheminCsvCjbg = Config::get('chemins.csvCjbg');
$retour = false;
echo "---- vérification CSV CJBG [$cheminCsvCjbg] et génération CSV Rtax\n";
 
// Correspondances de colonnes pour le remplissage à minima du fichier CSV Rtax
// Clefs: CJBG
// Valeurs: Rtax
$entetesCjbgVersRtax = array(
"id_name" => "num_nom",
"presence" => "presence",
"statut_introduction" => "statut_introduction",
"statut_origine" => "statut_origine",
"nom_addendum" => "nom_addendum",
"BASIONYME" => "num_basyonyme",
"NO_RANG" => "rang",
"auteur" => "auteur",
"ANNEE" => "annee",
"type_epithete" => "type_epithete",
"SYN_mal_applique" => "synonyme_mal_applique",
"nom_sci" => "nom_sci",
"num_tax_sup" => "num_tax_sup",
"num_nom_retenu" => "num_nom_retenu",
"genre" => "genre",
"NOTES" => "notes",
"epithete_sp" => "epithete_sp",
"epithete_infra_sp" => "epithete_infra_sp",
// champs additionnels
"NOM_STANDARD2" => false,
"STATUT_SYN" => false, // @TODO convertir
"hybride_parents" => false, // toujours "x" => ??
"FAM APG3" => false,
"auth_genre" => false,
"auth_esp" => false
);
 
$analyseOK = true;
$numLigne = 1;
$idNames = array();
// lecture CSV d'origine
$csv = fopen($cheminCsvCjbg, "r");
$donneesTransformees = array();
if ($csv) {
$entetes = fgetcsv($csv);
//echo "Entetes: " . print_r($entetes, true) . "\n";
while(($ligne = fgetcsv($csv)) !== false) {
$numLigne++;
$nouvelleLigne = array();
if (isset($idNames[$ligne[0]])) {
echo "Entrée dupliquée pour id_name [" . $ligne[0] . "]\n";
$analyseOK = false;
} else if (! is_numeric($ligne[0])) {
echo "Ligne $numLigne : la clef [" . $ligne[0] . "] n'est pas un entier\n";
$analyseOK = false;
} else if ($ligne[0] == 0) {
echo "Ligne $numLigne : la clef [" . $ligne[0] . "] vaut zéro\n";
$analyseOK = false;
} else {
$idNames[$ligne[0]] = $ligne[13]; // stockage du nom retenu
foreach ($ligne as $idx => $col) {
$entete = $entetes[$idx];
$ert = $entetesCjbgVersRtax[$entete];
if (strpos($col, "\n") > -1) {
echo "Info: la colonne $ert de la ligne $numLigne contient des retours chariot. Conversion en espaces.\n";
$col = str_replace("\n", " ", $col);
}
$nouvelleLigne[$ert] = $col;
}
$donneesTransformees[] = $nouvelleLigne;
}
}
} else {
echo "Erreur lors de l'ouverture du fichier\n";
}
 
// Vérifications:
// - existence des num_nom_retenu et num_tax_sup mentionnés
// - réduction des chaînes de synonymie
$nnrManquants = array();
$ntsManquants = array();
$chaineSyn = array();
foreach ($donneesTransformees as $ligne) {
$taxSup = $ligne['num_tax_sup'];
$nomRet = $ligne['num_nom_retenu'];
$numNom = $ligne['num_nom'];
// Si un nom est retenu, son taxon supérieur doit être mentionné et exister
if (($numNom == $nomRet) && $taxSup && (! isset($idNames[$taxSup])) && (! isset($ntsManquants[$taxSup]))) {
$ntsManquants[$taxSup] = true;
}
// Si un nom retenu est mentionné, il doit exister et être un nom retenu
if ($nomRet) {
if (isset($idNames[$nomRet])) {
/*$nrnr = $idNames[$nomRet];
echo "Test pour nn $numNom, nr $nomRet, " . $nrnr . "\n";
if ($nomRet && $nrnr != $nomRet) {
if (! isset($chaineSyn[$nomRet])) {
$chaineSyn[$nomRet] = true;
}
}*/
} else {
if (! isset($nnrManquants[$nomRet])) {
$nnrManquants[$nomRet] = true;
}
}
}
}
if (count($nnrManquants) > 0) {
echo count($nnrManquants) . " Nom(s) retenu(s) absent(s):\n";
echo "(" . implode(",", array_keys($nnrManquants)) . ")\n";
}
if (count($ntsManquants) > 0) {
echo count($ntsManquants) . " Taxon(s) supérieur(s) absent(s):\n";
echo "(" . implode(",", array_keys($ntsManquants)) . ")\n";
}
/*if (count($chaineSyn) > 0) {
echo count($chaineSyn) . " Synonymes ne sont pas des noms retenus:\n";
//echo "(" . implode(",", array_keys($chaineSyn)) . ")\n";
}*/
 
if ($analyseOK === true) {
// Production CSV de destination
$csvDestination = '';
$csvDestination .= implode($this->entetesRtax, ',') . "\n";
$tailleLigne = count($this->entetesRtax);
foreach ($donneesTransformees as $dt) {
//$ligne = array();
$ligneCsv = '';
$i = 0;
foreach ($this->entetesRtax as $e) {
/*if (isset($dt[$e])) {
$ligne[] = $dt[$e];
} else {
$ligne[] = '';
}*/
if (isset($dt[$e]) && ($dt[$e] !== '')) {
$ligneCsv .= '"' . $dt[$e] . '"';
}
if ($i < $tailleLigne) {
$ligneCsv .= ',';
}
$i++;
}
$ligneCsv .= "\n";
//$ligneCsv = '"' . implode($ligne, '","') . '"' . "\n"; // met des double guillemets sur les champs vides et /i
$csvDestination .= $ligneCsv;
}
// @TODO créer le répertoire dans /tmp et donner les droits 777
file_put_contents($cheminCsvRtax, $csvDestination);
$retour = true;
} else {
echo "L'analyse a mis en évidence des erreurs. Interruption.\n";
}
 
return $retour;
}
 
// Charge le CSV minimal au format TexRaf
protected function chargerCsvRtax() {
$cheminCsvRtax = Config::get('chemins.csvRtax');
echo "---- chargement du fichier CSV Rtax [$cheminCsvRtax]\n";
$req = "LOAD DATA INFILE '" . $cheminCsvRtax . "' INTO TABLE " . $this->table
. " FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES";
$retour = $this->getBdd()->requeter($req);
return $retour;
}
 
// Convertit les rangs du format chaispasquoi au format RexTaf
protected function changerRangs() {
echo "---- conversion des rangs\n";
$rangs = array(
"0" => "10",
"1" => "20",
"2" => "50",
"3" => "53",
"4" => "80",
"5" => "140",
"6" => "180",
"7" => "190",
"8" => "200",
"9" => "220",
"10" => "230",
"11" => "240",
"12" => "250",
"13" => "260",
"14" => "280",
"15" => "290",
"16" => "320",
"17" => "340",
"18" => "350",
"19" => "360",
"20" => "370",
"26" => "440"
);
foreach ($rangs as $src => $dest) {
echo "rang $src => rang $dest\n";
$req = "UPDATE " . $this->table . " SET rang=$dest WHERE rang=$src;";
$this->getBdd()->requeter($req);
}
}
 
// Copie num_nom dans num_nom_retenu lorsque ce dernier est vide
protected function completerNumNomRetenu() {
echo "---- complétion des num_nom_retenu\n";
$req = "UPDATE " . $this->table . " SET num_nom_retenu = num_nom WHERE num_nom_retenu='';";
$this->getBdd()->requeter($req);
}
 
// Supprime le num_tax_sup pour les synonymes
// et le met à 1 s'il est égal au num_nom
protected function supprimerNumTaxSupPourSynonymes() {
echo "---- suppression de num_tax_sup pour les synonymes et mise à 1 si égal à num_nom\n";
$req = "UPDATE " . $this->table . " SET num_tax_sup = '' WHERE num_nom != num_nom_retenu;";
$this->getBdd()->requeter($req);
$req = "UPDATE " . $this->table . " SET num_tax_sup = 1 WHERE num_nom = num_tax_sup;";
$this->getBdd()->requeter($req);
}
 
// Pour chaque subsp. autonyme, inscrit l'epithete_infra_sp
protected function subspAutonymes() {
echo "---- inscription de l'épithète infraspécifique des subsp. autonymes\n";
$req = "SELECT num_nom, nom_sci, epithete_infra_sp FROM " . $this->table . " WHERE nom_sci LIKE '%subsp.%'";
$res = $this->getBdd()->recupererTous($req);
 
$nbres = count($res);
$cpt = 0;
$ok = 0;
$ids = array();
foreach ($res as $subsp) {
$ns = $subsp['nom_sci'];
$pos = strpos($ns, 'subsp.');
$gsp = substr($ns, 0, $pos - 1);
$sp = substr($gsp, strrpos($gsp, ' ') + 1);
$sub = substr($ns, $pos + 8);
if ($sub == $sp) {
$cpt++;
// @TODO
// 1) récupérer l'auteur
// 2) intégrer l'auteur avant "subsp." dans le nom_sci
//echo "[$sp] || [$sub] || [" . $subsp['epithete_infra_sp'] . "]\n";
if ($sub == $subsp['epithete_infra_sp']) {
$ok++;
} else {
$reqMod = "UPDATE " . $this->table . " SET epithete_infra_sp='"
. $sub . "' WHERE num_nom=" . $subsp['num_nom'];
$this->getBdd()->requeter($reqMod);
}
}
}
echo "subsp.: $nbres\n";
echo "Autonymes: $cpt dont $ok déjà inscrites\n";
}
 
// Copie le nom scientifique dans le nom supra générique pour les taxons de rang
// supérieur au genre
protected function genererNomSupraGenerique() {
echo "---- complétion des noms supragénériques\n";
$req = "UPDATE " . $this->table . " SET nom_supra_generique = nom_sci WHERE rang < 220";
$res = $this->getBdd()->requeter($req);
}
 
// Copie le nom scientifique dans l'épithète infra générique pour les taxons de rang
// entre genre et espèce
protected function genererEpitheteInfraGenerique() {
echo "---- complétion des épithètes infragénériques\n";
$req = "UPDATE " . $this->table . " SET epithete_infra_generique = nom_sci WHERE rang > 220 AND rang < 290";
$res = $this->getBdd()->requeter($req);
}
 
protected function exporterCSVModifie() {
$cheminFichierCsvRtaxModifie = Config::get('chemins.csvRtaxModifie');
echo "---- export du CSV Rtax modifié [$cheminFichierCsvRtaxModifie]\n";
if (file_exists($cheminFichierCsvRtaxModifie)) {
unlink($cheminFichierCsvRtaxModifie);
}
$req = "SELECT '" . implode("','", $this->entetesRtax) . "'"
. " UNION ALL "
. " SELECT * FROM " . $this->table . " INTO OUTFILE '" . $cheminFichierCsvRtaxModifie . "'"
. " FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n'";
$res = $this->getBdd()->requeter($req);
// Remplacement des cases vides par '' aulieu de '""' (peut faire foirer l'import par la suite)
exec("sed -i 's/\"\"//g' " . $cheminFichierCsvRtaxModifie);
}
 
// -------------- partie eFlore ------------- copiée depuis le script Bdtfx
 
private function genererChpNomSciHtml() {
echo "---- génération des noms scientifiques en HTML \n";
$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");
}
echo "\n";
 
if (count($erreurs) > 0) {
echo 'Erreurs lors de la génération HTML des noms scientifiques:\n' . print_r($erreurs, true) . "\n";
}
}
 
private function preparerTablePrChpNomSciHtml() {
echo "---- ajout de la colonne nom_sci_html \n";
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD nom_sci_html VARCHAR( 500 ) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function recupererNbTotalTuples(){
$requete = "SELECT count(*) AS nb FROM {$this->table} ";
$resultat = $this->getBdd()->recuperer($requete);
return $resultat['nb'];
}
 
private function recupererTuplesPrChpNomSciHtml() {
$requete = 'SELECT num_nom, rang, nom_sci, nom_supra_generique, genre, epithete_infra_generique, '.
' epithete_sp, type_epithete, epithete_infra_sp,cultivar_groupe, '.
' nom_commercial, cultivar '.
"FROM {$this->table} ".
"LIMIT {$this->departInsertion},{$this->pasInsertion} ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function remplirChpNomSciHtm($nomsSciHtm) {
foreach ($nomsSciHtm as $id => $html) {
$html = $this->getBdd()->proteger($html);
$requete = "UPDATE {$this->table} SET nom_sci_html = $html WHERE num_nom = $id ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $id");
}
}
}
 
// Attention c'est over-lent !
private function genererChpNumTax() {
$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";
if (count($erreurs) > 0) {
echo 'Erreurs lors de la génération des numéros taxonomiques' . print_r($erreurs, true) . "\n";
}
}
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 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 :\n";
$requete = "UPDATE {$this->table} SET nom_complet = CONCAT(nom_sci,' ',auteur)";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
echo "Erreur de génération du champ nom complet\n";
} else {
echo "OK\n";
}
}
 
private function genererChpFamille() {
$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");
}
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";
 
if (count($introuvables) > 0) {
echo count($introuvables) . ' familles sont introuvables : ' . implode(',', $introuvables) . "\n";
}
$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->preparerTablePrChpHierarchie();
$table = Config::get('tables.isfan');
$requete = "UPDATE {$this->table} SET hierarchie = NULL ";
$mise_a_jour = $this->getBdd()->requeter($requete);
$requete_hierarchie = "SELECT num_nom, num_nom_retenu, num_tax_sup FROM " . $this->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 {$this->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);
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/apd/apd.ini
New file
0,0 → 1,18
version="3_4_0"
dossierapd = "{ref:dossierDonneesEflore}apd/{ref:version}/"
 
[tables]
apdMeta = "apd_meta"
apd = "apd_v{ref:version}"
 
[fichiers]
structureSql = "apd_v{ref:version}.sql"
csvCjbg = "apd_v{ref:version}.csv"
csvRtax = "apd_v{ref:version}_rtax.csv"
csvRtaxModifie = "apd_v{ref:version}_rtax_modifie.csv"
 
[chemins]
structureSql = "{ref:dossierapd}{ref:fichiers.structureSql}"
csvCjbg = "{ref:dossierapd}{ref:fichiers.csvCjbg}"
csvRtax = "{ref:dossierapd}{ref:fichiers.csvRtax}"
csvRtaxModifie = "{ref:dossierapd}{ref:fichiers.csvRtaxModifie}"
/tags/v5.7-arrayanal/scripts/modules/biblio_bota/BiblioBota.php
New file
0,0 → 1,70
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php cel -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class BiblioBota extends EfloreScript {
 
public function executer() {
try {
$this->initialiserProjet('biblio_bota');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerBiblioBota();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
public function chargerBiblioBota() {
$tablesCodes = array_keys(Config::get('tables'));
foreach ($tablesCodes as $code) {
echo "Chargement de la table : $code\n";
$this->chargerFichierTsvDansTable($code);
}
}
 
private function chargerFichierTsvDansTable($code) {
$chemin = Config::get('chemins.'.$code);
$table = Config::get('tables.'.$code);
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ";
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS biblio_article, biblio_article_sauv, biblio_aut_saisie, ".
"biblio_collection, biblio_domaine, biblio_domaine_lier, biblio_domaine_lier_sauv, biblio_fasc, ".
"biblio_fasc_sauv, biblio_item, biblio_item_sauv, biblio_item_typlog, biblio_item_typphy, ".
"biblio_link, biblio_link_categ, biblio_link_categoriser, biblio_link_sauv, biblio_media, ".
"biblio_modif, biblio_serie, biblio_spy, biblio_str, biblio_str_sauve, biblio_str_type, ".
"biblio_meta";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/biblio_bota/biblio_bota.ini
New file
0,0 → 1,84
version="2009-10-05"
dossierTsv = "{ref:dossierDonneesEflore}biblio_bota/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
prefixe = "biblio_"
 
[tables]
article = "{ref:prefixe}article"
article_sauv = "{ref:prefixe}article_sauv"
aut_saisie = "{ref:prefixe}aut_saisie"
collection = "{ref:prefixe}collection"
domaine = "{ref:prefixe}domaine"
domaine_lier = "{ref:prefixe}domaine_lier"
domaine_lier_sauv = "{ref:prefixe}domaine_lier_sauv"
fasc = "{ref:prefixe}fasc"
fasc_sauv = "{ref:prefixe}fasc_sauv"
item = "{ref:prefixe}item"
item_sauv = "{ref:prefixe}item_sauv"
item_typlog = "{ref:prefixe}item_typlog"
item_typphy = "{ref:prefixe}item_typphy"
link = "{ref:prefixe}link"
link_categ = "{ref:prefixe}link_categ"
link_categoriser = "{ref:prefixe}link_categoriser"
link_sauv = "{ref:prefixe}link_sauv"
media = "{ref:prefixe}media"
modif = "{ref:prefixe}modif"
serie = "{ref:prefixe}serie"
spy = "{ref:prefixe}spy"
str = "{ref:prefixe}str"
str_sauve = "{ref:prefixe}str_sauve"
str_type = "{ref:prefixe}str_type"
 
[fichiers]
structureSql = "biblio_bota.sql"
article = "{ref:prefixe}article.tsv"
article_sauv = "{ref:prefixe}article_sauv.tsv"
aut_saisie = "{ref:prefixe}aut_saisie.tsv"
collection = "{ref:prefixe}collection.tsv"
domaine = "{ref:prefixe}domaine.tsv"
domaine_lier = "{ref:prefixe}domaine_lier.tsv"
domaine_lier_sauv = "{ref:prefixe}domaine_lier_sauv.tsv"
fasc = "{ref:prefixe}fasc.tsv"
fasc_sauv = "{ref:prefixe}fasc_sauv.tsv"
item = "{ref:prefixe}item.tsv"
item_sauv = "{ref:prefixe}item_sauv.tsv"
item_typlog = "{ref:prefixe}item_typlog.tsv"
item_typphy = "{ref:prefixe}item_typphy.tsv"
link = "{ref:prefixe}link.tsv"
link_categ = "{ref:prefixe}link_categ.tsv"
link_categoriser = "{ref:prefixe}link_categoriser.tsv"
link_sauv = "{ref:prefixe}link_sauv.tsv"
media = "{ref:prefixe}media.tsv"
modif = "{ref:prefixe}modif.tsv"
serie = "{ref:prefixe}serie.tsv"
spy = "{ref:prefixe}spy.tsv"
str = "{ref:prefixe}str.tsv"
str_sauve = "{ref:prefixe}str_sauve.tsv"
str_type = "{ref:prefixe}str_type.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
article = "{ref:dossierSql}{ref:fichiers.article}"
article_sauv = "{ref:dossierSql}{ref:fichiers.article_sauv}"
aut_saisie = "{ref:dossierSql}{ref:fichiers.aut_saisie}"
collection = "{ref:dossierSql}{ref:fichiers.collection}"
domaine = "{ref:dossierSql}{ref:fichiers.domaine}"
domaine_lier = "{ref:dossierSql}{ref:fichiers.domaine_lier}"
domaine_lier_sauv = "{ref:dossierSql}{ref:fichiers.domaine_lier_sauv}"
fasc = "{ref:dossierSql}{ref:fichiers.fasc}"
fasc_sauv = "{ref:dossierSql}{ref:fichiers.fasc_sauv}"
item = "{ref:dossierSql}{ref:fichiers.item}"
item_sauv = "{ref:dossierSql}{ref:fichiers.item_sauv}"
item_typlog = "{ref:dossierSql}{ref:fichiers.item_typlog}"
item_typphy = "{ref:dossierSql}{ref:fichiers.item_typphy}"
link = "{ref:dossierSql}{ref:fichiers.link}"
link_categ = "{ref:dossierSql}{ref:fichiers.link_categ}"
link_categoriser = "{ref:dossierSql}{ref:fichiers.link_categoriser}"
link_sauv = "{ref:dossierSql}{ref:fichiers.link_sauv}"
media = "{ref:dossierSql}{ref:fichiers.media}"
modif = "{ref:dossierSql}{ref:fichiers.modif}"
serie = "{ref:dossierSql}{ref:fichiers.serie}"
spy = "{ref:dossierSql}{ref:fichiers.spy}"
str = "{ref:dossierSql}{ref:fichiers.str}"
str_sauve = "{ref:dossierSql}{ref:fichiers.str_sauve}"
str_type = "{ref:dossierSql}{ref:fichiers.str_type}"
/tags/v5.7-arrayanal/scripts/modules/wikipedia/wikipedia.ini
New file
0,0 → 1,21
version="2011"
dossierDonnees = "{ref:dossierDonneesEflore}wikipedia/"
 
[dossiers]
structure = "{ref:dossierDonnees}"
meta = "{ref:dossierDonnees}"
communes = "{ref:dossierDonnees}communes/2011-05-13/"
[tables]
wikipediaMeta = "wikipedia_meta"
wikipediaCommunes = "wikipedia_communes_v{ref:version}"
 
[fichiers]
structureSql = "wikipedia.sql"
wikipediaMeta = "wikipedia_meta.sql"
wikipediaCommunes = "communes_tom_com_v2011.csv"
 
[chemins]
structureSql = "{ref:dossiers.structure}{ref:fichiers.structureSql}"
wikipediaMeta = "{ref:dossiers.meta}{ref:fichiers.wikipediaMeta}"
wikipediaCommunes = "{ref:dossiers.communes}{ref:fichiers.wikipediaCommunes}"
/tags/v5.7-arrayanal/scripts/modules/wikipedia/Wikipedia.php
New file
0,0 → 1,115
<?php
//declare(encoding='UTF-8');
/**
* Classe permettant de :
* - rajouter l'objet point centroide de la commune.
* - charger la bdd
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php wikipedia -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Mohcen BENMOUNAH <mohcen@tela-botanica.org>
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Wikipedia extends EfloreScript {
private $tableMeta = '';
private $cheminFichierMeta = '';
private $tableCommunes = '';
private $cheminFichierCommunes = '';
 
public function executer() {
try {
$this->initialiserProjet('wikipedia');
$this->tableMeta = Config::get('tables.wikipediaMeta');
$this->cheminFichierMeta = Config::get('chemins.wikipediaMeta');
$this->tableCommunes = Config::get('tables.wikipediaCommunes');
$this->cheminFichierCommunes = Config::get('chemins.wikipediaCommunes');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerMetaDonnees();
$this->chargerWikipediaCommunes();
$this->preparerTable();
$this->recupererPoints();
case 'points' :
$this->preparerTable();
$this->recupererPoints();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
protected function chargerMetaDonnees() {
$contenuSql = $this->recupererContenu($this->cheminFichierMeta);
$this->executerScripSql($contenuSql);
}
 
private function chargerWikipediaCommunes() {
$requete = "LOAD DATA INFILE '{$this->cheminFichierCommunes}' ".
"REPLACE INTO TABLE {$this->tableCommunes} ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY ',' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function preparerTable() {
$requete = "ALTER TABLE {$this->tableCommunes} ".
'DROP centroide ';
$this->getBdd()->requeter($requete);
 
$requete = "ALTER TABLE {$this->tableCommunes} ".
' ADD centroide point NOT NULL ';
$this->getBdd()->requeter($requete);
 
$requete = "ALTER TABLE {$this->tableCommunes} ".
' ADD INDEX (centroide) ';
$this->getBdd()->requeter($requete);
}
 
private function recupererPoints() {
$requete = 'SELECT * '.
"FROM {$this->tableCommunes} ";
$LatLons = $this->getBdd()->recupererTous($requete);
 
foreach ($LatLons as $LatLon) {
$latitude_degre = $LatLon['latitude'];
$longitude_degre = $LatLon['longitude'];
$insee = $LatLon['code_insee'];
$this->formerPointCentre($latitude_degre, $longitude_degre, $insee);
$this->afficherAvancement('Analyse des communes Wikipedia');
}
}
 
private function formerPointCentre($latitude_degre, $longitude_degre, $insee) {
$centre = "$latitude_degre $longitude_degre";
$requete = "UPDATE {$this->tableCommunes} ".
"SET centroide = POINTFROMTEXT('POINT($centre)') ".
"WHERE code_insee = $insee ";
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS {$this->tableMeta}, {$this->tableCommunes}";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/baseveg/Baseveg.php
New file
0,0 → 1,111
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php baseveg -a chargerTous
*/
 
class Baseveg extends EfloreScript {
 
 
 
 
public function executer() {
try {
$this->initialiserProjet('baseveg');
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'supprimerTous' :
$this->supprimerTous();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerMetadonnees' :
$this->chargerMetadonnees();
break;
case 'chargerDonnees' :
$this->chargerDonnees();
break;
case 'verifierFichier' :
//cette étape met en avant les valeurs qui vont poser des problèmes (ontologies..)
$this->verifierFichier();
break;
case 'supprimerOntologies' :
$this->supprimerOntologies();
break;
case 'chargerOntologies' :
$this->chargerOntologies();
break;
case 'chargerTous' :
$this->supprimerTous();
$this->chargerStructureSql();
$this->chargerMetadonnees();
$this->chargerDonnees();
$this->chargerOntologies();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
private function getClasseBasevegVerif() {
$conteneur = new Conteneur();
require_once dirname(__FILE__)."/BasevegVerif.php";
$verif = new BasevegVerif($conteneur,'baseveg');
return $verif;
}
private function verifierFichier() {
$verif = $this->getClasseBasevegVerif();
$verif->verifierFichier(Config::get('chemins.donnees'));
}
private function supprimerOntologies() {
$chemin = Config::get('chemins.ontologies');
$table = Config::get('tables.ontologies');
$requete = "TRUNCATE TABLE $table ;";
$this->getBdd()->requeter($requete);
}
private function chargerOntologies() {
$chemin = Config::get('chemins.ontologies');
$table = Config::get('tables.ontologies');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' "
;
$this->getBdd()->requeter($requete);
}
 
private function chargerDonnees() {
$table = Config::get('tables.donnees');
$requete = "LOAD DATA INFILE '".Config::get('chemins.donnees')."' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\'";
$this->getBdd()->requeter($requete);
}
protected function chargerMetadonnees() {
$contenuSql = $this->recupererContenu(Config::get('chemins.metadonnees'));
$this->executerScripSql($contenuSql);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS baseveg_meta, baseveg_ontologies, baseveg_v".Config::get('version');
$this->getBdd()->requeter($requete);
}
 
}
?>
/tags/v5.7-arrayanal/scripts/modules/baseveg/baseveg.ini
New file
0,0 → 1,26
version="2014_01_16"
dossierTsv = "{ref:dossierDonneesEflore}baseveg/2014-01-16/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
donnees = "baseveg_v{ref:version}"
metadonnees = "baseveg_meta"
ontologies = "baseveg_ontologies"
 
[fichiers]
structureSql = "baseveg_v{ref:version}.sql"
metadonnees = "baseveg_insertion_meta_v{ref:version}.sql"
donnees = "baseveg_v{ref:version}.tsv"
ontologies = "baseveg_ontologies.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
donnees = "{ref:dossierTsv}{ref:fichiers.donnees}"
metadonnees = "{ref:dossierSql}{ref:fichiers.metadonnees}"
ontologies ="{ref:dossierTsv}{ref:fichiers.ontologies}"
 
[Parametres]
niveaux = "'CLA';'ALL';'ORD';'ASS';'GRPT';'SUBORD';'SUBASS';'BC';'SUBCLA';'DC';'SUBALL'"
synonymes = "'incl';'=';'= ?';'illeg';'pp';'pmaxp';'pminp';'compl';'ambig';'non';'inval';'nn';'ined'"
motifs = "/^[0-9]+$/=1;
/(?:[0-9]{2}\/$|[0-9]{2}\/[0-9]\.$|[0-9]{2}\/(?:[0-9]\.){1,5}[0-9]$|[0-9]{2}\/(?:[0-9]\.){4,5}[0-9]\/[0-9]+(?:bis|ter){0,1}$)|incertae sedis/=2"
/tags/v5.7-arrayanal/scripts/modules/baseveg/BasevegVerif.php
New file
0,0 → 1,94
<?php
 
class BasevegVerif extends VerificateurDonnees {
 
private $synonymes;
private $niveaux;
private $motifs;
 
//obligatoire
public function definirTraitementsColonnes() {
$this->initialiserParametresVerif();
if ($this->colonne_num == 1 ) {
$this->verifierColonne();
} elseif ($this->colonne_num == 2 ) {
$this->verifierColonne();
} elseif ($this->colonne_num == 4 ) {
$this->verifierNiveaux();
}
}
public function initialiserParametresVerif() {
$this->niveaux = array('CLA','ALL','ORD','ASS','GRPT','SUBORD','SUBASS','BC','SUBCLA','DC','SUBALL');
$this->synonymes = array('incl','=','?','illeg','pp','pmaxp','pminp','compl','ambig','non','inval','nn','ined');
$this->motifs= $this->inverserTableau(array('/^[0-9]+$/' => 1,
'/(?:[0-9]{2}\/$|[0-9]{2}\/[0-9]\.$|[0-9]{2}\/(?:[0-9]\.){1,5}[0-9]$|[0-9]{2}\/(?:[0-9]\.){4,5}[0-9]\/[0-9]+(?:bis|ter|quater){0,1}$)|incertae sedis/' => 2));
//présence de '=' , '= ?' et ',' dans les valeurs des paramètres. ne pas utiliser getParametresTableau.
}
//++---------------------------------traitements des colonnes baseveg------------------------------------++
/**
*
* verifie le champ niveau
*/
public function verifierNiveaux(){
if (preg_match("/^syn(.+)$/", $this->colonne_valeur, $retour) == 1) {
$synonymes = explode(' ', trim($retour[1]));
foreach($synonymes as $syn){
if (!in_array($syn, $this->synonymes)) {
$this->noterErreur();
}
}
} elseif($this->colonne_valeur != '') {
if (!in_array($this->colonne_valeur , $this->niveaux)) {
$this->noterErreur();
}
}
}
 
/**
*
* vérifie un motif sur la valeur entière d'une colonne par expression régulière
*
*/
public function verifierColonne(){
$motif = $this->motifs[$this->colonne_num];
if (preg_match($motif, $this->colonne_valeur) == 0 && $this->verifierSiVide() == false){
$this->noterErreur();
}
}
 
/**
*
* vérifie si une colonne est vide ou non de valeurs
*
*/
public function verifierSiVide(){
$vide = ($this->colonne_valeur == '') ? true : false;
return $vide;
}
/*--------------------------------------------OUtils-------------------------------------------*/
//attention , dans les motifs !!
private function inverserTableau($tableau) {
$inverse = array();
foreach ($tableau as $cle => $valeurs) {
$valeurs = explode(';', $valeurs);
foreach ($valeurs as $valeur) {
$inverse[$valeur] = $cle;
}
}
return $inverse;
}
}
 
?>
/tags/v5.7-arrayanal/scripts/modules/ifn/Ifn.php
New file
0,0 → 1,243
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M cli.php ifn -a chargerTous
* Options :
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).
*/
class Ifn extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('ifn');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerDonnees("documentationFlore");
$this->chargerDonneesAnnuelles();
include_once dirname(__FILE__)."/bibliotheque/proj4php/proj4php.php";
$this->genererCoordonneesWgs('placettesForet');
$this->genererCoordonneesWgs('placettesPeupleraie');
$this->genererCodeInsee('placettesForet');
$this->genererCodeInsee('placettesPeupleraie');
$this->creerVueTapir();
$this->ajouterTupleEfloreOntologies();
break;
case 'chargerStructure' :
$this->chargerStructureSql();
break;
case 'chargerDonnees' :
$this->chargerDonnees("documentationFlore");
$this->chargerDonneesAnnuelles();
break;
case 'genererCoordWgs' :
include_once dirname(__FILE__)."/bibliotheque/proj4php/proj4php.php";
$this->genererCoordonneesWgs('placettesForet');
$this->genererCoordonneesWgs('placettesPeupleraie');
break;
case 'genererCodeInsee' :
$this->genererCodeInsee('placettesForet');
$this->genererCodeInsee('placettesPeupleraie');
break;
case 'creerVueTapir' :
$this->creerVueTapir();
$this->ajouterTupleEfloreOntologies();
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 chargerDonneesAnnuelles() {
$categories = explode(",",Config::get('categories'));
$annees = explode(",",Config::get('versions'));
foreach ($categories as $categorie) {
foreach ($annees as $annee) {
$this->chargerDonnees($categorie, $annee."/");
Debug::printr($categorie." ".$annee."\n");
}
}
}
private function chargerDonnees($categorie, $annee = '') {
$chemin = Config::get('dossierTsv').$annee.Config::get('fichiers.'.$categorie);
$table = Config::get('tables.'.$categorie);
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY ';' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
private function genererNumNomBdtfx() {
$table = Config::get('tables.flore');
$placettes = $this->recupererTuplesPrChpCoordonnees($table);
$this->preparerTablePrCoordWgs($table);
foreach ($placettes as $placette) {
$placette = $this->transformerCoordL93enWgs84($placette);
$this->remplirChpCoordonnees($table, $placette);
}
}
private function creerVueTapir() {
$requete = "DROP VIEW IF EXISTS ifn_tapir; CREATE VIEW ifn_tapir AS ".
"SELECT f.idp as observation_id, b.nom_sci as nom_scientifique_complet, b.num_nom, ".
" fo.lieu_commune_code_insee, fo.lieu_station_latitude, fo.lieu_station_longitude,".
" 'WGS84' AS geodeticDatum, e.dateeco as observation_date, '' AS observateur_nom_complet".
" FROM `bdtfx_v2_01` b, ifn_flore f, ifn_ecologie e, ifn_placettes_foret fo".
" WHERE f.idp = e.idp".
" AND e.idp = fo.idp".
" AND b.cd_nom = f.cd_ref";
$this->getBdd()->requeter($requete);
}
private function ajouterTupleEfloreOntologies(){ // pour la légende
$requete = "INSERT INTO `eflore_ontologies`(id,`classe_id`, `nom`, `description`, `code`, `complements`) VALUES ".
"(24,10,'IFN',".
"'données issues des données brutes mises en ligne de l\'Inventaire Forestier National',".
"'ifn','legende=#F2B148')";
$this->getBdd()->requeter($requete);
}
private function genererCoordonneesWgs($categorie) {
$table = Config::get('tables.'.$categorie);
$placettes = $this->recupererTuplesPrChpCoordonnees($table);
$this->preparerTablePrCoordWgs($table);
foreach ($placettes as $placette) {
$placette = $this->transformerCoordL93enWgs84($placette);
$this->remplirChpCoordonnees($table, $placette);
}
}
private function transformerCoordL93enWgs84($coord) {
$proj4 = new Proj4php();
$projL93 = new Proj4phpProj('EPSG:2154',$proj4);
$projWGS84 = new Proj4phpProj('EPSG:4326',$proj4);
$projLI = new Proj4phpProj('EPSG:27571',$proj4);
$projLSud = new Proj4phpProj('EPSG:27563',$proj4);
$projL72 = new Proj4phpProj('EPSG:31370',$proj4);
$pointSrc = new proj4phpPoint($coord['xl93'],$coord['yl93']);
$pointDest = $proj4->transform($projL93,$projWGS84,$pointSrc);
$coord['longitude_wgs'] = '"'.number_format($pointDest->x, 6).'"';
$coord['latitude_wgs'] = '"'.number_format($pointDest->y, 6).'"';
return $coord;
}
private function recupererTuplesPrChpCoordonnees($table) {
$requete = 'SELECT idp, xl93, yl93 '.
"FROM {$table} ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
private function remplirChpCoordonnees($table, $placette) {
$requete = "UPDATE {$table} ".
" SET lieu_station_longitude = {$placette['longitude_wgs']} , lieu_station_latitude = {$placette['latitude_wgs']} ".
" WHERE idp = {$placette['idp']} ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $idp");
}
}
 
private function preparerTablePrCoordWgs($table) {
$requete = "SHOW COLUMNS FROM {$table} LIKE 'lieu_station_latitude' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$table} ".
' ADD `lieu_station_latitude` DECIMAL( 9, 6 ),'.
' ADD `lieu_station_longitude` DECIMAL( 9, 6 )';
$this->getBdd()->requeter($requete);
}
}
 
private function genererCodeInsee($categorie) {
$table = Config::get('tables.'.$categorie);
$this->preparerTablePrChpCodeInsee($table);
$liste_coordonnees = $this->recupererTuplesPrChpCodeInsee($table);
foreach ($liste_coordonnees as $coordonnees) {
$code_insee = $this->chercherCodeCommune($coordonnees['latitude'], $coordonnees['longitude']);
if ($code_insee != "") {
$this->remplirChpCodeInsee($table, $coordonnees['latitude'], $coordonnees['longitude'], $code_insee);
}
}
}
private function preparerTablePrChpCodeInsee($table) {
$requete = "SHOW COLUMNS FROM {$table} LIKE 'lieu_commune_code_insee' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$table} ".
' ADD `lieu_commune_code_insee` VARCHAR(5);';
$this->getBdd()->requeter($requete);
}
}
private function recupererTuplesPrChpCodeInsee($table) {
$requete = 'SELECT distinct lieu_station_latitude as latitude, lieu_station_longitude as longitude '.
"FROM {$table} WHERE lieu_commune_code_insee IS NULL ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
private function remplirChpCodeInsee($table, $latitude, $longitude, $code_insee) {
$requete = "UPDATE {$table} ".
" SET lieu_commune_code_insee = '{$code_insee}'".
" WHERE lieu_station_longitude = {$longitude} AND lieu_station_latitude = {$latitude} ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $idp");
}
}
private function chercherCodeCommune($latitude, $longitude) {
$code_insee = '';
if ($this->testerCoordonneesWgsFrance($latitude, $longitude)) {
$url_service = "api.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 supprimerTous() {
$requete = "DROP TABLE IF EXISTS `ifn_arbres_forets`, `ifn_arbres_peupleraie`, `ifn_couverts_foret`,
`ifn_documentation`, `ifn_documentation_flore`, `ifn_ecologie`, `ifn_flore`, `ifn_placettes_foret`,
`ifn_placettes_peupleraie`;
";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/ifn/ifn.ini
New file
0,0 → 1,35
code = "ifn"
versions = "2005,2006,2007,2008,2009,2010,2011,2012"
categories = "arbresForet,arbresPeupleraie,couvertsForet,documentation,ecologie,flore,placettesForet,placettesPeupleraie"
dossierTsv = "{ref:dossierDonneesEflore}{ref:code}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
ifnMeta = "if_meta"
documentationFlore = "ifn_documentation_flore"
arbresForet = "ifn_arbres_foret"
arbresPeupleraie = "ifn_arbres_peupleraie"
couvertsForet = "ifn_couverts_foret"
documentation = "ifn_documentation"
ecologie = "ifn_ecologie"
flore = "ifn_flore"
placettesForet = "ifn_placettes_foret"
placettesPeupleraie = "ifn_placettes_peupleraie"
ifnTest = "ifn"
 
 
[fichiers]
structureSql = "{ref:code}.sql"
arbresForet = "arbres_foret.csv"
arbresPeupleraie = "arbres_peupleraie.csv"
couvertsForet = "couverts_foret.csv"
documentation = "documentation.csv"
ecologie = "ecologie.csv"
flore = "flore.csv"
placettesForet = "placettes_foret.csv"
placettesPeupleraie = "placettes_peupleraie.csv"
documentationFlore = "documentation_flore.csv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
documentation_flore = "{ref:dossierTsv}{ref:documentation_flore}"
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG27571.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:27571"] = "+proj=lcc +lat_1=49.50000000000001 +lat_0=49.50000000000001 +lon_0=0 +k_0=0.999877341 +x_0=600000 +y_0=1200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG31468.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:31468"] = "+proj=tmerc +lat_0=0 +lon_0=12 +k=1.000000 +x_0=4500000 +y_0=0 +ellps=bessel +datum=potsdam +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG26591.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:26591"] = "+title= Monte Mario (Rome) / Italy zone 1 EPSG:26591 +proj=tmerc +lat_0=0 +lon_0=-3.45233333333333 +from_greenwich=12.45233333333333 +k=0.999600 +x_0=1500000 +y_0=0 +a=6378388.0, +b=6356911.94612795 +units=m";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG27563.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:27563"]="+title=NTF (Paris)/Lambert Sud France +proj=lcc +lat_1=44.10000000000001 +lat_0=44.10000000000001 +lon_0=0 +k_0=0.9998774990000001 +x_0=600000 +y_0=200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs ";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG4302.php
New file
0,0 → 1,3
<?php
Proj4php::$defs["EPSG:4302"] = "+title=Trinidad 1903 EPSG:4302 (7 param datum shift) +proj=longlat +a=6378293.63683822 +b=6356617.979337744 +towgs84=-61.702,284.488,472.052,0,0,0,0";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG2154.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:2154"] = "+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG4181.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:4181"] = "+title=Luxembourg 1930 EPSG:4181 (7 param datum shift) +proj=longlat +towgs84=-193,13.7,-39.3,-0.41,-2.933,2.688,0.43 +a=6378388.0, +b=6356911.94612795";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG900913.txt
New file
0,0 → 1,11
// Google Mercator projection
// Used in combination with GoogleMercator layer type in OpenLayers
//+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs
 
csList.EPSG900913= "\
+title= Google Mercator EPSG:900913\
+proj=merc +a=6378137 +b=6378137 \
+lat_ts=0.0 +lon_0=0.0 \
+x_0=0.0 +y_0=0 +k=1.0 \
+units=m +nadgrids=@null +no_defs \
";
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/GOOGLE.php
New file
0,0 → 1,3
<?php
Proj4php::$defs["GOOGLE"]="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs";
Proj4php::$defs["EPSG:900913"]=Proj4php::$defs["GOOGLE"];
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG4272.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:4272"] = "+title=NZGD49 +proj=longlat +ellps=intl +datum=nzgd49 +no_defs ";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG4139.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:4139"] = "+title=Puerto Rico EPSG:4139 (3 param datum shift) +proj=longlat +towgs84 = 11,72,-101,0,0,0,0 +a=6378206.4 +b=6356583.8";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG900913.php
New file
0,0 → 1,6
<?php
// Google Mercator projection
// Used in combination with GoogleMercator layer type in OpenLayers
//+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs
 
Proj4php::$defs["EPSG:900913"]= "+title= Google Mercator EPSG:900913 +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG102757.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:102757"] = "+title=NAD 1983 StatePlane Wyoming West Central FIPS 4903 Feet +proj=tmerc +lat_0=40.5 +lon_0=-108.75 +x_0=600000.0 +y_0=0 +k=0.999938 +a=6378137.0 +b=6356752.3141403 +to_meter=0.3048006096012192";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG41001.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:41001"] = "+title=simple mercator EPSG:41001 +proj=merc +lat_ts=0 +lon_0=0 +k=1.000000 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG102758.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:102758"] = "+title=NAD 1983 StatePlane Wyoming West FIPS 4904 Feet +proj=tmerc +lat_0=40.5 +lon_0=-110.0833333333333 +x_0=800000 +y_0=100000 +k=0.999938 +a=6378137.0 +b=6356752.3141403 +to_meter=0.3048006096012192";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG27200.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:27200"] = "+title=New Zealand Map Grid +proj=nzmg +lat_0=-41 +lon_0=173 +x_0=2510000 +y_0=6023150 +ellps=intl +datum=nzgd49 +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG42304.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:42304"]="+title=Atlas of Canada, LCC +proj=lcc +lat_1=49 +lat_2=77 +lat_0=49 +lon_0=-95 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG31370.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:31370"] = "+proj=lcc +lat_1=51.16666723333333 +lat_2=49.8333339 +lat_0=90 +lon_0=4.367486666666666 +x_0=150000.013 +y_0=5400088.438 +ellps=intl +towgs84=106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1 +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG21781.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:21781"] = "+title=CH1903 / LV03 +proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +x_0=600000 +y_0=200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG25832.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:25832"] = "+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG26912.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG26912"] = "+title=NAD83 / UTM zone 12N +proj=utm +zone=12 +a=6378137.0 +b=6356752.3141403";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/defs/EPSG31467.php
New file
0,0 → 1,2
<?php
Proj4php::$defs["EPSG:31467"] = "+proj=tmerc +lat_0=0 +lon_0=9 +k=1.000000 +x_0=3500000 +y_0=0 +ellps=bessel +datum=potsdam +units=m +no_defs";
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/WSProj4PHP_1.0.php
New file
0,0 → 1,104
<?php
 
include_once("proj4php.php");
 
$error = false;
 
/**
* Geometry-Points
*/
if( isset( $_GET['GEOM'] ) ) {
list($x, $y) = explode( ' ', $_GET['GEOM'] );
} else {
if( isset( $_GET['x'] ) ) {
$x = $_GET['x'];
}
else
$error = true;
 
if( isset( $_GET['y'] ) ) {
$y = $_GET['y'];
}
else
$error = true;
}
 
/**
* Source-CRS
*/
if( isset( $_GET['SOURCECRS'] ) ) {
$srcProjection = str_replace( '::', ':', $_GET['SOURCECRS'] );
} else if( isset( $_GET['projectionxy'] ) ) {
$srcProjection = $_GET['projectionxy'];
$srcProjection = str_replace( '::', ':', $srcProjection );
}
else
$srcProjection = 'EPSG:2154';
 
/**
* Target-CRS
*/
if( isset( $_GET['TARGETCRS'] ) ) {
$tgtProjection = str_replace( '::', ':', $_GET['TARGETCRS'] );
} else if( isset( $_GET['projection'] ) ) {
$tgtProjection = $_GET['projection'];
$tgtProjection = str_replace( '::', ':', $tgtProjection );
}
else
$tgtProjection = 'EPSG:4326';
 
/**
* Format
*/
if( isset( $_GET['format'] ) ) {
$format = $_GET['format'];
if( !($format == 'xml' || $format == 'json') )
$error = true;
}
else
$format = 'xml';
 
 
$proj4 = new Proj4php();
$projsource = new Proj4phpProj( $srcProjection, $proj4 );
$projdest = new Proj4phpProj( $tgtProjection, $proj4 );
 
// check the projections
if( Proj4php::$defs[$srcProjection] == Proj4php::$defs['WGS84'] && $srcProjection != 'EPSG:4326' )
$error = true;
if( Proj4php::$defs[$tgtProjection] == Proj4php::$defs['WGS84'] && $tgtProjection != 'EPSG:4326' )
$error = true;
 
if( $error === true ) {
if( $format == 'json' ) {
echo "{\"status\":\"error\", \"erreur\": {\"code\": 2, \"message\": \"Wrong parameters.\"} }";
exit;
} else {
echo "<reponse>";
echo " <erreur>";
echo " <code>2</code>";
echo " <message>Wrong parameters</message>";
echo " </erreur>";
echo "</reponse>";
exit;
}
}
 
$pointSrc = new proj4phpPoint( $x, $y );
$pointDest = $proj4->transform( $projsource, $projdest, $pointSrc );
 
$tgtProjection = str_replace( ':', '::', $tgtProjection );
 
if( $format == 'json' ) {
echo "{\"status\" :\"success\", \"point\" : {\"x\":" . $pointDest->x . ", \"y\":" . $pointDest->y . ",\"projection\" :\"" . $tgtProjection . "\"}}";
exit;
} else {
header ("Content-Type:text/xml");
echo "<reponse>";
echo "<point>";
echo "<x>" . $pointDest->x . "</x>";
echo "<y>" . $pointDest->y . "</y>";
echo "<projection>" . $tgtProjection . "</projection>";
echo "</point>";
echo "</reponse>";
}
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/proj4phpCommon.php
New file
0,0 → 1,389
<?php
 
/**
* Author : Julien Moquet
*
* Inspired by Proj4js from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodmap.com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class Proj4phpCommon {
 
public $PI = M_PI; #3.141592653589793238; //Math.PI,
public $HALF_PI = M_PI_2; #1.570796326794896619; //Math.PI*0.5,
public $TWO_PI = 6.283185307179586477; //Math.PI*2,
public $FORTPI = 0.78539816339744833;
public $R2D = 57.29577951308232088;
public $D2R = 0.01745329251994329577;
public $SEC_TO_RAD = 4.84813681109535993589914102357e-6; /* SEC_TO_RAD = Pi/180/3600 */
public $EPSLN = 1.0e-10;
public $MAX_ITER = 20;
// following constants from geocent.c
public $COS_67P5 = 0.38268343236508977; /* cosine of 67.5 degrees */
public $AD_C = 1.0026000; /* Toms region 1 constant */
 
/* datum_type values */
public $PJD_UNKNOWN = 0;
public $PJD_3PARAM = 1;
public $PJD_7PARAM = 2;
public $PJD_GRIDSHIFT = 3;
public $PJD_WGS84 = 4; // WGS84 or equivalent
public $PJD_NODATUM = 5; // WGS84 or equivalent
 
const SRS_WGS84_SEMIMAJOR = 6378137.0; // only used in grid shift transforms
 
// ellipoid pj_set_ell.c
 
public $SIXTH = .1666666666666666667; /* 1/6 */
public $RA4 = .04722222222222222222; /* 17/360 */
public $RA6 = .02215608465608465608; /* 67/3024 */
public $RV4 = .06944444444444444444; /* 5/72 */
public $RV6 = .04243827160493827160; /* 55/1296 */
 
 
/* meridinal distance for ellipsoid and inverse
* * 8th degree - accurate to < 1e-5 meters when used in conjuction
* * with typical major axis values.
* * Inverse determines phi to EPS (1e-11) radians, about 1e-6 seconds.
*/
protected $C00 = 1.0;
protected $C02 = .25;
protected $C04 = .046875;
protected $C06 = .01953125;
protected $C08 = .01068115234375;
protected $C22 = .75;
protected $C44 = .46875;
protected $C46 = .01302083333333333333;
protected $C48 = .00712076822916666666;
protected $C66 = .36458333333333333333;
protected $C68 = .00569661458333333333;
protected $C88 = .3076171875;
 
/**
* Function to compute the constant small m which is the radius of
* a parallel of latitude, phi, divided by the semimajor axis.
*
* @param type $eccent
* @param type $sinphi
* @param type $cosphi
* @return type
*/
public function msfnz( $eccent, $sinphi, $cosphi ) {
$con = $eccent * $sinphi;
return $cosphi / (sqrt( 1.0 - $con * $con ));
}
 
/**
* Function to compute the constant small t for use in the forward
* computations in the Lambert Conformal Conic and the Polar
* Stereographic projections.
*
* @param type $eccent
* @param type $phi
* @param type $sinphi
* @return type
*/
public function tsfnz( $eccent, $phi, $sinphi ) {
$con = $eccent * $sinphi;
$com = 0.5 * $eccent;
$con = pow( ((1.0 - $con) / (1.0 + $con) ), $com );
return (tan( .5 * (M_PI_2 - $phi) ) / $con);
}
 
/**
* Function to compute the latitude angle, phi2, for the inverse of the
* Lambert Conformal Conic and Polar Stereographic projections.
*
* rise up an assertion if there is no convergence.
*
* @param type $eccent
* @param type $ts
* @return type
*/
public function phi2z( $eccent, $ts ) {
$eccnth = .5 * $eccent;
$phi = M_PI_2 - 2 * atan( $ts );
for( $i = 0; $i <= 15; $i++ ) {
$con = $eccent * sin( $phi );
$dphi = M_PI_2 - 2 * atan( $ts * (pow( ((1.0 - $con) / (1.0 + $con) ), $eccnth )) ) - $phi;
$phi += $dphi;
if( abs( $dphi ) <= .0000000001 )
return $phi;
}
assert( "false; /* phi2z has NoConvergence */" );
return (-9999);
}
 
/**
* Function to compute constant small q which is the radius of a
* parallel of latitude, phi, divided by the semimajor axis.
*
* @param type $eccent
* @param type $sinphi
* @return type
*/
public function qsfnz( $eccent, $sinphi ) {
if( $eccent > 1.0e-7 ) {
$con = $eccent * $sinphi;
return (( 1.0 - $eccent * $eccent) * ($sinphi / (1.0 - $con * $con) - (.5 / $eccent) * log( (1.0 - $con) / (1.0 + $con) )));
}
return (2.0 * $sinphi);
}
 
/**
* Function to eliminate roundoff errors in asin
*
* @param type $x
* @return type
*/
public function asinz( $x ) {
return asin(
abs( $x ) > 1.0 ? ($x > 1.0 ? 1.0 : -1.0) : $x
);
#if( abs( $x ) > 1.0 ) {
# $x = ($x > 1.0) ? 1.0 : -1.0;
#}
#return asin( $x );
}
 
/**
* following functions from gctpc cproj.c for transverse mercator projections
*
* @param type $x
* @return type
*/
public function e0fn( $x ) {
return (1.0 - 0.25 * $x * (1.0 + $x / 16.0 * (3.0 + 1.25 * $x)));
}
 
/**
*
* @param type $x
* @return type
*/
public function e1fn( $x ) {
return (0.375 * $x * (1.0 + 0.25 * $x * (1.0 + 0.46875 * $x)));
}
 
/**
*
* @param type $x
* @return type
*/
public function e2fn( $x ) {
return (0.05859375 * $x * $x * (1.0 + 0.75 * $x));
}
 
/**
*
* @param type $x
* @return type
*/
public function e3fn( $x ) {
return ($x * $x * $x * (35.0 / 3072.0));
}
 
/**
*
* @param type $e0
* @param type $e1
* @param type $e2
* @param type $e3
* @param type $phi
* @return type
*/
public function mlfn( $e0, $e1, $e2, $e3, $phi ) {
return ($e0 * $phi - $e1 * sin( 2.0 * $phi ) + $e2 * sin( 4.0 * $phi ) - $e3 * sin( 6.0 * $phi ));
}
 
/**
*
* @param type $esinp
* @param type $exp
* @return type
*/
public function srat( $esinp, $exp ) {
return (pow( (1.0 - $esinp) / (1.0 + $esinp), $exp ));
}
 
/**
* Function to return the sign of an argument
*
* @param type $x
* @return type
*/
public function sign( $x ) {
return $x < 0.0 ? -1 : 1;
}
 
/**
* Function to adjust longitude to -180 to 180; input in radians
*
* @param type $x
* @return type
*/
public function adjust_lon( $x ) {
return (abs( $x ) < M_PI) ? $x : ($x - ($this->sign( $x ) * $this->TWO_PI) );
}
 
/**
* IGNF - DGR : algorithms used by IGN France
* Function to adjust latitude to -90 to 90; input in radians
*
* @param type $x
* @return type
*/
public function adjust_lat( $x ) {
$x = (abs( $x ) < M_PI_2) ? $x : ($x - ($this->sign( $x ) * M_PI) );
return $x;
}
 
/**
* Latitude Isometrique - close to tsfnz ...
*
* @param type $eccent
* @param float $phi
* @param type $sinphi
* @return string
*/
public function latiso( $eccent, $phi, $sinphi ) {
if( abs( $phi ) > M_PI_2 )
return +NaN;
if( $phi == M_PI_2 )
return INF;
if( $phi == -1.0 * M_PI_2 )
return -1.0 * INF;
 
$con = $eccent * $sinphi;
return log( tan( (M_PI_2 + $phi) / 2.0 ) ) + $eccent * log( (1.0 - $con) / (1.0 + $con) ) / 2.0;
}
 
/**
*
* @param type $x
* @param type $L
* @return type
*/
public function fL( $x, $L ) {
return 2.0 * atan( $x * exp( $L ) ) - M_PI_2;
}
 
/**
* Inverse Latitude Isometrique - close to ph2z
*
* @param type $eccent
* @param type $ts
* @return type
*/
public function invlatiso( $eccent, $ts ) {
$phi = $this->fL( 1.0, $ts );
$Iphi = 0.0;
$con = 0.0;
do {
$Iphi = $phi;
$con = $eccent * sin( $Iphi );
$phi = $this->fL( exp( $eccent * log( (1.0 + $con) / (1.0 - $con) ) / 2.0 ), $ts );
} while( abs( $phi - $Iphi ) > 1.0e-12 );
return $phi;
}
 
/**
* Grande Normale
*
* @param type $a
* @param type $e
* @param type $sinphi
* @return type
*/
public function gN( $a, $e, $sinphi ) {
$temp = $e * $sinphi;
return $a / sqrt( 1.0 - $temp * $temp );
}
 
/**
* code from the PROJ.4 pj_mlfn.c file; this may be useful for other projections
*
* @param type $es
* @return type
*/
public function pj_enfn( $es ) {
 
$en = array( );
$en[0] = $this->C00 - $es * ($this->C02 + $es * ($this->C04 + $es * ($this->C06 + $es * $this->C08)));
$en[1] = es * ($this->C22 - $es * ($this->C04 + $es * ($this->C06 + $es * $this->C08)));
$t = $es * $es;
$en[2] = $t * ($this->C44 - $es * ($this->C46 + $es * $this->C48));
$t *= $es;
$en[3] = $t * ($this->C66 - $es * $this->C68);
$en[4] = $t * $es * $this->C88;
return $en;
}
 
/**
*
* @param type $phi
* @param type $sphi
* @param type $cphi
* @param type $en
* @return type
*/
public function pj_mlfn( $phi, $sphi, $cphi, $en ) {
$cphi *= $sphi;
$sphi *= $sphi;
return ($en[0] * $phi - $cphi * ($en[1] + $sphi * ($en[2] + $sphi * ($en[3] + $sphi * $en[4]))));
}
 
/**
*
* @param type $arg
* @param type $es
* @param type $en
* @return type
*/
public function pj_inv_mlfn( $arg, $es, $en ) {
$k = (float) 1 / (1 - $es);
$phi = $arg;
for( $i = Proj4php::$common->MAX_ITER; $i; --$i ) { /* rarely goes over 2 iterations */
$s = sin( $phi );
$t = 1. - $es * $s * $s;
//$t = $this->pj_mlfn($phi, $s, cos($phi), $en) - $arg;
//$phi -= $t * ($t * sqrt($t)) * $k;
$t = ($this->pj_mlfn( $phi, $s, cos( $phi ), $en ) - $arg) * ($t * sqrt( $t )) * $k;
$phi -= $t;
if( abs( $t ) < Proj4php::$common->EPSLN )
return $phi;
}
 
Proj4php::reportError( "cass:pj_inv_mlfn: Convergence error" );
 
return $phi;
}
 
}
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/eqdc.php
New file
0,0 → 1,152
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME EQUIDISTANT CONIC
 
PURPOSE: Transforms input longitude and latitude to Easting and Northing
for the Equidistant Conic projection. The longitude and
latitude must be in radians. The Easting and Northing values
will be returned in meters.
 
PROGRAMMER DATE
---------- ----
T. Mittan Mar, 1993
 
ALGORITHM REFERENCES
 
1. Snyder, John $p->, "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John $p-> and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
*******************************************************************************/
 
/* Variables common to all subroutines in this code file
-----------------------------------------------------*/
 
class Proj4phpProjEqdc {
/* Initialize the Equidistant Conic projection
------------------------------------------ */
public function init() {
/* Place parameters in static storage for common use
------------------------------------------------- */
if( !$this->mode )
$this->mode = 0; //chosen default mode
$this->temp = $this->b / $this->a;
$this->es = 1.0 - pow( $this->temp, 2 );
$this->e = sqrt( $this->es );
$this->e0 = Proj4php::$common->e0fn( $this->es );
$this->e1 = Proj4php::$common->e1fn( $this->es );
$this->e2 = Proj4php::$common->e2fn( $this->es );
$this->e3 = Proj4php::$common->e3fn( $this->es );
 
$this->sinphi = sin( $this->lat1 );
$this->cosphi = cos( $this->lat1 );
 
$this->ms1 = Proj4php::$common->msfnz( $this->e, $this->sinphi, $this->cosphi );
$this->ml1 = Proj4php::$common->mlfn( $this->e0, $this->e1, $this->e2, $this->e3, $this->lat1 );
 
/* format B
--------- */
if( $this->mode != 0 ) {
if( abs( $this->lat1 + $this->lat2 ) < Proj4php::$common->EPSLN ) {
Proj4php::reportError( "eqdc:Init:EqualLatitudes" );
//return(81);
}
$this->sinphi = sin( $this->lat2 );
$this->cosphi = cos( $this->lat2 );
 
$this->ms2 = Proj4php::$common->msfnz( $this->e, $this->sinphi, $this->cosphi );
$this->ml2 = Proj4php::$common->mlfn( $this->e0, $this->e1, $this->e2, $this->e3, $this->lat2 );
if( abs( $this->lat1 - $this->lat2 ) >= Proj4php::$common->EPSLN ) {
$this->ns = ($this->ms1 - $this->ms2) / ($this->ml2 - $this->ml1);
} else {
$this->ns = $this->sinphi;
}
} else {
$this->ns = $this->sinphi;
}
$this->g = $this->ml1 + $this->ms1 / $this->ns;
$this->ml0 = Proj4php::$common->mlfn( $this->e0, $this->e1, $this->e2, $this->e3, $this->lat0 );
$this->rh = $this->a * ($this->g - $this->ml0);
}
 
/* Equidistant Conic forward equations--mapping lat,long to x,y
----------------------------------------------------------- */
public function forward( $p ) {
$lon = $p->x;
$lat = $p->y;
 
/* Forward equations
----------------- */
$ml = Proj4php::$common->mlfn( $this->e0, $this->e1, $this->e2, $this->e3, $lat );
$rh1 = $this->a * ($this->g - $ml);
$theta = $this->ns * Proj4php::$common->adjust_lon( $lon - $this->long0 );
 
$x = $this->x0 + $rh1 * sin( $theta );
$y = $this->y0 + $this->rh - $rh1 * cos( $theta );
$p->x = $x;
$p->y = $y;
return $p;
}
 
/* Inverse equations
----------------- */
public function inverse( $p ) {
$p->x -= $this->x0;
$p->y = $this->rh - $p->y + $this->y0;
if( $this->ns >= 0 ) {
$rh1 = sqrt( $p->x * $p->x + $p->y * $p->y );
$con = 1.0;
} else {
$rh1 = -sqrt( $p->x * $p->x + $p->y * $p->y );
$con = -1.0;
}
$theta = 0.0;
if( $rh1 != 0.0 )
$theta = atan2( $con * $p->x, $con * $p->y );
$ml = $this->g - $rh1 / $this->a;
$lat = $this->phi3z( $ml, $this->e0, $this->e1, $this->e2, $this->e3 );
$lon = Proj4php::$common->adjust_lon( $this->long0 + $theta / $this->ns );
 
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
/* Function to compute latitude, phi3, for the inverse of the Equidistant
Conic projection.
----------------------------------------------------------------- */
 
public function phi3z( $ml, $e0, $e1, $e2, $e3 ) {
 
$phi = $ml;
for( $i = 0; $i < 15; $i++ ) {
$dphi = ($ml + $e1 * sin( 2.0 * $phi ) - $e2 * sin( 4.0 * $phi ) + $e3 * sin( 6.0 * $phi )) / $e0 - $phi;
$phi += $dphi;
if( abs( $dphi ) <= .0000000001 ) {
return $phi;
}
}
Proj4php::reportError( "PHI3Z-CONV:Latitude failed to converge after 15 iterations" );
return null;
}
}
 
Proj4php::$proj['eqdc'] = new Proj4phpProjEqdc();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/sinu.php
New file
0,0 → 1,139
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME SINUSOIDAL
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Sinusoidal projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
D. Steinwand, EROS May, 1991
 
This function was adapted from the Sinusoidal projection code (FORTRAN) in the
General Cartographic Transformation Package software which is available from
the U.S. Geological Survey National Mapping Division.
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. "Software Documentation for GCTP General Cartographic Transformation
Package", U.S. Geological Survey National Mapping Division, May 1982.
* ***************************************************************************** */
 
class Proj4phpProjSinu {
/* Initialize the Sinusoidal projection
------------------------------------ */
public function init() {
/* Place parameters in static storage for common use
------------------------------------------------- */
#$this->R = 6370997.0; //Radius of earth
 
if( !$this->sphere ) {
$this->en = Proj4php::$common->pj_enfn( $this->es );
} else {
$this->n = 1.;
$this->m = 0.;
$this->es = 0;
$this->C_y = sqrt( ($this->m + 1.) / $this->n );
$this->C_x = $this->C_y / ($this->m + 1.);
}
}
 
/* Sinusoidal forward equations--mapping lat,long to x,y
----------------------------------------------------- */
public function forward( $p ) {
 
#$x,y,delta_lon;
$lon = $p->x;
$lat = $p->y;
 
/* Forward equations
----------------- */
$lon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
if( isset($this->sphere) ) {
if( !$this->m ) {
$lat = $this->n != 1. ? asin( $this->n * sin( $lat ) ) : $lat;
} else {
$k = $this->n * sin( $lat );
for( $i = Proj4php::$common->MAX_ITER; $i; --$i ) {
$V = ($this->m * $lat + sin( $lat ) - $k) / ($this->m + cos( $lat ));
$lat -= $V;
if( abs( $V ) < Proj4php::$common->EPSLN )
break;
}
}
$x = $this->a * $this->C_x * $lon * ($this->m + cos( $lat ));
$y = $this->a * $this->C_y * $lat;
} else {
 
$s = sin( $lat );
$c = cos( $lat );
$y = $this->a * Proj4php::$common->pj_mlfn( $lat, $s, $c, $this->en );
$x = $this->a * $lon * $c / sqrt( 1. - $this->es * $s * $s );
}
 
$p->x = $x;
$p->y = $y;
 
return $p;
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
#$lat;
#$temp;
#$lon;
 
/* Inverse equations
----------------- */
$p->x -= $this->x0;
$p->y -= $this->y0;
$lat = $p->y / $this->a;
 
if( isset($this->sphere) ) {
 
$p->y /= $this->C_y;
$lat = $this->m ? asin( ($this->m * $p->y + sin( $p->y )) / $this->n ) : ( $this->n != 1. ? asin( sin( $p->y ) / $this->n ) : $p->y );
$lon = $p->x / ($this->C_x * ($this->m + cos( $p->y )));
}
else {
$lat = Proj4php::$common->pj_inv_mlfn( $p->y / $this->a, $this->es, $this->en );
$s = abs( $lat );
if( $s < Proj4php::$common->HALF_PI ) {
$s = sin( $lat );
$temp = $this->long0 + $p->x * sqrt( 1. - $this->es * $s * $s ) / ($this->a * cos( $lat ));
//temp = $this->long0 + $p->x / ($this->a * cos($lat));
$lon = Proj4php::$common->adjust_lon( $temp );
} else if( ($s - Proj4php::$common->EPSLN) < Proj4php::$common->HALF_PI ) {
$lon = $this->long0;
}
}
$p->x = $lon;
$p->y = $lat;
 
return $p;
}
 
}
 
Proj4php::$proj['sinu'] = new Proj4phpProjSinu();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/gauss.php
New file
0,0 → 1,74
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class Proj4phpProjGauss {
 
/**
*
*/
public function init() {
$sphi = sin( $this->lat0 );
$cphi = cos( $this->lat0 );
$cphi *= $cphi;
$this->rc = sqrt( 1.0 - $this->es ) / (1.0 - $this->es * $sphi * $sphi);
$this->C = sqrt( 1.0 + $this->es * $cphi * $cphi / (1.0 - $this->es) );
$this->phic0 = asin( $sphi / $this->C );
$this->ratexp = 0.5 * $this->C * $this->e;
$this->K = tan( 0.5 * $this->phic0 + Proj4php::$common->FORTPI ) / (pow( tan( 0.5 * $this->lat0 + Proj4php::$common->FORTPI ), $this->C ) * Proj4php::$common->srat( $this->e * $sphi, $this->ratexp ));
}
 
/**
*
* @param type $p
* @return type
*/
public function forward( $p ) {
$lon = $p->x;
$lat = $p->y;
 
$p->y = 2.0 * atan( $this->K * pow( tan( 0.5 * $lat + Proj4php::$common->FORTPI ), $this->C ) * Proj4php::$common->srat( $this->e * sin( $lat ), $this->ratexp ) ) - Proj4php::$common->HALF_PI;
$p->x = $this->C * $lon;
return $p;
}
 
/**
*
* @param type $p
* @return null
*/
public function inverse( $p ) {
$DEL_TOL = 1e-14;
$lon = $p->x / $this->C;
$lat = $p->y;
$num = pow( tan( 0.5 * $lat + Proj4php::$common . FORTPI ) / $this->K, 1. / $this->C );
for( $i = Proj4php::$common . MAX_ITER; $i > 0; --$i ) {
$lat = 2.0 * atan( $num * Proj4php::$common->srat( $this->e * sin( $p->y ), -0.5 * $this->e ) ) - Proj4php::$common->HALF_PI;
if( abs( $lat - $p->y ) < $DEL_TOL )
break;
$p->y = $lat;
}
/* convergence failed */
if( !$i ) {
Proj4php::reportError( "gauss:inverse:convergence failed" );
return null;
}
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
}
 
Proj4php::$proj['gauss'] = new Proj4phpProjGauss();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/stere.php
New file
0,0 → 1,303
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
 
// Initialize the Stereographic projection
class Proj4phpProjStere {
 
protected $TOL = 1.e-8;
protected $NITER = 8;
protected $CONV = 1.e-10;
protected $S_POLE = 0;
protected $N_POLE = 1;
protected $OBLIQ = 2;
protected $EQUIT = 3;
 
/**
*
* @param type $phit
* @param type $sinphi
* @param type $eccen
* @return type
*/
public function ssfn_( $phit, $sinphi, $eccen ) {
$sinphi *= $eccen;
return (tan( .5 * (Proj4php::$common->HALF_PI + $phit) ) * pow( (1. - $sinphi) / (1. + $sinphi), .5 * $eccen ));
}
/**
*
*/
public function init() {
$this->phits = $this->lat_ts ? $this->lat_ts : Proj4php::$common->HALF_PI;
$t = abs( $this->lat0 );
if( (abs( $t ) - Proj4php::$common->HALF_PI) < Proj4php::$common->EPSLN ) {
$this->mode = $this->lat0 < 0. ? $this->S_POLE : $this->N_POLE;
} else {
$this->mode = $t > Proj4php::$common->EPSLN ? $this->OBLIQ : $this->EQUIT;
}
$this->phits = abs( $this->phits );
if( $this->es ) {
#$X;
 
switch( $this->mode ) {
case $this->N_POLE:
case $this->S_POLE:
if( abs( $this->phits - Proj4php::$common->HALF_PI ) < Proj4php::$common->EPSLN ) {
$this->akm1 = 2. * $this->k0 / sqrt( pow( 1 + $this->e, 1 + $this->e ) * pow( 1 - $this->e, 1 - $this->e ) );
} else {
$t = sin( $this->phits );
$this->akm1 = cos( $this->phits ) / Proj4php::$common->tsfnz( $this->e, $this->phits, $t );
$t *= $this->e;
$this->akm1 /= sqrt( 1. - $t * $t );
}
break;
case $this->EQUIT:
$this->akm1 = 2. * $this->k0;
break;
case $this->OBLIQ:
$t = sin( $this->lat0 );
$X = 2. * atan( $this->ssfn_( $this->lat0, $t, $this->e ) ) - Proj4php::$common->HALF_PI;
$t *= $this->e;
$this->akm1 = 2. * $this->k0 * cos( $this->lat0 ) / sqrt( 1. - $t * $t );
$this->sinX1 = sin( $X );
$this->cosX1 = cos( $X );
break;
}
} else {
switch( $this->mode ) {
case $this->OBLIQ:
$this->sinph0 = sin( $this->lat0 );
$this->cosph0 = cos( $this->lat0 );
case $this->EQUIT:
$this->akm1 = 2. * $this->k0;
break;
case $this->S_POLE:
case $this->N_POLE:
$this->akm1 = abs( $this->phits - Proj4php::$common->HALF_PI ) >= Proj4php::$common->EPSLN ?
cos( $this->phits ) / tan( Proj4php::$common->FORTPI - .5 * $this->phits ) :
2. * $this->k0;
break;
}
}
}
 
/**
* Stereographic forward equations--mapping lat,long to x,y
*
* @param type $p
* @return type
*/
public function forward( $p ) {
$lon = $p->x;
$lon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
$lat = $p->y;
#$x;
#$y;
 
if( $this->sphere ) {
/*
$sinphi;
$cosphi;
$coslam;
$sinlam;
*/
$sinphi = sin( $lat );
$cosphi = cos( $lat );
$coslam = cos( $lon );
$sinlam = sin( $lon );
switch( $this->mode ) {
case $this->EQUIT:
$y = 1. + $cosphi * $coslam;
if( y <= Proj4php::$common->EPSLN ) {
Proj4php::reportError("stere:forward:Equit");
}
$y = $this->akm1 / $y;
$x = $y * $cosphi * $sinlam;
$y *= $sinphi;
break;
case $this->OBLIQ:
$y = 1. + $this->sinph0 * $sinphi + $this->cosph0 * $cosphi * $coslam;
if( $y <= Proj4php::$common->EPSLN ) {
Proj4php::reportError("stere:forward:Obliq");
}
$y = $this->akm1 / $y;
$x = $y * $cosphi * $sinlam;
$y *= $this->cosph0 * $sinphi - $this->sinph0 * $cosphi * $coslam;
break;
case $this->N_POLE:
$coslam = -$coslam;
$lat = -$lat;
//Note no break here so it conitnues through S_POLE
case $this->S_POLE:
if( abs( $lat - Proj4php::$common->HALF_PI ) < $this->TOL ) {
Proj4php::reportError("stere:forward:S_POLE");
}
$y = $this->akm1 * tan( Proj4php::$common->FORTPI + .5 * $lat );
$x = $sinlam * $y;
$y *= $coslam;
break;
}
} else {
$coslam = cos( $lon );
$sinlam = sin( $lon );
$sinphi = sin( $lat );
if( $this->mode == $this->OBLIQ || $this->mode == $this->EQUIT ) {
$Xt = 2. * atan( $this->ssfn_( $lat, $sinphi, $this->e ) );
$sinX = sin( $Xt - Proj4php::$common->HALF_PI );
$cosX = cos( $Xt );
}
switch( $this->mode ) {
case $this->OBLIQ:
$A = $this->akm1 / ($this->cosX1 * (1. + $this->sinX1 * $sinX + $this->cosX1 * $cosX * $coslam));
$y = $A * ($this->cosX1 * $sinX - $this->sinX1 * $cosX * $coslam);
$x = $A * $cosX;
break;
case $this->EQUIT:
$A = 2. * $this->akm1 / (1. + $cosX * $coslam);
$y = $A * $sinX;
$x = $A * $cosX;
break;
case $this->S_POLE:
$lat = -$lat;
$coslam = - $coslam;
$sinphi = -$sinphi;
case $this->N_POLE:
$x = $this->akm1 * Proj4php::$common->tsfnz( $this->e, $lat, $sinphi );
$y = - $x * $coslam;
break;
}
$x = $x * $sinlam;
}
$p->x = $x * $this->a + $this->x0;
$p->y = $y * $this->a + $this->y0;
return $p;
}
 
 
/**
* Stereographic inverse equations--mapping x,y to lat/long
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
$x = ($p->x - $this->x0) / $this->a; /* descale and de-offset */
$y = ($p->y - $this->y0) / $this->a;
/*
$lon;
$lat;
$cosphi;
$sinphi;
$rho;
$tp = 0.0;
$phi_l = 0.0;
$i;
*/
$halfe = 0.0;
$pi2 = 0.0;
 
if( $this->sphere ) {
/*
$c;
$rh;
$sinc;
$cosc;
*/
$rh = sqrt( $x * $x + $y * $y );
$c = 2. * atan( $rh / $this->akm1 );
$sinc = sin( $c );
$cosc = cos( $c );
$lon = 0.;
switch( $this->mode ) {
case $this->EQUIT:
if( abs( $rh ) <= Proj4php::$common->EPSLN ) {
$lat = 0.;
} else {
$lat = asin( $y * $sinc / $rh );
}
if( $cosc != 0. || $x != 0. )
$lon = atan2( $x * $sinc, $cosc * $rh );
break;
case $this->OBLIQ:
if( abs( $rh ) <= Proj4php::$common->EPSLN ) {
$lat = $this->phi0;
} else {
$lat = asin( $cosc * $this->sinph0 + $y * $sinc * $this->cosph0 / $rh );
}
$c = $cosc - $this->sinph0 * sin( $lat );
if( $c != 0. || $x != 0. ) {
$lon = atan2( $x * $sinc * $this->cosph0, $c * $rh );
}
break;
case $this->N_POLE:
$y = -$y;
case $this->S_POLE:
if( abs( $rh ) <= Proj4php::$common->EPSLN ) {
$lat = $this->phi0;
} else {
$lat = asin( $this->mode == $this->S_POLE ? -$cosc : $cosc );
}
$lon = ($x == 0. && $y == 0.) ? 0. : atan2( $x, $y );
break;
}
$p->x = Proj4php::$common->adjust_lon( $lon + $this->long0 );
$p->y = $lat;
} else {
$rho = sqrt( $x * $x + $y * $y );
switch( $this->mode ) {
case $this->OBLIQ:
case $this->EQUIT:
$tp = 2. * atan2( $rho * $this->cosX1, $this->akm1 );
$cosphi = cos( $tp );
$sinphi = sin( $tp );
if( $rho == 0.0 ) {
$phi_l = asin( $cosphi * $this->sinX1 );
} else {
$phi_l = asin( $cosphi * $this->sinX1 + ($y * $sinphi * $this->cosX1 / $rho) );
}
 
$tp = tan( .5 * (Proj4php::$common->HALF_PI + $phi_l) );
$x *= $sinphi;
$y = $rho * $this->cosX1 * $cosphi - $y * $this->sinX1 * $sinphi;
$pi2 = Proj4php::$common->HALF_PI;
$halfe = .5 * $this->e;
break;
case $this->N_POLE:
$y = -$y;
case $this->S_POLE:
$tp = - $rho / $this->akm1;
$phi_l = Proj4php::$common->HALF_PI - 2. * atan( $tp );
$pi2 = -Proj4php::$common->HALF_PI;
$halfe = -.5 * $this->e;
break;
}
for( $i = $this->NITER; $i--; $phi_l = $lat ) { //check this
$sinphi = $this->e * sin( $phi_l );
$lat = 2. * atan( $tp * pow( (1. + $sinphi) / (1. - $sinphi), $halfe ) ) - $pi2;
if( abs( phi_l - lat ) < $this->CONV ) {
if( $this->mode == $this->S_POLE )
$lat = -$lat;
$lon = ($x == 0. && $y == 0.) ? 0. : atan2( $x, $y );
$p->x = Proj4php::$common->adjust_lon( $lon + $this->long0 );
$p->y = $lat;
return $p;
}
}
}
}
 
}
 
Proj4php::$proj['stere'] = new Proj4phpProjStere();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/poly.php
New file
0,0 → 1,192
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
 
 
/* Function to compute, phi4, the latitude for the inverse of the
Polyconic projection.
------------------------------------------------------------ */
function phi4z( $eccent, $e0, $e1, $e2, $e3, $a, $b, &$c, $phi ) {
/*
$sinphi;
$sin2ph;
$tanph;
$ml;
$mlp;
$con1;
$con2;
$con3;
$dphi;
$i;
*/
 
$phi = $a;
for( $i = 1; $i <= 15; $i++ ) {
$sinphi = sin( $phi );
$tanphi = tan( $phi );
$c = $tanphi * sqrt( 1.0 - $eccent * $sinphi * $sinphi );
$sin2ph = sin( 2.0 * $phi );
/*
ml = e0 * *phi - e1 * sin2ph + e2 * sin (4.0 * *phi);
mlp = e0 - 2.0 * e1 * cos (2.0 * *phi) + 4.0 * e2 * cos (4.0 * *phi);
*/
$ml = $e0 * $phi - $e1 * $sin2ph + $e2 * sin( 4.0 * $phi ) - $e3 * sin( 6.0 * $phi );
$mlp = $e0 - 2.0 * $e1 * cos( 2.0 * $phi ) + 4.0 * $e2 * cos( 4.0 * $phi ) - 6.0 * $e3 * cos( 6.0 * $phi );
$con1 = 2.0 * $ml + $c * ($ml * $ml + $b) - 2.0 * $a * ($c * $ml + 1.0);
$con2 = $eccent * $sin2ph * ($ml * $ml + $b - 2.0 * $a * $ml) / (2.0 * $c);
$con3 = 2.0 * ($a - $ml) * ($c * $mlp - 2.0 / $sin2ph) - 2.0 * $mlp;
$dphi = $con1 / ($con2 + $con3);
$phi += $dphi;
if( abs( $dphi ) <= .0000000001 )
return($phi);
}
Proj4php::reportError( "phi4z: No convergence" );
return null;
}
 
/* Function to compute the constant e4 from the input of the eccentricity
of the spheroid, x. This constant is used in the Polar Stereographic
projection.
-------------------------------------------------------------------- */
function e4fn( $x ) {
#$con;
#$com;
$con = 1.0 + $x;
$com = 1.0 - $x;
return (sqrt( (pow( $con, $con )) * (pow( $com, $com )) ));
}
 
/* * *****************************************************************************
NAME POLYCONIC
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Polyconic projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
T. Mittan Mar, 1993
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
* ***************************************************************************** */
 
class Proj4phpProjPoly {
/* Initialize the POLYCONIC projection
---------------------------------- */
public function init() {
#$temp; /* temporary variable */
if( $this->lat0 == 0 )
$this->lat0 = 90; //$this->lat0 ca
 
/* Place parameters in static storage for common use
------------------------------------------------- */
$this->temp = $this->b / $this->a;
$this->es = 1.0 - pow( $this->temp, 2 ); // devait etre dans tmerc.js mais n y est pas donc je commente sinon retour de valeurs nulles
$this->e = sqrt( $this->es );
$this->e0 = Proj4php::$common->e0fn( $this->es );
$this->e1 = Proj4php::$common->e1fn( $this->es );
$this->e2 = Proj4php::$common->e2fn( $this->es );
$this->e3 = Proj4php::$common->e3fn( $this->es );
$this->ml0 = Proj4php::$common->mlfn( $this->e0, $this->e1, $this->e2, $this->e3, $this->lat0 ); //si que des zeros le calcul ne se fait pas
//if (!$this->ml0) {$this->ml0=0;}
}
 
/* Polyconic forward equations--mapping lat,long to x,y
--------------------------------------------------- */
public function forward( $p ) {
/*
$sinphi;
$cosphi; // sin and cos value
$al; // temporary values
$c; // temporary values
$con;
$ml; // cone constant, small m
$ms; // small m
$x;
$y;
*/
$lon = $p->x;
$lat = $p->y;
 
$con = Proj4php::$common->adjust_lon( $lon - $this->long0 );
if( abs( $lat ) <= .0000001 ) {
$x = $this->x0 + $this->a * $con;
$y = $this->y0 - $this->a * $this->ml0;
} else {
$sinphi = sin( $lat );
$cosphi = cos( $lat );
$ml = Proj4php::$common->mlfn( $this->e0, $this->e1, $this->e2, $this->e3, $lat );
$ms = Proj4php::$common->msfnz( $this->e, $sinphi, $cosphi );
$x = $this->x0 + $this->a * $ms * sin( $sinphi ) / $sinphi;
$y = $this->y0 + $this->a * ($ml - $this->ml0 + $ms * (1.0 - cos( $sinphi )) / $sinphi);
}
 
$p->x = $x;
$p->y = $y;
return $p;
}
 
/* Inverse equations
----------------- */
public function inverse( $p ) {
/*
$sin_phi;
$cos_phi; // sin and cos values
$al; // temporary values
$b; // temporary values
$c; // temporary values
$con;
$ml; // cone constant, small m
$iflg; // error flag
$lon;
$lat;
*/
$p->x -= $this->x0;
$p->y -= $this->y0;
$al = $this->ml0 + $p->y / $this->a;
$iflg = 0;
 
if( abs( $al ) <= .0000001 ) {
$lon = $p->x / $this->a + $this->long0;
$lat = 0.0;
} else {
$b = $al * $al + ($p->x / $this->a) * ($p->x / $this->a);
$iflg = phi4z( $this->es, $this->e0, $this->e1, $this->e2, $this->e3, $this->al, $b, $c, $lat );
if( $iflg != 1 )
return($iflg);
$lon = Proj4php::$common->adjust_lon( (Proj4php::$common->asinz( $p->x * $c / $this->a ) / sin( $lat )) + $this->long0 );
}
 
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
}
 
Proj4php::$proj['poly'] = new Proj4phpProjPoly();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/sterea.php
New file
0,0 → 1,91
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class Proj4phpProjSterea {
 
protected $dependsOn = 'gauss';
/**
*
* @return void
*/
public function init() {
if( !$this->rc ) {
Proj4php::reportError( "sterea:init:E_ERROR_0" );
return;
}
$this->sinc0 = sin( $this->phic0 );
$this->cosc0 = cos( $this->phic0 );
$this->R2 = 2.0 * $this->rc;
if( !$this->title )
$this->title = "Oblique Stereographic Alternative";
}
 
/**
*
* @param type $p
* @return type
*/
public function forward( $p ) {
$p->x = Proj4php::$common->adjust_lon( $p->x - $this->long0 ); /* adjust del longitude */
$p = Proj4php::$proj['gauss']->forward( $p );
$sinc = sin( $p->y );
$cosc = cos( $p->y );
$cosl = cos( $p->x );
$k = $this->k0 * $this->R2 / (1.0 + $this->sinc0 * $sinc + $this->cosc0 * $cosc * $cosl);
$p->x = $k * $cosc * sin( $p->x );
$p->y = $k * ($this->cosc0 * sinc - $this->sinc0 * $cosc * $cosl);
$p->x = $this->a * $p->x + $this->x0;
$p->y = $this->a * $p->y + $this->y0;
return $p;
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
#$lon;
#$lat;
$p->x = ($p->x - $this->x0) / $this->a; /* descale and de-offset */
$p->y = ($p->y - $this->y0) / $this->a;
 
$p->x /= $this->k0;
$p->y /= $this->k0;
if( ($rho = sqrt( $p->x * $p->x + $p->y * $p->y ) ) ) {
$c = 2.0 * atan2( $rho, $this->R2 );
$sinc = sin( $c );
$cosc = cos( $c );
$lat = asin( $cosc * $this->sinc0 + $p->y * $sinc * $this->cosc0 / $rho );
$lon = atan2( $p->x * $sinc, $rho * $this->cosc0 * $cosc - $p->y * $this->sinc0 * $sinc );
} else {
$lat = $this->phic0;
$lon = 0.;
}
 
$p->x = $lon;
$p->y = $lat;
$p = Proj4php::$proj['gauss']->inverse( $p );
$p->x = Proj4php::$common->adjust_lon( $p->x + $this->long0 ); /* adjust longitude to CM */
return $p;
}
 
}
 
Proj4php::$proj['sterea'] = new Proj4phpProjSterea();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/merc.php
New file
0,0 → 1,129
<?php
 
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/* * *****************************************************************************
NAME MERCATOR
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Mercator projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
D. Steinwand, EROS Nov, 1991
T. Mittan Mar, 1993
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
* ***************************************************************************** */
 
//static double r_major = a; /* major axis */
//static double r_minor = b; /* minor axis */
//static double lon_center = long0; /* Center longitude (projection center) */
//static double lat_origin = lat0; /* center latitude */
//static double e,es; /* eccentricity constants */
//static double m1; /* small value m */
//static double false_northing = y0; /* y offset in meters */
//static double false_easting = x0; /* x offset in meters */
//scale_fact = k0
 
class Proj4phpProjMerc {
 
public function init() {
//?$this->temp = $this->r_minor / $this->r_major;
//$this->temp = $this->b / $this->a;
//$this->es = 1.0 - sqrt($this->temp);
//$this->e = sqrt( $this->es );
//?$this->m1 = cos($this->lat_origin) / (sqrt( 1.0 - $this->es * sin($this->lat_origin) * sin($this->lat_origin)));
//$this->m1 = cos(0.0) / (sqrt( 1.0 - $this->es * sin(0.0) * sin(0.0)));
if( $this->lat_ts ) {
if( $this->sphere ) {
$this->k0 = cos( $this->lat_ts );
} else {
$this->k0 = Proj4php::$common->msfnz( $this->es, sin( $this->lat_ts ), cos( $this->lat_ts ) );
}
}
}
 
/* Mercator forward equations--mapping lat,long to x,y
-------------------------------------------------- */
 
public function forward( $p ) {
//alert("ll2m coords : ".coords);
$lon = $p->x;
$lat = $p->y;
// convert to radians
if( $lat * Proj4php::$common->R2D > 90.0 &&
$lat * Proj4php::$common->R2D < -90.0 &&
$lon * Proj4php::$common->R2D > 180.0 &&
$lon * Proj4php::$common->R2D < -180.0 ) {
Proj4php::reportError( "merc:forward: llInputOutOfRange: " . $lon . " : " . $lat );
return null;
}
if( abs( abs( $lat ) - Proj4php::$common->HALF_PI ) <= Proj4php::$common->EPSLN ) {
Proj4php::reportError( "merc:forward: ll2mAtPoles" );
return null;
} else {
if( $this->sphere ) {
$x = $this->x0 + $this->a * $this->k0 * Proj4php::$common->adjust_lon( $lon - $this->long0 );
$y = $this->y0 + $this->a * $this->k0 * log( tan( Proj4php::$common->FORTPI + 0.5 * $lat ) );
} else {
$sinphi = sin( lat );
$ts = Proj4php::$common . tsfnz( $this->e, $lat, $sinphi );
$x = $this->x0 + $this->a * $this->k0 * Proj4php::$common->adjust_lon( $lon - $this->long0 );
$y = $this->y0 - $this->a * $this->k0 * log( $ts );
}
$p->x = $x;
$p->y = $y;
return $p;
}
}
 
/* Mercator inverse equations--mapping x,y to lat/long
-------------------------------------------------- */
 
public function inverse( $p ) {
 
$x = $p->x - $this->x0;
$y = $p->y - $this->y0;
if( $this->sphere ) {
$lat = Proj4php::$common->HALF_PI - 2.0 * atan( exp( -$y / $this->a * $this->k0 ) );
} else {
$ts = exp( -$y / ($this->a * $this->k0) );
$lat = Proj4php::$common->phi2z( $this->e, $ts );
if( $lat == -9999 ) {
Proj4php::reportError( "merc:inverse: lat = -9999" );
return null;
}
}
$lon = Proj4php::$common->adjust_lon( $this->long0 + $x / ($this->a * $this->k0) );
 
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
}
 
Proj4php::$proj['merc'] = new Proj4phpProjMerc();
 
 
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/aea.php
New file
0,0 → 1,184
<?php
/*******************************************************************************
NAME ALBERS CONICAL EQUAL AREA
 
PURPOSE: Transforms input longitude and latitude to Easting and Northing
for the Albers Conical Equal Area projection. The longitude
and latitude must be in radians. The Easting and Northing
values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
T. Mittan, Feb, 1992
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
*******************************************************************************/
 
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class Proj4phpProjAea {
 
/**
*
* @return void
*/
public function init() {
 
if( abs( $this->lat1 + $this->lat2 ) < Proj4php::$common->EPSLN ) {
Proj4php::reportError( "aeaInitEqualLatitudes" );
return;
}
$this->temp = $this->b / $this->a;
$this->es = 1.0 - pow( $this->temp, 2 );
$this->e3 = sqrt( $this->es );
 
$this->sin_po = sin( $this->lat1 );
$this->cos_po = cos( $this->lat1 );
$this->t1 = $this->sin_po;
$this->con = $this->sin_po;
$this->ms1 = Proj4php::$common->msfnz( $this->e3, $this->sin_po, $this->cos_po );
$this->qs1 = Proj4php::$common->qsfnz( $this->e3, $this->sin_po, $this->cos_po );
 
$this->sin_po = sin( $this->lat2 );
$this->cos_po = cos( $this->lat2 );
$this->t2 = $this->sin_po;
$this->ms2 = Proj4php::$common->msfnz( $this->e3, $this->sin_po, $this->cos_po );
$this->qs2 = Proj4php::$common->qsfnz( $this->e3, $this->sin_po, $this->cos_po );
 
$this->sin_po = sin( $this->lat0 );
$this->cos_po = cos( $this->lat0 );
$this->t3 = $this->sin_po;
$this->qs0 = Proj4php::$common->qsfnz( $this->e3, $this->sin_po, $this->cos_po );
 
if( abs( $this->lat1 - $this->lat2 ) > Proj4php::$common->EPSLN ) {
$this->ns0 = ($this->ms1 * $this->ms1 - $this->ms2 * $this->ms2) / ($this->qs2 - $this->qs1);
} else {
$this->ns0 = $this->con;
}
$this->c = $this->ms1 * $this->ms1 + $this->ns0 * $this->qs1;
$this->rh = $this->a * sqrt( $this->c - $this->ns0 * $this->qs0 ) / $this->ns0;
}
 
/**
* Albers Conical Equal Area forward equations--mapping lat,long to x,y
*
* @param Point $p
* @return Point $p
*/
public function forward( $p ) {
 
$lon = $p->x;
$lat = $p->y;
 
$this->sin_phi = sin( $lat );
$this->cos_phi = cos( $lat );
 
$qs = Proj4php::$common->qsfnz( $this->e3, $this->sin_phi, $this->cos_phi );
$rh1 = $this->a * sqrt( $this->c - $this->ns0 * $qs ) / $this->ns0;
$theta = $this->ns0 * Proj4php::$common->adjust_lon( $lon - $this->long0 );
$x = rh1 * sin( $theta ) + $this->x0;
$y = $this->rh - $rh1 * cos( $theta ) + $this->y0;
 
$p->x = $x;
$p->y = $y;
return $p;
}
 
/**
*
* @param Point $p
* @return Point $p
*/
public function inverse( $p ) {
$p->x -= $this->x0;
$p->y = $this->rh - $p->y + $this->y0;
if( $this->ns0 >= 0 ) {
$rh1 = sqrt( $p->x * $p->x + $p->y * $p->y );
$con = 1.0;
} else {
$rh1 = -sqrt( $p->x * $p->x + $p->y * $p->y );
$con = -1.0;
}
$theta = 0.0;
if( $rh1 != 0.0 ) {
$theta = atan2( $con * $p->x, $con * $p->y );
}
$con = $rh1 * $this->ns0 / $this->a;
$qs = ($this->c - $con * $con) / $this->ns0;
if( $this->e3 >= 1e-10 ) {
$con = 1 - .5 * (1.0 - $this->es) * log( (1.0 - $this->e3) / (1.0 + $this->e3) ) / $this->e3;
if( abs( abs( $con ) - abs( $qs ) ) > .0000000001 ) {
$lat = $this->phi1z( $this->e3, $qs );
} else {
if( $qs >= 0 ) {
$lat = .5 * Proj4php::$Common->PI;
} else {
$lat = -.5 * Proj4php::$Common->PI;
}
}
} else {
$lat = $this->phi1z( $this->e3, $qs );
}
 
$lon = Proj4php::$common->adjust_lon( $theta / $this->ns0 + $this->long0 );
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
/**
* Function to compute phi1, the latitude for the inverse of the Albers Conical Equal-Area projection.
*
* @param type $eccent
* @param type $qs
* @return $phi or null on Convergence error
*/
public function phi1z( $eccent, $qs ) {
$phi = Proj4php::$common->asinz( .5 * $qs );
if( $eccent < Proj4php::$common->EPSLN )
return $phi;
 
$eccnts = $eccent * $eccent;
for( $i = 1; $i <= 25; ++$i ) {
$sinphi = sin( $phi );
$cosphi = cos( $phi );
$con = $eccent * $sinphi;
$com = 1.0 - $con * $con;
$dphi = .5 * $com * $com / $cosphi * ($qs / (1.0 - $eccnts) - $sinphi / $com + .5 / $eccent * log( (1.0 - $con) / (1.0 + $con) ));
$phi = $phi + $dphi;
if( abs( $dphi ) <= 1e-7 )
return $phi;
}
Proj4php::reportError( "aea:phi1z:Convergence error" );
return null;
}
 
}
 
Proj4php::$proj['aea'] = new Proj4phpProjAea();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/somerc.php
New file
0,0 → 1,135
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME SWISS OBLIQUE MERCATOR
 
PURPOSE: Swiss projection.
WARNING: X and Y are inverted (weird) in the swiss coordinate system. Not
here, since we want X to be horizontal and Y vertical.
 
ALGORITHM REFERENCES
1. "Formules et constantes pour le Calcul pour la
projection cylindrique conforme à axe oblique et pour la transformation entre
des systèmes de référence".
http://www.swisstopo.admin.ch/internet/swisstopo/fr/home/topics/survey/sys/refsys/switzerland.parsysrelated1.31216.downloadList.77004.DownloadFile.tmp/swissprojectionfr.pdf
 
*******************************************************************************/
 
class Proj4phpProjSomerc {
 
/**
*
*/
public function init() {
$phy0 = $this->lat0;
$this->lambda0 = $this->long0;
$sinPhy0 = sin( $phy0 );
$semiMajorAxis = $this->a;
$invF = $this->rf;
$flattening = 1 / $invF;
$e2 = 2 * $flattening - pow( $flattening, 2 );
$e = $this->e = sqrt( $e2 );
$this->R = $this->k0 * $semiMajorAxis * sqrt( 1 - $e2 ) / (1 - $e2 * pow( $sinPhy0, 2.0 ));
$this->alpha = sqrt( 1 + $e2 / (1 - $e2) * pow( cos( $phy0 ), 4.0 ) );
$this->b0 = asin( $sinPhy0 / $this->alpha );
$this->K = log( tan( $PI / 4.0 + $this->b0 / 2.0 ) )
- $this->alpha
* log( tan( $PI / 4.0 + $phy0 / 2.0 ) )
+ $this->alpha
* $e / 2
* log( (1 + $e * $sinPhy0)
/ (1 - $e * $sinPhy0) );
}
 
/**
*
* @param type $p
* @return type
*/
public function forward( $p ) {
$Sa1 = log( tan( $PI / 4.0 - $p->y / 2.0 ) );
$Sa2 = $this->e / 2.0
* log( (1 + $this->e * sin( $p->y ))
/ (1 - $this->e * sin( $p->y )) );
$S = -$this->alpha * ($Sa1 + $Sa2) + $this->K;
 
// spheric latitude
$b = 2.0 * (atan( exp( $S ) ) - proj4phpCommon::PI / 4.0);
 
// spheric longitude
$I = $this->alpha * ($p->x - $this->lambda0);
 
// psoeudo equatorial rotation
$rotI = atan( sin( $I )
/ (sin( $this->b0 ) * tan( $b ) +
cos( $this->b0 ) * cos( $I )) );
 
$rotB = asin( cos( $this->b0 ) * sin( $b ) -
sin( $this->b0 ) * cos( $b ) * cos( $I ) );
 
$p->y = $this->R / 2.0
* log( (1 + sin( $rotB )) / (1 - sin( $rotB )) )
+ $this->y0;
$p->x = $this->R * $rotI + $this->x0;
return $p;
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
$Y = $p->x - $this->x0;
$X = $p->y - $this->y0;
 
$rotI = $Y / $this->R;
$rotB = 2 * (atan( exp( $X / $this->R ) ) - $PI / 4.0);
 
$b = asin( cos( $this->b0 ) * sin( $rotB )
+ sin( $this->b0 ) * cos( $rotB ) * cos( $rotI ) );
$I = atan( sin( $rotI )
/ (cos( $this->b0 ) * cos( $rotI ) - sin( $this->b0 )
* tan( $rotB )) );
 
$lambda = $this->lambda0 + $I / $this->alpha;
 
$S = 0.0;
$phy = $b;
$prevPhy = -1000.0;
$iteration = 0;
while( abs( $phy - $prevPhy ) > 0.0000001 ) {
if( ++$iteration > 20 ) {
Proj4php::reportError( "omercFwdInfinity" );
return;
}
//S = log(tan(PI / 4.0 + phy / 2.0));
$S = 1.0
/ $this->alpha
* (log( tan( $PI / 4.0 + $b / 2.0 ) ) - $this->K)
+ $this->e
* log( tan( $PI / 4.0
+ asin( $this->e * sin( $phy ) )
/ 2.0 ) );
$prevPhy = $phy;
$phy = 2.0 * atan( exp( $S ) ) - $PI / 2.0;
}
 
$p->x = $lambda;
$p->y = $phy;
return $p;
}
 
}
 
Proj4php::$proj['somerc'] = new Proj4phpProjSomerc();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/cea.php
New file
0,0 → 1,97
<?php
/*******************************************************************************
NAME LAMBERT CYLINDRICAL EQUAL AREA
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Lambert Cylindrical Equal Area projection.
This class of projection includes the Behrmann and
Gall-Peters Projections. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
R. Marsden August 2009
Winwaed Software Tech LLC, http://www.winwaed.com
 
This function was adapted from the Miller Cylindrical Projection in the Proj4php
library.
 
Note: This implementation assumes a Spherical Earth. The (commented) code
has been included for the ellipsoidal forward transform, but derivation of
the ellispoidal inverse transform is beyond me. Note that most of the
Proj4php implementations do NOT currently support ellipsoidal figures.
Therefore this is not seen as a problem - especially this lack of support
is explicitly stated here.
 
ALGORITHM REFERENCES
 
1. "Cartographic Projection Procedures for the UNIX Environment -
A User's Manual" by Gerald I. Evenden, USGS Open File Report 90-284
and Release 4 Interim Reports (2003)
 
2. Snyder, John P., "Flattening the Earth - Two Thousand Years of Map
Projections", Univ. Chicago Press, 1993
****************************************************************************** */
 
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class Proj4phpProjCea {
/* Initialize the Cylindrical Equal Area projection
------------------------------------------- */
 
public function init() {
//no-op
}
 
/* Cylindrical Equal Area forward equations--mapping lat,long to x,y
------------------------------------------------------------ */
public function forward( $p ) {
$lon = $p->x;
$lat = $p->y;
/* Forward equations
----------------- */
$dlon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
$x = $this->x0 + $this->a * $dlon * cos( $this->lat_ts );
$y = $this->y0 + $this->a * sin( $lat ) / cos( $this->lat_ts );
/* Elliptical Forward Transform
Not implemented due to a lack of a matchign inverse function
{
$Sin_Lat = sin(lat);
$Rn = $this->a * (sqrt(1.0e0 - $this->es * Sin_Lat * Sin_Lat ));
x = $this->x0 + $this->a * dlon * cos($this->lat_ts);
y = $this->y0 + Rn * sin(lat) / cos($this->lat_ts);
}
*/
 
$p->x = $x;
$p->y = $y;
return $p;
}
 
/**
* Cylindrical Equal Area inverse equations--mapping x,y to lat/long
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
$p->x -= $this->x0;
$p->y -= $this->y0;
 
$p->x = Proj4php::$common->adjust_lon( $this->long0 + ($p->x / $this->a) / cos( $this->lat_ts ) );
$p->y = asin( ($p->y / $this->a) * cos( $this->lat_ts ) );
return $p;
}
}
 
Proj4php::$proj['cea'] = new Proj4phpProjCea();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/cass.php
New file
0,0 → 1,118
<?php
 
/*******************************************************************************
NAME CASSINI
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Cassini projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
Ported from PROJ.4.
 
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
****************************************************************************** */
 
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
//Proj4php.defs["EPSG:28191"] = "+proj=cass +lat_0=31.73409694444445 +lon_0=35.21208055555556 +x_0=170251.555 +y_0=126867.909 +a=6378300.789 +b=6356566.435 +towgs84=-275.722,94.7824,340.894,-8.001,-4.42,-11.821,1 +units=m +no_defs";
// Initialize the Cassini projection
// -----------------------------------------------------------------
 
class Proj4phpProjCass {
 
public function init() {
if( !$this->sphere ) {
$this->en = Proj4php::$common->pj_enfn( $this->es );
$this->m0 = Proj4php::$common->pj_mlfn( $this->lat0, sin( $this->lat0 ), cos( $this->lat0 ), $this->en );
}
}
 
protected $C1 = .16666666666666666666;
protected $C2 = .00833333333333333333;
protected $C3 = .04166666666666666666;
protected $C4 = .33333333333333333333;
protected $C5 = .06666666666666666666;
 
/* Cassini forward equations--mapping lat,long to x,y
----------------------------------------------------------------------- */
public function forward( $p ) {
 
/* Forward equations
----------------- */
#$x;
#$y;
$lam = $p->x;
$phi = $p->y;
$lam = Proj4php::$common->adjust_lon( $lam - $this->long0 );
 
if( $this->sphere ) {
$x = asin( cos( $phi ) * sin( $lam ) );
$y = atan2( tan( $phi ), cos( $lam ) ) - $this->phi0;
} else {
//ellipsoid
$this->n = sin( $phi );
$this->c = cos( $phi );
$y = $this->pj_mlfn( $phi, $this->n, $this->c, $this->en );
$this->n = 1. / sqrt( 1. - $this->es * $this->n * $this->n );
$this->tn = tan( $phi );
$this->t = $this->tn * $this->tn;
$this->a1 = $lam * $this->c;
$this->c *= $this->es * $this->c / (1 - $this->es);
$this->a2 = $this->a1 * $this->a1;
$x = $this->n * $this->a1 * (1. - $this->a2 * $this->t * ($this->C1 - (8. - $this->t + 8. * $this->c) * $this->a2 * $this->C2));
$y -= $this->m0 - $this->n * $this->tn * $this->a2 * (.5 + (5. - $this->t + 6. * $this->c) * $this->a2 * $this->C3);
}
 
$p->x = $this->a * $x + $this->x0;
$p->y = $this->a * $y + $this->y0;
return $p;
}
 
/* Inverse equations
----------------- */
public function inverse( $p ) {
$p->x -= $this->x0;
$p->y -= $this->y0;
$x = $p->x / $this->a;
$y = $p->y / $this->a;
 
if( $this->sphere ) {
$this->dd = $y + $this->lat0;
$phi = asin( sin( $this->dd ) * cos( $x ) );
$lam = atan2( tan( $x ), cos( $this->dd ) );
} else {
/* ellipsoid */
$ph1 = Proj4php::$common->pj_inv_mlfn( $this->m0 + $y, $this->es, $this->en );
$this->tn = tan( $ph1 );
$this->t = $this->tn * $this->tn;
$this->n = sin( $ph1 );
$this->r = 1. / (1. - $this->es * $this->n * $this->n);
$this->n = sqrt( $this->r );
$this->r *= (1. - $this->es) * $this->n;
$this->dd = $x / $this->n;
$this->d2 = $this->dd * $this->dd;
$phi = $ph1 - ($this->n * $this->tn / $this->r) * $this->d2 * (.5 - (1. + 3. * $this->t) * $this->d2 * $this->C3);
$lam = $this->dd * (1. + $this->t * $this->d2 * (-$this->C4 + (1. + 3. * $this->t) * $this->d2 * $this->C5)) / cos( $ph1 );
}
$p->x = Proj4php::$common->adjust_lon( $this->long0 + $lam );
$p->y = $phi;
return $p;
}
}
 
Proj4php::$proj['cass'] = new Proj4phpProjCass();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/ortho.php
New file
0,0 → 1,139
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/* * *****************************************************************************
NAME ORTHOGRAPHIC
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Orthographic projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
T. Mittan Mar, 1993
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
* ***************************************************************************** */
 
class Proj4phpProjOrtho {
/* Initialize the Orthographic projection
------------------------------------- */
public function init( $def ) {
//double temp; /* temporary variable */
 
/* Place parameters in static storage for common use
------------------------------------------------- */;
$this->sin_p14 = sin( $this->lat0 );
$this->cos_p14 = cos( $this->lat0 );
}
 
/* Orthographic forward equations--mapping lat,long to x,y
--------------------------------------------------- */
public function forward( $p ) {
/*
$sinphi;
$cosphi; // sin and cos value
$dlon; // delta longitude value
$coslon; // cos of longitude
$ksp; // scale factor
$g;
*/
$lon = $p->x;
$lat = $p->y;
/* Forward equations
----------------- */
$dlon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
 
$sinphi = sin( $lat );
$cosphi = cos( $lat );
 
$coslon = cos( $dlon );
$g = $this->sin_p14 * sinphi + $this->cos_p14 * $cosphi * $coslon;
$ksp = 1.0;
if( ($g > 0) || (abs( $g ) <= Proj4php::$common->EPSLN) ) {
$x = $this->a * $ksp * $cosphi * sin( $dlon );
$y = $this->y0 + $this->a * $ksp * ($this->cos_p14 * $sinphi - $this->sin_p14 * $cosphi * $coslon);
} else {
Proj4php::reportError( "orthoFwdPointError" );
}
$p->x = $x;
$p->y = $y;
return $p;
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
/*
$rh; // height above ellipsoid
$z; // angle
$sinz;
$cosz; // sin of z and cos of z
$temp;
$con;
$lon;
$lat;
*/
/* Inverse equations
----------------- */
$p->x -= $this->x0;
$p->y -= $this->y0;
$rh = sqrt( $p->x * $p->x + $p->y * $p->y );
if( $rh > $this->a + .0000001 ) {
Proj4php::reportError( "orthoInvDataError" );
}
$z = Proj4php::$common . asinz( $rh / $this->a );
 
$sinz = sin( $z );
$cosz = cos( $z );
 
$lon = $this->long0;
if( abs( $rh ) <= Proj4php::$common->EPSLN ) {
$lat = $this->lat0;
}
$lat = Proj4php::$common . asinz( $cosz * $this->sin_p14 + ($p->y * $sinz * $this->cos_p14) / $rh );
$con = abs( $this->lat0 ) - Proj4php::$common->HALF_PI;
if( abs( con ) <= Proj4php::$common->EPSLN ) {
if( $this->lat0 >= 0 ) {
$lon = Proj4php::$common->adjust_lon( $this->long0 + atan2( $p->x, -$p->y ) );
} else {
$lon = Proj4php::$common->adjust_lon( $this->long0 - atan2( -$p->x, $p->y ) );
}
}
$con = $cosz - $this->sin_p14 * sin( $lat );
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
}
 
Proj4php::$proj['ortho'] = new Proj4phpProjOrtho();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/krovak.php
New file
0,0 → 1,156
<?php
 
/**
NOTES: According to EPSG the full Krovak projection method should have
the following parameters. Within PROJ.4 the azimuth, and pseudo
standard parallel are hardcoded in the algorithm and can't be
altered from outside. The others all have defaults to match the
common usage with Krovak projection.
 
lat_0 = latitude of centre of the projection
 
lon_0 = longitude of centre of the projection
 
* * = azimuth (true) of the centre line passing through the centre of the projection
 
* * = latitude of pseudo standard parallel
 
k = scale factor on the pseudo standard parallel
 
x_0 = False Easting of the centre of the projection at the apex of the cone
 
y_0 = False Northing of the centre of the projection at the apex of the cone
 
**/
class Proj4phpProjKrovak {
 
/**
*
*/
public function init() {
/* we want Bessel as fixed ellipsoid */
$this->a = 6377397.155;
$this->es = 0.006674372230614;
$this->e = sqrt( $this->es );
/* if latitude of projection center is not set, use 49d30'N */
if( !$this->lat0 ) {
$this->lat0 = 0.863937979737193;
}
if( !$this->long0 ) {
$this->long0 = 0.7417649320975901 - 0.308341501185665;
}
/* if scale not set default to 0.9999 */
if( !$this->k0 ) {
$this->k0 = 0.9999;
}
$this->s45 = 0.785398163397448; /* 45° */
$this->s90 = 2 * $this->s45;
$this->fi0 = $this->lat0; /* Latitude of projection centre 49° 30' */
/* Ellipsoid Bessel 1841 a = 6377397.155m 1/f = 299.1528128,
e2=0.006674372230614;
*/
$this->e2 = $this->es; /* 0.006674372230614; */
$this->e = sqrt( $this->e2 );
$this->alfa = sqrt( 1. + ($this->e2 * pow( cos( $this->fi0 ), 4 )) / (1. - $this->e2) );
$this->uq = 1.04216856380474; /* DU(2, 59, 42, 42.69689) */
$this->u0 = asin( sin( $this->fi0 ) / $this->alfa );
$this->g = pow( (1. + $this->e * sin( $this->fi0 )) / (1. - $this->e * sin( $this->fi0 )), $this->alfa * $this->e / 2. );
$this->k = tan( $this->u0 / 2. + $this->s45 ) / pow( tan( $this->fi0 / 2. + $this->s45 ), $this->alfa ) * $this->g;
$this->k1 = $this->k0;
$this->n0 = $this->a * sqrt( 1. - $this->e2 ) / (1. - $this->e2 * pow( sin( $this->fi0 ), 2 ));
$this->s0 = 1.37008346281555; /* Latitude of pseudo standard parallel 78° 30'00" N */
$this->n = sin( $this->s0 );
$this->ro0 = $this->k1 * $this->n0 / tan( $this->s0 );
$this->ad = $this->s90 - $this->uq;
}
/**
* ellipsoid
* calculate xy from lat/lon
* Constants, identical to inverse transform function
*
* @param type $p
* @return type
*/
public function forward( $p ) {
$lon = $p->x;
$lat = $p->y;
$delta_lon = Proj4php::$common->adjust_lon( $lon - $this->long0 ); // Delta longitude
/* Transformation */
$gfi = pow( ((1. + $this->e * sin( $lat )) / (1. - $this->e * sin( $lat )) ), ($this->alfa * $this->e / 2. ) );
$u = 2. * (atan( $this->k * pow( tan( $lat / 2. + $this->s45 ), $this->alfa ) / $gfi ) - $this->s45);
$deltav = - $delta_lon * $this->alfa;
$s = asin( cos( $this->ad ) * sin( $u ) + sin( $this->ad ) * cos( $u ) * cos( $deltav ) );
$d = asin( cos( $u ) * sin( $deltav ) / cos( $s ) );
$eps = $this->n * $d;
$ro = $this->ro0 * pow( tan( $this->s0 / 2. + $this->s45 ), $this->n ) / pow( tan( $s / 2. + $this->s45 ), $this->n );
/* x and y are reverted! */
//$p->y = ro * cos(eps) / a;
//$p->x = ro * sin(eps) / a;
$p->y = $ro * cos( $eps ) / 1.0;
$p->x = $ro * sin( $eps ) / 1.0;
 
if( $this->czech ) {
$p->y *= -1.0;
$p->x *= -1.0;
}
return $p;
}
/**
* calculate lat/lon from xy
*
* @param Point $p
* @return Point $p
*/
public function inverse( $p ) {
/* Transformation */
/* revert y, x */
$tmp = $p->x;
$p->x = $p->y;
$p->y = $tmp;
if( $this->czech ) {
$p->y *= -1.0;
$p->x *= -1.0;
}
$ro = sqrt( $p->x * $p->x + $p->y * $p->y );
$eps = atan2( $p->y, $p->x );
$d = $eps / sin( $this->s0 );
$s = 2. * (atan( pow( $this->ro0 / $ro, 1. / $this->n ) * tan( $this->s0 / 2. + $this->s45 ) ) - $this->s45);
$u = asin( cos( $this->ad ) * sin( s ) - sin( $this->ad ) * cos( s ) * cos( d ) );
$deltav = asin( cos( $s ) * sin( $d ) / cos( $u ) );
$p->x = $this->long0 - $deltav / $this->alfa;
/* ITERATION FOR $lat */
$fi1 = $u;
$ok = 0;
$iter = 0;
do {
$p->y = 2. * ( atan( pow( $this->k, -1. / $this->alfa ) *
pow( tan( $u / 2. + $this->s45 ), 1. / $this->alfa ) *
pow( (1. + $this->e * sin( $fi1 )) / (1. - $this->e * sin( $fi1 )), $this->e / 2. )
) - $this->s45);
if( abs( $fi1 - $p->y ) < 0.0000000001 )
$ok = 1;
$fi1 = $p->y;
$iter += 1;
} while( $ok == 0 && $iter < 15 );
if( $iter >= 15 ) {
Proj4php::reportError( "PHI3Z-CONV:Latitude failed to converge after 15 iterations" );
//console.log('iter:', iter);
return null;
}
 
return $p;
}
 
}
 
Proj4php::$proj['krovak'] = new Proj4phpProjKrovak();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/mill.php
New file
0,0 → 1,82
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME MILLER CYLINDRICAL
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Miller Cylindrical projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
T. Mittan March, 1993
 
This function was adapted from the Lambert Azimuthal Equal Area projection
code (FORTRAN) in the General Cartographic Transformation Package software
which is available from the U.S. Geological Survey National Mapping Division.
 
ALGORITHM REFERENCES
 
1. "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
 
2. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
3. "Software Documentation for GCTP General Cartographic Transformation
Package", U.S. Geological Survey National Mapping Division, May 1982.
* ***************************************************************************** */
 
class Proj4phpProjMill {
/* Initialize the Miller Cylindrical projection
------------------------------------------- */
 
public function init() {
//no-op
}
 
/* Miller Cylindrical forward equations--mapping lat,long to x,y
------------------------------------------------------------ */
public function forward( $p ) {
$lon = $p->x;
$lat = $p->y;
/* Forward equations
----------------- */
$dlon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
$x = $this->x0 + $this->a * $dlon;
$y = $this->y0 + $this->a * log( tan( (Proj4php::$common->PI / 4.0) + ($lat / 2.5) ) ) * 1.25;
 
$p->x = $x;
$p->y = $y;
return $p;
}
 
/* Miller Cylindrical inverse equations--mapping x,y to lat/long
------------------------------------------------------------ */
public function inverse( $p ) {
$p->x -= $this->x0;
$p->y -= $this->y0;
 
$lon = Proj4php::$common->adjust_lon( $this->long0 + $p->x / $this->a );
$lat = 2.5 * (atan( exp( 0.8 * $p->y / $this->a ) ) - Proj4php::$common->PI / 4.0);
 
$p->x = $lon;
$p->y = $lat;
return $p;
}
}
 
Proj4php::$proj['mill'] = new Proj4phpProjMill();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/vandg.php
New file
0,0 → 1,167
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME VAN DER GRINTEN
 
PURPOSE: Transforms input Easting and Northing to longitude and
latitude for the Van der Grinten projection. The
Easting and Northing must be in meters. The longitude
and latitude values will be returned in radians.
 
PROGRAMMER DATE
---------- ----
T. Mittan March, 1993
 
This function was adapted from the Van Der Grinten projection code
(FORTRAN) in the General Cartographic Transformation Package software
which is available from the U.S. Geological Survey National Mapping Division.
 
ALGORITHM REFERENCES
 
1. "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
 
2. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
3. "Software Documentation for GCTP General Cartographic Transformation
Package", U.S. Geological Survey National Mapping Division, May 1982.
* ***************************************************************************** */
 
class Proj4phpProjVandg {
/* Initialize the Van Der Grinten projection
---------------------------------------- */
public function init() {
$this->R = 6370997.0; //Radius of earth
}
 
/**
*
* @param type $p
* @return type
*/
public function forward( $p ) {
 
$lon = $p->x;
$lat = $p->y;
 
/* Forward equations
----------------- */
$dlon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
$x;
$y;
 
if( abs( $lat ) <= Proj4php::$common->EPSLN ) {
$x = $this->x0 + $this->R * $dlon;
$y = $this->y0;
}
$theta = Proj4php::$common . asinz( 2.0 * abs( $lat / Proj4php::$common->PI ) );
if( (abs( $dlon ) <= Proj4php::$common->EPSLN) || (abs( abs( $lat ) - Proj4php::$common->HALF_PI ) <= Proj4php::$common->EPSLN) ) {
$x = $this->x0;
if( $lat >= 0 ) {
$y = $this->y0 + Proj4php::$common->PI * $this->R * tan( .5 * $theta );
} else {
$y = $this->y0 + Proj4php::$common->PI * $this->R * - tan( .5 * $theta );
}
// return(OK);
}
$al = .5 * abs( (Proj4php::$common->PI / $dlon) - ($dlon / Proj4php::$common->PI) );
$asq = $al * $al;
$sinth = sin( $theta );
$costh = cos( $theta );
 
$g = $costh / ($sinth + $costh - 1.0);
$gsq = $g * $g;
$m = $g * (2.0 / $sinth - 1.0);
$msq = $m * $m;
$con = Proj4php::$common->PI * $this->R * ($al * ($g - $msq) + sqrt( $asq * ($g - $sq) * ($g - $msq) - ($msq + $asq) * ($gsq - $msq) )) / ($msq + $asq);
if( $dlon < 0 ) {
$con = -$con;
}
$x = $this->x0 + $con;
$con = abs( $con / (Proj4php::$common->PI * $this->R) );
if( $lat >= 0 ) {
$y = $this->y0 + Proj4php::$common->PI * $this->R * sqrt( 1.0 - $con * $con - 2.0 * $al * $con );
} else {
$y = $this->y0 - Proj4php::$common->PI * $this->R * sqrt( 1.0 - $con * $con - 2.0 * $al * $con );
}
$p->x = $x;
$p->y = $y;
return $p;
}
 
/* Van Der Grinten inverse equations--mapping x,y to lat/long
--------------------------------------------------------- */
 
public function inverse( $p ) {
/*
$dlon;
$xx;
$yy;
$xys;
$c1;
$c2;
$c3;
$al;
$asq;
$a1;
$m1;
$con;
$th1;
$d;
*/
/* inverse equations
----------------- */
$p->x -= $this->x0;
$p->y -= $this->y0;
$con = Proj4php::$common->PI * $this->R;
$xx = $p->x / $con;
$yy = $p->y / $con;
$xys = $xx * $xx + $yy * $yy;
$c1 = -abs( $yy ) * (1.0 + $xys);
$c2 = $c1 - 2.0 * $yy * $yy + $xx * $xx;
$c3 = -2.0 * $c1 + 1.0 + 2.0 * $yy * $yy + $xys * $xys;
$d = $yy * $yy / $c3 + (2.0 * $c2 * $c2 * $c2 / $c3 / $c3 / $c3 - 9.0 * $c1 * $c2 / $c3 / $c3) / 27.0;
$a1 = ($c1 - $c2 * $c2 / 3.0 / $c3) / $c3;
$m1 = 2.0 * sqrt( -$a1 / 3.0 );
$con = ((3.0 * $d) / $a1) / $m1;
if( abs( $con ) > 1.0 ) {
if( $con >= 0.0 ) {
$con = 1.0;
} else {
$con = -1.0;
}
}
$th1 = acos( $con ) / 3.0;
if( $p->$y >= 0 ) {
$lat = (-$m1 * cos( $th1 + Proj4php::$common->PI / 3.0 ) - $c2 / 3.0 / $c3) * Proj4php::$common->PI;
} else {
$lat = -(-m1 * cos( $th1 + Proj4php::$common->PI / 3.0 ) - $c2 / 3.0 / $c3) * Proj4php::$common->PI;
}
 
if( abs( $xx ) < Proj4php::$common->EPSLN ) {
$lon = $this->$long0;
}
$lon = Proj4php::$common->adjust_lon( $this->long0 + Proj4php::$common->PI * ($xys - 1.0 + sqrt( 1.0 + 2.0 * ($xx * $xx - $yy * $yy) + $xys * $xys )) / 2.0 / $xx );
 
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
}
 
Proj4php::$proj['vandg'] = new Proj4phpProjVandg();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/gnom.php
New file
0,0 → 1,145
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*****************************************************************************
NAME GNOMONIC
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Gnomonic Projection.
Implementation based on the existing sterea and ortho
implementations.
 
PROGRAMMER DATE
---------- ----
Richard Marsden November 2009
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Flattening the Earth - Two Thousand Years of Map
Projections", University of Chicago Press 1993
 
2. Wolfram Mathworld "Gnomonic Projection"
http://mathworld.wolfram.com/GnomonicProjection.html
Accessed: 12th November 2009
******************************************************************************/
 
class Proj4phpProjGnom {
/**
* Initialize the Gnomonic projection
*
* @todo $def not used in context...?
* @param type $def
*/
public function init( $def ) {
 
/* Place parameters in static storage for common use
------------------------------------------------- */
$this->sin_p14 = sin( $this->lat0 );
$this->cos_p14 = cos( $this->lat0 );
// Approximation for projecting points to the horizon (infinity)
$this->infinity_dist = 1000 * $this->a;
$this->rc = 1;
}
 
/* Gnomonic forward equations--mapping lat,long to x,y
--------------------------------------------------- */
public function forward( $p ) {
/*
$sinphi;
$cosphi; // sin and cos value
$dlon; // delta longitude value
$coslon; // cos of longitude
$ksp; // scale factor
$g;
*/
$lon = $p->x;
$lat = $p->y;
/* Forward equations
----------------- */
$dlon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
 
$sinphi = sin( $lat );
$cosphi = cos( $lat );
 
$coslon = cos( $dlon );
$g = $this->sin_p14 * $sinphi + $this->cos_p14 * $cosphi * $coslon;
$ksp = 1.0;
if( (g > 0) || (abs( g ) <= Proj4php::$common->EPSLN) ) {
$x = $this->x0 + $this->a * $ksp * $cosphi * sin( $dlon ) / $g;
$y = $this->y0 + $this->a * $ksp * ($this->cos_p14 * $sinphi - $this->sin_p14 * $cosphi * $coslon) / $g;
} else {
Proj4php::reportError( "orthoFwdPointError" );
 
// Point is in the opposing hemisphere and is unprojectable
// We still need to return a reasonable point, so we project
// to infinity, on a bearing
// equivalent to the northern hemisphere equivalent
// This is a reasonable approximation for short shapes and lines that
// straddle the horizon.
 
$x = $this->x0 + $this->infinity_dist * $cosphi * sin( $dlon );
$y = $this->y0 + $this->infinity_dist * ($this->cos_p14 * $sinphi - $this->sin_p14 * $cosphi * $coslon);
}
$p->x = $x;
$p->y = $y;
return $p;
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
/*
$rh; // Rho
$z; // angle
$sinc;
$cosc;
$c;
$lon;
$lat;
*/
/* Inverse equations
----------------- */
$p->x = ($p->x - $this->x0) / $this->a;
$p->y = ($p->y - $this->y0) / $this->a;
 
$p->x /= $this->k0;
$p->y /= $this->k0;
 
if( ($rh = sqrt( $p->x * $p->x + $p->y * $p->y ) ) ) {
$c = atan2( $rh, $this->rc );
$sinc = sin( $c );
$cosc = cos( $c );
 
$lat = Proj4php::$common->asinz( $cosc * $this->sin_p14 + ($p->y * $sinc * $this->cos_p14) / $rh );
$lon = atan2( $p->x * sinc, rh * $this->cos_p14 * $cosc - $p->y * $this->sin_p14 * $sinc );
$lon = Proj4php::$common->adjust_lon( $this->long0 + $lon );
} else {
$lat = $this->phic0;
$lon = 0.0;
}
 
$p->x = $lon;
$p->y = $lat;
return $p;
}
}
 
Proj4php::$proj['gnom'] = new Proj4phpProjGnom();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/lcc.php
New file
0,0 → 1,166
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME LAMBERT CONFORMAL CONIC
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Lambert Conformal Conic projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
*******************************************************************************/
 
 
//<2104> +proj=lcc +lat_1=10.16666666666667 +lat_0=10.16666666666667 +lon_0=-71.60561777777777 +k_0=1 +x0=-17044 +x0=-23139.97 +ellps=intl +units=m +no_defs no_defs
// Initialize the Lambert Conformal conic projection
// -----------------------------------------------------------------
//class Proj4phpProjlcc = Class.create();
class Proj4phpProjLcc {
 
public function init() {
// array of: r_maj,r_min,lat1,lat2,c_lon,c_lat,false_east,false_north
//double c_lat; /* center latitude */
//double c_lon; /* center longitude */
//double lat1; /* first standard parallel */
//double lat2; /* second standard parallel */
//double r_maj; /* major axis */
//double r_min; /* minor axis */
//double false_east; /* x offset in meters */
//double false_north; /* y offset in meters */
 
//if lat2 is not defined
if( !isset($this->lat2) ) {
$this->lat2 = $this->lat0;
}
//if k0 is not defined
if( !isset($this->k0) )
$this->k0 = 1.0;
 
// Standard Parallels cannot be equal and on opposite sides of the equator
if( abs( $this->lat1 + $this->lat2 ) < Proj4php::$common->EPSLN ) {
Proj4php::reportError( "lcc:init: Equal Latitudes" );
return;
}
 
$temp = $this->b / $this->a;
$this->e = sqrt( 1.0 - $temp * $temp );
 
$sin1 = sin( $this->lat1 );
$cos1 = cos( $this->lat1 );
$ms1 = Proj4php::$common->msfnz( $this->e, $sin1, $cos1 );
$ts1 = Proj4php::$common->tsfnz( $this->e, $this->lat1, $sin1 );
 
$sin2 = sin( $this->lat2 );
$cos2 = cos( $this->lat2 );
$ms2 = Proj4php::$common->msfnz( $this->e, $sin2, $cos2 );
$ts2 = Proj4php::$common->tsfnz( $this->e, $this->lat2, $sin2 );
 
$ts0 = Proj4php::$common->tsfnz( $this->e, $this->lat0, sin( $this->lat0 ) );
 
if( abs( $this->lat1 - $this->lat2 ) > Proj4php::$common->EPSLN ) {
$this->ns = log( $ms1 / $ms2 ) / log( $ts1 / $ts2 );
} else {
$this->ns = $sin1;
}
$this->f0 = $ms1 / ($this->ns * pow( $ts1, $this->ns ));
$this->rh = $this->a * $this->f0 * pow( $ts0, $this->ns );
if( !isset($this->title) )
$this->title = "Lambert Conformal Conic";
}
 
// Lambert Conformal conic forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
public function forward( $p ) {
 
$lon = $p->x;
$lat = $p->y;
 
// convert to radians
if( $lat <= 90.0 && $lat >= -90.0 && $lon <= 180.0 && $lon >= -180.0 ) {
//lon = lon * Proj4php::$common.D2R;
//lat = lat * Proj4php::$common.D2R;
} else {
Proj4php::reportError( "lcc:forward: llInputOutOfRange: " . $lon . " : " . $lat );
return null;
}
 
$con = abs( abs( $lat ) - Proj4php::$common->HALF_PI );
if( $con > Proj4php::$common->EPSLN ) {
$ts = Proj4php::$common->tsfnz( $this->e, $lat, sin( $lat ) );
$rh1 = $this->a * $this->f0 * pow( $ts, $this->ns );
} else {
$con = $lat * $this->ns;
if( $con <= 0 ) {
Proj4php::reportError( "lcc:forward: No Projection" );
return null;
}
$rh1 = 0;
}
$theta = $this->ns * Proj4php::$common->adjust_lon( $lon - $this->long0 );
$p->x = $this->k0 * ($rh1 * sin( $theta )) + $this->x0;
$p->y = $this->k0 * ($this->rh - $rh1 * cos( $theta )) + $this->y0;
 
return $p;
}
/**
* Lambert Conformal Conic inverse equations--mapping x,y to lat/long
*
* @param type $p
* @return null
*/
public function inverse( $p ) {
$x = ($p->x - $this->x0) / $this->k0;
$y = ($this->rh - ($p->y - $this->y0) / $this->k0);
if( $this->ns > 0 ) {
$rh1 = sqrt( $x * $x + $y * $y );
$con = 1.0;
} else {
$rh1 = -sqrt( $x * $x + $y * $y );
$con = -1.0;
}
$theta = 0.0;
if( $rh1 != 0 ) {
$theta = atan2( ($con * $x ), ($con * $y ) );
}
if( ($rh1 != 0) || ($this->ns > 0.0) ) {
$con = 1.0 / $this->ns;
$ts = pow( ($rh1 / ($this->a * $this->f0) ), $con );
$lat = Proj4php::$common->phi2z( $this->e, $ts );
if( $lat == -9999 )
return null;
} else {
$lat = -Proj4php::$common->HALF_PI;
}
$lon = Proj4php::$common->adjust_lon( $theta / $this->ns + $this->long0 );
 
$p->x = $lon;
$p->y = $lat;
return $p;
}
}
 
Proj4php::$proj['lcc'] = new Proj4phpProjLcc();
 
 
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/laea.php
New file
0,0 → 1,398
<?php
 
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/* * *****************************************************************************
NAME LAMBERT AZIMUTHAL EQUAL-AREA
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Lambert Azimuthal Equal-Area projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
D. Steinwand, EROS March, 1991
 
This function was adapted from the Lambert Azimuthal Equal Area projection
code (FORTRAN) in the General Cartographic Transformation Package software
which is available from the U.S. Geological Survey National Mapping Division.
 
ALGORITHM REFERENCES
 
1. "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
 
2. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
3. "Software Documentation for GCTP General Cartographic Transformation
Package", U.S. Geological Survey National Mapping Division, May 1982.
* ***************************************************************************** */
 
class Proj4phpProjLaea {
 
protected $S_POLE = 1;
protected $N_POLE = 2;
protected $EQUIT = 3;
protected $OBLIQ = 4;
 
protected $P00 = .33333333333333333333;
protected $P01 = .17222222222222222222;
protected $P02 = .10257936507936507936;
protected $P10 = .06388888888888888888;
protected $P11 = .06640211640211640211;
protected $P20 = .01641501294219154443;
/* Initialize the Lambert Azimuthal Equal Area projection
------------------------------------------------------ */
public function init() {
$t = abs( $this->lat0 );
if( abs( $t - Proj4php::$common->HALF_PI ) < Proj4php::$common->EPSLN ) {
$this->mode = $this->lat0 < 0. ? $this->S_POLE : $this->N_POLE;
} else if( abs( $t ) < Proj4php::$common->EPSLN ) {
$this->mode = $this->EQUIT;
} else {
$this->mode = $this->OBLIQ;
}
if( $this->es > 0 ) {
#$sinphi;
 
$this->qp = Proj4php::$common->qsfnz( $this->e, 1.0 );
$this->mmf = .5 / (1. - $this->es);
$this->apa = $this->authset( $this->es );
switch( $this->mode ) {
case $this->N_POLE:
case $this->S_POLE:
$this->dd = 1.;
break;
case $this->EQUIT:
$this->rq = sqrt( .5 * $this->qp );
$this->dd = 1. / $this->rq;
$this->xmf = 1.;
$this->ymf = .5 * $this->qp;
break;
case $this->OBLIQ:
$this->rq = sqrt( .5 * $this->qp );
$sinphi = sin( $this->lat0 );
$this->sinb1 = Proj4php::$common->qsfnz( $this->e, $sinphi ) / $this->qp;
$this->cosb1 = sqrt( 1. - $this->sinb1 * $this->sinb1 );
$this->dd = cos( $this->lat0 ) / (sqrt( 1. - $this->es * $sinphi * $sinphi ) * $this->rq * $this->cosb1);
$this->ymf = ($this->xmf = $this->rq) / $this->dd;
$this->xmf *= $this->dd;
break;
}
} else {
if( $this->mode == $this->OBLIQ ) {
$this->sinph0 = sin( $this->lat0 );
$this->cosph0 = cos( $this->lat0 );
}
}
}
 
/* Lambert Azimuthal Equal Area forward equations--mapping lat,long to x,y
----------------------------------------------------------------------- */
public function forward( $p ) {
 
/* Forward equations
----------------- */
#$x;
#$y;
$lam = $p->x;
$phi = $p->y;
$lam = Proj4php::$common->adjust_lon( $lam - $this->long0 );
 
if( $this->sphere ) {
/*
$coslam;
$cosphi;
$sinphi;
*/
$sinphi = sin( $phi );
$cosphi = cos( $phi );
$coslam = cos( $lam );
switch( $this->mode ) {
case $this->OBLIQ:
case $this->EQUIT:
$y = ($this->mode == $this->EQUIT) ? 1. + $cosphi * $coslam : 1. + $this->sinph0 * $sinphi + $this->cosph0 * $cosphi * $coslam;
if( y <= Proj4php::$common->EPSLN ) {
Proj4php::reportError( "laea:fwd:y less than eps" );
return null;
}
$y = sqrt( 2. / $y );
$x = $y * cosphi * sin( $lam );
$y *= ($this->mode == $this->EQUIT) ? $sinphi : $this->cosph0 * $sinphi - $this->sinph0 * $cosphi * $coslam;
break;
case $this->N_POLE:
$coslam = -$coslam;
case $this->S_POLE:
if( abs( $phi + $this->phi0 ) < Proj4php::$common->EPSLN ) {
Proj4php::reportError( "laea:fwd:phi < eps" );
return null;
}
$y = Proj4php::$common->FORTPI - $phi * .5;
$y = 2. * (($this->mode == $this->S_POLE) ? cos( $y ) : sin( $y ));
$x = $y * sin( $lam );
$y *= $coslam;
break;
}
} else {
/*
$coslam;
$sinlam;
$sinphi;
$q;
*/
$sinb = 0.0;
$cosb = 0.0;
$b = 0.0;
 
$coslam = cos( $lam );
$sinlam = sin( $lam );
$sinphi = sin( $phi );
$q = Proj4php::$common->qsfnz( $this->e, $sinphi );
if( $this->mode == $this->OBLIQ || $this->mode == $this->EQUIT ) {
$sinb = $q / $this->qp;
$cosb = sqrt( 1. - $sinb * $sinb );
}
switch( $this->mode ) {
case $this->OBLIQ:
$b = 1. + $this->sinb1 * $sinb + $this->cosb1 * $cosb * $coslam;
break;
case $this->EQUIT:
$b = 1. + $cosb * $coslam;
break;
case $this->N_POLE:
$b = Proj4php::$common->HALF_PI + $phi;
$q = $this->qp - $q;
break;
case $this->S_POLE:
$b = $phi - Proj4php::$common->HALF_PI;
$q = $this->qp + $q;
break;
}
if( abs( $b ) < Proj4php::$common->EPSLN ) {
Proj4php::reportError( "laea:fwd:b < eps" );
return null;
}
switch( $this->mode ) {
case $this->OBLIQ:
case $this->EQUIT:
$b = sqrt( 2. / $b );
if( $this->mode == $this->OBLIQ ) {
$y = $this->ymf * $b * ($this->cosb1 * $sinb - $this->sinb1 * $cosb * $coslam);
} else {
$y = ($b = sqrt( 2. / (1. + $cosb * $coslam) )) * $sinb * $this->ymf;
}
$x = $this->xmf * $b * $cosb * $sinlam;
break;
case $this->N_POLE:
case $this->S_POLE:
if( q >= 0. ) {
$x = ($b = sqrt( $q )) * $sinlam;
$y = $coslam * (($this->mode == $this->S_POLE) ? $b : -$b);
} else {
$x = $y = 0.;
}
break;
}
}
 
//v 1.0
/*
$sin_lat=sin(lat);
$cos_lat=cos(lat);
 
$sin_delta_lon=sin(delta_lon);
$cos_delta_lon=cos(delta_lon);
 
$g =$this->sin_lat_o * sin_lat +$this->cos_lat_o * cos_lat * cos_delta_lon;
if (g == -1.0) {
Proj4php::reportError("laea:fwd:Point projects to a circle of radius "+ 2.0 * R);
return null;
}
$ksp = $this->a * sqrt(2.0 / (1.0 + g));
$x = ksp * cos_lat * sin_delta_lon + $this->x0;
$y = ksp * ($this->cos_lat_o * sin_lat - $this->sin_lat_o * cos_lat * cos_delta_lon) + $this->y0;
*/
$p->x = $this->a * $x + $this->x0;
$p->y = $this->a * $y + $this->y0;
return $p;
}
/* Inverse equations
----------------- */
public function inverse( $p ) {
$p->x -= $this->x0;
$p->y -= $this->y0;
$x = $p->x / $this->a;
$y = $p->y / $this->a;
 
if( $this->sphere ) {
$cosz = 0.0;
#$rh;
$sinz = 0.0;
 
$rh = sqrt( $x * $x + $y * $y );
$phi = $rh * .5;
if( $phi > 1. ) {
Proj4php::reportError( "laea:Inv:DataError" );
return null;
}
$phi = 2. * asin( $phi );
if( $this->mode == $this->OBLIQ || $this->mode == $this->EQUIT ) {
$sinz = sin( $phi );
$cosz = cos( $phi );
}
switch( $this->mode ) {
case $this->EQUIT:
$phi = (abs( $rh ) <= Proj4php::$common->EPSLN) ? 0. : asin( $y * $sinz / $rh );
$x *= $sinz;
$y = $cosz * $rh;
break;
case $this->OBLIQ:
$phi = (abs( $rh ) <= Proj4php::$common->EPSLN) ? $this->phi0 : asin( $cosz * $this->sinph0 + $y * $sinz * $this->cosph0 / $rh );
$x *= $sinz * $this->cosph0;
$y = ($cosz - sin( $phi ) * $this->sinph0) * $rh;
break;
case $this->N_POLE:
$y = -$y;
$phi = Proj4php::$common->HALF_PI - $phi;
break;
case $this->S_POLE:
$phi -= Proj4php::$common->HALF_PI;
break;
}
$lam = ($y == 0. && ($this->mode == $this->EQUIT || $this->mode == $this->OBLIQ)) ? 0. : atan2( $x, $y );
} else {
/*
$cCe;
$sCe;
$q;
$rho;
*/
$ab = 0.0;
 
switch( $this->mode ) {
case $this->EQUIT:
case $this->OBLIQ:
$x /= $this->dd;
$y *= $this->dd;
$rho = sqrt( $x * $x + $y * $y );
if( $rho < Proj4php::$common->EPSLN ) {
$p->x = 0.;
$p->y = $this->phi0;
return $p;
}
$sCe = 2. * asin( .5 * $rho / $this->rq );
$cCe = cos( $sCe );
$x *= ($sCe = sin( $sCe ));
if( $this->mode == $this->OBLIQ ) {
$ab = $cCe * $this->sinb1 + $y * $sCe * $this->cosb1 / $rho;
$q = $this->qp * $ab;
$y = $rho * $this->cosb1 * $cCe - $y * $this->sinb1 * $sCe;
} else {
$ab = $y * $sCe / $rho;
$q = $this->qp * $ab;
$y = $rho * $cCe;
}
break;
case $this->N_POLE:
$y = -$y;
case $this->S_POLE:
$q = ($x * $x + $y * $y);
if( !$q ) {
$p->x = 0.;
$p->y = $this->phi0;
return $p;
}
/*
q = $this->qp - q;
*/
$ab = 1. - $q / $this->qp;
if( $this->mode == $this->S_POLE ) {
$ab = - $ab;
}
break;
}
$lam = atan2( $x, $y );
$phi = $this->authlat( asin( $ab ), $this->apa );
}
 
/*
$Rh = sqrt($p->x *$p->x +$p->y * $p->y);
$temp = Rh / (2.0 * $this->a);
 
if (temp > 1) {
Proj4php::reportError("laea:Inv:DataError");
return null;
}
 
$z = 2.0 * Proj4php::$common.asinz(temp);
$sin_z=sin(z);
$cos_z=cos(z);
 
$lon =$this->long0;
if (abs(Rh) > Proj4php::$common->EPSLN) {
$lat = Proj4php::$common.asinz($this->sin_lat_o * cos_z +$this-> cos_lat_o * sin_z *$p->y / Rh);
$temp =abs($this->lat0) - Proj4php::$common->HALF_PI;
if (abs(temp) > Proj4php::$common->EPSLN) {
temp = cos_z -$this->sin_lat_o * sin(lat);
if(temp!=0.0) lon=Proj4php::$common->adjust_lon($this->long0+atan2($p->x*sin_z*$this->cos_lat_o,temp*Rh));
} else if ($this->lat0 < 0.0) {
lon = Proj4php::$common->adjust_lon($this->long0 - atan2(-$p->x,$p->y));
} else {
lon = Proj4php::$common->adjust_lon($this->long0 + atan2($p->x, -$p->y));
}
} else {
lat = $this->lat0;
}
*/
//return(OK);
$p->x = Proj4php::$common->adjust_lon( $this->long0 + $lam );
$p->y = $phi;
return $p;
}
 
/**
* determine latitude from authalic latitude
*
* @param type $es
* @return type
*/
public function authset( $es ) {
#$t;
$APA = array( );
$APA[0] = $es * $this->P00;
$t = $es * $es;
$APA[0] += $t * $this->P01;
$APA[1] = $t * $this->P10;
$t *= $es;
$APA[0] += $t * $this->P02;
$APA[1] += $t * $this->P11;
$APA[2] = $t * $this->P20;
return $APA;
}
 
/**
*
* @param type $beta
* @param type $APA
* @return type
*/
public function authlat( $beta, $APA ) {
$t = $beta + $beta;
return($beta + $APA[0] * sin( $t ) + $APA[1] * sin( $t + $t ) + $APA[2] * sin( $t + $t + $t ));
}
 
}
 
Proj4php::$proj['laea'] = new Proj4phpProjLaea();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/equi.php
New file
0,0 → 1,80
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME EQUIRECTANGULAR
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Equirectangular projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
T. Mittan Mar, 1993
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
*******************************************************************************/
class Proj4phpProjEqui {
 
public function init() {
if( !$this->x0 )
$this->x0 = 0;
if( !$this->y0 )
$this->y0 = 0;
if( !$this->lat0 )
$this->lat0 = 0;
if( !$this->long0 )
$this->long0 = 0;
///$this->t2;
}
 
/* Equirectangular forward equations--mapping lat,long to x,y
--------------------------------------------------------- */
public function forward( $p ) {
 
$lon = $p->x;
$lat = $p->y;
 
$dlon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
$x = $this->x0 + $this->a * $dlon * cos( $this->lat0 );
$y = $this->y0 + $this->a * $lat;
 
$this->t1 = $x;
$this->t2 = cos( $this->lat0 );
$p->x = $x;
$p->y = $y;
return $p;
}
 
/* Equirectangular inverse equations--mapping x,y to lat/long
--------------------------------------------------------- */
public function inverse( $p ) {
 
$p->x -= $this->x0;
$p->y -= $this->y0;
$lat = $p->y / $this->a;
 
if( abs( $lat ) > Proj4php::$common->HALF_PI ) {
Proj4php::reportError( "equi:Inv:DataError" );
}
$lon = Proj4php::$common->adjust_lon( $this->long0 + $p->x / ($this->a * cos( $this->lat0 )) );
$p->x = $lon;
$p->y = $lat;
}
}
 
Proj4php::$proj['equi'] = new Proj4phpProjEqui();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/moll.php
New file
0,0 → 1,121
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME MOLLWEIDE
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the MOllweide projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
D. Steinwand, EROS May, 1991; Updated Sept, 1992; Updated Feb, 1993
S. Nelson, EDC Jun, 2993; Made corrections in precision and
number of iterations.
 
ALGORITHM REFERENCES
 
1. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
 
2. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
****************************************************************************** */
 
class Proj4phpProjMoll {
/* Initialize the Mollweide projection
------------------------------------ */
 
public function init() {
//no-op
}
 
/* Mollweide forward equations--mapping lat,long to x,y
---------------------------------------------------- */
public function forward( $p ) {
 
/* Forward equations
----------------- */
$lon = $p->x;
$lat = $p->y;
 
$delta_lon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
$theta = $lat;
$con = Proj4php::$common->PI * sin( $lat );
 
/* Iterate using the Newton-Raphson method to find theta
----------------------------------------------------- */
for( $i = 0; true; ++$i ) {
$delta_theta = -($theta + sin( $theta ) - $con) / (1.0 + cos( $theta ));
$theta += $delta_theta;
if( abs( $delta_theta ) < Proj4php::$common->EPSLN )
break;
if( $i >= 50 ) {
Proj4php::reportError( "moll:Fwd:IterationError" );
//return(241);
}
}
$theta /= 2.0;
 
/* If the latitude is 90 deg, force the x coordinate to be "0 . false easting"
this is done here because of precision problems with "cos(theta)"
-------------------------------------------------------------------------- */
if( Proj4php::$common->PI / 2 - abs( $lat ) < Proj4php::$common->EPSLN )
$delta_lon = 0;
$x = 0.900316316158 * $this->a * $delta_lon * cos( $theta ) + $this->x0;
$y = 1.4142135623731 * $this->a * sin( $theta ) + $this->y0;
 
$p->x = $x;
$p->y = $y;
return $p;
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
#$theta;
#$arg;
 
/* Inverse equations
----------------- */
$p->x-= $this->x0;
//~ $p->y -= $this->y0;
$arg = $p->y / (1.4142135623731 * $this->a);
 
/* Because of division by zero problems, 'arg' can not be 1.0. Therefore
a number very close to one is used instead.
------------------------------------------------------------------- */
if( abs( $arg ) > 0.999999999999 )
$arg = 0.999999999999;
$theta = asin( $arg );
$lon = Proj4php::$common->adjust_lon( $this->long0 + ($p->x / (0.900316316158 * $this->a * cos( $theta ))) );
if( $lon < (-Proj4php::$common->PI) )
$lon = -Proj4php::$common->PI;
if( $lon > Proj4php::$common->PI )
$lon = Proj4php::$common->PI;
$arg = (2.0 * $theta + sin( 2.0 * $theta )) / Proj4php::$common->PI;
if( abs( $arg ) > 1.0 )
$arg = 1.0;
$lat = asin( $arg );
//return(OK);
 
$p->x = $lon;
$p->y = $lat;
return $p;
}
}
 
Proj4php::$proj['moll'] = new Proj4phpProjMoll();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/gstmerc.php
New file
0,0 → 1,63
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class Proj4phpProjGstmerc {
 
public function init() {
 
// array of: a, b, lon0, lat0, k0, x0, y0
$temp = $this->b / $this->a;
$this->e = sqrt( 1.0 - $temp * $temp );
$this->lc = $this->long0;
$this->rs = sqrt( 1.0 + $this->e * $this->e * pow( cos( $this->lat0 ), 4.0 ) / (1.0 - $this->e * $this->e) );
$sinz = sin( $this->lat0 );
$pc = asin( $sinz / $this->rs );
$sinzpc = sin( $pc );
$this->cp = Proj4php::$common->latiso( 0.0, $pc, $sinzpc ) - $this->rs * Proj4php::$common->latiso( $this->e, $this->lat0, $sinz );
$this->n2 = $this->k0 * $this->a * sqrt( 1.0 - $this->e * $this->e ) / (1.0 - $this->e * $this->e * $sinz * $sinz);
$this->xs = $this->x0;
$this->ys = $this->y0 - $this->n2 * $pc;
 
if( !$this->title )
$this->title = "Gauss Schreiber transverse mercator";
}
 
// forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
public function forward( $p ) {
 
$lon = $p->x;
$lat = $p->y;
 
$L = $this->rs * ($lon - $this->lc);
$Ls = $this->cp + ($this->rs * Proj4php::$common->latiso( $this->e, $lat, sin( $lat ) ));
$lat1 = asin( sin( $L ) / Proj4php::$common . cosh( $Ls ) );
$Ls1 = Proj4php::$common . latiso( 0.0, $lat1, sin( $lat1 ) );
$p->x = $this->xs + ($this->n2 * $Ls1);
$p->y = $this->ys + ($this->n2 * atan( Proj4php::$common->sinh( $Ls ) / cos( $L ) ));
return $p;
}
 
// inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
public function inverse( $p ) {
 
$x = $p->x;
$y = $p->y;
 
$L = atan( Proj4php::$common . sinh( ($x - $this->xs) / $this->n2 ) / cos( ($y - $this->ys) / $this->n2 ) );
$lat1 = asin( sin( ($y - $this->ys) / $this->n2 ) / Proj4php::$common . cosh( ($x - $this->xs) / $this->n2 ) );
$LC = Proj4php::$common . latiso( 0.0, $lat1, sin( $lat1 ) );
$p->x = $this->lc + $L / $this->rs;
$p->y = Proj4php::$common . invlatiso( $this->e, ($LC - $this->cp) / $this->rs );
return $p;
}
 
}
 
Proj4php::$proj['gstmerc'] = new Proj4phpProjGestmerc();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/utm.php
New file
0,0 → 1,74
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME TRANSVERSE MERCATOR
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Transverse Mercator projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
*******************************************************************************/
 
/**
Initialize Transverse Mercator projection
*/
class Proj4phpProjUtm {
 
public $dependsOn = 'tmerc';
public $utmSouth = false; // UTM north/south
/**
*
* @return void
*/
public function init() {
if( !isset($this->zone) ) {
Proj4php::reportError( "utm:init: zone must be specified for UTM" );
return;
}
$this->lat0 = 0.0;
$this->long0 = ((6 * abs( $this->zone )) - 183) * Proj4php::$common->D2R;
$this->x0 = 500000.0;
$this->y0 = $this->utmSouth ? 10000000.0 : 0.0;
$this->k0 = 0.9996;
}
/**
*
* @param type $p
* @return type
*/
public function forward( $p ) {
return Proj4php::$proj['tmerc']->forward( $p );
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
return Proj4php::$proj['tmerc']->inverse( $p );
}
}
 
Proj4php::$proj['utm'] = new Proj4phpProjUtm();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/omerc.php
New file
0,0 → 1,301
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/* * *****************************************************************************
NAME OBLIQUE MERCATOR (HOTINE)
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Oblique Mercator projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
PROGRAMMER DATE
---------- ----
T. Mittan Mar, 1993
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
* ***************************************************************************** */
 
class Proj4phpProjOmerc {
/* Initialize the Oblique Mercator projection
------------------------------------------ */
 
public function init() {
if( !$this->mode )
$this->mode = 0;
if( !$this->lon1 ) {
$this->lon1 = 0;
$this->mode = 1;
}
if( !$this->lon2 )
$this->lon2 = 0;
if( !$this->lat2 )
$this->lat2 = 0;
 
/* Place parameters in static storage for common use
------------------------------------------------- */
$temp = $this->b / $this->a;
$es = 1.0 - pow( $temp, 2 );
$e = sqrt( $es );
 
$this->sin_p20 = sin( $this->lat0 );
$this->cos_p20 = cos( $this->lat0 );
 
$this->con = 1.0 - $this->es * $this->sin_p20 * $this->sin_p20;
$this->com = sqrt( 1.0 - $es );
$this->bl = sqrt( 1.0 + $this->es * pow( $this->cos_p20, 4.0 ) / (1.0 - $es) );
$this->al = $this->a * $this->bl * $this->k0 * $this->com / $this->con;
if( abs( $this->lat0 ) < Proj4php::$common->EPSLN ) {
$this->ts = 1.0;
$this->d = 1.0;
$this->el = 1.0;
} else {
$this->ts = Proj4php::$common->tsfnz( $this->e, $this->lat0, $this->sin_p20 );
$this->con = sqrt( $this->con );
$this->d = $this->bl * $this->com / ($this->cos_p20 * $this->con);
if( ($this->d * $this->d - 1.0) > 0.0 ) {
if( $this->lat0 >= 0.0 ) {
$this->f = $this->d + sqrt( $this->d * $this->d - 1.0 );
} else {
$this->f = $this->d - sqrt( $this->d * $this->d - 1.0 );
}
} else {
$this->f = $this->d;
}
$this->el = $this->f * pow( $this->ts, $this->bl );
}
 
//$this->longc=52.60353916666667;
 
if( $this->mode != 0 ) {
$this->g = .5 * ($this->f - 1.0 / $this->f);
$this->gama = Proj4php::$common->asinz( sin( $this->alpha ) / $this->d );
$this->longc = $this->longc - Proj4php::$common->asinz( $this->g * tan( $this->gama ) ) / $this->bl;
 
/* Report parameters common to format B
------------------------------------- */
//genrpt(azimuth * R2D,"Azimuth of Central Line: ");
//cenlon(lon_origin);
// cenlat(lat_origin);
 
$this->con = abs( $this->lat0 );
if( ($this->con > Proj4php::$common->EPSLN) && (abs( $this->con - Proj4php::$common->HALF_PI ) > Proj4php::$common->EPSLN) ) {
$this->singam = sin( $this->gama );
$this->cosgam = cos( $this->gama );
 
$this->sinaz = sin( $this->alpha );
$this->cosaz = cos( $this->alpha );
 
if( $this->lat0 >= 0 ) {
$this->u = ($this->al / $this->bl) * atan( sqrt( $this->d * $this->d - 1.0 ) / $this->cosaz );
} else {
$this->u = -($this->al / $this->bl) * atan( sqrt( $this->d * $this->d - 1.0 ) / $this->cosaz );
}
} else {
Proj4php::reportError( "omerc:Init:DataError" );
}
} else {
$this->sinphi = sin( $this->at1 );
$this->ts1 = Proj4php::$common->tsfnz( $this->e, $this->lat1, $this->sinphi );
$this->sinphi = sin( $this->lat2 );
$this->ts2 = Proj4php::$common->tsfnz( $this->e, $this->lat2, $this->sinphi );
$this->h = pow( $this->ts1, $this->bl );
$this->l = pow( $this->ts2, $this->bl );
$this->f = $this->el / $this->h;
$this->g = .5 * ($this->f - 1.0 / $this->f);
$this->j = ($this->el * $this->el - $this->l * $this->h) / ($this->el * $this->el + $this->l * $this->h);
$this->p = ($this->l - $this->h) / ($this->l + $this->h);
$this->dlon = $this->lon1 - $this->lon2;
if( $this->dlon < -Proj4php::$common->PI )
$this->lon2 = $this->lon2 - 2.0 * Proj4php::$common->PI;
if( $this->dlon > Proj4php::$common->PI )
$this->lon2 = $this->lon2 + 2.0 * Proj4php::$common->PI;
$this->dlon = $this->lon1 - $this->lon2;
$this->longc = .5 * ($this->lon1 + $this->lon2) - atan( $this->j * tan( .5 * $this->bl * $this->dlon ) / $this->p ) / $this->bl;
$this->dlon = Proj4php::$common->adjust_lon( $this->lon1 - $this->longc );
$this->gama = atan( sin( $this->bl * $this->dlon ) / $this->g );
$this->alpha = Proj4php::$common->asinz( $this->d * sin( $this->gama ) );
 
/* Report parameters common to format A
------------------------------------- */
if( abs( $this->lat1 - $this->lat2 ) <= Proj4php::$common->EPSLN ) {
Proj4php::reportError( "omercInitDataError" );
//return(202);
} else {
$this->con = abs( $this->lat1 );
}
if( ($this->con <= Proj4php::$common->EPSLN) || (abs( $this->con - Proj4php::$common->HALF_PI ) <= Proj4php::$common->EPSLN) ) {
Proj4php::reportError( "omercInitDataError" );
//return(202);
} else {
if( abs( abs( $this->lat0 ) - Proj4php::$common->HALF_PI ) <= Proj4php::$common->EPSLN ) {
Proj4php::reportError( "omercInitDataError" );
//return(202);
}
}
 
$this->singam = sin( $this->gam );
$this->cosgam = cos( $this->gam );
 
$this->sinaz = sin( $this->alpha );
$this->cosaz = cos( $this->alpha );
 
 
if( $this->lat0 >= 0 ) {
$this->u = ($this->al / $this->bl) * atan( sqrt( $this->d * $this->d - 1.0 ) / $this->cosaz );
} else {
$this->u = -($this->al / $this->bl) * atan( sqrt( $this->d * $this->d - 1.0 ) / $this->cosaz );
}
}
}
 
/* Oblique Mercator forward equations--mapping lat,long to x,y
---------------------------------------------------------- */
public function forward( $p ) {
/*
$theta; // angle
$sin_phi;
$cos_phi; // sin and cos value
$b; // temporary values
$c;
$t;
$tq; // temporary values
$con;
$n;
$ml; // cone constant, small m
$q;
$us;
$vl;
$ul;
$vs;
$s;
$dlon;
$ts1;
*/
 
$lon = $p->x;
$lat = $p->y;
/* Forward equations
----------------- */
$sin_phi = sin( $lat );
$dlon = Proj4php::$common->adjust_lon( $lon - $this->longc );
$vl = sin( $this->bl * $dlon );
if( abs( abs( $lat ) - Proj4php::$common->HALF_PI ) > Proj4php::$common->EPSLN ) {
$ts1 = Proj4php::$common->tsfnz( $this->e, $lat, $sin_phi );
$q = $this->el / (pow( $ts1, $this->bl ));
$s = .5 * ($q - 1.0 / $q);
$t = .5 * ($q + 1.0 / $q);
$ul = ($s * $this->singam - $vl * $this->cosgam) / $t;
$con = cos( $this->bl * $dlon );
if( abs( con ) < .0000001 ) {
$us = $this->al * $this->bl * $dlon;
} else {
$us = $this->al * atan( ($s * $this->cosgam + $vl * $this->singam) / $con ) / $this->bl;
if( $con < 0 )
$us = $us + Proj4php::$common->PI * $this->al / $this->bl;
}
} else {
if( $lat >= 0 ) {
$ul = $this->singam;
} else {
$ul = -$this->singam;
}
$us = $this->al * $lat / $this->bl;
}
if( abs( abs( $ul ) - 1.0 ) <= Proj4php::$common->EPSLN ) {
//alert("Point projects into infinity","omer-for");
Proj4php::reportError( "omercFwdInfinity" );
//return(205);
}
$vs = .5 * $this->al * log( (1.0 - $ul) / (1.0 + $ul) ) / $this->bl;
$us = $us - $this->u;
$p->x = $this->x0 + $vs * $this->cosaz + $us * $this->sinaz;
$p->y = $this->y0 + $us * $this->cosaz - $vs * $this->sinaz;
 
return $p;
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
/*
$delta_lon; /* Delta longitude (Given longitude - center
$theta; /* angle
$delta_theta; /* adjusted longitude
$sin_phi;
$cos_phi; /* sin and cos value
$b; /* temporary values
$c;
$t;
$tq; /* temporary values
$con;
$n;
$ml; /* cone constant, small m
$vs;
$us;
$q;
$s;
$ts1;
$vl;
$ul;
$bs;
$dlon;
$flag;
*/
/* Inverse equations
----------------- */
$p->x -= $this->x0;
$p->y -= $this->y0;
#$flag = 0;
$vs = $p->x * $this->cosaz - $p->y * $this->sinaz;
$us = $p->y * $this->cosaz + $p->x * $this->sinaz;
$us = $us + $this->u;
$q = exp( -$this->bl * $vs / $this->al );
$s = .5 * ($q - 1.0 / $q);
$t = .5 * ($q + 1.0 / $q);
$vl = sin( $this->bl * $us / $this->al );
$ul = ($vl * $this->cosgam + $s * $this->singam) / $t;
if( abs( abs( $ul ) - 1.0 ) <= Proj4php::$common->EPSLN ) {
$lon = $this->longc;
if( ul >= 0.0 ) {
$lat = Proj4php::$common->HALF_PI;
} else {
$lat = -Proj4php::$common->HALF_PI;
}
} else {
$con = 1.0 / $this->bl;
$ts1 = pow( ($this->el / sqrt( (1.0 + $ul) / (1.0 - $ul) ) ), $con );
$lat = Proj4php::$common->phi2z( $this->e, $ts1 );
//if ($flag != 0)
//return($flag);
//~ con = cos($this->bl * us /al);
$theta = $this->longc - atan2( ($s * $this->cosgam - $vl * $this->singam ), $con ) / $this->bl;
$lon = Proj4php::$common->adjust_lon( $theta );
}
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
}
 
Proj4php::$proj['omerc'] = new Proj4phpProjOmerc();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/eqc.php
New file
0,0 → 1,58
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/* similar to equi.js FIXME proj4 uses eqc */
class Proj4phpProjEqc {
 
public function init() {
 
if( !$this->x0 )
$this->x0 = 0;
if( !$this->y0 )
$this->y0 = 0;
if( !$this->lat0 )
$this->lat0 = 0;
if( !$this->long0 )
$this->long0 = 0;
if( !$this->lat_ts )
$this->lat_ts = 0;
if( !$this->title )
$this->title = "Equidistant Cylindrical (Plate Carre)";
 
$this->rc = cos( $this->lat_ts );
}
 
// forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
public function forward( $p ) {
 
$lon = $p->x;
$lat = $p->y;
 
$dlon = Proj4php::$common->adjust_lon( $lon - $this->long0 );
$dlat = Proj4php::$common . adjust_lat( $lat - $this->lat0 );
$p->x = $this->x0 + ($this->a * $dlon * $this->rc);
$p->y = $this->y0 + ($this->a * $dlat );
return $p;
}
 
// inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
public function inverse( $p ) {
 
$x = $p->x;
$y = $p->y;
 
$p->x = Proj4php::$common->adjust_lon( $this->long0 + (($x - $this->x0) / ($this->a * $this->rc)) );
$p->y = Proj4php::$common->adjust_lat( $this->lat0 + (($y - $this->y0) / ($this->a )) );
return $p;
}
 
}
 
Proj4php::$proj['eqc'] = new Proj4phpProjEqc();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/aeqd.php
New file
0,0 → 1,101
<?php
 
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class Proj4phpProjAeqd {
 
public function init() {
$this->sin_p12 = sin( $this->lat0 );
$this->cos_p12 = cos( $this->lat0 );
}
 
/**
*
* @param type $p
* @return type
*/
public function forward( $p ) {
 
#$lon = $p->x;
#$lat = $p->y;
#$ksp;
 
$sinphi = sin( $p->y );
$cosphi = cos( $p->y );
$dlon = Proj4php::$common->adjust_lon( lon - $this->long0 );
$coslon = cos( $dlon );
$g = $this->sin_p12 * $sinphi + $this->cos_p12 * $cosphi * $coslon;
if( abs( abs( $g ) - 1.0 ) < Proj4php::$common->EPSLN ) {
$ksp = 1.0;
if( $g < 0.0 ) {
Proj4php::reportError( "aeqd:Fwd:PointError" );
return;
}
} else {
$z = acos( $g );
$ksp = $z / sin( $z );
}
$p->x = $this->x0 + $this->a * $ksp * $cosphi * sin( $dlon );
$p->y = $this->y0 + $this->a * $ksp * ($this->cos_p12 * $sinphi - $this->sin_p12 * $cosphi * $coslon);
return $p;
}
 
/**
*
* @param type $p
* @return type
*/
public function inverse( $p ) {
$p->x -= $this->x0;
$p->y -= $this->y0;
 
$rh = sqrt( $p->x * $p->x + $p->y * $p->y );
if( $rh > (2.0 * Proj4php::$common->HALF_PI * $this->a) ) {
Proj4php::reportError( "aeqdInvDataError" );
return;
}
$z = $rh / $this->a;
 
$sinz = sin( $z );
$cosz = cos( $z );
 
$lon = $this->long0;
#$lat;
if( abs( $rh ) <= Proj4php::$common->EPSLN ) {
$lat = $this->lat0;
} else {
$lat = Proj4php::$common->asinz( $cosz * $this->sin_p12 + ($p->y * $sinz * $this->cos_p12) / $rh );
$con = abs( $this->lat0 ) - Proj4php::$common->HALF_PI;
if( abs( $con ) <= Proj4php::$common->EPSLN ) {
if( $this->lat0 >= 0.0 ) {
$lon = Proj4php::$common->adjust_lon( $this->long0 + atan2( $p->x, -$p->y ) );
} else {
$lon = Proj4php::$common->adjust_lon( $this->long0 - atan2( -$p->x, $p->y ) );
}
} else {
$con = $cosz - $this->sin_p12 * sin( $lat );
if( (abs( $con ) < Proj4php::$common->EPSLN) && (abs( $p->x ) < Proj4php::$common->EPSLN) ) {
//no-op, just keep the lon value as is
} else {
#$temp = atan2( ($p->x * $sinz * $this->cos_p12 ), ($con * $rh ) ); // $temp is unused !?!
$lon = Proj4php::$common->adjust_lon( $this->long0 + atan2( ($p->x * $sinz * $this->cos_p12 ), ($con * $rh ) ) );
}
}
}
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
}
 
Proj4php::$proj['aeqd'] = new Proj4phpProjAeqd();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/tmerc.php
New file
0,0 → 1,166
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME TRANSVERSE MERCATOR
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Transverse Mercator projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
ALGORITHM REFERENCES
 
1. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
 
2. Snyder, John P. and Voxland, Philip M., "An Album of Map Projections",
U.S. Geological Survey Professional Paper 1453 , United State Government
Printing Office, Washington D.C., 1989.
*******************************************************************************/
 
/**
Initialize Transverse Mercator projection
*/
class Proj4phpProjTmerc {
private $e0, $e1, $e2, $e3, $ml0;
/**
*
*/
public function init() {
$this->e0 = Proj4php::$common->e0fn( $this->es );
$this->e1 = Proj4php::$common->e1fn( $this->es );
$this->e2 = Proj4php::$common->e2fn( $this->es );
$this->e3 = Proj4php::$common->e3fn( $this->es );
$this->ml0 = $this->a * Proj4php::$common->mlfn( $this->e0, $this->e1, $this->e2, $this->e3, $this->lat0 );
}
 
/**
Transverse Mercator Forward - long/lat to x/y
long/lat in radians
*/
public function forward( $p ) {
$lon = $p->x;
$lat = $p->y;
 
$delta_lon = Proj4php::$common->adjust_lon( $lon - $this->long0 ); // Delta longitude
#$con = 0; // cone constant
#$x = 0;
#$y = 0;
$sin_phi = sin( $lat );
$cos_phi = cos( $lat );
 
if( isset($this->sphere) && $this->sphere === true ) { /* spherical form */
$b = $cos_phi * sin( $delta_lon );
if( (abs( abs( $b ) - 1.0 )) < .0000000001 ) {
Proj4php::reportError( "tmerc:forward: Point projects into infinity" );
return(93);
} else {
$x = .5 * $this->a * $this->k0 * log( (1.0 + $b) / (1.0 - $b) );
$con = acos( $cos_phi * cos( $delta_lon ) / sqrt( 1.0 - $b * $b ) );
if( $lat < 0 )
$con = - $con;
$y = $this->a * $this->k0 * ($con - $this->lat0);
}
} else {
$al = $cos_phi * $delta_lon;
$als = pow( $al, 2 );
$c = $this->ep2 * pow( $cos_phi, 2 );
$tq = tan( $lat );
$t = pow( $tq, 2 );
$con = 1.0 - $this->es * pow( $sin_phi, 2 );
$n = $this->a / sqrt( $con );
$ml = $this->a * Proj4php::$common->mlfn( $this->e0, $this->e1, $this->e2, $this->e3, $lat );
 
$x = $this->k0 * $n * $al * (1.0 + $als / 6.0 * (1.0 - $t + $c + $als / 20.0 * (5.0 - 18.0 * $t + pow( $t, 2 ) + 72.0 * $c - 58.0 * $this->ep2))) + $this->x0;
$y = $this->k0 * ($ml - $this->ml0 + $n * $tq * ($als * (0.5 + $als / 24.0 * (5.0 - $t + 9.0 * $c + 4.0 * pow( $c, 2 ) + $als / 30.0 * (61.0 - 58.0 * $t + pow( $t, 2 ) + 600.0 * $c - 330.0 * $this->ep2))))) + $this->y0;
}
$p->x = $x;
$p->y = $y;
return $p;
}
 
/**
Transverse Mercator Inverse - x/y to long/lat
*/
public function inverse( $p ) {
#$phi; /* temporary angles */
#$delta_phi; /* difference between longitudes */
$max_iter = 6; /* maximun number of iterations */
 
if( isset($this->sphere) && $this->sphere === true ) { /* spherical form */
$f = exp( $p->x / ($this->a * $this->k0) );
$g = .5 * ($f - 1 / $f);
$temp = $this->lat0 + $p->y / ($this->a * $this->k0);
$h = cos( $temp );
$con = sqrt( (1.0 - $h * $h) / (1.0 + $g * $g) );
$lat = Proj4php::$common->asinz( $con );
if( $temp < 0 )
$lat = -$lat;
if( ($g == 0) && ($h == 0) ) {
$lon = $this->long0;
} else {
$lon = Proj4php::$common->adjust_lon( atan2( $g, $h ) + $this->long0 );
}
} else { // ellipsoidal form
$x = $p->x - $this->x0;
$y = $p->y - $this->y0;
 
$con = ($this->ml0 + $y / $this->k0) / $this->a;
$phi = $con;
for( $i = 0; true; $i++ ) {
$delta_phi = (($con + $this->e1 * sin( 2.0 * $phi ) - $this->e2 * sin( 4.0 * $phi ) + $this->e3 * sin( 6.0 * $phi )) / $this->e0) - $phi;
$phi += $delta_phi;
if( abs( $delta_phi ) <= Proj4php::$common->EPSLN )
break;
if( $i >= $max_iter ) {
Proj4php::reportError( "tmerc:inverse: Latitude failed to converge" );
return(95);
}
} // for()
if( abs( $phi ) < Proj4php::$common->HALF_PI ) {
// sincos(phi, &sin_phi, &cos_phi);
$sin_phi = sin( $phi );
$cos_phi = cos( $phi );
$tan_phi = tan( $phi );
$c = $this->ep2 * pow( $cos_phi, 2 );
$cs = pow( $c, 2 );
$t = pow( $tan_phi, 2 );
$ts = pow( $t, 2 );
$con = 1.0 - $this->es * pow( $sin_phi, 2 );
$n = $this->a / sqrt( $con );
$r = $n * (1.0 - $this->es) / $con;
$d = $x / ($n * $this->k0);
$ds = pow( $d, 2 );
$lat = $phi - ($n * $tan_phi * $ds / $r) * (0.5 - $ds / 24.0 * (5.0 + 3.0 * $t + 10.0 * $c - 4.0 * $cs - 9.0 * $this->ep2 - $ds / 30.0 * (61.0 + 90.0 * $t + 298.0 * $c + 45.0 * $ts - 252.0 * $this->ep2 - 3.0 * $cs)));
$lon = Proj4php::$common->adjust_lon( $this->long0 + ($d * (1.0 - $ds / 6.0 * (1.0 + 2.0 * $t + $c - $ds / 20.0 * (5.0 - 2.0 * $c + 28.0 * $t - 3.0 * $cs + 8.0 * $this->ep2 + 24.0 * $ts))) / $cos_phi) );
} else {
$lat = Proj4php::$common->HALF_PI * Proj4php::$common->sign( $y );
$lon = $this->long0;
}
}
$p->x = $lon;
$p->y = $lat;
return $p;
}
 
}
 
Proj4php::$proj['tmerc'] = new Proj4phpProjTmerc();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/projCode/nzmg.php
New file
0,0 → 1,338
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4php from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
/*******************************************************************************
NAME NEW ZEALAND MAP GRID
 
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the New Zealand Map Grid projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
 
 
ALGORITHM REFERENCES
 
1. Department of Land and Survey Technical Circular 1973/32
http://www.linz.govt.nz/docs/miscellaneous/nz-map-definition.pdf
 
2. OSG Technical Report 4.1
http://www.linz.govt.nz/docs/miscellaneous/nzmg.pdf
 
 
IMPLEMENTATION NOTES
 
The two references use different symbols for the calculated values. This
implementation uses the variable names similar to the symbols in reference [1].
 
The alogrithm uses different units for delta latitude and delta longitude.
The delta latitude is assumed to be in units of seconds of arc x 10^-5.
The delta longitude is the usual radians. Look out for these conversions.
 
The algorithm is described using complex arithmetic. There were three
options:
* find and use a Javascript library for complex arithmetic
* write my own complex library
* expand the complex arithmetic by hand to simple arithmetic
 
This implementation has expanded the complex multiplication operations
into parallel simple arithmetic operations for the real and imaginary parts.
The imaginary part is way over to the right of the display; this probably
violates every coding standard in the world, but, to me, it makes it much
more obvious what is going on.
 
The following complex operations are used:
- addition
- multiplication
- division
- complex number raised to integer power
- summation
 
A summary of complex arithmetic operations:
(from http://en.wikipedia.org/wiki/Complex_arithmetic)
addition: (a + bi) + (c + di) = (a + c) + (b + d)i
subtraction: (a + bi) - (c + di) = (a - c) + (b - d)i
multiplication: (a + bi) x (c + di) = (ac - bd) + (bc + ad)i
division: (a + bi) / (c + di) = [(ac + bd)/(cc + dd)] + [(bc - ad)/(cc + dd)]i
 
The algorithm needs to calculate summations of simple and complex numbers. This is
implemented using a for-loop, pre-loading the summed value to zero.
 
The algorithm needs to calculate theta^2, theta^3, etc while doing a summation.
There are three possible implementations:
- use pow in the summation loop - except for complex numbers
- precalculate the values before running the loop
- calculate theta^n = theta^(n-1) * theta during the loop
This implementation uses the third option for both real and complex arithmetic.
 
For example
psi_n = 1;
sum = 0;
for (n = 1; n <=6; n++) {
psi_n1 = psi_n * psi; // calculate psi^(n+1)
psi_n = psi_n1;
sum = sum + A[n] * psi_n;
}
 
 
TEST VECTORS
 
NZMG E, N: 2487100.638 6751049.719 metres
NZGD49 long, lat: 172.739194 -34.444066 degrees
 
NZMG E, N: 2486533.395 6077263.661 metres
NZGD49 long, lat: 172.723106 -40.512409 degrees
 
NZMG E, N: 2216746.425 5388508.765 metres
NZGD49 long, lat: 169.172062 -46.651295 degrees
 
Note that these test vectors convert from NZMG metres to lat/long referenced
to NZGD49, not the more usual WGS84. The difference is about 70m N/S and about
10m E/W.
 
These test vectors are provided in reference [1]. Many more test
vectors are available in
http://www.linz.govt.nz/docs/topography/topographicdata/placenamesdatabase/nznamesmar08.zip
which is a catalog of names on the 260-series maps.
 
 
EPSG CODES
 
NZMG EPSG:27200
NZGD49 EPSG:4272
 
http://spatialreference.org/ defines these as
Proj4php.defs["EPSG:4272"] = "+proj=longlat +ellps=intl +datum=nzgd49 +no_defs ";
Proj4php.defs["EPSG:27200"] = "+proj=nzmg +lat_0=-41 +lon_0=173 +x_0=2510000 +y_0=6023150 +ellps=intl +datum=nzgd49 +units=m +no_defs ";
 
 
LICENSE
Copyright: Stephen Irons 2008
Released under terms of the LGPL as per: http://www.gnu.org/copyleft/lesser.html
 
* ***************************************************************************** */
 
/**
Initialize New Zealand Map Grip projection
*/
class Proj4phpProjNzmg {
 
/**
* iterations: Number of iterations to refine inverse transform.
* 0 -> km accuracy
* 1 -> m accuracy -- suitable for most mapping applications
* 2 -> mm accuracy
*/
protected $iterations = 1;
 
/**
*
*/
public function init() {
$this->A = array( );
$this->A[1] = +0.6399175073;
$this->A[2] = -0.1358797613;
$this->A[3] = +0.063294409;
$this->A[4] = -0.02526853;
$this->A[5] = +0.0117879;
$this->A[6] = -0.0055161;
$this->A[7] = +0.0026906;
$this->A[8] = -0.001333;
$this->A[9] = +0.00067;
$this->A[10] = -0.00034;
 
$this->B_re = array( );
$this->B_im = array( );
$this->B_re[1] = +0.7557853228;
$this->B_im[1] = 0.0;
$this->B_re[2] = +0.249204646;
$this->B_im[2] = +0.003371507;
$this->B_re[3] = -0.001541739;
$this->B_im[3] = +0.041058560;
$this->B_re[4] = -0.10162907;
$this->B_im[4] = +0.01727609;
$this->B_re[5] = -0.26623489;
$this->B_im[5] = -0.36249218;
$this->B_re[6] = -0.6870983;
$this->B_im[6] = -1.1651967;
 
$this->C_re = array( );
$this->C_im = array( );
$this->C_re[1] = +1.3231270439;
$this->C_im[1] = 0.0;
$this->C_re[2] = -0.577245789;
$this->C_im[2] = -0.007809598;
$this->C_re[3] = +0.508307513;
$this->C_im[3] = -0.112208952;
$this->C_re[4] = -0.15094762;
$this->C_im[4] = +0.18200602;
$this->C_re[5] = +1.01418179;
$this->C_im[5] = +1.64497696;
$this->C_re[6] = +1.9660549;
$this->C_im[6] = +2.5127645;
 
$this->D = array( );
$this->D[1] = +1.5627014243;
$this->D[2] = +0.5185406398;
$this->D[3] = -0.03333098;
$this->D[4] = -0.1052906;
$this->D[5] = -0.0368594;
$this->D[6] = +0.007317;
$this->D[7] = +0.01220;
$this->D[8] = +0.00394;
$this->D[9] = -0.0013;
}
 
/**
New Zealand Map Grid Forward - long/lat to x/y
long/lat in radians
*/
public function forward( $p ) {
$lon = $p->x;
$lat = $p->y;
 
$delta_lat = $lat - $this->lat0;
$delta_lon = $lon - $this->long0;
 
// 1. Calculate d_phi and d_psi ... // and d_lambda
// For this algorithm, delta_latitude is in seconds of arc x 10-5, so we need to scale to those units. Longitude is radians.
$d_phi = $delta_lat / Proj4php::$common->SEC_TO_RAD * 1E-5;
$d_lambda = $delta_lon;
$d_phi_n = 1; // d_phi^0
 
$d_psi = 0;
for( $n = 1; $n <= 10; $n++ ) {
$d_phi_n = $d_phi_n * $d_phi;
$d_psi = $d_psi + $this->A[$n] * $d_phi_n;
}
 
// 2. Calculate theta
$th_re = $d_psi;
$th_im = $d_lambda;
 
// 3. Calculate z
$th_n_re = 1;
$th_n_im = 0; // theta^0
#$th_n_re1;
#$th_n_im1;
 
$z_re = 0;
$z_im = 0;
for( $n = 1; $n <= 6; $n++ ) {
$th_n_re1 = $th_n_re * $th_re - $th_n_im * $th_im;
$th_n_im1 = $th_n_im * $th_re + $th_n_re * $th_im;
$th_n_re = $th_n_re1;
$th_n_im = $th_n_im1;
$z_re = $z_re + $this->B_re[$n] * $th_n_re - $this->B_im[$n] * $th_n_im;
$z_im = $z_im + $this->B_im[$n] * $th_n_re + $this->B_re[$n] * $th_n_im;
}
 
// 4. Calculate easting and northing
$p->x = ($z_im * $this->a) + $this->x0;
$p->y = ($z_re * $this->a) + $this->y0;
 
return $p;
}
 
/**
New Zealand Map Grid Inverse - x/y to long/lat
*/
public function inverse( $p ) {
 
$x = $p->x;
$y = $p->y;
 
$delta_x = $x - $this->x0;
$delta_y = $y - $this->y0;
 
// 1. Calculate z
$z_re = $delta_y / $this->a;
$z_im = $delta_x / $this->a;
 
// 2a. Calculate theta - first approximation gives km accuracy
$z_n_re = 1;
$z_n_im = 0; // z^0
$z_n_re1;
$z_n_im1;
 
$th_re = 0;
$th_im = 0;
for( $n = 1; $n <= 6; $n++ ) {
$z_n_re1 = $z_n_re * $z_re - $z_n_im * $z_im;
$z_n_im1 = $z_n_im * $z_re + $z_n_re * $z_im;
$z_n_re = $z_n_re1;
$z_n_im = $z_n_im1;
$th_re = $th_re + $this->C_re[$n] * $z_n_re - $this->C_im[$n] * $z_n_im;
$th_im = $th_im + $this->C_im[$n] * $z_n_re + $this->C_re[$n] * $z_n_im;
}
 
// 2b. Iterate to refine the accuracy of the calculation
// 0 iterations gives km accuracy
// 1 iteration gives m accuracy -- good enough for most mapping applications
// 2 iterations bives mm accuracy
for( $i = 0; $i < $this->iterations; $i++ ) {
$th_n_re = $th_re;
$th_n_im = $th_im;
$th_n_re1;
$th_n_im1;
 
$num_re = $z_re;
$num_im = $z_im;
for( $n = 2; $n <= 6; $n++ ) {
$th_n_re1 = $th_n_re * th_re - $th_n_im * $th_im;
$th_n_im1 = $th_n_im * $th_re + $th_n_re * $th_im;
$th_n_re = $th_n_re1;
$th_n_im = $th_n_im1;
$num_re = $num_re + ($n - 1) * ($this->B_re[$n] * $th_n_re - $this->B_im[$n] * $th_n_im);
$num_im = $num_im + (n - 1) * ($this->B_im[$n] * $th_n_re + $this->B_re[$n] * $th_n_im);
}
 
$th_n_re = 1;
$th_n_im = 0;
$den_re = $this->B_re[1];
$den_im = $this->B_im[1];
for( $n = 2; $n <= 6; $n++ ) {
$th_n_re1 = $th_n_re * $th_re - $th_n_im * $th_im;
$th_n_im1 = $th_n_im * $th_re + $th_n_re * $th_im;
$th_n_re = $th_n_re1;
$th_n_im = $th_n_im1;
$den_re = $den_re + $n * ($this->B_re[$n] * $th_n_re - $this->B_im[$n] * $th_n_im);
$den_im = $den_im + $n * ($this->B_im[n] * $th_n_re + $this->B_re[$n] * $th_n_im);
}
 
// Complex division
$den2 = $den_re * $den_re + $den_im * $den_im;
$th_re = ($num_re * $den_re + $num_im * $den_im) / $den2;
$th_im = ($num_im * $den_re - $num_re * $den_im) / $den2;
}
 
// 3. Calculate d_phi ... // and d_lambda
$d_psi = $th_re;
$d_lambda = $th_im;
$d_psi_n = 1; // d_psi^0
 
$d_phi = 0;
for( $n = 1; $n <= 9; $n++ ) {
$d_psi_n = $d_psi_n * $d_psi;
$d_phi = $d_phi + $this->D[$n] * $d_psi_n;
}
 
// 4. Calculate latitude and longitude
// d_phi is calcuated in second of arc * 10^-5, so we need to scale back to radians. d_lambda is in radians.
$lat = $this->lat0 + ($d_phi * Proj4php::$common->SEC_TO_RAD * 1E5);
$lon = $this->long0 + $d_lambda;
 
$p->x = $lon;
$p->y = $lat;
 
return $p;
}
 
}
 
Proj4php::$proj['nzmg'] = new Proj4phpProjNzmg();
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/proj4phpPoint.php
New file
0,0 → 1,86
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4js from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodmap.com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
 
/**
* point object, nothing fancy, just allows values to be
* passed back and forth by reference rather than by value.
* Other point classes may be used as long as they have
* x and y properties, which will get modified in the transform method.
*/
class proj4phpPoint {
 
public $x;
public $y;
public $z;
 
/**
* Constructor: Proj4js.Point
*
* Parameters:
* - x {float} or {Array} either the first coordinates component or
* the full coordinates
* - y {float} the second component
* - z {float} the third component, optional.
*/
public function __construct( $x = null, $y = null, $z = null ) {
if( is_array( $x ) ) {
$this->x = $x[0];
$this->y = $x[1];
$this->z = isset($x[2]) ? $x[2] : 0.0;#(count( $x ) > 2) ? $x[2] : 0.0;
} else if( is_string( $x ) && !is_numeric( $y ) ) {
$coord = explode( ' ', $x );
$this->x = floatval( $coord[0] );
$this->y = floatval( $coord[1] );
$this->z = (count( $coord ) > 2) ? floatval( $coord[2] ) : 0.0;
} else {
$this->x = $x !== null ? $x : 0.0;
$this->y = $y !== null ? $y : 0.0;
$this->z = $z !== null ? $z : 0.0;
}
}
 
/**
* APIMethod: clone
* Build a copy of a Proj4js.Point object.
*
* renamed because of PHP keyword.
*
* Return:
* {Proj4js}.Point the cloned point.
*/
public function _clone() {
return new Proj4phpPoint( $this->x, $this->y, $this->z );
}
 
/**
* APIMethod: toString
* Return a readable string version of the point
*
* Return:
* {String} String representation of Proj4js.Point object.
* (ex. <i>"x=5,y=42"</i>)
*/
public function toString() {
return "x=" . $this->x . ",y=" . $this->y;
}
 
/**
* APIMethod: toShortString
* Return a short string version of the point.
*
* Return:
* {String} Shortened String representation of Proj4js.Point object.
* (ex. <i>"5, 42"</i>)
*/
public function toShortString() {
return $this->x . " " . $this->y;
}
 
}
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/LGPL GNU lesser licence.txt
New file
0,0 → 1,165
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
 
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
 
 
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
 
0. Additional Definitions.
 
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
 
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
 
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
 
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
 
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
 
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
 
1. Exception to Section 3 of the GNU GPL.
 
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
 
2. Conveying Modified Versions.
 
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
 
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
 
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
 
3. Object Code Incorporating Material from Library Header Files.
 
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
 
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
 
b) Accompany the object code with a copy of the GNU GPL and this license
document.
 
4. Combined Works.
 
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
 
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
 
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
 
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
 
d) Do one of the following:
 
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
 
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
 
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
 
5. Combined Libraries.
 
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
 
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
 
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
 
6. Revised Versions of the GNU Lesser General Public License.
 
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
 
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
 
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/proj4phpDatum.php
New file
0,0 → 1,401
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4js from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodma$p->com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
 
/** datum object
*/
class proj4phpDatum {
 
public $datum_type;
public $datum_params;
/**
*
* @param type $proj
*/
public function __construct( $proj ) {
$this->datum_type = Proj4php::$common->PJD_WGS84; //default setting
if( isset($proj->datumCode) && $proj->datumCode == 'none' ) {
$this->datum_type = Proj4php::$common->PJD_NODATUM;
}
if( isset( $proj->datum_params ) ) {
for( $i = 0; $i < sizeof( $proj->datum_params ); $i++ ) {
$proj->datum_params[$i] = floatval( $proj->datum_params[$i] );
}
if( $proj->datum_params[0] != 0 || $proj->datum_params[1] != 0 || $proj->datum_params[2] != 0 ) {
$this->datum_type = Proj4php::$common->PJD_3PARAM;
}
if( sizeof( $proj->datum_params ) > 3 ) {
if( $proj->datum_params[3] != 0 || $proj->datum_params[4] != 0 ||
$proj->datum_params[5] != 0 || $proj->datum_params[6] != 0 ) {
$this->datum_type = Proj4php::$common->PJD_7PARAM;
$proj->datum_params[3] *= Proj4php::$common->SEC_TO_RAD;
$proj->datum_params[4] *= Proj4php::$common->SEC_TO_RAD;
$proj->datum_params[5] *= Proj4php::$common->SEC_TO_RAD;
$proj->datum_params[6] = ($proj->datum_params[6] / 1000000.0) + 1.0;
}
}
$this->datum_params = $proj->datum_params;
}
if( isset( $proj ) ) {
$this->a = $proj->a; //datum object also uses these values
$this->b = $proj->b;
$this->es = $proj->es;
$this->ep2 = $proj->ep2;
#$this->datum_params = $proj->datum_params;
}
}
/**
*
* @param type $dest
* @return boolean Returns TRUE if the two datums match, otherwise FALSE.
* @throws type
*/
public function compare_datums( $dest ) {
if( $this->datum_type != $dest->datum_type ) {
return false; // false, datums are not equal
} else if( $this->a != $dest->a || abs( $this->es - $dest->es ) > 0.000000000050 ) {
// the tolerence for es is to ensure that GRS80 and WGS84
// are considered identical
return false;
} else if( $this->datum_type == Proj4php::$common->PJD_3PARAM ) {
return ($this->datum_params[0] == $dest->datum_params[0]
&& $this->datum_params[1] == $dest->datum_params[1]
&& $this->datum_params[2] == $dest->datum_params[2]);
} else if( $this->datum_type == Proj4php::$common->PJD_7PARAM ) {
return ($this->datum_params[0] == $dest->datum_params[0]
&& $this->datum_params[1] == $dest->datum_params[1]
&& $this->datum_params[2] == $dest->datum_params[2]
&& $this->datum_params[3] == $dest->datum_params[3]
&& $this->datum_params[4] == $dest->datum_params[4]
&& $this->datum_params[5] == $dest->datum_params[5]
&& $this->datum_params[6] == $dest->datum_params[6]);
} else if( $this->datum_type == Proj4php::$common->PJD_GRIDSHIFT ||
$dest->datum_type == Proj4php::$common->PJD_GRIDSHIFT ) {
throw(new Exception( "ERROR: Grid shift transformations are not implemented." ));
return false;
}
return true; // datums are equal
}
 
/*
* The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
* (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
* according to the current ellipsoid parameters.
*
* Latitude : Geodetic latitude in radians (input)
* Longitude : Geodetic longitude in radians (input)
* Height : Geodetic height, in meters (input)
* X : Calculated Geocentric X coordinate, in meters (output)
* Y : Calculated Geocentric Y coordinate, in meters (output)
* Z : Calculated Geocentric Z coordinate, in meters (output)
*
*/
public function geodetic_to_geocentric( $p ) {
$Longitude = $p->x;
$Latitude = $p->y;
$Height = isset( $p->z ) ? $p->z : 0; //Z value not always supplied
$Error_Code = 0; // GEOCENT_NO_ERROR;
/*
* * Don't blow up if Latitude is just a little out of the value
* * range as it may just be a rounding issue. Also removed longitude
* * test, it should be wrapped by cos() and sin(). NFW for PROJ.4, Sep/2001.
*/
if( $Latitude < -Proj4php::$common->HALF_PI && $Latitude > -1.001 * Proj4php::$common->HALF_PI ) {
$Latitude = -Proj4php::$common->HALF_PI;
} else if( $Latitude > Proj4php::$common->HALF_PI && $Latitude < 1.001 * Proj4php::$common->HALF_PI ) {
$Latitude = Proj4php::$common->HALF_PI;
} else if( ($Latitude < -Proj4php::$common->HALF_PI) || ($Latitude > Proj4php::$common->HALF_PI) ) {
/* Latitude out of range */
Proj4php::reportError( 'geocent:lat out of range:' . $Latitude );
return null;
}
 
if( $Longitude > Proj4php::$common->PI )
$Longitude -= (2 * Proj4php::$common->PI);
$Sin_Lat = sin( $Latitude ); /* sin(Latitude) */
$Cos_Lat = cos( $Latitude ); /* cos(Latitude) */
$Sin2_Lat = $Sin_Lat * $Sin_Lat; /* Square of sin(Latitude) */
$Rn = $this->a / (sqrt( 1.0e0 - $this->es * $Sin2_Lat )); /* Earth radius at location */
$p->x = ($Rn + $Height) * $Cos_Lat * cos( $Longitude );
$p->y = ($Rn + $Height) * $Cos_Lat * sin( $Longitude );
$p->z = (($Rn * (1 - $this->es)) + $Height) * $Sin_Lat;
return $Error_Code;
}
 
/**
*
* @param object $p
* @return type
*/
public function geocentric_to_geodetic( $p ) {
/* local defintions and variables */
/* end-criterium of loop, accuracy of sin(Latitude) */
$genau = 1.E-12;
$genau2 = ($genau * $genau);
$maxiter = 30;
$X = $p->x;
$Y = $p->y;
$Z = $p->z ? $p->z : 0.0; //Z value not always supplied
/*
$P; // distance between semi-minor axis and location
$RR; // distance between center and location
$CT; // sin of geocentric latitude
$ST; // cos of geocentric latitude
$RX;
$RK;
$RN; // Earth radius at location
$CPHI0; // cos of start or old geodetic latitude in iterations
$SPHI0; // sin of start or old geodetic latitude in iterations
$CPHI; // cos of searched geodetic latitude
$SPHI; // sin of searched geodetic latitude
$SDPHI; // end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1))
$At_Pole; // indicates location is in polar region
$iter; // of continous iteration, max. 30 is always enough (s.a.)
$Longitude;
$Latitude;
$Height;
*/
$At_Pole = false;
$P = sqrt( $X * $X + $Y * $Y );
$RR = sqrt( $X * $X + $Y * $Y + $Z * $Z );
 
/* special cases for latitude and longitude */
if( $P / $this->a < $genau ) {
 
/* special case, if P=0. (X=0., Y=0.) */
$At_Pole = true;
$Longitude = 0.0;
 
/* if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
* of ellipsoid (=center of mass), Latitude becomes PI/2 */
if( $RR / $this->a < $genau ) {
$Latitude = Proj4php::$common->HALF_PI;
$Height = -$this->b;
return;
}
} else {
/* ellipsoidal (geodetic) longitude
* interval: -PI < Longitude <= +PI */
$Longitude = atan2( $Y, $X );
}
 
/* --------------------------------------------------------------
* Following iterative algorithm was developped by
* "Institut für Erdmessung", University of Hannover, July 1988.
* Internet: www.ife.uni-hannover.de
* Iterative computation of CPHI,SPHI and Height.
* Iteration of CPHI and SPHI to 10**-12 radian res$p->
* 2*10**-7 arcsec.
* --------------------------------------------------------------
*/
$CT = $Z / $RR;
$ST = $P / $RR;
$RX = 1.0 / sqrt( 1.0 - $this->es * (2.0 - $this->es) * $ST * $ST );
$CPHI0 = $ST * (1.0 - $this->es) * $RX;
$SPHI0 = $CT * $RX;
$iter = 0;
 
/* loop to find sin(Latitude) res$p-> Latitude
* until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
do {
++$iter;
$RN = $this->a / sqrt( 1.0 - $this->es * $SPHI0 * $SPHI0 );
 
/* ellipsoidal (geodetic) height */
$Height = $P * $CPHI0 + $Z * $SPHI0 - $RN * (1.0 - $this->es * $SPHI0 * $SPHI0);
 
$RK = $this->es * $RN / ($RN + $Height);
$RX = 1.0 / sqrt( 1.0 - $RK * (2.0 - $RK) * $ST * $ST );
$CPHI = $ST * (1.0 - $RK) * $RX;
$SPHI = $CT * $RX;
$SDPHI = $SPHI * $CPHI0 - $CPHI * $SPHI0;
$CPHI0 = $CPHI;
$SPHI0 = $SPHI;
} while( $SDPHI * $SDPHI > $genau2 && $iter < $maxiter );
 
/* ellipsoidal (geodetic) latitude */
$Latitude = atan( $SPHI / abs( $CPHI ) );
 
$p->x = $Longitude;
$p->y = $Latitude;
$p->z = $Height;
return $p;
}
 
/**
* Convert_Geocentric_To_Geodetic
* The method used here is derived from 'An Improved Algorithm for
* Geocentric to Geodetic Coordinate Conversion', by Ralph Toms, Feb 1996
*
* @param object Point $p
* @return object Point $p
*/
public function geocentric_to_geodetic_noniter( $p ) {
/*
$Longitude;
$Latitude;
$Height;
$W; // distance from Z axis
$W2; // square of distance from Z axis
$T0; // initial estimate of vertical component
$T1; // corrected estimate of vertical component
$S0; // initial estimate of horizontal component
$S1; // corrected estimate of horizontal component
$Sin_B0; // sin(B0), B0 is estimate of Bowring aux variable
$Sin3_B0; // cube of sin(B0)
$Cos_B0; // cos(B0)
$Sin_p1; // sin(phi1), phi1 is estimated latitude
$Cos_p1; // cos(phi1)
$Rn; // Earth radius at location
$Sum; // numerator of cos(phi1)
$At_Pole; // indicates location is in polar region
*/
$X = floatval( $p->x ); // cast from string to float
$Y = floatval( $p->y );
$Z = floatval( $p->z ? $p->z : 0 );
 
$At_Pole = false;
if( $X <> 0.0 ) {
$Longitude = atan2( $Y, $X );
} else {
if( $Y > 0 ) {
$Longitude = Proj4php::$common->HALF_PI;
} else if( Y < 0 ) {
$Longitude = -Proj4php::$common->HALF_PI;
} else {
$At_Pole = true;
$Longitude = 0.0;
if( $Z > 0.0 ) { /* north pole */
$Latitude = Proj4php::$common->HALF_PI;
} else if( Z < 0.0 ) { /* south pole */
$Latitude = -Proj4php::$common->HALF_PI;
} else { /* center of earth */
$Latitude = Proj4php::$common->HALF_PI;
$Height = -$this->b;
return;
}
}
}
$W2 = $X * $X + $Y * $Y;
$W = sqrt( $W2 );
$T0 = $Z * Proj4php::$common->AD_C;
$S0 = sqrt( $T0 * $T0 + $W2 );
$Sin_B0 = $T0 / $S0;
$Cos_B0 = $W / $S0;
$Sin3_B0 = $Sin_B0 * $Sin_B0 * $Sin_B0;
$T1 = $Z + $this->b * $this->ep2 * $Sin3_B0;
$Sum = $W - $this->a * $this->es * $Cos_B0 * $Cos_B0 * $Cos_B0;
$S1 = sqrt( $T1 * $T1 + $Sum * $Sum );
$Sin_p1 = $T1 / $S1;
$Cos_p1 = $Sum / $S1;
$Rn = $this->a / sqrt( 1.0 - $this->es * $Sin_p1 * $Sin_p1 );
if( $Cos_p1 >= Proj4php::$common->COS_67P5 ) {
$Height = $W / $Cos_p1 - $Rn;
} else if( $Cos_p1 <= -Proj4php::$common->COS_67P5 ) {
$Height = $W / -$Cos_p1 - $Rn;
} else {
$Height = $Z / $Sin_p1 + $Rn * ($this->es - 1.0);
}
if( $At_Pole == false ) {
$Latitude = atan( $Sin_p1 / $Cos_p1 );
}
$p->x = $Longitude;
$p->y = $Latitude;
$p->z = $Height;
return $p;
}
 
/************************************************************** */
// pj_geocentic_to_wgs84( p )
// p = point to transform in geocentric coordinates (x,y,z)
public function geocentric_to_wgs84( $p ) {
 
if( $this->datum_type == Proj4php::$common->PJD_3PARAM ) {
// if( x[io] == HUGE_VAL )
// continue;
$p->x += $this->datum_params[0];
$p->y += $this->datum_params[1];
$p->z += $this->datum_params[2];
} else if( $this->datum_type == Proj4php::$common->PJD_7PARAM ) {
$Dx_BF = $this->datum_params[0];
$Dy_BF = $this->datum_params[1];
$Dz_BF = $this->datum_params[2];
$Rx_BF = $this->datum_params[3];
$Ry_BF = $this->datum_params[4];
$Rz_BF = $this->datum_params[5];
$M_BF = $this->datum_params[6];
// if( x[io] == HUGE_VAL )
// continue;
$p->x = $M_BF * ( $p->x - $Rz_BF * $p->y + $Ry_BF * $p->z) + $Dx_BF;
$p->y = $M_BF * ( $Rz_BF * $p->x + $p->y - $Rx_BF * $p->z) + $Dy_BF;
$p->z = $M_BF * (-$Ry_BF * $p->x + $Rx_BF * $p->y + $p->z) + $Dz_BF;
}
}
 
/*************************************************************** */
 
// pj_geocentic_from_wgs84()
// coordinate system definition,
// point to transform in geocentric coordinates (x,y,z)
public function geocentric_from_wgs84( $p ) {
 
if( $this->datum_type == Proj4php::$common->PJD_3PARAM ) {
//if( x[io] == HUGE_VAL )
// continue;
$p->x -= $this->datum_params[0];
$p->y -= $this->datum_params[1];
$p->z -= $this->datum_params[2];
} else if( $this->datum_type == Proj4php::$common->PJD_7PARAM ) {
$Dx_BF = $this->datum_params[0];
$Dy_BF = $this->datum_params[1];
$Dz_BF = $this->datum_params[2];
$Rx_BF = $this->datum_params[3];
$Ry_BF = $this->datum_params[4];
$Rz_BF = $this->datum_params[5];
$M_BF = $this->datum_params[6];
$x_tmp = ($p->x - $Dx_BF) / $M_BF;
$y_tmp = ($p->y - $Dy_BF) / $M_BF;
$z_tmp = ($p->z - $Dz_BF) / $M_BF;
//if( x[io] == HUGE_VAL )
// continue;
 
$p->x = $x_tmp + $Rz_BF * $y_tmp - $Ry_BF * $z_tmp;
$p->y = -$Rz_BF * $x_tmp + $y_tmp + $Rx_BF * $z_tmp;
$p->z = $Ry_BF * $x_tmp - $Rx_BF * $y_tmp + $z_tmp;
} //cs_geocentric_from_wgs84()
}
 
}
 
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/proj4phpProj.php
New file
0,0 → 1,641
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4js from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodmap.com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class Proj4phpProj {
 
/**
* Property: readyToUse
* Flag to indicate if initialization is complete for $this Proj object
*/
public $readyToUse = false;
 
/**
* Property: title
* The title to describe the projection
*/
public $title = null;
 
/**
* Property: projName
* The projection class for $this projection, e.g. lcc (lambert conformal conic,
* or merc for mercator). These are exactly equivalent to their Proj4
* counterparts.
*/
public $projName = null;
/**
* Property: projection
* The projection object for $this projection. */
public $projection = null;
 
/**
* Property: units
* The units of the projection. Values include 'm' and 'degrees'
*/
public $units = null;
 
/**
* Property: datum
* The datum specified for the projection
*/
public $datum = null;
 
/**
* Property: x0
* The x coordinate origin
*/
public $x0 = 0;
 
/**
* Property: y0
* The y coordinate origin
*/
public $y0 = 0;
 
/**
* Property: localCS
* Flag to indicate if the projection is a local one in which no transforms
* are required.
*/
public $localCS = false;
/**
*
* @var type
*/
protected $wktRE = '/^(\w+)\[(.*)\]$/';
 
/**
* Constructor: initialize
* Constructor for Proj4php::Proj objects
*
* Parameters:
* $srsCode - a code for map projection definition parameters. These are usually
* (but not always) EPSG codes.
*/
public function __construct( $srsCode ) {
$this->srsCodeInput = $srsCode;
 
//check to see if $this is a WKT string
if( (strpos( $srsCode, 'GEOGCS' ) !== false) ||
(strpos( $srsCode, 'GEOCCS' ) !== false) ||
(strpos( $srsCode, 'PROJCS' ) !== false) ||
(strpos( $srsCode, 'LOCAL_CS' ) !== false) ) {
$this->parseWKT( $srsCode );
$this->deriveConstants();
$this->loadProjCode( $this->projName );
return;
}
 
// DGR 2008-08-03 : support urn and url
if( strpos( $srsCode, 'urn:' ) === 0 ) {
//urn:ORIGINATOR:def:crs:CODESPACE:VERSION:ID
$urn = explode( ':', $srsCode );
if( ($urn[1] == 'ogc' || $urn[1] == 'x-ogc') &&
($urn[2] == 'def') &&
($urn[3] == 'crs') ) {
$srsCode = $urn[4] . ':' . $urn[strlen( $urn ) - 1];
}
} else if( strpos( $srsCode, 'http://' ) === 0 ) {
//url#ID
$url = explode( '#', $srsCode );
if( preg_match( "/epsg.org/", $url[0] ) ) {
// http://www.epsg.org/#
$srsCode = 'EPSG:' . $url[1];
} else if( preg_match( "/RIG.xml/", $url[0] ) ) {
//http://librairies.ign.fr/geoportail/resources/RIG.xml#
//http://interop.ign.fr/registers/ign/RIG.xml#
$srsCode = 'IGNF:' . $url[1];
}
}
$this->srsCode = strtoupper( $srsCode );
if( strpos( $this->srsCode, "EPSG" ) === 0 ) {
$this->srsCode = $this->srsCode;
$this->srsAuth = 'epsg';
$this->srsProjNumber = substr( $this->srsCode, 5 );
// DGR 2007-11-20 : authority IGNF
} else if( strpos( $this->srsCode, "IGNF" ) === 0 ) {
$this->srsCode = $this->srsCode;
$this->srsAuth = 'IGNF';
$this->srsProjNumber = substr( $this->srsCode, 5 );
// DGR 2008-06-19 : pseudo-authority CRS for WMS
} else if( strpos( $this->srsCode, "CRS" ) === 0 ) {
$this->srsCode = $this->srsCode;
$this->srsAuth = 'CRS';
$this->srsProjNumber = substr( $this->srsCode, 4 );
} else {
$this->srsAuth = '';
$this->srsProjNumber = $this->srsCode;
}
$this->loadProjDefinition();
}
 
/**
* Function: loadProjDefinition
* Loads the coordinate system initialization string if required.
* Note that dynamic loading happens asynchronously so an application must
* wait for the readyToUse property is set to true.
* To prevent dynamic loading, include the defs through a script tag in
* your application.
*
*/
public function loadProjDefinition() {
//check in memory
if( array_key_exists( $this->srsCode, Proj4php::$defs ) ) {
$this->defsLoaded();
return;
}
//else check for def on the server
$filename = dirname( __FILE__ ) . '/defs/' . strtoupper( $this->srsAuth ) . $this->srsProjNumber . '.php';
try {
Proj4php::loadScript( $filename );
$this->defsLoaded(); // succes
} catch ( Exception $e ) {
$this->loadFromService(); // fail
}
}
 
/**
* Function: loadFromService
* Creates the REST URL for loading the definition from a web service and
* loads it.
*
*
* DO IT AGAIN. : SHOULD PHP CODE BE GET BY WEBSERVICES ?
*/
public function loadFromService() {
//else load from web service
$url = Proj4php::$defsLookupService . '/' . $this->srsAuth . '/' . $this->srsProjNumber . '/proj4/';
try {
Proj4php::$defs[strtoupper($this->srsAuth) . ":" . $this->srsProjNumber] = Proj4php::loadScript( $url );
} catch ( Exception $e ) {
$this->defsFailed();
}
}
 
/**
* Function: defsLoaded
* Continues the Proj object initilization once the def file is loaded
*
*/
public function defsLoaded() {
$this->parseDefs();
$this->loadProjCode( $this->projName );
}
 
/**
* Function: checkDefsLoaded
* $this is the loadCheck method to see if the def object exists
*
*/
public function checkDefsLoaded() {
return isset(Proj4php::$defs[$this->srsCode]) && !empty(Proj4php::$defs[$this->srsCode]);
}
 
/**
* Function: defsFailed
* Report an error in loading the defs file, but continue on using WGS84
*
*/
public function defsFailed() {
Proj4php::reportError( 'failed to load projection definition for: ' . $this->srsCode );
Proj4php::$defs[$this->srsCode] = Proj4php::$defs['WGS84']; //set it to something so it can at least continue
$this->defsLoaded();
}
 
/**
* Function: loadProjCode
* Loads projection class code dynamically if required.
* Projection code may be included either through a script tag or in
* a built version of proj4php
*
* An exception occurs if the projection is not found.
*/
public function loadProjCode( $projName ) {
if( array_key_exists( $projName, Proj4php::$proj ) ) {
$this->initTransforms();
return;
}
//the filename for the projection code
$filename = dirname( __FILE__ ) . '/projCode/' . $projName . '.php';
 
try {
Proj4php::loadScript( $filename );
$this->loadProjCodeSuccess( $projName );
} catch ( Exception $e ) {
$this->loadProjCodeFailure( $projName );
}
}
 
/**
* Function: loadProjCodeSuccess
* Loads any proj dependencies or continue on to final initialization.
*
*/
public function loadProjCodeSuccess( $projName ) {
if( isset(Proj4php::$proj[$projName]->dependsOn) && !empty(Proj4php::$proj[$projName]->dependsOn)) {
$this->loadProjCode( Proj4php::$proj[$projName]->dependsOn );
} else {
$this->initTransforms();
}
}
 
/**
* Function: defsFailed
* Report an error in loading the proj file. Initialization of the Proj
* object has failed and the readyToUse flag will never be set.
*
*/
public function loadProjCodeFailure( $projName ) {
Proj4php::reportError( "failed to find projection file for: " . $projName );
//TBD initialize with identity transforms so proj will still work?
}
 
/**
* Function: checkCodeLoaded
* $this is the loadCheck method to see if the projection code is loaded
*
*/
public function checkCodeLoaded( $projName ) {
return isset(Proj4php::$proj[$projName]) && !empty(Proj4php::$proj[$projName]);
}
 
/**
* Function: initTransforms
* Finalize the initialization of the Proj object
*
*/
public function initTransforms() {
$this->projection = clone(Proj4php::$proj[$this->projName]);
Proj4php::extend( $this->projection, $this );
$this->init();
// initiate depending class
if( false !== ($dependsOn = isset($this->projection->dependsOn) && !empty($this->projection->dependsOn) ? $this->projection->dependsOn : false) ) {
Proj4php::extend( Proj4php::$proj[$dependsOn], $this->projection) &&
Proj4php::$proj[$dependsOn]->init() &&
Proj4php::extend( $this->projection, Proj4php::$proj[$dependsOn] );
}
$this->readyToUse = true;
}
 
/**
*
*/
public function init() {
$this->projection->init();
}
 
/**
*
* @param type $pt
* @return type
*/
public function forward( $pt ) {
return $this->projection->forward( $pt );
}
 
/**
*
* @param type $pt
* @return type
*/
public function inverse( $pt ) {
return $this->projection->inverse( $pt );
}
 
/**
* Function: parseWKT
* Parses a WKT string to get initialization parameters
*
*/
public function parseWKT( $wkt ) {
if( false === ($match = preg_match( $this->wktRE, $wkt, $wktMatch )) )
return;
$wktObject = $wktMatch[1];
$wktContent = $wktMatch[2];
$wktTemp = explode( ",", $wktContent );
$wktName = (strtoupper($wktObject) == "TOWGS84") ? "TOWGS84" : array_shift( $wktTemp );
$wktName = preg_replace( '/^\"/', "", $wktName );
$wktName = preg_replace( '/\"$/', "", $wktName );
 
/*
$wktContent = implode(",",$wktTemp);
$wktArray = explode("],",$wktContent);
for ($i=0; i<sizeof($wktArray)-1; ++$i) {
$wktArray[$i] .= "]";
}
*/
 
$wktArray = array();
$bkCount = 0;
$obj = "";
foreach( $wktTemp as $token ) {
$bkCount = substr_count($token, "[") - substr_count($token, "]");
// ???
$obj .= $token;
if( $bkCount === 0 ) {
array_push( $wktArray, $obj );
$obj = "";
} else {
$obj .= ",";
}
}
 
//do something based on the type of the wktObject being parsed
//add in variations in the spelling as required
switch( $wktObject ) {
case 'LOCAL_CS':
$this->projName = 'identity';
$this->localCS = true;
$this->srsCode = $wktName;
break;
case 'GEOGCS':
$this->projName = 'longlat';
$this->geocsCode = $wktName;
if( !$this->srsCode )
$this->srsCode = $wktName;
break;
case 'PROJCS':
$$this->srsCode = $wktName;
break;
case 'GEOCCS':
break;
case 'PROJECTION':
$this->projName = Proj4php::$wktProjections[$wktName];
break;
case 'DATUM':
$this->datumName = $wktName;
break;
case 'LOCAL_DATUM':
$this->datumCode = 'none';
break;
case 'SPHEROID':
$this->ellps = $wktName;
$this->a = floatval( array_shift( $wktArray ) );
$this->rf = floatval( array_shift( $wktArray ) );
break;
case 'PRIMEM':
$this->from_greenwich = floatval( array_shift( $wktArray ) ); //to radians?
break;
case 'UNIT':
$this->units = $wktName;
$this->unitsPerMeter = floatval( array_shift( $wktArray ) );
break;
case 'PARAMETER':
$name = strtolower( $wktName );
$value = floatval( array_shift( $wktArray ) );
//there may be many variations on the wktName values, add in case
//statements as required
switch( $name ) {
case 'false_easting':
$this->x0 = $value;
break;
case 'false_northing':
$this->y0 = $value;
break;
case 'scale_factor':
$this->k0 = $value;
break;
case 'central_meridian':
$this->long0 = $value * Proj4php::$common->D2R;
break;
case 'latitude_of_origin':
$this->lat0 = $value * Proj4php::$common->D2R;
break;
case 'more_here':
break;
default:
break;
}
break;
case 'TOWGS84':
$this->datum_params = $wktArray;
break;
//DGR 2010-11-12: AXIS
case 'AXIS':
$name = strtolower( $wktName );
$value = array_shift( $wktArray );
switch( $value ) {
case 'EAST' : $value = 'e';
break;
case 'WEST' : $value = 'w';
break;
case 'NORTH': $value = 'n';
break;
case 'SOUTH': $value = 's';
break;
case 'UP' : $value = 'u';
break;
case 'DOWN' : $value = 'd';
break;
case 'OTHER':
default : $value = ' ';
break; //FIXME
}
if( !$this->axis ) {
$this->axis = "enu";
}
switch( $name ) {
case 'X': $this->axis = $value . substr( $this->axis, 1, 2 );
break;
case 'Y': $this->axis = substr( $this->axis, 0, 1 ) . $value . substr( $this->axis, 2, 1 );
break;
case 'Z': $this->axis = substr( $this->axis, 0, 2 ) . $value;
break;
default : break;
}
case 'MORE_HERE':
break;
default:
break;
}
foreach( $wktArray as $wktArrayContent )
$this->parseWKT( $wktArrayContent );
}
 
/**
* Function: parseDefs
* Parses the PROJ.4 initialization string and sets the associated properties.
*
*/
public function parseDefs() {
$this->defData = Proj4php::$defs[$this->srsCode];
#$paramName;
#$paramVal;
if( !$this->defData ) {
return;
}
$paramArray = explode( "+", $this->defData );
for( $prop = 0; $prop < sizeof( $paramArray ); $prop++ ) {
if( strlen( $paramArray[$prop] ) == 0 )
continue;
$property = explode( "=", $paramArray[$prop] );
$paramName = strtolower( $property[0] );
if( sizeof( $property ) >= 2 ) {
$paramVal = $property[1];
}
 
switch( trim( $paramName ) ) { // trim out spaces
case "": break; // throw away nameless parameter
case "title": $this->title = $paramVal;
break;
case "proj": $this->projName = trim( $paramVal );
break;
case "units": $this->units = trim( $paramVal );
break;
case "datum": $this->datumCode = trim( $paramVal );
break;
case "nadgrids": $this->nagrids = trim( $paramVal );
break;
case "ellps": $this->ellps = trim( $paramVal );
break;
case "a": $this->a = floatval( $paramVal );
break; // semi-major radius
case "b": $this->b = floatval( $paramVal );
break; // semi-minor radius
// DGR 2007-11-20
case "rf": $this->rf = floatval( paramVal );
break; // inverse flattening rf= a/(a-b)
case "lat_0": $this->lat0 = $paramVal * Proj4php::$common->D2R;
break; // phi0, central latitude
case "lat_1": $this->lat1 = $paramVal * Proj4php::$common->D2R;
break; //standard parallel 1
case "lat_2": $this->lat2 = $paramVal * Proj4php::$common->D2R;
break; //standard parallel 2
case "lat_ts": $this->lat_ts = $paramVal * Proj4php::$common->D2R;
break; // used in merc and eqc
case "lon_0": $this->long0 = $paramVal * Proj4php::$common->D2R;
break; // lam0, central longitude
case "alpha": $this->alpha = floatval( $paramVal ) * Proj4php::$common->D2R;
break; //for somerc projection
case "lonc": $this->longc = paramVal * Proj4php::$common->D2R;
break; //for somerc projection
case "x_0": $this->x0 = floatval( $paramVal );
break; // false easting
case "y_0": $this->y0 = floatval( $paramVal );
break; // false northing
case "k_0": $this->k0 = floatval( $paramVal );
break; // projection scale factor
case "k": $this->k0 = floatval( $paramVal );
break; // both forms returned
case "r_a": $this->R_A = true;
break; // sphere--area of ellipsoid
case "zone": $this->zone = intval( $paramVal, 10 );
break; // UTM Zone
case "south": $this->utmSouth = true;
break; // UTM north/south
case "towgs84": $this->datum_params = explode( ",", $paramVal );
break;
case "to_meter": $this->to_meter = floatval( $paramVal );
break; // cartesian scaling
case "from_greenwich": $this->from_greenwich = $paramVal * Proj4php::$common->D2R;
break;
// DGR 2008-07-09 : if pm is not a well-known prime meridian take
// the value instead of 0.0, then convert to radians
case "pm": $paramVal = trim( $paramVal );
$this->from_greenwich = Proj4php::$primeMeridian[$paramVal] ? Proj4php::$primeMeridian[$paramVal] : floatval( $paramVal );
$this->from_greenwich *= Proj4php::$common->D2R;
break;
// DGR 2010-11-12: axis
case "axis": $paramVal = trim( $paramVal );
$legalAxis = "ewnsud";
if( strlen( paramVal ) == 3 &&
strpos( $legalAxis, substr( $paramVal, 0, 1 ) ) !== false &&
strpos( $legalAxis, substr( $paramVal, 1, 1 ) ) !== false &&
strpos( $legalAxis, substr( $paramVal, 2, 1 ) ) !== false ) {
$this->axis = $paramVal;
} //FIXME: be silent ?
break;
case "no_defs": break;
default: //alert("Unrecognized parameter: " . paramName);
} // switch()
} // for paramArray
$this->deriveConstants();
}
 
/**
* Function: deriveConstants
* Sets several derived constant values and initialization of datum and ellipse parameters.
*
*/
public function deriveConstants() {
if( isset( $this->nagrids ) && $this->nagrids == '@null' )
$this->datumCode = 'none';
if( isset( $this->datumCode ) && $this->datumCode != 'none' ) {
$datumDef = Proj4php::$datum[$this->datumCode];
if( is_array($datumDef ) ) {
$this->datum_params = array_key_exists( 'towgs84', $datumDef ) ? explode( ',', $datumDef['towgs84'] ) : null;
$this->ellps = $datumDef['ellipse'];
$this->datumName = array_key_exists( 'datumName', $datumDef ) ? $datumDef['datumName'] : $this->datumCode;
}
}
if( !isset( $this->a ) ) { // do we have an ellipsoid?
if( !isset( $this->ellps ) || strlen( $this->ellps ) == 0 || !array_key_exists( $this->ellps, Proj4php::$ellipsoid ) )
$ellipse = Proj4php::$ellipsoid['WGS84'];
else {
$ellipse = Proj4php::$ellipsoid[$this->ellps];
}
Proj4php::extend( $this, $ellipse );
}
 
if( isset( $this->rf ) && !isset( $this->b ) )
$this->b = (1.0 - 1.0 / $this->rf) * $this->a;
if ( (isset($this->rf) && $this->rf === 0) || abs($this->a - $this->b) < Proj4php::$common->EPSLN) {
$this->sphere = true;
$this->b = $this->a;
}
$this->a2 = $this->a * $this->a; // used in geocentric
$this->b2 = $this->b * $this->b; // used in geocentric
$this->es = ($this->a2 - $this->b2) / $this->a2; // e ^ 2
$this->e = sqrt( $this->es ); // eccentricity
if( isset( $this->R_A ) ) {
$this->a *= 1. - $this->es * (Proj4php::$common->SIXTH + $this->es * (Proj4php::$common->RA4 + $this->es * Proj4php::$common->RA6));
$this->a2 = $this->a * $this->a;
$this->b2 = $this->b * $this->b;
$this->es = 0.0;
}
$this->ep2 = ($this->a2 - $this->b2) / $this->b2; // used in geocentric
if( !isset( $this->k0 ) )
$this->k0 = 1.0; //default value
//DGR 2010-11-12: axis
if( !isset( $this->axis ) ) {
$this->axis = "enu";
}
 
$this->datum = new Proj4phpDatum( $this );
}
 
}
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/proj4php.php
New file
0,0 → 1,437
<?php
/**
* Author : Julien Moquet
*
* Simple conversion from javascript to PHP of Proj4php by Mike Adair madairATdmsolutions.ca and Richard Greenwood rich@greenwoodmap.com
*
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
$dir = dirname( __FILE__ );
 
require_once($dir . "/proj4phpProj.php");
require_once($dir . "/proj4phpCommon.php");
require_once($dir . "/proj4phpDatum.php");
require_once($dir . "/proj4phpLongLat.php");
require_once($dir . "/proj4phpPoint.php");
 
class Proj4php {
 
protected $defaultDatum = 'WGS84';
public static $ellipsoid = array( );
public static $common = null;
public static $datum = array( );
public static $defs = array( );
public static $wktProjections = array( );
public static $WGS84 = null;
public static $primeMeridian = array( );
public static $proj = array( );
/**
* Property: defsLookupService
* service to retreive projection definition parameters from
*/
public static $defsLookupService = 'http://spatialreference.org/ref';
/**
Proj4php.defs is a collection of coordinate system definition objects in the
PROJ.4 command line format.
Generally a def is added by means of a separate .js file for example:
 
<SCRIPT type="text/javascript" src="defs/EPSG26912.js"></SCRIPT>
 
def is a CS definition in PROJ.4 WKT format, for example:
+proj="tmerc" //longlat, etc.
+a=majorRadius
+b=minorRadius
+lat0=somenumber
+long=somenumber
*/
protected function initDefs() {
// These are so widely used, we'll go ahead and throw them in
// without requiring a separate .js file
self::$defs['WGS84'] = "+title=long/lat:WGS84 +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees";
self::$defs['EPSG:4326'] = "+title=long/lat:WGS84 +proj=longlat +a=6378137.0 +b=6356752.31424518 +ellps=WGS84 +datum=WGS84 +units=degrees";
self::$defs['EPSG:4269'] = "+title=long/lat:NAD83 +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees";
self::$defs['EPSG:3875'] = "+title= Google Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs";
self::$defs['EPSG:3785'] = self::$defs['EPSG:3875'];
self::$defs['GOOGLE'] = self::$defs['EPSG:3875'];
self::$defs['EPSG:900913'] = self::$defs['EPSG:3875'];
self::$defs['EPSG:102113'] = self::$defs['EPSG:3875'];
}
 
//lookup table to go from the projection name in WKT to the Proj4php projection name
//build this out as required
protected function initWKTProjections() {
self::$wktProjections["Lambert Tangential Conformal Conic Projection"] = "lcc";
self::$wktProjections["Mercator"] = "merc";
self::$wktProjections["Mercator_1SP"] = "merc";
self::$wktProjections["Transverse_Mercator"] = "tmerc";
self::$wktProjections["Transverse Mercator"] = "tmerc";
self::$wktProjections["Lambert Azimuthal Equal Area"] = "laea";
self::$wktProjections["Universal Transverse Mercator System"] = "utm";
}
 
protected function initDatum() {
self::$datum["WGS84"] = array( 'towgs84' => "0,0,0", 'ellipse' => "WGS84", 'datumName' => "WGS84" );
self::$datum["GGRS87"] = array( 'towgs84' => "-199.87,74.79,246.62", 'ellipse' => "GRS80", 'datumName' => "Greek_Geodetic_Reference_System_1987" );
self::$datum["NAD83"] = array( 'towgs84' => "0,0,0", 'ellipse' => "GRS80", 'datumName' => "North_American_Datum_1983" );
self::$datum["NAD27"] = array( 'nadgrids' => "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat", 'ellipse' => "clrk66", 'datumName' => "North_American_Datum_1927" );
self::$datum["potsdam"] = array( 'towgs84' => "606.0,23.0,413.0", 'ellipse' => "bessel", 'datumName' => "Potsdam Rauenberg 1950 DHDN" );
self::$datum["carthage"] = array( 'towgs84' => "-263.0,6.0,431.0", 'ellipse' => "clark80", 'datumName' => "Carthage 1934 Tunisia" );
self::$datum["hermannskogel"] = array( 'towgs84' => "653.0,-212.0,449.0", 'ellipse' => "bessel", 'datumName' => "Hermannskogel" );
self::$datum["ire65"] = array( 'towgs84' => "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15", 'ellipse' => "mod_airy", 'datumName' => "Ireland 1965" );
self::$datum["nzgd49"] = array( 'towgs84' => "59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993", 'ellipse' => "intl", 'datumName' => "New Zealand Geodetic Datum 1949" );
self::$datum["OSGB36"] = array( 'towgs84' => "446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894", 'ellipse' => "airy", 'datumName' => "Airy 1830" );
}
 
protected function initEllipsoid() {
self::$ellipsoid["MERIT"] = array( 'a' => 6378137.0, 'rf' => 298.257, 'ellipseName' => "MERIT 1983" );
self::$ellipsoid["SGS85"] = array( 'a' => 6378136.0, 'rf' => 298.257, 'ellipseName' => "Soviet Geodetic System 85" );
self::$ellipsoid["GRS80"] = array( 'a' => 6378137.0, 'rf' => 298.257222101, 'ellipseName' => "GRS 1980(IUGG, 1980)" );
self::$ellipsoid["IAU76"] = array( 'a' => 6378140.0, 'rf' => 298.257, 'ellipseName' => "IAU 1976" );
self::$ellipsoid["airy"] = array( 'a' => 6377563.396, 'b' => 6356256.910, 'ellipseName' => "Airy 1830" );
self::$ellipsoid["APL4."] = array( 'a' => 6378137, 'rf' => 298.25, 'ellipseName' => "Appl. Physics. 1965" );
self::$ellipsoid["NWL9D"] = array( 'a' => 6378145.0, 'rf' => 298.25, 'ellipseName' => "Naval Weapons Lab., 1965" );
self::$ellipsoid["mod_airy"] = array( 'a' => 6377340.189, 'b' => 6356034.446, 'ellipseName' => "Modified Airy" );
self::$ellipsoid["andrae"] = array( 'a' => 6377104.43, 'rf' => 300.0, 'ellipseName' => "Andrae 1876 (Den., Iclnd.)" );
self::$ellipsoid["aust_SA"] = array( 'a' => 6378160.0, 'rf' => 298.25, 'ellipseName' => "Australian Natl & S. Amer. 1969" );
self::$ellipsoid["GRS67"] = array( 'a' => 6378160.0, 'rf' => 298.2471674270, 'ellipseName' => "GRS 67(IUGG 1967)" );
self::$ellipsoid["bessel"] = array( 'a' => 6377397.155, 'rf' => 299.1528128, 'ellipseName' => "Bessel 1841" );
self::$ellipsoid["bess_nam"] = array( 'a' => 6377483.865, 'rf' => 299.1528128, 'ellipseName' => "Bessel 1841 (Namibia)" );
self::$ellipsoid["clrk66"] = array( 'a' => 6378206.4, 'b' => 6356583.8, 'ellipseName' => "Clarke 1866" );
self::$ellipsoid["clrk80"] = array( 'a' => 6378249.145, 'rf' => 293.4663, 'ellipseName' => "Clarke 1880 mod." );
self::$ellipsoid["CPM"] = array( 'a' => 6375738.7, 'rf' => 334.29, 'ellipseName' => "Comm. des Poids et Mesures 1799" );
self::$ellipsoid["delmbr"] = array( 'a' => 6376428.0, 'rf' => 311.5, 'ellipseName' => "Delambre 1810 (Belgium)" );
self::$ellipsoid["engelis"] = array( 'a' => 6378136.05, 'rf' => 298.2566, 'ellipseName' => "Engelis 1985" );
self::$ellipsoid["evrst30"] = array( 'a' => 6377276.345, 'rf' => 300.8017, 'ellipseName' => "Everest 1830" );
self::$ellipsoid["evrst48"] = array( 'a' => 6377304.063, 'rf' => 300.8017, 'ellipseName' => "Everest 1948" );
self::$ellipsoid["evrst56"] = array( 'a' => 6377301.243, 'rf' => 300.8017, 'ellipseName' => "Everest 1956" );
self::$ellipsoid["evrst69"] = array( 'a' => 6377295.664, 'rf' => 300.8017, 'ellipseName' => "Everest 1969" );
self::$ellipsoid["evrstSS"] = array( 'a' => 6377298.556, 'rf' => 300.8017, 'ellipseName' => "Everest (Sabah & Sarawak)" );
self::$ellipsoid["fschr60"] = array( 'a' => 6378166.0, 'rf' => 298.3, 'ellipseName' => "Fischer (Mercury Datum) 1960" );
self::$ellipsoid["fschr60m"] = array( 'a' => 6378155.0, 'rf' => 298.3, 'ellipseName' => "Fischer 1960" );
self::$ellipsoid["fschr68"] = array( 'a' => 6378150.0, 'rf' => 298.3, 'ellipseName' => "Fischer 1968" );
self::$ellipsoid["helmert"] = array( 'a' => 6378200.0, 'rf' => 298.3, 'ellipseName' => "Helmert 1906" );
self::$ellipsoid["hough"] = array( 'a' => 6378270.0, 'rf' => 297.0, 'ellipseName' => "Hough" );
self::$ellipsoid["intl"] = array( 'a' => 6378388.0, 'rf' => 297.0, 'ellipseName' => "International 1909 (Hayford)" );
self::$ellipsoid["kaula"] = array( 'a' => 6378163.0, 'rf' => 298.24, 'ellipseName' => "Kaula 1961" );
self::$ellipsoid["lerch"] = array( 'a' => 6378139.0, 'rf' => 298.257, 'ellipseName' => "Lerch 1979" );
self::$ellipsoid["mprts"] = array( 'a' => 6397300.0, 'rf' => 191.0, 'ellipseName' => "Maupertius 1738" );
self::$ellipsoid["new_intl"] = array( 'a' => 6378157.5, 'b' => 6356772.2, 'ellipseName' => "New International 1967" );
self::$ellipsoid["plessis"] = array( 'a' => 6376523.0, 'rf' => 6355863.0, 'ellipseName' => "Plessis 1817 (France)" );
self::$ellipsoid["krass"] = array( 'a' => 6378245.0, 'rf' => 298.3, 'ellipseName' => "Krassovsky, 1942" );
self::$ellipsoid["SEasia"] = array( 'a' => 6378155.0, 'b' => 6356773.3205, 'ellipseName' => "Southeast Asia" );
self::$ellipsoid["walbeck"] = array( 'a' => 6376896.0, 'b' => 6355834.8467, 'ellipseName' => "Walbeck" );
self::$ellipsoid["WGS60"] = array( 'a' => 6378165.0, 'rf' => 298.3, 'ellipseName' => "WGS 60" );
self::$ellipsoid["WGS66"] = array( 'a' => 6378145.0, 'rf' => 298.25, 'ellipseName' => "WGS 66" );
self::$ellipsoid["WGS72"] = array( 'a' => 6378135.0, 'rf' => 298.26, 'ellipseName' => "WGS 72" );
self::$ellipsoid["WGS84"] = array( 'a' => 6378137.0, 'rf' => 298.257223563, 'ellipseName' => "WGS 84" );
self::$ellipsoid["sphere"] = array( 'a' => 6370997.0, 'b' => 6370997.0, 'ellipseName' => "Normal Sphere (r=6370997)" );
}
 
protected function initPrimeMeridian() {
self::$primeMeridian["greenwich"] = '0.0'; //"0dE",
self::$primeMeridian["lisbon"] = -9.131906111111; //"9d07'54.862\"W",
self::$primeMeridian["paris"] = 2.337229166667; //"2d20'14.025\"E",
self::$primeMeridian["bogota"] = -74.080916666667; //"74d04'51.3\"W",
self::$primeMeridian["madrid"] = -3.687938888889; //"3d41'16.58\"W",
self::$primeMeridian["rome"] = 12.452333333333; //"12d27'8.4\"E",
self::$primeMeridian["bern"] = 7.439583333333; //"7d26'22.5\"E",
self::$primeMeridian["jakarta"] = 106.807719444444; //"106d48'27.79\"E",
self::$primeMeridian["ferro"] = -17.666666666667; //"17d40'W",
self::$primeMeridian["brussels"] = 4.367975; //"4d22'4.71\"E",
self::$primeMeridian["stockholm"] = 18.058277777778; //"18d3'29.8\"E",
self::$primeMeridian["athens"] = 23.7163375; //"23d42'58.815\"E",
self::$primeMeridian["oslo"] = 10.722916666667; //"10d43'22.5\"E"
}
/**
*
*/
public function __construct() {
$this->initWKTProjections();
$this->initDefs();
$this->initDatum();
$this->initEllipsoid();
$this->initPrimeMeridian();
self::$proj['longlat'] = new proj4phpLongLat();
self::$proj['identity'] = new proj4phpLongLat();
self::$common = new proj4phpCommon();
self::$WGS84 = new Proj4phpProj( 'WGS84' );
}
 
/**
* Method: transform(source, dest, point)
* Transform a point coordinate from one map projection to another. This is
* really the only public method you should need to use.
*
* Parameters:
* source - {Proj4phpProj} source map projection for the transformation
* dest - {Proj4phpProj} destination map projection for the transformation
* point - {Object} point to transform, may be geodetic (long, lat) or
* projected Cartesian (x,y), but should always have x,y properties.
*/
public function transform( $source, $dest, $point ) {
if( !$source->readyToUse ) {
self::reportError( "Proj4php initialization for:" . $source->srsCode . " not yet complete" );
return $point;
}
if( !$dest->readyToUse ) {
self::reportError( "Proj4php initialization for:" . $dest->srsCode . " not yet complete" );
return $point;
}
// Workaround for datum shifts towgs84, if either source or destination projection is not wgs84
if ( isset($source->datum) && isset($dest->datum) && (
(($source->datum->datum_type == Proj4php::$common->PJD_3PARAM || $source->datum->datum_type == Proj4php::$common->PJD_7PARAM) && (isset($dest->datumCode) && $dest->datumCode != "WGS84")) ||
(($dest->datum->datum_type == Proj4php::$common->PJD_3PARAM || $dest->datum->datum_type == Proj4php::$common->PJD_7PARAM) && (isset($source->datumCode) && $source->datumCode != "WGS84")))) {
$wgs84 = Proj4php::$WGS84;
$this->transform($source, $wgs84, $point);
$source = $wgs84;
}
 
// Workaround for Spherical Mercator => skipped in proj4js 1.1.0
/*
if( ($source->srsProjNumber == "900913" && $dest->datumCode != "WGS84") ||
($dest->srsProjNumber == "900913" && $source->datumCode != "WGS84") ) {
$wgs84 = Proj4php::$WGS84; // DONT KNOW WHAT YET
$this->transform( $source, $wgs84, $point );
$source = $wgs84;
}
*/
 
// DGR, 2010/11/12
if( $source->axis != "enu" ) {
$this->adjust_axis( $source, false, $point );
}
 
// Transform source points to long/lat, if they aren't already.
if( $source->projName == "longlat" ) {
$point->x *= Proj4php::$common->D2R; // convert degrees to radians
$point->y *= Proj4php::$common->D2R;
} else {
if( isset($source->to_meter) ) {
$point->x *= $source->to_meter;
$point->y *= $source->to_meter;
}
$source->inverse( $point ); // Convert Cartesian to longlat
}
 
// Adjust for the prime meridian if necessary
if( isset( $source->from_greenwich ) ) {
$point->x += $source->from_greenwich;
}
 
// Convert datums if needed, and if possible.
$point = $this->datum_transform( $source->datum, $dest->datum, $point );
// Adjust for the prime meridian if necessary
if( isset( $dest->from_greenwich ) ) {
$point->x -= $dest->from_greenwich;
}
 
if( $dest->projName == "longlat" ) {
// convert radians to decimal degrees
$point->x *= Proj4php::$common->R2D;
$point->y *= Proj4php::$common->R2D;
} else { // else project
$dest->forward( $point );
if( isset($dest->to_meter) ) {
$point->x /= $dest->to_meter;
$point->y /= $dest->to_meter;
}
}
 
// DGR, 2010/11/12
if( $dest->axis != "enu" ) {
$this->adjust_axis( $dest, true, $point );
}
 
return $point;
}
 
/** datum_transform()
source coordinate system definition,
destination coordinate system definition,
point to transform in geodetic coordinates (long, lat, height)
*/
public function datum_transform( $source, $dest, $point ) {
// Short cut if the datums are identical.
if( $source->compare_datums( $dest ) ) {
return $point; // in this case, zero is sucess,
// whereas cs_compare_datums returns 1 to indicate TRUE
// confusing, should fix this
}
 
// Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest
if( $source->datum_type == Proj4php::$common->PJD_NODATUM
|| $dest->datum_type == Proj4php::$common->PJD_NODATUM ) {
return $point;
}
 
/*
// If this datum requires grid shifts, then apply it to geodetic coordinates.
if( $source->datum_type == Proj4php::$common->PJD_GRIDSHIFT ) {
throw(new Exception( "ERROR: Grid shift transformations are not implemented yet." ));
}
 
if( $dest->datum_type == Proj4php::$common->PJD_GRIDSHIFT ) {
throw(new Exception( "ERROR: Grid shift transformations are not implemented yet." ));
}
*/
 
// Do we need to go through geocentric coordinates?
if( $source->es != $dest->es || $source->a != $dest->a
|| $source->datum_type == Proj4php::$common->PJD_3PARAM
|| $source->datum_type == Proj4php::$common->PJD_7PARAM
|| $dest->datum_type == Proj4php::$common->PJD_3PARAM
|| $dest->datum_type == Proj4php::$common->PJD_7PARAM ) {
 
// Convert to geocentric coordinates.
$source->geodetic_to_geocentric( $point );
// CHECK_RETURN;
// Convert between datums
if( $source->datum_type == Proj4php::$common->PJD_3PARAM || $source->datum_type == Proj4php::$common->PJD_7PARAM ) {
$source->geocentric_to_wgs84( $point );
// CHECK_RETURN;
}
 
if( $dest->datum_type == Proj4php::$common->PJD_3PARAM || $dest->datum_type == Proj4php::$common->PJD_7PARAM ) {
$dest->geocentric_from_wgs84( $point );
// CHECK_RETURN;
}
 
// Convert back to geodetic coordinates
$dest->geocentric_to_geodetic( $point );
// CHECK_RETURN;
}
 
// Apply grid shift to destination if required
/*
if( $dest->datum_type == Proj4php::$common->PJD_GRIDSHIFT ) {
throw(new Exception( "ERROR: Grid shift transformations are not implemented yet." ));
// pj_apply_gridshift( pj_param(dest.params,"snadgrids").s, 1, point);
// CHECK_RETURN;
}
*/
return $point;
}
/**
* Function: adjust_axis
* Normalize or de-normalized the x/y/z axes. The normal form is "enu"
* (easting, northing, up).
* Parameters:
* crs {Proj4php.Proj} the coordinate reference system
* denorm {Boolean} when false, normalize
* point {Object} the coordinates to adjust
*/
public function adjust_axis( $crs, $denorm, $point ) {
$xin = $point->x;
$yin = $point->y;
$zin = isset( $point->z ) ? $point->z : 0.0;
#$v;
#$t;
for( $i = 0; $i < 3; $i++ ) {
if( $denorm && $i == 2 && !isset( $point->z ) ) {
continue;
}
if( $i == 0 ) {
$v = $xin;
$t = 'x';
} else if( $i == 1 ) {
$v = $yin;
$t = 'y';
} else {
$v = $zin;
$t = 'z';
}
switch( $crs->axis[$i] ) {
case 'e':
$point[$t] = $v;
break;
case 'w':
$point[$t] = -$v;
break;
case 'n':
$point[$t] = $v;
break;
case 's':
$point[$t] = -$v;
break;
case 'u':
if( isset( $point[$t] ) ) {
$point->z = $v;
}
break;
case 'd':
if( isset( $point[$t] ) ) {
$point->z = -$v;
}
break;
default :
throw(new Exception( "ERROR: unknow axis (" . $crs->axis[$i] . ") - check definition of " . $crs->projName ));
return null;
}
}
return $point;
}
 
/**
* Function: reportError
* An internal method to report errors back to user.
* Override this in applications to report error messages or throw exceptions.
*/
public static function reportError( $msg ) {
//console.log(msg);
echo $msg . "<br />\n";
}
 
/**
* Function : loadScript
* adapted from original. PHP is simplier.
*/
public static function loadScript( $filename, $onload = null, $onfail = null, $loadCheck = null ) {
if( stripos($filename, 'http://') !== false ) {
return @file_get_contents($filename);
}
elseif( file_exists( $filename ) ) {
require_once($filename);
return true;
}
else {
throw(new Exception( "File $filename could not be found or was not able to be loaded." ));
return false;
}
}
 
/**
* Function: extend
* Copy all properties of a source object to a destination object. Modifies
* the passed in destination object. Any properties on the source object
* that are set to undefined will not be (re)set on the destination object.
*
* Parameters:
* destination - {Object} The object that will be modified
* source - {Object} The object with properties to be set on the destination
*
* Returns:
* {Object} The destination object.
*/
public static function extend( $destination, $source ) {
if( $source != null )
foreach( $source as $key => $value ) {
$destination->$key = $value;
}
return $destination;
}
 
}
/tags/v5.7-arrayanal/scripts/modules/ifn/bibliotheque/proj4php/proj4phpLongLat.php
New file
0,0 → 1,23
<?php
/**
* Author : Julien Moquet
*
* Inspired by Proj4js from Mike Adair madairATdmsolutions.ca
* and Richard Greenwood rich@greenwoodmap.com
* License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
*/
class proj4phpLongLat {
 
public function init() {
}
 
public function forward( $pt ) {
return $pt;
}
 
public function inverse( $pt ) {
return $pt;
}
 
}
/tags/v5.7-arrayanal/scripts/modules/photoflora/photoflora.ini
New file
0,0 → 1,13
version="1_0"
dossierTsv = "{ref:dossierDonneesEflore}photoflora/1.0/"
dossierSql = "{ref:dossierTsv}"
bdd_nom = "tb_eflore"
 
[tables]
bdtfxMeta = "photoflora_meta"
 
[fichiers]
structureSql = "photoflora_v1_0.sql"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
/tags/v5.7-arrayanal/scripts/modules/photoflora/Photoflora.php
New file
0,0 → 1,38
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php bdnt -a chargerTous
*/
class Photoflora extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('photoflora');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerOntologies' :
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS photoflora_meta";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/coste/Description.php
New file
0,0 → 1,570
<?php
// commande : /opt/lampp/bin/php cli.php description_sp -a tester -n /home/jennifer/Tela-botanica_projets/Coste/descriptions/html
class Description {
 
const DOSSIER_V0 = '../../../donnees/coste/0.00/';
const DOSSIER_DSC_HTML = '../../../donnees/coste/descriptions/html/';
const DOSSIER_DSC_TXT = '../../../donnees/coste/descriptions/txt/';
const DOSSIER_LOG = 'log/';
 
private $auteurs = array();
private $dossierBase = '';
private $conteneur = null;
private $outils = null;
private $messages = null;
private $action = '';
private $nomFichier = '';
private $nomDossier = '';
private $listeFichiers = array();
private $fichierNum = '';
private $fichier = '';
private $log = '';
private $correspondance = array();
private $infosCorrespondanceBase = array(
'nom_sci' => '',
'auteur' => '',
'nom_addendum' => '',
'annee' => '',
'biblio_origine' => '',
'rang' => 290,
'nom_francais' => '',
'nom_coste' => '',
'auteur_coste' => '',
'biblio_coste' => '',
'num_nom_coste' => '',
'num_nom_retenu_coste' => '',
'num_tax_sup_coste' => '',
'tome' => '',
'page' => '',
'synonymie_coste' => '',
'flore_bdtfx_nn' => '',
'flore_bdtfx_nt' => '');
 
public function __construct(Conteneur $conteneur) {
mb_internal_encoding('UTF-8');
setlocale(LC_ALL, 'fr_FR.UTF-8');
$this->conteneur = $conteneur;
$this->outils = $conteneur->getOutils();
$this->messages = $conteneur->getMessages();
$this->dossierBase = dirname(__FILE__).'/';
}
 
public function genererDescriptionTxt() {
$this->chargerFichiers();
 
foreach ($this->listeFichiers as $this->fichierNum => $this->fichier) {
$this->messages->afficherAvancement("Création des descriptions au format txt");
$this->genererFichier();
}
echo "\n";
}
 
public function verifierDescriptionTxt() {
$this->chargerFichiers();
 
foreach ($this->listeFichiers as $this->fichierNum => $this->fichier) {
$this->messages->afficherAvancement("Analyse des descriptions");
$this->verifierFichier();
}
echo "\n";
$this->ecrireLogs();
}
 
public function genererCorrespondance() {
$this->chargerFichiers();
 
$this->ajouterLogSyno(implode("\t", array_keys($this->infosCorrespondanceBase)));
foreach ($this->listeFichiers as $this->fichierNum => $this->fichier) {
$this->messages->afficherAvancement("Création du fichier de correspondance");
$this->extraireInfosCorrespondance();
}
echo "\n";
 
$fichierTxt = $this->dossierBase.self::DOSSIER_V0.'index_general_sp.tsv';
$txtCorrespondance = $this->creerFichierCsvCorrespondance();
file_put_contents($fichierTxt, $txtCorrespondance);
 
ksort($this->auteurs);
foreach ($this->auteurs as $auteur => $nbre) {
$this->ajouterLogAuteur("$auteur\t$nbre");
}
 
$this->ecrireLogs();
}
 
 
private function chargerFichiers() {
$this->nomDossier = $this->dossierBase.self::DOSSIER_DSC_HTML;
if (file_exists($this->nomDossier) === true) {
if (is_dir($this->nomDossier)) {
if ($dossierOuvert = opendir($this->nomDossier)) {
while (($this->nomFichier = readdir($dossierOuvert)) !== false) {
if (! is_dir($this->nomFichier) && preg_match('/e([0-9]{4})\.htm/', $this->nomFichier, $match)) {
$this->listeFichiers[$match[1]] = $this->nomDossier.'/'.$this->nomFichier;
}
}
closedir($dossierOuvert);
} else {
$this->messages->traiterErreur("Le dossier {$this->nomDossier} n'a pas pu être ouvert.");
}
} else {
$this->messages->traiterErreur("{$this->nomDossier} n'est pas un dossier.");
}
} else {
$this->messages->traiterErreur("Le dossier {$this->nomDossier} est introuvable.");
}
 
asort($this->listeFichiers);
}
 
private function verifierFichier() {
$donnees = $this->analyserFichier();
$txt = $donnees['texte'];
$this->verifierOuvertureFermetureBalise($txt);
$this->verifierAbscenceEgale($txt);
$this->verifierNumero($txt);
// TODO : vérifier les noms vernauclaire qui sont abrégés
}
 
private function verifierOuvertureFermetureBalise($txt) {
$b_ouvert = substr_count($txt, '<B>');
$b_ferme = substr_count($txt, '</B>');
if ($b_ouvert != $b_ferme) {
$message = "{$this->fichierNum} contient $b_ouvert balises B ouvertes et $b_ferme fermées";
$this->ajouterLogAnalyse($message);
}
$i_ouvert = substr_count($txt, '<I>');
$i_ferme = substr_count($txt, '</I>');
if ($i_ouvert != $i_ferme) {
$message = "{$this->fichierNum} contient $i_ouvert balises I ouvertes et $i_ferme fermées";
$this->ajouterLogAnalyse($message);
}
}
 
private function verifierAbscenceEgale($txt) {
if (strripos($txt, '=') === false) {
$message = "{$this->fichierNum} ne contient pas le séparateur de phénologie (=)";
$this->ajouterLogAnalyse($message);
}
}
 
private function verifierNumero($txt) {
if (preg_match('/^<B>[0-9]{1,4}. – /', $txt) == 0) {
$message = "{$this->fichierNum} ne contient pas un numéro bien formaté";
$this->ajouterLogAnalyse($message);
}
}
 
private function extraireInfosCorrespondance() {
$donnees = $this->analyserFichier();
$infos = $this->infosCorrespondanceBase;
 
$titre = $donnees['titre'];
if (preg_match('/^Coste ([0-9]+) - ((?:(?! - ).)+) - F[0-9]+, (?:(?! - ).)+ - (G[0-9]+), T([123])[.]p([0-9]+)$/', $titre, $match)) {
$infos['num_nom_coste'] = $match[1];
$infos['num_nom_retenu_coste'] = $match[1];
$infos['nom_sci'] = $match[2];
$infos['num_tax_sup_coste'] = $match[3];
$infos['tome'] = $match[4];
$infos['page'] = $match[5];
} else {
$this->messages->traiterErreur("Le titre du fichier {$this->fichierNum} est mal formaté.");
}
 
$corres = $donnees['correspondance'];
if (preg_match('/^Bdnff ([0-9]+) - (?:(?! - ).)+ - (?:(?! - ).)+ - Tax=([0-9]+)$/', $corres, $match)) {
$infos['flore_bdtfx_nn'] = $match[1];
$infos['flore_bdtfx_nt'] = $match[2];
} else {
$this->messages->traiterErreur("La correspondance du fichier {$this->fichierNum} est mal formatée.");
}
 
$txt = $donnees['texte'];
$txt = $this->corrigerDescription($txt);
if (preg_match('/^<B>[0-9]{1,4}[.] – ([^<]+)<\/B> ([^–]*)– (?:<I>([^<]+)<\/I>[.] – |<I>([^<]+)<\/I>( \([^)]+\))[.] – |[A-Z]|<I>(?:Sous-|Espèce|Turion|Souche|Plante|Feuille|Racine))/u', $txt, $match)) {
$infos['nom_coste'] = trim($match[1]);
$infos['rang'] = $this->obtenirRangNom($infos['nom_coste']);
$infos['auteur_coste'] = trim($match[2]);
$infos['nom_francais'] = isset($match[3]) ? $match[3] : '';
$infos['nom_francais'] = isset($match[4]) && isset($match[5]) ? $match[4].$match[5] : $infos['nom_francais'];
if (strpos($infos['auteur_coste'], '(' ) !== false) {
if (preg_match('/^([^(]*)\(([^)]+)\)(?:[.]?| ; ((?:(?! – ).)+))$/', $infos['auteur_coste'], $match)) {
$infos['auteur_coste'] = $this->traiterAuteur(trim($match[1]));
$infos['auteur'] = $this->normaliserAuteur($infos['auteur_coste']);
$parentheseContenu = trim($match[2]);
if (preg_match('/^[0-9]+$/', $parentheseContenu)) {
$infos['annee'] = $parentheseContenu;
} else {
$infos['synonymie_coste'] = $parentheseContenu;
$infos['biblio_coste'] = isset($match[3]) ? trim($match[3]) : '';
}
} else {
$this->messages->traiterErreur("L'auteur du nom sciencitifique du fichier {$this->fichierNum} est mal formaté.");
}
}
} else {
$this->messages->traiterErreur("La texte du fichier {$this->fichierNum} est mal formaté.");
}
 
$this->correspondance[] = $infos;
 
if ($infos['synonymie_coste'] != '') {
$this->traiterSynonymie($infos);
}
}
 
private function normaliserAuteur($auteurCoste) {
$auteur = '';
if ($auteurCoste != '') {
$auteur = str_replace(' et ', ' & ', $auteurCoste);
}
return $auteur;
}
 
private function traiterSynonymie($infos) {
$synoCoste = $infos['synonymie_coste'];
$synoCoste = preg_replace('/, etc[.]$/', '', $synoCoste);
$synoCoste = preg_replace('/^et /', '', $synoCoste);
$synoCoste = preg_replace('/^(([A-Z][.]|[A-Z]{3,}) [A-Z]{3,}(?:(?! et ).+)) et ([A-Z]{3,}) ((?![A-Z]{3,}).+)$/', '$1 ; $2 $3 $4', $synoCoste);
$synoCoste = preg_replace('/ et ((?:[A-Z][.]|[A-Z]{3,}) [A-Z]{3,})/', ' ; $1', $synoCoste);
$synoCoste = preg_replace('/, ((?:(?!non |part[.]|an |G[.] G[.]|part[.]|centr[.])[^,]+))/', ' ;$1', $synoCoste);
 
$synonymes = explode(';', $synoCoste);
 
foreach ($synonymes as $num => $syno) {
$synoTraite = $this->traiterNomSyno($syno);
$nomSci = $this->obtenirNomSci($synoTraite, $infos, $synonymes, $num);
$rang = $this->obtenirRangNom($nomSci);
$complementNom = $this->obtenirComplementNom($synoTraite);
$auteurCoste = $this->obtenirAuteur($complementNom);
$auteur = $this->normaliserAuteur($auteurCoste);
$this->ajouterAuteur($auteur);
$biblioCoste = $this->obtenirBiblio($complementNom);
$annee = $this->extraireAnnee($complementNom);
 
$infosSyno = $this->infosCorrespondanceBase;
$infosSyno['nom_sci'] = $nomSci;
$infosSyno['auteur'] = $auteur;
$infosSyno['biblio_origine'] = $biblioCoste;
$infosSyno['annee'] = $annee;
$infosSyno['nom_addendum'] = $this->obtenirNomAddendum($syno);
 
$infosSyno['rang'] = $rang;
$infosSyno['nom_coste'] = $synoTraite;
$infosSyno['auteur_coste'] = $auteurCoste;
$infosSyno['biblio_coste'] = $biblioCoste;
$infosSyno['num_nom_coste'] = $infos['num_nom_coste'].'.'.($num + 1);
$infosSyno['num_nom_retenu_coste'] = $infos['num_nom_coste'];
$this->ajouterLogSyno(implode("\t", $infosSyno));
$this->correspondance[] = $infosSyno;
}
}
 
private function traiterNomSyno($syno) {
$syno = $this->nettoyerEspacesNomSyno($syno);
$syno = preg_replace('/^(?:avec|(?:compr|incl)[.]) /', '', $syno);
return $syno;
}
 
private function nettoyerEspacesNomSyno($syno) {
$syno = trim($syno);
$syno = trim($syno, ' ');
return $syno;
}
 
private function obtenirComplementNom($syno) {
$complementNom = '';
if (preg_match('/^(?:[^ ]+ [^ ]+ (?:(?:var|V)[.] [^ ]+|STELATUM|MINUS)|[^ ]+ [^ ]+) (.+)$/', $syno, $match)) {
$complementNom = $match[1];
}
return $complementNom;
}
 
private function obtenirBiblio($complementNom) {
$biblioCoste = '';
if (preg_match("/ (p[.] [0-9]{1,}|in .+||Fl[.] fr[.]|(?: Sp[.])? ed[.] [1-2])$/", $complementNom, $match)) {
$biblioCoste = $match[1];
}
return $biblioCoste;
}
 
private function extraireAnnee($complementNom) {
$annee = '';
if (preg_match('/(?:^| )([0-9]+)$/', $complementNom, $match)) {
$annee = $match[1];
}
return $annee;
}
 
private function obtenirAuteur($complementNom) {
$auteurCoste = '';
if ($complementNom != '') {
if (preg_match("/^((?!(?:auct.+|(?:, )?(?:non|an) .+|p[.] p[.])$).+)$/", $complementNom, $match)) {
$auteurCoste = $this->traiterAuteur($match[1]);
} else {
$message = "Impossible de récupérer l'auteur pour le complément de nom ($complementNom).";
$this->ajouterLogProbleme($message);
}
}
return $auteurCoste;
}
 
private function traiterAuteur($auteurCoste) {
$auteur = '';
if ($auteurCoste != '') {
$remplacementTxt = array(' p. p.', ' saltem part.', 'Fl. fr.');
$auteurCoste = str_replace($remplacementTxt, '', $auteurCoste);
$remplacementsRegExp = array(
' [0-9]{4}',
'[^ ]+ et auct[.], .+',
' auct.+',
',? part[.]',
' p[.] [0-9]{1,}',
' in .+|,? (?:non|an) .+',
'(?: Sp[.])? ed[.] [1-2]');
$auteur = preg_replace('/(?:'.implode('|', $remplacementsRegExp).')$/', '', $auteurCoste);
}
return $auteur;
}
 
private function ajouterAuteur($auteur) {
if (!isset($this->auteurs[$auteur])) {
$this->auteurs[$auteur] = 1;
} else {
$this->auteurs[$auteur]++;
}
}
 
private function obtenirNomAddendum($syno) {
$syno = $this->nettoyerEspacesNomSyno($syno);
$nomAddendum = array();
if (preg_match('/^((?:compr|incl)[.]) /', $syno, $match)) {
$nomAddendum[] = '['.$match[1].']';
}
if (preg_match('/ ([^ ]+ et auct[.], .+)$/', $syno, $match)) {
$nomAddendum[] = '['.$match[1].']';
} elseif (preg_match('/ (auct[.],? .+)$/', $syno, $match)) {
$nomAddendum[] = '['.$match[1].']';
} else if (preg_match('/,? ((?:non|an) .+)$/', $syno, $match)) {
$nomAddendum[] = '['.$match[1].']';
} else if (preg_match('/ (p[.] p[.])$/', $syno, $match)) {
$nomAddendum[] = '['.$match[1].']';
} else if (preg_match('/ (saltem part[.])$/', $syno, $match)) {
$nomAddendum[] = '['.$match[1].']';
} else if (preg_match('/,? (part[.])$/', $syno, $match)) {
$nomAddendum[] = '['.$match[1].']';
}
 
$nomAddendum = implode(' ; ', $nomAddendum);
return $nomAddendum;
}
 
private function remplacerAbreviationGenre($syno, $infos, $synonymes, $num) {
$nomSci = $syno;
 
if (preg_match('/^(([A-Zƌ])[.]) /', $syno, $matchSyno)) {
if ($matchSyno[2] == substr($infos['nom_coste'], 0, 1)) {
if (preg_match('/^([^ ]+) /', $infos['nom_coste'], $matchNomRetenu)) {
$nomSci = str_replace($matchSyno[1], $matchNomRetenu[1], $syno);
}
} else {
$synoPrecedent = $this->obtenirSynoAvecGenreComplet($synonymes, $num);
 
if ($matchSyno[2] == substr($synoPrecedent, 0, 1)) {
if (preg_match('/^([^ ]+) /', $synoPrecedent, $matchSynoPrec)) {
$nomSci = str_replace($matchSyno[1], $matchSynoPrec[1], $syno);
}
} else {
$message = "L'initiale du synonyme ($syno) ne correspondant pas au nom retenu {$infos['num_nom_coste']} ({$infos['nom_coste']}) ".
"ni au synonyme précédent ($synoPrecedent).";
$this->ajouterLogProbleme($message);
}
}
}
return $nomSci;
}
 
private function obtenirSynoAvecGenreComplet($synonymes, $num) {
$synoPrecedent = '';
$synoOk = false;
while ($synoOk == false) {
if ($num < 0) {
$synoOk = true;
}
$synoPrecedent = $this->obtenirSynoPrecedent($synonymes, $num);
if (preg_match('/^[A-Zƌ][.] /', $synoPrecedent)) {
$num = $num - 1;
} else {
$synoOk = true;
}
}
return $synoPrecedent;
}
 
private function obtenirSynoPrecedent($synonymes, $num) {
$synoPrecedent = '';
if (isset($synonymes[($num - 1 )])) {
$synoPrecedent = $this->traiterNomSyno($synonymes[($num - 1 )]);
}
return $synoPrecedent;
}
 
 
private function obtenirNomSci($syno, $infos, $synonymes, $num) {
$nomSci = $this->remplacerAbreviationGenre($syno, $infos, $synonymes, $num);
 
if (preg_match('/^([^ ]+) ([^ ]+) (?:(?:var|V)[.] ([^ ]+)|(STELATUM||MINUS) )/', $nomSci, $match)) {
$genre = $this->normaliserGenre($match[1]);
$sp = $this->normaliserEpithete($match[2]);
$infrasp = isset($match[4]) ? $match[4] : $match[3];
$infrasp = $this->normaliserEpithete($infrasp);
$nomSci = "$genre $sp var. $infrasp";
} else if (preg_match('/^([^ ]+) ([^ ]+)(?: |$)/', $nomSci, $match)) {
$genre = $this->normaliserGenre($match[1]);
$sp = $this->normaliserEpithete($match[2]);
$nomSci = "$genre $sp";
} else {
$message = "Le synonyme ($nomSci) du nom {$infos['num_nom_coste']} a une structure étrange.";
$this->ajouterLogProbleme($message);
}
return $nomSci;
}
 
private function normaliserGenre($genre) {
$genre = mb_convert_case(mb_strtolower($genre), MB_CASE_TITLE);
$genre = str_replace('Æ', 'æ', $genre);
return $genre;
}
 
private function normaliserEpithete($sp) {
$sp = mb_strtolower($sp);
$sp = str_replace('Æ', 'æ', $sp);
return $sp;
}
 
private function obtenirRangNom($syno) {
$rang = 290;
if (strpos($syno, ' var. ')) {
$rang = 340;
}
return $rang;
}
 
private function creerFichierCsvCorrespondance() {
$lignes[] = implode("\t", array_keys($this->infosCorrespondanceBase));
foreach ($this->correspondance as $infos) {
$lignes[] = implode("\t", $infos);
}
 
$txt = '';
$txt = implode("\n", $lignes);
return $txt;
}
 
private function genererFichier() {
$donnees = $this->analyserFichier();
 
$txt = $this->nettoyerDescription($donnees['texte']);
$txt = $this->corrigerDescription($txt);
$txt = $this->remplacerHtmlParSyntaxeWiki($txt);
$fichierTxt = $this->dossierBase.self::DOSSIER_DSC_TXT.$this->fichierNum.'.txt';
file_put_contents($fichierTxt, $txt);
 
unset($donnees['texte']);
$txt = implode("\n", $donnees);
$fichierTxt = $this->dossierBase.self::DOSSIER_DSC_TXT.$this->fichierNum.'.json';
file_put_contents($fichierTxt, $txt);
}
 
private function analyserFichier() {
$donnees = array('titre' => '', 'texte' => '', 'correspondance' => '');
if ($fichierOuvert = fopen($this->fichier, 'r')) {
$i = 1;
while ($ligne = fgets($fichierOuvert)) {
if ($i == 24) {
$donnees['titre'] = $this->supprimerHtml($ligne);
} elseif ($i >= 45 && $i <= 60) {
$donnees['texte'] .= $this->traiterLigneDescription($ligne);
} elseif ($i >= 61 && preg_match('/Bdnff /ui', $ligne)) {
$donnees['correspondance'] = $this->supprimerHtml($ligne);
}
$i++;
}
fclose($fichierOuvert);
} else {
$this->messages->traiterErreur("Le fichier {$this->fichier} n'a pas pu être ouvert.");
}
return $donnees;
}
 
private function supprimerHtml($txt) {
$txt = strip_tags($txt,'<b>,<i>');
$txt = str_replace('&#173;', '', $txt);
$txt = str_ireplace('&nbsp;', ' ', $txt);
$txt = trim($txt);
$txt = preg_replace('/^<\/I>/', '', $txt);
$txt = html_entity_decode($txt, ENT_NOQUOTES, 'UTF-8');
return $txt;
}
 
private function traiterLigneDescription($txt) {
$txt = $this->supprimerHtml($txt);
$txt = $txt."\n";
return $txt;
}
 
private function nettoyerDescription($txt) {
$txt = preg_replace("/\n{2,}+/", "\n", $txt);
$txt = trim($txt);
return $txt;
}
 
private function corrigerDescription($txt) {
$txt = preg_replace("/– <I>([^.]+?)[.] – <\/I>/", "– <I>$1</I>. – ", $txt);
$txt = preg_replace("/– <I>([^.]+?)[.] – ([A-Z])<\/I>/", "– <I>$1</I>. – $2", $txt);
$txt = preg_replace("/– <I>([^.]+?) – <\/I>/", "– <I>$1</I>. – ", $txt);
return $txt;
}
 
private function remplacerHtmlParSyntaxeWiki($txt) {
$txt = str_replace(array('<B>', '</B>'), '**', $txt);
$txt = str_replace(array('<I>', '</I>'), '//', $txt);
return $txt;
}
 
private function ajouterLogAnalyse($txt) {
if (isset($this->log['analyse']) == false) {
$this->log['analyse'] = '';
}
$this->log['analyse'] .= "$txt\n";
}
 
private function ajouterLogSyno($txt) {
if (isset($this->log['synonymes']) == false) {
$this->log['synonymes'] = '';
}
$this->log['synonymes'] .= "$txt\n";
}
 
private function ajouterLogAuteur($txt) {
if (isset($this->log['auteurs']) == false) {
$this->log['auteurs'] = '';
}
$this->log['auteurs'] .= "$txt\n";
}
 
private function ajouterLogProbleme($txt) {
if (isset($this->log['problemes']) == false) {
$this->log['problemes'] = '';
}
$this->log['problemes'] .= "$txt\n";
}
 
private function ecrireLogs() {
foreach ($this->log as $nom => $log) {
$fichier = $this->dossierBase.self::DOSSIER_LOG.$nom.'.log';
file_put_contents($fichier, $log);
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/coste/Wiki.php
New file
0,0 → 1,251
<?php
class Wiki {
const DOSSIER_V2 = '../../../donnees/coste/2.00/';
const DOSSIER_DSC_TXT = '../../../donnees/coste/descriptions/txt/';
 
private $URL_WIKI = '';
private $URL_WIKI_EFLORE = '';
private $conteneur = null;
private $outils = null;
private $messages = null;
private $restClient = null;
private $bdd = null;
private $dossierBase = '';
private $index = array();
 
public function __construct(Conteneur $conteneur) {
mb_internal_encoding('UTF-8');
setlocale(LC_ALL, 'fr_FR.UTF-8');
$this->conteneur = $conteneur;
$this->URL_WIKI = $this->conteneur->getParametre('wiki.travail');
$this->URL_WIKI_EFLORE = $this->conteneur->getParametre('wiki.eflore');
$this->outils = $conteneur->getOutils();
$this->messages = $conteneur->getMessages();
$this->restClient = $conteneur->getRestClient();
$this->bdd = $conteneur->getBdd();
$this->dossierBase = dirname(__FILE__).'/';
}
 
public function uploaderFichiersSp() {
$this->chargerIndex();
$envoyes = array();
foreach ($this->index as $nom) {
$tag = $nom['page_wiki_dsc'];
if (isset($envoyes[$tag]) == false && preg_match('/^Esp([0-9]{4})/', $tag, $match)) {
$fichier = $this->dossierBase.self::DOSSIER_DSC_TXT.$match[1].'.txt';
if (file_exists($fichier) === true) {
$txt = file_get_contents($fichier);
$donnees = array('pageTag' => $tag, 'pageContenu' => $txt);
$this->restClient->ajouter($this->URL_WIKI, $donnees);
$envoyes[$tag] = 'OK';
} else {
$this->messages->traiterErreur("Le fichier $fichier est introuvable.");
}
}
$this->messages->afficherAvancement("Upload des fichiers d'espèce dans le wikini");
}
echo "\n";
}
 
public function dowloaderPagesWiki() {
$this->chargerIndex();
$envoyes = array();
foreach ($this->index as $nom) {
$tagDsc = $nom['page_wiki_dsc'];
$tagCle = $nom['page_wiki_cle'];
if (isset($envoyes[$tagDsc]) == false) {
$url = $this->URL_WIKI.'/'.$tagDsc;
$txt = $this->telechargerTxt($url);
$fichier = $this->dossierBase.self::DOSSIER_V2.'dsc/'.$tagDsc.'.txt';
if (file_put_contents($fichier, $txt)) {
$envoyes[$tagDsc] = 'OK';
}
}
if (isset($envoyes[$tagCle]) == false) {
$url = $this->URL_WIKI.'/'.$tagCle;
$txt = $this->telechargerTxt($url);
$fichier = $this->dossierBase.self::DOSSIER_V2.'cle/'.$tagCle.'.txt';
if (file_put_contents($fichier, $txt)) {
$envoyes[$tagCle] = 'OK';
}
}
$this->messages->afficherAvancement("Download des fichiers en cours");
}
echo "\n";
}
 
public function uploaderDansWikiEflore() {
$this->chargerIndex();
$envoyes = array();
 
foreach ($this->index as $nom) {
$tagDsc = $nom['page_wiki_dsc'];
if (isset($envoyes[$tagDsc]) == false) {
$fichier = $this->dossierBase.self::DOSSIER_V2.'dsc/'.$tagDsc.'.txt';
if (file_exists($fichier) === true) {
$txt = file_get_contents($fichier);
$this->envoyerPage($tagDsc, $txt);
$envoyes[$tagDsc] = 'OK';
} else {
$this->messages->traiterErreur("Le fichier $fichier est introuvable.");
}
}
 
$tagCle = $nom['page_wiki_cle'];
if (isset($envoyes[$tagCle]) == false) {
$fichier = $this->dossierBase.self::DOSSIER_V2.'cle/'.$tagCle.'.txt';
if (file_exists($fichier) === true) {
$txt = file_get_contents($fichier);
$this->envoyerPage($tagCle, $txt);
$envoyes[$tagCle] = 'OK';
} else {
$this->messages->traiterErreur("Le fichier $fichier est introuvable.");
}
}
$this->messages->afficherAvancement("Upload des textes dans le wikini eFlore");
}
echo "\n";
}
 
public function chargerTxtDansWikiEflore() {
$this->chargerIndex();
$envoyes = array();
foreach ($this->index as $nom) {
$tagDsc = $nom['page_wiki_dsc'];
if ($tagDsc != '' && isset($envoyes[$tagDsc]) == false) {
$fichier = $this->dossierBase.self::DOSSIER_V2.'dsc/'.$tagDsc.'.txt';
if (file_exists($fichier) === true) {
$txt = file_get_contents($fichier);
$this->enregistrerPage($tagDsc, $txt);
$envoyes[$tagDsc] = 'OK';
} else {
$this->messages->traiterErreur("Le fichier $fichier est introuvable.");
}
}
 
$tagCle = $nom['page_wiki_cle'];
if ($tagCle != '' && isset($envoyes[$tagCle]) == false) {
$fichier = $this->dossierBase.self::DOSSIER_V2.'cle/'.$tagCle.'.txt';
if (file_exists($fichier) === true) {
$txt = file_get_contents($fichier);
$this->enregistrerPage($tagCle, $txt);
$envoyes[$tagCle] = 'OK';
} else {
$this->messages->traiterErreur("Le fichier $fichier est introuvable.");
}
}
$this->messages->afficherAvancement("Enregistrement des textes dans le wikini eFlore");
}
echo "\n";
}
 
public function chargerIndexDansWikiEflore() {
$index = $this->creerIndex();
foreach ($index as $titre => $txt) {
$this->enregistrerPage($titre, $txt);
}
}
 
public function uploaderIndexDansWikiEflore() {
$index = $this->creerIndex();
foreach ($index as $titre => $txt) {
$this->envoyerPage($titre, $txt);
}
}
 
public function creerIndex() {
$this->chargerIndex();
$envoyes = array();
$pageIndexFamille = "==Index Famille Coste==\n\n";
$pageIndexGenre = "==Index Genre Coste==\n\n";
$pageIndexEspece = "==Index Espèce Coste==\n\n";
foreach ($this->index as $nom) {
$indentation = $this->getIndentationTxtLien($nom);
$txtLien = $this->getTxtLienGenerique($nom);
$img = $nom['image'];
$tagDsc = $nom['page_wiki_dsc'];
if (isset($envoyes[$tagDsc]) == false) {
//$fichier = $this->dossierBase.self::DOSSIER_V2.'dsc/'.$tagDsc.'.txt';
if ($nom['rang'] <= 180) {
$pageIndexFamille .= "$indentation- [[$tagDsc $txtLien]]\n";
} elseif ($nom['rang'] == 220) {
$pageIndexGenre .= "$indentation- [[$tagDsc $txtLien]]\n";
} else {
$pageIndexEspece .= "$indentation- [[$tagDsc $txtLien]] - [[http://www.tela-botanica.org/eflore/donnees/coste/2.00/img/$img]]\n";
}
$envoyes[$tagDsc] = 'OK';
}
 
$tagCle = $nom['page_wiki_cle'];
if (isset($envoyes[$tagCle]) == false) {
//$fichier = $this->dossierBase.self::DOSSIER_V2.'cle/'.$tagCle.'.txt';
$indentation = $indentation.' ';
if ($nom['rang'] <= 180) {
$pageIndexFamille = rtrim($pageIndexFamille, "\n");
$pageIndexFamille .= " - [[$tagCle Clé]]\n";
} elseif ($nom['rang'] == 220) {
$pageIndexGenre = rtrim($pageIndexGenre, "\n");
$pageIndexGenre .= " - [[$tagCle Clé]]\n";
}
$envoyes[$tagCle] = 'OK';
}
$this->messages->afficherAvancement("Création des pages d'index pour le wikini eFlore");
}
echo "\n";
 
$index = array('IndexFamille' => $pageIndexFamille, 'IndexGenre' => $pageIndexGenre, 'IndexEspece' => $pageIndexEspece);
return $index;
}
 
private function getIndentationTxtLien($nom) {
$rangs = array('Reg' => 1, 'Emb' => 2, 'Cla' => 3, 'Fam' => 4, 'Gen' => 5, 'Esp' => 6);
$indentation = '';
if (preg_match('/^(Reg|Emb|Cla|Fam|Gen|Esp)[0-9]+/', $nom['page_wiki_dsc'], $match)) {
$type = $match[1];
$indentation = str_repeat(' ', $rangs[$type]);
}
return $indentation;
}
 
private function getTxtLienGenerique($nom) {
$rangs = array('Reg' => 'Règne', 'Emb' => 'Embranchement', 'Cla' => 'Classe', 'Fam' => 'Famille',
'Gen' => 'Genre', 'Esp' => 'Espèce');
$nomSci = $nom['nom_sci'];
$nomCoste = $nom['nom_coste'];
$txtLien = '';
if (preg_match('/^(Reg|Emb|Cla|Fam|Gen|Esp)([0-9]*)/', $nom['page_wiki_dsc'], $match)) {
$numCoste = $match[2];
$type = $match[1];
$nomRang = $rangs[$type];
$nom = ($type == 'Fam') ? $nomCoste : $nomSci;
$txtLien = "$nomRang $numCoste - $nom";
}
return $txtLien;
}
 
private function envoyerPage($titre, $txt) {
$donnees = array('pageTag' => $titre, 'pageContenu' => $txt);
$this->restClient->ajouter($this->URL_WIKI_EFLORE, $donnees);
}
 
private function enregistrerPage($titre, $txt) {
$titre = $this->bdd->proteger($titre);
$time = $this->bdd->proteger(date('Y-m-d H:i:s'));
$txt = $this->bdd->proteger($txt);
$requete = "INSERT INTO `coste_pages` (`tag`, `time`, `body`, `body_r`, `owner`, `user`, `latest`, `handler`, `comment_on`) VALUES ".
"($titre, $time, $txt, '', '', 'ScriptEflore', 'Y', 'page', '')";
$this->bdd->requeter($requete);
}
 
private function telechargerTxt($url) {
$json = $this->restClient->consulter($url);
$donnees = json_decode($json, true);
return $donnees['texte'];
}
 
private function chargerIndex() {
$indexTxt = $this->dossierBase.self::DOSSIER_V2.'coste_v2_00.tsv';
$this->index = $this->outils->transformerTxtTsvEnTableau($indexTxt);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/coste/coste.ini
New file
0,0 → 1,30
; Ajouter les nouvelles version à la suite dans versions et versionsDonnees.
version="2_00"
versionDonnees="2.00"
dossierTsv = "{ref:dossierDonneesEflore}coste/{ref:versionDonnees}/"
dossierTsvTpl = "{ref:dossierDonneesEflore}coste/%s/"
dossierSql = "{ref:dossierDonneesEflore}coste/"
 
[tables]
costeMeta = "coste_meta"
coste = "coste_v{ref:version}"
costeTpl = "coste_v%s"
 
[fichiers]
structureSqlVersion = "coste_v{ref:version}.sql"
structureSqlVersionTpl = "coste_v%s.sql"
coste = "coste_v{ref:version}.tsv"
costeTpl = "coste_v%s.tsv"
costeWikiniTpl = "coste_wikini_v%s.sql"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
structureSqlVersion = "{ref:dossierTsv}{ref:fichiers.structureSqlVersion}"
structureSqlVersionTpl = "{ref:dossierTsvTpl}{ref:fichiers.structureSqlVersionTpl}"
coste = "{ref:dossierTsv}{ref:fichiers.coste}"
costeTpl = "{ref:dossierTsvTpl}{ref:fichiers.costeTpl}"
costeWikiniTpl = "{ref:dossierTsvTpl}{ref:fichiers.costeWikiniTpl}"
 
[wiki]
travail = "http://www.tela-botanica.org/wikini/florecoste/api/rest/0.5/pages"
eflore = "http://www.tela-botanica.org/wikini/coste/api/rest/0.5/pages"
/tags/v5.7-arrayanal/scripts/modules/coste/Index.php
New file
0,0 → 1,329
<?php
class Index {
 
const DOSSIER_V0 = '../../../donnees/coste/0.00/';
const DOSSIER_V2 = '../../../donnees/coste/2.00/';
 
private $conteneur = null;
private $outils = null;
private $messages = null;
private $generateur = null;
private $dossierBase = '';
private $spIndex = array();
private $supraSpIndex = array();
private $imgIndex = array();
private $indexFinal = array();
private $tableauParDefaut = array();
private $nbreTaxonInf = array();
private $enteteFinal = array(
'num_nom',
'num_nom_retenu',
'num_tax_sup',
'rang',
'nom_sci',
'nom_supra_generique',
'genre',
'epithete_infra_generique',
'epithete_sp',
'type_epithete',
'epithete_infra_sp',
'cultivar_groupe',
'cultivar',
'nom_commercial',
'auteur',
'annee',
'biblio_origine',
'notes',
'nom_addendum',
'nom_francais',
'nom_coste',
'auteur_coste',
'biblio_coste',
'num_nom_coste',
'num_nom_retenu_coste',
'num_tax_sup_coste',
'synonymie_coste',
'tome',
'page',
'nbre_taxons',
'flore_bdtfx_nn',
'flore_bdtfx_nt',
'image',
'image_auteur',
'page_wiki_dsc',
'page_wiki_cle',
'nom_sci_html');
 
public function __construct(Conteneur $conteneur) {
mb_internal_encoding('UTF-8');
setlocale(LC_ALL, 'fr_FR.UTF-8');
$this->conteneur = $conteneur;
$this->outils = $conteneur->getOutils();
$this->messages = $conteneur->getMessages();
$this->generateur = $conteneur->getGenerateurNomSciHtml();
$this->dossierBase = dirname(__FILE__).'/';
}
 
public function fusionnerIndex() {
$this->chargerIndexSp();
$this->chargerIndexSupraSp();
$this->initialiserTableauLigneIndexFinal();
$this->creerIndexFinal();
$this->insererCorrections();
$this->ajouterChampsDansIndexFinal();
$this->ajouteurAuteurImage();
$this->decomposerNomSci();
$this->ajouteurNomSciHtml();
$this->creerFichierCsvIndexFinal();
}
 
private function chargerIndexSp() {
$spIndexFichier = $this->dossierBase.self::DOSSIER_V0.'index_general_sp.tsv';
$index = $this->outils->transformerTxtTsvEnTableau($spIndexFichier);
$index = $this->reindexerParNumNomCoste($index);
foreach ($index as $numNomCoste => $infos) {
$numTaxSup = '';
if ($infos['num_nom_coste'] == $infos['num_nom_retenu_coste']) {
$numTaxSup = $infos['num_tax_sup_coste'];
} else {
$infosNomRetenu = $index[$infos['num_nom_retenu_coste']];
$numTaxSup = $infosNomRetenu['num_tax_sup_coste'];
}
$this->spIndex[$numTaxSup][] = $infos;
}
}
 
private function reindexerParNumNomCoste($index) {
$nouvelIndex = array();
foreach ($index as $infos) {
$nouvelIndex[$infos['num_nom_coste']] = $infos;
}
return $nouvelIndex;
}
 
private function chargerIndexSupraSp() {
$infraSpIndexFichier = $this->dossierBase.self::DOSSIER_V0.'index_general.tsv';
$this->supraSpIndex = $this->outils->transformerTxtTsvEnTableau($infraSpIndexFichier);
foreach ($this->supraSpIndex as $cle => $infos) {
$this->supraSpIndex[$cle]['num_nom_retenu_coste'] = $infos['num_nom_coste'];
}
}
 
private function initialiserTableauLigneIndexFinal() {
$this->tableauParDefaut = array();
foreach ($this->enteteFinal as $cle) {
$this->tableauParDefaut[$cle] = '';
}
}
 
private function creerIndexFinal() {
foreach ($this->supraSpIndex as $infos) {
$this->ajouterDansIndexFinal($infos);
if (preg_match('/^G[0-9]+$/', $infos['num_nom_coste'])) {
foreach ($this->spIndex[$infos['num_nom_coste']] as $infosSp) {
$this->ajouterDansIndexFinal($infosSp);
}
}
}
}
 
private function ajouterDansIndexFinal($infos) {
$infos = array_merge($this->tableauParDefaut, $infos);
$infos['num_nom'] = (count($this->indexFinal) + 1);
$this->indexFinal[$infos['num_nom_coste']] = $infos;
}
 
private function ajouterChampsDansIndexFinal() {
$this->genererNbreTaxons();
foreach ($this->indexFinal as $nnc => $infos) {
if ($infos['num_nom_coste'] == $infos['num_nom_retenu_coste']) {
$infos['num_nom_retenu'] = $infos['num_nom'];
if ($nnc != 'R') {
$nomSuperieur = $this->indexFinal[$infos['num_tax_sup_coste']];
$infos['num_tax_sup'] = $nomSuperieur['num_nom'];
}
$nomRetenu = $infos;
} else {
$nomRetenu = $this->indexFinal[$infos['num_nom_retenu_coste']];
$infos['num_nom_retenu'] = $nomRetenu['num_nom'];
$infos['page'] = $nomRetenu['page'];
$infos['tome'] = $nomRetenu['tome'];
}
$infos['image'] = $this->obtenirNomFichierImg($nomRetenu);
$infos['nbre_taxons'] = $this->obtenirNbreTaxon($infos);
$nomRetenu['nbre_taxons'] = $infos['nbre_taxons'];
$infos['page_wiki_dsc'] = $this->genererPageWikiDsc($nomRetenu);
$infos['page_wiki_cle'] = $this->genererPageWikiCle($nomRetenu);
 
$this->indexFinal[$nnc] = $infos;
}
}
 
private function genererNbreTaxons() {
foreach ($this->indexFinal as $infos) {
if ($infos['num_tax_sup_coste'] != '') {
if (isset($this->nbreTaxonInf[$infos['num_tax_sup_coste']])) {
$this->nbreTaxonInf[$infos['num_tax_sup_coste']] += 1;
} else {
$this->nbreTaxonInf[$infos['num_tax_sup_coste']] = 1;
}
}
}
}
 
private function genererPageWikiDsc($infos) {
$prefixe = $this->genererPrefixePage($infos);
if ($infos['rang'] == '180') {
$nomSci = str_replace(' ', '', ucwords(strtolower($infos['nom_coste'])));
} else {
$nomSci = str_replace(' ', '', ucwords(strtolower($infos['nom_sci'])));
}
$pageWiki = $prefixe.$nomSci;
return $pageWiki;
}
 
private function genererPageWikiCle($infos) {
$pageWiki = '';
if ($infos['nbre_taxons'] > 1) {
$prefixe = $this->genererPrefixePage($infos);
if ($infos['rang'] == '20') {
$pageWiki = $prefixe.'TabClaEtEmb';
} elseif ($infos['rang'] == '40' && ($infos['num_nom_coste'] == 'E2' || $infos['num_nom_coste'] == 'E3')) {
$pageWiki = $prefixe.'TabFam';
} else if ($infos['rang'] == '80') {
$pageWiki = $prefixe.'TabFam';
} else if ($infos['rang'] == '180') {
$pageWiki = $prefixe.'TabGen';
} else if ($infos['rang'] == '220') {
$pageWiki = $prefixe.'TabSp';
}
}
return $pageWiki;
}
 
private function genererPrefixePage($infos) {
$prefixe = '';
$num = preg_replace('/^[a-z]*([0-9]+)(?:[.][0-9a-z]|)$/i', '$1', $infos['num_nom_coste']);
if (preg_match('/^([0-9]+)[.][0-9a-z]$/i', $infos['num_nom_coste'], $match)) {
$num = sprintf('%04s', $match[1]);
} else if ($infos['rang'] == 20 ) {
$num = '';
} else if ($infos['rang'] < 80 ) {
$num = sprintf('%02s', $num);
} else if ($infos['rang'] < 290 ) {
$num = sprintf('%03s', $num);
} else {
$num = sprintf('%04s', $num);
}
$rangsTxt = array('20' => 'Reg', '40' => 'Emb', '80' => 'Cla', '180' => 'Fam', '220' => 'Gen', '290' => 'Esp', '340' => 'Var');
$rang = $rangsTxt[$infos['rang']];
 
$prefixe = $rang.$num;
return $prefixe;
}
 
private function obtenirNbreTaxon($infos) {
$nbre = '';
if (isset($this->nbreTaxonInf[$infos['num_nom_coste']])) {
$nbre = $this->nbreTaxonInf[$infos['num_nom_coste']];
}
return $nbre;
}
 
private function obtenirNomFichierImg($infos) {
$img = '';
if ($infos['rang'] == '290') {
$prefixe = preg_replace('/[.][a-z]$/', '', $infos['num_nom_retenu']);
$img = $prefixe.'.png';
}
return $img;
}
 
private function ajouteurAuteurImage() {
$this->chargerAuteurImg();
foreach ($this->indexFinal as $nnc => $infos) {
$infos['image_auteur'] = $this->imgIndex[$infos['image']];
$this->indexFinal[$nnc] = $infos;
}
}
 
private function chargerAuteurImg() {
$imgIndexFichier = $this->dossierBase.self::DOSSIER_V0.'coste_images_auteur_correspondance_bdnff.tsv';
$index = $this->outils->transformerTxtTsvEnTableau($imgIndexFichier);
foreach ($index as $infos) {
$id = $infos['id_image'];
$this->imgIndex[$id] = $infos['auteur'];
}
}
 
private function decomposerNomSci() {
$majuscule = "[ÆŒA-Z]";
$epithete = "[æœïa-z-]+";
foreach ($this->indexFinal as $nnc => $infos) {
$id = $infos['num_nom_coste'];
$nomSci = $infos['nom_sci'];
$rang = $infos['rang'];
if ($rang < 220) {
$infos['nom_supra_generique'] = $nomSci;
} else if ($rang == 220) {
$infos['genre'] = $nomSci;
} else if ($rang == 290) {
if (preg_match("/^($majuscule$epithete) ($epithete)$/", $nomSci, $match)) {
$infos['genre'] = $match[1];
$infos['epithete_sp'] = $match[2];
} else {
$this->messages->traiterErreur("Le nom $nomSci ($id) de rang $rang n'est pas standard.");
}
} else if ($rang == 340) {
if (preg_match("/^($majuscule$epithete) ($epithete) (var[.]) ($epithete)$/", $nomSci, $match)) {
$infos['genre'] = $match[1];
$infos['epithete_sp'] = $match[2];
$infos['type_epithete'] = $match[3];
$infos['epithete_infra_sp'] = $match[4];
} else {
$this->messages->traiterErreur("Le nom $nomSci ($id) de rang $rang n'est pas standard.");
}
}
 
$this->indexFinal[$nnc] = $infos;
$this->messages->afficherAvancement("Décomposition des noms scientifiques en cours");
}
echo "\n";
}
 
private function ajouteurNomSciHtml() {
foreach ($this->indexFinal as $nnc => $infos) {
$this->indexFinal[$nnc]['nom_sci_html'] = $this->generateur->genererNomSciHtml($infos);
$this->messages->afficherAvancement("Création des noms scientifiques HTML en cours");
}
echo "\n";
}
 
private function insererCorrections() {
$correctionsFichier = $this->dossierBase.self::DOSSIER_V2.'coste_v2_00_corrections.tsv';
$corrections = $this->outils->transformerTxtTsvEnTableau($correctionsFichier);
foreach ($corrections as $infos) {
$nnc = $infos['num_nom_coste'];
$infosACorriger = isset($this->indexFinal[$nnc]) ? $this->indexFinal[$nnc] : array();
foreach ($corrections as $champ => $valeur) {
$infosACorriger[$champ] = $valeur;
}
$this->indexFinal[$nnc] = $infosACorriger;
}
}
 
private function creerFichierCsvIndexFinal() {
$lignes = array();
array_unshift($this->indexFinal, $this->enteteFinal);
foreach ($this->indexFinal as $infos) {
$lignes[] = implode("\t", $infos);
}
 
$txt = '';
$txt = implode("\n", $lignes);
 
$fichierTsvIndexFinal = $this->dossierBase.self::DOSSIER_V2.'coste_v2_00.tsv';
file_put_contents($fichierTsvIndexFinal, $txt);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/coste/Versions.php
New file
0,0 → 1,71
<?php
class Versions {
 
private $conteneur = null;
private $eflore = null;
private $bdd = null;
 
public function __construct(Conteneur $conteneur) {
$this->conteneur = $conteneur;
$this->eflore = $conteneur->getEfloreCommun();
$this->bdd = $conteneur->getBdd();
}
 
public function chargerTous() {
$this->chargerVersions();
}
 
public function chargerVersions() {
$versions = explode(',', Config::get('versions'));
$versionsDonnees = explode(',', Config::get('versionsDonnees'));
foreach ($versions as $id => $version) {
$versionDonnees = $versionsDonnees[$id];
$this->chargerStructureSqlVersion($versionDonnees, $version);
$this->chargerIndexVersion($versionDonnees, $version);
$this->chargerDumpWikiniVersion($versionDonnees, $version);
}
}
 
private function chargerStructureSqlVersion($versionDonnees, $version) {
$fichierSqlTpl = Config::get('chemins.structureSqlVersionTpl');
$fichierSql = sprintf($fichierSqlTpl, $versionDonnees, $version);
$contenuSql = $this->eflore->recupererContenu($fichierSql);
$this->eflore->executerScriptSql($contenuSql);
}
 
private function chargerIndexVersion($versionDonnees, $version) {
$fichierTsvTpl = Config::get('chemins.costeTpl');
$fichierTsv = sprintf($fichierTsvTpl, $versionDonnees, $version);
$tableTpl = Config::get('tables.costeTpl');
$table = sprintf($tableTpl, $version);
$requete = "LOAD DATA INFILE '$fichierTsv' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES ';
$this->bdd->requeter($requete);
}
 
private function chargerDumpWikiniVersion($versionDonnees, $version) {
$versionMajeure = (int) substr($version, 0, 1);
if ($versionMajeure < 2) {
$fichierWikiTpl = Config::get('chemins.costeWikiniTpl');
$fichierDump = sprintf($fichierWikiTpl, $versionDonnees, $version);
$contenuSql = $this->eflore->recupererContenu($fichierDump);
$this->eflore->executerScriptSql($contenuSql);
}
}
 
public function supprimerTous() {
$requete = "DROP TABLE IF EXISTS coste_meta, ".
" coste_correspondance_bdnff, coste_images_auteur_correspondance_bdnff, ".
" coste_images_correspondance_bdnff, coste_index, coste_index_general, ".
" coste_acls, coste_links, coste_pages, coste_referrers, coste_triples, coste_users, ".
" coste_v1_00, coste_v2_00 ";
$this->bdd->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/coste/Coste.php
New file
0,0 → 1,117
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php coste -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2012, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Coste extends EfloreScript {
 
public function executer() {
try {
$this->initialiserProjet('coste');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$version = $this->getClasseVersion();
$version->chargerTous();
break;
case 'chargerStructureSql' :
$version = $this->getClasseVersion();
$version->chargerStructureSql();
break;
case 'chargerVersions' :
$version = $this->getClasseVersion();
$version->chargerVersions();
break;
case 'supprimerTous' :
$version = $this->getClasseVersion();
$version->supprimerTous();
break;
case 'creerDscTxt' :
$description = $this->getClasseDescription();
$description->genererDescriptionTxt();
break;
case 'statDscTxt' :
$description = $this->getClasseDescription();
$description->verifierDescriptionTxt();
break;
case 'correspondanceDsc' :
$description = $this->getClasseDescription();
$description->genererCorrespondance();
break;
case 'fusionIndex' :
$description = $this->getClasseIndex();
$description->fusionnerIndex();
break;
case 'uploadFichiersSp' :
$wiki = $this->getClasseWiki();
$wiki->uploaderFichiersSp();
break;
case 'downloadWiki' :
$wiki = $this->getClasseWiki();
$wiki->dowloaderPagesWiki();
break;
case 'uploadTxt' :
$wiki = $this->getClasseWiki();
$wiki->uploaderDansWikiEflore();
break;
case 'uploadIndex' :
$wiki = $this->getClasseWiki();
$wiki->uploaderIndexDansWikiEflore();
break;
case 'chargerTxt' :
$wiki = $this->getClasseWiki();
$wiki->chargerTxtDansWikiEflore();
break;
case 'chargerIndex' :
$wiki = $this->getClasseWiki();
$wiki->chargerIndexDansWikiEflore();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function getClasseVersion() {
$version = $this->getClasse('Versions');
return $version;
}
 
private function getClasseDescription() {
$description = $this->getClasse('Description');
return $description;
}
 
private function getClasseIndex() {
$index = $this->getClasse('Index');
return $index;
}
 
private function getClasseWiki() {
$wiki = $this->getClasse('Wiki');
return $wiki;
}
 
private function getClasse($classeNom) {
$conteneur = new Conteneur();
$conteneur->setParametre('-v', $this->getParametre('-v'));
$conteneur->setParametre('scriptChemin', $this->getScriptChemin());
require_once dirname(__FILE__).'/'.$classeNom.'.php';
$objet = new $classeNom($conteneur);
return $objet;
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/lion1906/Lion1906.php
New file
0,0 → 1,122
<?php
//declare(encoding='UTF-8');
/**
* Classe permettant de :
* - convertir la latitude et longitude en degre, et rajouter l'objet point centroide de la commune.
* - charger la bdd
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php lion1906 -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Mohcen BENMOUNAH <mohcen@tela-botanica.org>
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Lion1906 extends EfloreScript {
 
public function executer() {
try {
$this->initialiserProjet('lion1906');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerMetaDonnees();
$this->chargerLion1906();
$this->preparerTable();
$this->convertirRadianEnDegre();
break;
case 'convertir' :
$this->preparerTable();
$this->convertirRadianEnDegre();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
protected function chargerMetaDonnees() {
$contenuSql = $this->recupererContenu(Config::get('chemins.lion1906Meta'));
$this->executerScripSql($contenuSql);
}
 
private function chargerLion1906() {
$chemin = Config::get('chemins.lion1906');
$table = Config::get('tables.lion1906');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET latin1 '.
'FIELDS '.
" TERMINATED BY ';' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function convertirRadianEnDegre() {
$table = Config::get('tables.lion1906');
$requete = 'SELECT insee, latitude_radian, longitude_radian '.
"FROM $table ";
$LatLons = $this->getBdd()->recupererTous($requete);
 
foreach ($LatLons as $LatLon) {
$insee = $LatLon['insee'] ;
$latitude_degre = $LatLon['latitude_radian'] * 180 / pi();
$longitude_degre = $LatLon['longitude_radian'] * 180 / pi();
$latitude_degre = str_replace(',', '.', $latitude_degre);
$longitude_degre = str_replace(',', '.', $longitude_degre);
$this->formerPointCentre($latitude_degre, $longitude_degre, $insee);
$this->afficherAvancement('Analyse des communes Lion1906');
}
}
 
private function preparerTable() {
$table = Config::get('tables.lion1906');
$requete = "ALTER TABLE $table ".
'DROP latitude_degre, '.
'DROP longitude_degre, '.
'DROP centroide, '.
'DROP INDEX insee ';
$this->getBdd()->requeter($requete);
 
$requete = "ALTER TABLE $table ".
' ADD latitude_degre double NOT NULL , '.
' ADD longitude_degre double NOT NULL , '.
' ADD centroide point NOT NULL ';
$this->getBdd()->requeter($requete);
 
$requete = "ALTER TABLE $table ".
'ADD INDEX insee (insee, latitude_degre, longitude_degre, centroide) ';
$this->getBdd()->requeter($requete);
}
 
private function formerPointCentre($latitude_degre, $longitude_degre, $insee) {
$centre = "$latitude_degre $longitude_degre" ;
$table = Config::get('tables.lion1906');
$requete = "UPDATE $table ".
"SET latitude_degre = '$latitude_degre', longitude_degre = '$longitude_degre', ".
" centroide = POINTFROMTEXT('POINT($centre)') ".
"WHERE insee = '$insee' ";
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS lion1906_meta, lion1906_communes_v2008";
$this->getBdd()->requeter($requete);
}
 
}
?>
/tags/v5.7-arrayanal/scripts/modules/lion1906/lion1906.ini
New file
0,0 → 1,17
version="2008"
dossierTsv = "{ref:dossierDonneesEflore}lion1906/2008-12-17/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
lion1906Meta = "lion1906_meta"
lion1906 = "lion1906_communes_v{ref:version}"
 
[fichiers]
structureSql = "lion1906.sql"
lion1906Meta = "lion1906_meta.sql"
lion1906 = "villes.csv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
lion1906Meta = "{ref:dossierSql}{ref:fichiers.lion1906Meta}"
lion1906 = "{ref:dossierTsv}{ref:fichiers.lion1906}"
/tags/v5.7-arrayanal/scripts/modules/nva/nva.ini
New file
0,0 → 1,21
version="2_03"
dossierTsv = "{ref:dossierDonneesEflore}nva/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
nva = "nva_v{ref:version}"
index = "nva_index_v{ref:version}"
ontologies = "nva_ontologies"
bdtxa = "bdtxa_v1_00"
 
[fichiers]
structureSql = "nva_v{ref:version}.sql"
nva = "nva_v{ref:version}.tsv"
index = "index_v{ref:version}.tsv"
ontologies = "nva_ontologies.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
nva = "{ref:dossierTsv}{ref:fichiers.nva}"
index = "{ref:dossierTsv}{ref:fichiers.index}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.7-arrayanal/scripts/modules/nva/Nva.php
New file
0,0 → 1,97
<?php
/** Corriger les codes langues pays genre et nombre à la main
* Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php nva -a chargerTous
*/
class Nva extends EfloreScript {
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('nva');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerDonnees(Config::get('chemins.nva'), Config::get('tables.nva'));
$this->chargerDonnees(Config::get('chemins.index'), Config::get('tables.index'));
$this->ajouterChampNomVernaIndex();
$this->chargerDonnees(Config::get('chemins.ontologies'), Config::get('tables.ontologies'));
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerDonnees' :
$this->chargerDonnees();
break;
case 'ajouterChampNomVernaIndex' :
$this->ajouterChampNomVernaIndex();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerDonnees($chemin, $table) {
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
private function ajouterChampNomVernaIndex() {
$this->preparerTablePrChpNomVerna();
$this->remplirChpNomVerna();
}
private function preparerTablePrChpNomVerna() {
$table = Config::get('tables.index');
$requete = "SHOW COLUMNS FROM $table LIKE 'nom_vernaculaire' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE $table ".
'ADD `nom_vernaculaire` VARCHAR( 40 ) NOT NULL ,
ADD `code_langue` VARCHAR( 10 ) NOT NULL ,
ADD `num_genre` INT( 1 ), ADD `num_nombre` INT( 1 ) ';
$this->getBdd()->requeter($requete);
}
}
 
private function remplirChpNomVerna() {
$table = Config::get('tables.index');
$requete = "UPDATE `nva_index_v2_03`
SET nom_vernaculaire=(select n.nom_vernaculaire from nva_v2_03 n where n.num_nom_vernaculaire=nva_index_v2_03.num_nom_vernaculaire),
code_langue=(select n.code_langue from nva_v2_03 n where n.num_nom_vernaculaire=nva_index_v2_03.num_nom_vernaculaire),
num_genre=(select n.num_genre from nva_v2_03 n where n.num_nom_vernaculaire=nva_index_v2_03.num_nom_vernaculaire),
num_nombre=(select n.num_nombre from nva_v2_03 n where n.num_nom_vernaculaire=nva_index_v2_03.num_nom_vernaculaire)";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'update d'ajouts des noms");
}
$this->afficherAvancement("Ajout des noms vernaculaires à l'index");
echo "\n";
}
 
 
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS ".Config::get('tables.nva').", ".Config::get('tables.index').
", ".Config::get('tables.ontologies').", nva_meta ";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/nvps/Nvps.php
New file
0,0 → 1,124
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php nvps
* -a chargerTous
* Options :
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).
*/
class Nvps extends EfloreScript {
 
private $nomsIndex = array();
private $numeroIndex = 1;
 
protected $parametres_autorises = array(
'-t' => array(false, false, 'Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).'));
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('nvps');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerNvps();
break;
case 'chargerStructure' :
$this->chargerStructureSql();
break;
case 'chargerNvps' :
$this->chargerNvps();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
/**
* Charge le fichier en créant un id pour chaque nom vernaculaire.
*/
private function chargerNvps() {
//Debug::printr(Config::get('fichiers'));
$fichierOuvert = $this->ouvrirFichier(Config::get('chemins.nvps'));
$donnees = $this->analyserFichier($fichierOuvert);
fclose($fichierOuvert);
foreach ($donnees as $donnee) {
$table = Config::get('tables.nvps');
$fields = implode(', ', array_keys($donnee));
$values = implode(', ', $donnee);
 
$requete = "INSERT INTO $table ($fields) VALUES ($values) ";
$this->getBdd()->requeter($requete);
 
$this->afficherAvancement("Insertion des noms vernaculaires dans la base de données");
if ($this->stopperLaBoucle($this->getParametre('t'))) {
break;
}
}
echo "\n";
}
 
private function ouvrirFichier($chemin) {
$fichierOuvert = false;
if ($chemin) {
if (file_exists($chemin) === true) {
$fichierOuvert = fopen($chemin, 'r');
if ($fichierOuvert == false) {
throw new Exception("Le fichier $chemin n'a pas pu être ouvert.");
}
} else {
throw new Exception("Le fichier $chemin est introuvable.");
}
} else {
throw new Exception("Aucun chemin de fichier n'a été fourni.");
}
return $fichierOuvert;
}
 
private function analyserFichier($fichierOuvert) {
$entetesCsv = explode("\t", trim(fgets($fichierOuvert)));
 
$donnees = array();
while ($ligneCsv = fgets($fichierOuvert)) {
$champs = explode("\t", trim($ligneCsv));
if (count($champs) > 0) {
$infos = array();
foreach ($entetesCsv as $ordre => $champNom) {
$valeur = isset($champs[$ordre]) ? $champs[$ordre] : '';
$infos[$champNom] = $valeur;
}
$infos['id'] = $this->getIndexNomVernaculaire($infos['nom_vernaculaire']);
$donnees[] = $this->getBdd()->protegerTableau($infos);
}
$this->afficherAvancement("Analyse du fichier des noms vernaculaires");
if ($this->stopperLaBoucle()) {
break;
}
}
echo "\n";
 
return $donnees;
}
 
private function getIndexNomVernaculaire($nomVernaculaire) {
$indexCourrant = null;
if (array_key_exists($nomVernaculaire, $this->nomsIndex) == false) {
$this->nomsIndex[$nomVernaculaire] = $this->numeroIndex++;
}
$indexCourrant = $this->nomsIndex[$nomVernaculaire];
return $indexCourrant;
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS nvps_meta, nvps_v2007, nvps_v2012";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/nvps/nvps.ini
New file
0,0 → 1,14
version = "2012"
dossierTsv = "{ref:dossierDonneesEflore}nvps/2012/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
nvps = "nvps_v{ref:version}"
 
[fichiers]
structureSql = "nvps_v{ref:version}.sql"
nvps = "{ref:tables.nvps}.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
nvps = "{ref:dossierTsv}{ref:fichiers.nvps}"
/tags/v5.7-arrayanal/scripts/modules/iso_3166_1/Iso31661.php
New file
0,0 → 1,82
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php iso6391
* -a chargerTous
* Options :
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).
*/
class Iso31661 extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('iso-3166-1');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerIso31661();
$this->chargerOntologies();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerIso31661' :
$this->chargerIso31661();
break;
case 'chargerOntologies' :
$this->chargerOntologies();
break;
case 'test' :
$this->tester();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function tester() {
echo Config::get('test');
}
 
private function chargerIso31661() {
$chemin = Config::get('chemins.iso31661');
$table = Config::get('tables.iso31661');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerOntologies() {
$chemin = Config::get('chemins.ontologies');
$table = Config::get('tables.ontologies');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS iso_3166_1_meta, iso_3166_1_ontologies_v2006, iso_3166_1_v2006";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/iso_3166_1/iso-3166-1.ini
New file
0,0 → 1,18
version="2006"
dossierTsv = "{ref:dossierDonneesEflore}iso-3166-1/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
 
[tables]
iso31661 = "iso_3166_1_v{ref:version}"
ontologies = "iso_3166_1_ontologies_v{ref:version}"
 
[fichiers]
structureSql = "iso-3166-1_v{ref:version}.sql"
iso31661 = "iso-3166-1_v{ref:version}.tsv"
ontologies = "iso-3166-1_ontologies_v{ref:version}.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
iso31661 = "{ref:dossierTsv}{ref:fichiers.iso31661}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.7-arrayanal/scripts/modules/iso_3166_1
New file
Property changes:
Added: svn:ignore
+iso-3166-1.ini
/tags/v5.7-arrayanal/scripts/modules/tapirlink/A_LIRE.txt
New file
0,0 → 1,0
Créer une base de données tb_hit_indexation avant de lancer les scripts
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/tapirlink/tapirlink.ini
New file
0,0 → 1,15
version="1_00"
dossierTsv = "{ref:dossierDonneesEflore}tapirlink/2012-01-30/"
dossierSql = "{ref:dossierTsv}"
bdd_nom = "tb_hit_indexation"
 
[tables]
enr = raw_occurrence_record
 
[fichiers]
structureSql = "raw_occurrence_record_v{ref:version}.sql"
enr = "{ref:tables.enr}.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
enr = "{ref:dossierTsv}{ref:fichiers.enr}"
/tags/v5.7-arrayanal/scripts/modules/tapirlink/Tapirlink.php
New file
0,0 → 1,93
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php cel -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Tapirlink extends EfloreScript {
 
public function executer() {
try {
$this->initialiserProjet('tapirlink');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerTapirlink();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
protected function initialiserProjet($projet) {
$bases = $this->getListeBases();
parent::initialiserProjet($projet);
$this->verifierPresenceBdd($bases);
}
 
private function getListeBases() {
$requete = "SHOW DATABASES";
$bases = $this->getBdd()->recupererTous($requete);
return $bases;
}
 
private function verifierPresenceBdd($bases) {
$bddNom = Config::get('bdd_nom');
$existe = false;
foreach ($bases as $base) {
if ($base['Database'] == $bddNom) {
$existe = true;
break;
}
}
if ($existe === false) {
$message = "Veuillez créer la base de données '$bddNom'.";
throw new Exception($message);
}
}
 
private function chargerTapirlink() {
$tablesCodes = array_keys(Config::get('tables'));
foreach ($tablesCodes as $code) {
echo "Chargement de la table : $code\n";
$this->chargerFichierTsvDansTable($code);
}
}
 
private function chargerFichierTsvDansTable($code) {
$chemin = Config::get('chemins.'.$code);
$table = Config::get('tables.'.$code);
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS raw_occurrence_record ";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/baseflor/BaseflorRangSupInsertion.php
New file
0,0 → 1,272
<?php
/**
*
*
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org>
*
*
*/
class BaseflorRangSupInsertion {
private $table = null;
private $donnees_initiales = array();
private $valeurs_insertion;
private $infos_taxon = array();
private $conteneur;
private $efloreCommun;
private $message;
private $outils;
private $nn_courant;
private $nn_superieur;
private $champs_ecologiques = array();
private $Bdd;
public function __construct(Conteneur $conteneur, Bdd $bdd) {
$this->conteneur = $conteneur;
$this->Bdd = $bdd;
$this->efloreCommun = $conteneur->getEfloreCommun();
$this->message = $conteneur->getMessages();
$this->outils = $conteneur->getOutils();
$this->dossierBase = dirname(__FILE__).'/';
}
public function insererDonnees(){
echo "Chargement de la structure en cours \n" ;
$this->efloreCommun->chargerFichierSql('chemins.rang_sup_sql');
echo "Récupération des données de baseflor en cours \n";
$this->recupererDonneesInitiales();
echo "Calcul des valeurs pour les rangs supérieurs en cours \n";
$this->consulterInfosTaxons();
$this->recupererValeursInsertion();
$this->insererDonneesRangSup();
}
private function insererDonneesRangSup() {
$table = Config::get('tables.rang_sup');
$requete_truncate = 'TRUNCATE TABLE '.$table;
$this->Bdd->requeter($requete_truncate);
$i = 0;
foreach ($this->valeurs_insertion as $nn => $valeurs){
$requete = "INSERT INTO $table VALUES({$i},$nn, 'bdtfx', '{$valeurs['ve_lumiere']['min']}', ".
"'{$valeurs['ve_lumiere']['max']}','{$valeurs['ve_temperature']['min']}',".
"'{$valeurs['ve_temperature']['max']}','{$valeurs['ve_continentalite']['min']}',".
"'{$valeurs['ve_continentalite']['max']}','{$valeurs['ve_humidite_atmos']['min']}',".
"'{$valeurs['ve_humidite_atmos']['max']}','{$valeurs['ve_humidite_edaph']['min']}',".
"'{$valeurs['ve_humidite_edaph']['max']}','{$valeurs['ve_reaction_sol']['min']}',".
"'{$valeurs['ve_reaction_sol']['max']}','{$valeurs['ve_nutriments_sol']['min']}',".
"'{$valeurs['ve_nutriments_sol']['max']}','{$valeurs['ve_salinite']['min']}',".
"'{$valeurs['ve_salinite']['max']}','{$valeurs['ve_texture_sol']['min']}',".
"'{$valeurs['ve_texture_sol']['max']}','{$valeurs['ve_mat_org_sol']['min']}',".
"'{$valeurs['ve_mat_org_sol']['max']}');";
$this->Bdd->requeter($requete);
$i++;
$this->message->afficherAvancement('Insertion des valeurs pour les rangs supérieurs en cours');
}
}
 
 
// dans cette solution je parcours les donnees de baseflor
// je teste une donnée (si min max) pour récuperer les valeurs pour chaque rang superieur
// jusqu'à famille (180) puis je passe à la suivante jusqu'à avoir parcouru tout baseflor
private function recupererValeursInsertion(){
$this->champs_ecologiques = $this->outils->recupererTableauConfig(Config::get('Parametres.champsEcologiques'));
$this->valeurs_insertion = array();
if (empty($this->donnees_initiales)) {
throw new Exception("Erreur : pas de données à traiter.");
} else {
foreach ($this->donnees_initiales as $nn => $ecologie) {
$this->nn_courant = $nn;
$this->nn_superieur = isset($this->infos_taxon[$this->nn_courant]) ? $this->infos_taxon[$this->nn_courant]['nn_sup'] : null;
$rang = isset($this->infos_taxon[$this->nn_superieur]) ? $this->infos_taxon[$this->nn_superieur]['rang'] : 179 ;
while ($rang >= 180){
if (!isset($donnees_initiales[$this->nn_superieur])) {
foreach ($this->champs_ecologiques as $nom) {
$this->testerSiMinMax($nom, $ecologie[$nom]);
}
}
$this->nn_superieur = isset($this->infos_taxon[$this->nn_superieur]) ? $this->infos_taxon[$this->nn_superieur]['nn_sup'] : null;
$rang = !empty($this->nn_superieur) ? $this->infos_taxon[$this->nn_superieur]['rang'] : 179 ;
}
}
}
}
// ici je parcours toutes les données de baseflor et je teste et récupère les valeurs pour le rang superieur
//direct puis je récupère les données obtenues et je recommence jusqu'à que tous les rangs obtenus soient des familles
private function recupererValeursInsertion2(){
$this->champs_ecologiques = $this->outils->recupererTableauConfig(Config::get('Parametres.champsEcologiques'));
$this->valeurs_insertion = array();
if (empty($this->donnees_initiales)) {
throw new Exception("Erreur : pas de données à traiter.");
} else {
$donnees_traitees = $this->donnees_initiales;
$donnees_deja_traitees = array();
$condition_fin = true;
$tab_num_nom = array_keys($donnees_traitees);
while (!empty($donnees_traitees)) {
reset($donnees_traitees);
$this->nn_courant = array_shift($tab_num_nom);
$data = array_shift($donnees_traitees);
if (isset($this->infos_taxon[$this->nn_courant])) {
$this->nn_superieur = $this->infos_taxon[$this->nn_courant]['nn_sup'];
if (!isset($donnees_deja_traitees[$this->nn_courant])) {
if ($this->infos_taxon[$this->nn_superieur]['rang'] >= 180){
$condition_fin = false;
foreach ($this->champs_ecologiques as $nom) {
$this->testerSiMinMax($nom, $data[$nom]);
}
}
}
$donnees_deja_traitees[$this->nn_courant] = 1;
}
if ($condition_fin == false && empty($donnees_traitees)) {
$donnees_traitees = $this->valeurs_insertion;
$tab_num_nom = array_keys($donnees_traitees);
$condition_fin = true;
}
}
}
}
// je stocke des valeurs à insérer sous la forme : $insertion [{nn_tax_sup}][{nom_de_chps}][{max ou min}] = {valeur}
private function testerSiMinMax($nom, $valeur) {
$nn = $this->nn_superieur;
if ( !isset($this->valeurs_insertion[$nn][$nom]['min'])
|| empty($valeur['min'])
|| empty($this->valeurs_insertion[$nn][$nom]['min'])
|| $this->valeurs_insertion[$nn][$nom]['min'] > $valeur['min'] ){
$this->valeurs_insertion[$nn][$nom]['min'] = $valeur['min'];
}
if ( !isset($this->valeurs_insertion[$nn][$nom]['max'])
|| empty($this->valeurs_insertion[$nn][$nom]['max'])
|| empty($valeur['max'])
|| $this->valeurs_insertion[$nn][$nom]['max'] < $valeur['max'] ) {
$this->valeurs_insertion[$nn][$nom]['max'] = $valeur['max'];
}
}
// je stocke les infos taxons sous la forme : $info_taxon[{num_nomem}][{num_nomen_sup ou rang}] = {valeur}
private function consulterInfosTaxons() {
$table = Config::get('tables.taxons');
$requete = 'SELECT A.num_nom AS nn, B.num_tax_sup AS nn_sup, A.rang '.
"FROM $table A JOIN $table B ON (A.num_nom_retenu = B.num_nom) ".
'WHERE B.num_nom = B.num_nom_retenu ';
$resultat = $this->Bdd->recupererTous($requete);
foreach ($resultat as $res) {
$this->infos_taxon[$res['nn']] = array('nn_sup' => $res['nn_sup'], 'rang' => $res['rang'] );
}
}
// je stocke les valeurs initiales sous la forme : $initiales[{nn_nomem}][{champs ecologique}][{'min' ou 'max'}]
private function recupererDonneesInitiales() {
$table = Config::get('tables.donnees');
$requete = "SELECT num_nomen, ve_lumiere, ve_temperature, ve_continentalite, ve_humidite_atmos, ".
"ve_humidite_edaph, ve_reaction_sol, ve_nutriments_sol, ve_salinite, ve_texture_sol, ve_mat_org_sol ".
"FROM $table WHERE BDNT = 'BDTFX' ".
" AND num_nomen != 0 ".
" AND !(ve_lumiere = '' and ve_mat_org_sol = '' and ve_temperature = '' and ve_continentalite = '' ".
" and ve_humidite_atmos = '' and ve_humidite_edaph = '' and ve_nutriments_sol = '' and ve_salinite = ''".
" and ve_texture_sol = '' and ve_reaction_sol = '')";
$resultat = $this->Bdd->recupererTous($requete);
foreach ($resultat as $res) {
$this->donnees_initiales[$res['num_nomen']] = array(
've_lumiere' => array('min' => $res['ve_lumiere'], 'max' => $res['ve_lumiere']),
've_temperature' => array('min' => $res['ve_temperature'], 'max' => $res['ve_temperature']),
've_continentalite' => array('min' => $res['ve_continentalite'], 'max' => $res['ve_continentalite']),
've_humidite_atmos' => array('min' => $res['ve_humidite_atmos'], 'max' => $res['ve_humidite_atmos']),
've_humidite_edaph' => array('min' => $res['ve_humidite_edaph'], 'max' => $res['ve_humidite_edaph']),
've_reaction_sol' => array('min' => $res['ve_reaction_sol'], 'max' => $res['ve_reaction_sol']),
've_nutriments_sol' => array('min' => $res['ve_nutriments_sol'], 'max' => $res['ve_nutriments_sol']),
've_salinite' => array('min' => $res['ve_salinite'], 'max' => $res['ve_salinite']),
've_texture_sol' => array('min' => $res['ve_texture_sol'], 'max' => $res['ve_texture_sol']),
've_mat_org_sol' => array('min' => $res['ve_mat_org_sol'], 'max' => $res['ve_mat_org_sol']));
}
}
// +++ Fonctions de vérification des donnée obtenues ++++//
public function testAscendantsDeBaseflor(){
$this->recupererDonneesInitiales();
$this->consulterInfosTaxons();
$fichier = dirname(__FILE__).'/log/verifTaxonsSup.log';
$liste = array();
foreach ($this->donnees_initiales as $nn => $data) {
$nn_sup = isset($this->infos_taxon[$nn]) ? $this->infos_taxon[$nn]['nn_sup'] : '' ;
if (!empty($nn_sup) && !isset($donnees_initiales[$nn_sup])){
$rang = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['rang'] : 179 ;
while ($rang >= 180) {
if (!empty($nn_sup)) {
if (isset($liste["$nn_sup($rang)"])){
$liste["$nn_sup($rang)"] .= ", $nn";
}else {
$liste["$nn_sup($rang)"] = "$nn";
}
$nn_sup = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['nn_sup'] : '' ;
$rang = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['rang'] : 179 ;
}else {
break;
}
}
}
}
$log = "un ascendant (pas forcement l'ascendant directement au dessus) : les descendants contenus dans baseflor \n";
foreach ($liste as $cle => $inferieur){
$log .= "$cle : $inferieur \n";
}
file_put_contents($fichier, $log);
}
public function testEcologieAscendantsDeBaseflor(){
$this->recupererDonneesInitiales();
$this->consulterInfosTaxons();
$fichier = dirname(__FILE__).'/log/verifTaxonsSupEcolo.log';
$liste = array();
foreach ($this->donnees_initiales as $nn => $data) {
$nn_sup = isset($this->infos_taxon[$nn]) ? $this->infos_taxon[$nn]['nn_sup'] : '' ;
if (!empty($nn_sup) && !isset($donnees_initiales[$nn_sup])){
$rang = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['rang'] : 179 ;
while ($rang >= 180) {
if (!empty($nn_sup)) {
$ecolo = array_values($data);
list($l,$t,$c,$ha,$he,$r,$n,$s,$tx,$mo) = $ecolo;
if (isset($liste["$nn_sup($rang)"])){
$liste["$nn_sup($rang)"] .= ",[{$l['min']}, {$t['min']}, {$c['min']},"
."{$ha['min']}, {$he['min']}, {$r['min']}, {$n['min']}, {$s['min']},"
."{$tx['min']}, {$mo['min']}]";
}else {
$liste["$nn_sup($rang)"] = "[{$l['min']}, {$t['min']}, {$c['min']},"
."{$ha['min']}, {$he['min']}, {$r['min']}, {$n['min']}, {$s['min']},"
."{$tx['min']}, {$mo['min']}]";
}
$nn_sup = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['nn_sup'] : '' ;
$rang = isset($this->infos_taxon[$nn_sup]) ? $this->infos_taxon[$nn_sup]['rang'] : 179 ;
}else {
break;
}
}
}
}
$log = "nn ascendant (pas forcement l'ascendant directement au dessus) :"
." valeurs descendants contenus dans baseflor \n"
."Pour le calcul des valeurs min et max de gauche, les valeurs de droite sont utilisées. \n";
foreach ($liste as $cle => $inferieurs){
$log .= "$cle : $inferieurs \n";
}
file_put_contents($fichier, $log);
}
 
}
/tags/v5.7-arrayanal/scripts/modules/baseflor/BaseflorVerif.php
New file
0,0 → 1,149
<?php
 
class BaseflorVerif extends VerificateurDonnees {
 
private $type_bio = array();
private $ss_type_bio = array();
private $signes_seuls = array();// basés sur valeurs trouvées (--> pas de légende !)
private $signes_nn_seuls = array();// basés sur valeurs trouvées (--> pas de légende !)
private $intervalles = array();
private $motifs = array();
 
//obligatoire
public function definirTraitementsColonnes() {
$this->initialiserParametresVerif() ;
if (( $this->colonne_num > 0 && $this->colonne_num < 15 )
|| $this->colonne_num == 16
|| ($this->colonne_num > 18 && $this->colonne_num < 23)
|| $this->colonne_num > 39) {
$this->verifierColonne();
} elseif ($this->colonne_num == 15) {
$this->verifierTypeBio();
} elseif ($this->colonne_num >= 23 && $this->colonne_num <= 32) {
$this->verifierIntervalles($this->colonne_valeur);
} elseif ($this->colonne_num >= 33 && $this->colonne_num < 41) {
$this->verifierValeursIndic();
}
}
private function initialiserParametresVerif() {
$this->type_bio = $this->getParametreTableau('Parametres.typesBio');
$this->ss_type_bio = $this->getParametreTableau('Parametres.sousTypesBio');
$this->signes_seuls = $this->getParametreTableau('Parametres.signesSeuls');
$this->signes_nn_seuls = $this->getParametreTableau('Parametres.signesNonSeuls');
$this->intervalles = $this->inverserTableau($this->getParametreTableau('Parametres.intervalles'));
$this->motifs = $this->inverserTableau($this->getParametreTableau('Parametres.motifs'));
}
//++---------------------------------traitements des colonnes baseflor------------------------------------++
private function verifierColonne(){
$motif = $this->motifs[$this->colonne_num];
if (preg_match($motif, $this->colonne_valeur) == 0 && $this->verifierSiVide() == false){
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur;
}
}
 
private function verifierSiVide(){
$vide = ($this->colonne_valeur == '') ? true : false;
return $vide;
}
 
private function verifierTypeBio(){
if (preg_match("/(.+)\((.+)\)$/", $this->colonne_valeur, $retour) == 1) {
$this->verifierTypeEtSsType($retour[1]);
$this->verifierTypeEtSsType($retour[2]);
} else {
$this->verifierTypeEtSsType($this->colonne_valeur);
}
}
 
private function verifierTypeEtSsType($chaine_a_verif){
if (preg_match("/^([a-zA-Zé]+)\-(.+)$|^([a-zA-Zé]+[^\-])$/", $chaine_a_verif, $retour) == 1) {
$type = (isset($retour[3])) ? $retour[3] : $retour[1];
$this->verifierType($type);
 
$sousType = $retour[2];
$this->verifierSousType($sousType);
}
}
 
private function verifierType($type) {
if (in_array($type, $this->type_bio) == false) {
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur;
}
}
 
private function verifierSousType($sousType) {
if ($sousType != ''){
$ss_type = explode('-', $sousType);
foreach ($ss_type as $sst) {
if (in_array($sst, $this->ss_type_bio) == false) {
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur;
}
}
}
}
 
private function verifierIntervalles($valeur){
if ($valeur != '') {
list($min, $max) = explode('-', $this->intervalles[$this->colonne_num]);
if ($valeur < $min || $valeur > $max){
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur;
}
}
}
 
private function verifierValeursIndic(){
if (preg_match("/^([^0-9])*([0-9]+)([^0-9])*$/", $this->colonne_valeur, $retour) == 1){
$this->verifierIntervalles($retour[2]);
if (isset($retour[3]) && in_array($retour[3], $this->signes_nn_seuls) == false){
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur;
}
if ($retour[1] != '-' && $retour[1] != ''){
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur;
}
} elseif (in_array( $this->colonne_valeur, $this->signes_seuls) == false && $this->verifierSiVide() == false) {
$this->erreurs_ligne[$this->colonne_num] = $this->colonne_valeur;
}
}
/*--------------------------------------------OUtils-------------------------------------------*/
private function getParametreTableau($cle) {
$tableau = array();
$parametre = Config::get($cle);
if (empty($parametre) === false) {
$tableauPartiel = explode(',', $parametre);
$tableauPartiel = array_map('trim', $tableauPartiel);
foreach ($tableauPartiel as $champ) {
if (strpos($champ, '=') !== false && strlen($champ) >= 3) {
list($cle, $val) = explode('=', $champ);
$tableau[trim($cle)] = trim($val);
} else {
$tableau[] = trim($champ);
}
}
}
return $tableau;
}
 
private function inverserTableau($tableau) {
$inverse = array();
foreach ($tableau as $cle => $valeurs) {
$valeurs = explode(';', $valeurs);
foreach ($valeurs as $valeur) {
$inverse[$valeur] = $cle;
}
}
return $inverse;
}
}
 
?>
/tags/v5.7-arrayanal/scripts/modules/baseflor/log
New file
Property changes:
Added: svn:ignore
+test
/tags/v5.7-arrayanal/scripts/modules/baseflor/Baseflor.php
New file
0,0 → 1,313
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php baseflor -a chargerTous
*/
class Baseflor extends EfloreScript {
 
private $table = null;
 
 
public function executer() {
try {
$this->initialiserProjet('baseflor');
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerMetadonnees':
$this->chargerMetadonnees();
break;
case 'chargerOntologies' :
$this->chargerOntologies();
break;
case 'verifierFichier' :
$this->verifierFichier();
break;
case 'chargerDonnees' :
$this->chargerDonnees();
break;
case 'genererChamps' :
$this->genererChamps();
break;
case 'chargerTous':
$this->chargerStructureSql();
$this->chargerMetadonnees();
$this->chargerOntologies();
$this->chargerDonnees();
$this->genererChamps();
$this->insererDonneesBaseflorRangSupEcolo();
$this->insererDonneesIndex();
break;
case 'insererDonneesRangSup' :
$this->insererDonneesBaseflorRangSupEcolo();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
case 'voirRangSup' :
$this->voirRangSup();
break;
case 'voirRangSupEcologie' :
$this->voirRangSupEcologie();
break;
case 'insererDonneesIndex' :
$this->insererDonneesIndex();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
 
//-- traitement de la table baseflorRangSupInsertion --//
 
private function getClasseBaseflorRangSupInsertion() {
$conteneur = new Conteneur();
require_once dirname(__FILE__)."/BaseflorRangSupInsertion.php";
$rangSupInsert = new BaseflorRangSupInsertion($conteneur, $this->getBdd());
return $rangSupInsert;
}
 
private function insererDonneesBaseflorRangSupEcolo(){
$rangSupInsert = $this->getClasseBaseflorRangSupInsertion();
$rangSupInsert->insererDonnees();
}
 
private function voirRangSup(){
$rangSupInsert = $this->getClasseBaseflorRangSupInsertion();
$rangSupInsert->testAscendantsDeBaseflor();
}
 
private function voirRangSupEcologie(){
$rangSupInsert = $this->getClasseBaseflorRangSupInsertion();
$rangSupInsert->testEcologieAscendantsDeBaseflor();
}
 
 
//-- traitement de la table baseflorIndex --//
 
private function getClasseBaseflorIndex() {
$conteneur = new Conteneur();
require_once dirname(__FILE__)."/BaseflorIndex.php";
$Index = new BaseflorIndex($conteneur, $this->getBdd());
return $Index;
}
 
private function insererDonneesIndex(){
$Index= $this->getClasseBaseflorIndex();
$Index->insererDonnees();
}
 
 
//-- traitement de la table generer champs --//
 
private function genererChamps(){
$this->initialiserGenerationChamps();
$this->ajouterChamps();
$this->analyserChampsExistant();
}
 
private function initialiserGenerationChamps() {
$this->table = Config::get('tables.donnees');
}
 
private function ajouterChamps() {
$this->preparerTablePrChpsBDNT();
$this->preparerTablePrChpsNumTaxon();
$this->preparerTablePrChpsNumNomen();
}
 
private function preparerTablePrChpsBDNT() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'BDNT' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD BDNT VARCHAR( 6 ) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci '.
'NOT NULL AFTER catminat_code ';
$this->getBdd()->requeter($requete);
}
}
 
private function preparerTablePrChpsNumTaxon() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'num_taxon' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD num_taxon INT( 10 ) NOT NULL '.
'AFTER catminat_code';
$this->getBdd()->requeter($requete);
}
}
 
private function preparerTablePrChpsNumNomen() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'num_nomen' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD num_nomen INT( 10 ) NOT NULL '.
'AFTER catminat_code';
$this->getBdd()->requeter($requete);
}
}
 
private function analyserChampsExistant() {
$resultats = $this->recupererTuplesNumsOriginels();
foreach ($resultats as $chps) {
$cle = $chps['cle'];
$nno = $chps['num_nomen_originel'];
$nto = $chps['num_taxon_originel'];
 
$valeurs = array();
$valeurs["BDNT"] = $this->genererChpsBDNT($nno, $nto);
$valeurs["num_taxon"] = $this->genererChpsNumTaxon($nto);
$valeurs["num_nomen"] = $this->genererChpsNumNomen($nno);
 
$this->remplirChamps($cle, $valeurs);
 
$this->afficherAvancement("Insertion des valeurs dans la base en cours");
}
echo "\n";
}
 
private function recupererTuplesNumsOriginels(){
$requete = "SELECT cle, num_taxon_originel, num_nomen_originel FROM {$this->table} ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function genererChpsBDNT($nno, $nto) {
$bdnt = '';
if (preg_match("/^([AB])[0-9]+$/", $nno, $retour) || preg_match("/^([AB])[0-9]+$/", $nto, $retour)){
if ($retour[1]=='A') {
$bdnt = "BDAFX";
} else {
$bdnt = "BDBFX";
}
} elseif (($nno == 'nc') && ($nto == 'nc')) {
$bdnt = "nc";
} else {
$bdnt = "BDTFX";
}
return $bdnt;
}
 
private function genererChpsNumTaxon($nto){
$num_taxon = '';
if (preg_match("/^[AB]([0-9]+)$/", $nto, $retour)) {
$num_taxon = intval($retour[1]);
} elseif($nto == 'nc') {
$num_taxon = 0;
} else {
$num_taxon = intval($nto);
}
return $num_taxon;
}
 
private function genererChpsNumNomen($nno) {
$num_nomen = '';
if (preg_match("/^[AB]([0-9]+)$/", $nno, $retour)) {
$num_nomen = intval($retour[1]);
} elseif ($nno == 'nc') {
$num_nomen = 0;
} else {
$num_nomen = intval($nno);
}
return $num_nomen;
}
 
private function remplirChamps($cle, $valeurs) {
foreach ($valeurs as $nomChamp => $valeurChamp) {
$valeurChamp = $this->getBdd()->proteger($valeurChamp);
$requete = "UPDATE {$this->table} SET $nomChamp = $valeurChamp WHERE cle = $cle ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple clé = $cle");
}
}
}
 
//+------------------------------------------------------------------------------------------------------+
// chargements, suppression, exécution
 
protected function chargerMetadonnees() {
$contenuSql = $this->recupererContenu(Config::get('chemins.metadonnees'));
$this->executerScriptSql($contenuSql);
}
 
private function chargerOntologies() {
$chemin = Config::get('chemins.ontologies');
$table = Config::get('tables.ontologies');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' "
;
$this->getBdd()->requeter($requete);
}
 
protected function chargerStructureSql() {
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSql'));
$this->executerScriptSql($contenuSql);
}
 
protected function executerScriptSql($sql) {
$requetes = Outils::extraireRequetes($sql);
foreach ($requetes as $requete) {
$this->getBdd()->requeter($requete);
}
}
 
private function chargerDonnees() {
$nb_err = $this->verifierFichier();
if ($nb_err > 0) {
$e = "Je ne peux pas charger les données car le fichier comporte des erreurs.".
"Voir le fichier baseflor_verif.txt\n";
throw new Exception($e);
}
 
$table = Config::get('tables.donnees');
$requete = "LOAD DATA INFILE '".Config::get('chemins.donnees')."' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\'";
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
// TODO : rajouter une boucle utilisant un parametre de config stockant toutes les versions pour supprimer les tables
$requete = "DROP TABLE IF EXISTS baseflor_meta, baseflor_ontologies, ".
" baseflor_v2012_03_19, ".
" baseflor_v2012_05_08, baseflor_rang_sup_ecologie_v2012_05_08, baseflor_index_v2012_05_08, ".
" baseflor_v2012_12_31, baseflor_rang_sup_ecologie_v2012_12_31, baseflor_index_v2012_12_31, ".
" baseflor_v2013_07_04, baseflor_rang_sup_ecologie_v2013_07_04, baseflor_index_v2013_07_04";
$this->getBdd()->requeter($requete);
}
 
//++------------------------------------verifierFichier------------------------------------------++//
 
private function getClasseBaseflorVerif() {
$conteneur = new Conteneur();
require_once dirname(__FILE__)."/BaseflorVerif.php";
$verif = new BaseflorVerif($conteneur,'baseflor');
return $verif;
}
 
private function verifierFichier() {
$verif = $this->getClasseBaseflorVerif();
$nb_erreurs = $verif->verifierFichier(Config::get('chemins.donnees'));
return $nb_erreurs;
}
 
}
?>
/tags/v5.7-arrayanal/scripts/modules/baseflor/BaseflorIndex.php
New file
0,0 → 1,83
<?php
/**
*
* @author Mathilde SALTHUN-LASSALLE <mathilde@tela-botanica.org>
*
*
*/
class BaseflorIndex {
private $conteneur;
private $efloreCommun;
private $message;
private $dossierBase;
private $valeurs_insertion = array();
private $Bdd;
public function __construct(Conteneur $conteneur, Bdd $Bdd) {
$this->conteneur = $conteneur;
$this->Bdd = $Bdd;
$this->efloreCommun = $conteneur->getEfloreCommun();
$this->message = $conteneur->getMessages();
$this->dossierBase = dirname(__FILE__).'/';
}
public function insererDonnees(){
$this->efloreCommun->chargerFichierSql('chemins.index_sql');
$this->recupererDonneesBaseflor();
$this->recupererDonneesRangSup();
$this->insererDonneesIndex();
}
private function recupererDonneesBaseflor() {
$table = Config::get('tables.donnees');
$requete = "SELECT cle, num_nomen, BDNT FROM $table WHERE num_nomen != 0 ".
" AND num_nomen != 0 ".
" AND !(ve_lumiere = '' and ve_mat_org_sol = '' and ve_temperature = '' and ve_continentalite = '' ".
" and ve_humidite_atmos = '' and ve_humidite_edaph = '' and ve_nutriments_sol = '' and ve_salinite = ''".
" and ve_texture_sol = '' and ve_reaction_sol = '')";
$resultat = $this->Bdd->recupererTous($requete);
$this->valeurs_insertion['baseflor'] = $resultat;
$this->valeurs_insertion['rangSup'] = $resultat;
}
private function recupererDonneesRangSup() {
$table = Config::get('tables.rang_sup');
$requete = "SELECT cle, num_nomen, bdnt FROM $table ;";
$resultat = $this->Bdd->recupererTous($requete);
$this->valeurs_insertion['rangSup']= $resultat;
 
}
 
private function insererDonneesIndex() {
$table = Config::get('tables.index');
$requete_truncate = 'TRUNCATE TABLE '.$table;
$this->Bdd->requeter($requete_truncate);
$i = 0;
foreach ($this->valeurs_insertion as $tab => $res){
if ($tab == 'baseflor') {
foreach ($res as $valeurs ) {
if ($valeurs['num_nomen'] != 0) {
$requete = "INSERT INTO $table VALUES({$i},{$valeurs['cle']},null,'".strtolower($valeurs['BDNT']).".nn:{$valeurs['num_nomen']}')";
$this->Bdd->requeter($requete);
$i++;
$this->message->afficherAvancement('Insertion des valeurs issues de baseflor en cours');
}
}
} else {
foreach ($res as $valeurs ) {
if ($valeurs['num_nomen'] != 0) {
$requete = "INSERT INTO $table VALUES({$i},null,{$valeurs['cle']},'{$valeurs['bdnt']}.nn:{$valeurs['num_nomen']}')";
$this->Bdd->requeter($requete);
$i++;
$this->message->afficherAvancement('Insertion des valeurs issues des rangs supérieurs en cours');
}
}
}
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/baseflor/baseflor.ini
New file
0,0 → 1,52
version="2014_01_06"
dossierTsv = "{ref:dossierDonneesEflore}baseflor/2014-01-06/"
dossierSql = "{ref:dossierTsv}"
dossierRangSup = "{ref:dossierDonneesEflore}baseflor/2014-01-06/rang_sup/"
dossierIndex = "{ref:dossierDonneesEflore}baseflor/2014-01-06/index/"
 
[tables]
donnees = "baseflor_v{ref:version}"
ontologies = "baseflor_ontologies"
metadonnees = "baseflor_meta"
rang_sup = "baseflor_rang_sup_ecologie_v{ref:version}"
taxons = "bdtfx_v2_00";
index = "baseflor_index_v{ref:version}";
 
 
 
[fichiers]
structureSql = "baseflor.sql"
metadonnees = "insertion_baseflor_meta.sql"
donnees = "baseflor_v{ref:version}.tsv"
donnees_verif = "baseflor_verif.txt"
ontologies = "baseflor_ontologies.tsv"
rang_sup_sql = "baseflor_rang_sup_ecologie.sql"
index_sql = "baseflor_index.sql"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
donnees = "{ref:dossierTsv}{ref:fichiers.donnees}"
donnees_verif = "{ref:dossierTsv}{ref:fichiers.donnees_verif}"
ontologies ="{ref:dossierTsv}{ref:fichiers.ontologies}"
metadonnees = "{ref:dossierSql}{ref:fichiers.metadonnees}"
rang_sup_sql = "{ref:dossierRangSup}{ref:fichiers.rang_sup_sql}"
index_sql = "{ref:dossierIndex}{ref:fichiers.index_sql}"
 
[services]
url_base="http://localhost/"
url_service_base="{ref:url_base}service:eflore:0.1/"
 
[Parametres]
typesBio = "A,a,B,b,C,c,Cfru,cfru,Csuf,csuf,Ccou,ccou,H,h,Heri,heri,Hsto,hsto,Hces,hces,Hros,hros,Hrub,hrub,Hbis,hbis,G,g,Gbul,gbul,Gtub,gtub,Grhi,grhi,T,t,Tver,tver,Test,test"
sousTypesBio = "aqua,lia,épi,hpar,par,suc,semp,cad,car"
signesSeuls = "?, x, x~, x=, xb, xB, -"
signesNonSeuls = "~, =, b, B"
intervalles = "1-9 = 23;24;25;26;28;29;31;32;33;34;35;37;38,
1-12 = 27;36,
0-9 = 30;39"
motifs = "/(^[0-9]*\/)|(inconnu)/ = 1,
/(^[AB]?[0-9]+$)|(^nc$)/ = 2;3,
/[^0-9]+/ = 4;5;6;7;8;9;10;11;12;13;16;19;20;21;22;40;41;42;43;44;45;46;47;48;49;50;51;52;53;54;55,
/^([1-9]|1[0-2])(\-([1-9]|1[0-2]))*$/ = 14"
champsEcologiques = "ve_lumiere,ve_temperature,ve_continentalite,ve_humidite_atmos,ve_humidite_edaph,ve_reaction_sol,ve_nutriments_sol,ve_salinite,ve_texture_sol,ve_mat_org_sol"
 
/tags/v5.7-arrayanal/scripts/modules/isfan/Isfan.php
New file
0,0 → 1,391
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php isfan -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2012, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Isfan extends EfloreScript {
 
private $table = null;
private $pasInsertion = 1000;
private $departInsertion = 0;
 
protected $parametres_autorises = array(
'-t' => array(false, false, 'Permet de tester le script sur un jeu réduit de données (indiquer le nombre de lignes).'));
 
public function executer() {
try {
$this->initialiserProjet('isfan');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerisfan();
$this->genererChpNumTax();
$this->genererChpNomSciHtml();
$this->genererChpFamille();
$this->genererChpNomComplet();
$this->genererChpHierarchie();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerIsfan' :
$this->chargerIsfan();
break;
case 'genererChpNumTax' :
$this->genererChpNumTax();
break;
case 'genererChpNomSciHtml' :
$this->genererChpNomSciHtml();
break;
case 'genererChpNomComplet' :
$this->initialiserGenerationChamps();
$this->genererChpNomComplet();
break;
case 'genererChpFamille' :
$this->genererChpFamille();
break;
case 'genererChpHierarchie' :
$this->genererChpHierarchie();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerIsfan() {
$chemin = Config::get('chemins.bdt');
$table = Config::get('tables.isfan');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
private function genererChpNumTax() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpNumTax();
$erreurs = array();
$this->departInsertion = 0;
$dernier_num_tax = 0;
$requete = 'SELECT num_nom '.
'FROM '.$this->table.' '.
'WHERE num_nom = num_nom_retenu AND num_nom_retenu != 0 '.
'ORDER by num_nom_retenu ASC ';
 
$resultat = $this->getBdd()->recupererTous($requete);
foreach ($resultat as $taxon) {
$dernier_num_tax++;
$requete_maj = 'UPDATE '.$this->table.' '.
'SET num_taxonomique = '.$dernier_num_tax.' '.
'WHERE num_nom_retenu = '.$taxon['num_nom'];
$this->getBdd()->requeter($requete_maj);
$this->pasInsertion++;
$this->afficherAvancement("Insertion des num tax, ".count($resultat)." num tax a traiter");
}
echo "\n";
$this->creerFichierLog('Erreurs lors de la génération des numéros taxonomiques', $erreurs, 'erreurs_num_tax');
}
private function preparerTablePrChpNumTax() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'num_taxonomique' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD num_taxonomique INT( 9 ) ';
$this->getBdd()->requeter($requete);
}
}
 
private function genererChpNomSciHtml() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpNomSciHtml();
$generateur = new GenerateurNomSciHtml();
$nbreTotal = $this->recupererNbTotalTuples();
$erreurs = array();
$this->departInsertion = 0;
while ($this->departInsertion < $nbreTotal) {
$resultat = $this->recupererTuplesPrChpNomSciHtml();
 
try {
$nomsSciEnHtml = $generateur->generer($resultat);
} catch (Exception $e) {
$erreurs[] = $e->getMessage();
}
 
$this->remplirChpNomSciHtm($nomsSciEnHtml);
$this->departInsertion += $this->pasInsertion;
$this->afficherAvancement("Insertion des noms scientifique au format HTML dans la base par paquet de {$this->pasInsertion} en cours");
if ($this->stopperLaBoucle($this->getParametre('t'))) break;
}
echo "\n";
 
$this->creerFichierLog('Erreurs lors de la génération HTML des noms scientifiques', $erreurs, 'erreurs_noms_sci_html');
}
 
private function initialiserGenerationChamps() {
$this->table = Config::get('tables.isfan');
}
 
private function preparerTablePrChpNomSciHtml() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD nom_sci_html VARCHAR( 500 ) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function recupererNbTotalTuples(){
$requete = "SELECT count(*) AS nb FROM {$this->table} ";
$resultat = $this->getBdd()->recuperer($requete);
return $resultat['nb'];
}
 
private function recupererTuplesPrChpNomSciHtml() {
$requete = 'SELECT num_nom, rang, genre, '.
' epithete_sp, type_epithete, epithete_infra_sp '.
"FROM {$this->table} ".
"LIMIT {$this->departInsertion},{$this->pasInsertion} ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function remplirChpNomSciHtm($nomsSciHtm) {
foreach ($nomsSciHtm as $id => $html) {
$html = $this->getBdd()->proteger($html);
$requete = "UPDATE {$this->table} SET nom_sci_html = $html WHERE num_nom = $id ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $id");
}
}
}
 
private function genererChpNomComplet() {
$this->preparerTablePrChpNomComplet();
$this->remplirChpNomComplet();
}
 
private function preparerTablePrChpNomComplet() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_complet' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD nom_complet VARCHAR( 500 ) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function remplirChpNomComplet() {
echo "Attribution du champ nom complet au taxons : ";
$requete = "UPDATE {$this->table} SET nom_complet = CONCAT(nom_sci,' ',auteur)";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
echo "KO\n";
throw new Exception("Erreur de génération du champ nom complet");
} else {
echo "OK\n";
}
}
 
private function genererChpFamille() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpFamille();
$resultats = $this->recupererTuplesPrChpFamille();
$noms = array();
$introuvables = array();
$introuvablesSyno = array();
foreach ($resultats as $id => $nom) {
$nn = $nom['num_nom'];
$nnr = $nom['num_nom_retenu'];
$nts = $nom['num_tax_sup'];
$rg = $nom['rang'];
if ($nnr != '') {
if ($rg == '180') {
$noms[$nn] = $nom['nom_sci'];
} else {
if ($nn == $nnr) {// nom retenu
if (isset($noms[$nts])) {
$noms[$nn] = $noms[$nts];
} else {
$introuvables[] = $nn;
}
} else {// nom synonyme
if (isset($noms[$nnr])) {
$noms[$nn] = $noms[$nnr];
} else {
$introuvablesSyno[] = $nom;
}
}
}
}
unset($resultats[$id]);
$this->afficherAvancement("Attribution de leur famille aux noms en cours");
if ($this->stopperLaBoucle($this->getParametre('t'))) break;
}
echo "\n";
 
foreach ($introuvablesSyno as $id => $nom) {
$nn = $nom['num_nom'];
$nnr = $nom['num_nom_retenu'];
if (isset($noms[$nnr])) {
$noms[$nn] = $noms[$nnr];
} else {
$introuvables[] = $nn;
}
unset($introuvablesSyno[$id]);
$this->afficherAvancement("Attribution de leur famille aux synonymes en cours");
}
echo "\n";
 
$msg = 'Plusieurs familles sont introuvables';
$this->creerFichierLog($msg, $introuvables, 'famille_introuvable');
 
$this->remplirChpFamille($noms);
}
 
private function preparerTablePrChpFamille() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'famille' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD famille VARCHAR(255) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function recupererTuplesPrChpFamille() {
$requete = 'SELECT num_nom, num_nom_retenu, num_tax_sup, rang, nom_sci '.
"FROM {$this->table} ".
"WHERE rang >= 180 ".
"ORDER BY rang ASC, num_tax_sup ASC, num_nom_retenu DESC ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function remplirChpFamille($noms) {
foreach ($noms as $id => $famille) {
$famille = $this->getBdd()->proteger($famille);
$requete = "UPDATE {$this->table} SET famille = $famille WHERE num_nom = $id ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $id");
}
$this->afficherAvancement("Insertion des noms de famille dans la base en cours");
}
echo "\n";
}
private function genererChpHierarchie() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpHierarchie();
$table = Config::get('tables.isfan');
$requete = "UPDATE $table SET hierarchie = NULL ";
$mise_a_jour = $this->getBdd()->requeter($requete);
$requete_hierarchie = "SELECT num_nom, num_nom_retenu, num_tax_sup FROM ".$table." ORDER BY rang DESC";
$resultat = $this->getBdd()->recupererTous($requete_hierarchie);
$num_nom_a_num_sup = array();
foreach($resultat as &$taxon) {
$num_nom_a_num_sup[$taxon['num_nom']] = $taxon['num_tax_sup'];
}
$chemin_taxo = "";
foreach($resultat as &$taxon) {
$chemin_taxo = $this->traiterHierarchieNumTaxSup($taxon['num_nom_retenu'], $num_nom_a_num_sup).'-';
$requete = "UPDATE $table SET hierarchie = ".$this->getBdd()->proteger($chemin_taxo)." WHERE num_nom = ".$taxon['num_nom']." ";
$mise_a_jour = $this->getBdd()->requeter($requete);
$this->afficherAvancement("Insertion de la hierarchie taxonomique en cours");
}
echo "\n";
}
private function traiterHierarchieNumTaxSup($num_nom_retenu, &$num_nom_a_num_sup) {
$chaine_hierarchie = "";
if(isset($num_nom_a_num_sup[$num_nom_retenu])) {
$num_tax_sup = $num_nom_a_num_sup[$num_nom_retenu];
$chaine_hierarchie = '-'.$num_tax_sup;
if($num_tax_sup != 0 && $num_tax_sup != '') {
$chaine_hierarchie = $this->traiterHierarchieNumTaxSup($num_tax_sup, $num_nom_a_num_sup).$chaine_hierarchie;
}
}
return $chaine_hierarchie;
}
private function preparerTablePrChpHierarchie() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'hierarchie' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD hierarchie VARCHAR(1000) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
private function genererDonneesTestMultiVersion() {
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSqlTest'));
$this->executerScripSql($contenuSql);
 
$table = Config::get('tables.isfan');
$tableTest = Config::get('tables.isfanTest');
$requete = "INSERT INTO $tableTest SELECT * FROM $table";
$this->getBdd()->requeter($requete);
}
 
private function supprimerDonneesTestMultiVersion() {
$tableMeta = Config::get('tables.isfanMeta');
$requete = "DELETE FROM $tableMeta WHERE guid = 'urn:lsid:tela-botanica.org:isfan:1.00'";
$this->getBdd()->requeter($requete);
 
$tableTest = Config::get('tables.isfanTest');
$requete = "DROP TABLE IF EXISTS $tableTest";
$this->getBdd()->requeter($requete);
}
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS isfan_meta, isfan_v0_01, isfan_v1_00";
$this->getBdd()->requeter($requete);
}
 
private function creerFichierLog($message, $lignes, $nomFichier) {
$lignesNbre = count($lignes);
if ($lignesNbre != 0) {
echo "$message. Voir le log de $lignesNbre lignes :\n";
 
$logContenu = implode(", \n", $lignes);
$logFichier = realpath(dirname(__FILE__))."/log/$nomFichier.log";
echo $logFichier."\n";
file_put_contents($logFichier, $logContenu);
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/isfan/isfan.ini
New file
0,0 → 1,18
code="isfan"
version="2013"
dossierTsv = "{ref:dossierDonneesEflore}{ref:code}/1.00/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
isfanMeta = "isfan_meta"
isfan = "isfan_v{ref:version}"
isfanTest = "isfan_v2013"
 
 
[fichiers]
structureSql = "{ref:code}_v{ref:version}.sql"
bdt = "{ref:code}_v{ref:version}_ref.txt"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
bdt = "{ref:dossierTsv}{ref:fichiers.bdt}"
/tags/v5.7-arrayanal/scripts/modules/bdtxa/bdtxa.ini
New file
0,0 → 1,18
code="bdtxa"
version="1_00"
dossierTsv = "{ref:dossierDonneesEflore}{ref:code}/1.00/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
bdtxaMeta = "bdtxa_meta"
bdtxa = "bdtxa_v{ref:version}"
bdtxaTest = "bdtxa_v1_00"
 
 
[fichiers]
structureSql = "{ref:code}_v{ref:version}.sql"
bdt = "{ref:code}_v{ref:version}_ref.txt"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
bdt = "{ref:dossierTsv}{ref:fichiers.bdt}"
/tags/v5.7-arrayanal/scripts/modules/bdtxa/Bdtxa.php
New file
0,0 → 1,353
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php bdtxa -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2012, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Bdtxa extends EfloreScript {
 
private $table = null;
private $pasInsertion = 1000;
private $departInsertion = 0;
 
protected $parametres_autorises = array(
'-t' => array(false, false, 'Permet de tester le script sur un jeu réduit de données (indiquer le nombre de lignes).'));
 
public function executer() {
try {
$this->initialiserProjet('bdtxa');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerBdtxa();
$this->genererChpNomSciHtml();
$this->genererChpFamille();
$this->genererChpNomComplet();
$this->genererChpHierarchie();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerBdtxa' :
$this->chargerBdtxa();
break;
case 'genererChpNomSciHtml' :
$this->genererChpNomSciHtml();
break;
case 'genererChpNomComplet' :
$this->initialiserGenerationChamps();
$this->genererChpNomComplet();
break;
case 'genererChpFamille' :
$this->genererChpFamille();
break;
case 'genererChpHierarchie' :
$this->genererChpHierarchie();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerBdtxa() {
$chemin = Config::get('chemins.bdt');
$table = Config::get('tables.bdtxa');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function genererChpNomSciHtml() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpNomSciHtml();
$generateur = new GenerateurNomSciHtml();
$nbreTotal = $this->recupererNbTotalTuples();
$erreurs = array();
$this->departInsertion = 0;
while ($this->departInsertion < $nbreTotal) {
$resultat = $this->recupererTuplesPrChpNomSciHtml();
 
try {
$nomsSciEnHtml = $generateur->generer($resultat);
} catch (Exception $e) {
$erreurs[] = $e->getMessage();
}
 
$this->remplirChpNomSciHtm($nomsSciEnHtml);
$this->departInsertion += $this->pasInsertion;
$this->afficherAvancement("Insertion des noms scientifique au format HTML dans la base par paquet de {$this->pasInsertion} en cours");
if ($this->stopperLaBoucle($this->getParametre('t'))) break;
}
echo "\n";
 
$this->creerFichierLog('Erreurs lors de la génération HTML des noms scientifiques', $erreurs, 'erreurs_noms_sci_html');
}
 
private function initialiserGenerationChamps() {
$this->table = Config::get('tables.bdtxa');
echo $this->table;
}
 
private function preparerTablePrChpNomSciHtml() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD nom_sci_html VARCHAR( 500 ) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function recupererNbTotalTuples(){
$requete = "SELECT count(*) AS nb FROM {$this->table} ";
$resultat = $this->getBdd()->recuperer($requete);
return $resultat['nb'];
}
 
private function recupererTuplesPrChpNomSciHtml() {
$requete = 'SELECT num_nom, rang, nom_supra_generique, genre, epithete_infra_generique, '.
' epithete_sp, type_epithete, epithete_infra_sp,cultivar_groupe, '.
' nom_commercial, cultivar '.
"FROM {$this->table} ".
"LIMIT {$this->departInsertion},{$this->pasInsertion} ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function remplirChpNomSciHtm($nomsSciHtm) {
foreach ($nomsSciHtm as $id => $html) {
$html = $this->getBdd()->proteger($html);
$requete = "UPDATE {$this->table} SET nom_sci_html = $html WHERE num_nom = $id ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $id");
}
}
}
 
private function genererChpNomComplet() {
$this->preparerTablePrChpNomComplet();
$this->remplirChpNomComplet();
}
 
private function preparerTablePrChpNomComplet() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_complet' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD nom_complet VARCHAR( 500 ) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function remplirChpNomComplet() {
echo "Attribution du champ nom complet au taxons : ";
$requete = "UPDATE {$this->table} SET nom_complet = CONCAT(nom_sci,' ',auteur)";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
echo "KO\n";
throw new Exception("Erreur de génération du champ nom complet");
} else {
echo "OK\n";
}
}
 
private function genererChpFamille() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpFamille();
$resultats = $this->recupererTuplesPrChpFamille();
$noms = array();
$introuvables = array();
$introuvablesSyno = array();
foreach ($resultats as $id => $nom) {
$nn = $nom['num_nom'];
$nnr = $nom['num_nom_retenu'];
$nts = $nom['num_tax_sup'];
$rg = $nom['rang'];
if ($nnr != '') {
if ($rg == '180') {
$noms[$nn] = $nom['nom_sci'];
} else {
if ($nn == $nnr) {// nom retenu
if (isset($noms[$nts])) {
$noms[$nn] = $noms[$nts];
} else {
$introuvables[] = $nn;
}
} else {// nom synonyme
if (isset($noms[$nnr])) {
$noms[$nn] = $noms[$nnr];
} else {
$introuvablesSyno[] = $nom;
}
}
}
}
unset($resultats[$id]);
$this->afficherAvancement("Attribution de leur famille aux noms en cours");
if ($this->stopperLaBoucle($this->getParametre('t'))) break;
}
echo "\n";
 
foreach ($introuvablesSyno as $id => $nom) {
$nn = $nom['num_nom'];
$nnr = $nom['num_nom_retenu'];
if (isset($noms[$nnr])) {
$noms[$nn] = $noms[$nnr];
} else {
$introuvables[] = $nn;
}
unset($introuvablesSyno[$id]);
$this->afficherAvancement("Attribution de leur famille aux synonymes en cours");
}
echo "\n";
 
$msg = 'Plusieurs familles sont introuvables';
$this->creerFichierLog($msg, $introuvables, 'famille_introuvable');
 
$this->remplirChpFamille($noms);
}
 
private function preparerTablePrChpFamille() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'famille' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD famille VARCHAR(255) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function recupererTuplesPrChpFamille() {
$requete = 'SELECT num_nom, num_nom_retenu, num_tax_sup, rang, nom_sci '.
"FROM {$this->table} ".
"WHERE rang >= 180 ".
"ORDER BY rang ASC, num_tax_sup ASC, num_nom_retenu DESC ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function remplirChpFamille($noms) {
foreach ($noms as $id => $famille) {
$famille = $this->getBdd()->proteger($famille);
$requete = "UPDATE {$this->table} SET famille = $famille WHERE num_nom = $id ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $id");
}
$this->afficherAvancement("Insertion des noms de famille dans la base en cours");
}
echo "\n";
}
private function genererChpHierarchie() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpHierarchie();
$table = Config::get('tables.bdtxa');
$requete = "UPDATE $table SET hierarchie = NULL ";
$mise_a_jour = $this->getBdd()->requeter($requete);
$requete_hierarchie = "SELECT num_nom, num_nom_retenu, num_tax_sup FROM ".$table." ORDER BY rang DESC";
$resultat = $this->getBdd()->recupererTous($requete_hierarchie);
$num_nom_a_num_sup = array();
foreach($resultat as &$taxon) {
$num_nom_a_num_sup[$taxon['num_nom']] = $taxon['num_tax_sup'];
}
$chemin_taxo = "";
foreach($resultat as &$taxon) {
$chemin_taxo = $this->traiterHierarchieNumTaxSup($taxon['num_nom_retenu'], $num_nom_a_num_sup).'-';
$requete = "UPDATE $table SET hierarchie = ".$this->getBdd()->proteger($chemin_taxo)." WHERE num_nom = ".$taxon['num_nom']." ";
$mise_a_jour = $this->getBdd()->requeter($requete);
$this->afficherAvancement("Insertion de la hierarchie taxonomique en cours");
}
echo "\n";
}
private function traiterHierarchieNumTaxSup($num_nom_retenu, &$num_nom_a_num_sup) {
$chaine_hierarchie = "";
if(isset($num_nom_a_num_sup[$num_nom_retenu])) {
$num_tax_sup = $num_nom_a_num_sup[$num_nom_retenu];
$chaine_hierarchie = '-'.$num_tax_sup;
if($num_tax_sup != 0 && $num_tax_sup != '') {
$chaine_hierarchie = $this->traiterHierarchieNumTaxSup($num_tax_sup, $num_nom_a_num_sup).$chaine_hierarchie;
}
}
return $chaine_hierarchie;
}
private function preparerTablePrChpHierarchie() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'hierarchie' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD hierarchie VARCHAR(1000) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
private function genererDonneesTestMultiVersion() {
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSqlTest'));
$this->executerScripSql($contenuSql);
 
$table = Config::get('tables.bdtxa');
$tableTest = Config::get('tables.bdtxaTest');
$requete = "INSERT INTO $tableTest SELECT * FROM $table";
$this->getBdd()->requeter($requete);
}
 
private function supprimerDonneesTestMultiVersion() {
$tableMeta = Config::get('tables.bdtxaMeta');
$requete = "DELETE FROM $tableMeta WHERE guid = 'urn:lsid:tela-botanica.org:bdtxa:1.00'";
$this->getBdd()->requeter($requete);
 
$tableTest = Config::get('tables.bdtxaTest');
$requete = "DROP TABLE IF EXISTS $tableTest";
$this->getBdd()->requeter($requete);
}
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS bdtxa_meta, bdtxa_v0_01, bdtxa_v1_00";
$this->getBdd()->requeter($requete);
}
 
private function creerFichierLog($message, $lignes, $nomFichier) {
$lignesNbre = count($lignes);
if ($lignesNbre != 0) {
echo "$message. Voir le log de $lignesNbre lignes :\n";
 
$logContenu = implode(", \n", $lignes);
$logFichier = realpath(dirname(__FILE__))."/log/$nomFichier.log";
echo $logFichier."\n";
file_put_contents($logFichier, $logContenu);
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/sitemap/sitemap.ini
New file
0,0 → 1,2
; Encodage : UTF-8
; ici mettre les variables du module
/tags/v5.7-arrayanal/scripts/modules/sitemap/Sitemap.php
New file
0,0 → 1,160
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Sitemap
*
* Description : classe permettant de réaliser un fichier Sitemap pour eFlore
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Tela-Botanica 1999-2008
* @link http://www.tela-botanica.org/wikini/eflore
* @licence GPL v3 & CeCILL v2
* @version $Id: Sitemap.class.php 1873 2009-03-31 10:07:24Z Jean-Pascal MILCENT $
*/
// +-------------------------------------------------------------------------------------------------------------------+
 
/**
* Classe crééant un Sitemap
*/
class Robot extends ScriptCommande {
private $lastmod = '2008-04-28';
private $changefreq = 'monthly';
public function executer() {
$cmd = $this->getParam('a');
switch ($cmd) {
case 'creer' :
$this->creerSiteMap();
break;
default :
trigger_error('Erreur : la commande "'.$cmd.'" n\'existe pas!'."\n", E_USER_ERROR);
}
}
private function creerSiteMap() {
// +-----------------------------------------------------------------------------------------------------------+
// Initialisation des paramêtres variables
$url_site = 'http://www.tela-botanica.org/';
$url_eflore = $url_site.'eflore/%s/nt/%s/%s';
$projets = array( array('id' => 25, 'code' => 'BDNFF', 'url' => $url_eflore, 'taxon_max' => 50000, 'onglets' => '*'),
array('id' => 29, 'code' => 'BDNFM', 'url' => $url_eflore, 'taxon_max' => 50000, 'onglets' => 'synthese,synonymie,vernaculaire,chorologie,biblio,information,illustration,wiki'),
array('id' => 38, 'code' => 'BDNBE', 'url' => $url_eflore, 'taxon_max' => 50000, 'onglets' => 'synthese,synonymie,chorologie,biblio,information,illustration,wiki'),
array('id' => 45, 'code' => 'BDAFN', 'url' => $url_eflore, 'taxon_max' => 500000, 'onglets' => 'synthese,synonymie,chorologie,biblio,information,illustration,wiki')
);
$onglets = array( 'synthese' => '0.9',
'synonymie' => '0.6',
'vernaculaire' => '0.8',
'chorologie' => '0.7',
'biblio' => '0.8',
'information' => '0.2',
'illustration' => '0.9',
'wiki' => '0.3',
'cel' => '0.5');
$xmlstr_sitemap = '<?xml version="1.0" encoding="UTF-8"?>'."\n".
'<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '.
'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 '.
'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" '.
'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n".
'</urlset>'."\n";
$xmlstr_sitemapindex = '<?xml version="1.0" encoding="UTF-8"?>'."\n".
'<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '.
'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 '.
'http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" '.
'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n".
'</sitemapindex>'."\n";
// +-----------------------------------------------------------------------------------------------------------+
// Initialisation des variables
$UrlSet = null;
$SiteMapIndex = null;
$cpt_url = 1;
$cpt_fichier = 1;
$Taxon = new EfloreTaxon(true);
// +-----------------------------------------------------------------------------------------------------------+
// Lancement du traitement
foreach ($projets as $projet) {
// Gestion des onglets affichables pour le projet courrant
if ($projet['onglets'] != '*') {
$projet['onglets'] = array_flip(explode(',', $projet['onglets']));
}
 
// +-------------------------------------------------------------------------------------------------------+
echo "Création des URLs des taxons pour le projet {$projet['code']} : ";
$i = 1;
$taxons = $Taxon->consulterTaxon($projet['id']);
foreach ($taxons as $taxon) {
// Seul les taxons du projet sont indexés, on exclue les taxons virtuels
if ($taxon['et']['id']['taxon'] < $projet['taxon_max']) {
foreach ($onglets as $onglet => $priorite) {
// Vérification que l'onglet est autorisé pour ce projet
if ($projet['onglets'] == '*' || isset($projet['onglets'][$onglet])) {
// Affichage en console et en cas de test...
echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++;
// Création du fichier XML si nécessaire
if (is_null($UrlSet)) {
$UrlSet = new SimpleXMLElement($xmlstr_sitemap);
}
// Ajout de l'url
$Url = $UrlSet->addChild('url');
$Url->addChild('loc', sprintf($projet['url'], $projet['code'], $taxon['et']['id']['taxon'], $onglet));
$Url->addChild('lastmod', $this->lastmod);
$Url->addChild('changefreq', $this->changefreq);
$Url->addChild('priority', $priorite);
// Vérification écriture du fichier ou pas
if ($cpt_url == 1) {
$estimation = strlen($UrlSet->asXml());
}
if (49999 == $cpt_url++ || ($estimation * $cpt_url) > 20000000 || $i == (int)$this->getParam('t')) {
$contenu = $UrlSet->asXml();
$cpt_url = 1;
$UrlSet = null;
 
// Création du fichier Sitemap compressé
$fichier_nom = 'sitemap'.$cpt_fichier++.'.xml';
$compression = false;
if (!is_numeric($this->getParam('t'))) {
$compression = true;
$fichier_nom .= '.gz';
}
$fichier = $this->getIni('log_chemin').$fichier_nom;
$this->creerFichier($fichier, $contenu, $compression);
// Création du XML d'index des Sitemap si nécessaire
if (is_null($SiteMapIndex)) {
$SiteMapIndex = new SimpleXMLElement($xmlstr_sitemapindex);
}
 
// Ajout du fichier Sitemap à l'index
$SiteMap = $SiteMapIndex->addChild('sitemap');
$SiteMap->addChild('loc', $url_site.$fichier_nom);
$SiteMap->addChild('lastmod', date('c', time()));
}
 
if ($i == (int)$this->getParam('t')) {break;}
}
}
}
// En cas de test...
if ($i == (int)$this->getParam('t')) {break;}
}
echo "\n";
// Création du fichier d'index des Sitemap
if (is_object($SiteMapIndex)) {
$index_contenu = $SiteMapIndex->asXml();
$index_fichier_nom = 'sitemap_index.xml';
$index_fichier = $this->getIni('log_chemin').$index_fichier_nom;
$this->creerFichier($index_fichier, $index_contenu);
}
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/sophy/Insertion.php
New file
0,0 → 1,906
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Traitement des fichiers de la banque de données SOPHY pour insertion
*
* Description : classe permettant d'insérer les tableaux phytosociologiques de la banque de données SOPHY
* Utilisation : php script.php insertion -a test
*
* @category PHP 5.3
* @package phytosocio
//Auteur original :
* @author Delphine CAUQUIL <delphine@tela-botanica.org>
* @copyright Copyright (c) 2009, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL-v3
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2
* @version $Id$
*/
// +-------------------------------------------------------------------------------------------------------------------+
class Insertion extends EfloreScript {
protected $tableauTaxon;
protected $dao;
protected $observations;
// Paramêtres autorisées lors de l'appel au script en ligne de commande
protected $parametres_autorises = array(
'-n' => array(true, true, 'Nom du fichier ou du dossier à traiter'));
 
protected $param_bd_pour_stat = array(
'sophy_publication' => array(),
'sophy_tableau' => array('stab_id_publi' => 'nombrePubli'),
'sophy_releve' => array(
'sr_id_publi' => 'nombrePubli',
'sr_id_publi, sr_id_tableau' => 'nombreTableau',
'sr_id_station' => 'nombreStation'),
'sophy_observation' => array(
'so_id_publi' => 'nombrePubli',
'so_id_publi, so_id_tableau' => 'nombreTableau',
'so_id_publi, so_id_tableau, so_id_releve' => 'nombreReleve',
'so_id_taxon' => 'nombreTaxon'),
'sophy_station' => array(),
'sophy_taxon' => array()
);
 
// Composition classique d'un titre de tableau de stations ou phytosociologiques
protected $format_titre = array(
'numPubli' => array(0, 4),
'numTableau' => array(4, 3),
'nombreStations' => array(7, 3),
'titrePubli' => array(11, -1),
'typeTableau' => array(79, 1)
);
 
// Composition classique d'une station
protected $format_station = array(
'numSource' => array(0, 4),
'posteMeteo' => array(4, 5),
'nomStation' => array(10, 38),
'latitude' => array(49, 7),
'codePays' => array(56, 2),
'longitude' => array(59, 6),
'codeDept' => array(66, 2),
'altitude' => array(69, 4),
'codeCommune' => array(74, 3),
'precisionGeographique' => array(78, 1),
'systemeProjection' => array(79, 1),
'latitude2' => array(80, 8),
'longitude2' => array(88, 8)
);
 
// Composition classique d'une ligne de tableau phytosociologique
protected $format_tableau = array(
0 => array(
'numLigne' => array(0, 3),
'idTaxon' => array(3, 5),
'strate' => array(8, 1),
'codeFlore' => array(9, 1),
'abondance_rem' => array(10, 70)),
2 => array(
'numSource' => array(0, 5),
'posteMeteo' => array(5, 3),
'numLigne' => array(8, 2),
'codeFournier1' => array(10, 5),
'abondance1' => array(15, 1),
'strate1' => array(16, 1),
'codeFournier2' => array(17, 5),
'abondance2' => array(22, 1),
'strate2' => array(23, 1),
'codeFournier3' => array(24, 5),
'abondance3' => array(29, 1),
'strate3' => array(30, 1),
'codeFournier4' => array(31, 5),
'abondance4' => array(36, 1),
'strate4' => array(37, 1),
'codeFournier5' => array(38, 5),
'abondance5' => array(43, 1),
'strate5' => array(44, 1),
'codeFournier6' => array(45, 5),
'abondance6' => array(50, 1),
'strate6' => array(51, 1),
'codeFournier7' => array(52, 5),
'abondance7' => array(57, 1),
'strate7' => array(58, 1),
'codeFournier8' => array(59, 5),
'abondance8' => array(64, 1),
'strate8' => array(65, 1),
'codeFournier9' => array(66, 5),
'abondance9' => array(71, 1),
'strate9' => array(72, 1),
'codeFournier10' => array(73, 5),
'abondance10' => array(78, 1),
'strate10' => array(79, 1)),
6 => array(
'numSource' => array(0, 4),
'posteMeteo' => array(4, 4),
'numLigne' => array(8, 2),
'strate1' => array(10, 1),
'codeFournier1' => array(11, 4),
'abondance1' => array(16, 1),
'strate2' => array(17, 1),
'codeFournier2' => array(18, 4),
'abondance2' => array(23, 1),
'strate3' => array(24, 1),
'codeFournier3' => array(25, 4),
'abondance3' => array(30, 1),
'strate4' => array(31, 1),
'codeFournier4' => array(32, 4),
'abondance4' => array(37, 1),
'strate5' => array(38, 1),
'codeFournier5' => array(39, 4),
'abondance5' => array(44, 1),
'strate6' => array(45, 1),
'codeFournier6' => array(46, 4),
'abondance6' => array(51, 1),
'strate7' => array(52, 1),
'codeFournier7' => array(53, 4),
'abondance7' => array(58, 1),
'strate8' => array(59, 1),
'codeFournier8' => array(60, 4),
'abondance8' => array(65, 1),
'strate9' => array(66, 1),
'codeFournier9' => array(67, 4),
'abondance9' => array(72, 1),
'strate10' => array(73, 1),
'codeFournier10' => array(74, 4),
'abondance10' => array(79, 1)),
7 => array(
'numReleve' => array(2, 3),
'posteMeteo' => array(7, 3),
'codeFournier1' => array(10, 4),
'abondance1' => array(14, 1),
'strate1' => array(15, 1),
'codeFournier2' => array(16, 4),
'abondance2' => array(20, 1),
'strate2' => array(21, 1),
'codeFournier3' => array(22, 4),
'abondance3' => array(26, 1),
'strate3' => array(27, 1),
'codeFournier4' => array(28, 4),
'abondance4' => array(32, 1),
'strate4' => array(33, 1),
'codeFournier5' => array(34, 4),
'abondance5' => array(38, 1),
'strate5' => array(39, 1),
'codeFournier6' => array(40, 4),
'abondance6' => array(44, 1),
'strate6' => array(45, 1),
'codeFournier7' => array(46, 4),
'abondance7' => array(50, 1),
'strate7' => array(51, 1),
'codeFournier8' => array(52, 4),
'abondance8' => array(56, 1),
'strate8' => array(57, 1),
'codeFournier9' => array(58, 4),
'abondance9' => array(62, 1),
'strate9' => array(63, 1),
'codeFournier10' => array(64, 4),
'abondance10' => array(68, 1),
'strate10' => array(69, 1),
'numLigne' => array(71, 2),
'codeCarte' => array(73, 7))
);
 
// +-------------------------------------------------------------------------------------------------------------------+
public function executer() {
include_once dirname(__FILE__).'/bibliotheque/Dao.php';
Config::charger(dirname(__FILE__).'/sophy.ini');
$this->dao = new Dao();
// Récupération de paramétres
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'testDossier' :
$this->executerTestDossier();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'supprimerTous' :
$this->supprimerTous();
case 'biblio' :
$this->executerBiblio();
break;
case 'station' :
include_once dirname(__FILE__).'/bibliotheque/gPoint.php';
$this->executerStation();
break;
case 'stationCodeInsee' :
$this->executerStationCodeInsee();
break;
case 'tableau' :
include_once dirname(__FILE__).'/bibliotheque/TaxonDao.php';
$this->tableauTaxon = new TaxonDao();
$this->executerTableau();
break;
case 'stats' :
$this->executerStats();
break;
case 'tapir' :
$info = $this->dao->creerTapir();
$this->traiterErreur($info);
break;
default :
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
}
}
protected function chargerStructureSql() {
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSql'));
$this->executerScripSql($contenuSql);
}
protected function executerScripSql($sql) {
$requetes = Outils::extraireRequetes($sql);
foreach ($requetes as $requete) {
$this->getBdd()->requeter($requete);
}
}
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS sophy_abondance, `sophy_bdnff`, `sophy_bryophyte`, `sophy_ciff`, ".
"`sophy_ciff_fournier`, `sophy_codefr94`, `sophy_flora_europea`, `sophy_fournier`, `sophy_fournier_bdnff`,".
" `sophy_observation`, `sophy_precision_geo`, `sophy_publication`, `sophy_releve`, `sophy_station`, `sophy_strate`,".
" `sophy_syntri`, `sophy_syntri_fournier`, `sophy_tableau`, `sophy_taxon`";
$this->getBdd()->requeter($requete);
}
// +-------------------------------------------------------------------------------------------------------------------+
// vérifie qu'il n'y est pas de fichier en double dans le dossier
// à faire avant d'insérer un nouveau dossier
private function executerTestDossier() {
$nomDossier = Config::get('dossierDonneesSophy').$this->getParametre('n');
if (file_exists($nomDossier) === true) {
if (is_dir($nomDossier)) {
if ($dossierOuvert = opendir($nomDossier) ) {
while ( ($nomFichier = readdir($dossierOuvert)) !== false) {
if ( !is_dir($nomFichier) ) {
if (preg_match('/^[ST]{1,2}(\d{2}1)(\d{2}0)\.*/', $nomFichier, $match)) {
// fichier normal type 001 à 010
} elseif (preg_match('/^([ST]{1,2})(\d{3})(\d{3})\.*/', $nomFichier, $match)) {
if (($match[1]=='ST' || $match[1]=='T') && ($match[3] - $match[2] == 1)) {
// fichier normal type 1000 à 1010
} else {
$this->traiterErreur("Le fichier $nomFichier risque d'être en double.");
}
}
}
}
closedir($dossierOuvert);
} else {
$this->traiterErreur("Le dossier $nomDossier n'a pas pu être ouvert.");
}
} else {
$this->traiterErreur("$nomDossier n'est pas un dossier.");
}
} else {
$this->traiterErreur("Le dossier $nomDossier est introuvable.");
}
}
 
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier biblio format csv
// /opt/lampp/bin/php cli.php sophy/insertion -a biblio -n ./../donnees/sophy/BIBLIO.csv
private function executerBiblio() {
// Parcours le fichier .csv et enregistre chaque ligne dans un tableau.
$nomFichier = Config::get('dossierDonneesSophy').'BIBLIO.csv';
if ($nomFichier && file_exists($nomFichier) ){
$extensionFichier = strtolower(strrchr($nomFichier, '.'));
if ($extensionFichier === ".csv"){
$file = new SplFileObject($nomFichier);
$file->setFlags(SplFileObject::SKIP_EMPTY);
$i = 0;
echo "Traitement de la biblio : ";
while (!$file->eof()){
$ligne_csv = $file->fgetcsv();
if (preg_match('/^\d+$/', $ligne_csv[0])){
// récupére les colonnes du csv pour les transformer en table publication
$biblio = $this->transformerBiblio($ligne_csv);
// integre les publications à la bdd
$info = $this->dao->integrerBiblio($biblio);
$this->traiterInfo($info);
}
echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++;
}
echo "\n";
} else {
$this->traiterErreur("Le fichier de références bibliographiques : $nomFichier n'est pas au format csv.");
}
} else {
$this->traiterErreur("Le fichier de références bibliographiques : $nomFichier n'existe pas.");
}
}
 
private function transformerBiblio($ligne_csv){
$biblio['id_publi'] = $ligne_csv[0];
$biblio['auteur'] = $ligne_csv[2].' '.$ligne_csv[3];
$biblio['date'] = $ligne_csv[4];
$biblio['titre'] = rtrim($ligne_csv[5].' '.$ligne_csv[6].' '.$ligne_csv[7].' '.$ligne_csv[8].' '.$ligne_csv[9]);
$biblio['revue'] = rtrim($ligne_csv[10].' '.$ligne_csv[11]);
$biblio['volume'] = $ligne_csv[12];
$biblio['tome'] = $ligne_csv[13];
$biblio['fascicule'] = $ligne_csv[14];
$biblio['page_debut'] = $ligne_csv[15];
$biblio['page_fin'] = $ligne_csv[16];
return $biblio;
}
 
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement des fichiers stations
// /opt/lampp/bin/php cli.php insertion -a station -n ./../doc/donnees/ST/
private function executerStation() {
// transforme les fichiers passés en un tableau
//de la forme [nom du fichier][index des tableaux][numéro de ligne]
$tableaux = $this->ouvrirDossier(Config::get('dossierDonneesSophy').'ST/');
foreach ($tableaux as $fichier) {
foreach ($fichier as $tableau) {
if ($tableau[0] != "") {
// découpe la première ligne du tableau et insére les données dans la table tableau
$titre = $this->analyserTitreStation($tableau['0']);
for ($numReleve = 1; $numReleve < sizeof($tableau); $numReleve++) {
// découpe les autres lignes, insére les données dans la table station et retourne l'id de la station
if (trim($tableau[$numReleve]) == '') {
$id_station = 0;
} else {
$id_station = $this->analyserStation($tableau[$numReleve]);
}
// insére les données tableau et station dans la table relevé
$info = $this->dao->integrerReleve($titre, $numReleve, $id_station);
if ($info != '') {
$this->traiterErreur($info);
}
}
}
}
}
}
 
private function analyserTitreStation($titre) {
$titreDecoupe = $this->decouperLigne($titre, $this->format_titre);
$info = $this->dao->integrerTableau($titreDecoupe);
if ($info != '') {
$this->traiterErreur($info);
}
return $titreDecoupe;
}
 
private function analyserStation($ligne) {
$ligneDecoupe = $this->decouperLigne($ligne, $this->format_station);
$ligneDecoupe['latitude_wgs'] = null;
$ligneDecoupe['longitude_wgs'] = null;
// vérifie que les zéro du code sont présents
$ligneDecoupe = $this->analyserCodeDeptComm($ligneDecoupe);
// transforme les grades paris en degrés décimaux wms
$ligneDecoupe = $this->analyserCoordGrdParis($ligneDecoupe, $ligne);
// transforme les degrés sexagécimaux en degrés décimaux
$ligneDecoupe = $this->analyserCoordDmsWms($ligneDecoupe);
// transforme les degrés décimaux en UTM
$ligneDecoupe = $this->transformerCoordWmsUtm($ligneDecoupe);
$ligneDecoupe['nomStation'] = utf8_encode($ligneDecoupe['nomStation']);
$retour_requete = $this->dao->integrerStation($ligneDecoupe);
if ($retour_requete['info'] != '') {
$this->traiterErreur($retour_requete['info']);
}
return $retour_requete['id_station'];
}
private function executerStationCodeInsee() {
$this->dao->creerColonneCodeInseeCalculee();
$liste_coordonnees = $this->dao->rechercherCoordonneesWgs();
foreach ($liste_coordonnees as $coordonnees) {
$code_insee = $this->chercherCodeCommune($coordonnees['latitude'], $coordonnees['longitude']);
if ($code_insee != "") {
$this->dao->ajouterCodeInseeCalculee($coordonnees['latitude'], $coordonnees['longitude'], $code_insee);
}
}
}
private function chercherCodeCommune($latitude, $longitude) {
$code_insee = '';
if ($this->testerCoordonneesWgsFrance($latitude, $longitude)) {
$url_service = "www.tela-botanica.org/service:eflore:0.1/osm/nom-commune".
"?lat={$latitude}&lon={$longitude}";
$url_service = str_replace(',', '.', $url_service);
$ch = curl_init($url_service);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$reponse = curl_exec($ch);
$reponse = json_decode($reponse);
if (isset($reponse->codeINSEE)) {
$code_insee = $reponse->codeINSEE;
}
curl_close($ch);
}
return $code_insee;
}
private function testerCoordonneesWgsFrance($latitude, $longitude) {
$coord_france = false;
if ($latitude != '' && $longitude != '') {
if ($latitude < 51.071667 && $latitude > 41.316667) {
if ($longitude < 9.513333 && $longitude > -5.140278) {
$coord_france = true;
}
}
}
return $coord_france;
}
private function analyserCodeDeptComm($ligneDecoupe) {
if (preg_match('/^\d{2}$/', $ligneDecoupe['codeDept'])) {
} elseif (preg_match('/^\s{0,1}\d{1,2}\s{0,1}$/',$ligneDecoupe['codeDept'])) {
$ligneDecoupe['codeDept'] = str_replace(' ', '0', $ligneDecoupe['codeDept']);
} else {
$ligneDecoupe['codeDept'] = null;
}
if (preg_match('/^\d{3}$/', $ligneDecoupe['codeCommune'])) {
} elseif (preg_match('/^\s{0,2}\d{1,2,3}\s{0,2}$/', $ligneDecoupe['codeCommune'])) {
$ligneDecoupe['codeCommune'] = str_replace(' ', '0', $ligneDecoupe['codeCommune']);
} elseif ($ligneDecoupe['codeDept'] == null) {
$ligneDecoupe['codeCommune'] = null;
} else {
$ligneDecoupe['codeCommune'] = '000';
}
return $ligneDecoupe;
}
private function analyserCoordGrdParis($ligneDecoupe, $ligne) {
if (preg_match('/[\s0]0\.000/', $ligneDecoupe['latitude'], $match)) {
$ligneDecoupe['latitude'] = null;
$ligneDecoupe['longitude'] = null;
} elseif (preg_match('/\d{1,2}\.\d{2,3}/', $ligneDecoupe['latitude'], $match)) {// format souhaité
$ligneDecoupe['latitude_wgs'] = round($ligneDecoupe['latitude']*0.9, 7);
$ligneDecoupe['longitude_wgs'] = round($ligneDecoupe['longitude']*0.9+2.3372291, 7);
} elseif (preg_match('/(\d{2})[\d\s,](\d{3})/', $ligneDecoupe['latitude'], $match)) {//erreur de saisie
$ligneDecoupe['latitude'] = $match[1].'.'.$match[2];
$ligneDecoupe['latitude_wgs'] = round($ligneDecoupe['latitude']*0.9, 7);
$ligneDecoupe['longitude_wgs'] = round($ligneDecoupe['longitude']*0.9 + 2.3372291, 7);
} elseif (preg_match('/^[a-zA-Z\s]*[a-zA-Z][a-zA-Z\s]*$/', $ligneDecoupe['latitude'])) {// lat absente + nom long
$ligneDecoupe['nomStation'] = rtrim(substr($ligne, 10, 48));
$ligneDecoupe['latitude'] = null;
$ligneDecoupe['longitude'] = null;
} elseif (preg_match('/.[AO].123/', $ligneDecoupe['latitude'], $match)) {
$ligneDecoupe['latitude'] = null;
$ligneDecoupe['longitude'] = null;
} elseif ($ligneDecoupe['latitude'] != null) {
$ligneDecoupe['latitude'] = null;
$ligneDecoupe['longitude'] = null;
}
return $ligneDecoupe;
}
private function analyserCoordDmsWms($ligneDecoupe) {
if (preg_match('/(\d{1,2})\.(\d{2})\.(\d{2})/', $ligneDecoupe['latitude2'], $match)) {
$ligneDecoupe['latitude_wgs'] = round($match[1]+($match[2]/60)+($match[3]/3600), 7);
}
if (preg_match('/(-{0,1})(\d{1,2})\.(\d{2})\.(\d{2})/', $ligneDecoupe['longitude2'], $match)) {
$ligneDecoupe['longitude_wgs'] = round($match[2]+($match[3]/60)+($match[4]/3600), 7);
if ($match[1] == '-') {
$ligneDecoupe['longitude_wgs'] = -$ligneDecoupe['longitude_wgs'];
}
}
return $ligneDecoupe;
}
private function transformerCoordWmsUtm($ligneDecoupe) {
$ligneDecoupe['utmNorthing'] = null;
$ligneDecoupe['utmEasting'] = null;
$ligneDecoupe['utmZone'] = null;
if ($ligneDecoupe['longitude_wgs'] != null && $ligneDecoupe['latitude_wgs'] != null) {
$convertisseur = new gPoint();
$convertisseur->setLongLat($ligneDecoupe['longitude_wgs'], $ligneDecoupe['latitude_wgs']);
$convertisseur->convertLLtoTM();
$ligneDecoupe['utmNorthing'] = round($convertisseur->N(), 2);
$ligneDecoupe['utmEasting'] = round($convertisseur->E(), 2);
$ligneDecoupe['utmZone'] = $convertisseur->Z();
}
return $ligneDecoupe;
}
 
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement des fichiers tableaux
// /opt/lampp/bin/php cli.php insertion -a tableau -n ./../doc/donnees/T/
private function executerTableau() {
$tableaux = $this->ouvrirDossier(Config::get('dossierDonneesSophy').'T/');
$observations = array();
foreach ($tableaux as $fichier) {
foreach ($fichier as $tableau) {
if ($tableau[0] != "") {
$this->observations = array();
$titre = $this->decouperLigne($tableau[0], $this->format_titre);
$this->analyserTableau($tableau, $titre);
/*$info = $this->dao->integrerObservation($this->observations, $titre);
if ($info != '') {
$this->traiterErreur($info);
}*/
}
}
} $this->tableauTaxon->integrerTaxons();
}
 
private function analyserTableau($tableau, $titre) {
if ($titre['typeTableau'] == ' ') {
$titre['typeTableau'] = 0;
}
switch ($titre['typeTableau']) {
case 0 :
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) {
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['0']);
if (trim($ligneDecoupe['idTaxon']) == '' && trim($ligneDecoupe['abondance_rem']) == '' &&
preg_match('/^\s+\*N\s*\*\s*$/', $ligneDecoupe['indetermine'])) {
for ($nombreReleve = 1; $nombreReleve <= $titre['nombreStations']; $nombreReleve ++) {
$this->observations[$numeroLigne][$nombreReleve]['sc_id_publi'] = $titre['numPubli'];
$this->observations[$numeroLigne][$nombreReleve]['sc_id_tableau'] = $titre['numTableau'];
$this->observations[$numeroLigne][$nombreReleve]['sc_id_releve'] = $nombreReleve;
$this->observations[$numeroLigne][$nombreReleve]['sc_num_ligne'] = $ligneDecoupe['numLigne'];
$this->observations[$numeroLigne][$nombreReleve]['sc_id_taxon'] = 0;
$this->observations[$numeroLigne][$nombreReleve]['sc_id_strate'] = 0;
$this->observations[$numeroLigne][$nombreReleve]['sc_ce_abondance'] = '?';
}
} else {
$this->creerObservType0($titre, $ligneDecoupe, $numeroLigne);
}
}
for ($nombreReleve = 1; $nombreReleve <= $titre['nombreStations']; $nombreReleve ++) {
$j = false;
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) {
if (isset($this->observations[$numeroLigne][$nombreReleve])) {
$j = true;
}
}
if ($j == false) {
$this->observations[0][$nombreReleve]['sc_id_publi'] = $titre['numPubli'];
$this->observations[0][$nombreReleve]['sc_id_tableau'] = $titre['numTableau'];
$this->observations[0][$nombreReleve]['sc_id_releve'] = $nombreReleve;
$this->observations[0][$nombreReleve]['sc_num_ligne'] = 0;
$this->observations[0][$nombreReleve]['sc_id_taxon'] = 0;
$this->observations[0][$nombreReleve]['sc_id_strate'] = 0;
$this->observations[0][$nombreReleve]['sc_ce_abondance'] = '?';
}
}
break;
case 2 :
$numSource = 0; $numReleve = 0;
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) {
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['2']);
if ($ligneDecoupe['numSource'] != $numSource) {
// $numSource correspond au numero à la station par l'auteur,
// $numReleve correspond à l'id de la station
$numSource = $ligneDecoupe['numSource'];
$numReleve ++;
}
if (strlen(trim($tableau[$numeroLigne])) < 10) {
$this->observations[$numeroLigne][1]['sc_id_publi'] = $titre['numPubli'];
$this->observations[$numeroLigne][1]['sc_id_tableau'] = $titre['numTableau'];
$this->observations[$numeroLigne][1]['sc_id_releve'] = $numReleve;
$this->observations[$numeroLigne][1]['sc_num_ligne'] = 0;
$this->observations[$numeroLigne][1]['sc_id_taxon'] = 0;
$this->observations[$numeroLigne][1]['sc_id_strate'] = 0;
$this->observations[$numeroLigne][1]['sc_ce_abondance'] = '?';
} else {
$this->creerObservType2($titre, $ligneDecoupe, $numReleve, $numeroLigne);
}
}
break;
case 6 :
$numSource = 0; $numReleve = 0;
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) {
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['6']);
$num = (preg_match('/[\dA-Z]+\s+[\dA-Z]+/', $ligneDecoupe['numSource'].$ligneDecoupe['posteMeteo']))
? ltrim($ligneDecoupe['numSource'])
: $ligneDecoupe['numSource'].$ligneDecoupe['posteMeteo'];
if ($num !== $numSource) {
$numSource = $num;
$numReleve ++;
}
$this->creerObservType2($titre, $ligneDecoupe, $numReleve, $numeroLigne);
}
break;
case 7 :
$numSource = 0; $numReleve = 0;
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) {
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['7']);
if (trim($ligneDecoupe['numReleve']) !== $numSource) {
$numSource = trim($ligneDecoupe['numReleve']);
$numReleve ++;
}
$this->creerObservType2($titre, $ligneDecoupe, $numReleve, $numeroLigne);
}
break;
default :
for ($numeroLigne = 1; $numeroLigne < sizeof($tableau); $numeroLigne++) {
$ligneDecoupe = $this->decouperLigne($tableau[$numeroLigne], $this->format_tableau['0']);
$this->creerObservType0($titre, $ligneDecoupe);
}
break;
}
return $ligneDecoupe;
}
// crée des observations au format de la table à partir d'un tableau de type standard (0)
private function creerObservType0($titre, $ligneDecoupe, $numeroLigne) {
$observation = null;
// Retourne l'id du taxon dans la bd sophy
$idTaxon = $this->identifierTaxon($titre['nombreStations'], $ligneDecoupe, $numeroLigne);
// découpe le champs abondance_rem ou indetermine selon le nombre de relevés
$remAbondance = substr(
($ligneDecoupe['abondance_rem'] != null) ? $ligneDecoupe['abondance_rem'] : $ligneDecoupe['indetermine'],
0, $titre['nombreStations']);
// si aucun relevé ne contient d'abondance pour un taxon, ajout d'une abondance ? pour ce taxon
if (trim($remAbondance) == '') {
$remAbondance = '?';
}
for ($numReleve = 1; $numReleve <= $titre['nombreStations']; $numReleve++) {
if ($remAbondance === '?' && $numeroLigne === 1) {
$abondance = '?';
} else {
$abondance = substr($remAbondance, ($numReleve-1), 1);
}
if ($abondance != '' && $abondance != ' ') {
$this->observations[$numeroLigne][$numReleve]['sc_id_publi'] = $titre['numPubli'];
$this->observations[$numeroLigne][$numReleve]['sc_id_tableau'] = $titre['numTableau'];
$this->observations[$numeroLigne][$numReleve]['sc_id_releve'] = $numReleve;
$this->observations[$numeroLigne][$numReleve]['sc_num_ligne'] = $numeroLigne;
$this->observations[$numeroLigne][$numReleve]['sc_id_taxon'] = $idTaxon;
if ($ligneDecoupe['strate'] != null) {
$this->observations[$numeroLigne][$numReleve]['sc_id_strate'] = $ligneDecoupe['strate'];
} else {
$this->observations[$numeroLigne][$numReleve]['sc_id_strate'] = 0;
}
$this->observations[$numeroLigne][$numReleve]['sc_ce_abondance'] = $abondance;
}
}
}
// crée des observations au format de la table à partir d'un tableau de type 2, 6 ou 7 (10 plantes en lignes)
private function creerObservType2($titre, $ligneDecoupe, $numReleve, $numeroLigne) {
$observation = null;
for ($i = 1; $i < 11; $i++) {
// si le numéro de taxon et l'abondance ne sont pas nulls
if ((($ligneDecoupe['abondance'.$i] == '' || $ligneDecoupe['abondance'.$i] == '0') &&
(trim($ligneDecoupe['codeFournier'.$i]) == '' || $ligneDecoupe['codeFournier'.$i] == '0'))) {
} else {
$positionTaxon = $ligneDecoupe['numLigne']*10 + $i - 10;
$this->observations[$numeroLigne][$positionTaxon]['sc_id_publi'] = $titre['numPubli'];
$this->observations[$numeroLigne][$positionTaxon]['sc_id_tableau'] = $titre['numTableau'];
$this->observations[$numeroLigne][$positionTaxon]['sc_id_releve'] = $numReleve;
$this->observations[$numeroLigne][$positionTaxon]['sc_num_ligne'] = $positionTaxon;
$idTaxon = str_replace(' ', '0', $ligneDecoupe['codeFournier'.$i]);
$this->observations[$numeroLigne][$positionTaxon]['sc_id_taxon'] =
$this->identifierTaxon2($idTaxon, $titre['typeTableau']);
if ($ligneDecoupe['strate'.$i] != null) {
$this->observations[$numeroLigne][$positionTaxon]['sc_id_strate'] = $ligneDecoupe['strate'.$i];
} else {
$this->observations[$numeroLigne][$positionTaxon]['sc_id_strate'] = 0;
}
if ($ligneDecoupe['abondance'.$i] == '' || $ligneDecoupe['abondance'.$i] == '0') {
$this->observations[$numeroLigne][$positionTaxon]['sc_ce_abondance'] = '?';
} else {
$this->observations[$numeroLigne][$positionTaxon]['sc_ce_abondance'] = $ligneDecoupe['abondance'.$i];
}
}
}
}
private function identifierTaxon2($idTaxon, $typeTableau) {
$id = 0;
if ($typeTableau == 2 && $idTaxon == 75000) {
$id = $this->tableauTaxon->getId(75000, 'algues');
} elseif ($typeTableau == 2 && $idTaxon == 85000) {
$id = $this->tableauTaxon->getId(85000, 'characees');
} elseif ($typeTableau == 2 && $idTaxon == 90000) {
$id = $this->tableauTaxon->getId(90000, 'bryo');
} elseif ($typeTableau == 2 && $idTaxon == 95000) {
$id = $this->tableauTaxon->getId(95000, 'lichen');
} elseif ($typeTableau == 2 && $idTaxon >= 90000) {
$idTaxon -= 90000;
$id = $this->tableauTaxon->getId($idTaxon, 'bryo');
} elseif ($typeTableau == 2 && $idTaxon >= 20000) {
$idTaxon -= 20000;
$id = $this->tableauTaxon->getId($idTaxon, 'floeur');
} else {
if ($typeTableau == 2 && ($idTaxon != '00000' && $idTaxon != '')) {
$idTaxon = (substr($idTaxon, 0, 2) - 1)*600 +
(substr($idTaxon, 2, 2) - 11)*10 + (substr($idTaxon, 4, 1) + 1);
} elseif ($idTaxon != '00000' && $idTaxon != '') {
$idTaxon = ltrim($idTaxon, "0");
} else {
$idTaxon = 0;
}
$id = $this->tableauTaxon->getId($idTaxon, 'fournier');
}
return $id;
}
 
// fonctions nécessaires pour les tableaux de type standard (0)
private function identifierTaxon($nombreReleves, $ligneDecoupe, $numeroLigne) {
// decoupe le champs remarque
if ($ligneDecoupe['abondance_rem'] != null) {
$rem = trim(substr($ligneDecoupe['abondance_rem'], (int) ltrim($nombreReleves), strlen($ligneDecoupe['abondance_rem'])));
} else {
$rem = substr($ligneDecoupe['indetermine'], (int) ltrim($nombreReleves), strlen($ligneDecoupe['indetermine']));
}
$remAnalyse = $this->analyserRemarque($rem, $numeroLigne);
$id = 0;
if ($ligneDecoupe['idTaxon'] != null) {
$idTaxon = str_replace(' ', '0', $ligneDecoupe['idTaxon']);
switch ($idTaxon) { // probleme code dans les 80000 attentes reponses brisse
case 0 : $id = $this->recupererId($remAnalyse, 00000); break;
case 00000 : $id = $this->recupererId($remAnalyse, $idTaxon); break;
case 20000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'floeur'); break;
case 75000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'algues'); break;
case 85000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'characees'); break;
case 90000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'bryo'); break;
case 95000 : $id = $this->recupererId($remAnalyse, $idTaxon, 'lichen'); break;
default :
if ($idTaxon < 1100) {
$id = $this->recupererId($remAnalyse, 0);
}elseif ($idTaxon < 20000) {
// transformer code fournier en numéro fournier
$numeroFournier = (substr($idTaxon, 0, 2) - 1)*600 + (substr($idTaxon, 2, 2) - 11)*10 +
(substr($idTaxon, 4, 1) + 1);
$id = $this->recupererId($remAnalyse, $numeroFournier, 'fournier'); break;
} elseif ($idTaxon < 90000) {
$idTaxon -= 20000;
$id = $this->recupererId($remAnalyse, $idTaxon, 'floeur'); break;
} else {
$idTaxon -= 90000;
$id = $this->recupererId($remAnalyse, $idTaxon, 'bryo'); break;
}
break;
}
} else {
$id = $this->recupererId($remAnalyse, 0);
}
return $id;
}
 
private function recupererId($remAnalyse, $idTaxon, $flore = 'ind') {
if ($remAnalyse['presence'] == true) {
$id = $this->tableauTaxon->getId($remAnalyse['num'], $remAnalyse['flore'], $remAnalyse['nom'],
$flore, $idTaxon, $remAnalyse['remarques']);
} else {
$id = $this->tableauTaxon->getId($idTaxon, $flore);
}
return $id;
}
 
private function analyserRemarque($rem, $numeroLigne) {
$taxon['presence'] = false;
if ($rem != '') {
$taxon['flore'] = 'ind';
$taxon['num'] = 0;
$taxon['nom'] = null;
$taxon['remarques'] = null;
$remAsterique = preg_split('/\*/', $rem);
// recuperer le numero et/ou le nom qui sont en remarque
foreach ($remAsterique as $morceauRem) {
if ($morceauRem == 'N000000') {
} elseif (preg_match('/^[A-Z]{1,2}\s{5,6}$/', $morceauRem)) {
} elseif (preg_match('/^[\s0]*$/', $morceauRem)) {
} elseif (preg_match('/^([A-Z]{1,2})([0\s]{5,6})$/', $morceauRem)) {
} elseif (preg_match('/^[\d\s]{5}\d$/', $morceauRem)) {
$taxon['num'] = ltrim(str_replace(' ', '0', $morceauRem), '0');
$taxon['flore'] = 'syntri';
$taxon['presence'] = true;
} elseif (preg_match('/^\s*(\d[\d\s]+\d)\s*$/', $morceauRem, $match)) {
$taxon['num'] = ltrim(str_replace(' ', '0', $match[1]), '0');
$taxon['flore'] = 'syntri';
$taxon['presence'] = true;
} elseif (preg_match('/^\s*[A-Za-z][a-z\s\.()]+$/', $morceauRem)) {
$taxon['nom'] = $morceauRem;
$taxon['presence'] = true;
} elseif (preg_match('/^\s*("\s*[\s"]*)([A-Za-z][A-Za-z\s\.()]+)$/', $morceauRem, $match)) {
foreach ($this->observations[$numeroLigne-1] as $obsPrec) {
$idPrec = $obsPrec['sc_id_taxon'];
}
$nombreQuote = substr_count($match[1], '"');
$nomPrec = preg_split('/\s/', $this->tableauTaxon->getNom($idPrec)); $nom = '';
if (preg_match('/^(x|var|ssp)/', $match[2])) {
} elseif ($nombreQuote == 2 || $nombreQuote == 4) {
$nombreQuote = $nombreQuote/2;
}
for ($i = 0; $i < $nombreQuote; $i++) {
if ($i < count($nomPrec)) {
$nom .= $nomPrec[$i]." ";
}
}
$taxon['nom'] = $nom.$match[2];
$taxon['remarques'] = $morceauRem;
$taxon['presence'] = true;
} elseif (preg_match('/^([A-Z]{1,2})([\d\s]{4,5}\d)$/', $morceauRem, $match) ||
preg_match('/^(\s{1,2})([\d\s]{4,5}\d)$/', $morceauRem, $match)) {
switch (trim($match[1])) {
case 'S' : $taxon['flore'] = 'syntri'; break;
case 'CI' : $taxon['flore'] = 'ciff'; break;
case 'C' : $taxon['flore'] = 'codefr94'; break;
case 'BD' : $taxon['flore'] = 'bdnff'; break;
case 'N' : $taxon['flore'] = 'syntri'; break;
case '' : $taxon['flore'] = 'syntri'; break;
default : $taxon['flore'] = 'ind'; break;
}
$taxon['num'] = ltrim(str_replace(' ', '0', $match[2]), '0');
$taxon['presence'] = true;
} else {
$morceauRem = trim($morceauRem);
if ($morceauRem != '' && $morceauRem != null) {
$taxon['remarques'] = $morceauRem;
$taxon['presence'] = true;
}
}
}
}
return $taxon;
}
 
// +-------------------------------------------------------------------------------------------------------------------+
// Fonction Statistiques
private function executerStats() {
$nombreTotalLignesTable = $this->dao->getNombreLigne($this->param_bd_pour_stat);
print_r($nombreTotalLignesTable);
}
 
// +-------------------------------------------------------------------------------------------------------------------+
// Fonction générale
private function ouvrirDossier($nomDossier) {
$tableaux = null;
if (file_exists($nomDossier) === true) {
if (is_dir($nomDossier)) {
if ($dossierOuvert = opendir($nomDossier) ) {
while ( ($nomFichier = readdir($dossierOuvert)) !== false) {
if ( !is_dir($nomFichier) ) {
$nomFichier = $nomDossier.$nomFichier;
$tableaux[$nomFichier] = $this->ouvrirFichier($nomFichier);
}
}
closedir($dossierOuvert);
} else {
$this->traiterErreur("Le dossier $nomDossier n'a pas pu être ouvert.");
}
} else {
$tableaux[$nomDossier] = $this->ouvrirFichier($nomDossier);
}
} else {
$this->traiterErreur("Le dossier $nomDossier est introuvable.");
}
return $tableaux;
}
 
// Prend en entree un fichier et retourne un tableau de Tableau phytosocio ou stations
private function ouvrirFichier($nomFichier) {
$tableauxDecoupes = null;
$clefTableau = 0;
$clefLigne = 0;
if (file_exists($nomFichier) === true) {
if ( $fichierOuvert = fopen($nomFichier, 'r') ) {
while ($ligne = fgets($fichierOuvert)) {
if (preg_match('/^.*9{10}.*$/', $ligne)) {
$clefTableau ++ ;
$clefLigne = 0;
} else {
$tableauxDecoupes[$clefTableau][$clefLigne] = rtrim($ligne, " \t");
$clefLigne ++;
}
}
fclose($fichierOuvert);
} else {
$this->traiterErreur("Le fichier $nomFichier n'a pas pu être ouvert.");
}
} else {
$this->traiterErreur("Le fichier $nomFichier est introuvable.");
}
return $tableauxDecoupes;
}
// utilise les tableaux format_titre ou format_station pour découper les lignes
private function decouperLigne($ligne, $format) {
$ligne = rtrim($ligne);
$taille = strlen($ligne);
foreach ($format as $param => $position) {
// si la taille de la ligne est inférieure à la taille du champs que l'on veut récupérer
if ($taille < ($position[0]+$position[1])) {
// on met à null sauf dans certains formats
$ligneDecoupe[$param] = null;
if (isset($format['numLigne'])) {
$ligneDecoupe['indetermine'] = rtrim(substr($ligne, $position[0], $taille));
}
} else {
$ligneDecoupe[$param] = trim(substr($ligne, $position[0], $position[1]));
}
}
return $ligneDecoupe;
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/sophy/sophy.ini
New file
0,0 → 1,20
; +------------------------------------------------------------------------------------------------------+
; Général
; Séparateur de dossier
ds = DIRECTORY_SEPARATOR
 
; +------------------------------------------------------------------------------------------------------+
; Info sur l'application
info.nom = Scripts de gestion de la phytosociologie
; Abréviation de l'application
info.abr = sophy
; Version du Framework nécessaire au fonctionnement de cette application
info.framework.version = 0.2
;Encodage de l'application
appli_encodage = "UTF-8"
version="2010-12-02"
dossierDonneesSophy = "{ref:dossierDonneesEflore}{ref:info.abr}/{ref:version}/"
[fichiers]
structureSql = "sophy.sql"
[chemins]
structureSql = "{ref:dossierDonneesSophy}{ref:fichiers.structureSql}"
/tags/v5.7-arrayanal/scripts/modules/sophy/Export.php
New file
0,0 → 1,224
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Export des données de SOPHY
*
* Description : classe permettant d'exporter les tableaux phytosociologiques de la banque de données SOPHY
* Utilisation : php script.php export
*
* @category PHP 5.3
* @package phytosocio
//Auteur original :
* @author Delphine CAUQUIL <delphine@tela-botanica.org>
* @copyright Copyright (c) 2009, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL-v3
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2
* @version $Id$
*
* /opt/lampp/bin/php -d memory_limit=2048M cli.php sophy/export -a rien -c publication/strate/flore
* -f annee:sup:1990/auteur:like:ma%/departement:in:14,50,61,76,27/nomsci:like:trifolium%/fournier:neg: >log.txt
*
*
*
* export pour le crpf
*
*
* export pour les plantes de la liste rouge des suisses
* /opt/lampp/bin/php -d memory_limit=2048M cli.php sophy/export -a rien -f nomsci:in:"'Adenophora liliifolia (L.) A. DC.','Adenostyles leucophylla (Willd.) Rchb.','Allium angulosum L.','Allium rotundum L.','Anagallis minima (L.) E. H. L. Krause','Anagallis tenella (L.) L.','Anchusa officinalis L.','Andromeda polifolia L.','Androsace brevis (Hegetschw.) Ces.','Anemone baldensis L.','Anemone sylvestris L.','Anogramma leptophylla (L.) Link','Apium repens (Jacq.) Lag.','Aquilegia einseleana F. W. Schultz','Artemisia nivalis Braun-Blanq.','Asperugo procumbens L.','Asplenium adulterinum Milde','Asplenium billotii F. W. Schultz','Asplenium foreziense Magnier','Astragalus australis (L.) Lam.','Barbarea stricta Andrz.','Blackstonia acuminata (W. D. J. Koch & Ziz) Domin','Bromus grossus DC.','Bufonia paniculata Dubois','Campanula excisa Murith','Campanula latifolia L.','Cardamine kitaibelii Bech.','Cardamine matthioli Moretti','Carduus crispus L.','Carex baldensis L.','Carex fimbriata Schkuhr','Carex hartmanii Cajander','Carpesium cernuum L.','Chenopodium ficifolium Sm.','Chenopodium rubrum L.','Clematis alpina (L.) Mill.','Corydalis intermedia (L.) Mérat','Corydalis solida (L.) Clairv.','Crepis pygmaea L.','Crepis terglouensis (Hacq.) A. Kern.','Cuscuta europaea L.','Cytisus decumbens (Durande) Spach','Cytisus emeriflorus Rchb.','Cytisus nigricans L.','Cytisus scoparius (L.) Link','Deschampsia littoralis (Gaudin) Reut.','Dianthus gratianopolitanus Vill.','Dianthus seguieri Vill.','Diphasiastrum complanatum (L.) Holub','Diplotaxis muralis (L.) DC.','Draba fladnizensis Wulfen','Draba hoppeana Rchb.','Draba ladina Braun-Blanq.','Draba siliquosa M. Bieb.','Draba tomentosa Clairv.','Equisetum ramosissimum Desf.','Eriophorum gracile Roth','Erythronium dens-canis L.','Euonymus latifolius (L.) Mill.','Euphrasia christii Gremli','Falcaria vulgaris Bernh.','Fragaria viridis Duchesne','Gagea pratensis (Pers.) Dumort.','Galeopsis pubescens Besser','Gentiana engadinensis (Wettst.) Braun-Blanq. & Sam.','Geranium rivulare Vill.','Gladiolus imbricatus L.','Gladiolus italicus Mill.','Gladiolus palustris Gaudin','Gratiola officinalis L.','Hammarbya paludosa (L.) Kuntze','Helianthemum salicifolium (L.) Mill.','Iberis saxatilis L.','Inula britannica L.','Inula helvetica Weber','Inula spiraeifolia L.','Isopyrum thalictroides L.','Juniperus sabina L.','Knautia godetii Reut.','Lathyrus sphaericus Retz.','Leucanthemum halleri (Vitman) Ducommun','Leucojum aestivum L.','Linaria alpina subsp. petraea (Jord.) Rouy','Lindernia procumbens (Krock.) Borbás','Linnaea borealis L.','Littorella uniflora (L.) Asch.','Minuartia cherlerioides subsp. rionii (Gremli) Friedrich','Myosotis rehsteineri Wartm.','Myrrhis odorata (L.) Scop.','Nigella arvensis L.','Notholaena marantae (L.) Desv.','Ononis rotundifolia L.','Orchis laxiflora Lam.','Orchis papilionacea L.','Orchis provincialis DC.','Orchis spitzelii W. D. J. Koch','Ostrya carpinifolia Scop.','Pedicularis oederi Hornem.','Peucedanum verticillare (L.) Mert. & W. D. J. Koch','Phyteuma humile Gaudin','Pilularia globulifera L.','Pinguicula grandiflora Lam. s.str.','Polygonum minus Huds.','Potentilla alpicola Fauc.','Potentilla caulescens L.','Potentilla grammopetala Moretti','Potentilla inclinata Vill.','Primula daonensis (Leyb.) Leyb.','Primula latifolia Lapeyr.','Pulmonaria helvetica Bolliger','Ranunculus gramineus L.','Ranunculus parnassiifolius L.','Rhodiola rosea L.','Rhynchospora alba (L.) Vahl','Rumex nivalis Hegetschw.','Sagina nodosa (L.) Fenzl','Saponaria lutea L.','Saxifraga adscendens L.','Saxifraga aphylla Sternb.','Saxifraga diapensioides Bellardi','Saxifraga mutata L.','Scorzonera laciniata L. s.str.','Scutellaria alpina L.','Sedum anacampseros L.','Sedum cepaea L.','Sedum rubens L.','Senecio aquaticus Hill','Senecio halleri Dandy','Senecio incanus subsp. insubricus (Chenevard) Braun-Blanq.','Senecio paludosus L.','Silene pusilla Waldst. & Kit.','Silene suecica (Lodd.) Greuter & Burdet','Sisymbrium supinum L.','Teucrium scordium L.','Thlaspi rotundifolium subsp. corymbosum Gremli','Trifolium saxatile All.','Trochiscanthes nodiflora (All.) W. D. J. Koch','Typha minima Hoppe','Valeriana celtica L.','Valeriana supina Ard.','Viola cenisia L.','Viola elatior Fr.','Viola lutea Huds.','Viola persicifolia Schreb.','Viola pinnata L.','Viola pyrenaica DC.','Woodsia alpina (Bolton) Gray'"/departement:in:14,39,25,90,68,74
*
*/
// +-------------------------------------------------------------------------------------------------------------------+
class Export extends EfloreScript {
protected $tableauTaxon;
protected $dao;
protected $observations;
// Paramêtres autorisées lors de l'appel au script en ligne de commande
protected $parametres_autorises = array(
'-n' => array(false, 'export', 'Nom du fichier à créer'),
'-c' => array(false, 'tous', 'Liste des champs à récupérer'),
'-f' => array(false, true, 'Liste des filtres à executer'));
 
// à utiliser dans les valeurs des parametres pour séparer les champs ou filtres
protected $separateur = "/";
// correspondances parametres/champs de la bd
protected $champs_exportes = array(
"code_identifiant" => "CONCAT(o.so_id_publi,'.',o.so_id_tableau,'.',o.so_id_releve,'.',
o.so_num_ligne,'.',o.so_id_taxon,'.',o.so_id_strate) AS code_identifiant",
"numero_publication" => "sp_id_publi AS numero_publication",
"publication" => "CONCAT (sp_auteur, '. ', sp_revue, ' ', sp_volume, ' ', sp_tome, ' ', sp_fascicule, ', ', sp_date,
'. ', sp_titre, ', p.', sp_page_debut, '-', sp_page_fin, '.') AS publication",
"auteur" => "sp_auteur AS auteur",
"annee" => "sp_date AS annee",
"numero_tableau" => "sr_id_tableau AS numero_tableau",
"numero_releve" => "sr_id_releve AS numero_releve",
"nom_station" => "ss_localisation AS nom_station",
"code_insee" => "IF (ss_code_departement != 0,
CONCAT(ss_code_departement, ss_code_insee_commune), ss_code_insee_calculee) AS code_insee",
"code_insee_calcule" => "ss_code_insee_calculee AS code_insee_calcule",
"altitude" => "ss_altitude AS altitude",
"coordonnees_wgs" => "ss_latitude_wgs, ss_longitude_wgs",
"coordonnees_utm" => "ss_utmEasting, ss_utmNorthing, ss_utmZone",
"precision_geographique" => "ss_ce_precision_geographique",
"nom_scientifique" => "st_nom AS nom_scientifique",
"flore" => "st_ce_num_fournier, st_ce_num_floeur, st_ce_num_algues, st_ce_num_characees, st_ce_num_bryo,
st_ce_num_lichen, st_ce_num_syntri, st_ce_num_bdnff, st_ce_num_ciff, st_ce_num_codefr94",
"strate" => "so_id_strate AS strate",
"code_abondance" => "so_ce_abondance AS code_abondance");
protected $autresChamps = array(
"signification_precision" => "spg_num_precision, spg_valeur",
"signification_strate" => "so_id_strate",
"signification_abondance" => "sa_valeur");
protected $filtres_existants = array(
"annee" => "sp_date",
"auteur" => "sp_auteur",
"departement" => "",
"commune" => "",
"precisiongeo" => "ss_ce_precision_geographique",
"nomsci" => "st_nom",
"fournier" => "st_ce_num_fournier",
"floeur" => "st_ce_num_floeur",
"algues" => "st_ce_num_algues",
"characees" => "st_ce_num_characees",
"bryo" => "st_ce_num_bryo",
"lichen" => "st_ce_num_lichen",
"syntri" => "st_ce_num_syntri",
"bdnff" => "st_ce_num_bdnff",
"ciff" => "st_ce_num_ciff",
"codefr" => "st_ce_num_codefr94");
protected $operateurs = array(
"inf" => "<",
"sup" => ">",
"eg" => "=",
"neg" => "!=",
"infeg" => "<=",
"supeg" => ">=",
"in" => " IN ",
"like" => " LIKE ");
// +-------------------------------------------------------------------------------------------------------------------+
public function executer() {
include_once dirname(__FILE__).'/bibliotheque/Dao.php';
Config::charger(dirname(__FILE__).'/sophy.ini');
$this->dao = new Dao();
// Récupération de paramétres
$requete['nomFichier'] = $this->getParametre('n');
$requete['champs'] = $this->formaterChamps($this->getParametre('c'));
$requete['filtres'] = $this->formaterFiltres($this->getParametre('f'));
$donnees = $this->recupererDonnees($requete);
if ($donnees === false) {
$info = "Pas de données";
} else {
$titre = $this->formaterTitre($this->getParametre('c')); //à revoir
$this->exportCSV($requete['nomFichier'], $titre, $donnees);
}
}
protected function formaterFiltres($filtres) {
$where = array();
if ($filtres != '') {
$liste_filtres = explode($this->separateur, $filtres);
foreach ($liste_filtres as $filtre) {
$morceaux_filtre = explode(':', $filtre);
if (isset($this->filtres_existants[$morceaux_filtre[0]])) {
if (isset($this->operateurs[$morceaux_filtre[1]])) {
$where[] = $this->traiterFiltres($morceaux_filtre);
} else {
echo "L'operateur demandé {$morceaux_filtre[1]} n'existe pas. Les opérateurs existants sont :\n".
implode(', ', array_keys($this->operateurs));
}
} else {
echo "Le filtre demandé {$morceaux_filtre[0]} n'existe pas. Les filtres existants sont :\n".
implode(', ', array_keys($this->filtres_existants));
}
}
$where = ' WHERE '.implode(' AND ', $where);
}
return $where;
}
protected function traiterFiltres($morceaux) {
$where = '';
if ($this->operateurs[$morceaux[1]] == ' IN ') {
$where = $this->operateurs[$morceaux[1]].'('.$morceaux[2].')';
} else {
$where= $this->operateurs[$morceaux[1]].$this->getBdd()->proteger($morceaux[2]);
}
switch ($morceaux[0]) {
case 'departement' :
$where = "( ss_code_departement".$where.
" OR substring( `ss_code_insee_calculee`, -5, 2 ) ".$where.") ";
break;
case 'commune' :
$where = "( CONCAT(ss_code_departement, ss_code_insee_commune) ".$where.
" OR `ss_code_insee_calculee` ".$where.") ";
break;
default : $where= $this->filtres_existants[$morceaux[0]].$where;
break;
}
return $where;
}
protected function formaterChamps($champs_demandes) {
$champs_demandes = explode($this->separateur, $champs_demandes);
if ($champs_demandes[0] == 'tous') {
$champs = implode(', ', array_values($this->champs_exportes));
} else {
foreach ($champs_demandes as $champ) {
if (isset($this->champs_exportes[$champ])) {
$champs[] = $this->champs_exportes[$champ];
} else {
echo "Le champ demandé {$champ} n'existe pas. Les champs existants sont :\n".
implode(', ', array_keys($this->champs_exportes));
}
}
$champs = implode(', ', $champs);
}
return $champs;
}
protected function formaterTitre($champs) {
$liste_champs = ($champs == 'tous') ? array_keys($this->champs_exportes) :explode(',', $champs);
foreach ($liste_champs as $champs) {
switch ($champs) {
case "flore" : $titre[] = "fournier"; $titre[] = "floeur"; $titre[] = "algues"; $titre[] = "characees";
$titre[] = "bryo"; $titre[] = "lichen"; $titre[] = "syntri"; $titre[] = "bdnff"; $titre[] = "ciff";
$titre[] = "code france 94"; break;
case "coordonnees_wgs": $titre[] = "latitude (wgs)"; $titre[] = "longitude (wgs)"; break;
case "coordonnees_utm" :
$titre[] = "Easting (utm)"; $titre[] = "Northing (utm)"; $titre[] = "zone utm"; break;
default: $titre[] = $champs; break;
}
}
return $titre;
}
 
// Requête de création et d'insertion sur table sophy_tapir
public function recupererDonnees($parametre) {
$bdd = new Bdd();
$requete = "SELECT {$parametre['champs']}
FROM sophy_observation o LEFT JOIN sophy_taxon t ON (o.so_id_taxon = t.st_id_taxon)
LEFT JOIN sophy_releve r ON (r.sr_id_publi = o.so_id_publi AND r.sr_id_tableau = o.so_id_tableau AND r.sr_id_releve = o.so_id_releve )
LEFT JOIN sophy_station s ON (r.sr_id_station = s.ss_id_station)
LEFT JOIN sophy_publication p ON (r.sr_id_publi = p.sp_id_publi)
{$parametre['filtres']}";
//INTO OUTFILE '/home/delphine/web/eflore-projets/scripts/{$parametre['nomFichier']}.csv';";
echo $requete;
$reponse = $bdd->recupererTous($requete);
return $reponse;
}
function exportCSV($nomFichier, $titre, $data) {
$outstream = fopen("./{$nomFichier}.csv", 'w');
fputcsv($outstream, $titre, ';', '"');
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ';', '"'); //\t = chr(9)
}
array_walk($data, '__outputCSV', $outstream);
fclose($outstream);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/sophy/Insertionflore.php
New file
0,0 → 1,295
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Traitement des fichiers de la banque de données SOPHY pour insertion
*
* Description : classe permettant d'insérer les flores nécessaires à l'étude des données issues de SOPHY.
* Avant d'utiliser cette classe nettoyer les fichiers pour ne garder que les lignes à insérer.
* Utilisation : php script.php insertionFlore -a test
*
* @category PHP 5.3
* @package phytosocio
//Auteur original :
* @author Delphine CAUQUIL <delphine@tela-botanica.org>
* @copyright Copyright (c) 2009, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL-v3
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2
* @version $Id$
*/
// +-------------------------------------------------------------------------------------------------------------------+
class Insertionflore extends Script {
protected $dao;
protected $dossier;
protected $flore;
protected $parametres_autorises = array(
'-n' => array(true, true, 'Nom du fichier ou du dossier à traiter'));
public function executer() {
include_once dirname(__FILE__).'/bibliotheque/FloreDao.php';
Config::charger(dirname(__FILE__).'/sophy.ini');
$this->dossier = Config::get('dossierDonneesSophy').'FLORE/';
$this->dao = new FloreDao();
// Récupération de paramètres
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'florenbi' : // fournier
$this->executerFlorenbi();
break;
case 'bdnff' : // bdnff
$this->executerBdnff();
break;
case 'listepla' : // fournier/bdnff
$this->executerListePla();
break;
case 'floeur' : // flora europea
$this->executerFloeur();
break;
case 'bryo' : // bryophyte
$this->executerBryo();
break;
case 'syntri' : //syntri : numéro complémentaire
$this->executerSyntri();
break;
case 'ciff' : // CIFF CIFF/BDNFF
$this->executerCiff();
break;
case 'donneebb' : // Num_nom num_tax bdnff
$this->executerDonneebb();
break;
case 'codefr' : // CODEFR94
$this->executerCodefr();
break;
default :
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
}
}
 
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier flore florenbi qui contient tous codes, numéro et nom fournier
// /opt/lampp/bin/php cli.php sophy/insertionflore -a florenbi -n ./../donnees/sophy/2010-12-02/FLORE/FLORENBI
private function executerFlorenbi() {
$nomFichier = $this->dossier.'FLORENBI';
if (file_exists($nomFichier) === true) {
if ( $fichierOuvert = fopen($nomFichier, 'r') ) {
$nom = '';
while ($ligne = fgets($fichierOuvert)) {
if (preg_match('/^\s{2}[\d\s]{4}\s([\d\s]{3}\d)\s{2}([\d\s]\d\.\d\d\.\d)\s[\d\s]{5}[A-Z\s]\s(\d)\s*(.+)$/', $ligne, $champs)) {
// si le rang taxonomique est inf à 4 (subsp et var)
if ($champs[3] < 4) {
$flore[$champs[1]] = $champs[4];
$nom = trim($champs[4]);
} else {
$flore[$champs[1]] = $nom." ".$champs[4];
}
}
}
$info = $this->dao->integrerFlore($flore, 'fournier');
$this->traiterErreur($info);
}
fclose($fichierOuvert);
} else {
$this->traiterErreur("Le fichier {$fichier} n'existe pas.");
}
}
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier flore florenbi qui contient tous codes, numéro et nom fournier
// /opt/lampp/bin/php cli.php sophy/insertionflore -a florenbi -n ./../donnees/sophy/2010-12-02/FLORE/FLORENBI
private function executerBdnff() {
$nomFichier = $this->dossier.'bdnffv5.csv';
if (file_exists($nomFichier) === true) {
$this->dao->chargerDonnees($nomFichier, 'sophy_bdnff');
} else {
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas.");
}
}
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier flore listePla qui contient numéro de fournier, nom de fournier, numéro bdnff, nom bdnff
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a listepla -n ./../doc/jeux_test/FLORE/LISTEPLA.csv
private function executerListePla() {
// Parcours le fichier .csv et enregistre chaque ligne dans un tableau.
$nomFichier = $this->dossier.'LISTEPLA.csv';
if ($nomFichier && file_exists($nomFichier) ){
$extensionFichier = strtolower(strrchr($nomFichier, '.'));
if ($extensionFichier === ".csv"){
$file = new SplFileObject($nomFichier);
$file->setFlags(SplFileObject::SKIP_EMPTY);
$i = 0;
echo "Traitement de LISTEPLA : ";
while (!$file->eof()){
$flore = $this->transformerFournierBdnff($file->fgetcsv());
echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++;
}
echo "\n";
//$info = $this->dao->integrerFlore($this->flore['bdnff'], 'bdnff');
$info .= $this->dao->integrerFlore($this->flore['correspondance'], 'fournier_bdnff');
$this->traiterErreur($info);
} else {
$this->traiterErreur("Le fichier $nomFichier n'est pas au format csv.");
}
} else {
$this->traiterErreur("Le fichier $nomFichier n'existe pas.");
}
}
private function transformerFournierBdnff($ligne_csv){
//$this->flore['bdnff'][$ligne_csv[5]] = $ligne_csv[6];
$this->flore['correspondance'][$ligne_csv[3]] = $ligne_csv[5];
}
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier flore floeur.bis qui contient numéro et nom de flora europea
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a floeur -n ./../doc/jeux_test/FLORE/FLOEUR.BIS
private function executerFloeur() {
$nomFichier = $this->dossier.'FLOEUR.BIS';
if (file_exists($nomFichier) === true) {
if ( $fichierOuvert = fopen($nomFichier, 'r') ) {
$i = 0;
while ($ligne = fgets($fichierOuvert)) {
if (preg_match('/^\s[\d\s]{9}[\d\sA-Z]\s([\d\s]{4}\d)\s(.{71})[\s\d]{2}/', $ligne, $champs)) {
$this->flore[$champs[1]] = trim($champs[2]);
}
}
$info = $this->dao->integrerFlore($this->flore, 'flora_europea');
$this->traiterErreur($info);
}
fclose($fichierOuvert);
} else {
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas.");
}
}
 
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier flore codebry qui contient numéro et nom des bryophytes
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a bryo -n ./../doc/jeux_test/FLORE/codebry.txt
private function executerBryo() {
$nomFichier = $this->dossier.'codebry.txt';
if (file_exists($nomFichier) === true) {
if ( $fichierOuvert = fopen($nomFichier, 'r') ) {
$i = 0;
while ($ligne = fgets($fichierOuvert)) {
if (preg_match('/^\s([\d\s]{4})\s[\d\s][\d\s]{4}\s{2}\d\s*(.*)\s[\d\s]{4}/', $ligne, $champs)) {
if ($champs[1] != 0) {
$this->flore[$champs[1]] = trim($champs[2]);
}
}
}
$info = $this->dao->integrerFlore($this->flore, 'bryophyte');
$this->traiterErreur($info);
}
fclose($fichierOuvert);
} else {
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas.");
}
}
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier flore Syntri qui contient numéro de fournier, numéro syntri, nom syntri
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a syntri -n ./../doc/jeux_test/FLORE/SYNTRI.TXT
private function executerSyntri() {
$nomFichier = $this->dossier.'SYNTRI.TXT';
if (file_exists($nomFichier) === true) {
if ( $fichierOuvert = fopen($nomFichier, 'r') ) {
$i = 0;
while ($ligne = fgets($fichierOuvert)) {
if (preg_match('/^(\d+)\s{2}\d\s([A-Z,\-\'\.()\s]+[A-Z,\-\'\.()])\s+([\d\s]+)$/', trim($ligne), $champs)) {
$syntri = preg_split('/\s+/', $champs[3]);
if (count($syntri) == 3) {
$num = $syntri[1];
} elseif (count($syntri) == 1){
$num = $syntri[0];
}
if (isset($flore['correspondance'][$num])) {
$flore['syntri'][$num] = $flore['syntri'][$num].$champs[2];
} else {
$flore['correspondance'][$num] = $champs[1];
$flore['syntri'][$num] = $champs[2];
}
$i++;
}
}
$info = $this->dao->integrerFlore($flore['syntri'], 'syntri');
$info .= $this->dao->integrerFlore($flore['correspondance'], 'syntri_fournier');
$this->traiterErreur($info);
}
fclose($fichierOuvert);
} else {
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas.");
}
}
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a ciff -n ./../doc/jeux_test/FLORE/ciff.txt
private function executerCiff() {
$nomFichier = $this->dossier.'ciff.txt';
if (file_exists($nomFichier) === true) {
if ( $fichierOuvert = fopen($nomFichier, 'r') ) {
$i = 0;
while ($ligne = fgets($fichierOuvert)) {
if (preg_match('/^(\d*)\t([A-Za-z].*)\t(\d*)\t\d*/', $ligne, $champs)) {
$flore['ciff'][$champs[1]] = $champs[2];
if ($champs[3] != '') {
$flore['correspondance'][$champs[1]] = $champs[3];
}
}
}
$info = $this->dao->integrerFlore($flore['ciff'], 'ciff');
$info .= $this->dao->integrerFlore($flore['correspondance'], 'ciff_bdnff');
$this->traiterErreur($info);
}
fclose($fichierOuvert);
} else {
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas.");
}
}
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier flore donneebb.tri qui contient le numero tax t numero nomenclatural de la bdnff
// num_tax||num_nom||num_nom_retenu||?||nom
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a donneebb -n ./../doc/jeux_test/FLORE/donneebb.tri
private function executerDonneebb() {
$nomFichier = $this->dossier.'donneebb.tri';
if (file_exists($nomFichier) === true) {
if ( $fichierOuvert = fopen($nomFichier, 'r') ) {
while ($ligne = fgets($fichierOuvert)) {
if (preg_match('/^([\d\s]{4}\d)\|([\d\s]{5})\|([\d\s]{5})\|/', $ligne, $champs)) {
if (!isset($this->flore[$champs[1]])) {
$this->flore[$champs[2]]['num_tax'] = $champs[1];
if (trim($champs[3]) != '') {
$this->flore[$champs[2]]['num_nom_retenu'] = $champs[3];
} else {
$this->flore[$champs[2]]['num_nom_retenu'] = $champs[2];
}
}
}
}
$info = $this->dao->ajouterColonnes($this->flore, 'sophy_bdnff');
$this->traiterErreur($info);
}
fclose($fichierOuvert);
} else {
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas.");
}
}
// +-------------------------------------------------------------------------------------------------------------------+
// Traitement du fichier flore codefr94 qui contient numéro et nom codefr94
// /opt/lampp/bin/php -d memory_limit=2048M cli.php insertionFlore -a ciff -n ./../doc/jeux_test/FLORE/CODEFR94
private function executerCodefr() {
$nomFichier = $this->dossier.'CODEFR94';
if (file_exists($nomFichier) === true) {
if ( $fichierOuvert = fopen($nomFichier, 'r') ) {
$i = 0;
while ($ligne = fgets($fichierOuvert)) {
if (preg_match('/^([\d\s]{5})[\d\s]{7}(.*)/', $ligne, $champs)) {
$flore[$champs[1]] = trim($champs[2]);
}
}
$info = $this->dao->integrerFlore($flore, 'codefr94');
$this->traiterErreur($info);
}
fclose($fichierOuvert);
} else {
$this->traiterErreur("Le fichier {$nomFichier} n'existe pas.");
}
}
}
/tags/v5.7-arrayanal/scripts/modules/sophy/insertion.ini
New file
0,0 → 1,20
; +------------------------------------------------------------------------------------------------------+
; Général
; Séparateur de dossier
ds = DIRECTORY_SEPARATOR
 
; +------------------------------------------------------------------------------------------------------+
; Info sur l'application
info.nom = Scripts de gestion de la phytosociologie
; Abréviation de l'application
info.abr = sophy
; Version du Framework nécessaire au fonctionnement de cette application
info.framework.version = 0.2
;Encodage de l'application
appli_encodage = "UTF-8"
version="2010-12-02"
dossierSql = "{ref:dossierDonneesEflore}{ref:info.abr}/{ref:version}/"
[fichiers]
structureSql = "sophy.sql"
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
/tags/v5.7-arrayanal/scripts/modules/sophy/bibliotheque/FloreDao.php
New file
0,0 → 1,74
<?php
class FloreDao extends Bdd {
 
public function integrerFlore($flore, $nom_flore){
$flore = array_map(array($this, 'proteger'), $flore);
$requete = "INSERT INTO sophy_{$nom_flore} VALUES ";
$i = 0; $j = 1000; $info = '';
foreach ($flore as $num => $nom) {
if ($i < $j) {
$requete .= " ({$num}, {$nom}), ";
} else {
$requete = substr($requete,0,-2).";";
$resultat = $this->requeter($requete);
if ($resultat === false) {
$info .= $nom_flore.$j." n'est pas intégrée.\n";
} else {
$info .= $nom_flore.$j." est intégrée.\n";
}
$j += 1000;
$requete = "INSERT INTO sophy_{$nom_flore} VALUES ({$num}, {$nom}), ";
}
$i++;
}
$requete = substr($requete,0,-2).";";
$resultat = $this->requeter($requete);
if ($resultat === false) {
$info .= $nom_flore.$i." n'est pas intégrée.\n";
//echo $requete."\n";
} else {
$info .= $nom_flore.$i." est intégrée.\n";
}
return $info;
}
public function chargerDonnees($fichier, $table) {
$requete = "LOAD DATA INFILE '$fichier' ".
"REPLACE INTO TABLE $table ".
"CHARACTER SET utf8 ".
"FIELDS
TERMINATED BY ','";
$this->requeter($requete);
}
public function ajouterColonnes($donnees, $table) {
$this->preparerTable($table, 'sb_num_nom_retenu');
$this->preparerTable($table, 'sb_num_tax');
$this->lancerRequeteModification($table, $donnees);
}
private function preparerTable($table, $colonne) {
$requete = "SHOW COLUMNS FROM {$table} LIKE '{$colonne}' ";
$resultat = $this->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$table} ".
"ADD {$colonne} INT(5) ";
$this->requeter($requete);
}
}
private function lancerRequeteModification($table, $flore) {
foreach ($flore as $num_nom => $info) {
$requete = "UPDATE {$table} ".
"SET sb_num_nom_retenu = {$info['num_nom_retenu']} ".
", sb_num_tax = {$info['num_tax']} ".
"WHERE sb_id_num_bdnff = $num_nom ";//echo $requete."\n";
$res = $this->requeter($requete);
if ($res === false) {
$this->traiterErreur("erreur d'insertion pour le tuple %s", array($id));
}
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/sophy/bibliotheque/TaxonDao.php
New file
0,0 → 1,279
<?php
class TaxonDao extends Bdd {
// tableau de la forme $taxons[num][flore][id]
// $taxons[num][flore][nom]
protected $taxons = array();
private $id = 0;
private $flores = array('syntri', 'ciff', 'codefr94', 'bdnff', 'bryo', 'floeur', 'algues', 'characees', 'lichen', 'fournier');
private $table_flores = array('bdnff', 'fournier', 'ciff', 'syntri', 'codefr94', 'bryo', 'floeur');
public function __construct() {
Bdd::__construct();
$this->id = $this->chargerId() + 1;
$this->taxons = $this->chargerTaxon();
}
// recherche si un taxon existe sinon le crée et renvoie son id
public function getId($num_taxon, $flore = 'ind', $nom = null, $flore_supp = null, $num_supp = null, $remarques = '') {
$idTaxon = null; $nom_supp = $nom;
if ($nom == null && $remarques != '') {
$nom = "rem:".$flore_supp.$num_supp.'/'.$remarques;
}
 
if (isset($this->taxons['ind'][$nom]['id'])) {
$idTaxon = $this->taxons['ind'][$nom]['id'];
} elseif (isset($this->taxons[$flore][$num_taxon]['id']) && $nom == null) {
$idTaxon = $this->taxons[$flore][$num_taxon]['id'];
} else {
$idTaxon = $this->ajouterTaxon($num_taxon, $flore, $nom_supp, $flore_supp, $num_supp, $remarques);
}
return $idTaxon;
}
 
// renvoie un nom d'apres son id
public function getNom($id) {
foreach ($this->taxons['ind'] as $nom=>$param) {
if ($param['id'] === $id) {
if (preg_match('/rem:[a-z]+\d+\/(.*)/', $nom, $match)) {
$nom = $match[1];
}
return $nom;
}
}
return '';
}
// Ajoute taxon avec pour clé le numéro taxon, le nom ou la remarque
public function ajouterTaxon($num_taxon, $flore, $nom, $flore_supp, $num_supp, $remarques) {
if ($nom != null) {
$cle = 'ind';
$num = $nom;
} elseif ($remarques != '') {
$cle = 'ind';
$num = "rem:".$flore_supp.$num_supp.'/'.$remarques;
} else {
$cle = $flore;
$num = $num_taxon;
}
$this->taxons[$cle][$num]['id'] = $this->id;
foreach ($this->flores as $nom_flore) {
if ($nom_flore == $flore) {
$this->taxons[$cle][$num][$nom_flore] = $num_taxon;
} elseif ($nom_flore == $flore_supp) {
$this->taxons[$cle][$num][$nom_flore] = $num_supp;
} else {
$this->taxons[$cle][$num][$nom_flore] = 'NULL';
}
}
$this->taxons[$cle][$num]['nom'] = $this->ajouterNomTaxon($num_taxon, $flore, $nom, $flore_supp, $num_supp);
$this->taxons[$cle][$num]['remarques'] = $remarques;
$this->id++;
return $this->taxons[$cle][$num]['id'];
}
public function ajouterNomTaxon($num_taxon, $flore, $nom_supp, $flore_supp, $num_supp) {
$nom = '';
$nomCherche = false;
foreach ($this->table_flores as $nom_flore) {
if ($nomCherche == false) {
if ($nom_flore == $flore) {
$nom = $this->rechercherNomTaxon($nom_flore, $num_taxon);
if ($nom != false) {
$nomCherche = true;
}
} elseif ($nom_flore == $flore_supp) {
$nom = $this->rechercherNomTaxon($nom_flore, $num_supp);
if ($nom != false) {
$nomCherche = true;
}
}
}
}
if ($nom == false && $nom_supp != null) {
$nom = $nom_supp;
} elseif ($nom == '' && $nom_supp != null) {
$nom = $nom_supp;
}
return $nom;
}
public function rechercherNomTaxon($nom_flore, $num_taxon) {
$requete2 = null;
switch ($nom_flore) {
case 'bdnff' :
$requete = "SELECT sb_nom_complet AS nom FROM sophy_bdnff
WHERE sb_num_tax = {$num_taxon} AND sb_id_num_bdnff = sb_num_nom_retenu; ";
break;
case 'fournier' :
$requete = "SELECT sb_nom_complet AS nom FROM sophy_bdnff, sophy_fournier_bdnff
WHERE sfb_id_num_fournier = {$num_taxon} AND sb_num_tax = sfb_id_num_bdnff AND sb_id_num_bdnff = sb_num_nom_retenu;";
$requete2 = "SELECT sf_nom_fournier AS nom FROM sophy_fournier WHERE sf_id_num_fournier = {$num_taxon};";
break;
case 'ciff' :
$requete = "SELECT sb_nom_complet AS nom
FROM sophy_bdnff, sophy_ciff_bdnff
WHERE scb_id_num_ciff = {$num_taxon} AND scb_id_num_bdnff = sb_id_num_bdnff;";
$requete2 = "SELECT sci_nom_ciff AS nom FROM sophy_ciff WHERE sci_id_num_ciff = {$num_taxon};";
break;
case 'syntri' :
$requete = "SELECT sb_nom_complet AS nom
FROM sophy_bdnff, sophy_syntri_fournier, sophy_fournier_bdnff
WHERE ssf_id_num_syntri = {$num_taxon} AND ssf_id_num_fournier = sfb_id_num_fournier
AND sb_num_tax = sfb_id_num_bdnff AND sb_id_num_bdnff = sb_num_nom_retenu;";
$requete2 = "SELECT ssyn_nom_supp AS nom FROM sophy_syntri WHERE ssyn_id_num_supp = {$num_taxon};";
break;
case 'codefr94' :
$requete = "SELECT sc_nom_codefr AS nom FROM sophy_codefr94 WHERE sc_id_num_codefr = {$num_taxon};";
break;
case 'bryo' :
$requete = "SELECT sbr_nom_bryo AS nom FROM sophy_bryophyte WHERE sbr_id_num_bryo = {$num_taxon};";
break;
case 'floeur' :
$requete = "SELECT sfe_nom_floeur AS nom FROM sophy_flora_europea WHERE sfe_id_num_floeur = {$num_taxon};";
break;
}
$resultat_requete = $this->recuperer($requete);
if ($resultat_requete['nom'] == false && $requete2 != null) {
$resultat_requete = $this->recuperer($requete2);
}
return $resultat_requete['nom'];
}
// recherche le dernier id de la base
public function chargerId() {
$id = 0;
$requete_select_id = "SELECT MAX(st_id_taxon) AS idMax FROM sophy_taxon;";
$resultat_requete_id = $this->recuperer($requete_select_id);
if ($resultat_requete_id['idMax'] != false) {
$id = $resultat_requete_id['idMax'];
}
return $id;
}
// Regarde si il y a des taxons dans la base, retourne le tableau de valeur et vide la base
public function chargerTaxon() {
$resultat = null;
$retour = null;
$requete_select = "SELECT * FROM sophy_taxon;";
$resultat = $this->recupererTous($requete_select);
if ($resultat != false) {
foreach ($resultat as $result) {
if ($result['st_nom_supp'] != null) {
$retour['ind'][$result['st_nom_supp']]['id'] = $result['st_id_taxon'];
foreach ($this->flores as $nom_flore) {
$retour['ind'][$result['st_nom_supp']][$nom_flore] = $result["st_ce_num_".$nom_flore];
}
$retour['ind'][$result['st_nom_supp']]['remarques'] = $result['st_nom_supp'];
} elseif ($result['st_remarques'] != null) {
$nom = $result['st_remarques'];
$retour['ind'][$nom]['id'] = $result['st_id_taxon'];
foreach ($this->flores as $nom_flore) {
$retour['ind'][$result['st_nom_supp']][$nom_flore] = $result["st_ce_num_".$nom_flore];
}
$retour['ind'][$nom]['remarques'] = $result['st_nom_supp'];
} elseif ($result['st_ce_num_syntri'] != null) {
$retour['syntri'][$result['st_ce_num_syntri']]['id'] = $result['st_id_taxon'];
$retour['syntri'][$result['st_ce_num_syntri']]['num_supp'] = $result['st_num_supp'];
} elseif ($result['st_ce_num_floeur'] != null) {
$retour['floeur'][$result['st_ce_num_floeur']]['id'] = $result['st_id_taxon'];
} elseif ($result['st_ce_num_bdnff'] != null) {
$retour['bdnff'][$result['st_ce_num_bdnff']]['id'] = $result['st_id_taxon'];
} elseif ($result['st_ce_num_codefr94'] != null) {
$retour['codefr94'][$result['st_ce_num_codefr94']]['id'] = $result['st_id_taxon'];
} elseif ($result['st_ce_num_bryo'] != null) {
$retour['bryo'][$result['st_ce_num_bryo']]['id'] = $result['st_id_taxon'];
} elseif ($result['st_ce_num_ciff'] != null) {
$retour['ciff'][$result['st_ce_num_ciff']]['id'] = $result['st_id_taxon'];
} elseif ($result['st_ce_num_fournier'] != null) {
$retour['fournier'][$result['st_ce_num_fournier']]['id'] = $result['st_id_taxon'];
}
}
}
$requete = "TRUNCATE TABLE `sophy_taxon`; ";
$res = $this->requeter($requete);
return $retour;
}
// +-------------------------------------------------------------------------------------------------------------------+
// Requête sur table sophy_taxon et toutes les tables flore de sophy
public function integrerTaxons() {
foreach ($this->taxons as $flore=>$taxons) {
switch ($flore) {
case 'ind' :
// insertion par 1000 pour éviter que la requête soit trop lourde
$i = 0; $j = 1000;
$requete = "INSERT INTO `sophy_taxon` (`st_id_taxon`, `st_nom`, `st_nom_supp`,";
foreach ($this->flores as $nom_flore) {
$requete .= "st_ce_num_{$nom_flore}, ";
}
$requete .= " st_remarques) VALUES ";
foreach ($taxons as $taxon=>$valeur) {
if (!isset($valeur['remarques'])){
$valeur['remarques'] = 'NULL';
$taxon = $this->proteger($taxon);
} elseif (substr_compare($taxon, 'rem:', 0, 4) == 0){
$valeur['remarques'] = $this->proteger($taxon);
$taxon = 'NULL';
} else {
$taxon = $this->proteger($taxon);
$valeur['remarques'] = $this->proteger($valeur['remarques']);
}
if ($i < $j) {
$requete .= " (".$valeur['id'].", ".$this->proteger($valeur['nom']).", ".$taxon.", ";
foreach ($this->flores as $nom_flore) {
$requete .= $valeur[$nom_flore].", ";
}
$requete .= " ".$valeur['remarques']."),";
} elseif ($i == $j) {$j += 1000;
$requete = substr($requete,0,-1).";";
$resultat = $this->requeter($requete);
if ($resultat == false) {
echo $flore.' : '.$i;
}
$requete = "INSERT INTO `sophy_taxon` (`st_id_taxon`, `st_nom`, `st_nom_supp`,";
foreach ($this->flores as $nom_flore) {
$requete .= "st_ce_num_{$nom_flore}, ";
}
$requete .= " st_remarques) VALUES (".$valeur['id'].", ".$this->proteger($valeur['nom']).
", ".$taxon.", ";
foreach ($this->flores as $nom_flore) {
$requete .= $valeur[$nom_flore].", ";
}
$requete .= " ".$valeur['remarques']."),";
}
$i++;
}
$requete = substr($requete,0,-1).";";
break;
case 'syntri' :
$i = 0;
$requete = "INSERT INTO `sophy_taxon` (`st_id_taxon`, ";
foreach ($this->flores as $nom_flore) {
$requete .= "st_ce_num_{$nom_flore}, ";
}
$requete .= "`st_nom`) VALUES ";
foreach ($taxons as $taxon=>$valeur) {
$requete .= " (".$valeur['id'].", ";
foreach ($this->flores as $nom_flore) {
$requete .= $valeur[$nom_flore].", ";
}
$requete .= $this->proteger($valeur['nom'])."), ";
}
$requete = substr($requete,0,-2).";";
break;
default:
$requete = "INSERT INTO `sophy_taxon` (`st_id_taxon`, `st_nom`, st_ce_num_{$flore}) VALUES ";
foreach ($taxons as $numTaxon=>$valeur) {
$requete .= " (".$valeur['id'].", ".$this->proteger($valeur['nom']).", ".$numTaxon."),";
}
$requete = substr($requete,0,-1).";";
break;
}
$resultat = $this->requeter($requete);
if ($resultat == false) {
echo " - flore : ".$flore;
}
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/sophy/bibliotheque/gPoint.php
New file
0,0 → 1,534
<?php
/*------------------------------------------------------------------------------
** File: gPoint.php
** Description: PHP class to convert Latitude & Longitude coordinates into
** UTM & Lambert Conic Conformal Northing/Easting coordinates.
** Version: 1.3
** Author: Brenor Brophy
** Email: brenor dot brophy at gmail dot com
** Homepage: brenorbrophy.com
**------------------------------------------------------------------------------
** COPYRIGHT (c) 2005, 2006, 2007, 2008 BRENOR BROPHY
**
** The source code included in this package is free software; you can
** redistribute it and/or modify it under the terms of the GNU General Public
** License as published by the Free Software Foundation. This license can be
** read at:
**
** http://www.opensource.org/licenses/gpl-license.php
**
** This program is distributed in the hope that it will be useful, but WITHOUT
** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
** FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
**------------------------------------------------------------------------------
**
** Code for datum and UTM conversion was converted from C++ code written by
** Chuck Gantz (chuck dot gantz at globalstar dot com) from
** http://www.gpsy.com/gpsinfo/geotoutm/ This URL has many other references to
** useful information concerning conversion of coordinates.
**
** Rev History
** -----------------------------------------------------------------------------
** 1.0 08/25/2005 Initial Release
** 1.1 05/15/2006 Added software license language to header comments
** Fixed an error in the convertTMtoLL() method. The latitude
** calculation had a bunch of variables without $ symbols.
** Fixed an error in convertLLtoTM() method, The $this-> was
** missing in front of a couple of variables. Thanks to Bob
** Robins of Maryland for catching the bugs.
** 1.2 05/18/2007 Added default of NULL to $LongOrigin arguement in convertTMtoLL()
** and convertLLtoTM() to eliminate warning messages when the
** methods are called without a value for $LongOrigin.
** 1.3 02/21/2008 Fixed a bug in the distanceFrom method, where the input parameters
** were not being converted to radians prior to calculating the
** distance. Thanks to Enrico Benco for finding pointing it out.
*/
define ("meter2nm", (1/1852));
define ("nm2meter", 1852);
 
/*------------------------------------------------------------------------------
** class gPoint ... for Geographic Point
**
** This class encapsulates the methods for representing a geographic point on the
** earth in three different coordinate systema. Lat/Long, UTM and Lambert Conic
** Conformal.
*/
class gPoint
{
/* Reference ellipsoids derived from Peter H. Dana's website-
** http://www.colorado.edu/geography/gcraft/notes/datum/datum_f.html
** email: pdana@pdana.com, web page: www.pdana.com
**
** Source:
** Defense Mapping Agency. 1987b. DMA Technical Report: Supplement to Department
** of Defense World Geodetic System 1984 Technical Report. Part I and II.
** Washington, DC: Defense Mapping Agency
*/
var $ellipsoid = array(//Ellipsoid name, Equatorial Radius, square of eccentricity
"Airy" =>array (6377563, 0.00667054),
"Australian National" =>array (6378160, 0.006694542),
"Bessel 1841" =>array (6377397, 0.006674372),
"Bessel 1841 Nambia" =>array (6377484, 0.006674372),
"Clarke 1866" =>array (6378206, 0.006768658),
"Clarke 1880" =>array (6378249, 0.006803511),
"Everest" =>array (6377276, 0.006637847),
"Fischer 1960 Mercury" =>array (6378166, 0.006693422),
"Fischer 1968" =>array (6378150, 0.006693422),
"GRS 1967" =>array (6378160, 0.006694605),
"GRS 1980" =>array (6378137, 0.00669438),
"Helmert 1906" =>array (6378200, 0.006693422),
"Hough" =>array (6378270, 0.00672267),
"International" =>array (6378388, 0.00672267),
"Krassovsky" =>array (6378245, 0.006693422),
"Modified Airy" =>array (6377340, 0.00667054),
"Modified Everest" =>array (6377304, 0.006637847),
"Modified Fischer 1960" =>array (6378155, 0.006693422),
"South American 1969" =>array (6378160, 0.006694542),
"WGS 60" =>array (6378165, 0.006693422),
"WGS 66" =>array (6378145, 0.006694542),
"WGS 72" =>array (6378135, 0.006694318),
"WGS 84" =>array (6378137, 0.00669438));
 
// Properties
var $a; // Equatorial Radius
var $e2; // Square of eccentricity
var $datum; // Selected datum
var $Xp, $Yp; // X,Y pixel location
var $lat, $long; // Latitude & Longitude of the point
var $utmNorthing, $utmEasting, $utmZone; // UTM Coordinates of the point
var $lccNorthing, $lccEasting; // Lambert coordinates of the point
var $falseNorthing, $falseEasting; // Origin coordinates for Lambert Projection
var $latOfOrigin; // For Lambert Projection
var $longOfOrigin; // For Lambert Projection
var $firstStdParallel; // For lambert Projection
var $secondStdParallel; // For lambert Projection
 
// constructor
function gPoint($datum='WGS 84') // Default datum is WGS 84
{
$this->a = $this->ellipsoid[$datum][0]; // Set datum Equatorial Radius
$this->e2 = $this->ellipsoid[$datum][1]; // Set datum Square of eccentricity
$this->datum = $datum; // Save the datum
}
//
// Set/Get X & Y pixel of the point (used if it is being drawn on an image)
//
function setXY($x, $y)
{
$this->Xp = $x; $this->Yp = $y;
}
function Xp() { return $this->Xp; }
function Yp() { return $this->Yp; }
//
// Set/Get/Output Longitude & Latitude of the point
//
function setLongLat($long, $lat)
{
$this->long = $long; $this->lat = $lat;
}
function Lat() { return $this->lat; }
function Long() { return $this->long; }
function printLatLong() { printf("Latitude: %1.5f Longitude: %1.5f",$this->lat, $this->long); }
//
// Set/Get/Output Universal Transverse Mercator Coordinates
//
function setUTM($easting, $northing, $zone='') // Zone is optional
{
$this->utmNorthing = $northing;
$this->utmEasting = $easting;
$this->utmZone = $zone;
}
function N() { return $this->utmNorthing; }
function E() { return $this->utmEasting; }
function Z() { return $this->utmZone; }
function printUTM() { print( "Northing: ".(int)$this->utmNorthing.", Easting: ".(int)$this->utmEasting.", Zone: ".$this->utmZone); }
//
// Set/Get/Output Lambert Conic Conformal Coordinates
//
function setLambert($easting, $northing)
{
$this->lccNorthing = $northing;
$this->lccEasting = $easting;
}
function lccN() { return $this->lccNorthing; }
function lccE() { return $this->lccEasting; }
function printLambert() { print( "Northing: ".(int)$this->lccNorthing.", Easting: ".(int)$this->lccEasting); }
 
//------------------------------------------------------------------------------
//
// Convert Longitude/Latitude to UTM
//
// Equations from USGS Bulletin 1532
// East Longitudes are positive, West longitudes are negative.
// North latitudes are positive, South latitudes are negative
// Lat and Long are in decimal degrees
// Written by Chuck Gantz- chuck dot gantz at globalstar dot com, converted to PHP by
// Brenor Brophy, brenor dot brophy at gmail dot com
//
// UTM coordinates are useful when dealing with paper maps. Basically the
// map will can cover a single UTM zone which is 6 degrees on longitude.
// So you really don't care about an object crossing two zones. You just get a
// second map of the other zone. However, if you happen to live in a place that
// straddles two zones (For example the Santa Babara area in CA straddles zone 10
// and zone 11) Then it can become a real pain having to have two maps all the time.
// So relatively small parts of the world (like say California) create their own
// version of UTM coordinates that are adjusted to conver the whole area of interest
// on a single map. These are called state grids. The projection system is the
// usually same as UTM (i.e. Transverse Mercator), but the central meridian
// aka Longitude of Origin is selected to suit the logitude of the area being
// mapped (like being moved to the central meridian of the area) and the grid
// may cover more than the 6 degrees of lingitude found on a UTM map. Areas
// that are wide rather than long - think Montana as an example. May still
// have to have a couple of maps to cover the whole state because TM projection
// looses accuracy as you move further away from the Longitude of Origin, 15 degrees
// is usually the limit.
//
// Now, in the case where we want to generate electronic maps that may be
// placed pretty much anywhere on the globe we really don't to deal with the
// issue of UTM zones in our coordinate system. We would really just like a
// grid that is fully contigious over the area of the map we are drawing. Similiar
// to the state grid, but local to the area we are interested in. I call this
// Local Transverse Mercator and I have modified the function below to also
// make this conversion. If you pass a Longitude value to the function as $LongOrigin
// then that is the Longitude of Origin that will be used for the projection.
// Easting coordinates will be returned (in meters) relative to that line of
// longitude - So an Easting coordinate for a point located East of the longitude
// of origin will be a positive value in meters, an Easting coordinate for a point
// West of the longitude of Origin will have a negative value in meters. Northings
// will always be returned in meters from the equator same as the UTM system. The
// UTMZone value will be valid for Long/Lat given - thought it is not meaningful
// in the context of Local TM. If a NULL value is passed for $LongOrigin
// then the standard UTM coordinates are calculated.
//
function convertLLtoTM($LongOrigin = NULL)
{
$k0 = 0.9996;
$falseEasting = 0.0;
 
//Make sure the longitude is between -180.00 .. 179.9
$LongTemp = ($this->long+180)-(integer)(($this->long+180)/360)*360-180; // -180.00 .. 179.9;
$LatRad = deg2rad($this->lat);
$LongRad = deg2rad($LongTemp);
 
if (!$LongOrigin)
{ // Do a standard UTM conversion - so findout what zone the point is in
$ZoneNumber = (integer)(($LongTemp + 180)/6) + 1;
// Special zone for South Norway
if( $this->lat >= 56.0 && $this->lat < 64.0 && $LongTemp >= 3.0 && $LongTemp < 12.0 ) // Fixed 1.1
$ZoneNumber = 32;
// Special zones for Svalbard
if( $this->lat >= 72.0 && $this->lat < 84.0 )
{
if( $LongTemp >= 0.0 && $LongTemp < 9.0 ) $ZoneNumber = 31;
else if( $LongTemp >= 9.0 && $LongTemp < 21.0 ) $ZoneNumber = 33;
else if( $LongTemp >= 21.0 && $LongTemp < 33.0 ) $ZoneNumber = 35;
else if( $LongTemp >= 33.0 && $LongTemp < 42.0 ) $ZoneNumber = 37;
}
$LongOrigin = ($ZoneNumber - 1)*6 - 180 + 3; //+3 puts origin in middle of zone
//compute the UTM Zone from the latitude and longitude
$this->utmZone = sprintf("%d%s", $ZoneNumber, $this->UTMLetterDesignator());
// We also need to set the false Easting value adjust the UTM easting coordinate
$falseEasting = 500000.0;
}
$LongOriginRad = deg2rad($LongOrigin);
 
$eccPrimeSquared = ($this->e2)/(1-$this->e2);
 
$N = $this->a/sqrt(1-$this->e2*sin($LatRad)*sin($LatRad));
$T = tan($LatRad)*tan($LatRad);
$C = $eccPrimeSquared*cos($LatRad)*cos($LatRad);
$A = cos($LatRad)*($LongRad-$LongOriginRad);
 
$M = $this->a*((1 - $this->e2/4 - 3*$this->e2*$this->e2/64 - 5*$this->e2*$this->e2*$this->e2/256)*$LatRad
- (3*$this->e2/8 + 3*$this->e2*$this->e2/32 + 45*$this->e2*$this->e2*$this->e2/1024)*sin(2*$LatRad)
+ (15*$this->e2*$this->e2/256 + 45*$this->e2*$this->e2*$this->e2/1024)*sin(4*$LatRad)
- (35*$this->e2*$this->e2*$this->e2/3072)*sin(6*$LatRad));
$this->utmEasting = ($k0*$N*($A+(1-$T+$C)*$A*$A*$A/6
+ (5-18*$T+$T*$T+72*$C-58*$eccPrimeSquared)*$A*$A*$A*$A*$A/120)
+ $falseEasting);
 
$this->utmNorthing = ($k0*($M+$N*tan($LatRad)*($A*$A/2+(5-$T+9*$C+4*$C*$C)*$A*$A*$A*$A/24
+ (61-58*$T+$T*$T+600*$C-330*$eccPrimeSquared)*$A*$A*$A*$A*$A*$A/720)));
if($this->lat < 0)
$this->utmNorthing += 10000000.0; //10000000 meter offset for southern hemisphere
}
//
// This routine determines the correct UTM letter designator for the given latitude
// returns 'Z' if latitude is outside the UTM limits of 84N to 80S
// Written by Chuck Gantz- chuck dot gantz at globalstar dot com, converted to PHP by
// Brenor Brophy, brenor dot brophy at gmail dot com
//
function UTMLetterDesignator()
{
if((84 >= $this->lat) && ($this->lat >= 72)) $LetterDesignator = 'X';
else if((72 > $this->lat) && ($this->lat >= 64)) $LetterDesignator = 'W';
else if((64 > $this->lat) && ($this->lat >= 56)) $LetterDesignator = 'V';
else if((56 > $this->lat) && ($this->lat >= 48)) $LetterDesignator = 'U';
else if((48 > $this->lat) && ($this->lat >= 40)) $LetterDesignator = 'T';
else if((40 > $this->lat) && ($this->lat >= 32)) $LetterDesignator = 'S';
else if((32 > $this->lat) && ($this->lat >= 24)) $LetterDesignator = 'R';
else if((24 > $this->lat) && ($this->lat >= 16)) $LetterDesignator = 'Q';
else if((16 > $this->lat) && ($this->lat >= 8)) $LetterDesignator = 'P';
else if(( 8 > $this->lat) && ($this->lat >= 0)) $LetterDesignator = 'N';
else if(( 0 > $this->lat) && ($this->lat >= -8)) $LetterDesignator = 'M';
else if((-8 > $this->lat) && ($this->lat >= -16)) $LetterDesignator = 'L';
else if((-16 > $this->lat) && ($this->lat >= -24)) $LetterDesignator = 'K';
else if((-24 > $this->lat) && ($this->lat >= -32)) $LetterDesignator = 'J';
else if((-32 > $this->lat) && ($this->lat >= -40)) $LetterDesignator = 'H';
else if((-40 > $this->lat) && ($this->lat >= -48)) $LetterDesignator = 'G';
else if((-48 > $this->lat) && ($this->lat >= -56)) $LetterDesignator = 'F';
else if((-56 > $this->lat) && ($this->lat >= -64)) $LetterDesignator = 'E';
else if((-64 > $this->lat) && ($this->lat >= -72)) $LetterDesignator = 'D';
else if((-72 > $this->lat) && ($this->lat >= -80)) $LetterDesignator = 'C';
else $LetterDesignator = 'Z'; //This is here as an error flag to show that the Latitude is outside the UTM limits
 
return($LetterDesignator);
}
 
//------------------------------------------------------------------------------
//
// Convert UTM to Longitude/Latitude
//
// Equations from USGS Bulletin 1532
// East Longitudes are positive, West longitudes are negative.
// North latitudes are positive, South latitudes are negative
// Lat and Long are in decimal degrees.
// Written by Chuck Gantz- chuck dot gantz at globalstar dot com, converted to PHP by
// Brenor Brophy, brenor dot brophy at gmail dot com
//
// If a value is passed for $LongOrigin then the function assumes that
// a Local (to the Longitude of Origin passed in) Transverse Mercator
// coordinates is to be converted - not a UTM coordinate. This is the
// complementary function to the previous one. The function cannot
// tell if a set of Northing/Easting coordinates are in the North
// or South hemesphere - they just give distance from the equator not
// direction - so only northern hemesphere lat/long coordinates are returned.
// If you live south of the equator there is a note later in the code
// explaining how to have it just return southern hemesphere lat/longs.
//
function convertTMtoLL($LongOrigin = NULL)
{
$k0 = 0.9996;
$e1 = (1-sqrt(1-$this->e2))/(1+sqrt(1-$this->e2));
$falseEasting = 0.0;
$y = $this->utmNorthing;
 
if (!$LongOrigin)
{ // It is a UTM coordinate we want to convert
sscanf($this->utmZone,"%d%s",$ZoneNumber,$ZoneLetter);
if($ZoneLetter >= 'N')
$NorthernHemisphere = 1;//point is in northern hemisphere
else
{
$NorthernHemisphere = 0;//point is in southern hemisphere
$y -= 10000000.0;//remove 10,000,000 meter offset used for southern hemisphere
}
$LongOrigin = ($ZoneNumber - 1)*6 - 180 + 3; //+3 puts origin in middle of zone
$falseEasting = 500000.0;
}
 
// $y -= 10000000.0; // Uncomment line to make LOCAL coordinates return southern hemesphere Lat/Long
$x = $this->utmEasting - $falseEasting; //remove 500,000 meter offset for longitude
 
$eccPrimeSquared = ($this->e2)/(1-$this->e2);
 
$M = $y / $k0;
$mu = $M/($this->a*(1-$this->e2/4-3*$this->e2*$this->e2/64-5*$this->e2*$this->e2*$this->e2/256));
 
$phi1Rad = $mu + (3*$e1/2-27*$e1*$e1*$e1/32)*sin(2*$mu)
+ (21*$e1*$e1/16-55*$e1*$e1*$e1*$e1/32)*sin(4*$mu)
+(151*$e1*$e1*$e1/96)*sin(6*$mu);
$phi1 = rad2deg($phi1Rad);
 
$N1 = $this->a/sqrt(1-$this->e2*sin($phi1Rad)*sin($phi1Rad));
$T1 = tan($phi1Rad)*tan($phi1Rad);
$C1 = $eccPrimeSquared*cos($phi1Rad)*cos($phi1Rad);
$R1 = $this->a*(1-$this->e2)/pow(1-$this->e2*sin($phi1Rad)*sin($phi1Rad), 1.5);
$D = $x/($N1*$k0);
 
$tlat = $phi1Rad - ($N1*tan($phi1Rad)/$R1)*($D*$D/2-(5+3*$T1+10*$C1-4*$C1*$C1-9*$eccPrimeSquared)*$D*$D*$D*$D/24
+(61+90*$T1+298*$C1+45*$T1*$T1-252*$eccPrimeSquared-3*$C1*$C1)*$D*$D*$D*$D*$D*$D/720); // fixed in 1.1
$this->lat = rad2deg($tlat);
 
$tlong = ($D-(1+2*$T1+$C1)*$D*$D*$D/6+(5-2*$C1+28*$T1-3*$C1*$C1+8*$eccPrimeSquared+24*$T1*$T1)
*$D*$D*$D*$D*$D/120)/cos($phi1Rad);
$this->long = $LongOrigin + rad2deg($tlong);
}
 
//------------------------------------------------------------------------------
// Configure a Lambert Conic Conformal Projection
//
// falseEasting & falseNorthing are just an offset in meters added to the final
// coordinate calculated.
//
// longOfOrigin & LatOfOrigin are the "center" latitiude and longitude of the
// area being projected. All coordinates will be calculated in meters relative
// to this point on the earth.
//
// firstStdParallel & secondStdParallel are the two lines of longitude (that
// is they run east-west) that define where the "cone" intersects the earth.
// Simply put they should bracket the area being projected.
//
// google is your friend to find out more
//
function configLambertProjection ($falseEasting, $falseNorthing,
$longOfOrigin, $latOfOrigin,
$firstStdParallel, $secondStdParallel)
{
$this->falseEasting = $falseEasting;
$this->falseNorthing = $falseNorthing;
$this->longOfOrigin = $longOfOrigin;
$this->latOfOrigin = $latOfOrigin;
$this->firstStdParallel = $firstStdParallel;
$this->secondStdParallel = $secondStdParallel;
}
 
//------------------------------------------------------------------------------
//
// Convert Longitude/Latitude to Lambert Conic Easting/Northing
//
// This routine will convert a Latitude/Longitude coordinate to an Northing/
// Easting coordinate on a Lambert Conic Projection. The configLambertProjection()
// function should have been called prior to this one to setup the specific
// parameters for the projection. The Northing/Easting parameters calculated are
// in meters (because the datum used is in meters) and are relative to the
// falseNorthing/falseEasting coordinate. Which in turn is relative to the
// Lat/Long of origin The formula were obtained from URL:
// http://www.ihsenergy.com/epsg/guid7_2.html.
// Code was written by Brenor Brophy, brenor dot brophy at gmail dot com
//
function convertLLtoLCC()
{
$e = sqrt($this->e2);
 
$phi = deg2rad($this->lat); // Latitude to convert
$phi1 = deg2rad($this->firstStdParallel); // Latitude of 1st std parallel
$phi2 = deg2rad($this->secondStdParallel); // Latitude of 2nd std parallel
$lamda = deg2rad($this->long); // Lonitude to convert
$phio = deg2rad($this->latOfOrigin); // Latitude of Origin
$lamdao = deg2rad($this->longOfOrigin); // Longitude of Origin
 
$m1 = cos($phi1) / sqrt(( 1 - $this->e2*sin($phi1)*sin($phi1)));
$m2 = cos($phi2) / sqrt(( 1 - $this->e2*sin($phi2)*sin($phi2)));
$t1 = tan((pi()/4)-($phi1/2)) / pow(( ( 1 - $e*sin($phi1) ) / ( 1 + $e*sin($phi1) )),$e/2);
$t2 = tan((pi()/4)-($phi2/2)) / pow(( ( 1 - $e*sin($phi2) ) / ( 1 + $e*sin($phi2) )),$e/2);
$to = tan((pi()/4)-($phio/2)) / pow(( ( 1 - $e*sin($phio) ) / ( 1 + $e*sin($phio) )),$e/2);
$t = tan((pi()/4)-($phi /2)) / pow(( ( 1 - $e*sin($phi ) ) / ( 1 + $e*sin($phi ) )),$e/2);
$n = (log($m1)-log($m2)) / (log($t1)-log($t2));
$F = $m1/($n*pow($t1,$n));
$rf = $this->a*$F*pow($to,$n);
$r = $this->a*$F*pow($t,$n);
$theta = $n*($lamda - $lamdao);
 
$this->lccEasting = $this->falseEasting + $r*sin($theta);
$this->lccNorthing = $this->falseNorthing + $rf - $r*cos($theta);
}
//------------------------------------------------------------------------------
//
// Convert Easting/Northing on a Lambert Conic projection to Longitude/Latitude
//
// This routine will convert a Lambert Northing/Easting coordinate to an
// Latitude/Longitude coordinate. The configLambertProjection() function should
// have been called prior to this one to setup the specific parameters for the
// projection. The Northing/Easting parameters are in meters (because the datum
// used is in meters) and are relative to the falseNorthing/falseEasting
// coordinate. Which in turn is relative to the Lat/Long of origin The formula
// were obtained from URL http://www.ihsenergy.com/epsg/guid7_2.html. Code
// was written by Brenor Brophy, brenor dot brophy at gmail dot com
//
function convertLCCtoLL()
{
$e = sqrt($this->e2);
 
$phi1 = deg2rad($this->firstStdParallel); // Latitude of 1st std parallel
$phi2 = deg2rad($this->secondStdParallel); // Latitude of 2nd std parallel
$phio = deg2rad($this->latOfOrigin); // Latitude of Origin
$lamdao = deg2rad($this->longOfOrigin); // Longitude of Origin
$E = $this->lccEasting;
$N = $this->lccNorthing;
$Ef = $this->falseEasting;
$Nf = $this->falseNorthing;
 
$m1 = cos($phi1) / sqrt(( 1 - $this->e2*sin($phi1)*sin($phi1)));
$m2 = cos($phi2) / sqrt(( 1 - $this->e2*sin($phi2)*sin($phi2)));
$t1 = tan((pi()/4)-($phi1/2)) / pow(( ( 1 - $e*sin($phi1) ) / ( 1 + $e*sin($phi1) )),$e/2);
$t2 = tan((pi()/4)-($phi2/2)) / pow(( ( 1 - $e*sin($phi2) ) / ( 1 + $e*sin($phi2) )),$e/2);
$to = tan((pi()/4)-($phio/2)) / pow(( ( 1 - $e*sin($phio) ) / ( 1 + $e*sin($phio) )),$e/2);
$n = (log($m1)-log($m2)) / (log($t1)-log($t2));
$F = $m1/($n*pow($t1,$n));
$rf = $this->a*$F*pow($to,$n);
$r_ = sqrt( pow(($E-$Ef),2) + pow(($rf-($N-$Nf)),2) );
$t_ = pow($r_/($this->a*$F),(1/$n));
$theta_ = atan(($E-$Ef)/($rf-($N-$Nf)));
 
$lamda = $theta_/$n + $lamdao;
$phi0 = (pi()/2) - 2*atan($t_);
$phi1 = (pi()/2) - 2*atan($t_*pow(((1-$e*sin($phi0))/(1+$e*sin($phi0))),$e/2));
$phi2 = (pi()/2) - 2*atan($t_*pow(((1-$e*sin($phi1))/(1+$e*sin($phi1))),$e/2));
$phi = (pi()/2) - 2*atan($t_*pow(((1-$e*sin($phi2))/(1+$e*sin($phi2))),$e/2));
$this->lat = rad2deg($phi);
$this->long = rad2deg($lamda);
}
 
//------------------------------------------------------------------------------
// This is a useful function that returns the Great Circle distance from the
// gPoint to another Long/Lat coordinate
//
// Result is returned as meters
//
function distanceFrom($lon1, $lat1)
{
$lon1 = deg2rad($lon1); $lat1 = deg2rad($lat1); // Added in 1.3
$lon2 = deg2rad($this->Long()); $lat2 = deg2rad($this->Lat());
$theta = $lon2 - $lon1;
$dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));
 
// Alternative formula supposed to be more accurate for short distances
// $dist = 2*asin(sqrt( pow(sin(($lat1-$lat2)/2),2) + cos($lat1)*cos($lat2)*pow(sin(($lon1-$lon2)/2),2)));
return ( $dist * 6366710 ); // from http://williams.best.vwh.net/avform.htm#GCF
}
 
//------------------------------------------------------------------------------
// This function also calculates the distance between two points. In this case
// it just uses Pythagoras's theorm using TM coordinates.
//
function distanceFromTM(&$pt)
{
$E1 = $pt->E(); $N1 = $pt->N();
$E2 = $this->E(); $N2 = $this->N();
$dist = sqrt(pow(($E1-$E2),2)+pow(($N1-$N2),2));
return $dist;
}
 
//------------------------------------------------------------------------------
// This function geo-references a geoPoint to a given map. This means that it
// calculates the x,y pixel coordinate that coresponds to the Lat/Long value of
// the geoPoint. The calculation is done using the Transverse Mercator(TM)
// coordinates of the gPoint with respect to the TM coordinates of the center
// point of the map. So this only makes sense if you are using Local TM
// projection.
//
// $rX & $rY are the pixel coordinates that corespond to the Northing/Easting
// ($rE/$rN) coordinate it is to this coordinate that the point will be
// geo-referenced. The $LongOrigin is needed to make sure the Easting/Northing
// coordinates of the point are correctly converted.
//
function gRef($rX, $rY, $rE, $rN, $Scale, $LongOrigin)
{
$this->convertLLtoTM($LongOrigin);
$x = (($this->E() - $rE) / $Scale) // The easting in meters times the scale to get pixels
// is relative to the center of the image so adjust to
+ ($rX); // the left coordinate.
$y = $rY - // Adjust to bottom coordinate.
(($rN - $this->N()) / $Scale); // The northing in meters
// relative to the equator. Subtract center point northing
// to get relative to image center and convert meters to pixels
$this->setXY((int)$x,(int)$y); // Save the geo-referenced result.
}
} // end of class gPoint
 
?>
/tags/v5.7-arrayanal/scripts/modules/sophy/bibliotheque/Dao.php
New file
0,0 → 1,175
<?php
class Dao extends Bdd {
 
// +-------------------------------------------------------------------------------------------------------------------+
// Requête d'intégration sur table sophy_publication
public function integrerBiblio($biblio){
$biblio = array_map(array($this, 'proteger'), $biblio);
$requete = 'INSERT INTO sophy_publication VALUES ('.implode(', ', $biblio).');';
$resultat = $this->requeter($requete);
if ($resultat === false) {
$info = $biblio['id_publi']." n'est pas intégrée.\n";
} else {
$info = $biblio['id_publi']." est intégrée.\n";
}
return $info;
}
// +-------------------------------------------------------------------------------------------------------------------+
// Requête d'intégration sur table sophy_tableau
public function integrerTableau($titre) {
$titre = array_map(array($this, 'proteger'), $titre);
$requete_integre_tableau = 'INSERT INTO sophy_tableau VALUES ('.implode(', ', $titre).');';
$reponse_requete_int_tab = $this->requeter($requete_integre_tableau);
if ($reponse_requete_int_tab === false) {
$info = "tableau ".$titre['numPubli']."-".$titre['numTableau']." non intégrée.";
} else {
$info = '';
}
return $info;
}
// +-------------------------------------------------------------------------------------------------------------------+
// Requêtes sur table sophy_station
// Requête d'intégration qui retourne l'id de la dernière station insérée (rechercheIdStation)
public function integrerStation($station) {
$station = array_map(array($this, 'proteger'), $station);
$reponse['id_station'] = null;
$requete_integre_station = 'INSERT INTO sophy_station (`ss_num_source`, `ss_poste_meteo`, `ss_localisation`,
`ss_latitude`, `ss_pays`, `ss_longitude`,`ss_code_departement`, `ss_altitude`, `ss_code_insee_commune`,
`ss_ce_precision_geographique`, `ss_systeme_projection`, `ss_latitude_dms`, `ss_longitude_dms`, `ss_latitude_wgs`,
`ss_longitude_wgs`, `ss_utmNorthing`, `ss_utmEasting`, `ss_utmZone`) VALUES
('.implode(', ', $station).');';
$reponse_requete_int_stat = $this->requeter($requete_integre_station);
if ($reponse_requete_int_stat === false) {
$reponse['info'] = "station ".$station['numSource']." non intégrée. $requete_integre_station";
} else {
$reponse['id_station'] = $this->rechercheIdStation();
$reponse['info'] = '';
}
return $reponse;
}
// Retourne le dernier identifiant de la table station
public function rechercheIdStation() {
$requete_select_id = "SELECT MAX(ss_id_station) as idMax FROM sophy_station;";
$resultat_requete_id = $this->recuperer($requete_select_id);
return $resultat_requete_id['idMax'];
}
public function rechercherCoordonneesWgs() {
$requete = "SELECT `ss_longitude_wgs` as longitude, `ss_latitude_wgs` as latitude
FROM `sophy_station`
GROUP BY `longitude` , `latitude`";
/* Les stations restantes avec coordonnées sans code insee
SELECT COUNT( * ) AS `Lignes` , `ss_longitude_wgs` , `ss_latitude_wgs`
FROM `sophy_station`
WHERE `ss_latitude_wgs` != ''
AND `ss_code_insee_calculee` =0
GROUP BY `ss_longitude_wgs` , `ss_latitude_wgs`
ORDER BY `Lignes` DESC
*/
$resultat = $this->recupererTous($requete);
return $resultat;
}
public function creerColonneCodeInseeCalculee() {
$create = "ALTER TABLE `sophy_station` ADD `ss_code_insee_calculee` VARCHAR( 5 ) NOT NULL ,
ADD INDEX ( `ss_code_insee_calculee` )";
$this->requeter($create);
}
public function ajouterCodeInseeCalculee($latitude, $longitude, $code_insee) {
$insert = "UPDATE `sophy_station` SET `ss_code_insee_calculee` = '$code_insee' ".
"WHERE ss_latitude_wgs = '$latitude' AND ss_longitude_wgs = '$longitude'";
$this->requeter($insert);
}
// +-------------------------------------------------------------------------------------------------------------------+
// Requête d'intégration sur table sophy_releve
public function integrerReleve($titre, $numReleve, $idStation) {
$requete_integre_releve = "INSERT INTO sophy_releve VALUES (".$titre['numPubli'].", ".
$titre['numTableau'].", ".$numReleve.", ".$idStation.");";
$reponse_requete_int_tab = $this->requeter($requete_integre_releve);
if ($reponse_requete_int_tab === false) {
$info = "releve ".$titre['numPubli']."-".$titre['numTableau']."-".$numReleve." non intégrée.";
echo $requete_integre_releve."\n";
} else {
$info = '';
}
return $info;
}
// +-------------------------------------------------------------------------------------------------------------------+
// Requête d'intégration sur table sophy_observation
public function integrerObservation($observations) {
$requete = "INSERT INTO `sophy_observation` (`so_id_publi`, `so_id_tableau`, `so_id_releve`, `so_num_ligne`,".
" `so_id_taxon`, `so_id_strate`, `so_ce_abondance`) VALUES ";
foreach ($observations as $plante) {
if (isset($plante)) {
foreach ($plante as $observation) {
$observation = array_map(array($this, 'proteger'), $observation);
$requete .= " (".implode(', ', $observation)." ),";
}
}
}
$requete = substr($requete,0,-1).";";
$resultat = $this->requeter($requete);
if ($resultat === false) {
echo $requete."\n";
$info = " n'est pas intégrée.\n";
} else {
$info = '';
}
return $info;
}
// +-------------------------------------------------------------------------------------------------------------------+
// Requête pour calculer les statistiques sur toutes les tables
public function getNombreLigne($tables) {
$requete = null;
foreach ($tables as $nomTable => $colonnes) {
$requete = "SELECT COUNT(*) as nombreTotal";
foreach ($colonnes as $recherche => $nom) {
$requete .= ", count(distinct {$recherche}) as {$nom}";
}
$requete .= " FROM {$nomTable}; ";
$resultat[$nomTable] = $this->recupererTous($requete);
}
return $resultat;
}
// +-------------------------------------------------------------------------------------------------------------------+
// Requête de création et d'insertion sur table sophy_tapir
public function creerTapir() {
$info = 'Créé';
$requete = "DROP TABLE IF EXISTS `sophy_tapir`;
CREATE table `sophy_tapir` AS
SELECT CONCAT(_utf8'urn:lsid:tela-botanica.org:sophy:',o.so_id_publi,'.',
o.so_id_tableau,'.',o.so_id_releve,'.',o.so_num_ligne,'.',
o.so_id_taxon,'.',o.so_id_strate) AS `guid`,
CONCAT(o.so_id_publi,'.',o.so_id_tableau,'.',o.so_id_releve,'.',
o.so_num_ligne,'.',o.so_id_taxon,'.',o.so_id_strate) AS `observation_id`,
p.sp_date AS observation_date,
t.st_nom AS nom_scientifique_complet,
CONCAT(s.ss_code_departement,s.ss_code_insee_commune) AS lieu_commune_code_insee,
s.ss_localisation AS `lieu_station_nom`,
s.ss_latitude_wgs AS `lieu_station_latitude`,
s.ss_longitude_wgs AS `lieu_station_longitude`,
s.ss_utmEasting AS `lieu_station_utm_est`,
s.ss_utmNorthing AS `lieu_station_utm_nord`,
s.ss_utmZone AS `lieu_station_utm_zone`,
p.sp_auteur AS observateur_nom_complet
FROM sophy_observation o LEFT JOIN sophy_taxon t ON (o.so_id_taxon = t.st_id_taxon)
LEFT JOIN sophy_releve r ON (r.sr_id_publi = o.so_id_publi AND r.sr_id_tableau = o.so_id_tableau AND r.sr_id_releve = o.so_id_releve )
LEFT JOIN sophy_station s ON (r.sr_id_station = s.ss_id_station)
LEFT JOIN sophy_publication p ON (r.sr_id_publi = p.sp_id_publi);";
$reponse = $this->requeter($requete);
if ($reponse === false) {
$info = "Erreur";
}
return $info;
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/cel/sphinx-maj.log
New file
0,0 → 1,39
Array
(
[no_nom_sel] => Array
(
[count] => 0
)
 
[not found] => Array
(
[count] => 6597
)
 
[too many] => Array
(
[count] => 1065
)
 
[fixable] => Array
(
[count] => 1448
)
 
[sauvages] => Array
(
[count] => 590
)
 
[sphinx errors] => Array
(
[count] => 0
)
 
[ref pb] => Array
(
[count] => 1543
)
 
)
total traité: 11243
/tags/v5.7-arrayanal/scripts/modules/cel/.current
New file
0,0 → 1,9
-- conserver ce fichier, il illustre les substitutions effectuées par le Makefile
-- et permet à celui-ci de déterminer et d'informer quelles bases seront utilisées/concernées par
-- les changements
BASEEDIT=`BASEEDIT`
BASEANNUAIRE=`BASEANNUAIRE`
BASESOURCE=`BASESOURCE`
TABLE_BDTFX=TABLEBDTFX
TABLE_BDTXA=TABLEBDTXA
TABLE_ISFAN=TABLEISFAN
/tags/v5.7-arrayanal/scripts/modules/cel/maj-referentiel-201307.sql
New file
0,0 → 1,78
/*
Mise à jour de réferentiels NULL ou vides pour les observations dotées d'un nom_sel_nn
75427 observations trouvées au 2013/07/19
 
Les observations problématiques sont les suivantes:
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, famille
FROM `BASEEDIT`.`cel_obs`
WHERE nom_referentiel IS NULL AND nom_sel != '' AND nom_sel IS NOT NULL AND nom_ret_nn IS NOT NULL;
 
Or maj-cleanup-201307.sql reset les valeurs des observations ayant un nom_sel NULL ou '', de plus la préférence de sélection est
donné au nom_sel (incluant les synonymes) plutôt que nom_ret_nn.
 
La requête est donc:
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, famille
FROM `BASEEDIT`.`cel_obs` WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL;
=> 76486
*/
 
 
DROP TEMPORARY TABLE IF EXISTS T_bis;
DROP PROCEDURE IF EXISTS majreferentiel;
 
CREATE TEMPORARY TABLE IF NOT EXISTS T_bis ( INDEX(`nom`(30))) AS \
SELECT "bdtfx" AS valid_ref, CONCAT(b.nom_sci, ' ', b.auteur) AS nom, b.num_nom, b.num_taxonomique, b.famille FROM `BASESOURCE`.`TABLEBDTFX` b UNION ALL \
SELECT "bdtxa" AS valid_ref, CONCAT(a.nom_sci, ' ', a.auteur) AS nom, a.num_nom, a.num_tax, a.famille FROM `BASESOURCE`.`TABLEBDTXA` a UNION ALL \
SELECT "isfan" AS valid_ref, CONCAT(i.nom_sci, ' ', i.auteur) AS nom, i.num_nom, i.num_taxonomique, i.famille FROM `BASESOURCE`.`TABLEISFAN` i;
 
/* Donc nous JOINons:
-- INNER JOIN sur bdtfx: 62633
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEBDTFX` b ON (b.num_nom = c.nom_sel_nn) WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL;
-- INNER JOIN sur bdtxa: 9469
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEISFAN` i ON (i.num_nom = c.nom_sel_nn) WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL;
-- INNER JOIN sur isfan: 1991
SELECT id_observation, nom_referentiel, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEISFAN` i ON (i.num_nom = c.nom_sel_nn) WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL;
-- INNER JOIN sur les 3 référentiels (bdtxa + bdtfx + isfan): 74093
SELECT id_observation, valid_ref, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille FROM `BASEEDIT`.`cel_obs` c INNER JOIN T_bis b ON (b.num_nom = c.nom_sel_nn) WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL;
*/
 
/* mais de nombreux noms sont exactement présents dans plusieurs référentiels,
d'où GROUP BY id_observation HAVING count(id_observation) = 1,
ce qui ne produit plus que 51359 matches (soit 22734 dups) */
/*
SELECT id_observation, valid_ref, nom_sel, nom, nom_sel_nn, nom_ret, nom_ret_nn, nt, c.famille
FROM `BASEEDIT`.`cel_obs` c
INNER JOIN T_bis b
ON (b.num_nom = c.nom_sel_nn)
WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL GROUP BY id_observation HAVING count(id_observation) = 1;
-- 63941, tous bdtfx...
*/
 
 
delimiter |
 
CREATE PROCEDURE majreferentiel()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE subst INT DEFAULT 0;
DECLARE _id_observation bigint(20) DEFAULT 0;
DECLARE _valid_ref varchar(20) DEFAULT NULL;
DECLARE cur1 CURSOR FOR SELECT id_observation, valid_ref FROM `BASEEDIT`.`cel_obs` c INNER JOIN T_bis b ON (b.num_nom = c.nom_sel_nn)
WHERE nom_referentiel IS NULL AND nom_sel_nn IS NOT NULL GROUP BY id_observation HAVING count(id_observation) = 1;
-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
 
OPEN cur1;
REPEAT
FETCH cur1 INTO _id_observation, _valid_ref;
UPDATE `BASEEDIT`.`cel_obs` c SET nom_referentiel = _valid_ref WHERE id_observation = _id_observation;
SET subst = subst + 1;
UNTIL done END REPEAT;
select subst AS 'nombre de mises à jour de référentiel effectuées';
CLOSE cur1;
END
|
 
delimiter ;
 
CALL majreferentiel;
/tags/v5.7-arrayanal/scripts/modules/cel/cel_references.sql
New file
0,0 → 1,128
/*
TODO:
* fix référentiel: suppression n° de version et uniformisation
SELECT DISTINCT nom_referentiel, COUNT(id_observation) AS count FROM `BASEEDIT`.`cel_obs` GROUP BY nom_referentiel ORDER BY count DESC;
* ajout INDEX nom_referentiel(5) sur `BASEEDIT`.`cel_obs`
* ajout INDEX catminat_code sur baseflor_v2012_12_31
* ajout INDEX num_taxon sur nva_v2013_06
* fix date: set NULL pour les dates dans le futur
SELECT courriel_utilisateur, id_observation, date_observation FROM `BASEEDIT`.`cel_obs` WHERE date_observation > NOW();
* intégrer les noms non-associés à un taxon (bdtfx where num_taxonomique = '')
* intégrer les noms non-associés à un taxon (bdtxa where num_tax = '' || num_tax IS NULL)
 
CREATE INDEX i_nom_referentiel ON `BASEEDIT`.`cel_obs` (`nom_referentiel`(5));
CREATE INDEX i_catminat_code ON baseflor_v2012_12_31 (`catminat_code`);
CREATE INDEX i_num_taxon ON nva_v2013_06 (`num_taxon`);
*/
 
-- malheureusement ceci est impossible en SQL d'où l'utilisation du shell-script
-- SET @destdb = 'tb_cel';
-- SET @desttable = 'cel_references';
-- -- SET BASEEDIT = `tb_cel`;
-- SET @dst = CONCAT('`',@destdb,'`','.`',@desttable,'`');
 
DROP TABLE IF EXISTS `BASEEDIT`.`cel_references`;
CREATE TABLE IF NOT EXISTS `BASEEDIT`.`cel_references` (
`referentiel` CHAR(5) NOT NULL COMMENT 'eg: "bdtfx", "bdtfx", "bdtxa", ... No ENUM!',
 
-- bdtfx
`num_nom` INT(9) NOT NULL DEFAULT '0' COMMENT 'depuis bdtfx',
`num_nom_retenu` VARCHAR(9) DEFAULT NULL COMMENT 'depuis bdtfx',
 
-- bdtfx + nvjfl_v2007 + nva_v2013_06
`num_taxon` int(9) NOT NULL COMMENT "depuis bdtfx, nvjfl_v2007 et nva_v2013_06 (commun), les noms non-associés ne sont pas intégrés pour l'instant", -- 'relax emacs
 
-- bdtfx
`nom_sci` VARCHAR(500) NOT NULL COMMENT 'depuis bdtfx',
`auteur` VARCHAR(100) DEFAULT NULL COMMENT 'depuis bdtfx',
 
 
-- `BASEEDIT`.`cel_obs`
-- `nom_ret_nn` DECIMAL(9,0) DEFAULT NULL COMMENT 'Numéro du nom retenu.',
-- `nom_ret` VARCHAR(255) DEFAULT NULL,
 
-- nvjfl_v2007 (`nom_vernaculaire` text NOT NULL)
-- mais NULL à cause de nva
`nom_commun` VARCHAR(60) NULL COMMENT 'nom_vernaculaire pour nvjfl_v2007 et nva_v2013_06',
 
-- baseflor_v2012_12_31
`catminat_code` varchar(18) DEFAULT 'inconnu' COMMENT 'depuis baseflor_v2012_12_31',
`ve_lumiere` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_temperature` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_continentalite` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_humidite_atmos` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_humidite_edaph` int(2) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_reaction_sol` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_nutriments_sol` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_salinite` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_texture_sol` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
`ve_mat_org_sol` int(1) DEFAULT NULL COMMENT 'depuis baseflor_v2012_12_31',
 
-- baseveg_v2013_01_09
`syntaxon` varchar(255) NULL COMMENT 'depuis baseveg_v2013_01_09',
PRIMARY KEY (`referentiel`, `num_nom`),
INDEX (`referentiel`(5)),
INDEX (`num_nom`),
INDEX (`num_taxon`)
) ENGINE=MyISAM \
DEFAULT CHARSET=utf8 \
COMMENT 'table générée par eflore/projets/scripts/modules/cel/cel_references.sql à partir de `TABLEBDTFX`, `TABLEBDTXA` et `TABLEISFAN`';
 
-- tables temporaires
DROP TEMPORARY TABLE IF EXISTS `T_nvjfl_v2007`, `T_nva_v2013_06`, `T_basevegflor`;
 
-- pour nvjfl_v2007, le nom recommandé ou typique est celui pour lequel num_statut = 1 (mais plusieurs sont possibles, d'où le GROUP BY num_taxon)
CREATE TEMPORARY TABLE T_nvjfl_v2007 ( INDEX(`num_taxon`) ) AS \
-- ( SELECT n.num_taxon, n.nom_vernaculaire FROM `BASESOURCE`.`nvjfl_v2007` n WHERE n.code_langue = 'fra' GROUP BY n.num_taxon, n.num_statut HAVING n.num_statut = MAX(n.num_statut) );
-- ( SELECT n.num_taxon, n.nom_vernaculaire, n.num_statut as void, MAX(n.num_statut) as void2 FROM `BASESOURCE`.`nvjfl_v2007` n WHERE n.code_langue = 'fra' GROUP BY n.num_taxon HAVING n.num_statut = MAX(n.num_statut) );
( SELECT n.num_taxon, n.nom_vernaculaire FROM `BASESOURCE`.`nvjfl_v2007` n WHERE n.code_langue = 'fra' AND n.num_statut = 1 GROUP BY n.num_taxon );
 
-- table temporaire uniquement parce qu'il manque un index-key, autrement le LEFT JOIN ci-dessous est bien trop long
CREATE TEMPORARY TABLE T_nva_v2013_06 ( INDEX(`num_taxon`) ) AS \
-- ( SELECT n.num_taxon, n.nom_vernaculaire FROM `BASESOURCE`.`nva_v2013_06` n WHERE n.code_langue = 'fra' /* DB pb */ AND n.num_taxon IS NOT NULL /* /DB pb */ GROUP BY n.num_nom); -- aggrégat arbitraire car pas de num_statut
-- pour nva_index, le nom recommandé ou typique est celui pour lequel num_statut = 0 (mais il n'y en a aucun à l'heure actuelle) (mais plusieurs sont possibles, d'où le GROUP BY num_nom)
( SELECT n.num_taxon, n.nom_vernaculaire FROM `BASESOURCE`.`nva_index_v2_03` n WHERE n.code_langue = 'fra' /* AND n.num_statut = 0 */ GROUP BY n.num_taxon);
 
 
-- JOIN ON num_taxon_originel car INDEX
-- cf: eflore/projets/donnees/baseflor/2012-12-31/baseflor.sql
CREATE TEMPORARY TABLE T_basevegflor ( INDEX(`num_nomen`), INDEX(`num_taxon`) ) AS \
SELECT f.num_nomen, f.num_taxon, f.catminat_code, f.ve_lumiere, f.ve_temperature, f.ve_continentalite, f.ve_humidite_atmos, f.ve_humidite_edaph, f.ve_reaction_sol, f.ve_nutriments_sol, f.ve_salinite, f.ve_texture_sol, f.ve_mat_org_sol, \
v.syntaxon \
FROM `BASESOURCE`.`baseflor_v2012_12_31` f LEFT JOIN `BASESOURCE`.`baseveg_v2013_01_09` v ON (f.catminat_code = v.code_catminat AND v.niveau = 'ALL' AND v.syntaxon IS NOT NULL) WHERE f.BDNT = "BDTFX" \
GROUP BY f.num_nomen, f.num_taxon; -- group by car plusieurs couple (f.num_nomen, f.num_taxon) peuvent exister dans baseveg_v2013_01_09 or num_nom est PRIMARY dans cel_references
 
 
-- INSERTIONS
-- pour le futur: attention au numéro taxonomique à 0 (WHERE b.num_taxonomique != '')
INSERT INTO `BASEEDIT`.`cel_references` (`referentiel`, `num_nom`, `num_nom_retenu`, `num_taxon`, `nom_sci`, `auteur`, `nom_commun`, \
`catminat_code`, `ve_lumiere`, `ve_temperature`, `ve_continentalite`, `ve_humidite_atmos`, `ve_humidite_edaph`, \
`ve_reaction_sol`, `ve_nutriments_sol`, `ve_salinite`, `ve_texture_sol`, `ve_mat_org_sol`, `syntaxon`) \
 
SELECT "bdtfx", b.num_nom, b.num_nom_retenu, b.num_taxonomique, b.nom_sci, b.auteur, n.nom_vernaculaire, \
bf.catminat_code, bf.ve_lumiere, bf.ve_temperature, bf.ve_continentalite, bf.ve_humidite_atmos, bf.ve_humidite_edaph, \
bf.ve_reaction_sol, bf.ve_nutriments_sol, bf.ve_salinite, bf.ve_texture_sol, bf.ve_mat_org_sol, bf.syntaxon
FROM `BASESOURCE`.`TABLEBDTFX` b LEFT JOIN T_nvjfl_v2007 n ON (b.num_taxonomique = n.num_taxon ) \
LEFT JOIN T_basevegflor bf ON (b.num_taxonomique = bf.num_taxon AND b.num_nom = bf.num_nomen);
 
 
-- pour le futur: attention au numéro taxonomique à 0 (WHERE b.num_tax IS NOT NULL AND b.num_tax != '')
INSERT INTO `BASEEDIT`.`cel_references` (`referentiel`, `num_nom`, `num_nom_retenu`, `num_taxon`, `nom_sci`, `auteur`, `nom_commun`) \
SELECT "bdtxa", b.num_nom, b.num_nom_retenu, b.num_tax, b.nom_sci, b.auteur, n.nom_vernaculaire FROM `BASESOURCE`.`TABLEBDTXA` b LEFT JOIN T_nva_v2013_06 n ON (b.num_tax = n.num_taxon);
 
 
INSERT INTO `BASEEDIT`.`cel_references` (`referentiel`, `num_nom`, `num_nom_retenu`, `num_taxon`, `nom_sci`, `auteur`) \
SELECT "isfan", b.num_nom, b.num_nom_retenu, b.num_taxonomique, b.nom_sci, b.auteur FROM `BASESOURCE`.`TABLEISFAN` b;
 
 
 
 
DROP TEMPORARY TABLE IF EXISTS `T_nvjfl_v2007`, `T_nva_v2013_06`, `T_basevegflor`;
 
SELECT SUM(theorie.a) AS théorie, pratique.a AS total FROM \
(SELECT COUNT(1) AS a FROM `BASESOURCE`.`TABLEBDTFX` UNION ALL \
SELECT COUNT(1) AS a FROM `BASESOURCE`.`TABLEBDTXA` UNION ALL \
SELECT COUNT(1) AS a FROM `BASESOURCE`.`TABLEISFAN` \
) AS theorie, \
(SELECT COUNT(1) AS a FROM `BASEEDIT`.cel_references) AS pratique;
-- bdtfx+bdtxa+isfan: 141181 (2013/07/23)
/tags/v5.7-arrayanal/scripts/modules/cel/dedup-ordre-201307.sql
New file
0,0 → 1,109
-- suppress dup:
-- >= 115 au 22/07/2013
-- mysql -N <<<"SELECT distinct ce_utilisateur FROM `BASEEDIT`.`cel_obs` GROUP BY ce_utilisateur, ordre HAVING COUNT(*) > 1;" > ordre-dup.txt
 
DROP FUNCTION IF EXISTS next_ordre;
DROP PROCEDURE IF EXISTS ordre_need_update;
DROP PROCEDURE IF EXISTS update_ordre_user;
DROP PROCEDURE IF EXISTS update_ordre_users;
 
DELIMITER |
 
CREATE FUNCTION next_ordre( s1 VARCHAR(255) )
RETURNS INT
READS SQL DATA
BEGIN
DECLARE c INT;
SET c = (SELECT MAX(ordre) + 1 FROM `BASEEDIT`.`cel_obs` where ce_utilisateur = s1);
RETURN c;
END
|
-- SELECT next_ordre("");
 
CREATE PROCEDURE ordre_need_update(IN _s1 VARCHAR(255), OUT _ordre INT, OUT _c INT, OUT _min_obs INT)
BEGIN
SELECT ordre, count(ordre), MIN(id_observation) INTO _ordre, _c, _min_obs FROM `BASEEDIT`.`cel_obs` WHERE ce_utilisateur = _s1 GROUP BY ordre HAVING COUNT(ordre) > 1 LIMIT 1;
END
|
-- SELECT ordre_need_update("");
 
CREATE PROCEDURE update_ordre_user(IN _s1 VARCHAR(255))
BEGIN
DECLARE obs_match int default -1;
CALL ordre_need_update(_s1, @o, @c, @minobs);
-- pour chaque ordre dupliqué
WHILE @o IS NOT NULL DO
SELECT CONCAT(" ", @o) as " ordre", @c as "(count/doublons)";
-- SELECT id_observation FROM `BASEEDIT`.`cel_obs` WHERE ce_utilisateur = _s1 AND ordre = @o AND id_observation != @minobs;
-- pour chaque obs concernée, exceptée la première, on met à jour l'ordre,
-- en utilisant next_ordre()
WHILE obs_match != 0 DO
-- SELECT CONCAT("== do update on", @o);
UPDATE `BASEEDIT`.`cel_obs` SET ordre = next_ordre(_s1)
WHERE ce_utilisateur = _s1 AND ordre = @o AND id_observation != @minobs LIMIT 1;
SELECT ROW_COUNT() into obs_match;
-- SELECT @o, obs_match;
END WHILE;
-- toutes les observations dupliquées pour l'ordre @o ont été mises à jour
-- un nouvel ordre à mettre à jour va être obtenu par ordre_need_update()
-- dont nous restaurons obs_match à une valeur qui n'empêche pas la boucle
-- contenant l'UPDATE
SELECT -1 into obs_match;
CALL ordre_need_update(_s1, @o, @c, @minobs);
-- SELECT "====X", @o, @c;
END WHILE;
END
|
-- CALL update_ordre_user("");
 
 
CREATE PROCEDURE update_ordre_users()
BEGIN
DECLARE _nom VARCHAR(255);
DECLARE subst INT DEFAULT 0;
DECLARE done INT DEFAULT 1;
 
-- temp table
-- the following fails, pas d'index (see EXPLAIN + http://dba.stackexchange.com/questions/48231 ?)
-- ( SELECT DISTINCT ce_utilisateur FROM `BASEEDIT`.`cel_obs` GROUP BY ce_utilisateur, ordre HAVING COUNT(*) > 1 );
IF (SELECT SUBSTR(version(),3,1)) != 5 THEN
-- mais celle-ci fonctionne, car l'ordre du GROUP BY correspond à l'INDEX [id_obs] : 16 secondes
CREATE TEMPORARY TABLE IF NOT EXISTS _temp_users (ce_utilisateur VARCHAR(255)) ENGINE=MEMORY AS \
( SELECT DISTINCT ce_utilisateur FROM `BASEEDIT`.`cel_obs` GROUP BY ordre, ce_utilisateur HAVING COUNT(1) > 1 );
ELSE
-- alternativement, comme solution de replis (nécessaire pour MariaDB ?):
CREATE TEMPORARY TABLE IF NOT EXISTS _temp_users (ce_utilisateur VARCHAR(255)) ENGINE=MEMORY AS \
( SELECT DISTINCT ce_utilisateur FROM `BASEEDIT`.`cel_obs` WHERE ce_utilisateur IN \
(SELECT ce_utilisateur FROM `BASEEDIT`.`cel_obs` GROUP BY ce_utilisateur, ordre HAVING COUNT(1) > 1) );
END IF;
 
SELECT COUNT(*) INTO done FROM _temp_users;
-- la requête principale de sélection des utilisateurs à mettre à jour
WHILE done > 0 DO
SELECT ce_utilisateur INTO _nom FROM _temp_users LIMIT 1;
SELECT _nom AS "utilisateur en mise à jour:";
CALL update_ordre_user(_nom);
SET subst = subst + 1;
DELETE FROM _temp_users WHERE ce_utilisateur = _nom;
SELECT COUNT(*) INTO done FROM _temp_users;
END WHILE;
SELECT subst AS "utilisateurs mis à jour";
END
|
 
DELIMITER ;
 
 
CALL update_ordre_users();
 
 
DROP FUNCTION IF EXISTS next_ordre;
DROP PROCEDURE IF EXISTS ordre_need_update;
DROP PROCEDURE IF EXISTS update_ordre_user;
DROP PROCEDURE IF EXISTS update_ordre_users;
 
-- clef unique sur (id_utilisateur, ordre)
-- [mais seulement si on a dédupliqué TOUS les utilisateurs, y compris l'utilisateur ''
-- à voir aussi: maj-hash-id-obs-migr.sql]
DROP INDEX `id_obs` ON `BASEEDIT`.`cel_obs`;
CREATE UNIQUE INDEX `id_obs` ON `BASEEDIT`.`cel_obs` (`ce_utilisateur` ASC, `ordre` ASC);
/tags/v5.7-arrayanal/scripts/modules/cel/A_LIRE.txt
New file
0,0 → 1,117
Créer une base de données tb_cel avant de lancer les scripts
 
== Sommaire ==
1) à propos de la mise à jour de septembre 2013
2) à propos de la table cel_references
==============
 
1) cel_references.sql
création de la table `cel_references`
 
2) maj-struct-201307.sql
mise à jour des structure de table (les index notamment):
 
3) maj-cleanup-201307.sql
uniformisation des données (lon/lat, date, ...)
et des NULL vs 0 (pour nom_sel_nn et nom_ret_nn)
 
4) fix-utilisateur-32.sql
 
5) dedup-ordre-201307.sql
 
6) maj-referentiel-201307.sql
fix le référentiel pour les observation ayant un nom_sel_nn sans nom_referentiel en se
basant sur une match exact de CONCAT(nom_sci, auteur) parmi bdtfx, bdtxa et isfan
 
7) referonosaure.sql
MAJ des observations (valides) avec les nouvelles données générées, à partir de bdtfx/bdtxa/isfan
 
=====
8) TODO: maj-nom-ret.sql
TODO (pas sûr) MAJ du référentiel pour les observation ayant un nom_ret sans nom_ret_nn mais dont le nom_ret
ne match pas le nom_sci en BDTFX (car en BDTFX nom_ret_nn peut être égal à 0 !)
 
9) maj-referentiel-und-201307.sql
MAJ du référentiel pour les observation n'ayant pas de nom_ret_nn (tentative de détermination par nom)
 
 
 
 
 
 
 
 
=== 2: À propos de la table cel_references ===
Celle-ci existe car:
* les projets doivent être indépendants (eflore, cel, projets nvjfl, ...)
* les données nécessaires à l'export et à l'import sont massives
* or les webservices s'appellent parfois récursivement, sont lents et inadaptés
 
La conséquence est que la construction d'une table dérivée de bdtfx/bdtxa/isfan contenant
les informations utiles pour CEL s'avère nécessaire.
cel_references.sql construit une telle table.
 
Suivent quelques éléments de compréhension et exemples de requêtes liés à cette initialisation:
 
1) Détermination des noms vernaculaires meilleurs et uniques:
 
Ce sont ceux qui ont le num_statut le plus élevé pour un num_taxon donné dans nvjfl_v2007.
Plusieurs méthodes sont exposées ci-dessous, sachant que le couple (référentiel, num_nom) est la clef
unique de cel_references.
Il existe à ce jour 16146 nom communs français distincts, 12312 num_taxon pour code_lang = fra et aucun num_statut NULL en français.
1.1:
SELECT n.num_taxon, n.nom_vernaculaire, n.num_statut, n2.num_statut FROM nvjfl_v2007 n LEFT JOIN nvjfl_v2007 n2 ON (n.num_taxon = n2.num_taxon) WHERE n.num_taxon < 32 AND n.code_langue = 'fra' GROUP BY n.num_taxon, n.num_statut HAVING n.num_statut = MAX(n2.num_statut) LIMIT 100;
# 12311 résultats
 
1.2:
SELECT n.num_taxon, n.nom_vernaculaire FROM nvjfl_v2007 n INNER JOIN nvjfl_v2007 n2 ON (n.num_taxon = n2.num_taxon AND n.code_langue = n2.code_langue AND n.num_statut > n2.num_statut) WHERE n.code_langue = 'fra' GROUP BY n.num_taxon;
# 2680 résultats
 
1.3:
SELECT n.num_taxon, n.nom_vernaculaire FROM nvjfl_v2007 n LEFT JOIN nvjfl_v2007 n2 ON (n.num_taxon = n2.num_taxon AND n.code_langue = n2.code_langue AND n.num_statut > n2.num_statut) WHERE n.code_langue = 'fra' AND n2.num_statut IS NOT NULL GROUP BY num_taxon;
# 2680 résultats
Mais problème ensuite: SELECT n.* from cel_references NATURAL JOIN nvjfl_v2007 n WHERE `nom_commun` = '' AND n.code_langue = 'fra';
 
 
 
2) à propos de l'insertion dans cel_references proprement dit:
Le modèle simplifié théorique de base est le suivant:
 
INSERT INTO @dst (`referentiel`, `num_nom`, `num_nom_retenu`, `nom_sci`, `auteur`, `nom_commun`) \
SELECT "bdtfx", b.num_nom, b.num_nom_retenu, b.nom_sci, b.auteur, n.nom_vernaculaire, MAX(n.num_statut) FROM bdtfx_v1_01 b LEFT JOIN nvjfl_v2007 n ON (b.num_taxonomique = n.num_taxon AND n.code_langue = 'fra' ) GROUP BY b.num_nom \
UNION \
SELECT "bdtxa", b.num_nom, b.num_nom_retenu, b.nom_sci, b.auteur, n.nom_vernaculaire, NULL FROM bdtxa_v1_00 b LEFT JOIN nva_v2013_06 n ON (b.num_tax = n.num_taxon AND n.code_langue = 'fra' ) GROUP BY b.num_nom \
UNION \
SELECT "isfan", b.num_nom, b.num_nom_retenu, b.nom_sci, b.auteur, NULL FROM isfan_v2013 b;
 
Mais évidemment, les noms communs n'existent que pour bdtfx[nvjfl], bdtxa[nva], de même que les données baseflor/baseveg.
Plusieurs tables temporaires sont donc nécessaires en particulier puisque toutes les colonnes n'ont pas
des indexes adaptés pour effectuer des JOIN efficaces dans le cadre de ce script d'intégration particulier.
 
Une version plus aboutie, mais spécifique à bdtfx, après création préalable de T_nvjfl_v2007, était la suivante (présence des noms communs):
INSERT INTO @dst (`referentiel`, `num_nom`, `num_nom_retenu`, `num_taxon`, `nom_sci`, `auteur`, `nom_commun`) \
SELECT "bdtfx", b.num_nom, b.num_nom_retenu, b.num_taxonomique, b.nom_sci, b.auteur, n.nom_vernaculaire FROM bdtfx_v1_01 b LEFT JOIN T_nvjfl_v2007 n ON (b.num_taxonomique = n.num_taxon );
 
 
À noter:
SELECT b.num_nom, b.num_nom_retenu, b.num_taxonomique, b.nom_sci FROM bdtfx_v1_01 b where b.num_taxonomique = '';
# 3968, c'est à dire des num_taxon vides, pourtant INDEX et NOT NULL.
Idem pour bdtxa
 
 
3) à propos de baseveg/baseflor:
Note au 16/07/2013: les schémas sont susceptibles de changer à l'avenir.
La jointure entre bdtfx et baseflor se fait sur le référentiel ("bdtfx") et num_nom.
À partir de là nous disposons d'un catminat_code qui correspond au code_catminat dans baseveg, afin d'obtenir le syntaxon.
Quelques exemples:
 
SELECT code_catminat, syntaxon, lumiere, hum_atmos, temperature, oceanite, ph_sol, hum_edaph, texture_sol FROM baseveg_v2013_01_09;
SELECT * from baseflor_v2012_12_31 where cle = 1174;
 
SELECT * from baseveg_v2013_01_09 where code_catminat = '05/3.0.1.0.2' AND niveau = 'ALL';
# 7 résultats
SELECT f.num_nomen, f.num_taxon, f.catminat_code, f.ve_lumiere, f.ve_temperature, f.ve_continentalite, f.ve_humidite_atmos, f.ve_humidite_edaph, f.ve_reaction_sol, f.ve_nutriments_sol, f.ve_salinite, f.ve_texture_sol, f.ve_mat_org_sol FROM baseflor_v2012_12_31 f LEFT JOIN baseveg_v2013_01_09 v ON (f.catminat_code = v.code_catminat) WHERE f.BDNT = "BDTFX" and f.cle = 1174;
# 7 résultats
SELECT f.num_nomen, f.num_taxon, f.catminat_code, f.ve_lumiere, f.ve_temperature, f.ve_continentalite, f.ve_humidite_atmos, f.ve_humidite_edaph, f.ve_reaction_sol, f.ve_nutriments_sol, f.ve_salinite, f.ve_texture_sol, f.ve_mat_org_sol FROM baseflor_v2012_12_31 f LEFT JOIN baseveg_v2013_01_09 v ON (f.catminat_code = v.code_catminat AND v.niveau = 'ALL') WHERE f.BDNT = "BDTFX" and f.cle = 1174;
# 1 résultat
Nous utilisons v.niveau = ALL pour nous assurer la présence d'un seul f.num_nomen dans `T_basevegflor` et donc assurer l'unicité de la PRIMARY KEY de `cel_references`
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/cel/redempteur.sql
New file
0,0 → 1,114
/*
À l'origine les observations nécessiteuses sont celles n'ayant pas de données génénées,
Soit: nom_ret, nom_ret_nn, nt ou famille à NULL|0|''
 
Eg:
SELECT id_observation, nom_sel
FROM `BASEEDIT`.`cel_obs`
WHERE (
nom_ret IS NULL or nom_ret = ''
OR nom_ret_nn IS NULL or nom_ret_nn = 0
OR nt IS NULL or nt = 0
OR famille IS NULL or famille = ''
)
 
Sauf que:
1) on exclue celles sans nom_sel (elles sont sans espoir):
nom_sel IS NOT NULL AND nom_sel != ''
2) on exclue celles qui on un nom_ret_nn à 0, car cela peut-être légal, cf maj-201307.sql à ce propos
# donc pas de `nom_ret_nn = 0` dans la requête
3) on exclue, dans un premier temps, celles dont le référentiel n'est pas défini
AND (nom_referentiel IS NULL)
 
D'où, les 3621 observations suivantes (2206 nom_sel distincts)
SELECT id_observation, nom_sel
FROM `BASEEDIT`.`cel_obs`
WHERE (
nom_sel IS NOT NULL AND nom_sel != ''
AND (
nom_ret IS NULL OR nom_ret = ''
OR nom_ret_nn IS NULL
OR nt IS NULL or nt = 0
OR famille IS NULL or famille = ''
)
AND (nom_referentiel IS NOT NULL)
)
 
Dans un premier temps nous travaillons avec le bdtfx, c'est à dire que
AND (nom_referentiel IS NOT NULL)
devient
AND (nom_referentiel like 'bdtfx%')
soit 3597/3621 observations:
 
Et effectuons une jointure sur bdtfx:
SELECT id_observation, nom_sel, b.num_nom, b.famille
FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEBDTFX` b ON (b.nom_sci = c.nom_sel)
WHERE (
nom_sel IS NOT NULL AND nom_sel != ''
AND (
nom_ret IS NULL OR nom_ret = ''
OR nom_ret_nn IS NULL
OR nt IS NULL OR nt = 0
OR c.famille IS NULL OR c.famille = ''
)
AND (nom_referentiel like 'bdtfx%')
)
 
* Or nous observons que la famille est parfois légitimement NULL ! Ce n'est pas pertinent de l'utiliser
comme critère de caractérisation d'une observation buggée, contentons-nous donc de empty ('')
 
* Or nous observons que le numéro taxonomique est parfois légitimement 0 ! Ce n'est pas pertinent de l'utiliser
comme critère de caractérisation d'une observation buggée, contentons-nous donc de NULL
 
 
 
Soit 84 lignes, cependant, un nom_sel peut correspondre à plusieurs num_nom_retenu dans bdtfx ! (et oui, les suffixes latins et d'auteur).
Il s'agit donc de ne pas traiter ceux qui risquerait d'être mal-corrigé (sans les 100% de certitude).
Ainsi un ` GROUP BY id_observation HAVING count(id_observation) = 1 ` sera du meilleur effet.
 
Nous obtenons donc ainsi les 69 observations à mettre à jour:
SELECT id_observation, nom_sel, nom_ret, nom_ret_nn, nt, c.famille, b.num_nom, b.nom_sci, b.num_taxonomique, b.famille
FROM `BASEEDIT`.`cel_obs` c INNER JOIN `BASESOURCE`.`TABLEBDTFX` b ON (b.nom_sci = c.nom_sel)
WHERE (
nom_sel IS NOT NULL AND nom_sel != ''
AND (
nom_ret IS NULL OR nom_ret = ''
OR nom_ret_nn IS NULL
OR nt IS NULL
OR c.famille = ''
)
AND (nom_referentiel like 'bdtfx%')
)
GROUP BY id_observation HAVING count(id_observation) = 1
 
 
=== la mise à jour ===
Comme nous voulons utiliser UPDATE, nous devons remplacer le JOIN par des conditions du WHERE, mais le GROUP BY bloque de
toute manière, un SUB-SELECT (table temporaire) est donc nécessaire:
 
=== finale ===
*/
 
CREATE TEMPORARY TABLE T_bis ( INDEX(`id_observation`)) AS
SELECT id_observation, b.num_nom, CONCAT(b.nom_sci, ' ', b.auteur), b.num_taxonomique, b.famille
FROM `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b
WHERE (
b.nom_sci = c.nom_sel
AND nom_sel IS NOT NULL AND nom_sel != ''
AND (
nom_ret IS NULL OR nom_ret = ''
OR nom_ret_nn IS NULL
OR nt IS NULL OR nt = 0
OR c.famille = ''
)
AND (nom_referentiel like 'bdtfx%')
)
GROUP BY id_observation HAVING count(id_observation) = 1
 
UPDATE `BASEEDIT`.`cel_obs` c, T_bis t SET
c.nom_ret = t.nom_sci,
c.nom_ret_nn = t.num_nom,
c.nt = t.num_taxonomique,
c.famille = t.famille
WHERE (c.id_observation = t.id_observation);
DROP TEMPORARY TABLE T_bis;
/tags/v5.7-arrayanal/scripts/modules/cel/referonosaure.sql
New file
0,0 → 1,116
/*
 
Objectif: prendre les observations dont nom_sel_nn est défini
(et donc dans laquelles les informations générées sont correctes)
et mettre à jour ces dernières à partir de la dernière version du référentiel
(bdtfx, bdtxa et isfan).
 
Pour éviter un maximum de faux-positifs, nous vérifions aussi que la famille
est conservée (même dans certains cas celle-ci a légitimement changé) et que
la première partie du nom_sel correspond toujours à la première partie du nouveau nom_sci
qui serait attribué.
 
-- la requête --
-- SELECT id_observation, b.num_nom, CONCAT(b.nom_sci, ' ', b.auteur), b.num_taxonomique, b.famille
SELECT id_observation, nom_ret, nom_ret_nn, nt, c.famille
FROM `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b
WHERE (
nom_sel_nn IS NOT NULL
AND nom_referentiel like 'bdtfx%'
AND nom_sel_nn = num_nom
)
ORDER BY id_observation asc;
 
 
Cependant le nom_ret_nn n'est pas directement le num_num du taxon dont le nom est
retenu. Pour cela, une jointure en bdtfx sur num_nom_retenu est nécessaire et c'est
ce dernier taxon dont le num_nom est utilisé pour nom_ret_nn.
Cependant il peut aussi être vide (si aucun nom_retenu "officiel" n'existe).
 
Attention, les nom_sel_nn = 0 doivent avoir disparus de cel_obs *AU PRÉALABLE* car le test
n'est pas effectué.
cf: maj-cleanup-201307.sql
 
Ici, contrairement à referonosaure_fromNomRet.sql, nous partons du nom_sel en admettant qu'il est
toujours correct et c'est donc sur ce champ que s'effectue la jointure.
Quelques exceptions notables existent cependant:
- certaines observations issues de sauvages sont corrompues, leur nom_sel_nn n'est donc PAS fiable
- il a été remarqué des observations pour lesquelles le nom_sel_nn était corrompu, impliquant une changement
de nom de famille incohérent. Pour se prémunir de cela, la famille doit être identique ou presque.
- enfin, la première partie du nom_sel doit matcher exactement la première partie du nom_sci
 
Consulter referonosaure_fromNomRet.sql pour des informations complémentaires.
*/
 
 
 
/* test:
SELECT c.nom_ret_nn, c.nom_ret, bLAST.num_nom, bLAST.nom_sci, bLAST.auteur, c.famille, bLAST.famille, c.nt, bLAST.num_taxonomique
FROM cel_obs c, tb_eflore.bdtfx_v1_01 b, tb_eflore.bdtfx_v1_01 bLAST
WHERE (
bLAST.num_nom = b.num_nom_retenu
AND nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0 AND nom_referentiel = 'bdtfx'
AND nom_ret_nn = bLAST.num_nom
AND (LOWER(c.famille) = LOWER(b.famille) OR c.famille IS NULL)
AND (c.famille != b.famille OR c.nom_ret != CONCAT(bLAST.nom_sci, ' ', bLAST.auteur) OR c.nt != b.num_taxonomique OR c.nom_ret_nn != bLAST.num_nom)
);
*/
 
-- l'update BDTFX avec nom_sel_nn seul
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b, `BASESOURCE`.`TABLEBDTFX` b_nom_ret SET
c.nom_ret = CONCAT(b_nom_ret.nom_sci, ' ', b_nom_ret.auteur),
c.nom_ret_nn = b_nom_ret.num_nom,
c.nt = b.num_taxonomique,
c.famille = b.famille,
c.date_modification = NOW() -- a supprimer pour estimer le nombre de changements réel
WHERE (
b_nom_ret.num_nom = b.num_nom_retenu
AND nom_sel_nn IS NOT NULL
AND nom_referentiel = 'bdtfx'
AND nom_sel_nn = b.num_nom
-- TODO: bug transferts multiples + mobile.js
-- Note: SELECT IF(NULL NOT LIKE "%blah%", 1, 0) : 0
AND (c.mots_cles_texte IS NULL OR c.mots_cles_texte NOT LIKE '%WidgetFlorileges Sauvages%')
AND (LOWER(c.famille) = LOWER(b.famille) OR c.famille IS NULL OR c.famille = 'Famille inconnue')
AND SUBSTRING_INDEX(c.nom_sel, ' ', 1) = SUBSTRING_INDEX(b.nom_sci, ' ', 1)
);
-- 42315 avec indirection num_nom_retenu
SELECT ROW_COUNT() AS "BDTFX upd après correction sur nom_sel_nn";
 
 
-- l'update BDTXA avec nom_sel_nn seul
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTXA` a, `BASESOURCE`.`TABLEBDTXA` a_nom_ret SET
c.nom_ret = CONCAT(a_nom_ret.nom_sci, ' ', a_nom_ret.auteur),
c.nom_ret_nn = a_nom_ret.num_nom,
c.nt = a.num_tax,
c.famille = a.famille,
c.date_modification = NOW()
WHERE (
a_nom_ret.num_nom = a.num_nom_retenu
AND nom_sel_nn IS NOT NULL
AND nom_referentiel = 'bdtxa'
AND nom_sel_nn = a.num_nom
AND (LOWER(c.famille) = LOWER(a.famille) OR c.famille IS NULL)
AND SUBSTRING_INDEX(c.nom_sel, ' ', 1) = SUBSTRING_INDEX(a.nom_sci, ' ', 1)
);
-- 49 avec les restrictions sur famille et SUBSTRING_INDEX()
-- 48 sans les restrictions sur famille et SUBSTRING_INDEX()
SELECT ROW_COUNT() AS "BDTXA upd après correction sur nom_sel_nn";
 
 
-- l'update ISFAN avec nom_sel_nn seul
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEISFAN` i, `BASESOURCE`.`TABLEISFAN` i_nom_ret SET
c.nom_ret = CONCAT(i_nom_ret.nom_sci, ' ', i_nom_ret.auteur),
c.nom_ret_nn = IF(i_nom_ret.num_nom=0,NULL,i_nom_ret.num_nom),
c.nt = i.num_taxonomique,
c.famille = i.famille,
c.date_modification = NOW()
WHERE (
i_nom_ret.num_nom = i.num_nom_retenu
AND nom_sel_nn IS NOT NULL
AND nom_referentiel = 'isfan'
AND nom_sel_nn = i.num_nom
AND (LOWER(c.famille) = LOWER(i.famille) OR c.famille IS NULL)
);
-- 0
SELECT ROW_COUNT() AS "ISFAN upd après correction sur nom_sel_nn";
/tags/v5.7-arrayanal/scripts/modules/cel/Makefile
New file
0,0 → 1,195
# Ce Makefile effectue les substitutions de nom de base de données
# nécessaire au préalable de l'application des scripts SQL
 
# Cela est d'un part moins complexe:
# - qu'un script PHP (interpréteur, getopt, framework, ...)
# - qu'un shell-script (lancement avec make)
# et d'autre part plus maintenable qu'un shell-script car
# le versionnage des fichiers (inc ".current") permet certaines facilités.
 
 
# TODO:
# idéalement, ce Makefile devrait permettre une bonne gestion du jeu de dépendances
# entre les scripts, seulement le lancement d'un script pouvant nécessiter un login/mdp
# il est difficile de vouloir rester "simple".
# Ce serait cependant la meilleure manière de procéder, ainsi "maj2" ne serait lancé qu'en
# cas de succès de "maj1", celui-ci pouvant être détecté comme "déjà exécuté" ou non.
# cf target "maj1" ci-dessous
 
 
# à l'aide de, note certains de ces fichiers n'ont pas cours dans le cadre de la maj1 (septembre 2013)
# echo $(egrep -l 'BASE(SOURCE|EDIT|ANNUAIRE)' *.sql)
fichiers = cel_references.sql dedup-ordre-201307.sql fix-utilisateur-32.sql maj-cleanup-201307.sql maj-nom-ret.sql \
maj-referentiel-201307.sql maj-referentiel-und-201307.sql maj-struct-201307.sql redempteur.sql \
referonosaure.sql \
.current
 
# la base de données à modifier
alterdb ?= tb_cel_test
 
# pour bdtfx, bdtxa, isfan, nvjfl, nva, baseflor, ... lecture seule;
# utilisée pour actualiser les enregistrements de cel_obs dans referonosaure.sql
sourcedb ?= tb_eflore
 
# pour annuaire_tela, lecture seule;
# utilisée pour initialiser cel_utilisateurs dans maj-struct-201307.sql
annuairedb ?= tela_prod_v4
 
bdtfx ?= 1_01
bdtxa ?= 1_00
isfan ?= 2013
bdtfx_table = bdtfx_v$(bdtfx)
bdtxa_table = bdtxa_v$(bdtxa)
isfan_table = isfan_v$(isfan)
 
# TODO: simply override bdd_user
ifdef bdd_user
bdd_user_h = -u$(bdd_user)
endif
 
ifneq ($(origin bdd_pass), undefined)
bdd_pass_h = "-p$(bdd_pass)"
endif
 
mysqlbin ?= mysql
mysqlcmd = $(mysqlbin) $(bdd_user_h) $(bdd_pass_h)
 
# macro utilisable pour les targets nécessitant de tester la présence d'un couple (base,table)
# exemples:
# * $(call is_table,tb_eflore,bdtfx_v1_01)
# * $(call is_table,$(annuairedb),annuaire_tela)
# argument 1: base de données
# argument 2: table
is_table = $(mysqlcmd) -N $(1) <<<"DESC $(2)" &> /dev/null
 
# macro utilisable pour effectuer des substitutions:
do_subst = sed -e "1i--\n-- fichier d'origine: \"${1}\"\n" \
-e 's/`BASEEDIT`/`$(alterdb)`/g' \
-e 's/`BASEANNUAIRE`/`$(annuairedb)`/g' \
-e 's/`BASESOURCE`/`$(sourcedb)`/g' \
-e 's/`TABLEBDTFX`/`$(bdtfx_table)`/g' \
-e 's/`TABLEBDTXA`/`$(bdtxa_table)`/g' \
-e 's/`TABLEISFAN`/`$(isfan_table)`/g' \
-e 's/TABLEBDTFX/`$(bdtfx_table)`/g' \
-e 's/TABLEBDTXA/`$(bdtxa_table)`/g' \
-e 's/TABLEISFAN/`$(isfan_table)`/g' \
$(1)
 
# default target
help:
@echo "make [alterdb=<$(alterdb)>] [sourcedb=<$(sourcedb)>] [annuairedb=<$(annuairedb)>] [bdtfx=<$(bdtfx)>] [bdtxa=<$(bdtxa)>] [isfan=$(isfan)] [bdd_user=\"\"] [bdd_pass=\"\"] [mysqlbin=mysql]"
@echo "make o_maj1 mysqlbin=/usr/local/mysql/bin/mysql bdd_user=telabotap bdd_pass=XXX"
 
# génère les fichiers avec les bases de données souhaitées
compile: reset
sed -i -e 's/`BASEEDIT`/`$(alterdb)`/g' \
-e 's/`BASEANNUAIRE`/`$(annuairedb)`/g' \
-e 's/`BASESOURCE`/`$(sourcedb)`/g' \
-e 's/TABLEBDTFX/`$(bdtfx_table)`/g' \
-e 's/TABLEBDTXA/`$(bdtxa_table)`/g' \
-e 's/`TABLEISFAN`/`$(isfan_table)`/g' \
$(fichiers)
printf "Attention: les changements s'appliqueront sur la base \"%s\"\nLes sources utilisées seront: annuaire=\"%s\" , sources=\"%s\" (%s,%s,%s)\n(Ctrl+C pour interrompre, Enter pour continuer)\n" \
`grep ^BASEEDIT .current|cut -d '\`' -f2` \
`grep ^BASEANNUAIRE .current|cut -d '\`' -f2` \
`grep ^BASESOURCE .current|cut -d '\`' -f2` \
`grep ^TABLE_BDTFX .current|cut -d '=' -f2` \
`grep ^TABLE_BDTXA .current|cut -d '=' -f2` \
`grep ^TABLE_ISFAN .current|cut -d '=' -f2`
read
 
reset:
svn revert -q $(fichiers)
 
# supprime les fichiers "compilés" (concaténation de plusieurs scripts SQL substitués)
clean:
rm -f *.comp.sql
 
### mises à jour
 
# mise à jour de septembre 2013
# spécifier les targets dans l'ordre (cf A_LIRE.txt)
 
 
# première version: substitution des fichiers: pas bon
# attention, si un prérequis ne génère pas de SQL, cela n'empêchera pas le fichier
# final de maj d'être généré,
#maj1: compile cel_references maj-struct-201307 maj-cleanup-201307 fix-utilisateur-32 dedup-ordre-201307 maj-referentiel-201307
# echo done
 
o_maj1: fichiers_generes = $(addsuffix .comp.sql,$(filter-out clean,$?))
o_maj1: clean o_cel_references o_maj-struct-201307 o_maj-cleanup-201307 o_fix-utilisateur-32 o_dedup-ordre-201307 o_maj-referentiel-201307 o_referonosaure
cat $(fichiers_generes) > maj1.comp.sql
echo done
 
### fin: mises à jour
 
 
### tools
 
check_cel_obs:
$(call is_table,$(alterdb),cel_obs)
 
### fin: tools
 
 
### mises à jour individuelles (scripts)
### pour chacun d'entre-eux, deux versions existent,
### 1) L'un compile (après substitution des noms dans le fichier SQL original)
### et pipe vers mysql directement, ce qui suppose aussi un .my.cnf ou autre
### 2) L'autre (préfixé par o_), renvoie le fichier substitué en sortie standard
### et le target principal s'occupe de concaténer et de créer un fichier de destination
### Cette méthode est de loin préférable et conforme à la philosophie Makefile
cel_references:
$(call is_table,$(sourcedb),$(bdtfx_table))
$(call is_table,$(sourcedb),nvjfl_v2007)
$(call is_table,$(sourcedb),nva_index_v2_03)
$(call is_table,$(alterdb),cel_references) || $(mysqlcmd) < cel_references.sql
o_cel_references:
$(call is_table,$(sourcedb),$(bdtfx_table))
$(call is_table,$(sourcedb),nvjfl_v2007)
$(call is_table,$(sourcedb),nva_index_v2_03)
$(call is_table,$(alterdb),cel_references) || $(call do_subst,cel_references.sql) > $@.comp.sql
 
maj-struct-201307: check_cel_obs
$(call is_table,$(annuairedb),annuaire_tela)
$(mysqlcmd) -N $(alterdb) <<<"DESC cel_obs nom_sel"|grep -q 601 || $(mysqlcmd) < maj-struct-201307.sql
o_maj-struct-201307: check_cel_obs
$(call is_table,$(annuairedb),annuaire_tela)
$(mysqlcmd) -N $(alterdb) <<<"DESC cel_obs nom_sel"|grep -q 601 || $(call do_subst,maj-struct-201307.sql) > $@.comp.sql
 
maj-cleanup-201307: check_cel_obs
! $(mysqlcmd) -N $(alterdb) <<<"SELECT 1 FROM cel_obs WHERE nom_ret = 'null' LIMIT 1"|grep -q 1 || $(mysqlcmd) < maj-cleanup-201307.sql
o_maj-cleanup-201307:
# tb_cel_test clean
! $(mysqlcmd) -N $(alterdb) <<<"SELECT 1 FROM cel_obs WHERE nom_ret = 'null' LIMIT 1"|grep -q 1 || $(call do_subst,maj-cleanup-201307.sql) > $@.comp.sql
 
fix-utilisateur-32: check_cel_obs
$(mysqlcmd) -N $(alterdb) <<<"DESC cel_obs ce_utilisateur"|grep -q 255 || $(mysqlcmd) < fix-utilisateur-32.sql
o_fix-utilisateur-32: check_cel_obs
$(mysqlcmd) -N $(alterdb) <<<"DESC cel_obs ce_utilisateur"|grep -q 255 || $(call do_subst,fix-utilisateur-32.sql) > $@.comp.sql
 
dedup-ordre-201307: check_cel_obs
#$(mysqlcmd) -N $(alterdb) <<<'SELECT distinct ce_utilisateur FROM `cel_obs` GROUP BY ce_utilisateur, ordre HAVING COUNT(*) > 1'|grep -q . || $(mysqlcmd) < dedup-ordre-201307.sql
$(mysqlcmd) -N $(alterdb) <<<"SHOW INDEX FROM cel_obs"|grep -q couple_user_ordre || $(mysqlcmd) < dedup-ordre-201307.sql
o_dedup-ordre-201307: check_cel_obs
# l'index doit sur cel_obs doit avoir deux lignes dont le champs "non_unique" = 0
$(mysqlcmd) -N $(alterdb) <<<"SHOW INDEX FROM cel_obs"|grep -w id_obs|awk '{print $$2}'|tr -d "\n"|grep -q 00 || $(call do_subst,dedup-ordre-201307.sql) > $@.comp.sql
 
# maj-referentiel-201307.sql: # pas de test aisé et rapide
# doit passer APRÈS o_maj-cleanup-201307 (pas de nom_ret_nn = 0)
o_maj-referentiel-201307: check_cel_obs
$(call do_subst,maj-referentiel-201307.sql) > $@.comp.sql
 
# pas de test aisé non plus pour savoir s'il doit repasser
# néanmoins c'est un script sur (peut-être invoqué répétivement)
o_referonosaure: check_cel_obs
$(call do_subst,referonosaure.sql) > $@.comp.sql
 
 
 
# pour une prochaine maj
maj-nom-ret:
$(mysqlcmd) -N <<<'SELECT count(1) FROM `$(alterdb)`.`cel_obs` c LEFT JOIN `$(sourcedb)`.`$(bdtfx_table)` b on (c.nom_ret = b.nom_sci) WHERE nom_ret_nn = 0 AND c.nom_ret != "" AND id_observation NOT IN ( SELECT id_observation FROM `$(alterdb)`.`cel_obs` c, `$(sourcedb)`.`$(bdtfx_table)` b WHERE c.nom_ret = b.nom_sci AND c.nom_ret_nn = 0 );'|grep -q 0
o_maj-nom-ret:
$(call do_subst,maj-nom-ret.sql) > $@.comp.sql
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/cel/fix-utilisateur-32.sql
New file
0,0 → 1,26
-- corriger les addresses erronées:
-- SELECT distinct ce_utilisateur FROM `BASEEDIT`.`cel_obs` WHERE LENGTH(ce_utilisateur) = 32 AND ce_utilisateur LIKE '%@%' AND ce_utilisateur NOT REGEXP '\.(fr|com)$';
 
ALTER TABLE `BASEEDIT`.`cel_obs` MODIFY ce_utilisateur VARCHAR(255) NOT NULL;
 
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = CONCAT(SUBSTRING_INDEX(ce_utilisateur,'@', 1), '@apprenti.isa-lille.fr') WHERE ce_utilisateur LIKE '%@apprenti.isa-%';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'amardeilh.michel@club-internet.fr' WHERE ce_utilisateur = 'amardeilh.michel@club-internet.f';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'claude.figureau.plantnet@gmail.com' WHERE ce_utilisateur = 'claude.figureau.plantnet@gmail.c';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'francoise.delachaussee@dbmail.com' WHERE ce_utilisateur = 'francoise.delachaussee@dbmail.co';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'lucie.boust@proxalys-environnement.com' WHERE ce_utilisateur = 'lucie.boust@proxalys-environneme';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'alexis.cochereau@plante-et-cite.fr' WHERE ce_utilisateur = 'alexis.cochereau@plante-et-cite.';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'environnement@andernos-les-bains.fr' WHERE ce_utilisateur = 'environnement@andernos-les-bains';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'hugounenc.guilhem@mairie-perpignan.fr' WHERE ce_utilisateur = 'hugounenc.guilhem@mairie-perpign';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'jean-pierre-blanchet@club-internet.fr' WHERE ce_utilisateur = 'jean-pierre-blanchet@club-intern';
UPDATE `BASEEDIT`.`cel_obs` SET ce_utilisateur = 'stephanie.grosset@ville-montpellier.fr' WHERE ce_utilisateur = 'stephanie.grosset@ville-montpell';
 
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = CONCAT(SUBSTRING_INDEX(ce_utilisateur,'@', 1), '@apprenti.isa-lille.fr') WHERE ce_utilisateur LIKE '%@apprenti.isa-%';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'amardeilh.michel@club-internet.fr' WHERE ce_utilisateur = 'amardeilh.michel@club-internet.f';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'claude.figureau.plantnet@gmail.com' WHERE ce_utilisateur = 'claude.figureau.plantnet@gmail.c';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'francoise.delachaussee@dbmail.com' WHERE ce_utilisateur = 'francoise.delachaussee@dbmail.co';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'lucie.boust@proxalys-environnement.com' WHERE ce_utilisateur = 'lucie.boust@proxalys-environneme';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'alexis.cochereau@plante-et-cite.fr' WHERE ce_utilisateur = 'alexis.cochereau@plante-et-cite.';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'environnement@andernos-les-bains.fr' WHERE ce_utilisateur = 'environnement@andernos-les-bains';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'hugounenc.guilhem@mairie-perpignan.fr' WHERE ce_utilisateur = 'hugounenc.guilhem@mairie-perpign';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'jean-pierre-blanchet@club-internet.fr' WHERE ce_utilisateur = 'jean-pierre-blanchet@club-intern';
UPDATE `BASEEDIT`.`cel_images` SET ce_utilisateur = 'stephanie.grosset@ville-montpellier.fr' WHERE ce_utilisateur = 'stephanie.grosset@ville-montpell';
/tags/v5.7-arrayanal/scripts/modules/cel/cel.ini
New file
0,0 → 1,31
version="1_00"
dossierTsv = "{ref:dossierDonneesEflore}cel/2011-11-10/"
dossierSql = "{ref:dossierTsv}"
bdd_nom = "tb_cel"
 
[tables]
obs = cel_inventory
obsImages = cel_obs_images
images = cel_images
motsClesImages = cel_mots_cles_images
motsClesObs = cel_mots_cles_obs
zoneGeo = locations
 
[fichiers]
structureSql = "cel_v{ref:version}.sql"
obs = "{ref:tables.obs}.tsv"
obsImages = "{ref:tables.obsImages}.tsv"
images = "{ref:tables.images}.tsv"
motsClesImages = "{ref:tables.motsClesImages}.tsv"
motsClesObs = "{ref:tables.motsClesObs}.tsv"
zoneGeo = "{ref:tables.zoneGeo}.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
obs = "{ref:dossierTsv}{ref:fichiers.obs}"
obsImages = "{ref:dossierTsv}{ref:fichiers.obsImages}"
images = "{ref:dossierTsv}{ref:fichiers.images}"
motsClesImages = "{ref:dossierTsv}{ref:fichiers.motsClesImages}"
motsClesObs = "{ref:dossierTsv}{ref:fichiers.motsClesObs}"
zoneGeo = "{ref:dossierTsv}{ref:fichiers.zoneGeo}"
 
/tags/v5.7-arrayanal/scripts/modules/cel/maj-struct-201307.sql
New file
0,0 → 1,21
-- dépot "cel", r1739
ALTER TABLE `BASEEDIT`.`cel_obs` MODIFY nom_sel VARCHAR(601) NULL DEFAULT NULL;
ALTER TABLE `BASEEDIT`.`cel_obs` MODIFY nom_ret VARCHAR(601) NULL DEFAULT NULL;
 
 
-- dépot "cel", r1739
CREATE INDEX nom_referentiel ON `BASEEDIT`.`cel_obs` (`nom_referentiel`(5));
 
-- depot "cel", r1809
ALTER TABLE `BASEEDIT`.`cel_obs` MODIFY altitude INTEGER(5) DEFAULT NULL;
 
-- depot "cel", r1811
CREATE OR REPLACE VIEW `BASEEDIT`.`cel_utilisateurs` AS
SELECT at.U_ID AS id_utilisateur, at.U_SURNAME AS prenom, at.U_NAME AS nom, at.U_MAIL AS courriel, at.U_PASSWD AS mot_de_passe,
ui.licence_acceptee, ui.admin, ui.preferences, ui.date_premiere_utilisation
FROM `BASEANNUAIRE`.`annuaire_tela` AS at
LEFT JOIN `BASEEDIT`.`cel_utilisateurs_infos` AS ui ON (ui.id_utilisateur = at.U_ID);
 
-- MySQL 5.6.5 only:
-- ALTER TABLE `BASEEDIT`.`cel_obs` CHANGE COLUMN `date_modification` `date_modification` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;
-- otherwise, convert `date_modification` to TIMESTAMP ?
/tags/v5.7-arrayanal/scripts/modules/cel/sphinx-maj-nom-ret.php
New file
0,0 → 1,203
<?php
/*
* @author Raphaël Droz <raphael@tela-botanica.org>
* @copyright Copyright (c) 2011, 2013 Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
*
* Corrige les erreurs de saisie de nom à l'aide d'une recherche via un index sphinx
* pour les observations ayant un nom saisi et dont l'un au moins de nom_ret[nn],
* nt ou famille est NULL ou vide.
*
*/
 
// time php -d memory_limit=1024M sphinx-maj-nom-ret.php 0 > sphinx-maj.log
// 23 secondes
 
// settings
define('USE_NVJFL', FALSE);
define('ESCAPE_ON_SPHINX_SYNERROR', TRUE);
 
define('TRY_FORCE_START_LINE', TRUE);
define('TRY_SPLIT', TRUE);
define('TRY_EXACT', TRUE);
define('TRY_REF', TRUE);
define('TRY_SPLIT_AND_AUTEUR', FALSE);
define('TRY_REMOVE_L', TRUE);
 
define('M_TRY_SPLIT', 0x01);
define('M_TRY_EXACT', 0x02);
define('M_TRY_REF', 0x04);
define('M_TRY_SPLIT_AND_AUTEUR', 0x08);
 
error_reporting(E_ALL);
$db = mysql_connect('localhost', 'root', '') or die('no mysql');
mysql_select_db('tb_cel', $db);
mysql_query("SET NAMES utf8", $db) or die('no sphinx');
$dbs = mysql_connect('127.0.0.1:9306', NULL, NULL, TRUE);
 
$req = <<<EOF
SELECT id_observation, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn, nt, famille, nom_referentiel
FROM `cel_obs`
WHERE nom_sel IS NOT NULL AND nom_sel != '' AND
id_observation BETWEEN %d AND %d AND
( nom_ret IS NULL or nom_ret = ''
OR nt IS NULL or nt = 0 or nt = ''
OR famille IS NULL or famille = '' )
LIMIT %d, %d
EOF;
// non: car nom_ret_nn peut-être légitimement à 0 [taxon identifié, sans nom_retenu]
// OR nom_ret_nn IS NULL or nom_ret_nn = 0 or nom_ret_nn = ''
 
 
array_shift($argv);
$start = array_shift($argv);
$max = array_shift($argv);
$chunk_size = array_shift($argv);
 
if(!$start) $start = 0;
// 1036314
if(!$max) $max = intval(mysql_fetch_assoc(mysql_query("SELECT MAX(id_observation) AS max FROM cel_obs", $db))['max']) + 1;
if(!$chunk_size) $chunk_size = 50000;
 
 
// escape sphinx
$from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=', "'", "\x00", "\n", "\r", "\x1a" );
$to = array ( '\\\\', '\\\(','\\\)','\\\|','\\\-','\\\!','\\\@','\\\~','\\\"', '\\\&', '\\\/', '\\\^', '\\\$', '\\\=', "\\'", "\\x00", "\\n", "\\r", "\\x1a" );
 
 
$stats = ['no_nom_sel' => ['count' => 0, 'data' => [] ],
'not found' => ['count' => 0, 'data' => [] ],
'too many' => ['count' => 0, 'data' => [] ],
'fixable' => ['count' => 0, 'data' => [] ],
'sauvages' => ['count' => 0, 'data' => [] ],
'sphinx errors' => ['count' => 0, 'data' => [] ],
'ref pb' => ['count' => 0, 'data' => [] ], ];
 
$sphinx_req = sprintf("SELECT * FROM i_bdtfx %s WHERE MATCH('%%s') LIMIT 5", USE_NVJFL ? ", i_nvjfl" : "");
 
for($current = 0; $current < intval($max/$chunk_size) + 1; $current++) {
// printf("current = %d, chunk_size = %d, max = %d (rmax = %d) [real limit: %d]\n", $current, $chunk_size, $max, intval($max/$chunk_size) + 1, $current*$chunk_size);
// printf(strtr($req, "\n", " ") . "\n", $start, $max, $current*$chunk_size, $chunk_size);
$data = mysql_query(sprintf($req, $start, $max, $current*$chunk_size, $chunk_size), $db);
if(!$data) { var_dump(mysql_error()); die('end'); }
while($d = mysql_fetch_assoc($data)) {
$n = trim($d['nom_sel']);
//d: fprintf(STDERR, "$n\n");
 
if(!$n) {
$stats['no_nom_sel']['count']++;
// $stats['no_nom_sel']['data'][] = [$d['id_observation'], $n];*/
continue;
}
 
if($n == 'Autre(s) espèce(s) (écrire le/les nom(s) dans les notes)' ||
$n == '-') {
$stats['sauvages']['count']++;
// $stats['sauvages']['data'][] = [$d['id_observation'], $n];
continue;
}
 
$MASQUE = 0;
 
if(TRY_REMOVE_L) {
$n = str_replace(' L.','', $n);
}
 
$orig_n = $n;
 
recherche:
if(TRY_FORCE_START_LINE && !_has($MASQUE, M_TRY_EXACT)) {
$n = '^' . $n;
}
 
$s = mysql_query(sprintf($sphinx_req, $n), $dbs);
 
 
if(!$s && ESCAPE_ON_SPHINX_SYNERROR) {
$s = mysql_query(sprintf($sphinx_req, str_replace($from,$to,$n)), $dbs);
}
if(!$s) {
$stats['sphinx errors']['count']++;
// $stats['sphinx errors']['data'][] = [$d['id_observation'], $orig_n];
continue;
}
 
$c = mysql_num_rows($s);
//d: fprintf(STDERR, "\t search [nb:%d] \"%s\" (msk:%d)\n", $c, $n, $MASQUE);
 
if($c == 0) {
if(TRY_SPLIT && !_has($MASQUE, M_TRY_SPLIT)) {
require_once('lib-split-auteur.php');
$MASQUE |= M_TRY_SPLIT;
// $n = RechercheInfosTaxonBeta::supprimerAuteur($orig_n);
// list($ret, $m) = RechercheInfosTaxonBeta::contientAuteur($orig_n);
$ret = RechercheInfosTaxonBeta::supprimerAuteurBis($orig_n, $m);
if($ret) {
// printf("===================== SPLIT: contientAuteur \"%s\" [@%s @%s)\n", $orig_n, $ret, $m);
$n = sprintf('%s @auteur %s', $ret, $m);
goto recherche;
}
}
if(TRY_SPLIT_AND_AUTEUR && !_has($MASQUE, M_TRY_SPLIT_AND_AUTEUR) && strpos($orig_n, ' ') !== FALSE) {
require_once('lib-split-auteur.php');
$MASQUE |= M_TRY_SPLIT_AND_AUTEUR;
$ns = RechercheInfosTaxonBeta::supprimerAuteur($orig_n);
if($ns) {
$a = trim(substr($orig_n, strlen($n)));
$n = sprintf("%s @auteur %s", $ns, $a);
// echo "===================== SPLIT N/A: $n\n";
goto recherche;
}
}
 
$stats['not found']['count']++;
// $stats['not found']['data'][] = [$d['id_observation'], $orig_n];
continue;
}
 
if($c > 1) {
 
if($c == 2) {
if(mysql_fetch_array($s)['group_id'] !=
mysql_fetch_array($s)['group_id']) {
// recherche donne seulement 2 résultats dans 2 référentiels
// potentiellement fixable si l'on peut se référer à $d['nom_referentiel']
$stats['ref pb']['count']++;
// $stats['ref pb']['data'][] = [$d['id_observation'], $orig_n];
continue;
}
}
 
if(TRY_EXACT && !_has($MASQUE, M_TRY_EXACT)) {
$MASQUE |= M_TRY_EXACT;
$n = '"^' . trim($orig_n) . '$"';
goto recherche;
}
if(TRY_REF && isset($d['nom_referentiel']) && !_has($MASQUE, M_TRY_REF)) {
$MASQUE |= M_TRY_REF;
$n = $orig_n . ' @group_id ' . $d['nom_referentiel'];
goto recherche;
}
 
$stats['too many']['count']++;
// $stats['too many']['data'][] = [$d['id_observation'], $orig_n];
continue;
}
 
 
ok:
$stats['fixable']['count']++;
// $stats['fixable']['data'][] = [$d['id_observation'], $orig_n];
 
}
}
 
function _has($v, $r) {
return ($v & $r) == $r;
}
 
 
array_walk($stats, function(&$v) { unset($v['data']); });
print_r($stats);
printf("total traité: %d\n", array_sum(array_map(function($v) { return $v['count']; }, $stats)));
/tags/v5.7-arrayanal/scripts/modules/cel/maj-cleanup-201307.sql
New file
0,0 → 1,62
-- date d'observation dans le futur
UPDATE `BASEEDIT`.`cel_obs` SET date_observation = NULL WHERE date_observation > now();
-- cleanup
UPDATE `BASEEDIT`.`cel_obs` SET date_observation = NULL WHERE date_observation = '0000-00-00 00:00:00';
-- cleanup
UPDATE `BASEEDIT`.`cel_obs` SET latitude = NULL, longitude = NULL WHERE longitude = 0 and latitude = 0;
 
-- referentiels: 65800 NULL, 13000 ''
UPDATE `BASEEDIT`.`cel_obs` SET nom_referentiel = SUBSTRING_INDEX(nom_referentiel, ':', 1);
UPDATE `BASEEDIT`.`cel_obs` SET nom_referentiel = 'bdtfx' WHERE nom_referentiel IN ('bdtfx_v1','bdnff');
 
-- pas de raison historique mémorisée à une différence '' vs NULL
UPDATE `BASEEDIT`.`cel_obs` SET nom_referentiel = NULL where nom_referentiel = '';
 
-- uniformisation NULL / vide pour nom_sel
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = NULL WHERE nom_sel = '';
 
-- uniformisation NULL / vide pour nom_sel_nn
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel_nn = NULL WHERE nom_sel_nn = 0;
 
-- restauration de nom_sel vraisemblablement valides, mais vides: 48 obs
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = nom_ret WHERE nom_sel IS NULL AND nom_ret IS NOT NULL AND nom_ret != '' AND nom_sel_nn IS NOT NULL;
 
 
-- suppression des infos générées pour les observations dont le nom_sel à été supprimé par l'utilisateur
-- 3380
UPDATE `BASEEDIT`.`cel_obs` c SET
c.nom_ret = '',
c.nom_sel_nn = NULL,
c.nom_ret = NULL,
c.nom_ret_nn = NULL,
c.nt = NULL,
c.famille = NULL
WHERE nom_sel IS NULL OR nom_ret = 'undefined';
 
-- problème n°1: mauvais référentiel (bdtfx au lieu de bdtxa), on utilise les lieudit "bdtxa" pour
-- corriger les observations qui pourraient être étiquetées avec un mauvais nom_referentiel: 49 obs
CREATE TEMPORARY TABLE T_cleanref (lieu VARCHAR(255)) ENGINE=MEMORY AS ( SELECT DISTINCT TRIM(lieudit) FROM `BASEEDIT`.`cel_obs` WHERE nom_referentiel = 'bdtxa' );
UPDATE `BASEEDIT`.`cel_obs` SET nom_referentiel = 'bdtxa' WHERE nom_referentiel != 'bdtxa' AND lieudit != '' AND lieudit IN (SELECT lieu FROM T_cleanref);
DROP TEMPORARY TABLE T_cleanref;
 
-- problème n°2: backslashes + newline: 90 + 217 obs
UPDATE `BASEEDIT`.`cel_obs` SET commentaire = REPLACE(commentaire, "\n\\\'", "'");
UPDATE `BASEEDIT`.`cel_obs` SET commentaire = REPLACE(commentaire, "\\\'", "'");
 
-- problème n°3: ce_zone_geo inutile: 57802 obs
UPDATE `BASEEDIT`.`cel_obs` SET ce_zone_geo = NULL WHERE ce_zone_geo = 'INSEE-C:';
 
-- trim nom_sel
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = REPLACE(nom_sel, '\\', '');
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = TRIM(LEADING "." FROM TRIM("\t" FROM TRIM(nom_sel)));
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = TRIM(TRIM('\\' FROM TRIM('‘' FROM TRIM('‘' FROM TRIM('"' FROM nom_sel))))) WHERE nom_sel REGEXP '^[\\"‘’].*[\\"‘’]$';
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = TRIM("'" FROM nom_sel) WHERE nom_sel REGEXP "^'.*'$"; -- ' relax emacs
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = TRIM('"' FROM nom_sel) WHERE nom_sel REGEXP '^"[^"]+$';
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = REPLACE(nom_sel, 'A©', 'é') WHERE nom_sel LIKE '%A©%';
-- nom_ret = "null"
UPDATE `BASEEDIT`.`cel_obs` SET nom_ret = NULL WHERE nom_ret = 'null';
 
 
-- inconsistence de date_transmission avec transmission (cf r1860)
UPDATE `BASEEDIT`.`cel_obs` SET date_transmission = date_creation WHERE date_transmission IS NULL AND transmission = 1;
UPDATE `BASEEDIT`.`cel_obs` SET date_transmission = NULL WHERE date_transmission IS NOT NULL AND transmission = 0;
/tags/v5.7-arrayanal/scripts/modules/cel/maj-nom-ret.sql
New file
0,0 → 1,45
/*
Cleanup des observation ayant un nom_ret_nn à 0 (mais un nom_ret défini...):
En effet, on peut pour l'instant POSTer $nom_ret, d'où bien souvent nom_sel == nom_ret, cependant nom_ret_nn = 0
(pas d'autodétection).
Nous pourrions donc les nullifier sans remord, ... mais ...
nom_ret_nn == 0 est VALIDE (car bdtfx.num_nom_retenu == 0 est "valide", 3960 taxons sont "orphelins" de nom_retenu)
 
1) créer un index pour les jointures:
CREATE INDEX i_nom_ret ON `BASESOURCE`.`TABLEBDTFX` (`nom_sci`(8))
2) regarder les num_nom_ret orphelins de taxon en BDTFX:
SELECT * FROM `BASESOURCE`.`TABLEBDTFX` WHERE num_nom_retenu = 0; # 3960
3) regarder les num_nom_ret orphelins de taxon en BDTXA:
SELECT * FROM `BASESOURCE`.`TABLEBDTXA` WHERE num_nom_retenu = 0; # 0
4) regarder les orphelins équivalents dans `BASEEDIT`.`cel_obs`:
SELECT date_observation, SUBSTRING(nom_sel, 1, 50), nom_ret_nn, nom_ret, b.nom_sci FROM `BASEEDIT`.`cel_obs` c LEFT JOIN `BASESOURCE`.`TABLEBDTFX` b on (c.nom_ret = b.nom_sci) WHERE nom_ret_nn = 0; # 7740
 
Donc ceux dont le nom_ret à été POSTé manuellement et qui matchent le nom_sci de BDTFX : on les conserve.
Mais les autres, qui ont un nom_ret probablement erroné et un nom_ret_nn à 0, on NULLify les données car elles seront théoriquement correctement autoregénérées !
 
Cela concerne:
SELECT date_observation, SUBSTRING(nom_sel, 1, 50), nom_ret_nn, nom_ret, b.nom_sci FROM `BASEEDIT`.`cel_obs` c LEFT JOIN `BASESOURCE`.`TABLEBDTFX` b ON (c.nom_ret = b.nom_sci) WHERE nom_ret_nn = 0
AND c.nom_ret != '' AND id_observation NOT IN ( SELECT id_observation FROM `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b WHERE c.nom_ret = b.nom_sci AND c.nom_ret_nn = 0 ); # 960
*/
-- D'où la requête :
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel_nn = NULL, nom_ret = NULL, nom_ret_nn = NULL, nt = NULL, famille = NULL WHERE id_observation IN
( SELECT id_observation FROM `BASEEDIT`.`cel_obs` c LEFT JOIN `BASESOURCE`.`TABLEBDTFX` b on (c.nom_ret = b.nom_sci) WHERE nom_ret_nn = 0
AND c.nom_ret != '' AND id_observation NOT IN ( SELECT id_observation FROM `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b WHERE c.nom_ret = b.nom_sci AND c.nom_ret_nn = 0 ) );
 
-- TODO
-- UPDATE `BASEEDIT`.`cel_obs` SET nom_ret_nn = NULL WHERE nom_ret_nn = 0;
 
/*
UPDATE `BASEEDIT`.`cel_obs` SET nom_sel = NULL, nom_sel_nn = NULL, nom_ret = NULL, nom_ret_nn = NULL, nt = NULL, famille = NULL,
FROM `BASEEDIT`.`cel_obs`
WHERE nom_sel IS NULL AND
(
(nom_ret IS NOT NULL AND nom_ret != '') OR
(nt IS NOT NULL AND nt != 0 AND nt != '') OR
(famille IS NOT NULL AND famille != '')
)
 
-- pas de test de nullité sur nom_ret_nn qui peut légitimement être NULL
(nom_ret_nn IS NOT NULL AND nom_ret_nn != 0 AND nom_ret_nn != '') OR
*/
 
/tags/v5.7-arrayanal/scripts/modules/cel/referonosaure_fromNomRet.sql
New file
0,0 → 1,105
/*
Ceci est une version dérivée de referonosaure.sql dans laquel est postulé que
les nom_ret sont un critère tangible.
En effet, sauf bug, il n'y a pas de raison qu'un num_nom_retenu soit moins fiable qu'un num_nom.
Cependant un taxon peut changer de num_nom_retenu, et auquel cas c'est bien referonosaure.sql
qu'il faut utiliser.
Cependant pour un simple "rafraîchissement" des chaînes de caractères attribuées au noms retenus,
ce script, referonosaure_fromNomRet.sql, doit suffire.
 
 
Attention, les nom_sel_nn = 0 doivent avoir disparus de cel_obs *AU PRÉALABLE* car le test
n'est pas effectué.
cf: maj-cleanup-201307.sql
*/
 
 
/* test:
SELECT c.nom_ret_nn, c.nom_ret, b.nom_sci, b.auteur, c.famille, b.famille, c.nt, b.num_taxonomique
FROM cel_obs c, tb_eflore.bdtfx_v1_01 b
WHERE (
nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0
AND nom_referentiel = 'bdtfx'
AND nom_ret_nn = num_nom
AND (LOWER(c.famille) = LOWER(b.famille) OR c.famille IS NULL)
AND (c.famille != b.famille OR c.nom_ret != CONCAT(b.nom_sci, ' ', b.auteur) OR c.nt != b.num_taxonomique)
);
= 2 taxons: 75134 et 75468 (changement de nt)
*/
 
-- l'update BDTFX avec nom_sel_nn et nom_ret_nn corrects
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTFX` b SET
c.nom_ret = CONCAT(b.nom_sci, ' ', b.auteur),
c.nt = b.num_taxonomique,
c.famille = b.famille
WHERE (
nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0
AND nom_referentiel = 'bdtfx'
AND nom_ret_nn = num_nom
AND (c.mots_cles_texte IS NULL OR c.mots_cles_texte NOT LIKE '%WidgetFlorileges Sauvages%') -- TODO: bug transferts multiples + mobile.js
AND (LOWER(c.famille) = LOWER(b.famille) OR c.famille IS NULL OR c.famille = 'Famille inconnue')
);
-- 25584
SELECT ROW_COUNT() AS "BDTFX upd après correction sur nom_ret_nn + nom_sel_nn";
 
 
 
-- l'update BDTXA avec nom_sel_nn et nom_ret_nn corrects
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEBDTXA` a SET
c.nom_ret = CONCAT(a.nom_sci, ' ', a.auteur),
c.nt = a.num_tax,
c.famille = a.famille
WHERE (
nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0
AND nom_referentiel = 'bdtxa'
AND nom_ret_nn = num_nom
AND (LOWER(c.famille) = LOWER(a.famille) OR c.famille IS NULL)
);
-- 2
SELECT ROW_COUNT() AS "BDTXA upd après correction sur nom_ret_nn + nom_sel_nn";
 
 
 
 
-- l'update ISFAN avec nom_sel_nn et nom_ret_nn corrects --
UPDATE `BASEEDIT`.`cel_obs` c, `BASESOURCE`.`TABLEISFAN` i SET
c.nom_ret = CONCAT(i.nom_sci, ' ', i.auteur),
c.nt = i.num_taxonomique,
c.famille = i.famille
WHERE (
nom_sel_nn IS NOT NULL AND nom_ret_nn IS NOT NULL AND nom_ret_nn != 0
AND nom_referentiel = 'isfan'
AND nom_ret_nn = num_nom
AND (LOWER(c.famille) = LOWER(i.famille) OR c.famille IS NULL)
);
-- 2 ou 0
SELECT ROW_COUNT() AS "ISFAN upd après correction sur nom_ret_nn + nom_sel_nn";
 
 
 
/*
Pour observer les différences:
wdiff -w '$(tput bold;tput setaf 1)' -x '$(tput sgr0)' -y '$(tput bold;tput setaf 2)' -z '$(tput sgr0)' pre.log post.log | \
ansi2html.sh --palette=solarized | \
sed '/^[0-9]/{/span/!d}' > diff.html
 
# extract les familles ayant changé: sed '/^[0-9]/{/<\/span>$/!d}'
# lowercase toutes les familles: awk '{ NF=tolower($NF); print }'
 
 
# filtre sed: changements de famille "normaux"
/aceraceae.*sapindaceae/d
/scrophulariaceae.*plantaginaceae/d
/globulariaceae.*plantaginaceae/d
/Famille inconnue.*null/d
 
# changement "anormaux"
/rosaceae.*caprifoliaceae/d
/valerianaceae.*caprifoliaceae/d
 
 
 
SELECT nom_sel, nom_ret FROM cel_obs GROUP BY nom_sel, nom_ret INTO OUTFILE '/tmp/new.csv' ;
SELECT id_observation, nom_sel, nom_sel_nn, nom_ret, nom_ret_nn FROM cel_obs INTO OUTFILE '/tmp/id.csv' ;
$ wdiff x y|sed -n "/\x1b/p"|less
*/
/tags/v5.7-arrayanal/scripts/modules/cel/maj-referentiel-und-201307.sql
New file
0,0 → 1,100
/*
Mise à jour de réferentiels NULL ou vides pour les observations orphelines (sans nom_ret_nn)
2722 observations trouvées au 2013/07/19
*/
 
DROP PROCEDURE IF EXISTS getNomSci;
DROP PROCEDURE IF EXISTS getNomSciCount;
DROP PROCEDURE IF EXISTS getNomSciAuteur;
DROP PROCEDURE IF EXISTS getNomSciAuteurCount;
DROP PROCEDURE IF EXISTS cur;
 
delimiter |
 
-- obtient le nombre de matches sur nom_sel = nom_sci
CREATE PROCEDURE getNomSciCount(IN _nom varchar(500), OUT param1 INT)
BEGIN
SELECT sum(c) INTO param1 FROM (SELECT count(1) as c FROM `BASESOURCE`.`TABLEBDTFX` b WHERE nom_sci = _nom UNION ALL SELECT count(1) FROM `BASESOURCE`.`TABLEBDTXA` a WHERE nom_sci = _nom) AS req;
END
|
-- retourne les paramètres d'une match
CREATE PROCEDURE getNomSci(IN _nom varchar(500), OUT param1 char(5), OUT param2 varchar(601), OUT param3 INT, OUT param4 INT, OUT param5 varchar(255))
BEGIN
SELECT * INTO param1, param2, param3, param4, param5 FROM
(SELECT "bdtfx", CONCAT(b.nom_sci, ' ', b.auteur), b.num_nom, b.num_taxonomique, b.famille FROM `BASESOURCE`.`TABLEBDTFX` b WHERE nom_sci = _nom
UNION ALL
SELECT "bdtxa", CONCAT(a.nom_sci, ' ', a.auteur), a.num_nom, a.num_tax, a.famille FROM `BASESOURCE`.`TABLEBDTXA` a WHERE nom_sci = _nom) AS req;
END
|
 
-- obtient le nombre de matches sur nom_sel = CONCAT(nom_sci, " ", auteur)
-- quasiment identique à ci-dessus, sauf que nous excluons de la recherche de bdtfx et bdtxa les nom dont le nom d'auteur est ''
CREATE PROCEDURE getNomSciAuteurCount(IN _nom varchar(500), OUT param1 INT)
BEGIN
SELECT sum(c) INTO param1 FROM (SELECT count(1) as c FROM `BASESOURCE`.`TABLEBDTFX` b WHERE CONCAT(nom_sci, ' ', auteur) = _nom UNION ALL SELECT count(1) FROM `BASESOURCE`.`TABLEBDTXA` a WHERE CONCAT(nom_sci, ' ', auteur) = _nom) AS req;
END
|
-- retourne les paramètres d'une match
CREATE PROCEDURE getNomSciAuteur(IN _nom varchar(500), OUT param1 char(5), OUT param2 varchar(601), OUT param3 INT, OUT param4 INT, OUT param5 varchar(255))
BEGIN
SELECT * INTO param1, param2, param3, param4, param5 FROM
(SELECT "bdtfx", CONCAT(b.nom_sci, ' ', b.auteur), b.num_nom, b.num_taxonomique, b.famille FROM `BASESOURCE`.`TABLEBDTFX` b WHERE CONCAT(nom_sci, ' ', auteur) = _nom AND auteur != ''
UNION ALL
SELECT "bdtxa", CONCAT(a.nom_sci, ' ', a.auteur), a.num_nom, a.num_tax, a.famille FROM `BASESOURCE`.`TABLEBDTXA` a WHERE CONCAT(nom_sci, ' ', auteur) = _nom AND auteur != '') AS req;
END
|
 
CREATE PROCEDURE cur()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE subst INT DEFAULT 0;
DECLARE _id_observation bigint(20) DEFAULT 0;
DECLARE _nom varchar(255) DEFAULT NULL;
 
-- la requête principale de sélection des observations à mettre à jour
DECLARE cur1 CURSOR FOR SELECT id_observation, nom_sel FROM `BASEEDIT`.`cel_obs` WHERE nom_referentiel IS NULL AND nom_sel != '' AND nom_sel IS NOT NULL AND nom_ret_nn IS NULL; -- 78149
-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
 
OPEN cur1;
 
REPEAT
FETCH cur1 INTO _id_observation, _nom;
CALL getNomSciCount(_nom, @a);
-- SELECT _id_observation, _nom, @a;
IF @a = 1 THEN
CALL getNomSci(_nom, @_ref, @_nom, @_num_nom, @_num_tax, @_famille);
SELECT "updb: getNomSci", _id_observation, _nom, '=', @_ref, @_nom, @_num_nom, @_num_tax, @_famille;
UPDATE `BASEEDIT`.`cel_obs` c SET
c.nom_referentiel = @_ref,
c.nom_ret = @_nom,
c.nom_ret_nn = @_num_nom,
c.nt = @_num_tax,
c.famille = @_famille
WHERE id_observation = _id_observation;
SET subst = subst + 1;
/* ELSE
CALL getNomSciAuteurCount(_nom, @a);
IF @a = 1 THEN
CALL getNomSciAuteur(_nom, @_ref, @_nom, @_num_nom, @_num_tax, @_famille);
SELECT "updb: getNomSciAuteur", _id_observation, _nom, '=', @_ref, @_nom, @_num_nom, @_num_tax, @_famille;
UPDATE `BASEEDIT`.`cel_obs` c SET
c.nom_referentiel = @_ref,
c.nom_ret = @_nom,
c.nom_ret_nn = @_num_nom,
c.nt = @_num_tax,
c.famille = @_famille
WHERE id_observation = _id_observation;
SET subst = subst + 1;
END IF;*/
END IF;
UNTIL done END REPEAT;
select subst AS 'nombre de mises à jour effectuées';
CLOSE cur1;
END
 
 
 
|
 
delimiter ;
/tags/v5.7-arrayanal/scripts/modules/cel/lib-split-auteur.php
New file
0,0 → 1,165
<?php
/*
fork temporaire de cel/jrest/lib/RechercheInfosTaxonBeta.php
[php-5.4 & co]
*/
 
require_once('/home/raphael/cel/jrest/lib/Cel.php');
// require_once('/home/raphael/cel/jrest/lib/RechercheInfosTaxonBeta.php');
require_once('/home/raphael/cel/jrest/lib/NameParser.php');
 
class RechercheInfosTaxonBeta {
static function getSpaceNoAfter($nom_saisi, $pattern, $offset) {
if( ($q = strpos($nom_saisi, $pattern, max(0, $offset))) ) {
// position du premier espace après $pattern,
// ou position de fin de $pattern autrement
if(! ($r = strpos($nom_saisi, ' ', $offset + strlen($pattern))) )
return $offset + strlen($pattern);
return $r;
}
return FALSE;
}
 
static function supprimerAuteurBis($nom_saisi, &$auteur = null) {
$strip_pos = 600;
 
$before = 600;
$after = 0;
// temp var
$p = $q = NULL;
 
if(strpos($nom_saisi, ' ') === FALSE) return FALSE; // pas d'espace, pas de nom d'auteur
 
// si "(", break après "Gp)" si présent, sinon, avant "("
if( ($p = strpos($nom_saisi, ' Gp)')) ) {
$after = $p + 4;
goto sendAuthor;
}
 
 
// si ".":
if( ($p = strpos($nom_saisi, '.')) ) {
// " f. "
 
/* SELECT nom_sci, LOCATE(' ', SUBSTRING_INDEX(nom_sci, ' f. ', -1)) AS space_pos
FROM tb_eflore.bdtfx_v1_02 WHERE nom_sci LIKE '% f. %' HAVING space_pos > 0; */
// f. suivi de 1 mot sauf, "Rosa pomifera f. x longicruris" (2)
/*if( ($q = strpos($nom_saisi, ' f. ', $p - 2)) ) {
$after = max($after, strpos($nom_saisi, ' ', $q + 4)); // premier espace après ' f. '
}*/
$after = max($after, self::getSpaceNoAfter($nom_saisi, ' f. ', $p - 2));
 
// " var. "
// var. n'est pas un repère vraiment adéquat, on sait juste qu'il fait partie du nom sci
// $after = min($strip_pos, strpos($nom_saisi, ' var. '));
$after = max($after, self::getSpaceNoAfter($nom_saisi, ' var. ', $p - 4));
 
// " subsp. "
// après subsp.: le plus souvent un ' x ', donc pas vraiment de règle (1 ou 2 mots)
$after = max($after, self::getSpaceNoAfter($nom_saisi, ' subsp. ', $p - 6));
 
// AUTEUR "."
// autrement, avant un "." dans la partie auteur, il peut y avoir entre 1 et 7 mots à gauche
// grep -o '^[^.]*\.' liste-auteur.txt|while read f; do grep -o ' '<<<"$f"|wc -l; done|sort -n|tail -1
if(!$after) { // si le "." rencontré n'est pas l'un du "nom_sci", c'est de "auteur"
$before = min($before, $p);
}
 
}
 
 
if( ($p = strpos($nom_saisi, ' x ')) ) {
$after = max($after, strpos($nom_saisi, ' x ', $p + 3));
}
 
// " (L.)" et " L."
if( ($p = strpos($nom_saisi, ' (L.)')) ) {
$before = min($before, $p);
}
 
// note: on supprime le " L." en amont
// if( ($p = strpos($nom_saisi, ' L.')) ) $before = min($before, $p);
 
 
 
// "(" et ")", uniquement dans nom_sci dans le cadre de " Gp)", autrement: auteur
// XXX: ce cas englobe " (L.)"
if( ($p = strpos($nom_saisi, '(')) ) {
$before = min($before, $p);
}
 
 
// TODO: gérer le " sp." [taxon supérieur], pour l'instant return FALSE
if( ($p = strpos($nom_saisi, ' sp.')) ) {
return FALSE;
}
// TODO: idem
if( ($p = strpos($nom_saisi, ' sp ')) ) {
return FALSE;
}
 
// si "&": auteur, et entre 1 et 10 mots à gauche
// grep -o '^[^&]*&' liste-auteur.txt|while read f; do grep -o ' '<<<"$f"|wc -l; done|sort -n|tail -1
 
// si ",": auteur, et entre 1 et 5 mots à gauche
// grep -o '^[^,]*,' liste-auteur.txt|while read f; do grep -o ' '<<<"$f"|wc -l; done|sort -n|tail -1
 
// TRIM auteurs:
// sed -e 's/[()]//g' liste-auteur.txt|awk '{print $1}'|sed -e 's/[ .,]*$//g'|awk '{print $1}'|sed -r '/^.{0,3}$/d'|sort -u|wc -l
 
sendAuthor:
$x = self::contientAuteur($nom_saisi, $after, $auteur);
if($x) {
$n = substr($nom_saisi, 0, min($before, strpos($nom_saisi, $auteur[1])));
$auteur = trim(substr($nom_saisi, strlen($n)));
return trim($n, " \t\n\r\0\x0B(),.&");
}
return FALSE;
}
 
static function contientAuteur($nom_saisi, $start, &$auteur = NULL) {
static $auteurs;
// XXX: PHP-5.3
// $auteurs = file_get_contents(dirname(__FILE__) . "/../static/auteurs-bdtfx.min.txt");
$auteurs = file_get_contents(__DIR__ . "/auteurs-bdtfx.min.txt") or die('no file: auteurs-bdtfx.min.txt');
return preg_match('^\s(' . $auteurs . ')^S', $nom_saisi, $auteur, 0, $start);
}
 
 
static function supprimerAuteur($nom_saisi, &$auteur = null) {
// TODO: gérer les hybrides
if(self::estUnHybride($nom_saisi) || self::estUneFormuleHybridite($nom_saisi)) {
 
$nom_decoupe = explode(' ', $nom_saisi);
$derniere_position_hybride = end(array_keys($nom_decoupe, 'x'));
$nom_saisi_sans_auteur = implode(' ',array_slice($nom_decoupe, 0, $derniere_position_hybride + 2));
 
/*
var_dump($nom_saisi, $nom_decoupe, $derniere_position_hybride, $nom_saisi_sans_auteur);
if($auteur != NULL) {
$c = strpos($nom_saisi, ' x ');
$auteur = substr($nom_saisi, $c + 3);
return substr($nom_saisi, 0, $c);
}
var_dump(substr($nom_saisi, 0, strpos($nom_saisi, ' x ')));
echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n";*/
} else {
/* Attention le parseur de nom n'est pas fiable à 100%
mais ça marche dans la plupart des cas
à part les formules d'hybridité saisies avec un auteur */
$nameparser = new NameParser();
$auteur = $nameparser->parse_auth($nom_saisi);
$nom_saisi_sans_auteur = str_replace($auteur, '', $nom_saisi);
}
 
return trim($nom_saisi_sans_auteur);
}
static function estUneFormuleHybridite($nom_saisi) {
return strpos($nom_saisi,' x ') !== false;
}
static function estUnHybride($nom_saisi) {
return strpos($nom_saisi,'x ') === 0;
}
}
/tags/v5.7-arrayanal/scripts/modules/cel/Cel.php
New file
0,0 → 1,94
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php cel -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Cel extends EfloreScript {
 
public function executer() {
try {
$this->initialiserProjet('cel');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerCel();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
protected function initialiserProjet($projet) {
$bases = $this->getListeBases();
parent::initialiserProjet($projet);
$this->verifierPresenceBdd($bases);
}
 
private function getListeBases() {
$requete = "SHOW DATABASES";
$bases = $this->getBdd()->recupererTous($requete);
return $bases;
}
 
private function verifierPresenceBdd($bases) {
$bddNom = Config::get('bdd_nom');
$existe = false;
foreach ($bases as $base) {
if ($base['Database'] == $bddNom) {
$existe = true;
break;
}
}
if ($existe === false) {
$message = "Veuillez créer la base de données '$bddNom'.";
throw new Exception($message);
}
}
 
public function chargerCel() {
$tablesCodes = array_keys(Config::get('tables'));
foreach ($tablesCodes as $code) {
echo "Chargement de la table : $code\n";
$this->chargerFichierTsvDansTable($code);
}
}
 
private function chargerFichierTsvDansTable($code) {
$chemin = Config::get('chemins.'.$code);
$table = Config::get('tables.'.$code);
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS cel_meta, cel_images, cel_inventory, cel_mots_cles_images, cel_mots_cles_obs, ".
"cel_obs_images, locations ";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/cel
New file
Property changes:
Added: svn:ignore
+o_*.comp.sql
/tags/v5.7-arrayanal/scripts/modules/chorodep/chorodep.ini
New file
0,0 → 1,40
; Ajouter les nouvelles version à la suite dans versions et versionsDonnees.
versions = "2011_04,2012_01,2013_07,2013_08,2013_11"
versionsDonnees="2011-04-05,2012-01-01,2013-07-22,2013-08-05,2013-11-13"
dossierTsv = "{ref:dossierDonneesEflore}chorodep/{ref:versionDonnees}/"
dossierTsvTpl = "{ref:dossierDonneesEflore}chorodep/%s/"
dossierSql = "{ref:dossierDonneesEflore}chorodep/"
chorodepChamps2011_04 = "rang, catminat, num_tax, num_nom, nom_sci, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat";
chorodepChamps2012_01 = "rang, catminat, num_tax, num_nom, nom_sci, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat";
chorodepChamps2013_07 = "rang, catminat,syntaxons, num_tax, num_nom, nom_sci, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat";
chorodepChamps2013_08 = "rang, catminat,indication_phytosocio_caracteristique, num_tax, num_nom, nom_sci, chorologie, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat";
chorodepChamps2013_11 = "rang, catminat,indication_phytosocio_caracteristique, num_tax, num_nom, nom_sci, chorologie, `01`, `02`, `03`, `04`, `06`, `07`, `08`, `09`, `10`, `11`, `12`, `67`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `20`, `21`, `22`, `23`, `79`, `24`, `25`, `26`, `91`, `27`, `28`, `29`, `30`, `32`, `33`, `31`, `43`, `52`, `05`, `70`, `74`, `65`, `87`, `68`, `92`, `34`, `35`, `36`, `37`, `38`, `39`, `40`, `42`, `44`, `45`, `41`, `46`, `47`, `48`, `49`, `50`, `51`, `53`, `54`, `55`, `56`, `57`, `58`, `59`, `60`, `61`, `75`, `62`, `63`, `66`, `64`, `69`, `71`, `72`, `73`, `77`, `76`, `93`, `80`, `81`, `82`, `90`, `94`, `95`, `83`, `84`, `85`, `86`, `88`, `89`, `78`, freq_abs, freq_rel, rare_nat";
 
 
[tables]
chorodepMeta = "chorodep_meta"
chorodepContributeurs = "chorodep_contributeurs"
chorodepSources = "chorodep_sources"
chorodepOntologies = "chorodep_ontologies"
chorodep = "chorodep_v{ref:version}"
chorodepTpl = "chorodep_v%s"
 
[fichiers]
structureSql = "chorodep.sql"
structureSqlVersion = "chorodep_v{ref:versionDonnees}.sql"
structureSqlVersionTpl = "chorodep_v%s.sql"
chorodepContributeurs = "chorodep_contributeurs.tsv"
chorodepSources = "chorodep_sources.tsv"
chorodepOntologies = "chorodep_ontologies.tsv"
chorodep = "chorodep_v{ref:versionDonnees}.tsv"
chorodepTpl = "chorodep_v%s.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
structureSqlVersion = "{ref:dossierTsv}{ref:fichiers.structureSqlVersion}"
structureSqlVersionTpl = "{ref:dossierTsvTpl}{ref:fichiers.structureSqlVersionTpl}"
chorodepContributeurs = "{ref:dossierSql}{ref:fichiers.chorodepContributeurs}"
chorodepSources = "{ref:dossierSql}{ref:fichiers.chorodepSources}"
chorodepOntologies = "{ref:dossierSql}{ref:fichiers.chorodepOntologies}"
chorodep = "{ref:dossierTsv}{ref:fichiers.chorodep}"
chorodepTpl = "{ref:dossierTsvTpl}{ref:fichiers.chorodepTpl}"
/tags/v5.7-arrayanal/scripts/modules/chorodep/Chorodep.php
New file
0,0 → 1,629
<?php
// /opt/lampp/bin/php cli.php chorodep -a chargerVersions
class Chorodep extends EfloreScript {
protected $nbre_dep = 0;
private $type_donnee = '';
protected $aso_num_nomenc = array();
protected $nbre_ligne = 0;
protected $nbre_plte_presente = 0;
protected $nbre_plte_a_confirmer = 0;
protected $nbre_plte_douteux = 0;
protected $nbre_plte_erreur = 0;
protected $nbre_plte_disparue = 0;
protected $nbre_plte_erreur_a_confirmer = 0;
protected $nc_autres_valeur_champ = 0;
protected $nc_nbre_plte_presente = 0;
protected $nc_nbre_plte_a_confirmer = 0;
protected $nc_nbre_plte_douteux = 0;
protected $nc_nbre_plte_disparue = 0;
protected $nc_nbre_plte_erreur = 0;
protected $nc_nbre_plte_erreur_a_confirmer = 0;
 
protected $aso_totaux_dep = array();
private $fichier_verif = './chorodep_verif.html';
 
public function executer() {
try {
$this->initialiserProjet('chorodep');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
 
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerVersions();
$this->chargerChorodepContributeurs();
$this->chargerChorodepSources();
$this->chargerChorodepOntologies();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerVersions' :
$this->chargerVersions();
break;
case 'chargerChorodep' :
$this->chargerChorodepContributeurs();
$this->chargerChorodepSources();
$this->chargerChorodepOntologies();
break;
case 'verifierDonnees' :
$this->initialiserTraitement();
$this->verifierDonnees();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerChorodepContributeurs() {
$chemin = Config::get('chemins.chorodepContributeurs');
$table = Config::get('tables.chorodepContributeurs');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 2 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerChorodepSources() {
$chemin = Config::get('chemins.chorodepSources');
$table = Config::get('tables.chorodepSources');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 2 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerChorodepOntologies() {
$chemin = Config::get('chemins.chorodepOntologies');
$table = Config::get('tables.chorodepOntologies');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerVersions() {
$versions = explode(',', Config::get('versions'));
$versionsDonnees = explode(',', Config::get('versionsDonnees'));
foreach ($versions as $id => $version) {
$versionDonnees = $versionsDonnees[$id];
$this->chargerStructureSqlVersion($versionDonnees);
$this->chargerDonneesVersion($versionDonnees, $version);
}
}
 
private function chargerStructureSqlVersion($versionDonnees) {
$fichierSqlTpl = Config::get('chemins.structureSqlVersionTpl');
$fichierSql = sprintf($fichierSqlTpl, $versionDonnees, $versionDonnees);
$contenuSql = $this->recupererContenu($fichierSql);
$this->executerScripSql($contenuSql);
}
 
private function chargerDonneesVersion($versionDonnees, $version) {
$fichierTsvTpl = Config::get('chemins.chorodepTpl');
$fichierTsv = sprintf($fichierTsvTpl, $versionDonnees, $versionDonnees);
$tableTpl = Config::get('tables.chorodepTpl');
$table = sprintf($tableTpl, $version);
$champs = Config::get('chorodepChamps'.$version);
$requete = "LOAD DATA INFILE '$fichierTsv' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
"($champs) ";
$this->getBdd()->requeter($requete);
}
 
private function initialiserTraitement() {
//------------------------------------------------------------------------------------------------------------//
// Récupération des informations à vérifier
$table = $this->getNomTableDernierVersion();
$requete = 'SELECT * '.
"FROM $table ";
$taxons = $this->getBdd()->recupererTous($requete);
$tax_col = $taxons[1];
$col = array_keys($tax_col);
$this->initialiserTableaux($col);
//------------------------------------------------------------------------------------------------------------//
// Analyse des données
echo 'Traitement de la ligne n° :';
$i = 0;
$j = 0;
$aso_departements_analyses = array();
$this->nbre_ligne_avec_guillemet = 0;
foreach ($taxons as $aso_champs) {
$nom = $aso_champs['nom_sci'];
$num_taxo = $aso_champs['num_tax'];
$num_nomenc = $aso_champs['num_nom'];
if ($num_nomenc == 'nc') {
$this->nc_nbre_nom++;
} else if ($num_nomenc != 'nc') {
$this->nbre_nom++;
// Vérification de la nom duplication des numéros nomenclaturaux
if ( !array_key_exists($num_nomenc, (array) $this->aso_num_nomenc) ) {
$this->aso_num_nomenc[$num_nomenc]['compteur'] = 1;
$this->aso_num_nomenc[$num_nomenc]['ligne'] = ($this->nbre_ligne+1);
} else {
$this->aso_num_nomenc[$num_nomenc]['compteur']++;
$this->aso_num_nomenc[$num_nomenc]['ligne'] .= ' - '.($this->nbre_ligne+1);
}
}
foreach ($aso_champs as $cle => $val ) {# Pour chaque département du taxon, on regarde la valeur
$this->nbre_ligne_avec_guillemet += preg_match('/"/', $val);
if ( preg_match('/^\d{2}$/', $cle) ) {# Nous vérifions que le nom du champs comprend bien le numéro du département entre ()
$nd = $cle;# Numéro du département
// Nous comptons le nombre de département en base de données
if (!isset($aso_departements_analyses[$nd])) {
$this->nbre_dep_analyse++;
$aso_departements_analyses[$nd] = $nd;
}
if ( $num_nomenc != 'nc' && isset($val) && $val != '') {# Si le taxon n'est pas abscent du département
if ($val == '1') {# Présent
// Calcul du nombre de plante ayant un statut "Présent"
$this->nbre_plte_presente++;
// Stockage par département du nombre de plante ayant un statut "Présent"
$this->aso_totaux_dep[$nd]['plte_presente']++;
// Stockage des informations
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 3, $this->id_donnee_choro++);
} else if ($val == '1?') {# Présence à confirmer
// Calcul du nombre de plante ayant un statut "Présence à confirmer"
$this->nbre_plte_a_confirmer++;
// Stockage par département du nombre de plante ayant un statut "Présence à confirmer"
$this->aso_totaux_dep[$nd]['plte_a_confirmer']++;
// Stockage des informations
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 4, $this->id_donnee_choro++);
} else if (preg_match('/^\s*(?:\?)\s*$/', $val)) {# Douteux
// Calcul du nombre de plante ayant un statut "Disparu ou douteux"
$this->nbre_plte_douteux++;
// Stockage par département du nombre de plante ayant un statut "Douteux"
$this->aso_totaux_dep[$nd]['plte_douteux']++;
// Stockage des informations
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 5, $this->id_donnee_choro++);
if (preg_match('/(?: \?|\? | \? )/', $val)) {# Douteux
// Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "?".
$this->autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
} elseif (preg_match('/^\s*(?:#)\s*$/', $val)) {# Erreur
# Calcul du nombre de plante ayant un statut "Erreur"
$this->nbre_plte_erreur++;
# Stockage par département du nombre de plante ayant un statut "Erreur"
$this->aso_totaux_dep[$nd]['plte_erreur']++;
# Stockage des informations
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 6, $this->id_donnee_choro++);
if (preg_match('/(?: #|# | # )/', $val)) {# Erreur avec espace
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "#".
$autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
} elseif (preg_match('/^\s*(?:-\|-)\s*$/', $val)) {# Disparu
# Calcul du nombre de plante ayant un statut "Disparu"
$this->nbre_plte_disparue++;
# Stockage par département du nombre de plante ayant un statut "Disparu"
$this->aso_totaux_dep[$nd]['plte_disparue']++;
# Stockage des informations
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 6, $this->id_donnee_choro++);
if (preg_match('/(?: -\|-|-\|- | -\|- )/', $val)) {# Disparu avec espace
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "-|-".
$autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
} elseif (preg_match('/^\s*(?:#\?)\s*$/', $val)) {# Erreur à confirmer
# Calcul du nombre de plante ayant un statut "Erreur à confirmer"
$this->nbre_plte_erreur_a_confirmer++;
# Stockage par département du nombre de plante ayant un statut "Erreur à confirmer"
$this->aso_totaux_dep[$nd]['plte_erreur_a_confirmer']++;
# Stockage des informations
$this->tab_choro_dep[$j] = array(ZgFrDepartements::getIdChaine($nd), $num_taxo, $num_nomenc, 6, $this->id_donnee_choro++);
if (preg_match('/^(?:\s+#\?|#\?\s+|\s+#\?\s+)$/', $val)) {# Erreur à confirmer avec espace
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "#?".
$autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
} else {
// Ajout de la valeur dans une variable car elle n'est pas conforme.
$this->autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
$j++;
} else if (isset($val) && $val != '') {
if ($val == '1') {# Présent
// Calcul du nombre de plante 'nc' ayant un statut "Présent"
$this->nc_nbre_plte_presente++;
// Stockage par département du nombre de plante 'nc' ayant un statut "Présent"
$this->aso_totaux_dep[$nd]['nc_plte_presente']++;
} elseif ($val == '1?') {# Présence à confirmer
// Calcul du nombre de plante 'nc' ayant un statut "Présence à confirmer"
$this->nc_nbre_plte_a_confirmer++;
// Stockage par département du nombre de plante 'nc' ayant un statut "Présence à confirmer"
$this->aso_totaux_dep[$nd]['nc_plte_a_confirmer']++;
} elseif (preg_match('/^(?:\?| \?|\? | \?)$/', $val)) {# Douteux
// Calcul du nombre de plante 'nc' ayant un statut "Douteux"
$this->nc_nbre_plte_douteux++;
// Stockage par département du nombre de plante 'nc' ayant un statut "Douteux"
$this->aso_totaux_dep[$nd]['nc_plte_douteux']++;
if (preg_match('/(?: \?|\? | \? )/', $val)) {# Douteux
// Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "?".
$this->nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
} elseif (preg_match('/^(?:#| #|# | # )$/', $val)) {# Erreur
# Calcul du nombre de plante 'nc' ayant un statut "Erreur"
$this->nc_nbre_plte_erreur++;
# Stockage par département du nombre de plante 'nc' ayant un statut "Erreur"
$this->aso_totaux_dep[$nd]['nc_plte_erreur']++;
if (preg_match('/(?: #|# | # )/', $val)) {# Erreur avec espace
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "#".
$nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
} elseif (preg_match('/^\s*(?:-\|-)\s*$/', $val)) {# Disparu
# Calcul du nombre de plante 'nc' ayant un statut "Disparu"
$this->nc_nbre_plte_disparue++;
# Stockage par département du nombre de plante 'nc' ayant un statut "Disparu"
$this->aso_totaux_dep[$nd]['nc_plte_disparue']++;
if (preg_match('/(?: -\|-|-\|- | -\|- )/', $val)) {# Disparu avec espace
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "-|-".
$nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
} elseif (preg_match('/^\s*(?:#\?)\s*$/', $val)) {# Erreur à confirmer
# Calcul du nombre de plante 'nc' ayant un statut "Erreur à confirmer"
$this->nc_nbre_plte_erreur_a_confirmer++;
# Stockage par département du nombre de plante 'nc' ayant un statut "Erreur à confirmer"
$this->aso_totaux_dep[$nd]['nc_plte_erreur_a_confirmer']++;
if (preg_match('/^(?:\s+#\?|#\?\s+|\s+#\?\s+)$/', $val)) {# Erreur à confirmer avec espace
# Ajout de la valeur dans une variable car elle n'est pas tout à fait conforme à "#?".
$nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
} else {
// Ajout de la valeur dans une variable car elle n'est pas conforme.
$this->nc_autres_valeur_champ .= '<'.$val.'> '.'(Ligne n°: '.($this->nbre_ligne+2).
' - N° nomenclatural: '.$num_nomenc.' - N° département: '.$nd.')<br />';
}
}
// Affichage dans la console du numéro de l'enregistrement analysé.
//echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++;
}
}// fin du foreach
// Affichage dans la console du numéro de l'enregistrement analysé.
echo str_repeat(chr(8), ( strlen( $this->nbre_ligne ) + 1 ))."\t".$this->nbre_ligne++;
}
echo "\n";
}
 
private function initialiserTableaux($dep) {
foreach ($dep as $code_dep) {
if ( preg_match('/^\d{2}$/', $code_dep) ) {
$this->aso_totaux_dep[$code_dep]['plte_presente'] = 0;
$this->aso_totaux_dep[$code_dep]['plte_a_confirmer'] = 0;
$this->aso_totaux_dep[$code_dep]['plte_douteux'] = 0;
$this->aso_totaux_dep[$code_dep]['plte_erreur'] = 0;
$this->aso_totaux_dep[$code_dep]['plte_disparue'] = 0;
$this->aso_totaux_dep[$code_dep]['plte_erreur_a_confirmer'] = 0;
$this->aso_totaux_dep[$code_dep]['autres_valeur_champ'] = 0;
$this->aso_totaux_dep[$code_dep]['nc_plte_presente'] = 0;
$this->aso_totaux_dep[$code_dep]['nc_plte_a_confirmer'] = 0;
$this->aso_totaux_dep[$code_dep]['nc_plte_douteux'] = 0;
$this->aso_totaux_dep[$code_dep]['nc_plte_erreur'] = 0;
$this->aso_totaux_dep[$code_dep]['nc_plte_disparue'] = 0;
$this->aso_totaux_dep[$code_dep]['nc_plte_erreur_a_confirmer'] = 0;
$this->aso_totaux_dep[$code_dep]['nc_autres_valeur_champ'] = 0;
}
}
}
 
private function verifierDonnees() {
// Ouverture du fichier contenant les résultats (sortie)
if (!$handle = fopen($this->fichier_verif, 'w')) {
echo "Impossible d'ouvrir le fichier ($this->fichier_verif)";
exit;
}
 
// Création de la page
$page = '<html>'."\n";
$page .= '<head>'."\n";
$page .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'."\n";
$page .= '<title>RESULTAT DE LA VERIFICATION DU FICHIER TABULE DE LA CHOROLOGIE</title>'."\n";
$page .= '</head>'."\n";
$page .= '<body>'."\n";
$page .= '<h1>RESULTAT DE LA VERIFICATION DU FICHIER TABULE DE LA CHOROLOGIE</h1>'."\n";
$page .= '<hr/>'."\n";
$page .= '<p>'.
'Adresse fichier analysé : '.'<br />'."\n".
'</p>'."\n";
$page .= '<hr/>'."\n";
$page .= '<h2>RESULTATS PROGRAMME DE VERIFICATION</h2>'."\n";
$page .= '<p>'.
'Nom du programme générant ce fichier : '.__FILE__.'<br />'."\n".
'Nombre de lignes analysées : '.$this->nbre_ligne.'<br />'."\n".
'Nbre de départements analysés : '.$this->nbre_dep_analyse.'<br />'."\n".
'Date d\'exécution du programme : '.date('d.m.Y').'<br />'."\n".
'</p>'."\n";
$page .= '<hr/>'."\n";
$page .= '<h2>RESULTATS ANALYSE CHOROLOGIE</h2>'."\n";
$page .= '<p>'.
'Nombre de nom "nc" : '.$this->nc_nbre_nom.'<br />'."\n".
'Nombre de nom : '.$this->nbre_nom.'<br />'."\n".
'Valeurs autres que 1, 1?, ?, #, #? et -|- : '.$this->autres_valeur_champ.'<br />'."\n".
'Valeurs autres que 1, 1?, ?, #, #? et -|- pour les plantes nc : <br />'."\n".$this->nc_autres_valeur_champ.'</br>'."\n".
'</p>'."\n";
$page .= '<hr/>'."\n";
$page .= '<h2>RESULTATS ANALYSE des CHAMPS</h2>'."\n";
$page .= '<p>'.
'Nombre de guillemets antislashés: '.$this->nbre_ligne_avec_guillemet.'<br />'."\n".
'</p>'."\n";
$page .= '<hr/>'."\n";
$page .= '<h2>TABLEAUX</h2>'."\n";
 
// Tableau des numéros nomenclaturaux dupliqués
$table = '<table><thead><tr><th colspan="3">Tableau des numéros nomenclaturaux dupliqués </th></tr>';
$table .= '<tr><th>Numéro nomenclatural</th><th>Nbre d\'itération</th><th>Lignes</th></tr></thead>';
$afficher_tab_num_duplique = 0;
ksort($this->aso_num_nomenc);
$table .= '<tbody style="text-align: center;">';
foreach ($this->aso_num_nomenc as $cle_nomenc => $val ) {
$ligne = '<tr><td>'.$cle_nomenc.'</td><td>'.$val['compteur'].'</td><td>'.$val['ligne'].'</td></tr>';
if ($val['compteur'] > 1) {
$table .= $ligne;
$afficher_tab_num_duplique = 1;
}
}
if ( $afficher_tab_num_duplique == 1 ) {
$page .= $table.'</tbody></table>';
}
 
// Tableau des résultats par départements
$table = '<table><thead><tr><th colspan="14">Tableau des résulats par départements</th></tr>';
$table .= '<tr><th>Département</th><th>Nbre pltes présentes</th><th>Nbre pltes à confirmer</th>'.
'<th>Nbre pltes douteuses</th><th>Nbre pltes disparues</th><th>Nbre pltes erreur</th><th>Nbre pltes erreur à confirmer</th>'.
'<th>Total</th><th>Nbre pltes nc présentes</th><th>Nbre pltes nc à confirmer</th>'.
'<th>Nbre nc pltes douteuses</th><th>Nbre nc pltes disparues</th><th>Nbre nc pltes erreur</th><th>Nbre nc pltes erreur à confirmer</th></tr></thead>';
$table .= '<tbody style="text-align: center;">';
ksort($this->aso_totaux_dep);
foreach ($this->aso_totaux_dep as $cle_dep => $val ) {
$plt_total = $val{'plte_presente'} + $val{'plte_a_confirmer'} + $val{'plte_douteux'} + $val{'plte_disparue'} + $val{'plte_erreur'} + $val{'plte_erreur_a_confirmer'};
$table .= '<tr><td>'.ZgFrDepartements::getNom($cle_dep).' ('.ZgFrDepartements::getIdChaine($cle_dep).') </td>'.
'<td>'.$val{'plte_presente'}.'</td><td>'.$val{'plte_a_confirmer'}.'</td><td>'.$val{'plte_douteux'}.'</td>'.
'<td>'.$val{'plte_disparue'}.'</td><td>'.$val{'plte_erreur'}.'</td><td>'.$val{'plte_erreur_a_confirmer'}.'</td><td>'.$plt_total.'</td>'.
'<td>'.$val{'nc_plte_presente'}.'</td><td>'.$val{'nc_plte_a_confirmer'}.'</td><td>'.$val{'nc_plte_douteux'}.'</td>'.
'<td>'.$val{'nc_plte_disparue'}.'</td><td>'.$val{'nc_plte_erreur'}.'</td><td>'.$val{'nc_plte_erreur_a_confirmer'}.'</td></tr>';
}
 
$table .= '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
$plt_total = $this->nbre_plte_presente + $this->nbre_plte_a_confirmer + $this->nbre_plte_douteux + $this->nbre_plte_disparue + $this->nbre_plte_erreur + $this->nbre_plte_erreur_a_confirmer;
$table .= '<tr><td>Totaux : '.$this->nbre_dep_analyse.' départements</td><td>'.$this->nbre_plte_presente.'</td>'.
'<td>'.$this->nbre_plte_a_confirmer.'</td><td>'.$this->nbre_plte_douteux.'</td><td>'.$this->nbre_plte_disparue.'</td>'.
'<td>'.$this->nbre_plte_erreur.'</td><td>'.$this->nbre_plte_erreur_a_confirmer.'</td><td>'.$plt_total.'</td>'.
'<td>'.$this->nc_nbre_plte_presente.'</td>'.'<td>'.$this->nc_nbre_plte_a_confirmer.'</td>'.
'<td>'.$this->nc_nbre_plte_douteux.'</td><td>'.$this->nc_nbre_plte_disparue.'</td><td>'.$this->nc_nbre_plte_erreur.'</td><td>'.$this->nc_nbre_plte_erreur_a_confirmer.'</td></tr>';
 
$table .= '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
$total_nbre_plte = ($this->nbre_plte_presente + $this->nbre_plte_a_confirmer + $this->nbre_plte_douteux + $this->nbre_plte_disparue + $this->nbre_plte_erreur + $this->nbre_plte_erreur_a_confirmer);
$total_nbre_plte_nc = ($this->nc_nbre_plte_presente + $this->nc_nbre_plte_a_confirmer + $this->nc_nbre_plte_douteux + $this->nc_nbre_plte_disparue + $this->nc_nbre_plte_erreur + $this->nc_nbre_plte_erreur_a_confirmer);
$table .= '<tr><td>Totaux plante / plante nc</td><td colspan="7">'.$total_nbre_plte.'</td>'.
'<td colspan="6">'.$total_nbre_plte_nc.'</td></tr>';
 
$table .= '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
$plt_total = $this->nbre_plte_presente + $this->nc_nbre_plte_presente + $this->nc_nbre_plte_a_confirmer + $this->nbre_plte_a_confirmer;
$table .= '<tr><td>Total plantes présentes et à confirmer</td><td colspan="13">'.$plt_total.'</td></tr>';
 
$table .= '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
$plt_total = $this->nbre_plte_presente + $this->nc_nbre_plte_presente;
$table .= '<tr><td>Total plantes présentes</td><td colspan="13">'.$plt_total.'</td></tr>';
 
$table .= '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'.
'<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
$plt_total = $total_nbre_plte + $total_nbre_plte_nc;
$table .= '<tr><td>Total données chorologiques</td><td colspan="13">'.$plt_total.'</td></tr>';
 
$table .= '</tbody></table>';
$page .= $table;
 
$page .= '<hr/>'."\n";
$page .= '<h2>NOTES</h2>'."\n";
$page .= '<p>'.
'1.- Chaque champ précédé par "ATTENTION" doit être vide.'."\n".
'S\'il ne l\'est pas, il y a une erreur'."\n".
'</p>'."\n";
$page .= '</body>'."\n";
$page .= '</html>'."\n";
// Fermeture de la poignée sur le fichier de sortie
if (fwrite($handle, $page) === FALSE) {
echo "Impossible d'écrire dans le fichier ($this->fichier_verif)";
exit;
}
echo 'Ecriture du fichier de vérification de la chorologie réalisée!'."\n";
fclose($handle);
}
 
private function supprimerTous() {
$tablesChorodep = implode(',', $this->getNomsTablesChorodep());
$tableContributeurs = Config::get('tables.chorodepContributeurs');
$tableSources = Config::get('tables.chorodepSources');
$tableOntologies = Config::get('tables.chorodepOntologies');
$requete = "DROP TABLE IF EXISTS chorodep_meta, $tablesChorodep, $tableContributeurs, $tableSources, $tableOntologies ";
$this->getBdd()->requeter($requete);
}
 
private function getNomsTablesChorodep() {
$versions = explode(',', Config::get('versions'));
$tableTpl = Config::get('tables.chorodepTpl');
$tablesChorodep = array();
foreach ($versions as $version) {
$tablesChorodep[] = sprintf($tableTpl, $version);
}
return $tablesChorodep;
}
 
private function getNomTableDernierVersion() {
$version = $this->getDerniereVersion();
$table = sprintf(Config::get('tables.chorodepTpl'), $version);
return $table;
}
 
private function getDerniereVersion() {
$version = array_pop(explode(',', Config::get('versions')));
return $version;
}
}
 
class ZgFrDepartements {
static private $departements =
array(
"01" => array("Ain", "01", 1),
"02" => array("Aisne", "02", 2),
"03" => array("Allier", "03", 3),
"04" => array("Alpes-de-Haute-Provence", "04", 4),
"05" => array("Hautes-Alpes", "05", 5),
"06" => array("Alpes-Maritimes", "06", 6),
"07" => array("Ardèche", "07", 7),
"08" => array("Ardennes", "08", 8),
"09" => array("Ariège", "09", 9),
"10" => array("Aube", "10", 10),
"11" => array("Aude", "11", 11),
"12" => array("Aveyron", "12", 12),
"13" => array("Bouches-du-Rhône", "13", 13),
"14" => array("Calvados", "14", 14),
"15" => array("Cantal", "15", 15),
"16" => array("Charente", "16", 16),
"17" => array("Charente-Maritime", "17", 17),
"18" => array("Cher", "18", 18),
"19" => array("Corrèze", "19", 19),
"20" => array("Corse", "20", 20),
"2A" => array("Haute-Corse", "2A", 20),
"2B" => array("Corse-du-Sud", "2B", 20),
"21" => array("Côte-d'Or", "21", 21),
"22" => array("Côtes-d'Armor", "22", 22),
"23" => array("Creuse", "23", 23),
"24" => array("Dordogne", "24", 24),
"25" => array("Doubs","25", 25),
"26" => array("Drôme", "26", 26),
"27" => array("Eure", "27", 27),
"28" => array("Eure-et-Loir", "28", 28),
"29" => array("Finistère", "29", 29),
"30" => array("Gard", "30", 30),
"31" => array("Haute-Garonne", "31", 31),
"32" => array("Gers", "32", 32),
"33" => array("Gironde", "33", 33),
"34" => array("Hérault", "34", 34),
"35" => array("Ille-et-Vilaine", "35", 35),
"36" => array("Indre", "36", 36),
"37" => array("Indre-et-Loire", "37", 37),
"38" => array("Isère", "38", 38),
"39" => array("Jura", "39", 39),
"40" => array("Landes", "40", 40),
"41" => array("Loir-et-Cher", "41", 41),
"42" => array("Loire", "42", 42),
"43" => array("Haute-Loire", "43", 43),
"44" => array("Loire-Atlantique", "44", 44),
"45" => array("Loiret", "45", 45),
"46" => array("Lot", "46", 46),
"47" => array("Lot-et-Garonne", "47", 47),
"48" => array("Lozére ", "48", 48),
"49" => array("Maine-et-Loire", "49", 49),
"50" => array("Manche", "50", 50),
"51" => array("Marne", "51", 51),
"52" => array("Haute-Marne", "52", 52),
"53" => array("Mayenne", "53", 53),
"54" => array("Meurthe-et-Moselle", "54", 54),
"55" => array("Meuse", "55", 55),
"56" => array("Morbihan", "56", 56),
"57" => array("Moselle", "57", 57),
"58" => array("Nièvre", "58", 58),
"59" => array("Nord", "59", 59),
"60" => array("Oise", "60", 60),
"61" => array("Orne", "61", 61),
"62" => array("Pas-de-Calais", "62", 62),
"63" => array("Puy-de-Dôme", "63", 63),
"64" => array("Pyrénées-Atlantiques", "64", 64),
"65" => array("Hautes-Pyrénées", "65", 65),
"66" => array("Pyrénées-Orientales", "66", 66),
"67" => array("Bas-Rhin", "67", 67),
"68" => array("Haut-Rhin", "68", 68),
"69" => array("Rhône", "69", 69),
"70" => array("Haute-Saône", "70", 70),
"71" => array("Saône-et-Loire", "71", 71),
"72" => array("Sarthe", "72", 72),
"73" => array("Savoie", "73", 73),
"74" => array("Haute-Savoie", "74", 74),
"75" => array("Paris", "75", 75),
"76" => array("Seine-Maritime", "76", 76),
"77" => array("Seine-et-Marne", "77", 77),
"78" => array("Yvelines", "78", 78),
"79" => array("Deux-Sèvres", "79", 79),
"80" => array("Somme", "80", 80),
"81" => array("Tarn", "81", 81),
"82" => array("Tarn-et-Garonne", "82", 82),
"83" => array("Var", "83", 83),
"84" => array("Vaucluse", "84", 84),
"85" => array("Vendée", "85", 85),
"86" => array("Vienne", "86", 86),
"87" => array("Haute-Vienne", "87", 87),
"88" => array("Vosges", "88", 88),
"89" => array("Yonne", "89", 89),
"90" => array("Territoire-de-Belfort", "90", 90),
"91" => array("Essonne", "91", 91),
"92" => array("Hauts-de-Seine", "92", 92),
"93" => array("Seine-Saint-Denis", "93", 93),
"94" => array("Val-de-Marne", "94", 94),
"95" => array("Val-d'Oise", "95", 95),
"96" => array("aaa", "96", 96),
"971" => array("Guadeloupe", "971", 971),
"972" => array("Martinique", "972", 972),
"973" => array("Guyane", "973", 973),
"974" => array("Réunion", "974", 974),
"99" => array("Etranger", "99", 99),
);
 
static public function get() {
return self::$departements;
}
 
static public function getNom($n) {
return self::$departements[$n][0];
}
 
static public function getIdChaine($n) {
return self::$departements[$n][1];
}
 
static public function getIdNumerique($n) {
return (int)self::$departements[$n][2];
}
 
static public function getIdEflore($n) {
return (int)self::$departements[$n][3];
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/insee_d/InseeD.php
New file
0,0 → 1,75
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php insee_d
* -a chargerTous
* Options :
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).
*/
class InseeD extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('insee-d');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerInseeD();
$this->chargerOntologies();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerInseeD' :
$this->chargerInseeD();
break;
case 'chargerOntologies' :
$this->chargerOntologies();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerInseeD() {
$chemin = Config::get('chemins.inseeD');
$table = Config::get('tables.inseeD');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY ';' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 0 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerOntologies() {
$chemin = Config::get('chemins.ontologies');
$table = Config::get('tables.ontologies');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS insee_d_meta, insee_d_ontologies_v2011, insee_d_v2011";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/insee_d/insee-d.ini
New file
0,0 → 1,17
version="2011"
dossierTsv = "{ref:dossierDonneesEflore}insee-d/2011/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
inseeD = "insee_d_v{ref:version}"
ontologies = "insee_d_ontologies_v{ref:version}"
 
[fichiers]
structureSql = "insee-d_v{ref:version}.sql"
inseeD = "insee-d_v{ref:version}.csv"
ontologies = "insee-d_ontologies_v{ref:version}.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
inseeD = "{ref:dossierTsv}{ref:fichiers.inseeD}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.7-arrayanal/scripts/modules/insee_d
New file
Property changes:
Added: svn:ignore
+insee-d.ini
/tags/v5.7-arrayanal/scripts/modules/bdtfx/bdtfx.ini
New file
0,0 → 1,19
version="2_01"
dossierTsv = "{ref:dossierDonneesEflore}bdtfx/2.01/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
bdtfxMeta = "bdtfx_meta"
bdtfx = "bdtfx_v{ref:version}"
bdtfxTest = "bdtfx_v2_02"
 
[fichiers]
structureSql = "bdtfx_v{ref:version}.sql"
structureSqlTest = "bdtfx_v2_02_test.sql"
bdtfx = "bdtfx_v{ref:version}_ref.txt"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
structureSqlTest = "{ref:dossierSql}{ref:fichiers.structureSqlTest}"
bdtfx = "{ref:dossierTsv}{ref:fichiers.bdtfx}"
bdtfxTest = "{ref:dossierTsv}{ref:fichiers.bdtfxTest}"
/tags/v5.7-arrayanal/scripts/modules/bdtfx/Bdtfx.php
New file
0,0 → 1,347
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php bdtfx -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Jennifer DHÉ <jennifer@tela-botanica.org>
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Bdtfx extends EfloreScript {
 
private $table = null;
private $pasInsertion = 1000;
private $departInsertion = 0;
 
protected $parametres_autorises = array(
'-t' => array(false, false, 'Permet de tester le script sur un jeu réduit de données (indiquer le nombre de lignes).'));
 
public function executer() {
try {
$this->initialiserProjet('bdtfx');
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerBdtfx();
$this->genererChpNomSciHtml();
$this->genererChpFamille();
$this->genererDonneesTestMultiVersion();
$this->genererChpHierarchie();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerBdtfx' :
$this->chargerBdtfx();
break;
case 'genererNomSciHtml' :
$this->genererChpNomSciHtml();
break;
case 'genererChpFamille' :
$this->genererChpFamille();
break;
case 'genererChpHierarchie' :
$this->genererChpHierarchie();
break;
case 'genererDonneesTestMultiVersion' :
$this->genererDonneesTestMultiVersion();
break;
case 'supprimerDonneesTestMultiVersion' :
$this->supprimerDonneesTestMultiVersion();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerBdtfx() {
$chemin = Config::get('chemins.bdtfx');
$table = Config::get('tables.bdtfx');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function genererChpNomSciHtml() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpNomSciHtml();
$generateur = new GenerateurNomSciHtml();
$nbreTotal = $this->recupererNbTotalTuples();
$erreurs = array();
$this->departInsertion = 0;
while ($this->departInsertion < $nbreTotal) {
$resultat = $this->recupererTuplesPrChpNomSciHtml();
 
try {
$nomsSciEnHtml = $generateur->generer($resultat);
} catch (Exception $e) {
$erreurs[] = $e->getMessage();
}
 
$this->remplirChpNomSciHtm($nomsSciEnHtml);
$this->departInsertion += $this->pasInsertion;
$this->afficherAvancement("Insertion des noms scientifique au format HTML dans la base par paquet de {$this->pasInsertion} en cours");
if ($this->stopperLaBoucle($this->getParametre('t'))) break;
}
echo "\n";
 
$this->creerFichierLog('Erreurs lors de la génération HTML des noms scientifiques', $erreurs, 'erreurs_noms_sci_html');
}
 
private function initialiserGenerationChamps() {
$this->table = Config::get('tables.bdtfx');
}
 
private function preparerTablePrChpNomSciHtml() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD nom_sci_html VARCHAR( 500 ) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function recupererNbTotalTuples(){
$requete = "SELECT count(*) AS nb FROM {$this->table} ";
$resultat = $this->getBdd()->recuperer($requete);
return $resultat['nb'];
}
 
private function recupererTuplesPrChpNomSciHtml() {
$requete = 'SELECT num_nom, rang, nom_sci, nom_supra_generique, genre, epithete_infra_generique, '.
' epithete_sp, type_epithete, epithete_infra_sp,cultivar_groupe, '.
' nom_commercial, cultivar '.
"FROM {$this->table} ".
"LIMIT {$this->departInsertion},{$this->pasInsertion} ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function remplirChpNomSciHtm($nomsSciHtm) {
foreach ($nomsSciHtm as $id => $html) {
$html = $this->getBdd()->proteger($html);
$requete = "UPDATE {$this->table} SET nom_sci_html = $html WHERE num_nom = $id ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $id");
}
}
}
 
private function traiterResultatsFamille(&$resultats, &$noms, &$introuvables, &$introuvablesSyno) {
foreach ($resultats as $id => $nom) {
$nn = $nom['num_nom'];
$nnr = $nom['num_nom_retenu'];
$nts = $nom['num_tax_sup'];
$rg = $nom['rang'];
if ($nnr != '') {
if ($rg == '180') {
$noms[$nn] = $nom['nom_sci'];
} else {
if ($nn == $nnr) {// nom retenu
if (isset($noms[$nts])) {
// signifie que recupererTuplesPrChpFamille() devrait
// récupérer ce record *avant*
$noms[$nn] = $noms[$nts];
} else {
$introuvables[] = $nn;
}
} else {// nom synonyme
if (isset($noms[$nnr])) {
// signifie que recupererTuplesPrChpFamille() devrait
// récupérer ce record *avant*
$noms[$nn] = $noms[$nnr];
} else {
$introuvablesSyno[] = $nom;
}
}
}
}
unset($resultats[$id]);
$this->afficherAvancement("Attribution de leur famille aux noms en cours");
if ($this->stopperLaBoucle($this->getParametre('t'))) break;
}
}
 
private function genererChpFamille() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpFamille();
$resultats = $this->recupererTuplesPrChpFamille();
$noms = array();
$introuvables = array();
$introuvablesSyno = array();
$i = 1;
 
while(true) {
printf("passe n°%d:\n", $i);
$this->traiterResultatsFamille($resultats, $noms, $introuvables, $introuvablesSyno);
echo "\n\n";
// printf("noms: %d, introuvables: %d, introuvablesSyno: %d\n", count($noms), count($introuvables), count($introuvablesSyno));
// XXX, au 22/07/2013, 3 passes sont suffisantes
// TODO: MySQL procédure stockée !
if($i++ == 3) break;
$resultats = array_merge($resultats, $introuvables, $introuvablesSyno);
$introuvables = $introuvablesSyno = array();
}
 
foreach ($introuvablesSyno as $id => $nom) {
$nn = $nom['num_nom'];
$nnr = $nom['num_nom_retenu'];
if (isset($noms[$nnr])) {
$noms[$nn] = $noms[$nnr];
} else {
$introuvables[] = $nn;
}
unset($introuvablesSyno[$id]);
$this->afficherAvancement("Attribution de leur famille aux synonymes en cours");
}
echo "\n";
 
$msg = 'Plusieurs familles sont introuvables';
$this->creerFichierLog($msg, $introuvables, 'famille_introuvable');
 
$this->remplirChpFamille($noms);
}
private function preparerTablePrChpFamille() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'famille' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD famille VARCHAR(255) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function recupererTuplesPrChpFamille() {
$requete = 'SELECT num_nom, num_nom_retenu, num_tax_sup, rang, nom_sci '.
"FROM {$this->table} ".
"WHERE rang >= 180 ".
"ORDER BY rang ASC, num_tax_sup ASC, num_nom_retenu DESC ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function remplirChpFamille($noms) {
foreach ($noms as $id => $famille) {
$famille = $this->getBdd()->proteger($famille);
$requete = "UPDATE {$this->table} SET famille = $famille WHERE num_nom = $id ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $id");
}
$this->afficherAvancement("Insertion des noms de famille dans la base en cours");
}
echo "\n";
}
private function genererChpHierarchie() {
$this->initialiserGenerationChamps();
$this->preparerTablePrChpHierarchie();
$table = Config::get('tables.bdtfx');
$requete = "UPDATE $table SET hierarchie = NULL ";
$mise_a_jour = $this->getBdd()->requeter($requete);
$requete_hierarchie = "SELECT num_nom, num_nom_retenu, num_tax_sup FROM ".$table." ORDER BY rang DESC";
$resultat = $this->getBdd()->recupererTous($requete_hierarchie);
$num_nom_a_num_sup = array();
foreach($resultat as &$taxon) {
$num_nom_a_num_sup[$taxon['num_nom']] = $taxon['num_tax_sup'];
}
$chemin_taxo = "";
foreach($resultat as &$taxon) {
$chemin_taxo = $this->traiterHierarchieNumTaxSup($taxon['num_nom_retenu'], $num_nom_a_num_sup).'-';
$requete = "UPDATE $table SET hierarchie = ".$this->getBdd()->proteger($chemin_taxo)." WHERE num_nom = ".$taxon['num_nom']." ";
$mise_a_jour = $this->getBdd()->requeter($requete);
$this->afficherAvancement("Insertion de la hierarchie taxonomique en cours");
}
echo "\n";
}
private function traiterHierarchieNumTaxSup($num_nom_retenu, &$num_nom_a_num_sup) {
$chaine_hierarchie = "";
if(isset($num_nom_a_num_sup[$num_nom_retenu])) {
$num_tax_sup = $num_nom_a_num_sup[$num_nom_retenu];
$chaine_hierarchie = '-'.$num_tax_sup;
if($num_tax_sup != 0 && $num_tax_sup != '') {
$chaine_hierarchie = $this->traiterHierarchieNumTaxSup($num_tax_sup, $num_nom_a_num_sup).$chaine_hierarchie;
}
}
return $chaine_hierarchie;
}
private function preparerTablePrChpHierarchie() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'hierarchie' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD hierarchie VARCHAR(1000) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function genererDonneesTestMultiVersion() {
$contenuSql = $this->recupererContenu(Config::get('chemins.structureSqlTest'));
$this->executerScripSql($contenuSql);
 
$table = Config::get('tables.bdtfx');
$tableTest = Config::get('tables.bdtfxTest');
$requete = "INSERT INTO $tableTest SELECT * FROM $table";
$this->getBdd()->requeter($requete);
}
 
private function supprimerDonneesTestMultiVersion() {
$tableMeta = Config::get('tables.bdtfxMeta');
$requete = "DELETE FROM $tableMeta WHERE guid = 'urn:lsid:tela-botanica.org:bdtfx:1.02'";
$this->getBdd()->requeter($requete);
 
$tableTest = Config::get('tables.bdtfxTest');
$requete = "DROP TABLE IF EXISTS $tableTest";
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS bdtfx_meta, bdtfx_v1_01, bdtfx_v1_02";
$this->getBdd()->requeter($requete);
}
 
private function creerFichierLog($message, $lignes, $nomFichier) {
$lignesNbre = count($lignes);
if ($lignesNbre != 0) {
echo "$message. Voir le log de $lignesNbre lignes :\n";
 
$logContenu = implode(", \n", $lignes);
$logFichier = realpath(dirname(__FILE__))."/log/$nomFichier.log";
echo $logFichier."\n";
file_put_contents($logFichier, $logContenu);
}
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/bdtfx
New file
Property changes:
Added: svn:ignore
+bdtfx.ini
/tags/v5.7-arrayanal/scripts/modules/sptb/sptb.ini
New file
0,0 → 1,19
version="2012"
dossierTsv = "{ref:dossierDonneesEflore}sptb/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
especes = "sptb_especes_v2012"
lois = "sptb_lois_v2012"
referentielTaxo = "bdtfx_v1_02"
 
[fichiers]
structureSql = "sptb_v2012.sql"
especes = "sptb_especes_v2012.tsv"
lois = "sptb_lois_v2012.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
especes = "{ref:dossierTsv}{ref:fichiers.especes}"
lois = "{ref:dossierTsv}{ref:fichiers.lois}"
numNomRetenus = "{ref:dossierTsv}{ref:fichiers.numNomRetenus}"
/tags/v5.7-arrayanal/scripts/modules/sptb/Sptb.php
New file
0,0 → 1,90
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M cli.php sptb -a chargerTous
*/
class Sptb extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('sptb');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerDonnees('especes');
$this->chargerDonnees('lois');
$this->genererChampNumNomRetenu();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerDonnees' :
$this->chargerDonnees('especes');
$this->chargerDonnees('lois');
$this->genererChampNumNomRetenu();
break;
case 'genererChampNumNomRetenu' :
$this->genererChampNumNomRetenu();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerDonnees($type) {
$chemin = Config::get('chemins.'.$type);
$table = Config::get('tables.'.$type);
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
private function genererChampNumNomRetenu() {
$this->preparerTablePrChpNumNomRetenu();
$this->genererNumNomRetenu();
}
private function preparerTablePrChpNumNomRetenu() {
$table = Config::get('tables.especes');
$requete = "SHOW COLUMNS FROM $table LIKE 'num_nom_retenu' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE $table ".
'ADD num_nom_retenu INT(10) '.
'NULL DEFAULT NULL AFTER num_nom';
$this->getBdd()->requeter($requete);
}
}
private function genererNumNomRetenu() {
$table = Config::get('tables.especes');
$table_referentiel = Config::get('tables.referentielTaxo');
$requete = 'UPDATE '.$table.' s, '.$table_referentiel.' r '.
'SET s.num_nom_retenu = r.num_nom_retenu '.
' WHERE s.num_nom = r.num_nom ';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS sptb_meta, sptb_especes_v2012, sptb_lois_v2012";
$this->getBdd()->requeter($requete);
Debug::printr('suppression');
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/sptba/sptba.ini
New file
0,0 → 1,19
version="2012"
dossierTsv = "{ref:dossierDonneesEflore}sptba/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
especes = "sptba_especes_v2012"
lois = "sptba_lois_v2012"
referentielTaxo = "bdtxa_v1_00"
 
[fichiers]
structureSql = "sptba_v2012.sql"
especes = "sptba_especes_v2012.tsv"
lois = "sptba_lois_v2012.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
especes = "{ref:dossierTsv}{ref:fichiers.especes}"
lois = "{ref:dossierTsv}{ref:fichiers.lois}"
numNomRetenus = "{ref:dossierTsv}{ref:fichiers.numNomRetenus}"
/tags/v5.7-arrayanal/scripts/modules/sptba/Sptba.php
New file
0,0 → 1,90
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M cli.php sptba -a chargerTous
*/
class Sptba extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('sptba');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerDonnees('especes');
$this->chargerDonnees('lois');
$this->genererChampNumNomRetenu();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerDonnees' :
$this->chargerDonnees('especes');
$this->chargerDonnees('lois');
$this->genererChampNumNomRetenu();
break;
case 'genererChampNumNomRetenu' :
$this->genererChampNumNomRetenu();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerDonnees($type) {
$chemin = Config::get('chemins.'.$type);
$table = Config::get('tables.'.$type);
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
private function genererChampNumNomRetenu() {
$this->preparerTablePrChpNumNomRetenu();
$this->genererNumNomRetenu();
}
private function preparerTablePrChpNumNomRetenu() {
$table = Config::get('tables.especes');
$requete = "SHOW COLUMNS FROM $table LIKE 'num_nom_retenu' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE $table ".
'ADD num_nom_retenu INT(10) '.
'NULL DEFAULT NULL AFTER num_nom';
$this->getBdd()->requeter($requete);
}
}
private function genererNumNomRetenu() {
$table = Config::get('tables.especes');
$table_referentiel = Config::get('tables.referentielTaxo');
$requete = 'UPDATE '.$table.' s, '.$table_referentiel.' r '.
'SET s.num_nom_retenu = r.num_nom_retenu '.
' WHERE s.num_nom = r.num_nom ';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS sptba_meta, sptba_especes_v2012, sptba_lois_v2012";
$this->getBdd()->requeter($requete);
Debug::printr('suppression');
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/iso_639_1/Iso6391.php
New file
0,0 → 1,64
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php iso6391
* -a chargerTous
* Options :
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).
*/
class Iso6391 extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('iso-639-1');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerIso6391();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerIso6391' :
$this->chargerIso6391();
break;
case 'test' :
$this->tester();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function tester() {
echo Config::get('test');
}
 
private function chargerIso6391() {
$chemin = Config::get('chemins.iso6391');
$table = Config::get('tables.iso6391');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY ';' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 0 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS iso_639_1_meta, iso_639_1_v2002";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/iso_639_1/iso-639-1.ini
New file
0,0 → 1,14
version="2002"
dossierTsv = "{ref:dossierDonneesEflore}iso-639-1/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
iso6391 = "iso_639_1_v{ref:version}"
 
[fichiers]
structureSql = "iso-639-1_v{ref:version}.sql"
iso6391 = "iso-639-1_v{ref:version}.csv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
iso6391 = "{ref:dossierTsv}{ref:fichiers.iso6391}"
/tags/v5.7-arrayanal/scripts/modules/iso_639_1
New file
Property changes:
Added: svn:ignore
+iso-639-1.ini
/tags/v5.7-arrayanal/scripts/modules/eflore/Eflore.php
New file
0,0 → 1,54
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M cli.php eflore -a chargerTous
*/
class Eflore extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('eflore');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerOntologies();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerOntologies' :
$this->chargerOntologies();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerOntologies() {
$chemin = Config::get('chemins.ontologies');
$table = Config::get('tables.ontologies');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS eflore_meta, eflore_ontologies";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/eflore/get-donnees-fiches-eflore.php
New file
0,0 → 1,181
<?php
/**
* @category PHP 5.2
* @package Framework
* @author Raphaël Droz <raphael@tela-botanica.org>
* @copyright Copyright (c) 2013, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL-v3
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL-v2
*/
 
/*
- bootstrap le framework
- bootstrap une fiche
- puis, pour un ou plusieurs onglet (automatique ou manuellement),
obtient les données correspondante.
 
L'objectif est de pouvoir générer un flux de données exhaustive pour une Fiche donnée
tout en restant assez indépendant des (lourds) appels à l'API.
Une finalité est de pouvoir s'orienter vers un cron pour index Sphinx, tout en
permettant d'identifier les limites de l'API.
*/
 
 
define('_DIR_FRAMEWORK', '/home/raphael/TBF/trunk/framework');
define('_DIR_CONSULT', '/home/raphael/eflore/consultation');
define('_DIR_SERVICES', '/home/raphael/eflore/projets/services/modules/0.1');
 
//require_once __DIR__ . '/../../framework.php';
set_include_path(_DIR_FRAMEWORK . PATH_SEPARATOR .
_DIR_CONSULT . '/controleurs' . PATH_SEPARATOR .
_DIR_CONSULT . '/bibliotheque' . PATH_SEPARATOR .
_DIR_CONSULT . '/modules/fiche' . PATH_SEPARATOR .
_DIR_CONSULT . '/metier/api_0.1' . PATH_SEPARATOR .
_DIR_SERVICES . '/commun' . PATH_SEPARATOR .
_DIR_SERVICES . '/bdtfx' . PATH_SEPARATOR .
_DIR_CONSULT . '/modules/fiche/formateurs' . PATH_SEPARATOR .
get_include_path());
spl_autoload_extensions('.php');
spl_autoload_register();
 
/*require_once _DIR_FRAMEWORK . '/Controleur.php';
require_once _DIR_CONSULT . '/controleurs/AppControleur.php';
require_once _DIR_CONSULT . '/bibliotheque/AppUrls.php';
require_once _DIR_CONSULT . '/controleurs/aControleur.php';
require_once _DIR_CONSULT . '/bibliotheque/Conteneur.php';
require_once _DIR_CONSULT . '/modules/fiche/Fiche.php';*/
 
 
// require_once _DIR_CONSULT . '/modules/fiche/Fiche.php'
require_once('Framework.php');
Framework::setCheminAppli(__FILE__);
Framework::setInfoAppli(Config::get('info'));
// idéalement
// $a = new Fiche(new Conteneur(array()));
 
 
require_once('Config.php');
require_once('Controleur.php');
require_once('aControleur.php');
require_once('AppControleur.php');
require_once('AppUrls.php');
require_once('Conteneur.php');
 
AppControleur::initialiser();
 
require_once('Commun.php');
require_once('CommunNomsTaxons.php');
require_once('Eflore.php');
require_once('Taxons.php');
require_once('Noms.php');
 
require_once('NomCourant.php');
require_once('Nom.php');
 
Config::charger(_DIR_FRAMEWORK . '/config.ini');
Config::charger(_DIR_CONSULT . '/configurations/config.ini');
 
 
require_once('Fiche.php');
$a = new Fiche();
$_GET['num_nom'] = 141;
$_GET['referentiel'] = 'bdtfx';
 
$a->initialiser();
 
$classes = array(
// 'illustrations',
// 'repartition',
// 'ecologie', // fait main (mais peu utile)
 
// 'nomenclature', // TODO
// 'description', // fait main
// 'ethnobotanique', // fait main
// 'bibliographie', // fait main
// 'statut', // TODO
);
 
// pour nomenclature
require_once('MetaDonnees.php');
require_once('Wikini.php');
 
// pour description
require_once('Textes.php');
require_once('Informations.php');
 
// pour ethnobotanique
require_once('NomsVernaculaires.php');
 
// pour bibliographie
require_once('BiblioBota.php');
 
// pour statuts
require_once('Statuts.php');
 
// pour ecologie
require_once('Graphiques.php');
require_once('Syntaxons.php');
 
// pour repartition
require_once('Cartes.php'); // TODO
 
// way 1
foreach($classes as $c) {
$a->onglet = $c;
$b = $a->obtenirDonnees();
var_dump($b);die();
}
 
 
// non-nécessaire si l'on peut récupérer le conteneur
// initialisé par new Fiche()
// $conteneur = new Conteneur($a->parametres);
 
// description
$onglet = new Description($a->conteneur);
$onglet->obtenirDonnees();
$onglet->getCoste();
echo implode('; ', $onglet->donnees['wikini']['description']);
echo implode('; ', $onglet->donnees['coste']['description']);
 
// bibliographie
Config::charger(_DIR_CONSULT . '/configurations/bdtfx.ini');
$onglet = new Bibliographie($a->conteneur);
$onglet->obtenirDonnees();
echo implode('; ', $onglet->donnees['flores']['liste_flores']);
echo implode('; ', $onglet->donnees['bibliobota']['references']);
 
// ethnobota
Config::charger(_DIR_CONSULT . '/configurations/bdtfx.ini');
$onglet = new Ethnobotanique($a->conteneur);
$onglet->obtenirDonnees();
echo implode('; ', array_map(function($v) { return $v['nom_vernaculaire']; }, $onglet->donnees['nvjfl']['noms'])) . '; ' .
implode('; ', array_map(function($v) { return $v['nom_vernaculaire']; }, $onglet->donnees['nvps']['noms']));
 
// ecologie
Config::charger(_DIR_CONSULT . '/configurations/bdtfx.ini');
$onglet = new Ecologie($a->conteneur);
// $onglet->obtenirDonnees(); // slow !
// var_dump($onglet->donnees['baseflor']['legende']);
 
 
 
/*
API: TODO:
- Chaque service de /consultation/formateur/ doit définir en en-tête:
* référentiels supportés
* fichiers/directives de configuration nécessaire
* class utilisées (namespace "use")
 
- obtenirDonnees() doit prendre ses paramètres [optionnels] par argument, sans compter
sur l'instanciation et la définition d'attributs
- obtenirDonnees() doit retourner les valeurs générées
- obtenirDonnees() ne doit pas traiter le formattage des résultats (getBloc() oui)
- si $this->données reste nécessaire pour une quelconque raison, celui-ci doit être public
 
- pour Fiche.php
- onglets ne doit plus être un attribut (pas même public)
- executerFiche(), executerOnglet() et obtenirDonnees() doivent prendre un $onglet comme paramètre
- $parametre et $conteneur doivent être "public"
 
*/
/tags/v5.7-arrayanal/scripts/modules/eflore/eflore.ini
New file
0,0 → 1,14
version="2011"
dossierTsv = "{ref:dossierDonneesEflore}eflore/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
ontologies = "eflore_ontologies"
 
[fichiers]
structureSql = "eflore_v2011.sql"
ontologies = "eflore_ontologies_v2011.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.7-arrayanal/scripts/modules/sauvages/Sauvages.php
New file
0,0 → 1,400
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php sauvages -a chargerTous
*/
class Sauvages extends EfloreScript {
private $contenu_fichier = array();
protected $parametres_autorises = array(
'-f' => array(true, true, 'Nom du fichier ou du dossier à traiter'));
private $caracteresAccentues = array(
'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î',
'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß',
'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î',
'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā',
'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď',
'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ',
'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ',
'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ',
'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ',
'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ',
'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ',
'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż',
'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ',
'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
private $caracteresNormaux = array(
'A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I',
'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's',
'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i',
'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a',
'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd',
'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g',
'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i',
'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l',
'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R',
'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't',
'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y',
'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I',
'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('sauvages');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->creerXmlTaxons();
$this->creerXmlCriteres();
break;
case 'creerXmlCriteres' :
$this->creerXmlCriteres();
break;
case 'creerXmlTaxons' :
$this->creerXmlTaxons();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
public function creerXmlCriteres() {
$this->recupererContenuFichier();
$criteres_nom = $this->contenu_fichier[0];
unset($this->contenu_fichier[0]);
$criteres_label = $this->contenu_fichier[1];
unset($this->contenu_fichier[1]);
$description_label = $this->contenu_fichier[2];
unset($this->contenu_fichier[2]);
$criteres_valeurs = $this->extraireValeurs();
$xml = $this->formerXmlCriteres($criteres_nom, $criteres_label, $description_label, $criteres_valeurs);//print_r($xml);
file_put_contents("./xml_criteres.xml", $xml);
}
public function formerXmlCriteres($nom, $label, $description, $valeurs) {
$xml='<keys>
<groupe id="1">
<nom>Arbres</nom>
<media>images/pictos/icone_arbre.png</media>
<criteres>';
foreach ($label as $id=>$criteres) {
if ($id > 3) {
$xml .= '<critere id="1.'.$id.'">
<label>'.$criteres.'</label>
<description>'.$description[$id].'</description>
<valeurs>';
foreach ($valeurs[$id] as $id_val=>$valeur) {
if ($valeur != "0") {
$crit = str_replace(" ", "_", $this->supprimerAccents($nom[$id]));
$val = str_replace(" ", "_", $this->supprimerAccents($valeur));
$image = $crit."_".$val;
$xml .= '<valeur code="1.'.$id.'.'.$id_val.'" media="images/pictos/'.$image.'.png">'.$valeur.'</valeur>';
}
}
$xml .= '</valeurs></critere>';
}
}
$xml .= "</criteres>
</groupe>
</keys>";
return $xml;
}
private function extraireValeurs() {
$valeurs = array();
foreach ($this->contenu_fichier as $ligne) {
$i = 0;
if ($ligne != "") {
foreach ($ligne as $critere) {
$valeur_multiple = explode("/", $critere);
foreach ($valeur_multiple as $valeur) {
if (!isset($valeurs[$i]) || !in_array(trim($valeur), $valeurs[$i])) {
$valeurs[$i][] = trim($valeur);
}
}
$i++;
}
}
}
return $valeurs;
}
public function creerXmlTaxons() {
$this->recupererContenuFichier();
$criteres_label = array_flip($this->contenu_fichier[0]);
unset($this->contenu_fichier[0]);
unset($this->contenu_fichier[1]);
unset($this->contenu_fichier[2]);
$criteres_valeurs = $this->extraireValeurs();
$xml = $this->formerXmlTaxons($criteres_label, $criteres_valeurs); //print_r($xml);
file_put_contents("./xml_taxons.xml", $xml);
}
public function formerXmlTaxons($criteres_label, $criteres_valeurs) {
$xml='<?xml version="1.0" ?><TAXONS SUBJECT="XML">';
$rest = new RestClient();
foreach ($this->contenu_fichier as $id=>$taxon) {
if ($taxon != "") {
$infos_taxon = $this->rechercherInfosTaxon($rest, $taxon[$criteres_label["nom scientifique"]]);
$xml .= '<TAXON id="'.$id.'" value="'.
ucfirst($taxon[$criteres_label["nom vernaculaire"]]).'" sciName="'.trim($taxon[$criteres_label["nom scientifique"]]).'" groupe="1">
<DESCRIPTION>'.$infos_taxon["description"].'</DESCRIPTION>
<PICTURES>';
if ($infos_taxon["images"] != array()) {
if (isset($infos_taxon["images"][$taxon[$criteres_label["image priorite"]]])) {
$auteur = $this->rechercherInfosAuteurImage($infos_taxon["images"][$taxon[$criteres_label["image priorite"]]], $rest).", www.tela-botanica.org, CC-Licence (by-sa)";
$xml .= '<PICTURE media="'.$infos_taxon["images"][$taxon[$criteres_label["image priorite"]]]["binaire.href"].'"><author>'.$auteur.'</author></PICTURE>';
unset($infos_taxon["images"][$taxon[$criteres_label["image priorite"]]]);
}
foreach ($infos_taxon["images"] as $image) {
$auteur = $this->rechercherInfosAuteurImage($image, $rest).", www.tela-botanica.org, CC-Licence (by-sa)";
$xml .= '<PICTURE media="'.$image["binaire.href"].'"><author>'.$auteur.'</author></PICTURE>';
}
}
$xml .= '</PICTURES><CRITERIAS>';
for ($i=4; $i < count($taxon); $i++) {
if (trim($taxon[$i]) !== "0") {
$valeurs = array();
foreach (explode("/",$taxon[$i]) as $valeur) {
$valeurs[] = '1.'.$i.'.'.array_search(trim($valeur), $criteres_valeurs[$i]);
}
$xml .= '<VALUE code="'.implode(',', $valeurs).'"/>';
}
}
$xml .= '</CRITERIAS></TAXON>';
}
}
$xml .= "</TAXONS>";
return $xml;
}
// interroge l'annuaire pour récupérer le pseudo
private function rechercherInfosAuteurImage($image, $rest) {
$courriel = $image["observation"]["auteur.courriel"];
$url_auteur = "http://www.tela-botanica.org/service:annuaire:utilisateur/identite-par-courriel/".$courriel;
$reponse = $rest->consulter($url_auteur);
$reponse = json_decode($reponse, true);
if (isset($reponse[$courriel]) && $reponse[$courriel]["pseudoUtilise"] == true) {
$auteur = $reponse[$courriel]["pseudo"];
} else{
$auteur = $image["observation"]["auteur.prenom"]." ".$image["observation"]["auteur.nom"];
}
return $auteur;
}
private function rechercherInfosTaxon($rest, $ns) {
$info = array("description" => "", "images" => array());
$reponse = $this->consulterWebService($rest, "bdtfx",
"noms", "?retour.champs=nom_retenu.id,num_taxonomique&retour.tri=retenu&masque=".urlencode(trim($ns)));
if (is_array($reponse["resultat"])) {
$num_nom = $reponse["resultat"][key($reponse["resultat"])]["nom_retenu.id"];
$num_taxon = $reponse["resultat"][key($reponse["resultat"])]['num_taxonomique'];
}
$info["description"] = $this->rechercherDescription($num_taxon, $num_nom, $rest);
$info["images"] =array();
$tags = array('fleur', 'feuille', 'rameau', 'port', 'fruit');
$cles = array();
foreach ($tags as $tag) {
$url_image = "http://www.tela-botanica.org/service:del:0.1/images".
"?masque.referentiel=bdtfx&masque.tag={$tag}&tri=votes&ordre=desc&protocole=3&navigation.limite=1&format=CRS&masque.nn=".$num_nom;
$image = $rest->consulter($url_image);
$image = json_decode($image, true);
if ($image["resultats"] !== array()) {
$info["images"][$tag]["binaire.href"] = $image["resultats"][key($image["resultats"])]["binaire.href"];
$info["images"][$tag]["observation"] = $image["resultats"][key($image["resultats"])]["observation"];
$cles[key($image["resultats"])] = "";
}
}
//si image taguée absente
$url_image = "http://www.tela-botanica.org/service:del:0.1/images".
"?masque.referentiel=bdtfx&tri=votes&ordre=desc&protocole=3&navigation.limite=5&format=CRS&masque.nn=".$num_nom;
$reponse = $rest->consulter($url_image);
$reponse = json_decode($reponse, true);
if ($cles !== array()) {
// supprimer les images communes au tag et les mieux notés
$reponse["resultats"] = array_diff_key($reponse["resultats"], $cles);
for ($i = 0; $i < 5-count($cles); $i++) {
$image = array_shift($reponse["resultats"]);
$info["images"][$i]["binaire.href"] = $image["binaire.href"];
$info["images"][$i]["observation"] = $image["observation"];
}
} else {
$info["images"] = $reponse["resultats"];
}
return $info;
}
private function rechercherDescription($num_taxon, $num_nom, $rest) {
$url_wiki = "http://www.tela-botanica.org/wikini/eFloreRedaction/api/rest/0.5/pages/SmartFloreBDTFXnt".
$num_taxon."?txt.format=text/plain&txt.section.titre=Comment%20la%20reconnaître%20%3F";
$wiki = $rest->consulter($url_wiki); $wiki = json_decode($wiki, true);
if ($wiki['texte'] != "" && strstr($wiki['texte'], 'Brève phrase sur son type biologique (simplifié)') === false ){
$description = $this->formaterSmartflore($wiki['texte']);
} else {
$coste = $this->consulterWebService($rest, "coste", "textes", "/bdtfx.nn:".$num_nom);
if ($coste['resultats'] != array() && $coste['resultats'][key($coste["resultats"])]['texte'] != "") {
$description = $this->formaterCoste($coste['resultats']);
} else {
$baseflor = $this->consulterWebService($rest, "baseflor", "informations", "/bdtfx.nn:".$num_nom);
$description = $this->formaterBaseflor($baseflor);
}
}
return $description;
}
//remplacement des \n par <br />
private function formaterSmartflore($texte) {
$a_enlever = array(Chr(10).'=', '='.Chr(10), Chr(10).''.Chr(10), '*');
$texte = str_replace($a_enlever, '', $texte);
$texte = str_replace(Chr(10), '<br />', $texte);
//supprimer image et lien
$texte = preg_replace('/\[\[http\:\/\/upload.*\.jpg [a-z| |A-Z]*\]\]/', '', $texte);
$texte = str_replace('[[http://fr.wikipedia.org/wiki/Corymbe corymbes]]', 'corymbes', $texte);
$texte = preg_replace('/\[\[SmartFlore.*[0-9] (.*)\]\]/', '\1', $texte);
$texte = preg_replace('/\[\[http\:\/\/www\..* (.*)\]\]/', '\1', $texte);
$texte = trim(str_replace('<br /><br />', '<br />', $texte));
return $texte;
}
private function formaterCoste($coste) {
$texte = $this->mettreEnFormeCoste($coste[key($coste)]['texte']);
return $texte;
}
static function mettreEnFormeCoste($texte) {
$txt_fmt = array();
//decouper elements remarquables avant le texte
self::separerNomScientifique_a_NomCommun($texte, $txt_fmt);
$txt_fmt = array();
$texte = preg_replace('/\//','',$texte);
//decouper elements remarquables après le texte
self::separerEcologie_a_Usages($texte, $txt_fmt);
//le morceau qui reste est le gros de la description
$texte = str_replace(';','</br> -','- '.$texte);
$texte = str_replace('–','',$texte);
$txt_fmt['description'] = $texte;
$retour = "";
foreach ($txt_fmt as $titre=>$parag) {
$parag = preg_replace('/\- \. /','- ',$parag);
$parag = preg_replace('/\. \./','.',$parag);
$retour .= ucfirst($titre)." : ".trim($parag)." ; ";
}
return $retour;
}
static function separerNomScientifique_a_NomCommun(&$txt, &$txt_fmt){
if ( preg_match('/\*\*(.+)\*\*([^–]*)–/', $txt, $retour)){
/* !! attention on enlève un tiret cadratin – pas un trait d'union - !! */
$a_enlever = array('/–/','/\./' );
$txt_fmt['nom_scientifique'] = preg_replace($a_enlever,'',$retour[1]);
if(preg_match('/\((.+)\)/',$retour[2],$synonymes)){
$txt_fmt['synonymes'] = $synonymes[1];
} else {
$txt_fmt['nom_scientifique'] .= $retour[2];
}
$txt = str_replace($retour[0],'',$txt);
}
/* !! attention il y a un espace avant les // du début !! */
if ( preg_match('/^ \/\/([^\/\/]+)\/\//', $txt, $retour)){
$a_enlever = array('/–/','/\./' );
$txt_fmt['nom_commun'] = preg_replace($a_enlever,'',$retour[1]);
$txt = str_replace($retour[0],'',$txt);
}
}
static function separerEcologie_a_Usages(&$txt, &$txt_fmt) {
if (preg_match('/\.\s*([A-ZÉÀÈ].+)$/',$txt, $retour)) {
$txt_fmt['ecologie'] = $retour[1];
$txt = str_replace($retour[0],'.',$txt);
if (isset($txt_fmt['ecologie']) && preg_match('/–(.+)/', $txt_fmt['ecologie'] , $retour)){
$txt_fmt['repartition'] = $retour[1];
$txt_fmt['ecologie'] = str_replace($retour[0],'',$txt_fmt['ecologie']);
}
if (isset($txt_fmt['repartition']) && preg_match('/=(.+)$/', $txt_fmt['repartition'], $retour)){
$txt_fmt['floraison'] = $retour[1];
$txt_fmt['repartition'] = str_replace($retour[0],'',$txt_fmt['repartition']);
$txt_fmt['repartition'] = str_replace(';',',',$txt_fmt['repartition']);
}
if (isset($txt_fmt['floraison']) && preg_match('/–(.+)$|\n(.+)$/',$txt_fmt['floraison'], $retour)){
$txt_fmt['usages'] = isset($retour[1]) ? $retour[1] : $retour[2];
$txt_fmt['floraison'] = str_replace($retour[0],'.',$txt_fmt['floraison']);
}
if (isset($txt_fmt['floraison']) && preg_match('/([Ff]l\.) (.+)/',$txt_fmt['floraison'], $retour)){
$txt_fmt['floraison'] = $retour[2];
$txt_fmt['floraison'] = str_replace($retour[1],'',$txt_fmt['floraison']);
}
if (isset($txt_fmt['floraison']) && preg_match('/([Ff]r\.) (.+)/',$txt_fmt['floraison'], $retour)){
$txt_fmt['fructification'] = $retour[2];
$txt_fmt['floraison'] = str_replace($retour[0],'',$txt_fmt['floraison']);
$txt_fmt['floraison'] = str_replace(',','',$txt_fmt['floraison']);
$txt_fmt['fructification'] = str_replace($retour[1],'',$txt_fmt['fructification']);
$txt_fmt['fructification'] = str_replace('.','',$txt_fmt['fructification']);
}
}
}
private function formaterBaseflor($reponse) {
$description = "En cours de rédaction.";
if (isset($reponse["nom_sci"]) && $reponse["nom_sci"] != "") {
$description = "Formation végétale : ".$reponse["form_vegetale"]."; ".
"Inflorescence : ".$reponse["inflorescence"]."; ".
"Couleur de la fleur : ".$reponse["couleur_fleur"]."; ".
"Sexualité : ".$reponse["sexualite"]."; ".
"Fruit : ".$reponse["fruit"]."; ".
"Pollinisation : ".$reponse["pollinisation"]."; ".
"Dissémination : ".$reponse["dissemination"]."; ".
"Ecologie : ".$reponse["carac_ecolo"]." – ".
"Chorologie : ".$reponse["chorologie"]."; ".
"Floraison : ".$reponse["floraison"];
}
return $description;
}
private function consulterWebService($rest, $projet,$resssource,$parametres) {
$url_id = "http://api.tela-botanica.org/service:eflore:0.1/".$projet."/".$resssource.$parametres;
$reponse = $rest->consulter($url_id);
return json_decode($reponse, true);
}
private function recupererContenuFichier() {
$nomFichier = Config::get('dossierCsv').Config::get('projet');
if ($nomFichier && file_exists($nomFichier) ){
$extensionFichier = strtolower(strrchr($nomFichier, '.'));
if ($extensionFichier === ".csv"){
$file = new SplFileObject($nomFichier);
$file->setFlags(SplFileObject::SKIP_EMPTY);
$i = 0;
echo "Traitement du fichier : ";
while (!$file->eof()){
$ligne_csv = $file->fgetcsv($delimiter = ';');
$this->contenu_fichier[$i] = $ligne_csv;
echo str_repeat(chr(8), ( strlen( $i ) + 1 ))."\t".$i++;
}
echo "\n";
} else {
$this->traiterErreur("Le fichier : $nomFichier n'est pas au format csv.");
}
} else {
$this->traiterErreur("Le fichier : $nomFichier n'existe pas.");
}
}
public function supprimerAccents($chaine) {
return str_replace($this->caracteresAccentues, $this->caracteresNormaux, $chaine);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/sauvages/sauvages.ini
New file
0,0 → 1,5
version="1"
projet="cles_sauvages.csv"
dossierCsv = "{ref:dossierDonneesEflore}sauvages/3/"
chemin_appli = "php:Framework::getCheminAppli()"
 
/tags/v5.7-arrayanal/scripts/modules/nvjfl/nvjfl.ini
New file
0,0 → 1,23
version = "2007"
dossierTsv = "{ref:dossierDonneesEflore}nvjfl/2007-10-29/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
nvjfl = "nvjfl_v{ref:version}"
nvjflLienBiblio = "nvjfl_lien_biblio_v{ref:version}"
nvjflBiblio = "nvjfl_biblio_v{ref:version}"
ontologies = "nvjfl_ontologies_v{ref:version}"
 
[fichiers]
structureSql = "nvjfl_v{ref:version}.sql"
nvjfl = "{ref:tables.nvjfl}.tsv"
nvjflBiblio = "{ref:tables.nvjflBiblio}.tsv"
nvjflLienBiblio = "{ref:tables.nvjflLienBiblio}.tsv"
ontologies = "{ref:tables.ontologies}.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
nvjfl = "{ref:dossierTsv}{ref:fichiers.nvjfl}"
nvjflBiblio = "{ref:dossierTsv}{ref:fichiers.nvjflBiblio}"
nvjflLienBiblio = "{ref:dossierTsv}{ref:fichiers.nvjflLienBiblio}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.7-arrayanal/scripts/modules/nvjfl/Nvjfl.php
New file
0,0 → 1,180
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php nvjfl
* -a chargerTous
* Options :
* -t : Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).
*/
class Nvjfl extends EfloreScript {
 
private $nomsIndex = array();
private $numeroIndex = 1;
 
protected $parametres_autorises = array(
'-t' => array(false, false, 'Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).'));
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('nvjfl');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerNvjfl();
$this->chargerBiblio();
$this->chargerBiblioLien();
$this->chargerOntologies();
break;
case 'chargerStructure' :
$this->chargerStructureSql();
break;
case 'chargerNvjfl' :
$this->chargerNvjfl();
break;
case 'chargerBiblio' :
$this->chargerBiblio();
break;
case 'chargerBiblioLien' :
$this->chargerBiblioLien();
break;
case 'chargerOntologies' :
$this->chargerOntologies();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
/**
* Charge le fichier en créant un id pour chaque nom vernaculaire.
*/
private function chargerNvjfl() {
//Debug::printr(Config::get('fichiers'));
$fichierOuvert = $this->ouvrirFichier(Config::get('chemins.nvjfl'));
$donnees = $this->analyserFichier($fichierOuvert);
fclose($fichierOuvert);
foreach ($donnees as $donnee) {
$requete = 'INSERT INTO '.Config::get('tables.nvjfl').' VALUES ('.implode(', ', $donnee).')';
$this->getBdd()->requeter($requete);
 
$this->afficherAvancement("Insertion des noms vernaculaires dans la base de données");
if ($this->stopperLaBoucle($this->getParametre('t'))) {
break;
}
}
echo "\n";
}
 
private function analyserFichier($fichierOuvert) {
$donnees = array();
$entetesCsv = fgets($fichierOuvert);
while ($ligneCsv = fgets($fichierOuvert)) {
$champs = explode("\t", trim($ligneCsv));
if (count($champs) > 0) {
if (isset($champs[2])) {
$nomVernaculaire = $champs[2];
$indexCourrant = $this->getIndexNomVernaculaire($nomVernaculaire);
$champs = array_merge(array($indexCourrant), $champs);
$donnees[] = $this->protegerValeursDesChamps($champs);
}
}
$this->afficherAvancement("Analyse du fichier des noms vernaculaires");
if ($this->stopperLaBoucle()) {
break;
}
}
echo "\n";
return $donnees;
}
 
private function getIndexNomVernaculaire($nomVernaculaire) {
$indexCourrant = null;
if (array_key_exists($nomVernaculaire, $this->nomsIndex) == false) {
$this->nomsIndex[$nomVernaculaire] = $this->numeroIndex++;
}
$indexCourrant = $this->nomsIndex[$nomVernaculaire];
return $indexCourrant;
}
 
private function ouvrirFichier($chemin) {
$fichierOuvert = false;
if ($chemin) {
if (file_exists($chemin) === true) {
$fichierOuvert = fopen($chemin, 'r');
if ($fichierOuvert == false) {
throw new Exception("Le fichier $chemin n'a pas pu être ouvert.");
}
} else {
throw new Exception("Le fichier $chemin est introuvable.");
}
} else {
throw new Exception("Aucun chemin de fichier n'a été fourni.");
}
return $fichierOuvert;
}
 
private function protegerValeursDesChamps($champs) {
$champsProteges = array();
for ($i = 0; $i < 9; $i++) {
$valeur = isset($champs[$i]) ? $champs[$i] : '';
$champsProteges[] = $this->getBdd()->proteger($valeur);
}
return $champsProteges;
}
 
private function chargerBiblio() {
$cheminsNvjflBiblio = Config::get('chemins.nvjflBiblio');
$tableNvjflBiblio = Config::get('tables.nvjflBiblio');
$requete = "LOAD DATA INFILE '$cheminsNvjflBiblio' ".
"REPLACE INTO TABLE $tableNvjflBiblio ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerBiblioLien() {
$cheminNvjflLienBiblio = Config::get('chemins.nvjflLienBiblio');
$tableNvjflLienBiblio = Config::get('tables.nvjflLienBiblio');
$requete = "LOAD DATA INFILE '$cheminNvjflLienBiblio' ".
"REPLACE INTO TABLE $tableNvjflLienBiblio ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function chargerOntologies() {
$cheminOntologies = Config::get('chemins.ontologies');
$tableOntologies = Config::get('tables.ontologies');
$requete = "LOAD DATA INFILE '$cheminOntologies' ".
"REPLACE INTO TABLE $tableOntologies ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS nvjfl_biblio_v2007, nvjfl_lien_biblio_v2007, nvjfl_meta, nvjfl_ontologies_v2007, nvjfl_v2007";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/nvjfl
New file
Property changes:
Added: svn:ignore
+nvjfl.ini
/tags/v5.7-arrayanal/scripts/modules/liste_rouge/liste_rouge.ini
New file
0,0 → 1,17
version="2012"
dossierTsv = "{ref:dossierDonneesEflore}liste_rouge/{ref:version}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
listeRouge = "liste_rouge_v{ref:version}"
referentielTaxo = "bdtfx_v2_00"
 
[fichiers]
structureSql = "liste_rouge_v{ref:version}.sql"
listeRouge = "liste_rouge_v{ref:version}.tsv"
listeRougeCorresp = "liste_rouge_correspondance_v{ref:version}.sql"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
listeRouge = "{ref:dossierTsv}{ref:fichiers.listeRouge}"
listeRougeCorresp = "{ref:dossierTsv}{ref:fichiers.listeRougeCorresp}"
/tags/v5.7-arrayanal/scripts/modules/liste_rouge/ListeRouge.php
New file
0,0 → 1,114
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M cli.php sptb -a chargerTous
*/
class ListeRouge extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('liste_rouge');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerDonnees();
$this->genererChampNumNomRetenu();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerDonnees' :
$this->chargerDonnees();
$this->genererChampNumNomRetenu();
break;
case 'genererChampNumNomRetenu' :
$this->genererChampNumNomRetenu();
break;
case 'ajouterChampNumNomRetenu' :
$this->ajouterChampNumNomRetenu();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerDonnees() {
$chemin = Config::get('chemins.listeRouge');
$table = Config::get('tables.listeRouge');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
private function genererChampNumNomRetenu() {
$this->preparerTablePrChpNumNomRetenu();
$this->genererNumNomRetenu();
$this->recupererNumNomNonTrouve();
}
private function preparerTablePrChpNumNomRetenu() {
$table = Config::get('tables.listeRouge');
$requete = "SHOW COLUMNS FROM $table LIKE 'num_nom_retenu' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE $table ".
' ADD `num_nom_retenu` VARCHAR( 10 ) NOT NULL ,'.
' ADD `nom_sci` VARCHAR( 500 ) NOT NULL ,'.
' ADD INDEX ( `num_nom_retenu` ) ';
$this->getBdd()->requeter($requete);
}
}
private function genererNumNomRetenu() {
$table = Config::get('tables.listeRouge');
$table_referentiel = Config::get('tables.referentielTaxo');
$requete = 'UPDATE '.$table.' s, '.$table_referentiel.' r '.
'SET s.num_nom_retenu = r.num_nom_retenu, s.nom_sci = r.nom_complet '.
'WHERE s.nom_sci_orig = r.nom_complet ';
$this->getBdd()->requeter($requete);
}
private function recupererNumNomNonTrouve() {
$table = Config::get('tables.listeRouge');
$requete = 'SELECT `id`, `nom_sci_orig`'.
' FROM '.$table.
' WHERE `num_nom_retenu` = ""';
$noms = $this->getBdd()->recupererTous($requete);
$debug = "Noms sans correspondance avec bdtfx :\n";
foreach ($noms as $nom) {
$debug .= $nom['id']." ".$nom['nom_sci_orig']."\n";
}
Debug::printr($debug);
}
 
private function ajouterChampNumNomRetenu() {
$chemin = Config::get('chemins.listeRougeCorresp');
$table = Config::get('tables.listeRouge');
$requetes = $this->recupererContenu($chemin);
$this->executerScripSql($requetes);
}
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS liste_rouge_meta, liste_rouge_v2012";
$this->getBdd()->requeter($requete);
Debug::printr('suppression');
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/moissonnage/moissonnage.ini
New file
0,0 → 1,35
code = "ifn"
versions = "2005,2006,2007,2008,2009,2010,2011,2012"
categories = "arbresForet,arbresPeupleraie,couvertsForet,documentation,ecologie,flore,placettesForet,placettesPeupleraie"
dossierTsv = "{ref:dossierDonneesEflore}{ref:code}/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
ifnMeta = "if_meta"
documentationFlore = "ifn_documentation_flore"
arbresForet = "ifn_arbres_foret"
arbresPeupleraie = "ifn_arbres_peupleraie"
couvertsForet = "ifn_couverts_foret"
documentation = "ifn_documentation"
ecologie = "ifn_ecologie"
flore = "ifn_flore"
placettesForet = "ifn_placettes_foret"
placettesPeupleraie = "ifn_placettes_peupleraie"
ifnTest = "ifn"
 
 
[fichiers]
structureSql = "{ref:code}.sql"
arbresForet = "arbres_foret.csv"
arbresPeupleraie = "arbres_peupleraie.csv"
couvertsForet = "couverts_foret.csv"
documentation = "documentation.csv"
ecologie = "ecologie.csv"
flore = "flore.csv"
placettesForet = "placettes_foret.csv"
placettesPeupleraie = "placettes_peupleraie.csv"
documentationFlore = "documentation_flore.csv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
documentation_flore = "{ref:dossierTsv}{ref:documentation_flore}"
/tags/v5.7-arrayanal/scripts/modules/moissonnage/Moissonnage.php
New file
0,0 → 1,120
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php moissonnage -a chargerTous -n baznat
* Options :
* -n : nom du projet
*/
 
class Moissonnage extends EfloreScript {
private $projet = "";
protected $parametres_autorises = array(
'-n' => array(true, true, 'Préciser le nom du dataset que vous souhaitez ajouter ex. baznat, naturedugard-flore'));
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('moissonnage');
 
$cmd = $this->getParametre('a');
$this->projet = $this->getParametre('n');
switch ($cmd) {
case 'chargerTous' :
$this->chargerDonnees();
$this->chargerMetaDonnees();
break;
case 'chargerDonnees' :
$this->chargerDonnees();
break;
case 'chargerMetadonnees' :
$this->chargerMetaDonnees();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
private function chargerDonnees() {
$requete = "CREATE TABLE tb_eflore.".$this->projet."_tapir2 ".
"AS SELECT concat('urn:lsid:',institutionCode,':',collectionCode,':', catalogNumber) AS guid, ".
"`catalogNumber` AS observation_id, `scientificName` AS nom_scientifique_complet, `referencess` AS num_nom, ".
"`county` AS lieu_station_nom, `locality` AS lieu_commune_code_insee, ".
"`decimalLatitude` AS lieu_station_latitude, `decimalLongitude` AS lieu_station_longitude, `geodeticDatum` , ".
"`eventDate` AS observation_date, `identifiedBy` AS observateur_nom_complet ".
"FROM tb_moissonnage.Occurrence ".
"WHERE dataset_id = (SELECT dataset_id FROM tb_moissonnage.Dataset WHERE name = '$this->projet')";
$this->getBdd()->requeter($requete);
}
private function chercherInfosMetaDonnees() {
$infos = array();
$requeteOccurrence = "SELECT institutionCode, collectionCode FROM tb_moissonnage.Occurrence WHERE dataset_id =
(SELECT id FROM tb_moissonnage.Dataset WHERE name='$this->projet');";
$infos['occurrence'] = $this->getBdd()->recuperer($requeteOccurrence);
$requeteDataset = "SELECT * FROM tb_moissonnage.DataPublisher WHERE id =
(SELECT dataPublisher_id FROM tb_moissonnage.Dataset WHERE name='$this->projet')";
$infos['dataPublisher'] = $this->getBdd()->recuperer($requeteDataset);
return $infos;
}
private function chargerMetaDonnees() {
$this->chargerStructureSqlMetaDonnees();
$infos = $this->chercherInfosMetaDonnees();
$date = date('Y_m_d');
$requete = "INSERT INTO tb_eflore.".$this->projet."_tapir_meta (guid, citation, url_projet, createurs) ".
"VALUES ('urn:lsid:{$infos['occurrence']['institutionCode']}:{$infos['occurrence']['collectionCode']}:{$date}', '".
$this->projet." : {$infos['dataPublisher']['description']} du ".
"<a href=\"{$infos['occurrence']['institutionCode']}\" title=\"{$infos['occurrence']['collectionCode']}\" ".
"onclick=\"window.open(this.href); return false;\">{$this->projet}</a>', ".
"'{$infos['occurrence']['institutionCode']}', ".
"'p.courriel={$infos['dataPublisher']['administrativeContact']}, p.courriel={$infos['dataPublisher']['technicalContact']}')";
$this->getBdd()->requeter($requete);
}
private function chargerStructureSqlMetaDonnees() {
$date = date('Y_m_d');
$requete = "CREATE TABLE IF NOT EXISTS tb_eflore.".$this->projet."_tapir_meta ".
"(`guid` varchar(255) NOT NULL ,
`langue_meta` varchar(2) NOT NULL DEFAULT 'fr',
`code` varchar(20) NOT NULL DEFAULT '{$this->projet}',
`version` varchar(20) NOT NULL DEFAULT '{$date}',
`titre` varchar(255) NOT NULL DEFAULT '{$this->projet}',
`description` text,
`mots_cles` varchar(510) NOT NULL DEFAULT 'flore, observation, {$this->projet}',
`citation` varchar(255) NOT NULL,
`url_tech` varchar(510) DEFAULT NULL,
`url_projet` varchar(510) NOT NULL,
`source` text,
`createurs` text NOT NULL,
`editeur` text,
`contributeurs` text,
`droits` text,
`url_droits` varchar(510) DEFAULT 'http://creativecommons.org/licenses/by-sa/2.0/fr/',
`langue` varchar(255) DEFAULT 'fr',
`date_creation` varchar(30) DEFAULT NULL,
`date_validite` varchar(255) DEFAULT NULL,
`couverture_spatiale` varchar(510) DEFAULT NULL,
`couverture_temporelle` varchar(510) DEFAULT NULL,
`web_services` varchar(255) DEFAULT 'meta-donnees:0.1;ontologies:0.1;cartes:0.1',
PRIMARY KEY (`guid`,`langue_meta`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
$this->getBdd()->requeter($requete);
}
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS `ifn_arbres_forets`, `ifn_arbres_peupleraie`, `ifn_couverts_foret`,
`ifn_documentation`, `ifn_documentation_flore`, `ifn_ecologie`, `ifn_flore`, `ifn_placettes_foret`,
`ifn_placettes_peupleraie`;
";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/robot/configuration/cassini.ini
New file
0,0 → 1,3
; Encodage : UTF-8
; Source des données : http://cassini.ehess.fr/
cache_chemin = "php:'/home/'.$_ENV['USER'].'/importation/robots/cassini.ehess.fr/'"
/tags/v5.7-arrayanal/scripts/modules/robot/configuration/wp_commune.ini
New file
0,0 → 1,4
; Encodage : UTF-8
; Source des données : http://fr.wikipedia.org/wiki/
; Version des noms de commune utilisé pour intéroger Wikipedia: Code géographique de l'INSEE version 2008-01-01
cache_chemin = "php:'/home/'.$_ENV['USER'].'/importation/robots/fr.wikipedia.org/'"
/tags/v5.7-arrayanal/scripts/modules/robot/configuration/utm_converter.ini
New file
0,0 → 1,3
; Encodage : UTF-8
; Source des données : http://www.rcn.montana.edu/resources/tools/coordinates.aspx
cache_chemin = "php:'/home/'.$_ENV['USER'].'/importation/robots/rcn.montana.edu/'"
/tags/v5.7-arrayanal/scripts/modules/robot/configuration/cookieconf.txt
New file
0,0 → 1,4
-b ../../../../../../../importation/robots/cookie.txt
-c ../../../../../../../importation/robots/cookie.txt
 
--max-time 50
Property changes:
Added: svn:eol-style
+native
\ No newline at end of property
/tags/v5.7-arrayanal/scripts/modules/robot/configuration/ipni_auteur.ini
New file
0,0 → 1,3
; Encodage : UTF-8
; Source des données : http://ipni.org/
cache_chemin = "php:'/home/'.$_ENV['USER'].'/importation/robots/ipni.org/'"
/tags/v5.7-arrayanal/scripts/modules/robot/Robot.php
New file
0,0 → 1,432
<?php
// Encodage : UTF-8
// +-------------------------------------------------------------------------------------------------------------------+
/**
* Robots
*
* Description : classe permettant d'analyser les pages d'un site web.
* Notes : les noms des pages doivent être dans la bonne casse. http://fr.wikipedia.org/wiki/ambronay ne renvera rien alors que
* http://fr.wikipedia.org/wiki/Ambronay renvera un résultat (Notez le A ou a).
*
//Auteur original :
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Tela-Botanica 1999-2009
* @link http://www.tela-botanica.org/wikini/eflore
* @licence GPL v3 & CeCILL v2
* @version $Id: Robot.class.php 2057 2011-05-13 16:39:06Z Jean-Pascal MILCENT $
*/
// +-------------------------------------------------------------------------------------------------------------------+
class Robot extends ScriptCommande {
/**
* Indique le nom du Robot.
*/
private $robot_nom;
/**
* Indique le fichier de config de la gestion des cookies du Robot.
*/
private $cookie;
/**
* Indique l'url de départ du Robot.
*/
private $page;
/**
* Tableau des URLs à analyse
*/
private $pages = array();
/**
* Chemin vers un fichier contenant les noms des pages à analyser (un nom de page par ligne).
*/
private $page_fichier;
/**
* Contient soit False soit le chemin vers le dossier où mettre les pages en cache.
*/
private $cache = false;
/**
* Contient le squelette de l'url à utiliser pour récupérer les pages web.
*/
private $url_tpl = '';
/**
* Contient false ou l'encodage des pages d'un site web si celui-ci n'est pas en UTF-8.
*/
private $encodage = false;
/**
* Contient la chaine de caractères indiquant où commencer une recherche d'informations dans la page web.
*/
private $chaine_debut = '';
/**
* Contient la chaine de caractères indiquant où terminer une recherche d'informations dans la page web.
*/
private $chaine_fin = '';
/**
* Tableau des expressions régulières récupérant des données lors de l'analyse
*/
private $regexps = array();
/**
* Indique le dossier ou fichier où le Robot doit sotcker les informations collectées.
*/
private $sortie;
 
public $parametres = array( '-pgf' => array(false, '', 'Fichier contenant les pages que le Robot doit analyser'),
'-s' => array(false, '', 'Fichier où stocker les données récupérées par le Robot'),
'-pg' => array(false, '', 'Nom de la page que le Robot doit analyser'));
 
 
public function executer() {
$this->page = $this->getParam('pg');
$this->page_fichier = $this->getParam('pgf');
$this->cookie = dirname(__FILE__).DS.'configuration'.DS.'cookieconf.txt';
$this->sortie = $this->getParam('s');
 
// Construction du tableau contenant les noms des pages à analyser
if (empty($this->page_fichier)) {
$this->pages[] = $this->page;
} else {
$this->pages = $this->convertirFichierEnTableau($this->page_fichier);
}
 
// Création du chemin du cache si le fichier ini du projet l'indique
if ($this->getIni('cache_chemin')) {
$this->cache = $this->getIni('cache_chemin');
}
 
// Lancement du Robot demandé
$cmd = $this->getParam('a');
switch ($cmd) {
case 'wp' :
$this->lancerRobotWikipedia();
break;
case 'wp-pays' :
$this->lancerRobotWikipediaPays();
break;
case 'wp-liste-communes' :
$this->lancerRobotWikipediaListeCommunes();
break;
case 'ipni' :
$this->lancerRobotIpni();
break;
case 'cassini' :
$this->lancerRobotCassini();
break;
case 'utm' :
$this->lancerRobotUtmConverter();
break;
default :
$this->traiterErreur('Erreur : la commande "%s" n\'existe pas!', array($cmd));
}
}
 
/**
* Robot analysant les pages de Wikipedia correspondant à des communes.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pgf ~/importation/robots/eFloreBotWp_INSEE_C.txt -s ~/importation/robots/wp_communes.tsv
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pg Montpellier -s ~/importation/robots/wp_communes.tsv
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pg Montpellier
*
* @return unknown_type
*/
private function lancerRobotWikipedia() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotWp';
$this->url_tpl = 'http://fr.wikipedia.org/wiki/%s';
$this->regexp_ligne = '/<!-- bodytext -->(.*)<!-- \/bodytext -->/umsi';
$this->regexps = array( 'CodeInsee' => 'Code commune<\/a><\/th>(?:\n|\r\n)<td>(\d+)<\/td>',
'Nom' => 'class="entete map" style="[^"]+">(.*)<',
'Latitutde' => '<span class="geo-dec geo" title=".*"><span class="latitude">(.*)<\/span>',
'Longitude' => '<span class="geo-dec geo" title=".*">.*<\/span>, <span class="longitude">(.*)<\/span>',
'Superficie' => 'Superficie<\/a>(?:<\/b><\/td>|<\/th>)(?:\n|\r\n)<td>((?:[0-9]| |&#160;)+(?:,[0-9]+)?) km<sup>2<\/sup>',
'AltitudeMin' => 'Altitudes<\/a><\/th>(?:\n|\r\n)<td>mini. (-?[0-9]+) m — maxi. [ 0-9]+ m<\/td>',
'AltitudeMax' => 'Altitudes<\/a><\/th>(?:\n|\r\n)<td>mini. -?[0-9]+ m — maxi. ([ 0-9]+) m<\/td>',
'Population' => 'Population<\/a><\/th>(?:\n|\r\n)<td>(.*) hab.',
'PopulationAnnee' => 'Population<\/a><\/th>(?:\n|\r\n)<td>.* hab. <small>\(<a href="\/wiki\/[0-9]+"(?: title="[0-9]+")?>([0-9]+)<\/a>',
'CodePostal' => 'Code postal<\/a><\/th>(?:\n|\r\n)<td>([0-9]{5}).*<\/td>',
'PageWikipedia' => '(?:Ce document provient|Récupérée) de « <a href="http:\/\/fr.wikipedia.org\/wiki\/(.*)">'
);
// Préparation des noms des pages
foreach ($this->pages as $id => $nom) {
$this->pages[$id] = str_replace(' ', '_', $nom);
}
$this->analyserUrls();
}
 
/**
* Robot analysant les pages de Wikipedia correspondant à des pays.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp-pays -pgf ~/importation/robots/eFloreBotWp_pays.txt -s ~/importation/robots/wp-pays.tsv
*
* @return unknown_type
*/
private function lancerRobotWikipediaPays() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotWp';
$this->url_tpl = 'http://fr.wikipedia.org/wiki/%s';
$this->regexp_ligne = '/<!-- bodytext -->(.*)<!-- \/bodytext -->/umsi';
$this->regexps = array( 'Nom' => '<table class="infobox_v2" cellspacing="[^"]+" style="[^"]+">(?:\n|\r\n)<caption style="[^"]+"><b>(.*)<\/b>',
'Latitutde' => '<span class="geo-dec geo" title=".*"><span class="latitude">(.*)<\/span>',
'Longitude' => '<span class="geo-dec geo" title=".*">.*<\/span>, <span class="longitude">(.*)<\/span>',
'Superficie' => 'Superficie<\/a><\/b><\/td>(?:\n|\r\n)<td>((?:[0-9]|\s*|&#160;)+(?:,[0-9]+)?)(?:&#160;|\s*)km<sup>2<\/sup>',
'Population' => 'Population<\/a><\/b>(?:&#160;|\s)*<small>\([0-9]+\)<\/small><\/td>(?:\n|\r\n)<td>(.*)(?:&#160;|\s*)hab.',
'PopulationAnnee' => 'Population<\/a><\/b>(?:&#160;|\s)*<small>\(([0-9]+)\)',
'Capitale' => 'Capitale<\/a><\/b><\/td>(?:\n|\r\n)<td>(?:<a href="\/wiki\/[^"]+" title="[^"]+">|)(.+)<',
'PageWikipedia' => '(?:Ce document provient|Récupérée) de « <a href="http:\/\/fr.wikipedia.org\/wiki\/(.*)">'
);
// Préparation des noms des pages
foreach ($this->pages as $id => $nom) {
$this->pages[$id] = str_replace(' ', '_', $nom);
}
$this->analyserUrls();
}
 
/**
* Robot analysant une page de wikipedia à la recherche de plusieurs données par page.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pgf ~/importation/robots/eFloreBotWp_INSEE_C.txt -s ~/importation/robots/wp_communes.tsv
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pg Montpellier -s ~/importation/robots/wp_communes.tsv
* /opt/lampp/bin/php script.php robot -p wp_commune -a wp -pg Montpellier
*
* @return unknown_type
*/
private function lancerRobotWikipediaListeCommunes() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotWpListe';
$this->url_tpl = 'http://fr.wikipedia.org/wiki/%s';
$this->regexp_ligne = '/<tr>(.*)?<\/tr>/Uumsi';
$this->mode = 'MULTI';
$this->regexps = array( 'PageWikipedia' => '^<td align="left"><a href="\/wiki\/([^"]+)"',
'CodeInsee' => '^<td>.+<\/td>(?:\n|\r\n)<td>(\d+)<\/td>',
'CodePostal' => '^(?:<td>.+<\/td>(?:\n|\r\n)){2}<td>(\d+)<\/td>',
'Superficie' => '^(?:<td>.+<\/td>(?:\n|\r\n)){4}<td><span.+span>((?:[0-9]| |&#160;)+(?:,[0-9]+)?)<\/td>',
'Population' => '^(?:<td>.+<\/td>(?:\n|\r\n)){5}<td><span.+span>((?:[0-9]| |&#160;)+)<\/td>'
);
// Préparation des noms des pages
foreach ($this->pages as $id => $nom) {
$this->pages[$id] = str_replace(' ', '_', $nom);
}
$this->analyserUrls();
}
 
/**
* Robot analysant les pages du site de l'IPNI.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p ipni_auteur -a wp -pgf ~/importation/robots/eFloreBotIpni_auteur.txt -s ~/importation/robots/ipni_auteurs.tsv
* /opt/lampp/bin/php script.php robot -p ipni_auteur -a wp -pg Z -s ~/importation/robots/ipni_auteurs.tsv
* /opt/lampp/bin/php script.php robot -p ipni_auteur -a wp -pg Z
*
* @return unknown_type
*/
private function lancerRobotIpni() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotIpni';
$this->url_tpl = 'http://ipni.org/ipni/advAuthorSearch.do?output_format=delimited&find_surname=%s*';
$this->regexp_ligne = '/^(.*)$/umi';
$this->regexps = array( 'Id' => '^([^%]+)%' ,
'Version' => '^(?:[^%]*%){1,}([^%]*)%' ,
'DefaultAuthorName' => '^(?:[^%]*%){2,}([^%]*)%' ,
'DefaultAuthorForename' => '^(?:[^%]*%){3,}([^%]*)%' ,
'DefaultAuthorSurname' => '^(?:[^%]*%){4,}([^%]*)%' ,
'StandardForm' => '^(?:[^%]*%){5,}([^%]*)%' ,
'NameNotes' => '^(?:[^%]*%){6,}([^%]*)%' ,
'NameSource' => '^(?:[^%]*%){7,}([^%]*)%' ,
'Dates' => '^(?:[^%]*%){8,}([^%]*)%' ,
'DateTypeCode' => '^(?:[^%]*%){9,}([^%]*)%' ,
'DateTypeString' => '^(?:[^%]*%){10,}([^%]*)%' ,
'AlternativeAbbreviations' => '^(?:[^%]*%){11,}([^%]*)%' ,
'AlternativeNames' => '^(?:[^%]*%){12,}([^%]*)%' ,
'TaxonGroups' => '^(?:[^%]*%){13,}([^%]*)%' ,
'ExampleOfNamePublished' => '^(?:[^%]*%){14,}([^%]*)$' );
$this->analyserUrls();
}
 
/**
* Robot analysant les pages du site de Cassini.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pgf ~/importation/robots/eFloreBotCassini.txt -s ~/importation/robots/cassini.tsv
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pg 1 -s ~/importation/robots/cassini.tsv
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pg 1
*
* @return unknown_type
*/
private function lancerRobotCassini() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotCassini';
$this->url_tpl = 'http://cassini.ehess.fr/cassini/fr/html/fiche.php?select_resultat=%s';
$this->encodage = 'ISO-8859-1';
$this->regexp_ligne = '/\s*var\s+chaine1\s+\t=\s+"(.*?)";/umsi';
$this->regexps = array( 'NomCommune' => '^([^\\\\]+)\\\\n' ,
'Superficie' => '\\\\nsuperficie;([^\\\\]+)\\\\n',
'AltitudeMin' => '\\\\naltitude;([^;]+);',
'AltitudeMax' => '\\\\naltitude;[^;]+;([^\\\\]+)\\\\n',
'LambertIIEtenduX' => '\\\\ncoordonnées;Lambert II étendu\\\\n;x;([^\\\\]+)\\\\n',
'LambertIIEtenduY' => '\\\\ncoordonnées;Lambert II étendu\\\\n;x;[^\\\\]+\\\\n;y;([^\\\\]+)\\\\n',
'Latitude' => '\\\\n;Latitude;(.+)?\\\\ncode',
'Longitude' => '\\\\n;Longitude;(.+?)\\\\n;Latitude',
'CodeInsee' => '\\\\ncode insee;([^\\\\]+)\\\\nstatut',
'Statut' => '\\\\nstatut\(s\);([^\\\\]+)\\\\n\\\\n');
$this->analyserUrls();
}
 
/**
* Robot analysant les pages du site de Cassini.
* Exemples d'utilisation :
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pgf ~/importation/robots/eFloreBotCassini.txt -s ~/importation/robots/cassini.tsv
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pg 1 -s ~/importation/robots/cassini.tsv
* /opt/lampp/bin/php script.php robot -p cassini -a cassini -pg 1
*
* @return unknown_type
*/
private function lancerRobotUtmConverter() {
// Valeur spécifique de ce Robot
$this->robot_nom = 'eFloreBotUtmConverter';
$this->url_tpl = 'http://www.rcn.montana.edu/resources/tools/coordinates.aspx?nav=11&c=DD&md=83&mdt=NAD83/WGS84&lat=%s&lath=N&lon=%s&lonh=E';
$this->encodage = 'ISO-8859-1';
$this->regexp_ligne = '/Universal Transverse Mercator \(UTM\):<\/td>(.*?)<\/table><\/td>/umsi';
$this->regexps = array( 'UTM_Zone' => 'Zone: ([0-9]+)<' ,
'UTM_Est_x' => 'Easting: ([0-9]+)<',
'UTM_Nord_y' => 'Northing: ([0-9]+)<');
$this->analyserUrls();
}
 
private function analyserUrls() {
// Lancement de l'analyse
$heure_debut = date('c',time());
 
echo "Analyse de l'URL # : ";
$pagesNum = 0;// Pages
$lignesNum = 0;// Lignes
$sortie = '';
foreach ($this->pages as $paramsPage) {
$xhtml_page = $this->getHtml($this->url_tpl, $paramsPage);
$xhtml_lignes = $this->extraireChaine($this->regexp_ligne, $xhtml_page);
 
// Pour chaque chaine début/fin trouvées au sein de la page, nous recherchons les regexps des données.
if (count($xhtml_lignes) > 1 && $this->mode != 'MULTI') {
$this->traiterAttention("Plusieurs lignes correspondent à votre expression régulière de limitation du contenu :\n %s", array($this->regexp_ligne));
} else if ($xhtml_lignes) {
print_r($xhtml_lignes );
foreach ($xhtml_lignes as $xhtml) {
$champsNum = 1;// Champs
$ligne = '';
foreach ($this->regexps as $chp => $regexp) {
// Si nous traitons la première ligne nous ajoutons les noms des champs en début de fichier de sortie
if ($lignesNum == 0) {
$sortie .= $chp.(($champsNum == count($this->regexps)) ? "\n" : "\t");
$champsNum++;
}
// Ajout de la valeur trouvée grâce à l'expression régulière à la ligne de sortie
if (preg_match('/'.$regexp.'/Umsi', $xhtml, $match)) {
$ligne .= $this->nettoyer($match[1])."\t";
} else {
$ligne .= "\t";
}
}
$lignesNum++;
$ligne = trim($ligne);
$sortie .= $ligne."\n";
 
// Affichage en console...
if (empty($this->sortie)) {
echo "\t".$ligne."\n";
}
}
 
} else {
$this->traiterAttention("Impossible de trouver les chaines début et fin dans la page «%s» avec la regexp :\n%s", array($this->getNomPage($paramsPage), $this->regexp_ligne));
}
// Affichage en console...
echo str_repeat(chr(8), ( strlen( $pagesNum ) + 1 ))."\t".$pagesNum++;
}
echo "\n";
$heure_fin = date('c',time());
 
// Ajout de métadonnées
$metadonnees = "Début d'importation : $heure_debut\nFin d'importation : $heure_fin\n";
$metadonnees .= "Source des données : ".$this->url_tpl."\n";
$sortie = $metadonnees.$sortie;
 
// Écriture du fichier de sortie ou retour dans la console
if (!empty($this->sortie)) {
file_put_contents($this->sortie, $sortie);
}
}
 
private function nettoyer($txt) {
$txt = trim($txt);
$txt = preg_replace('/(?:&nbsp;|&#160;)/', ' ', $txt);
return $txt;
}
 
private function getHtml($url_tpl, $paramsPage) {
// Lancement en ligne de commande pour tester :
//curl -v --url "http://fr.wikipedia.org/wiki/Montpellier" --config /home/jpm/web/eflore_bp/consultation/scripts/modules/robot/configuration/cookieconf.txt
if ($this->cache && file_exists($fichier_cache = $this->cache.$this->getNomPage($paramsPage))) {
$html = file_get_contents($fichier_cache);
} else {
$url = vsprintf($url_tpl, $paramsPage);
$this->traiterAttention(" Url : ".$url);
// Initialisation CURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1');
 
$html = curl_exec($curl);
 
// Mise en cache
if ($this->cache) {
file_put_contents($fichier_cache, $html);
}
}
 
// Nettoyage des entités html
$html = $this->encoderUtf8($html, 'HTML-ENTITIES');
// Nettoyage de l'encodage des urls
$html = urldecode($html);
 
// Convertion en UTF-8 si nécessaire
if ($this->encodage) {
$html = $this->encoderUtf8($html, $this->encodage);
}
 
return $html;
}
 
/**
* Méthode récupérant seulement une partie du texte passé en paramétre.
*
* @param $debut chaine de caractère indiquant le début du texte à prendre en compte.
* @param $fin chaine de caractère indiquant la fin du texte à prendre en compte.
* @param $txt le texte duquel extraire une partie bornée par $debut et $fin.
* @return le texte extrait.
*/
private function extraireChaine($regexp, $txt) {
if (preg_match_all($regexp, $txt, $match)) {
return $match[1];
} else {
return false;
}
}
/**
* Charge les lignes d'un fichier dans un tableau et le retourne.
* Supprime les caractères blancs et les nouvelles lignes.
*
* @param $fichier
* @return unknown_type
*/
private function convertirFichierEnTableau($fichier) {
$tableau = array();
$handle = fopen($fichier,'r');
if ($handle) {
while ($ligne = fgets($handle)) {
$tableau[] = explode("\t", trim($ligne));
}
fclose($handle);
}
return $tableau;
}
 
private function getNomPage($paramsPage) {
return str_replace(' ', '_', implode('_', $paramsPage)).'.html';
}
 
}
?>
/tags/v5.7-arrayanal/scripts/modules/bdnt/bdnt.ini
New file
0,0 → 1,14
version="4_40"
dossierTsv = "{ref:dossierDonneesEflore}bdnt/2013-07-01/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
ontologies = "bdnt_ontologies_v{ref:version}"
 
[fichiers]
structureSql = "bdnt_ontologies_v2013-07-01.sql"
ontologies = "bdnt_ontologies_v2013-07-01.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
ontologies = "{ref:dossierTsv}{ref:fichiers.ontologies}"
/tags/v5.7-arrayanal/scripts/modules/bdnt/Bdnt.php
New file
0,0 → 1,54
<?php
/** Exemple lancement:
* /opt/lampp/bin/php -d memory_limit=3500M ~/web/eflore-projets/scripts/cli.php bdnt -a chargerTous
*/
class Bdnt extends EfloreScript {
 
public function executer() {
// Lancement de l'action demandée
try {
$this->initialiserProjet('bdnt');
 
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerOntologies();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerOntologies' :
$this->chargerOntologies();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerOntologies() {
$chemin = Config::get('chemins.ontologies');
$table = Config::get('tables.ontologies');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY '\t' ".
" ENCLOSED BY '' ".
" ESCAPED BY '\\\' ".
'IGNORE 0 LINES';
$this->getBdd()->requeter($requete);
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS bdnt_meta, bdnt_ontologies_v4_30";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules/bdnt
New file
Property changes:
Added: svn:ignore
+bdnt.ini
/tags/v5.7-arrayanal/scripts/modules/fournier/fournier.ini
New file
0,0 → 1,15
version="1_00"
dossierTsv = "{ref:dossierDonneesEflore}fournier/1.00/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
fournierMeta = "fournier_meta"
fournier = "fournier_v{ref:version}"
 
[fichiers]
structureSql = "{ref:tables.fournier}.sql"
fournier = "{ref:tables.fournier}.csv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
fournier = "{ref:dossierTsv}{ref:fichiers.fournier}"
/tags/v5.7-arrayanal/scripts/modules/fournier/Fournier.php
New file
0,0 → 1,138
<?php
//declare(encoding='UTF-8');
/**
* Exemple de lancement du script : :
* /opt/lampp/bin/php cli.php bdtfx -a chargerTous
*
* @category php 5.2
* @package eFlore/Scripts
* @author Jennifer DHÉ <jennifer@tela-botanica.org>
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @copyright Copyright (c) 2011, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id$
*/
class Fournier extends EfloreScript {
 
private $table = null;
private $tableMeta = null;
private $pasInsertion = 1000;
private $departInsertion = 0;
 
protected $parametres_autorises = array(
'-t' => array(false, false, 'Permet de tester le script sur un jeux réduit de données (indiquer le nombre de lignes).'));
 
public function executer() {
try {
$this->initialiserProjet('fournier');
$this->initialiserTables();
 
// Lancement de l'action demandée
$cmd = $this->getParametre('a');
switch ($cmd) {
case 'chargerTous' :
$this->chargerStructureSql();
$this->chargerFournier();
$this->genererNomSciHtml();
break;
case 'chargerStructureSql' :
$this->chargerStructureSql();
break;
case 'chargerFournier' :
$this->chargerFournier();
break;
case 'genererNomSciHtml' :
$this->genererNomSciHtml();
break;
case 'supprimerTous' :
$this->supprimerTous();
break;
default :
throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
}
} catch (Exception $e) {
$this->traiterErreur($e->getMessage());
}
}
 
private function chargerFournier() {
$chemin = Config::get('chemins.fournier');
$table = Config::get('tables.fournier');
$requete = "LOAD DATA INFILE '$chemin' ".
"REPLACE INTO TABLE $table ".
'CHARACTER SET utf8 '.
'FIELDS '.
" TERMINATED BY ',' ".
" ENCLOSED BY '\"' ".
" ESCAPED BY '\\\' ".
'IGNORE 1 LINES';
$this->getBdd()->requeter($requete);
}
 
private function genererNomSciHtml() {
$this->preparerTable();
$generateur = new GenerateurNomSciHtml();
$nbreTotal = $this->recupererNbTotalTuples();
while ($this->departInsertion < $nbreTotal) {
$resultat = $this->recupererTuples();
$nomsSciEnHtml = $generateur->generer($resultat);
$this->lancerRequeteModification($nomsSciEnHtml);
$this->departInsertion += $this->pasInsertion;
$this->afficherAvancement("Insertion des noms scientifique au format HTML dans la base par paquet de {$this->pasInsertion} en cours");
if ($this->stopperLaBoucle($this->getParametre('t'))) break;
}
echo "\n";
}
 
private function initialiserTables() {
$this->table = Config::get('tables.fournier');
$this->tableMeta = Config::get('tables.fournierMeta');
}
 
private function preparerTable() {
$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' ";
$resultat = $this->getBdd()->recuperer($requete);
if ($resultat === false) {
$requete = "ALTER TABLE {$this->table} ".
'ADD nom_sci_html VARCHAR( 500 ) '.
'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
$this->getBdd()->requeter($requete);
}
}
 
private function recupererNbTotalTuples(){
$requete = "SELECT count(*) AS nb FROM {$this->table} ";
$resultat = $this->getBdd()->recuperer($requete);
return $resultat['nb'];
}
 
private function recupererTuples() {
$requete = 'SELECT num_nom, rang, nom_supra_generique, genre, epithete_infra_generique, '.
' epithete_sp, type_epithete, epithete_infra_sp, cultivar_groupe, '.
' nom_commercial, cultivar '.
"FROM {$this->table} ".
"LIMIT {$this->departInsertion},{$this->pasInsertion} ";
$resultat = $this->getBdd()->recupererTous($requete);
return $resultat;
}
 
private function lancerRequeteModification($nomsSciHtm) {
foreach ($nomsSciHtm as $id => $html) {
$html = $this->getBdd()->proteger($html);
$requete = "UPDATE {$this->table} ".
"SET nom_sci_html = $html ".
"WHERE num_nom = $id ";
$resultat = $this->getBdd()->requeter($requete);
if ($resultat === false) {
throw new Exception("Erreur d'insertion pour le tuple $id");
}
}
}
 
private function supprimerTous() {
$requete = "DROP TABLE IF EXISTS {$this->tableMeta}, {$this->table}";
$this->getBdd()->requeter($requete);
}
}
?>
/tags/v5.7-arrayanal/scripts/modules
New file
Property changes:
Added: svn:ignore
+tempsexecution
/tags/v5.7-arrayanal/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.7-arrayanal/scripts/configurations
New file
Property changes:
Added: svn:ignore
+config.ini
/tags/v5.7-arrayanal/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.7-arrayanal/scripts/.
New file
Property changes:
Added: svn:ignore
+framework.php