Subversion Repositories eFlore/Applications.cel

Rev

Rev 1648 | Rev 1650 | 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
15
 * ExportXLS::nomEnsembleVersListeColonnes() préfixés par C_  cf: detectionEntete()
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');
31
require_once('ExportXLS.php');
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()
43
define("MIN_DATES_DIFF", 25569);
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
 
67
class ImportXLS extends Cel  {
68
 
69
	static $ordre_BDD = Array(
70
		"ce_utilisateur",
71
		"prenom_utilisateur",
72
		"nom_utilisateur",
73
		"courriel_utilisateur",
74
		"ordre",
75
		"nom_sel",
76
		"nom_sel_nn",
77
		"nom_ret",
78
		"nom_ret_nn",
79
		"nt",
80
		"famille",
81
		"nom_referentiel",
82
		"zone_geo",
83
		"ce_zone_geo",
84
		"date_observation",
85
		"lieudit",
86
		"station",
87
		"milieu",
1649 raphael 88
		"mots_cles_texte",
1636 raphael 89
		"commentaire",
90
		"transmission",
91
		"date_creation",
92
		"date_modification",
1649 raphael 93
		"date_transmission",
1636 raphael 94
		"latitude",
1648 raphael 95
		"longitude",
1649 raphael 96
		"abondance",
97
		"certitude",
1648 raphael 98
		"phenologie",
99
		"code_insee_calcule"
100
	);
1636 raphael 101
 
1649 raphael 102
	// cf: initialiser_pdo_ordered_statements()
1648 raphael 103
	// eg: "INSERT INTO cel_obs (ce_utilisateur, ..., phenologie, code_insee_calcule) VALUES"
104
	// colonnes statiques d'abord, les autres ensuite, dans l'ordre de $ordre_BDD
105
	static $insert_prefix_ordre;
106
	// eg: "(<id>, <prenom>, <nom>, <email>, now(), now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
107
	// dont le nombre de placeholder dépend du nombre de colonnes non-statiques
108
	// colonnes statiques d'abord, les autres ensuite, dans l'ordre de $ordre_BDD
109
	static $insert_ligne_pattern_ordre;
110
 
1649 raphael 111
	// seconde (meilleure) possibilité
112
	// cf: initialiser_pdo_statements()
113
	// eg: "INSERT INTO cel_obs (ce_utilisateur, ..., date_creation, ...phenologie, code_insee_calcule) VALUES"
114
	static $insert_prefix;
1648 raphael 115
	// eg: "(<id>, <prenom>, <nom>, <email>, ?, ?, ?, now(), now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
116
	// dont le nombre de placeholder dépend du nombre de colonnes non-statiques
117
	static $insert_ligne_pattern;
118
 
1640 raphael 119
	/*
120
	  Ces colonnes:
1642 raphael 121
	  - sont propres à l'ensemble des enregistrements uploadés
1640 raphael 122
	  - sont indépendantes du numéro de lignes
123
	  - n'ont pas de valeur par défaut dans la structure de la table
124
	  - nécessitent une initialisation dans le cadre de l'upload
1649 raphael 125
 
126
	  initialiser_colonnes_statiques() y merge les données d'identification utilisateur
1640 raphael 127
	*/
128
	public $colonnes_statiques = Array(
129
		"ce_utilisateur" => NULL,
130
		"prenom_utilisateur" => NULL,
131
		"nom_utilisateur" => NULL,
132
		"courriel_utilisateur" => NULL,
133
 
1642 raphael 134
		// fixes (fonction SQL)
135
		// XXX future: mais pourraient varier dans le futur si la mise-à-jour
1640 raphael 136
		// d'observation est implémentée
1642 raphael 137
		"date_creation" => "now()",
138
		"date_modification" => "now()",
1640 raphael 139
	);
140
 
1642 raphael 141
	public $id_utilisateur = NULL;
1649 raphael 142
 
1642 raphael 143
	// erreurs d'import
144
	public $bilan = Array();
145
 
1649 raphael 146
 
1636 raphael 147
	function ExportXLS($config) {
148
		parent::__construct($config);
149
	}
150
 
151
	function createElement($pairs) {
152
		if(!isset($pairs['utilisateur']) || trim($pairs['utilisateur']) == '') {
153
			echo '0'; exit;
154
		}
1649 raphael 155
 
1640 raphael 156
		$id_utilisateur = intval($pairs['utilisateur']);
1642 raphael 157
		$this->id_utilisateur = $id_utilisateur; // pour traiterImage();
1640 raphael 158
 
1636 raphael 159
		if(!isset($_SESSION)) session_start();
1640 raphael 160
        $this->controleUtilisateur($id_utilisateur);
1636 raphael 161
 
1640 raphael 162
        $this->utilisateur = $this->getInfosComplementairesUtilisateur($id_utilisateur);
1649 raphael 163
 
1640 raphael 164
		$this->initialiser_colonnes_statiques($id_utilisateur);
1636 raphael 165
 
1648 raphael 166
		// initialisation du statement PDO/MySQL
1649 raphael 167
		// première version, pattern de requête pas génial
168
		/* list(self;;$insert_prefix_ordre, self::$insert_ligne_pattern_ordre) =
169
		   $this->initialiser_pdo_ordered_statements($this->colonnes_statiques); */
170
		list(self::$insert_prefix, self::$insert_ligne_pattern) =
171
			$this->initialiser_pdo_statements($this->colonnes_statiques);
1640 raphael 172
 
1648 raphael 173
 
1636 raphael 174
		$infos_fichier = array_pop($_FILES);
175
 
176
		/*$objPHPExcel = PHPExcel_IOFactory::load($infos_fichier['tmp_name']);
1638 raphael 177
		  $donnees = $objPHPExcel->getActiveSheet()->toArray(NULL,FALSE,FALSE,TRUE);*/
1636 raphael 178
 
179
		/*$objReader = PHPExcel_IOFactory::createReader("Excel5");
180
		$objReader->setReadDataOnly(true);
181
		$objPHPExcel = $objReader->load($infos_fichier['tmp_name']);*/
182
 
1638 raphael 183
		//var_dump($donnees);
1636 raphael 184
 
1642 raphael 185
		// renomme le fichier pour lui ajouter son extension initiale, ce qui
186
		// permet (une sorte) d'autodétection du format.
187
		$fichier = $infos_fichier['tmp_name'];
188
		$extension = pathinfo($infos_fichier['name'], PATHINFO_EXTENSION);
189
		if( (strlen($extension) == 3 || strlen($extension) == 4) &&
190
			(rename($fichier, $fichier . '.' . $extension))) {
191
			$fichier = $fichier . '.' . $extension;
192
		}
193
 
194
		$objReader = PHPExcel_IOFactory::createReaderForFile($fichier);
1636 raphael 195
		$objReader->setReadDataOnly(true);
1640 raphael 196
 
1642 raphael 197
		if(is_a($objReader, 'PHPExcel_Reader_CSV')) {
198
			$objReader->setDelimiter(',')
199
				->setEnclosure('"')
200
				->setLineEnding("\n")
201
				->setSheetIndex(0);
202
		}
203
 
1640 raphael 204
		// on ne conserve que l'en-tête
205
		$filtre = new MyReadFilter();
206
		$filtre->def_interval(1, 2);
207
		$objReader->setReadFilter($filtre);
208
 
1642 raphael 209
		$objPHPExcel = $objReader->load($fichier);
210
		$obj_infos = $objReader->listWorksheetInfo($fichier);
1640 raphael 211
		// XXX: indépendant du readFilter ?
212
		$nb_lignes = $obj_infos[0]['totalRows'];
1636 raphael 213
 
1640 raphael 214
		$donnees = $objPHPExcel->getActiveSheet()->toArray(NULL, FALSE, FALSE, TRUE);
215
		$filtre->exclues = self::detectionEntete($donnees[1]);
1636 raphael 216
 
1640 raphael 217
		$obs_ajouts = 0;
218
		$obs_maj = 0;
219
		$dernier_ordre = $this->requeter("SELECT MAX(ordre) AS ordre FROM cel_obs WHERE ce_utilisateur = $id_utilisateur");
220
		$dernier_ordre = intval($dernier_ordre[0]['ordre']) + 1;
221
		if(! $dernier_ordre) $dernier_ordre = 0;
222
 
1642 raphael 223
		// on catch to les trigger_error(E_USER_NOTICE);
224
		set_error_handler(array($this, 'erreurs_stock'), E_USER_NOTICE);
225
 
1640 raphael 226
		// lecture par morceaux (chunks), NB_LIRE_LIGNE_SIMUL lignes à fois
227
		// pour aboutir des requêtes SQL d'insert groupés.
228
		for($ligne = 2; $ligne < $nb_lignes + NB_LIRE_LIGNE_SIMUL; $ligne += NB_LIRE_LIGNE_SIMUL) {
229
			$filtre->def_interval($ligne, NB_LIRE_LIGNE_SIMUL);
230
			$objReader->setReadFilter($filtre);
231
 
232
			/* recharge avec $filtre actif (filtre sur lignes colonnes):
233
			   - exclue les colonnes inutiles/inutilisables)
234
			   - ne selectionne que les lignes dans le range [$ligne - $ligne + NB_LIRE_LIGNE_SIMUL] */
1642 raphael 235
			$objPHPExcel = $objReader->load($fichier);
1640 raphael 236
			$donnees = $objPHPExcel->getActiveSheet()->toArray(NULL, FALSE, FALSE, TRUE);
237
 
238
			// ici on appel la fonction qui fera effectivement l'insertion multiple
239
			// à partir des (au plus) NB_LIRE_LIGNE_SIMUL lignes
240
 
241
			// TODO: passer $this, ne sert que pour appeler des méthodes public qui pourraient être statiques
242
			// notamment dans RechercheInfosTaxonBeta.php
1642 raphael 243
			list($enregistrements, $images) =
244
				self::chargerLignes($this, $donnees, $this->colonnes_statiques, $dernier_ordre);
245
			if(! $enregistrements) break;
246
 
1648 raphael 247
			echo "===chunk\n";
248
			self::trierColonnes($enregistrements);
249
			// normalement: NB_LIRE_LIGNE_SIMUL, sauf si une enregistrement ne semble pas valide
250
			// ou bien lors du dernier chunk
251
 
252
			$nb_rec = count($enregistrements);
253
			$sql_pattern = self::$insert_prefix .
254
				str_repeat(self::$insert_ligne_pattern_ordre . ', ', $nb_rec - 1) .
255
				self::$insert_ligne_pattern_ordre;
256
 
257
			$sql_pattern = self::$insert_prefix .
258
				str_repeat(self::$insert_ligne_pattern . ', ', $nb_rec - 1) .
259
				self::$insert_ligne_pattern;
260
 
261
			$this->bdd->beginTransaction();
262
			$stmt = $this->bdd->prepare($sql_pattern);
263
			$donnees = array();
264
			foreach($enregistrements as $e) $donnees = array_merge($donnees, array_values($e));
265
 
1649 raphael 266
			/* debug ici: echo $sql_pattern . "\n"; var_dump($enregistrements, $donnees); die;*/
1648 raphael 267
 
268
			$stmt->execute($donnees);
269
 
270
			// $stmt->debugDumpParams(); // https://bugs.php.net/bug.php?id=52384
271
			//$this->bdd->commit();
272
			$dernier_autoinc = $this->bdd->lastInsertId();
273
			var_dump($dernier_autoinc);
274
			die;
275
 
276
 
277
 
1642 raphael 278
			$obs_ajouts += count($enregistrements);
1648 raphael 279
			// $obs_ajouts += count($enregistrements['insert']);
280
			// $obs_maj += count($enregistrements['update']);
1642 raphael 281
			self::stockerImages($this, $enregistrements, $images, $dernier_autoinc);
1640 raphael 282
		}
1642 raphael 283
 
284
		restore_error_handler();
285
 
286
		if($this->bilan) echo implode("\n", $this->bilan) . "\n";
287
		// fin: renvoi summary
288
		die("$obs_ajouts observations ajoutées");
1636 raphael 289
	}
290
 
291
	static function detectionEntete($entete) {
292
		$colonnes_reconnues = Array();
1646 raphael 293
		$cols = ExportXLS::nomEnsembleVersListeColonnes('standard');
1636 raphael 294
		foreach($entete as $k => $v) {
295
			$entete_simple = iconv('UTF-8', 'ASCII//TRANSLIT', strtolower(trim($v)));
296
			foreach($cols as $col) {
297
				$entete_officiel_simple = iconv('UTF-8', 'ASCII//TRANSLIT', strtolower(trim($col['nom'])));
1638 raphael 298
				$entete_officiel_abbrev = $col['abbrev'];
299
				if($entete_simple == $entete_officiel_simple || $entete_simple == $entete_officiel_abbrev) {
1648 raphael 300
					// debug echo "define C_" . strtoupper($entete_officiel_abbrev) . ", $k ($v)\n";
1638 raphael 301
					define("C_" . strtoupper($entete_officiel_abbrev), $k);
1636 raphael 302
					$colonnes_reconnues[$k] = 1;
303
					break;
304
				}
305
			}
306
		}
307
 
1640 raphael 308
		// prépare le filtre de PHPExcel qui évitera le traitement de toutes les colonnes superflues
309
 
310
		// eg: diff ( Array( H => Commune, I => rien ) , Array( H => 1, K => 1 )
311
		// ==> Array( I => rien )
1636 raphael 312
		$colonnesID_non_reconnues = array_diff_key($entete, $colonnes_reconnues);
313
 
1646 raphael 314
		// des colonnes de ExportXLS::nomEnsembleVersListeColonnes()
1640 raphael 315
		// ne retient que celles marquées "importables"
1636 raphael 316
		$colonnes_automatiques = array_filter($cols, function($v) {	return !$v['importable']; });
1640 raphael 317
 
1636 raphael 318
		// ne conserve que le nom long pour matcher avec la ligne XLS d'entête
319
		array_walk($colonnes_automatiques, function(&$v) {	$v = $v['nom']; });
1640 raphael 320
 
321
		// intersect ( Array ( N => Milieu, S => Ordre ), Array ( ordre => Ordre, phenologie => Phénologie ) )
322
		// ==> Array ( S => Ordre, AA => Phénologie )
1636 raphael 323
		$colonnesID_a_exclure = array_intersect($entete, $colonnes_automatiques);
324
 
1640 raphael 325
		// TODO: pourquoi ne pas comparer avec les abbrevs aussi ?
326
		// merge ( Array( I => rien ) , Array ( S => Ordre, AA => Phénologie ) )
327
		// ==> Array ( I => rien, AA => Phénologie )
1636 raphael 328
		return array_merge($colonnesID_non_reconnues, $colonnesID_a_exclure);
329
	}
330
 
1640 raphael 331
	/*
332
	 * charge un groupe de lignes
333
	 */
1642 raphael 334
	static function chargerLignes($cel, $lignes, $colonnes_statiques, &$dernier_ordre) {
1640 raphael 335
		$enregistrement = NULL;
336
		$enregistrements = Array();
1642 raphael 337
		$toutes_images = Array();
1640 raphael 338
 
339
		foreach($lignes as $ligne) {
1642 raphael 340
			//$ligne = array_filter($ligne, function($cell) { return !is_null($cell); });
341
			//if(!$ligne) continue;
342
			// on a besoin des NULL pour éviter des notice d'index indéfini
343
			if(! array_filter($ligne, function($cell) { return !is_null($cell); })) continue;
1640 raphael 344
 
1642 raphael 345
			if( ($enregistrement = self::chargerLigne($ligne, $dernier_ordre, $cel)) ) {
1648 raphael 346
				// $enregistrements[] = array_merge($colonnes_statiques, $enregistrement);
347
				$enregistrements[] = $enregistrement;
1640 raphael 348
 
349
				if(isset($enregistrement['_images'])) {
350
					$pos = count($enregistrements) - 1;
1642 raphael 351
					$last = &$enregistrements[$pos];
1640 raphael 352
					// ne dépend pas de cel_obs, et seront insérées *après* les enregistrements
353
					// mais nous ne voulons pas nous priver de faire des INSERT multiples pour autant
1642 raphael 354
					$toutes_images[] = Array("images" => $last['_images'],
355
											 "obs_pos" => $pos);
1640 raphael 356
					// ce champ n'a pas a faire partie de l'insertion dans cel_obs,
357
					// mais est utile pour cel_obs_images
1642 raphael 358
					unset($last['_images']);
1640 raphael 359
				}
360
 
361
				$dernier_ordre++;
362
			}
1636 raphael 363
		}
1640 raphael 364
 
1642 raphael 365
		// XXX future: return Array($enregistrements_a_inserer, $enregistrements_a_MAJ, $toutes_images);
366
		return Array($enregistrements, $toutes_images);
367
	}
1640 raphael 368
 
1642 raphael 369
 
1648 raphael 370
	static function trierColonnes(&$enregistrements) {
371
		foreach($enregistrements as &$enregistrement) {
1642 raphael 372
			$enregistrement = self::sortArrayByArray($enregistrement, self::$ordre_BDD);
1648 raphael 373
			//array_walk($enregistrement, function(&$item, $k) { $item = is_null($item) ? "NULL" : $item; });
374
			//$req .= implode(', ', $enregistrement) . "\n";
1642 raphael 375
		}
376
	}
377
 
378
 
379
	static function stockerImages($cel, $enregistrements, $toutes_images, $lastid) {
380
		if(! $lastid) $lastid = rand();
381
 
382
		$images_insert =
383
			'INSERT INTO cel_obs_images (id_image, id_observation) VALUES'
384
			.' %s '
385
			.'ON DUPLICATE KEY UPDATE id_image = id_image';
386
		$images_obs_assoc = Array();
387
 
388
		foreach($toutes_images as $images_pour_obs) {
389
			$obs = $enregistrements[$images_pour_obs["obs_pos"]];
1640 raphael 390
			$id_obs = $lastid // dernier autoinc inséré
391
				- count($enregistrements) - 1 // correspondrait au premier autoinc
1642 raphael 392
				+ $images_pour_obs["obs_pos"]; // ordre d'insertion = ordre dans le tableau $enregistrements
393
			foreach($images_pour_obs['images'] as $image) {
394
				$images_obs_assoc[] = sprintf('(%d,%d)',
395
											  $image['id_image'], // intval() useless
396
											  $id_obs); // intval() useless
397
			}
1640 raphael 398
		}
1642 raphael 399
 
400
		if($images_obs_assoc) {
401
			$requete = sprintf($images_insert, implode(', ', $images_obs_assoc));
402
			echo "$requete\n";
403
		}
1636 raphael 404
	}
405
 
1649 raphael 406
	/*
407
	  Aucune des valeurs présentes dans $enregistrement n'est quotée
408
	  cad aucune des valeurs retournée par traiter{Espece|Localisation}()
409
	  car ce tableau est passé à un PDO::preparedStatement() qui applique
410
	  proprement les règle d'échappement.
411
	 */
1642 raphael 412
	static function chargerLigne($ligne, $dernier_ordre, $cel) {
1636 raphael 413
		// en premier car le résultat est utile pour
414
		// traiter longitude et latitude (traiterLonLat())
1640 raphael 415
		$referentiel = self::identReferentiel($ligne[C_NOM_REFERENTIEL]);
1636 raphael 416
 
1640 raphael 417
		// $espece est rempli de plusieurs informations
1642 raphael 418
		$espece = Array(C_NOM_SEL => NULL, C_NOM_SEL_NN => NULL, C_NOM_RET => NULL,
419
						C_NOM_RET_NN => NULL, C_NT => NULL, C_FAMILLE => NULL);
1640 raphael 420
		self::traiterEspece($ligne, $espece, $cel);
1636 raphael 421
 
1642 raphael 422
		// $localisation est rempli à partir de plusieurs champs: C_ZONE_GEO et C_CE_ZONE_GEO
423
		$localisation = Array(C_ZONE_GEO => NULL, C_CE_ZONE_GEO => NULL);
424
		self::traiterLocalisation($ligne, $localisation, $cel);
1636 raphael 425
 
1649 raphael 426
		// $transmission est utilisé pour date_transmission
427
		$transmission = in_array(strtolower(trim($ligne[C_TRANSMISSION])), array(1, 'oui')) ? 1 : 0;
428
 
429
 
1642 raphael 430
		// Dans ce tableau, seules devraient apparaître les données variable pour chaque ligne.
431
		// Dans ce tableau, l'ordre des clefs n'importe pas (cf: self::sortArrayByArray())
432
		$enregistrement = Array(
433
			"ordre" => $dernier_ordre,
1640 raphael 434
 
1642 raphael 435
			"nom_sel" => $espece[C_NOM_SEL],
436
			"nom_sel_nn" => $espece[C_NOM_SEL_NN],
437
			"nom_ret" => $espece[C_NOM_RET],
438
			"nom_ret_nn" => $espece[C_NOM_RET_NN],
439
			"nt" => $espece[C_NT],
440
			"famille" => $espece[C_FAMILLE],
1640 raphael 441
 
1649 raphael 442
			"nom_referentiel" => $referentiel,
1640 raphael 443
 
1642 raphael 444
			"zone_geo" => $localisation[C_ZONE_GEO],
445
			"ce_zone_geo" => $localisation[C_CE_ZONE_GEO],
1640 raphael 446
 
1642 raphael 447
			// $ligne: uniquement pour les infos en cas de gestion d'erreurs (date incompréhensible)
1649 raphael 448
			"date_observation" => self::traiterDateObs($ligne[C_DATE_OBSERVATION], $ligne),
1640 raphael 449
 
1649 raphael 450
			"lieudit" => trim($ligne[C_LIEUDIT]),
451
			"station" => trim($ligne[C_STATION]),
452
			"milieu" => trim($ligne[C_MILIEU]),
1642 raphael 453
 
1649 raphael 454
			"mots_cles_texte" => NULL, // TODO: foreign-key
455
			"commentaire" => trim($ligne[C_COMMENTAIRE]),
1642 raphael 456
 
1649 raphael 457
			"transmission" => $transmission,
458
			"date_transmission" => $transmission ? date("Y-m-d H:i:s") : NULL, // pas de fonction SQL dans un PDO statement, <=> now()
1642 raphael 459
 
460
			// $ligne: uniquement pour les infos en cas de gestion d'erreurs (lon/lat incompréhensible)
461
			"latitude" => self::traiterLonLat(NULL, $ligne[C_LATITUDE], $referentiel, $ligne),
462
			"longitude" => self::traiterLonLat($ligne[C_LONGITUDE], NULL, $referentiel, $ligne),
1648 raphael 463
 
464
			// @ car potentiellement optionnelles ou toutes vides => pas d'index dans PHPExcel (tableau optimisé)
465
			"abondance" => @$ligne[C_ABONDANCE],
466
			"certitude" => @$ligne[C_CERTITUDE],
467
			"phenologie" => @$ligne[C_PHENOLOGIE],
468
 
1649 raphael 469
			"code_insee_calcule" => substr($localisation[C_CE_ZONE_GEO], -5) // varchar(5)
1642 raphael 470
		);
471
 
472
		// passage de $enregistrement par référence, ainsi ['_images'] n'est défini
473
		// que si des résultats sont trouvés
474
		// "@" car PHPExcel supprime les colonnes null sur toute la feuille (ou tout le chunk)
475
		if(@$ligne[C_IMAGES]) self::traiterImage($ligne[C_IMAGES], $cel, $enregistrement);
476
 
477
		return $enregistrement;
1636 raphael 478
	}
479
 
1642 raphael 480
	static function traiterImage($str, $cel, &$enregistrement) {
481
		$liste_images = array_filter(explode("/", $str));
482
		array_walk($liste_images,
1649 raphael 483
				   function($item, $key, $obj) { $item = $obj->quoteNonNull(trim($item)); },
1642 raphael 484
				   $cel);
485
		$requete = sprintf(
486
			"SELECT id_image, nom_original FROM cel_images WHERE ce_utilisateur = %d AND nom_original IN (\"%s\")",
487
			$cel->id_utilisateur,
488
			implode('","', $liste_images));
1640 raphael 489
 
1642 raphael 490
		$resultat = $cel->requeter($requete);
1640 raphael 491
 
1642 raphael 492
		if($resultat) $enregistrement['_images'] = $resultat;
493
	}
494
 
495
 
1640 raphael 496
	/* FONCTIONS de TRANSFORMATION de VALEUR DE CELLULE */
497
 
498
	// TODO: PHP 5.3, utiliser date_parse_from_format()
499
	// TODO: parser les heures (cf product-owner)
500
	// TODO: passer par le timestamp pour s'assurer de la validité
1642 raphael 501
	static function traiterDateObs($date, $ligne) {
1640 raphael 502
		// TODO: see https://github.com/PHPOffice/PHPExcel/issues/208
503
		if(is_double($date)) {
504
			if($date > 0)
505
				return PHPExcel_Style_NumberFormat::toFormattedString($date, PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2) . " 00:00:00";
1642 raphael 506
			trigger_error("ligne \"{$ligne[C_NOM_SEL]}\": " .
507
						  "Attention: date antérieure à 1970 et format de cellule \"DATE\" utilisés ensemble",
508
						  E_USER_NOTICE);
509
 
510
			// throw new Exception("erreur: date antérieure à 1970 et format de cellule \"DATE\" utilisés ensemble");
1640 raphael 511
 
512
			// attention, UNIX timestamp, car Excel les décompte depuis 1900
513
			// cf http://fczaja.blogspot.fr/2011/06/convert-excel-date-into-timestamp.html
514
			// $timestamp = ($date - MIN_DATES_DIFF) * 60 * 60 * 24 - time(); // NON
515
 
516
			// $timestamp = PHPExcel_Calculation::getInstance()->calculateFormula("=" . $date . "-DATE(1970,1,1)*60*60*24"); // NON
517
 
518
			// echo strftime("%Y/%m/%d 00:00:00", $timestamp); // NON
519
		}
520
		else {
521
			$timestamp = strtotime($date);
1642 raphael 522
			if(! $timestamp) {
523
				if($date) trigger_error("ligne \"{$ligne[C_NOM_SEL]}\": Attention: date erronée ($date)", E_USER_NOTICE);
524
				return NULL;
525
			}
1640 raphael 526
			return strftime("%Y-%m-%d 00:00:00", strtotime($date));
527
		}
1636 raphael 528
	}
529
 
530
	static function identReferentiel($referentiel) {
1640 raphael 531
		// SELECT DISTINCT nom_referentiel, COUNT(id_observation) AS count FROM cel_obs GROUP BY nom_referentiel ORDER BY count DESC;
532
		if(strpos(strtolower($referentiel), 'bdtfx') !== FALSE) return 'bdtfx:v1.01';
533
		if(strpos(strtolower($referentiel), 'bdtxa') !== FALSE) return 'bdtxa:v1.00';
534
		if(strpos(strtolower($referentiel), 'bdnff') !== FALSE) return 'bdnff:4.02';
535
		if(strpos(strtolower($referentiel), 'isfan') !== FALSE) return 'isfan:v1.00';
1642 raphael 536
 
537
		if($referentiel) {
538
			trigger_error("ligne \"{$ligne[C_NOM_SEL]}\": Attention: référentiel inconnu", E_USER_NOTICE);
539
		}
1640 raphael 540
		return NULL;
541
		/* TODO: cf story,
1642 raphael 542
		   En cas de NULL faire une seconde passe de détection à partir du nom saisi
543
		   + accepter les n° de version */
1636 raphael 544
	}
545
 
1642 raphael 546
	static function traiterLonLat($lon = NULL, $lat = NULL, $referentiel = 'bdtfx:v1.01', $ligne) {
547
		// en CSV ces valeurs sont des string, avec séparateur en français (","; cf défauts dans ExportXLS)
548
		if($lon && is_string($lon)) $lon = str_replace(',', '.', $lon);
549
		if($lat && is_string($lat)) $lat = str_replace(',', '.', $lat);
1640 raphael 550
 
1642 raphael 551
		// sprintf applique une précision à 5 décimale (comme le ferait MySQL)
552
		// tout en uniformisant le format de séparateur des décimales (le ".")
553
		if($lon && is_numeric($lon) && $lon >= -180 && $lon <= 180) return sprintf('%.5F', $lon);
554
		if($lat && is_numeric($lat) && $lat >= -90 && $lat <= 90) return sprintf('%.5F', $lat);
555
 
556
		if($lon || $lat) {
557
			trigger_error("ligne \"{$ligne[C_NOM_SEL]}\": " .
558
						  "Attention: longitude ou latitude erronée",
559
						  E_USER_NOTICE);
560
		}
561
		return NULL;
562
 
563
		/* limite france métropole si bdtfx ? ou bdtxa ? ...
564
		   NON!
565
		   Un taxon d'un référentiel donné peut être théoriquement observé n'importe où sur le globe.
566
		   Il n'y a pas lieu d'effectuer des restriction ici.
567
		   Cependant des erreurs fréquentes (0,0 ou lon/lat inversées) peuvent être détectés ici.
568
		   TODO */
1640 raphael 569
		$bbox = self::getReferentielBBox($referentiel);
570
		if(!$bbox) return NULL;
571
 
572
		if($lon) {
573
			if($lon < $bbox['EST'] && $lon > $bbox['OUEST']) return is_numeric($lon) ? $lon : NULL;
574
			else return NULL;
575
		}
576
		if($lat) {
577
			if($lat < $bbox['NORD'] && $lat > $bbox['SUD']) return is_numeric($lat) ? $lat : NULL;
578
			return NULL;
579
		}
1636 raphael 580
	}
581
 
1640 raphael 582
 
583
	static function traiterEspece($ligne, Array &$espece, $cel) {
1642 raphael 584
		if(!$ligne[C_NOM_SEL]) return;
585
 
1640 raphael 586
		$taxon_info_webservice = new RechercheInfosTaxonBeta($cel->config);
587
 
588
		$ascii = iconv('UTF-8', 'ASCII//TRANSLIT', $ligne[C_NOM_SEL]);
1642 raphael 589
		// FALSE = recherche étendue (LIKE x%)
1640 raphael 590
		$resultat_recherche_espece = $taxon_info_webservice->rechercherInfosSurTexteCodeOuNumTax($ligne[C_NOM_SEL]);
591
 
592
		// on supprime les noms retenus et renvoi tel quel
593
		// on réutilise les define pour les noms d'indexes, tant qu'à faire
594
		if (empty($resultat_recherche_espece['en_id_nom'])) {
1649 raphael 595
			$espece[C_NOM_SEL] = trim($ligne[C_NOM_SEL]);
1640 raphael 596
 
1642 raphael 597
			// le reste reste à NULL
1640 raphael 598
			// TODO: si empty(C_NOM_SEL) et !empty(C_NOM_SEL_NN) : recherche info à partir de C_NOM_SEL_NN
1642 raphael 599
			$espece[C_NOM_SEL_NN] = $ligne[C_NOM_SEL_NN];
1640 raphael 600
			$espece[C_NOM_RET] = $ligne[C_NOM_RET];
601
			$espece[C_NOM_RET_NN] = $ligne[C_NOM_RET_NN];
602
			$espece[C_NT] = $ligne[C_NT];
603
			$espece[C_FAMILLE] = $ligne[C_FAMILLE];
604
 
605
			return;
606
		}
607
 
608
		// succès de la détection, récupération des infos
1649 raphael 609
		$espece[C_NOM_SEL] = $resultat_recherche_espece['nom_sel'];
610
		$espece[C_NOM_SEL_NN] = $resultat_recherche_espece['en_id_nom'];
1640 raphael 611
 
612
		$complement = $taxon_info_webservice->rechercherInformationsComplementairesSurNumNom($resultat_recherche_espece['en_id_nom']);
1649 raphael 613
		$espece[C_NOM_RET] = $complement['Nom_Retenu'];
614
		$espece[C_NOM_RET_NN] = $complement['Num_Nom_Retenu'];
615
		$espece[C_NT] = $complement['Num_Taxon'];
616
		$espece[C_FAMILLE] = $complement['Famille'];
1640 raphael 617
	}
618
 
619
 
1642 raphael 620
	static function traiterLocalisation($ligne, Array &$localisation, $cel) {
621
	    $identifiant_commune = trim($ligne[C_ZONE_GEO]);
622
		if(!$identifiant_commune) {
623
			$departement = trim($ligne[C_CE_ZONE_GEO]);
624
			goto testdepartement;
625
		}
626
 
627
 
628
		$select = "SELECT DISTINCT nom, code  FROM cel_zones_geo";
629
 
630
		if (preg_match('/(.*) \((\d+)\)/', $identifiant_commune, $elements)) {
631
			// commune + departement : montpellier (34)
632
			$nom_commune=$elements[1];
633
			$code_commune=$elements[2];
634
	 	    $requete = sprintf("%s WHERE nom = %s AND code LIKE %s",
1649 raphael 635
							   $select, $cel->quoteNonNull($nom_commune), $cel->quoteNonNull($code_commune.'%'));
1642 raphael 636
		}
637
		elseif (preg_match('/^(\d+|(2[ab]\d+))$/i', $identifiant_commune, $elements)) {
638
			// Code insee seul
639
			$code_insee_commune=$elements[1];
1649 raphael 640
	 	    $requete = sprintf("%s WHERE code = %s", $select, $cel->quoteNonNull($code_insee_commune));
1642 raphael 641
		}
642
		else {
643
			// Commune seule (le departement sera recupere dans la colonne departement si elle est presente)
644
			// on prend le risque ici de retourner une mauvaise Commune
645
			$nom_commune = str_replace(" ", "%", iconv('UTF-8', 'ASCII//TRANSLIT', $identifiant_commune));
1649 raphael 646
	 	    $requete = sprintf("%s WHERE nom LIKE %s", $select, $cel->quoteNonNull($nom_commune.'%'));
1642 raphael 647
		}
648
 
649
		$resultat_commune = $cel->requeter($requete);
650
		// TODO: levenstein sort ?
651
 
652
		// cas de la commune introuvable dans le référentiel
653
		// réinitialisation aux valeurs du fichier XLS
654
		if(! $resultat_commune) {
655
			$localisation[C_ZONE_GEO] = trim($ligne[C_ZONE_GEO]);
656
			$localisation[C_CE_ZONE_GEO] = trim($ligne[C_CE_ZONE_GEO]);
657
		} else {
658
			$localisation[C_ZONE_GEO] = $resultat_commune[0]['nom'];
659
			$localisation[C_CE_ZONE_GEO] = $resultat_commune[0]['code'];
660
		}
661
 
662
		$departement = &$localisation[C_CE_ZONE_GEO];
663
 
664
	testdepartement:
665
		if(strpos($departement, "INSEE-C:", 0) === 0) goto protectloc;
666
 
667
		if(!is_numeric($departement)) goto protectloc; // TODO ?
668
		if(strlen($departement) == 4) $departement = "INSEE-C:0" . $departement;
669
		if(strlen($departement) == 5) $departement = "INSEE-C:" . $departement;
1640 raphael 670
		// if(strlen($departement) <= 9) return "INSEE-C:0" . $departement; // ? ... TODO
1642 raphael 671
 
672
		$departement = trim($departement); // TODO
673
 
674
	protectloc:
1649 raphael 675
		$localisation[C_ZONE_GEO] = $localisation[C_ZONE_GEO];
676
		$localisation[C_CE_ZONE_GEO] = $localisation[C_CE_ZONE_GEO];
1640 raphael 677
	}
678
 
679
 
1642 raphael 680
 
1640 raphael 681
	/* HELPERS */
682
 
1636 raphael 683
	// http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
1640 raphael 684
	static function sortArrayByArray($array, $orderArray) {
1636 raphael 685
		$ordered = array();
686
		foreach($orderArray as $key) {
687
			if(array_key_exists($key, $array)) {
688
				$ordered[$key] = $array[$key];
689
				unset($array[$key]);
690
			}
691
		}
692
		return $ordered + $array;
693
	}
1640 raphael 694
 
695
	// retourne une BBox [N,S,E,O) pour un référentiel donné
696
	static function getReferentielBBox($referentiel) {
697
		if($referentiel == 'bdtfx:v1.01') return Array(
698
			'NORD' => 51.2, // Dunkerque
699
			'SUD' => 41.3, // Bonifacio
700
			'EST' => 9.7, // Corse
701
			'OUEST' => -5.2); // Ouessan
702
		return FALSE;
703
	}
704
 
1649 raphael 705
	// ces valeurs ne sont pas inséré via les placeholders du PDO::preparedStatement
706
	// et doivent donc être échappées correctement.
1642 raphael 707
	public function initialiser_colonnes_statiques() {
1640 raphael 708
		$this->colonnes_statiques = array_merge($this->colonnes_statiques,
709
												Array(
1642 raphael 710
													"ce_utilisateur" => $this->id_utilisateur,
1649 raphael 711
													"prenom_utilisateur" => $this->quoteNonNull($this->utilisateur['prenom']),
712
													"nom_utilisateur" => $this->quoteNonNull($this->utilisateur['nom']),
713
													"courriel_utilisateur" => $this->quoteNonNull($this->utilisateur['courriel']),
1640 raphael 714
												));
715
 
716
	}
1642 raphael 717
 
1649 raphael 718
	static function initialiser_pdo_ordered_statements($colonnes_statiques) {
719
		return Array(
720
			// insert_ligne_pattern_ordre
721
			sprintf('INSERT INTO cel_obs (%s, %s) VALUES',
722
					implode(', ', array_keys($colonnes_statiques)),
723
					implode(', ', array_diff(self::$ordre_BDD, array_keys($colonnes_statiques)))),
724
 
725
			// insert_ligne_pattern_ordre
726
			sprintf('(%s, %s ?)',
727
					implode(', ', $colonnes_statiques),
728
					str_repeat('?, ', count(self::$ordre_BDD) - count($colonnes_statiques) - 1))
729
		);
1648 raphael 730
	}
731
 
1649 raphael 732
	static function initialiser_pdo_statements($colonnes_statiques) {
733
		return Array(
734
			// insert_prefix
735
			sprintf('INSERT INTO cel_obs (%s) VALUES ',
736
					implode(', ', self::$ordre_BDD)),
737
 
738
			// insert_ligne_pattern =
739
			'(' .
740
			implode(', ', array_values(array_map(
741
				function($item) { return is_null($item) ? '?' : $item; },
742
				array_merge(
743
					array_map(function() { return NULL; }, array_flip(self::$ordre_BDD)),
744
					$colonnes_statiques
745
				)))) .
746
			')'
747
		);
748
	}
749
 
1642 raphael 750
	// équivalent à CEL->Bdd->proteger() (qui wrap PDO::quote),
751
	// sans transformer NULL en ""
752
	private function quoteNonNull($chaine) {
753
		if(is_null($chaine)) return "NULL";
754
		if(!is_string($chaine)) die("erreur __FILE__, __LINE__");
755
		return $this->bdd->quote($chaine);
756
	}
757
 
758
	public function erreurs_stock($errno, $errstr) {
759
		$this->bilan[] = $errstr;
760
	}
1636 raphael 761
}