Subversion Repositories eFlore/Applications.cel

Rev

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