Subversion Repositories eFlore/Applications.cel

Rev

Rev 1933 | Rev 2055 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1636 raphael 1
<?php
2
/**
1929 raphael 3
 * @category  PHP
4
 * @package   jrest
5
 * @author    Raphaël Droz <raphael@tela-botania.org>
6
 * @copyright 2013 Tela-Botanica
7
 * @license   http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
8
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
9
 */
1636 raphael 10
 
11
/**
12
 * Service d'import de données d'observation du CEL au format XLS
1649 raphael 13
 *
14
 * Sont define()'d commme n° de colonne tous les abbrevs retournés par
1656 raphael 15
 * FormateurGroupeColonne::nomEnsembleVersListeColonnes() préfixés par C_  cf: detectionEntete()
1649 raphael 16
 *
17
 * Exemple d'un test:
18
 * $ GET "/jrest/ExportXLS/22506?format=csv&range=*&limite=13" \
19
 *   | curl -F "upload=@-" -F utilisateur=22506 "/jrest/ImportXLS"
20
 * # 13 observations importées
21
 * + cf MySQL general_log = 1
22
 *
23
 **/
1636 raphael 24
 
25
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(dirname(realpath(__FILE__))) . '/lib');
26
// TERM
27
error_reporting(-1);
28
ini_set('html_errors', 0);
29
ini_set('xdebug.cli_color', 2);
30
require_once('lib/PHPExcel/Classes/PHPExcel.php');
1656 raphael 31
require_once('FormateurGroupeColonne.php');
1636 raphael 32
 
1640 raphael 33
 
34
date_default_timezone_set("Europe/Paris");
35
 
36
// nombre d'INSERT à cumuler par requête SQL
37
// (= nombre de lignes XLS à bufferiser)
1648 raphael 38
//define('NB_LIRE_LIGNE_SIMUL', 30);
39
define('NB_LIRE_LIGNE_SIMUL', 5);
1640 raphael 40
 
1933 raphael 41
// en cas d'import d'un fichier CSV, utilise fgetcsv() plutôt
42
// que PHPExcel ce qui se traduit par un gain de performances très substanciel
43
define('QUICK_CSV_IMPORT', TRUE);
44
 
1640 raphael 45
// Numbers of days between January 1, 1900 and 1970 (including 19 leap years)
46
// see traiterDateObs()
1675 raphael 47
// define("MIN_DATES_DIFF", 25569);
1640 raphael 48
 
49
 
1636 raphael 50
class MyReadFilter implements PHPExcel_Reader_IReadFilter {
1929 raphael 51
    // exclusion de colonnes
52
    public $exclues = array();
1640 raphael 53
 
1929 raphael 54
    // lecture par morceaux
1640 raphael 55
    public $ligne_debut = 0;
56
    public $ligne_fin = 0;
57
 
1929 raphael 58
    public function __construct() {}
59
    public function def_interval($debut, $nb) {
60
	$this->ligne_debut = $debut;
61
	$this->ligne_fin = $debut + $nb;
62
    }
1638 raphael 63
    public function readCell($colonne, $ligne, $worksheetName = '') {
1929 raphael 64
	if(@$this->exclues[$colonne]) return false;
65
	// si des n° de morceaux ont été initialisés, on filtre...
66
	if($this->ligne_debut && ($ligne < $this->ligne_debut || $ligne >= $this->ligne_fin)) return false;
67
	return true;
1636 raphael 68
    }
69
}
70
 
1675 raphael 71
// XXX: PHP 5.3
72
function __anonyme_1($v) {	return !$v['importable']; }
73
function __anonyme_2(&$v) {	$v = $v['nom']; }
74
function __anonyme_3($cell) { return !is_null($cell); };
75
function __anonyme_5($item) { return is_null($item) ? '?' : $item; }
76
function __anonyme_6() { return NULL; }
77
 
1636 raphael 78
class ImportXLS extends Cel  {
1929 raphael 79
    static function __anonyme_4(&$item, $key) { $item = self::quoteNonNull(trim($item)); }
1636 raphael 80
 
1929 raphael 81
    static $ordre_BDD = Array(
82
	"ce_utilisateur",
83
	"prenom_utilisateur",
84
	"nom_utilisateur",
85
	"courriel_utilisateur",
86
	"ordre",
87
	"nom_sel",
88
	"nom_sel_nn",
89
	"nom_ret",
90
	"nom_ret_nn",
91
	"nt",
92
	"famille",
93
	"nom_referentiel",
94
	"zone_geo",
95
	"ce_zone_geo",
96
	"date_observation",
97
	"lieudit",
98
	"station",
99
	"milieu",
100
	"mots_cles_texte",
101
	"commentaire",
102
	"transmission",
103
	"date_creation",
104
	"date_modification",
105
	"date_transmission",
106
	"latitude",
107
	"longitude",
108
	"altitude",
109
	"abondance",
110
	"certitude",
111
	"phenologie",
112
	"code_insee_calcule"
113
    );
1636 raphael 114
 
1929 raphael 115
    // cf: initialiser_pdo_ordered_statements()
116
    // eg: "INSERT INTO cel_obs (ce_utilisateur, ..., phenologie, code_insee_calcule) VALUES"
117
    // colonnes statiques d'abord, les autres ensuite, dans l'ordre de $ordre_BDD
118
    static $insert_prefix_ordre;
119
    // eg: "(<id>, <prenom>, <nom>, <email>, now(), now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
120
    // dont le nombre de placeholder dépend du nombre de colonnes non-statiques
121
    // colonnes statiques d'abord, les autres ensuite, dans l'ordre de $ordre_BDD
122
    static $insert_ligne_pattern_ordre;
1648 raphael 123
 
1929 raphael 124
    // seconde (meilleure) possibilité
125
    // cf: initialiser_pdo_statements()
126
    // eg: "INSERT INTO cel_obs (ce_utilisateur, ..., date_creation, ...phenologie, code_insee_calcule) VALUES"
127
    static $insert_prefix;
128
    // eg: "(<id>, <prenom>, <nom>, <email>, ?, ?, ?, now(), now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
129
    // dont le nombre de placeholder dépend du nombre de colonnes non-statiques
130
    static $insert_ligne_pattern;
1648 raphael 131
 
1929 raphael 132
    /*
133
      Ces colonnes:
134
      - sont propres à l'ensemble des enregistrements uploadés
135
      - sont indépendantes du numéro de lignes
136
      - n'ont pas de valeur par défaut dans la structure de la table
137
      - nécessitent une initialisation dans le cadre de l'upload
1649 raphael 138
 
1929 raphael 139
      initialiser_colonnes_statiques() y merge les données d'identification utilisateur
140
    */
141
    public $colonnes_statiques = Array(
142
	"ce_utilisateur" => NULL,
143
	"prenom_utilisateur" => NULL,
144
	"nom_utilisateur" => NULL,
145
	"courriel_utilisateur" => NULL,
1640 raphael 146
 
1929 raphael 147
	// fixes (fonction SQL)
148
	// XXX future: mais pourraient varier dans le futur si la mise-à-jour
149
	// d'observation est implémentée
150
	"date_creation" => "now()",
151
	"date_modification" => "now()",
152
    );
1640 raphael 153
 
1929 raphael 154
    public $id_utilisateur = NULL;
1649 raphael 155
 
1929 raphael 156
    // erreurs d'import
157
    public $bilan = Array();
1642 raphael 158
 
1929 raphael 159
    // cache (pour traiterLocalisation() pour l'instant)
160
    static $cache = Array('geo' => array());
1649 raphael 161
 
1929 raphael 162
    function ImportXLS($config) {
163
	parent::__construct($config);
164
    }
165
 
166
    function createElement($pairs) {
167
	if(!isset($pairs['utilisateur']) || trim($pairs['utilisateur']) == '') {
168
	    exit('0');
1636 raphael 169
	}
170
 
1929 raphael 171
	$id_utilisateur = intval($pairs['utilisateur']);
172
	$this->id_utilisateur = $id_utilisateur; // pour traiterImage();
1649 raphael 173
 
1929 raphael 174
	if(!isset($_SESSION)) session_start();
175
	$this->controleUtilisateur($id_utilisateur);
1640 raphael 176
 
1929 raphael 177
	$this->utilisateur = $this->getInfosComplementairesUtilisateur($id_utilisateur);
2034 aurelien 178
 
1636 raphael 179
 
2034 aurelien 180
 
1929 raphael 181
	$this->initialiser_colonnes_statiques($id_utilisateur);
1649 raphael 182
 
1929 raphael 183
	// initialisation du statement PDO/MySQL
184
	// première version, pattern de requête pas génial
185
	/* list(self;;$insert_prefix_ordre, self::$insert_ligne_pattern_ordre) =
186
	   $this->initialiser_pdo_ordered_statements($this->colonnes_statiques); */
187
	list(self::$insert_prefix, self::$insert_ligne_pattern) =
188
	    $this->initialiser_pdo_statements($this->colonnes_statiques);
1636 raphael 189
 
1929 raphael 190
	$infos_fichier = array_pop($_FILES);
1636 raphael 191
 
1929 raphael 192
	/*$objPHPExcel = PHPExcel_IOFactory::load($infos_fichier['tmp_name']);
193
	  $donnees = $objPHPExcel->getActiveSheet()->toArray(NULL,FALSE,FALSE,TRUE);*/
1636 raphael 194
 
1929 raphael 195
	/*$objReader = PHPExcel_IOFactory::createReader("Excel5");
196
	  $objReader->setReadDataOnly(true);
197
	  $objPHPExcel = $objReader->load($infos_fichier['tmp_name']);*/
1636 raphael 198
 
1929 raphael 199
	//var_dump($donnees);
1636 raphael 200
 
1929 raphael 201
	// renomme le fichier pour lui ajouter son extension initiale, ce qui
202
	// permet (une sorte) d'autodétection du format.
203
	$fichier = $infos_fichier['tmp_name'];
204
	$extension = pathinfo($infos_fichier['name'], PATHINFO_EXTENSION);
205
	if( (strlen($extension) == 3 || strlen($extension) == 4) &&
206
	    (@rename($fichier, $fichier . '.' . $extension))) { // XXX: @ safe-mode
207
	    $fichier = $fichier . '.' . $extension;
208
	}
1642 raphael 209
 
1929 raphael 210
	$objReader = PHPExcel_IOFactory::createReaderForFile($fichier);
211
	// TODO: check if compatible with toArray(<1>,<2>,TRUE,<4>)
212
	$objReader->setReadDataOnly(true);
1640 raphael 213
 
1929 raphael 214
	// TODO: is_a obsolete entre 5.0 et 5.3, retirer le @ à terme
1933 raphael 215
	$IS_CSV = @is_a($objReader, 'PHPExcel_Reader_CSV') && QUICK_CSV_IMPORT;
216
	// en cas d'usage de fgetcsv, testons que nous pouvons compter les lignes
217
	if($IS_CSV) $nb_lignes = intval(exec("wc -l $fichier"));
218
	// et, le cas échéant, fallback sur PHPExcel à nouveau. La raison de ce test ici est
219
	// l'instabilité du serveur (safe_mode, safe_mode_exec_dir, symlink vers binaires pour exec(), ... multiples points-of-failure)
220
	if($IS_CSV && !$nb_lignes) $IS_CSV = FALSE;
221
 
222
	if($IS_CSV) {
1929 raphael 223
	    $objReader->setDelimiter(',')
224
		->setEnclosure('"')
225
		->setLineEnding("\n")
226
		->setSheetIndex(0);
227
	}
1642 raphael 228
 
1929 raphael 229
	// on ne conserve que l'en-tête
230
	$filtre = new MyReadFilter();
231
	$filtre->def_interval(1, 2);
232
	$objReader->setReadFilter($filtre);
1640 raphael 233
 
1929 raphael 234
	$objPHPExcel = $objReader->load($fichier);
235
	$obj_infos = $objReader->listWorksheetInfo($fichier);
1636 raphael 236
 
1933 raphael 237
	if($IS_CSV) {
238
	    // $nb_lignes est déjà défini ci-dessus
239
	    $csvFileHandler = fopen($fichier, 'r');
240
	    // nous utilisons la valeur de retour dans un but informatif de l'utilisateur à la
241
	    // fin de l'import, *mais aussi* dans un array_diff_key() ci-dessous car bien que dans le
242
	    // fond le "parser" fgetcsv() n'ait pas d'intérêt à connaître les colonnes à ignorer,
243
	    // il se trouve que celles-ci peuvent interférer sur des fonctions comme traiterEspece()
244
	    // cf test "ref-nom-num.test.php" pour lequel l'élément C_NOM_SEL vaudrait 3 et $ligne serait array(3 => -42)
245
	    $filtre->exclues = self::detectionEntete(fgetcsv($csvFileHandler), TRUE);
246
	} else {
247
	    // XXX: indépendant du readFilter ?
248
	    $nb_lignes = $obj_infos[0]['totalRows'];
249
	    $donnees = $objPHPExcel->getActiveSheet()->toArray(NULL, FALSE, TRUE, TRUE);
250
	    $filtre->exclues = self::detectionEntete($donnees[1]);
251
	}
1636 raphael 252
 
1929 raphael 253
	$obs_ajouts = 0;
254
	$obs_maj = 0;
255
	$nb_images_ajoutees = 0;
256
	$nb_mots_cle_ajoutes = 0;
1677 raphael 257
 
1929 raphael 258
	$dernier_ordre = Cel::db()->requeter("SELECT MAX(ordre) AS ordre FROM cel_obs WHERE ce_utilisateur = $id_utilisateur");
259
	$dernier_ordre = intval($dernier_ordre[0]['ordre']) + 1;
260
	if(! $dernier_ordre) $dernier_ordre = 0;
1640 raphael 261
 
1929 raphael 262
	// on catch to les trigger_error(E_USER_NOTICE);
263
	set_error_handler(array($this, 'erreurs_stock'), E_USER_NOTICE);
1933 raphael 264
	$this->taxon_info_webservice = new RechercheInfosTaxonBeta($this->config, NULL);
1642 raphael 265
 
1933 raphael 266
 
1929 raphael 267
	// lecture par morceaux (chunks), NB_LIRE_LIGNE_SIMUL lignes à fois
268
	// pour aboutir des requêtes SQL d'insert groupés.
269
	for($ligne = 2; $ligne < $nb_lignes + NB_LIRE_LIGNE_SIMUL; $ligne += NB_LIRE_LIGNE_SIMUL) {
1933 raphael 270
	    if(!$IS_CSV) {
271
		$filtre->def_interval($ligne, NB_LIRE_LIGNE_SIMUL);
272
		$objReader->setReadFilter($filtre);
1640 raphael 273
 
1933 raphael 274
		/* recharge avec $filtre actif (filtre sur lignes colonnes):
275
		   - exclue les colonnes inutiles/inutilisables)
276
		   - ne selectionne que les lignes dans le range [$ligne - $ligne + NB_LIRE_LIGNE_SIMUL] */
277
		$objPHPExcel = $objReader->load($fichier)->getActiveSheet();
1640 raphael 278
 
1933 raphael 279
		// set col typing
280
		if(C_CE_ZONE_GEO != 'C_CE_ZONE_GEO')
281
		    $objPHPExcel->getStyle(C_CE_ZONE_GEO . '2:' . C_CE_ZONE_GEO . $objPHPExcel->getHighestRow())->getNumberFormat()->setFormatCode('00000');
1818 raphael 282
 
1933 raphael 283
		// TODO: set to string type
284
		if(C_ZONE_GEO != 'C_ZONE_GEO')
285
		    $objPHPExcel->getStyle(C_ZONE_GEO . '2:' . C_ZONE_GEO . $objPHPExcel->getHighestRow())->getNumberFormat()->setFormatCode('00000');
1818 raphael 286
 
1933 raphael 287
		$donnees = $objPHPExcel->toArray(NULL, FALSE, TRUE, TRUE);
288
	    }
289
	    else {
290
		$i = NB_LIRE_LIGNE_SIMUL;
291
		$donnees = array();
292
		while($i--) {
293
		    $tab = fgetcsv($csvFileHandler);
294
		    if(!$tab) continue;
295
		    $donnees[] = array_diff_key($tab, $filtre->exclues);
296
		}
1818 raphael 297
 
1933 raphael 298
	    }
299
 
300
	    // var_dump($donnees, get_defined_constants(true)['user']);die;
1929 raphael 301
	    // ici on appel la fonction qui fera effectivement l'insertion multiple
302
	    // à partir des (au plus) NB_LIRE_LIGNE_SIMUL lignes
1640 raphael 303
 
1929 raphael 304
	    // TODO: passer $this, ne sert que pour appeler des méthodes publiques qui pourraient être statiques
305
	    list($enregistrements, $images, $mots_cle) =
306
		self::chargerLignes($this, $donnees, $this->colonnes_statiques, $dernier_ordre);
307
	    if(! $enregistrements) break;
1642 raphael 308
 
1929 raphael 309
	    self::trierColonnes($enregistrements);
310
	    // normalement: NB_LIRE_LIGNE_SIMUL, sauf si une enregistrement ne semble pas valide
311
	    // ou bien lors du dernier chunk
1648 raphael 312
 
1929 raphael 313
	    $nb_rec = count($enregistrements);
314
	    $sql_pattern = self::$insert_prefix .
315
		str_repeat(self::$insert_ligne_pattern_ordre . ', ', $nb_rec - 1) .
316
		self::$insert_ligne_pattern_ordre;
1648 raphael 317
 
1929 raphael 318
	    $sql_pattern = self::$insert_prefix .
319
		str_repeat(self::$insert_ligne_pattern . ', ', $nb_rec - 1) .
320
		self::$insert_ligne_pattern;
1648 raphael 321
 
1929 raphael 322
	    Cel::db()->beginTransaction();
323
	    $stmt = Cel::db()->prepare($sql_pattern);
324
	    $donnees = array();
325
	    foreach($enregistrements as $e) $donnees = array_merge($donnees, array_values($e));
1648 raphael 326
 
2034 aurelien 327
	     // echo $sql_pattern . "\n"; var_dump($enregistrements, $donnees); die; // debug ici
1648 raphael 328
 
1929 raphael 329
	    $stmt->execute($donnees);
1648 raphael 330
 
1929 raphael 331
	    // $stmt->debugDumpParams(); // https://bugs.php.net/bug.php?id=52384
332
	    $dernier_autoinc = Cel::db()->lastInsertId();
333
	    Cel::db()->commit();
1648 raphael 334
 
1929 raphael 335
	    if(! $dernier_autoinc) trigger_error("l'insertion semble avoir échoué", E_USER_NOTICE);
1648 raphael 336
 
1929 raphael 337
	    $obs_ajouts += count($enregistrements);
338
	    // $obs_ajouts += count($enregistrements['insert']);
339
	    // $obs_maj += count($enregistrements['update']);
2034 aurelien 340
 
341
	    $ordre_ids = self::chargerCorrespondancesIdOrdre($this, $enregistrements);
342
 
343
	    $nb_images_ajoutees += self::stockerImages($enregistrements, $images, $ordre_ids);
1929 raphael 344
	    $nb_mots_cle_ajoutes += self::stockerMotsCle($enregistrements, $mots_cle, $dernier_autoinc);
345
	}
1642 raphael 346
 
1929 raphael 347
	restore_error_handler();
1642 raphael 348
 
1929 raphael 349
	if($this->bilan) echo implode("\n", $this->bilan) . "\n";
350
	printf('%1$d observation%2$s ajoutée%2$s' . "\n" .
351
	       '%3$d image%4$s attachée%4$s' . "\n" .
352
	       // '%5$d mot%6$c-clef ajouté%6$c [TODO]' . "\n" . // TODO
353
	       (count($filtre->exclues) > 0 ? 'colonne%7$s non-traitée%7$s: %8$s' . "\n" : ''),
1792 raphael 354
 
1929 raphael 355
	       $obs_ajouts,
356
	       $obs_ajouts > 1 ? 's' : '',
357
	       $nb_images_ajoutees,
358
	       $nb_images_ajoutees > 1 ? 's' : '',
359
	       $nb_mots_cle_ajoutes,
360
	       $nb_mots_cle_ajoutes > 1 ? 's' : '',
361
	       count($filtre->exclues) > 1 ? 's' : '',
362
	       implode(', ', $filtre->exclues));
363
	die();
364
    }
1636 raphael 365
 
1933 raphael 366
    /* detectionEntete() sert deux rôles:
367
       1) détecter le type de colonne attendu à partir des textes de la ligne d'en-tête afin de define()
368
       2) permet d'identifier les colonnes non-supportées/inutiles afin d'alléger le processus de parsing de PHPExcel
369
       grace au ReadFilter (C'est le rôle de la valeur de retour)
370
 
371
       La raison de la présence du paramètre $numeric_keys est que pour réussir à identifier les colonnes à exclure nous
372
       devons traiter un tableau représentant la ligne d'en-tête aussi bien:
373
       - sous forme associative pour PHPExcel (les clefs sont les lettres de l'alphabet)
374
       - sous forme de clefs numériques (fgetcsv())
375
       Le détecter après coup est difficile et pourtant cette distinction est importante car le comportement
376
       d'array_merge() (réordonnancement des clefs numérique) n'est pas souhaitable dans le second cas. */
377
    static function detectionEntete($entete, $numeric_keys = FALSE) {
1929 raphael 378
	$colonnes_reconnues = Array();
379
	$cols = FormateurGroupeColonne::nomEnsembleVersListeColonnes('standard,avance');
380
	foreach($entete as $k => $v) {
381
	    // traite les colonnes en faisant fi de la casse et des accents
382
	    $entete_simple = iconv('UTF-8', 'ASCII//TRANSLIT', strtolower(trim($v)));
383
	    foreach($cols as $col) {
384
		$entete_officiel_simple = iconv('UTF-8', 'ASCII//TRANSLIT', strtolower(trim($col['nom'])));
385
		$entete_officiel_abbrev = $col['abbrev'];
386
		if($entete_simple == $entete_officiel_simple || $entete_simple == $entete_officiel_abbrev) {
387
		    // debug echo "define C_" . strtoupper($entete_officiel_abbrev) . ", $k ($v)\n";
388
		    define("C_" . strtoupper($entete_officiel_abbrev), $k);
389
		    $colonnes_reconnues[$k] = 1;
390
		    break;
1636 raphael 391
		}
1929 raphael 392
	    }
393
	}
394
	// défini tous les index que nous utilisons à une valeur d'index de colonne Excel qui n'existe pas dans
395
	// le tableau renvoyé par PHPExcel
396
	// Attention cependant d'utiliser des indexes différenciés car traiterLonLat() et traiterEspece()
397
	// les utilisent
398
	foreach($cols as $col) {
399
	    if(!defined("C_" . strtoupper($col['abbrev'])))
400
		define("C_" . strtoupper($col['abbrev']), "C_" . strtoupper($col['abbrev']));
401
	}
1636 raphael 402
 
1929 raphael 403
	// prépare le filtre de PHPExcel qui évitera le traitement de toutes les colonnes superflues
1640 raphael 404
 
1929 raphael 405
	// eg: diff ( Array( H => Commune, I => rien ) , Array( H => 1, K => 1 )
406
	// ==> Array( I => rien )
407
	$colonnesID_non_reconnues = array_diff_key($entete, $colonnes_reconnues);
1636 raphael 408
 
1929 raphael 409
	// des colonnes de FormateurGroupeColonne::nomEnsembleVersListeColonnes()
410
	// ne retient que celles marquées "importables"
411
	$colonnes_automatiques = array_filter($cols, '__anonyme_1');
1640 raphael 412
 
1929 raphael 413
	// ne conserve que le nom long pour matcher avec la ligne XLS d'entête
414
	array_walk($colonnes_automatiques, '__anonyme_2');
1640 raphael 415
 
1929 raphael 416
	// intersect ( Array ( N => Milieu, S => Ordre ), Array ( ordre => Ordre, phenologie => Phénologie ) )
417
	// ==> Array ( S => Ordre, AA => Phénologie )
418
	$colonnesID_a_exclure = array_intersect($entete, $colonnes_automatiques);
1636 raphael 419
 
1933 raphael 420
	if($numeric_keys) {
421
	    return $colonnesID_non_reconnues + $colonnesID_a_exclure;
422
	}
1929 raphael 423
	// TODO: pourquoi ne pas comparer avec les abbrevs aussi ?
424
	// merge ( Array( I => rien ) , Array ( S => Ordre, AA => Phénologie ) )
425
	// ==> Array ( I => rien, AA => Phénologie )
426
	return array_merge($colonnesID_non_reconnues, $colonnesID_a_exclure);
427
    }
2034 aurelien 428
 
429
    static function chargerCorrespondancesIdOrdre($cel, $lignes) {
430
 
431
    	$ordre_ids = array();
432
 
433
    	$requete_obs_ids = "SELECT id_observation, ordre FROM cel_obs WHERE ordre IN (";
434
    	foreach($lignes as &$ligne) {
435
    		$requete_obs_ids .= $ligne['ordre'].',';
436
    	}
437
    	$requete_obs_ids = rtrim($requete_obs_ids, ',');
438
    	$requete_obs_ids .= ") AND ce_utilisateur = ".Cel::db()->proteger($cel->id_utilisateur);
439
 
440
 
441
    	$obs_ids = Cel::db()->requeter($requete_obs_ids);
442
    	foreach($obs_ids as &$obs) {
443
    		$ordre_ids[$obs['ordre']] = $obs['id_observation'];
444
    	}
445
    	return $ordre_ids;
446
    }
1636 raphael 447
 
1929 raphael 448
    /*
449
     * charge un groupe de lignes
450
     */
451
    static function chargerLignes($cel, $lignes, $colonnes_statiques, &$dernier_ordre) {
452
	$enregistrement = NULL;
453
	$enregistrements = Array();
454
	$toutes_images = Array();
455
	$tous_mots_cle = Array();
1640 raphael 456
 
1929 raphael 457
	foreach($lignes as $ligne) {
1933 raphael 458
	    // dans le cas de fgetcsv, on peut avoir des false additionnel (cf do/while l. 279)
459
	    if($ligne === false) continue;
460
 
1929 raphael 461
	    //$ligne = array_filter($ligne, function($cell) { return !is_null($cell); });
462
	    //if(!$ligne) continue;
463
	    // on a besoin des NULL pour éviter des notice d'index indéfini
464
	    if(! array_filter($ligne, '__anonyme_3')) continue;
1640 raphael 465
 
1929 raphael 466
	    if( ($enregistrement = self::chargerLigne($ligne, $dernier_ordre, $cel)) ) {
467
		// $enregistrements[] = array_merge($colonnes_statiques, $enregistrement);
468
		$enregistrements[] = $enregistrement;
469
		$pos = count($enregistrements) - 1;
470
		$last = &$enregistrements[$pos];
1640 raphael 471
 
1929 raphael 472
		if(isset($enregistrement['_images'])) {
473
		    // ne dépend pas de cel_obs, et seront insérées *après* les enregistrements
474
		    // mais nous ne voulons pas nous priver de faire des INSERT multiples pour autant
475
		    $toutes_images[] = Array("images" => $last['_images'],
476
					     "obs_pos" => $pos);
477
		    // ce champ n'a pas à faire partie de l'insertion dans cel_obs,
478
		    // mais est utile pour cel_obs_images
479
		    unset($last['_images']);
480
		}
1640 raphael 481
 
1929 raphael 482
		if(isset($enregistrement['_mots_cle'])) {
483
		    // ne dépend pas de cel_obs, et seront insérés *après* les enregistrements
484
		    // mais nous ne voulons pas nous priver de faire des INSERT multiples pour autant
485
		    $tous_mots_cle[] = Array("mots_cle" => $last['_mots_cle'],
486
					     "obs_pos" => $pos);
487
		    // la version inlinée des mots est enregistrées dans cel_obs
488
		    // mais cel_mots_cles_obs fait foi.
489
		    // XXX: postponer l'ajout de ces informations dans cel_obs *après* l'insertion effective
490
		    // des records dans cel_mots_cles_obs ?
491
		    unset($last['_mots_cle']);
1636 raphael 492
		}
1640 raphael 493
 
1929 raphael 494
		$dernier_ordre++;
495
	    }
1642 raphael 496
	}
1640 raphael 497
 
1929 raphael 498
	// XXX future: return Array($enregistrements_a_inserer, $enregistrements_a_MAJ, $toutes_images);
499
	return Array($enregistrements, $toutes_images, $tous_mots_cle);
500
    }
1642 raphael 501
 
502
 
1929 raphael 503
    static function trierColonnes(&$enregistrements) {
504
	foreach($enregistrements as &$enregistrement) {
505
	    $enregistrement = self::sortArrayByArray($enregistrement, self::$ordre_BDD);
506
	    //array_walk($enregistrement, function(&$item, $k) { $item = is_null($item) ? "NULL" : $item; });
507
	    //$req .= implode(', ', $enregistrement) . "\n";
1677 raphael 508
	}
1929 raphael 509
    }
1677 raphael 510
 
1642 raphael 511
 
1929 raphael 512
    static function stockerMotsCle($enregistrements, $tous_mots_cle, $lastid) {
513
	$c = 0;
514
	// debug: var_dump($tous_mots_cle);die;
515
	foreach($tous_mots_cle as $v) $c += count($v['mots_cle']['to_insert']);
516
	return $c;
517
    }
1642 raphael 518
 
2034 aurelien 519
    static function stockerImages($enregistrements, $toutes_images, $ordre_ids) {
1929 raphael 520
	$images_insert = 'INSERT INTO cel_obs_images (id_image, id_observation) VALUES %s ON DUPLICATE KEY UPDATE id_image = id_image';
521
	$images_obs_assoc = Array();
1650 raphael 522
 
1929 raphael 523
	foreach($toutes_images as $images_pour_obs) {
524
	    $obs = $enregistrements[$images_pour_obs["obs_pos"]];
2034 aurelien 525
	    $id_obs = $ordre_ids[$obs['ordre']]; // id réel de l'observation correspondant à l'ordre
1929 raphael 526
	    foreach($images_pour_obs['images'] as $image) {
527
		$images_obs_assoc[] = sprintf('(%d,%d)',
528
					      $image['id_image'], // intval() useless
529
					      $id_obs); // intval() useless
530
	    }
1636 raphael 531
	}
532
 
1929 raphael 533
	if($images_obs_assoc) {
534
	    $requete = sprintf($images_insert, implode(', ', $images_obs_assoc));
535
	    // debug echo "$requete\n";
536
	    Cel::db()->requeter($requete);
537
	}
1770 raphael 538
 
1929 raphael 539
	return count($images_obs_assoc);
540
    }
1636 raphael 541
 
1929 raphael 542
    /*
543
      Aucune des valeurs présentes dans $enregistrement n'est quotée
544
      cad aucune des valeurs retournée par traiter{Espece|Localisation}()
545
      car ce tableau est passé à un PDO::preparedStatement() qui applique
546
      proprement les règle d'échappement.
547
    */
548
    static function chargerLigne($ligne, $dernier_ordre, $cel) {
549
	// évite des notices d'index lors des trigger_error()
550
	$ref_ligne = !empty($ligne[C_NOM_SEL]) ? trim($ligne[C_NOM_SEL]) : '';
1636 raphael 551
 
1929 raphael 552
	// en premier car le résultat est utile pour
553
	// * traiter espèce (traiterEspece())
554
	// * traiter longitude et latitude (traiterLonLat())
555
	$referentiel = self::identReferentiel(trim(strtolower(@$ligne[C_NOM_REFERENTIEL])), $ligne, $ref_ligne);
1852 raphael 556
 
1929 raphael 557
	// $espece est rempli de plusieurs informations
558
	$espece = Array(C_NOM_SEL => NULL, C_NOM_SEL_NN => NULL, C_NOM_RET => NULL,
559
			C_NOM_RET_NN => NULL, C_NT => NULL, C_FAMILLE => NULL);
560
	self::traiterEspece($ligne, $espece, $referentiel, $cel->taxon_info_webservice);
1636 raphael 561
 
1929 raphael 562
	if(!$espece[C_NOM_SEL]) $referentiel = Cel::$fallback_referentiel;
563
	if($espece[C_NOM_SEL] && !$espece[C_NOM_SEL_NN]) $referentiel = Cel::$fallback_referentiel;
1649 raphael 564
 
1929 raphael 565
	// $localisation est rempli à partir de plusieurs champs: C_ZONE_GEO et C_CE_ZONE_GEO
566
	$localisation = Array(C_ZONE_GEO => NULL, C_CE_ZONE_GEO => NULL);
567
	self::traiterLocalisation($ligne, $localisation);
1649 raphael 568
 
1929 raphael 569
	// $transmission est utilisé pour date_transmission
570
	// XXX: @ contre "Undefined index"
571
	@$transmission = in_array(strtolower(trim($ligne[C_TRANSMISSION])), array(1, 'oui')) ? 1 : 0;
1640 raphael 572
 
573
 
1929 raphael 574
	// Dans ce tableau, seules devraient apparaître les données variable pour chaque ligne.
575
	// Dans ce tableau, l'ordre des clefs n'importe pas (cf: self::sortArrayByArray())
576
	$enregistrement = Array(
577
	    "ordre" => $dernier_ordre,
1640 raphael 578
 
1929 raphael 579
	    "nom_sel" => $espece[C_NOM_SEL],
580
	    "nom_sel_nn" => $espece[C_NOM_SEL_NN],
581
	    "nom_ret" => $espece[C_NOM_RET],
582
	    "nom_ret_nn" => $espece[C_NOM_RET_NN],
583
	    "nt" => $espece[C_NT],
584
	    "famille" => $espece[C_FAMILLE],
1640 raphael 585
 
1929 raphael 586
	    "nom_referentiel" => $referentiel,
1640 raphael 587
 
1929 raphael 588
	    "zone_geo" => $localisation[C_ZONE_GEO],
589
	    "ce_zone_geo" => $localisation[C_CE_ZONE_GEO],
1642 raphael 590
 
1929 raphael 591
	    // $ligne: uniquement pour les infos en cas de gestion d'erreurs (date incompréhensible)
592
	    "date_observation" => isset($ligne[C_DATE_OBSERVATION]) ? self::traiterDateObs($ligne[C_DATE_OBSERVATION], $ref_ligne) : NULL,
1642 raphael 593
 
1929 raphael 594
	    "lieudit" => isset($ligne[C_LIEUDIT]) ? trim($ligne[C_LIEUDIT]) : NULL,
595
	    "station" => isset($ligne[C_STATION]) ? trim($ligne[C_STATION]) : NULL,
596
	    "milieu" => isset($ligne[C_MILIEU]) ? trim($ligne[C_MILIEU]) : NULL,
1642 raphael 597
 
1929 raphael 598
	    "mots_cles_texte" => NULL, // TODO: foreign-key
599
	    // XXX: @ contre "Undefined index"
600
	    "commentaire" => isset($ligne[C_COMMENTAIRE]) ? trim($ligne[C_COMMENTAIRE]) : NULL,
1648 raphael 601
 
1929 raphael 602
	    "transmission" => $transmission,
603
	    "date_transmission" => $transmission ? date("Y-m-d H:i:s") : NULL, // pas de fonction SQL dans un PDO statement, <=> now()
1648 raphael 604
 
1929 raphael 605
	    // $ligne: uniquement pour les infos en cas de gestion d'erreurs (lon/lat incompréhensible)
606
	    "latitude" => isset($ligne[C_LATITUDE]) ? self::traiterLonLat(NULL, $ligne[C_LATITUDE], $referentiel, $ref_ligne) : NULL,
607
	    "longitude" => isset($ligne[C_LONGITUDE]) ? self::traiterLonLat($ligne[C_LONGITUDE], NULL, $referentiel, $ref_ligne) : NULL,
608
	    "altitude" => isset($ligne[C_ALTITUDE]) ? intval($ligne[C_ALTITUDE]) : NULL, // TODO: guess alt from lon/lat
1642 raphael 609
 
1929 raphael 610
	    // @ car potentiellement optionnelles ou toutes vides => pas d'index dans PHPExcel (tableau optimisé)
611
	    "abondance" => @$ligne[C_ABONDANCE],
612
	    "certitude" => @$ligne[C_CERTITUDE],
613
	    "phenologie" => @$ligne[C_PHENOLOGIE],
1642 raphael 614
 
1929 raphael 615
	    "code_insee_calcule" => substr($localisation[C_CE_ZONE_GEO], -5) // varchar(5)
616
	);
1677 raphael 617
 
1929 raphael 618
	// passage de $enregistrement par référence, ainsi ['_images'] n'est défini
619
	// que si des résultats sont trouvés
620
	// "@" car PHPExcel supprime les colonnes null sur toute la feuille (ou tout le chunk)
621
	if(@$ligne[C_IMAGES]) self::traiterImage($ligne[C_IMAGES], $cel->id_utilisateur, $enregistrement);
1636 raphael 622
 
1929 raphael 623
	if(@$ligne[C_MOTS_CLES_TEXTE]) self::traiterMotsCle($ligne[C_MOTS_CLES_TEXTE], $cel->id_utilisateur, $enregistrement);
1675 raphael 624
 
1929 raphael 625
	return $enregistrement;
626
    }
1640 raphael 627
 
1929 raphael 628
    static function traiterImage($str, $id_utilisateur, &$enregistrement) {
629
	$liste_images = array_filter(explode("/", $str));
1640 raphael 630
 
1929 raphael 631
	//array_walk($liste_images, '__anonyme_4');
632
	array_walk($liste_images, array(__CLASS__, '__anonyme_4'));
633
	$requete = sprintf(
634
	    "SELECT id_image, nom_original FROM cel_images WHERE ce_utilisateur = %d AND nom_original IN (%s)",
635
	    $id_utilisateur,
636
	    implode(',', $liste_images));
1642 raphael 637
 
1929 raphael 638
	$resultat = Cel::db()->requeter($requete);
1678 raphael 639
 
1929 raphael 640
	if($resultat) $enregistrement['_images'] = $resultat;
641
    }
1642 raphael 642
 
1929 raphael 643
    static function traiterMotsCle($str, $id_utilisateur, &$enregistrement) {
644
	$liste_mots_cle = $liste_mots_cle_recherche = array_map("trim", array_unique(array_filter(explode(",", $str))));
645
	array_walk($liste_mots_cle_recherche, array(__CLASS__, '__anonyme_4'));
1677 raphael 646
 
1929 raphael 647
	// TODO!!!! remplace > (pour les tests uniquement) par un = et supprimer le group by mot_cle
648
	$requete = sprintf("SELECT id_mot_cle_obs, mot_cle FROM cel_mots_cles_obs WHERE id_utilisateur > %d ".
649
			   "AND mot_cle IN (%s) ".
650
			   "GROUP BY mot_cle",
651
			   $id_utilisateur,
652
			   implode(',', $liste_mots_cle_recherche));
1677 raphael 653
 
1929 raphael 654
	$resultat_sql = Cel::db()->requeter($requete);
655
	if(!$resultat_sql) return;
1677 raphael 656
 
1929 raphael 657
	$resultat = array();
658
	foreach($resultat_sql as $v) $resultat[$v['id_mot_cle_obs']] = $v['mot_cle'];
1677 raphael 659
 
1929 raphael 660
	$enregistrement['mots_cles_texte'] = implode(',', $liste_mots_cle);
661
	$enregistrement['_mots_cle'] = array("existing" => $resultat,
662
					     "to_insert" => array_diff($liste_mots_cle, $resultat));
663
    }
1640 raphael 664
 
1770 raphael 665
 
1929 raphael 666
    /* FONCTIONS de TRANSFORMATION de VALEUR DE CELLULE */
1640 raphael 667
 
1929 raphael 668
    // TODO: PHP 5.3, utiliser date_parse_from_format()
669
    // TODO: parser les heures (cf product-owner)
670
    // TODO: passer par le timestamp pour s'assurer de la validité
671
    static function traiterDateObs($date, $ref_ligne) {
672
	// TODO: see https://github.com/PHPOffice/PHPExcel/issues/208
673
	// TODO: PHPExcel_Shared_Date::ExcelToPHP()
674
	if(is_double($date)) {
675
	    if($date > 0)
676
		return PHPExcel_Style_NumberFormat::toFormattedString($date, PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2) . " 00:00:00";
677
	    trigger_error("ligne \"{$ref_ligne}\": " .
678
			  "Attention: date antérieure à 1970 et format de cellule \"DATE\" utilisés ensemble",
679
			  E_USER_NOTICE);
1640 raphael 680
 
1929 raphael 681
	    // throw new Exception("erreur: date antérieure à 1970 et format de cellule \"DATE\" utilisés ensemble");
1640 raphael 682
 
1929 raphael 683
	    // attention, UNIX timestamp, car Excel les décompte depuis 1900
684
	    // cf http://fczaja.blogspot.fr/2011/06/convert-excel-date-into-timestamp.html
685
	    // $timestamp = ($date - MIN_DATES_DIFF) * 60 * 60 * 24 - time(); // NON
1636 raphael 686
 
1929 raphael 687
	    // $timestamp = PHPExcel_Calculation::getInstance()->calculateFormula("=" . $date . "-DATE(1970,1,1)*60*60*24"); // NON
1642 raphael 688
 
1929 raphael 689
	    // echo strftime("%Y/%m/%d 00:00:00", $timestamp); // NON
690
	}
691
	else {
692
	    // attend l'un des formats de
693
	    // http://www.php.net/manual/fr/datetime.formats.date.php
694
	    // le plus simple: YYYY/MM/DD (utilisé à l'export), mais DD-MM-YYYY est aussi supporté
695
	    $matches = NULL;
696
	    // et on essaie d'être sympa et supporter aussi DD/MM/YYYY
697
	    if(preg_match(';^([0-3]?\d)/([01]\d)/([12]\d\d\d)$;', $date, $matches)) {
698
		$date = $matches[3] . '/' . $matches[2] . '/' . $matches[1];
699
	    }
700
	    $timestamp = strtotime($date);
701
	    if(! $timestamp || $timestamp > time() + 3600 * 24 * 1) { // une journée d'avance maxi autorisée (décallage horaire ?)
702
		if($date) trigger_error("ligne \"{$ref_ligne}\": Attention: date erronée ($date)", E_USER_NOTICE);
1640 raphael 703
		return NULL;
1929 raphael 704
	    }
705
	    return strftime("%Y-%m-%d 00:00:00", $timestamp);
1636 raphael 706
	}
1929 raphael 707
    }
1636 raphael 708
 
1929 raphael 709
    static function identReferentiel($referentiel, $ligne, $ref_ligne) {
710
	// SELECT DISTINCT nom_referentiel, COUNT(id_observation) AS count FROM cel_obs GROUP BY nom_referentiel ORDER BY count DESC;
711
	if(strpos($referentiel, 'bdtfx') !== FALSE) return 'bdtfx'; //:v1.01';
712
	if(strpos($referentiel, 'bdtxa') !== FALSE) return 'bdtxa'; //:v1.00';
713
	//if(strpos($referentiel, 'bdnff') !== FALSE) return 'bdnff'; //:4.02';
714
	if(strpos($referentiel, 'bdnff') !== FALSE) return 'bdtfx';
715
	if(strpos($referentiel, 'isfan') !== FALSE) return 'isfan'; //:v1.00';
716
	if(strpos($referentiel, 'autre') !== FALSE) return 'autre';
1640 raphael 717
 
1929 raphael 718
	if($referentiel && isset($ligne[C_NOM_SEL]) && $ligne[C_NOM_SEL]) {
719
	    trigger_error("ligne \"{$ref_ligne}\": Attention: référentiel \"{$referentiel}\" inconnu", E_USER_NOTICE);
720
	    return 'autre';
721
	}
1642 raphael 722
 
1929 raphael 723
	// pas de référentiel ou pas de NOM_SEL: NULL
724
	return NULL;
725
	/* TODO: cf story,
726
	   En cas de NULL faire une seconde passe de détection à partir du nom saisi
727
	   + accepter les n° de version */
728
    }
1642 raphael 729
 
1929 raphael 730
    static function traiterLonLat($lon = NULL, $lat = NULL, $referentiel = 'bdtfx', $ref_ligne) {
731
	// en CSV ces valeurs sont des string, avec séparateur en français (","; cf défauts dans ExportXLS)
732
	if($lon && is_string($lon)) $lon = str_replace(',', '.', $lon);
733
	if($lat && is_string($lat)) $lat = str_replace(',', '.', $lat);
1640 raphael 734
 
1929 raphael 735
	// sprintf applique une précision à 5 décimale (comme le ferait MySQL)
736
	// tout en uniformisant le format de séparateur des décimales (le ".")
737
	if($lon && is_numeric($lon) && $lon >= -180 && $lon <= 180) return sprintf('%.5F', $lon);
738
	if($lat && is_numeric($lat) && $lat >= -90 && $lat <= 90) return sprintf('%.5F', $lat);
739
 
740
	if($lon || $lat) {
741
	    trigger_error("ligne \"{$ref_ligne}\": " .
742
			  "Attention: longitude ou latitude erronée",
743
			  E_USER_NOTICE);
1636 raphael 744
	}
1929 raphael 745
	return NULL;
1636 raphael 746
 
1929 raphael 747
	/* limite france métropole si bdtfx ? ou bdtxa ? ...
748
	   NON!
749
	   Un taxon d'un référentiel donné peut être théoriquement observé n'importe où sur le globe.
750
	   Il n'y a pas lieu d'effectuer des restriction ici.
751
	   Cependant des erreurs fréquentes (0,0 ou lon/lat inversées) peuvent être détectés ici.
752
	   TODO */
753
	$bbox = self::getReferentielBBox($referentiel);
754
	if(!$bbox) return NULL;
1642 raphael 755
 
1929 raphael 756
	if($lon) {
757
	    if($lon < $bbox['EST'] && $lon > $bbox['OUEST']) return is_numeric($lon) ? $lon : NULL;
758
	    else return NULL;
759
	}
760
	if($lat) {
761
	    if($lat < $bbox['NORD'] && $lat > $bbox['SUD']) return is_numeric($lat) ? $lat : NULL;
762
	    return NULL;
763
	}
764
    }
1651 raphael 765
 
1929 raphael 766
    /*
767
      TODO: s'affranchir du webservice pour la détermination du nom scientifique en s'appuyant sur cel_references,
768
      pour des questions de performances
769
    */
770
    static function traiterEspece($ligne, Array &$espece, &$referentiel, $taxon_info_webservice) {
771
	if(empty($ligne[C_NOM_SEL])) {
772
	    // TODO: nous ne déclarons pas "Numéro nomenclatural" comme colonne importable
773
	    // Nous ne pouvons donc pas tenter d'être sympa sur la détermination par num_nom
774
	    /* if(!empty($ligne[C_NOM_SEL_NN]) && $referentiel != Cel::$fallback_referentiel)
775
	       $ligne[C_NOM_SEL] = $referentiel . ':nn:' . $ligne[C_NOM_SEL_NN];
776
	       else */
777
	    return;
778
	}
1651 raphael 779
 
1929 raphael 780
	// nom_sel reste toujours celui de l'utilisateur
781
	$espece[C_NOM_SEL] = trim($ligne[C_NOM_SEL]);
1640 raphael 782
 
1929 raphael 783
	// XXX/attention, nous ne devrions pas accepter un référentiel absent !
784
	if(!$referentiel) $referentiel = 'bdtfx';
785
	$taxon_info_webservice->setReferentiel($referentiel);
786
	$ascii = iconv('UTF-8', 'ASCII//TRANSLIT', $ligne[C_NOM_SEL]);
1688 raphael 787
 
1929 raphael 788
	// TODO: si empty(C_NOM_SEL) et !empty(C_NOM_SEL_NN) : recherche info à partir de C_NOM_SEL_NN
789
	// echo "rechercherInformationsComplementairesSurNom()\n";
790
	/*
791
	  SELECT num_nom, nom_sci, num_nom_retenu ,auteur, annee, biblio_origine, nom_sci,auteur  FROM bdtfx_v1_01  WHERE (nom_sci LIKE 'Heliotropium europaeum')  ORDER BY nom_sci ASC	  LIMIT 0, 1
792
	  #
793
	  SELECT num_nom, nom_sci, num_nom_retenu ,auteur, annee, biblio_origine, nom_sci,auteur  FROM bdtfx_v1_01  WHERE (nom_sci LIKE 'eliotropium euro')  ORDER BY nom_sci ASC   LIMIT 0, 1
794
	  SELECT num_nom, nom_sci, num_nom_retenu ,auteur, annee, biblio_origine, nom_sci,auteur  FROM bdtfx_v1_01  WHERE (nom_sci LIKE 'eliotropium')	ORDER BY nom_sci ASC   LIMIT 0, 1
795
	  SELECT num_nom, nom_sci, num_nom_retenu ,auteur, annee, biblio_origine, nom_sci,auteur  FROM bdtfx_v1_01  WHERE (nom_sci LIKE 'eliotropium% euro%')  ORDER BY nom_sci ASC   LIMIT 0, 1
796
	  #
1640 raphael 797
 
1929 raphael 798
	  SELECT nom_sci, num_nom_retenu, nom_sci_html, auteur, annee, biblio_origine FROM bdtfx_v1_01 WHERE num_nom = 31468
799
	*/
800
	// $determ = $taxon_info_webservice->rechercherInformationsComplementairesSurNom($ligne[C_NOM_SEL]);
801
	// permet une reconnaissance de bdtfx:nn:XXXX
802
	$determ = $taxon_info_webservice->rechercherInfosSurTexteCodeOuNumTax(trim($ligne[C_NOM_SEL]));
1640 raphael 803
 
1929 raphael 804
	// note: rechercherInfosSurTexteCodeOuNumTax peut ne retourner qu'une seule clef "nom_sel"
805
	if (! $determ) {
806
	    // on supprime les noms retenus et renvoi tel quel
807
	    // on réutilise les define pour les noms d'indexes, tant qu'à faire
808
	    // XXX; tout à NULL sauf C_NOM_SEL ci-dessus ?
809
	    $espece[C_NOM_SEL_NN] = @$ligne[C_NOM_SEL_NN];
810
	    $espece[C_NOM_RET] = @$ligne[C_NOM_RET];
811
	    $espece[C_NOM_RET_NN] = @$ligne[C_NOM_RET_NN];
812
	    $espece[C_NT] = @$ligne[C_NT];
813
	    $espece[C_FAMILLE] = @$ligne[C_FAMILLE];
1781 raphael 814
 
1929 raphael 815
	    return;
816
	}
1781 raphael 817
 
1929 raphael 818
	// succès de la détection, mais résultat partiel
819
	if(!isset($determ->id))
820
	    $determ = $taxon_info_webservice->effectuerRequeteInfosComplementairesSurNumNom($determ->{"nom_retenu.id"});
1784 raphael 821
 
1929 raphael 822
	// ne devrait jamais arriver !
823
	if(!$determ) die("erreur critique: " . __FILE__ . ':' . __LINE__);
1784 raphael 824
 
1929 raphael 825
	// un schéma <ref>:(nt|nn):<num> (ie: bdtfx:nt:8503) a été passé
826
	// dans ce cas on met à jour le référentiel avec celui passé dans le champ espèce
827
	if(isset($determ->ref)) {
828
	    $referentiel = $determ->ref;
1640 raphael 829
	}
830
 
1929 raphael 831
	// succès de la détection
832
	// nom_sel est remplacé, mais seulement si un motif spécial à été utilisé (bdtfx:nn:4567)
833
	if($taxon_info_webservice->is_notation_spe) {
834
	    $espece[C_NOM_SEL] = $determ->nom_sci;
1688 raphael 835
	}
836
 
1929 raphael 837
	// écrasement des numéros (nomenclatural, taxonomique) saisis...
838
	$espece[C_NOM_SEL_NN] = $determ->id;
839
	$espece[C_NOM_RET] = RechercheInfosTaxonBeta::supprimerBiblio($determ->nom_retenu_complet);
840
	$espece[C_NOM_RET_NN] = $determ->{"nom_retenu.id"};
841
	$espece[C_NT] = $determ->num_taxonomique;
842
	$espece[C_FAMILLE] = $determ->famille;
843
	return;
844
	// et des info complémentaires
1697 raphael 845
 
1797 raphael 846
	/*
1929 raphael 847
	// GET /service:eflore:0.1/bdtfx/noms/31468?retour.champs=nom_sci,auteur,id,nom_retenu_complet,nom_retenu.id,num_taxonomique,famille
848
	/home/raphael/eflore/projets/services/modules/0.1/bdtfx/Noms.php:280
849
	SELECT  *, nom_sci   FROM bdtfx_v1_01	 WHERE num_nom = '31468'
850
	SELECT nom_sci, num_nom_retenu, nom_sci_html, auteur, annee, biblio_origine FROM bdtfx_v1_01 WHERE num_nom = 31468
851
	SELECT nom_sci, num_nom_retenu, nom_sci_html, auteur, annee, biblio_origine FROM bdtfx_v1_01 WHERE num_nom = 86535
1797 raphael 852
	*/
1770 raphael 853
 
1697 raphael 854
 
1929 raphael 855
	//var_dump($complement, $espece);die;
856
    }
1697 raphael 857
 
1929 raphael 858
    static function detectFromNom($nom) {
859
	$r = Cel::db()->requeter(sprintf("SELECT num_nom, num_tax_sup FROM bdtfx_v1_01 WHERE (nom_sci LIKE '%s') ".
860
					 "ORDER BY nom_sci ASC LIMIT 0, 1",
861
					 Cel::db()->proteger($nom)));
862
	if($r) return $r;
1697 raphael 863
 
1929 raphael 864
	Cel::db()->requeter(sprintf("SELECT num_nom, num_tax_sup FROM bdtfx_v1_01 WHERE (nom_sci LIKE '%s' OR nom LIKE '%s') ".
865
				    "ORDER BY nom_sci ASC LIMIT 0, 1",
866
				    Cel::db()->proteger($nom),
867
				    Cel::db()->proteger(str_replace(' ', '% ', $nom))));
868
	return $r;
869
    }
1697 raphael 870
 
871
 
1929 raphael 872
    /*
873
     * TODO: analyse rigoureuse:
874
     * == Identifiant Commune
875
     * - INSEE-C:\d{5}
876
     * - \d{5}
877
     * - \d{2}
878
     * == Commune
879
     * - \w+ (\d{2})
880
     * - \w+ (\d{5})
881
     * - \w+
882
     *
883
     */
884
    static function traiterLocalisation($ligne, Array &$localisation) {
885
	if(empty($ligne[C_ZONE_GEO])) $ligne[C_ZONE_GEO] = NULL;
886
	if(empty($ligne[C_CE_ZONE_GEO])) $ligne[C_CE_ZONE_GEO] = NULL;
1697 raphael 887
 
1929 raphael 888
	$identifiant_commune = trim($ligne[C_ZONE_GEO]);
889
	if(!$identifiant_commune) {
890
	    $departement = trim($ligne[C_CE_ZONE_GEO]);
891
 
892
	    if(strpos($departement, "INSEE-C:", 0) === 0) {
893
		$localisation[C_CE_ZONE_GEO] = trim($ligne[C_CE_ZONE_GEO]);
894
		if(array_key_exists($localisation[C_CE_ZONE_GEO], self::$cache['geo'])) {
895
		    $localisation[C_ZONE_GEO] = self::$cache['geo'][$localisation[C_CE_ZONE_GEO]];
1697 raphael 896
		}
897
		else {
1929 raphael 898
		    $nom = Cel::db()->requeter(sprintf("SELECT nom FROM cel_zones_geo WHERE code = %s LIMIT 1",
899
						       self::quoteNonNull(substr($localisation[C_CE_ZONE_GEO], strlen("INSEE-C:")))));
900
		    if($nom) $localisation[C_ZONE_GEO] = $nom[0]['nom'];
901
		    self::$cache['geo'][$localisation[C_CE_ZONE_GEO]] = @$nom[0]['nom'];
1697 raphael 902
		}
1929 raphael 903
		return;
904
	    }
1697 raphael 905
 
1929 raphael 906
	    if(!is_numeric($departement)) {
907
		$localisation[C_CE_ZONE_GEO] = $ligne[C_CE_ZONE_GEO];
908
		return;
909
	    }
910
 
911
	    $cache_attempted = FALSE;
912
	    if(array_key_exists($departement, self::$cache['geo'])) {
913
		$cache_attempted = TRUE;
914
		if(self::$cache['geo'][$departement][0] && self::$cache['geo'][$departement][1]) {
915
		    $localisation[C_ZONE_GEO] = self::$cache['geo'][$departement][0];
916
		    $localisation[C_CE_ZONE_GEO] = self::$cache['geo'][$departement][1];
917
		    return;
1697 raphael 918
		}
1929 raphael 919
	    }
1697 raphael 920
 
1929 raphael 921
	    if(! $cache_attempted && ($resultat_commune = Cel::db()->requeter(sprintf("SELECT DISTINCT nom, CONCAT('INSEE-C:', code) AS code FROM cel_zones_geo WHERE code = %s LIMIT 1",
922
										      self::quoteNonNull($departement)))) ) {
923
		$localisation[C_ZONE_GEO] = $resultat_commune[0]['nom'];
924
		$localisation[C_CE_ZONE_GEO] = $resultat_commune[0]['code'];
925
		self::$cache['geo'][$departement] = array($resultat_commune[0]['nom'], $resultat_commune[0]['code']);
926
		return;
927
	    }
928
	    ;
929
	    // if(strlen($departement) == 4) $departement = "INSEE-C:0" . $departement;
930
	    // if(strlen($departement) == 5) $departement = "INSEE-C:" . $departement;
931
	    // if(strlen($departement) <= 9) return "INSEE-C:0" . $departement; // ? ... TODO
1697 raphael 932
 
1929 raphael 933
	    $departement = trim($departement); // TODO
1697 raphael 934
 
1929 raphael 935
	    $localisation[C_CE_ZONE_GEO] = $ligne[C_CE_ZONE_GEO];
936
	    return;
937
	}
1697 raphael 938
 
939
 
1929 raphael 940
	$select = "SELECT DISTINCT nom, code FROM cel_zones_geo";
941
 
942
	if (preg_match('/(.+) \((\d{1,5})\)/', $identifiant_commune, $elements)) {
943
	    // commune + departement : montpellier (34)
944
	    $nom_commune=$elements[1];
945
	    $code_commune=$elements[2];
946
	    if(strlen($code_commune) <= 2) {
947
		$requete = sprintf("%s WHERE nom = %s AND code LIKE %s",
948
				   $select, self::quoteNonNull($nom_commune),
949
				   self::quoteNonNull($code_commune.'%'));
950
	    }
951
	    else {
952
		$requete = sprintf("%s WHERE nom = %s AND code = %d",
953
				   $select, self::quoteNonNull($nom_commune),
954
				   $code_commune);
955
	    }
956
	}
957
	elseif (preg_match('/^(\d+|(2[ab]\d+))$/i', $identifiant_commune, $elements)) {
958
	    // Code insee seul
959
	    $code_insee_commune=$elements[1];
960
	    $requete = sprintf("%s WHERE code = %s", $select, self::quoteNonNull($code_insee_commune));
961
	}
962
	else {
963
	    // Commune seule (le departement sera recupere dans la colonne departement si elle est presente)
964
	    // on prend le risque ici de retourner une mauvaise Commune
965
	    $nom_commune = str_replace(" ", "%", iconv('UTF-8', 'ASCII//TRANSLIT', $identifiant_commune));
966
	    $requete = sprintf("%s WHERE nom LIKE %s", $select, self::quoteNonNull($nom_commune.'%'));
967
	}
1697 raphael 968
 
969
 
1929 raphael 970
	if(array_key_exists($identifiant_commune, self::$cache['geo'])) {
971
	    $resultat_commune = self::$cache['geo'][$identifiant_commune];
1697 raphael 972
	}
1929 raphael 973
	else {
974
	    $resultat_commune = Cel::db()->requeter($requete);
975
	    self::$cache['geo'][$identifiant_commune] = $resultat_commune;
976
	}
977
	// TODO: levenstein sort ?
978
	// TODO: count résultat !
1697 raphael 979
 
1929 raphael 980
	// cas de la commune introuvable dans le référentiel
981
	// réinitialisation aux valeurs du fichier XLS
982
	if(! $resultat_commune) {
983
	    $localisation[C_ZONE_GEO] = trim($ligne[C_ZONE_GEO]);
984
	    $localisation[C_CE_ZONE_GEO] = trim($ligne[C_CE_ZONE_GEO]);
985
	} else {
986
	    $localisation[C_ZONE_GEO] = $resultat_commune[0]['nom'];
987
	    $localisation[C_CE_ZONE_GEO] = "INSEE-C:" . $resultat_commune[0]['code'];
988
	    return;
989
	}
1642 raphael 990
 
1929 raphael 991
	$departement = &$localisation[C_CE_ZONE_GEO];
1642 raphael 992
 
1929 raphael 993
	if(strpos($departement, "INSEE-C:", 0) === 0) {
994
	    $localisation[C_ZONE_GEO] = $localisation[C_ZONE_GEO];
995
	    $localisation[C_CE_ZONE_GEO] = $localisation[C_CE_ZONE_GEO];
996
	}
997
 
998
 
999
	if(!is_numeric($departement)) {
1000
	    $localisation[C_ZONE_GEO] = $localisation[C_ZONE_GEO];
1001
	    $localisation[C_CE_ZONE_GEO] = $localisation[C_CE_ZONE_GEO];
1002
	}
1003
 
1004
	if(strlen($departement) == 4) $departement = "INSEE-C:0" . $departement;
1005
	if(strlen($departement) == 5) $departement = "INSEE-C:" . $departement;
1006
	// if(strlen($departement) <= 9) return "INSEE-C:0" . $departement; // ? ... TODO
1007
 
1008
	$departement = trim($departement); // TODO
1009
 
1010
	$localisation[C_ZONE_GEO] = $localisation[C_ZONE_GEO];
1011
	$localisation[C_CE_ZONE_GEO] = $localisation[C_CE_ZONE_GEO];
1012
    }
1013
 
1014
    /*
1015
      static function traiterLocalisation($ligne, Array &$localisation) {
1016
      $identifiant_commune = trim($ligne[C_ZONE_GEO]);
1017
      if(!$identifiant_commune) {
1018
      $departement = trim($ligne[C_CE_ZONE_GEO]);
1019
      goto testdepartement;
1020
      }
1021
 
1022
 
1023
      $select = "SELECT DISTINCT nom, code  FROM cel_zones_geo";
1642 raphael 1024
 
1929 raphael 1025
      if (preg_match('/(.*) \((\d+)\)/', $identifiant_commune, $elements)) {
1026
      // commune + departement : montpellier (34)
1027
      $nom_commune=$elements[1];
1028
      $code_commune=$elements[2];
1029
      $requete = sprintf("%s WHERE nom = %s AND code LIKE %s",
1030
      $select, self::quoteNonNull($nom_commune), self::quoteNonNull($code_commune.'%'));
1031
      }
1032
      elseif (preg_match('/^(\d+|(2[ab]\d+))$/i', $identifiant_commune, $elements)) {
1033
      // Code insee seul
1034
      $code_insee_commune=$elements[1];
1035
      $requete = sprintf("%s WHERE code = %s", $select, self::quoteNonNull($code_insee_commune));
1036
      }
1037
      else {
1038
      // Commune seule (le departement sera recupere dans la colonne departement si elle est presente)
1039
      // on prend le risque ici de retourner une mauvaise Commune
1040
      $nom_commune = str_replace(" ", "%", iconv('UTF-8', 'ASCII//TRANSLIT', $identifiant_commune));
1041
      $requete = sprintf("%s WHERE nom LIKE %s", $select, self::quoteNonNull($nom_commune.'%'));
1042
      }
1642 raphael 1043
 
1929 raphael 1044
      $resultat_commune = Cel::db()->requeter($requete);
1045
      // TODO: levenstein sort ?
1642 raphael 1046
 
1929 raphael 1047
      // cas de la commune introuvable dans le référentiel
1048
      // réinitialisation aux valeurs du fichier XLS
1049
      if(! $resultat_commune) {
1050
      $localisation[C_ZONE_GEO] = trim($ligne[C_ZONE_GEO]);
1051
      $localisation[C_CE_ZONE_GEO] = trim($ligne[C_CE_ZONE_GEO]);
1052
      } else {
1053
      $localisation[C_ZONE_GEO] = $resultat_commune[0]['nom'];
1054
      $localisation[C_CE_ZONE_GEO] = $resultat_commune[0]['code'];
1055
      }
1642 raphael 1056
 
1929 raphael 1057
      $departement = &$localisation[C_CE_ZONE_GEO];
1642 raphael 1058
 
1929 raphael 1059
      testdepartement:
1060
      if(strpos($departement, "INSEE-C:", 0) === 0) goto protectloc;
1642 raphael 1061
 
1929 raphael 1062
      if(!is_numeric($departement)) goto protectloc; // TODO ?
1063
      if(strlen($departement) == 4) $departement = "INSEE-C:0" . $departement;
1064
      if(strlen($departement) == 5) $departement = "INSEE-C:" . $departement;
1065
      // if(strlen($departement) <= 9) return "INSEE-C:0" . $departement; // ? ... TODO
1642 raphael 1066
 
1929 raphael 1067
      $departement = trim($departement); // TODO
1642 raphael 1068
 
1929 raphael 1069
      protectloc:
1070
      $localisation[C_ZONE_GEO] = $localisation[C_ZONE_GEO];
1071
      $localisation[C_CE_ZONE_GEO] = $localisation[C_CE_ZONE_GEO];
1072
      }
1073
    */
1640 raphael 1074
 
1075
 
1929 raphael 1076
    /* HELPERS */
1640 raphael 1077
 
1929 raphael 1078
    // http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
1079
    // XXX; utilisé aussi (temporairement ?) par FormateurGroupeColonne.
1080
    static function sortArrayByArray($array, $orderArray) {
1081
	$ordered = array();
1082
	foreach($orderArray as $key) {
1083
	    if(array_key_exists($key, $array)) {
1084
		$ordered[$key] = $array[$key];
1085
		unset($array[$key]);
1086
	    }
1636 raphael 1087
	}
1929 raphael 1088
	return $ordered + $array;
1089
    }
1640 raphael 1090
 
1929 raphael 1091
    // retourne une BBox [N,S,E,O) pour un référentiel donné
1092
    static function getReferentielBBox($referentiel) {
1093
	if($referentiel == 'bdtfx') return Array(
1094
	    'NORD' => 51.2, // Dunkerque
1095
	    'SUD' => 41.3, // Bonifacio
1096
	    'EST' => 9.7, // Corse
1097
	    'OUEST' => -5.2); // Ouessan
1098
	return FALSE;
1099
    }
1640 raphael 1100
 
1929 raphael 1101
    // ces valeurs ne sont pas inséré via les placeholders du PDO::preparedStatement
1102
    // et doivent donc être échappées correctement.
1103
    public function initialiser_colonnes_statiques() {
1104
	$this->colonnes_statiques = array_merge($this->colonnes_statiques,
1105
						Array(
1106
						    "ce_utilisateur" => self::quoteNonNull($this->id_utilisateur), // peut-être un hash ou un id
1107
						    "prenom_utilisateur" => self::quoteNonNull($this->utilisateur['prenom']),
1108
						    "nom_utilisateur" => self::quoteNonNull($this->utilisateur['nom']),
1109
						    "courriel_utilisateur" => self::quoteNonNull($this->utilisateur['courriel']),
1110
						));
1640 raphael 1111
 
1929 raphael 1112
    }
1642 raphael 1113
 
1929 raphael 1114
    static function initialiser_pdo_ordered_statements($colonnes_statiques) {
1115
	return Array(
1116
	    // insert_ligne_pattern_ordre
1117
	    sprintf('INSERT INTO cel_obs (%s, %s) VALUES',
1118
		    implode(', ', array_keys($colonnes_statiques)),
1119
		    implode(', ', array_diff(self::$ordre_BDD, array_keys($colonnes_statiques)))),
1649 raphael 1120
 
1929 raphael 1121
	    // insert_ligne_pattern_ordre
1122
	    sprintf('(%s, %s ?)',
1123
		    implode(', ', $colonnes_statiques),
1124
		    str_repeat('?, ', count(self::$ordre_BDD) - count($colonnes_statiques) - 1))
1125
	);
1126
    }
1648 raphael 1127
 
1929 raphael 1128
    static function initialiser_pdo_statements($colonnes_statiques) {
1129
	return Array(
1130
	    // insert_prefix
1131
	    sprintf('INSERT INTO cel_obs (%s) VALUES ',
1132
		    implode(', ', self::$ordre_BDD)),
1649 raphael 1133
 
1650 raphael 1134
 
1929 raphael 1135
	    // insert_ligne_pattern, cf: self::$insert_ligne_pattern
1136
	    '(' .
1137
	    // 3) créé une chaîne de liste de champ à inséré en DB
1138
	    implode(', ', array_values(
1139
		// 2) garde les valeurs fixes (de $colonnes_statiques),
1140
		// mais remplace les NULL par des "?"
1141
		array_map('__anonyme_5',
1142
			  // 1) créé un tableau genre (nom_sel_nn => NULL) depuis self::$ordre_BDD
1143
			  // et écrase certaines valeurs avec $colonnes_statiques (initilisé avec les données utilisateur)
1144
			  array_merge(array_map('__anonyme_6', array_flip(self::$ordre_BDD)), $colonnes_statiques
1145
			  )))) .
1146
	    ')'
1147
	);
1148
    }
1649 raphael 1149
 
1929 raphael 1150
    // équivalent à Bdd2->proteger() (qui wrap PDO::quote),
1151
    // sans transformer NULL en ""
1152
    static function quoteNonNull($chaine) {
1153
	if(is_null($chaine)) return "NULL";
1154
	if(!is_string($chaine) && !is_integer($chaine)) {
1155
	    die("erreur: " . __FILE__ . ':' . __LINE__);
1642 raphael 1156
	}
1929 raphael 1157
	return Cel::db()->quote($chaine);
1158
    }
1642 raphael 1159
 
1929 raphael 1160
    public function erreurs_stock($errno, $errstr) {
1161
	$this->bilan[] = $errstr;
1162
    }
1636 raphael 1163
}