Subversion Repositories eFlore/Applications.cel

Rev

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