Subversion Repositories eFlore/Applications.cel

Rev

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