Subversion Repositories eFlore/Projets.eflore-projets

Compare Revisions

No changes between revisions

Ignore whitespace Rev 1010 → Rev 1027

/tags/v5.5-arbousiere/CHANGELOG
New file
0,0 → 1,79
Changements <next>:
 
Changements 2014-03-04 [création de la branche "v5.5-arbousiere"]:
* Ajout du web service renvoyant des liens vers les cartes de flore probable isssue de sophy
* nouvelle version de la bdtfx
* debug graphique baseflor valeur vide ne s'affiche plus comme 0
* correction requete vue tapir
* Script d'intégration du référentiel bdtao
* Ajout des scripts eFlore pour bdtao ; utilisation de 'num_basionyme' à la place de 'basionyme'.
 
Changements 2014-02-11 [création de la branche "v5.4-Arboretum"]:
* nouvelle version baseflor
* Les services Noms des trois référentiels (bdtfx, bdtxa, isfan) retournent maintenant en plus du libellé du rang, le code du rang dans "rang.code" lorsqu'on leur demande "champs.retour=rang"
* script de création données ifn et vue tapir
* script transformant les données des tables de tb_moissonnage à une table _tapir et une table meta dans tb_eflore
* ajout du moissonage de l'ifn
* interrogation ifn et baznat par num_nom et plus par nom_sci
 
Changements 2014-01-06 [création de la branche "v5.3-Amandaie"]:
* service presencemuseum
* Protection du graphique Baseflor contre les données NULL
* ajout de version chorodep
* Coste/textes : REDIRECT_QUERY_STRING => QUERY_STRING
* array_unique() sur les courriels de la carte de répartition
 
Changements 20130912 [création de la branche "Acheb"]:
* API change: coste
* référentiels: bdtfx 2.00, ontologies 4.40
* config:
- directives inutiles supprimées pour Coste [r857]
- bdnt: ontologie: 4_40
* coste: réécriture du webservice
 
Changements [[http://svn.tela-botanica.net/websvn/filedetails.php?repname=eFlore%2FProjets.eflore-projets&path=%2Ftrunk%2FChangelog&peg=839 v5.0-agropyraie-20130829]] :
- tenue du Changelog
- config: directives modifiées:
- cache.miseEnCache
- cache.dureeDeVie
- cache.stockageChemin
- ontologies:
- support critères multiples bdnt
- support critères multiples nvjfl
- support critères multiples baseflor
- cache d'appels pour bdtfx/meta-donnees
- SQL hard-codé en place du HTTP dans certains cas
- tests: nombreux ajouts et quelques changements de prototypes
- scripts:
- upgrades pour Cel
- Makefile pour configuration/
- renommage de noms de classes en conflit: Cartes et Ontologies
- améliorations dans l'usage du cache
 
Changements v0.1-20130830-1:
* nvjfl: fix notices
* cache: correction du cache des synonymes (noms à 255 caractères)
* cel/images: déduplication de auteurs au préalable de la requête d'identités
* Note: erreur de tag sur "v0.1-20130830"
 
Changements v0.1-20130829:
* tenue du Changelog
* config: directives modifiées:
- cache.miseEnCache
- cache.dureeDeVie
- cache.stockageChemin
* ontologies:
* support critères multiples bdnt
* support critères multiples nvjfl
* support critères multiples baseflor
* support critères multiples eflore
* cache d'appels pour bdtfx/meta-donnees
* SQL hard-codé en place du HTTP dans certains cas
* tests: nombreux ajouts et quelques changements de prototypes
* scripts:
* upgrades pour Cel
* Makefile pour configuration/
* renommage de noms de classes en conflit: Cartes et Ontologies
* améliorations dans l'usage du cache
 
v0.1-20130600
/tags/v5.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/scripts/tests/tmp
New file
Property changes:
Added: svn:ignore
+test.defaut.ini
+test.ini
/tags/v5.5-arbousiere/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.5-arbousiere/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.5-arbousiere/scripts/modules/baseveg/baseveg.ini
New file
0,0 → 1,26
version="2013_09_23"
dossierTsv = "{ref:dossierDonneesEflore}baseveg/2013-09-23/"
dossierSql = "{ref:dossierTsv}"
 
[tables]
donnees = "baseveg_v{ref:version}"
metadonnees = "baseveg_meta"
ontologies = "baseveg_ontologies"
 
[fichiers]
structureSql = "baseveg_v{ref:version}.sql"
metadonnees = "baseveg_insertion_meta_v{ref:version}.sql"
donnees = "baseveg_v{ref:version}.tsv"
ontologies = "baseveg_ontologies.tsv"
 
[chemins]
structureSql = "{ref:dossierSql}{ref:fichiers.structureSql}"
donnees = "{ref:dossierTsv}{ref:fichiers.donnees}"
metadonnees = "{ref:dossierSql}{ref:fichiers.metadonnees}"
ontologies ="{ref:dossierTsv}{ref:fichiers.ontologies}"
 
[Parametres]
niveaux = "'CLA';'ALL';'ORD';'ASS';'GRPT';'SUBORD';'SUBASS';'BC';'SUBCLA';'DC';'SUBALL'"
synonymes = "'incl';'=';'= ?';'illeg';'pp';'pmaxp';'pminp';'compl';'ambig';'non';'inval';'nn';'ined'"
motifs = "/^[0-9]+$/=1;
/(?:[0-9]{2}\/$|[0-9]{2}\/[0-9]\.$|[0-9]{2}\/(?:[0-9]\.){1,5}[0-9]$|[0-9]{2}\/(?:[0-9]\.){4,5}[0-9]\/[0-9]+(?:bis|ter){0,1}$)|incertae sedis/=2"
/tags/v5.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/scripts/modules/iso_3166_1
New file
Property changes:
Added: svn:ignore
+iso-3166-1.ini
/tags/v5.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/scripts/modules/baseflor/log
New file
Property changes:
Added: svn:ignore
+test
/tags/v5.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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.5-arbousiere/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 fic