Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
1654 aurelien 1
<?php
1656 raphael 2
 
3
/**
4
* @category  PHP
5
* @package   jrest
6
* @author    Raphaël Droz <raphael@tela-botania.org>
7
* @copyright 2013 Tela-Botanica
8
* @license   http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
9
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
10
*/
1759 raphael 11
define('SEPARATEUR_IMAGES', " / ");
1656 raphael 12
 
1654 aurelien 13
Class FormateurGroupeColonne {
1656 raphael 14
 
1702 raphael 15
	// cache pour les données des fonctions
1656 raphael 16
	static $cache = Array();
17
 
1702 raphael 18
	// test sur la table cel_references, mis à TRUE si la table existe
19
	static $is_table = false;
20
 
1714 raphael 21
	// les groupes de champs utilisables
22
	static $fieldGroups = array(
23
		'standard',
24
		'avance',
25
		'etendu',
26
		'baseflor'
27
	);
28
 
1702 raphael 29
	// les données baseflor à récupérer: colonnes présentes dans cel_references
30
	// et intitulés associés
31
	static $baseflor_col = array(
32
		"ve_lumiere" => "Lumière",
33
		"ve_temperature" => "Température",
34
		"ve_continentalite" => "Continentalité",
35
		"ve_humidite_atmos" => "Humidité Atmosphérique",
36
		"ve_humidite_edaph" => "Humidité",
37
		"ve_reaction_sol" => "Réaction (pH)",
38
		"ve_nutriments_sol" => "Nutriments",
39
		"ve_salinite" => "Salinité",
40
		"ve_texture_sol" => "Texture" ,
41
		"ve_mat_org_sol" => "Matière Organique",
42
		"catminat_code" => "Code Catminat",
43
		"syntaxon" => "Syntaxon",
44
	);
45
 
1741 raphael 46
	// TODO: dirty, ordre des champs étendus... souhaité pour florilèges:
47
	static $ordre_champ_etendus_Florileges = array(
48
		"personneStructure",
49
		"personneService",
50
		"personneFonction",
51
		"adresse",
52
		"latitudeDebutRue",
53
		"longitudeDebutRue",
54
		"latitudeFinRue",
55
		"longitudeFinRue",
56
		"typoUrbaine",
57
		"revetementSol",
58
		"presenceZoneVegetalise",
59
		"hauteurBatimentAvoisinant",
60
		"intensiteGestion",
61
		"periodiciteTraitementPhyto",
62
		"dateArretTraitementPhyto",
63
		"itineraireGestion",
64
		"dateDerniereIntervention",
65
		"hauteurPlante",
66
		"resistanceTraitementPhyto",
67
		"vitesseCroissance",
68
		"perceptionTechnicien",
69
		"perceptionRiverainMauvaise",
70
	);
71
 
1714 raphael 72
	static function colGroupsValidation($groupe_de_champs = 'standard,avance') {
73
		if(! $groupe_de_champs) return FALSE;
74
		if(is_string($groupe_de_champs)) {
75
			$groupe_de_champs = array_flip(explode(',', $groupe_de_champs));
76
		}
77
		elseif(is_array($groupe_de_champs)) {
78
			$groupe_de_champs = array_flip($groupe_de_champs);
79
		}
80
		else {
81
			return NULL;
82
		}
83
		$groupe_de_champs = array_intersect_key(array_flip(self::$fieldGroups),
84
												$groupe_de_champs);
85
		if(!$groupe_de_champs) return FALSE;
86
		// toujours ajouter standard
87
		$groupe_de_champs['standard'] = TRUE;
88
		return implode(',', array_keys($groupe_de_champs));
89
	}
90
 
1654 aurelien 91
	/*
92
	* @param $fieldSets: un liste de noms de colonnes ou de sets de colonnes
93
	*		séparés par des virgules
94
	* 		eg: "espece" ou "champs-etendus", ...
95
	*
96
	* @return: un tableau associatif déjà ordonné
97
	* 		clé: abbrev [machine-name] de la colonne (eg: "espece" ou "mot-clef")
98
	* 		valeur: des données relative à cette colonne, cf GenColInfo
99
	*
1757 raphael 100
	* Si la colonne n'utilise pas de fonction de récupération particulière
101
	* (ie: si le champ exportés [ou importé] correspond exactement au champ dans la base de donnée)
102
	* Alors 'abbrev' doit avoir la même valeur que le nom de la colonne dans la table mysql `cel_obs`.
1654 aurelien 103
	*
104
	*/
105
	static function nomEnsembleVersListeColonnes($groupe_de_champs = 'standard') {
106
		if(! $groupe_de_champs) $groupe_de_champs = 'standard';
1711 raphael 107
		if(is_string($groupe_de_champs)) {
108
			$groupe_de_champs = array_flip(explode(',', $groupe_de_champs));
109
		}
110
		elseif(is_array($groupe_de_champs)) {
111
			$groupe_de_champs = array_flip($groupe_de_champs);
112
		}
113
		else {
114
			return NULL;
115
		}
1714 raphael 116
		$groupe_de_champs = array_intersect_key(array_flip(self::$fieldGroups),
1711 raphael 117
												$groupe_de_champs);
118
		if(!$groupe_de_champs) return NULL;
119
 
1656 raphael 120
		$colonnes = Array();
1654 aurelien 121
 
122
		if(isset($groupe_de_champs['standard'])) {
123
			$colonnes += Array(
1757 raphael 124
				'nom_sel'			=> self::GenColInfo(Array('abbrev' => 'nom_sel',
125
															  'nom' => 'Espèce')),
126
				'nom_sel_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_sel_nn',
127
															  'nom' => 'Numéro nomenclatural',
128
															  'importable' => FALSE)),
129
				'nom_ret'			=> self::GenColInfo(Array('abbrev' => 'nom_ret',
130
															  'nom' => 'Nom retenu',
131
															  'importable' => FALSE)),
132
				'nom_ret_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_ret_nn',
133
															  'nom' => 'Numéro nomenclatural nom retenu',
134
															  'importable' => FALSE)),
135
				'nt'				=> self::GenColInfo(Array('abbrev' => 'nt',
136
															  'nom' => 'Numéro taxonomique',
137
															  'importable' => FALSE)),
138
				'famille'			=> self::GenColInfo(Array('abbrev' => 'famille',
139
															  'nom' => 'Famille',
140
															  'importable' => FALSE)),
141
				'nom_referentiel'	=> self::GenColInfo(Array('abbrev' => 'nom_referentiel',
142
															  'nom' => 'Referentiel taxonomique')),
143
				'zone_geo'			=> self::GenColInfo(Array('abbrev' => 'zone_geo',
144
															  'nom' => 'Commune')),
145
				'ce_zone_geo'		=> self::GenColInfo(Array('abbrev' => 'ce_zone_geo',
146
															  'nom' => 'Identifiant Commune',
147
															  'fonction' => 'convertirCodeZoneGeoVersDepartement')),
148
				'date_observation'	=> self::GenColInfo(Array('abbrev' => 'date_observation',
149
															  'nom' => 'Date',
150
															  'fonction' => 'formaterDate')),
151
				'lieudit'			=> self::GenColInfo(Array('abbrev' => 'lieudit',
152
															  'nom' => 'Lieu-dit')),
153
				'station'			=> self::GenColInfo(Array('abbrev' => 'station',
154
															  'nom' => 'Station')),
155
				'milieu'			=> self::GenColInfo(Array('abbrev' => 'milieu',
156
															  'nom' => 'Milieu')),
157
				'commentaire'		=> self::GenColInfo(Array('abbrev' => 'commentaire',
158
															  'nom' => 'Notes')),
159
				'latitude'			=> self::GenColInfo(Array('abbrev' => 'latitude',
160
															  'nom' => 'Latitude',
161
															  'extra' => 1,
162
															  'fonction' => 'trim0')),
163
				'longitude'			=> self::GenColInfo(Array('abbrev' => 'longitude',
164
															  'nom' => 'Longitude',
165
															  'extra' => 1,
166
															  'fonction' => 'trim0')),
167
				'altitude'			=> self::GenColInfo(Array('abbrev' => 'altitude',
168
															  'nom' => 'Altitude',
169
															  'extra' => 1,
170
															  'fonction' => 'trim0')),
171
				'geodatum'			=> self::GenColInfo(Array('abbrev' => 'geodatum',
172
															  'nom' => 'Référentiel Géographique',
173
															  'extra' => 1,
174
															  'importable' => FALSE)),
1654 aurelien 175
			);
176
		}
177
 
178
		if(isset($groupe_de_champs['avance'])) {
1656 raphael 179
			$colonnes += array(
1757 raphael 180
				// TODO: importable = FALSE car pas de merge de données importées
181
				'ordre'				=> self::GenColInfo(Array('abbrev' => 'ordre',
182
															  'nom' => 'Ordre',
183
															  'extra' => 1,
184
															  'importable' => FALSE)),
185
				'id_observation'	=> self::GenColInfo(Array('abbrev' => 'id_observation',
186
															  'nom' => 'Identifiant',
187
															  'extra' => 1,
188
															  'importable' => FALSE)),
1656 raphael 189
 
1757 raphael 190
				'mots_cles_texte'	=> self::GenColInfo(Array('abbrev' => 'mots_cles_texte',
191
															  'nom' => 'Mots Clés',
192
															  'extra' => 1)),
193
				'date_creation'		=> self::GenColInfo(Array('abbrev' => 'date_creation',
194
															  'nom' => 'Date Création',
195
															  'extra' => 1,
196
															  'importable' => FALSE)),
197
				'date_modification'	=> self::GenColInfo(Array('abbrev' => 'date_modification',
198
															  'nom' => 'Date Modification',
199
															  'extra' => 1,
200
															  'importable' => FALSE)),
1656 raphael 201
 
1757 raphael 202
				// rappel transmission = 1, signifie simplement "public"
203
				// des données importées peuvent être d'emblée "publiques"
204
				// "importable" = TRUE
205
				'transmission'		=> self::GenColInfo(Array('abbrev' => 'transmission',
206
															  'nom' => 'Transmis',
207
															  'extra' => 1,
208
															  'fonction' => 'boolOuiNon')),
209
				'date_transmission'	=> self::GenColInfo(Array('abbrev' => 'date_transmission',
210
															  'nom' => 'Date Transmission',
211
															  'extra' => 1,
212
															  'importable' => FALSE)),
213
				'abondance'			=> self::GenColInfo(Array('abbrev' => 'abondance',
214
															  'nom' => 'Abondance',
215
															  'extra' => 1)),
216
				'certitude'			=> self::GenColInfo(Array('abbrev' => 'certitude',
217
															  'nom' => 'Certitude',
218
															  'extra' => 1)),
219
				'phenologie'		=> self::GenColInfo(Array('abbrev' => 'phenologie',
220
															  'nom' => 'Phénologie',
221
															  'extra' => 1)),
222
 
223
				// XXX: getImages() dépend du contexte de Cel, et doit être appelée comme cas particulier
224
				// cf ExportXLS::traiterLigneObservation()
225
				'images'			=> self::GenColInfo(Array('abbrev' => 'images',
226
															  'nom' => 'Image(s)',
227
															  'extra' => 1,
228
															  'fonction_data' => NULL /* cas particulier 'getImages' */,
229
															  'importable' => TRUE,
230
															  //'preload' => array(__CLASS__, 'getImages_preload')//TODO
231
				)),
1656 raphael 232
 
1757 raphael 233
				/* 'nom_commun'			=> self::GenColInfo(Array('abbrev' => 'nom_commun',
234
				   'nom' => 'Nom Commun',
235
				   'extra' => 1,
236
				   'fonction_data' => 'getNomCommun',
237
				   'importable' => FALSE),
1685 raphael 238
 
1757 raphael 239
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
240
				   'nom' => 'Nom Commun',
241
				   'extra' => 1,
242
				   'fonction_data' => 'getNomCommun_v2'),
243
 
244
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
245
				   'nom' => 'Nom Commun',
246
				   'extra' => 1,
247
				   'fonction_data' => 'getNomCommun_v3'),
248
				   'importable' => FALSE), */
249
				'nom-commun'		=> self::GenColInfo(Array('abbrev' => 'nom-commun',
250
															  'nom' => 'Nom Commun',
251
															  'extra' => 1,
252
															  'fonction_data' => NULL /* cas particu 'getNomCommun_v4' */,
253
															  'preload' => array(__CLASS__, 'getNomCommun_preload')))
1702 raphael 254
			);
255
		}
1685 raphael 256
 
1702 raphael 257
		if(isset($groupe_de_champs['baseflor'])) {
258
			$colonnes += array(
259
				// champ dynamique
1757 raphael 260
				'baseflor'			=> self::GenColInfo(Array('abbrev' => 'baseflor',
261
															  'nom' => '',
262
															  'extra' => 1,
263
															  'importable' => FALSE,
264
															  'preload' => array(__CLASS__, 'baseflor_preload'),
265
															  'dyna' => array(__CLASS__, 'baseflor_ligne'))),
1654 aurelien 266
			);
1702 raphael 267
		}
1656 raphael 268
 
1714 raphael 269
		if(isset($groupe_de_champs['etendu'])) {
270
			$colonnes += array(
271
				// champ dynamique
1757 raphael 272
				'etendu'			=> self::GenColInfo(Array('abbrev' => 'etendu',
273
															  'nom' => '',
274
															  'extra' => 1,
275
															  'importable' => FALSE,
276
															  'preload' => array(__CLASS__, 'champsEtendus_preload'),
277
															  'dyna' => array(__CLASS__, 'champsEtendus_ligne'))),
1714 raphael 278
			);
279
		}
1654 aurelien 280
		return $colonnes;
281
	}
1694 raphael 282
 
283
	static function preload($colonnes, $cel, $ids) {
284
		$result = array();
285
		foreach($colonnes as $abbrev => $colonne) {
286
			if(!$colonne['preload']) continue;
1702 raphael 287
			$result[$abbrev] = call_user_func($colonne['preload'], $cel, $ids);
1694 raphael 288
		}
289
		return $result;
290
	}
1654 aurelien 291
 
1656 raphael 292
	public static function getIntitulesColonnes($colonnes) {
1702 raphael 293
		// array_filter pour supprimer les colonnes "dynamique" n'ayant pas défini $nom (cf GenColInfo())
294
		return array_filter(array_map(array('FormateurGroupeColonne', 'retournerNomItem'), $colonnes));
1654 aurelien 295
	}
296
 
1671 aurelien 297
	public static function retournerNomItem(&$item) {
298
		return $item['nom'];
299
	}
1694 raphael 300
 
1656 raphael 301
	public static function getLigneObservation(&$obs, &$colonnes, $cel = false) {
1757 raphael 302
 
1654 aurelien 303
		$ligne_formatee = array();
304
		foreach($colonnes as $abbrev => $colonne) {
305
			$valeur = null;
1702 raphael 306
			if($colonne['extra'] == 2 || ! is_null($colonne['dyna'])) continue;
1654 aurelien 307
 
308
			// valeur direct depuis cel_obs ?
309
			if(isset($obs[$abbrev])) $valeur = $obs[$abbrev];
310
 
311
			// pré-processeur de la champs
312
			if(function_exists($colonne['fonction'])) {
313
				$valeur = $colonne['fonction']($valeur);
314
			} elseif(method_exists(__CLASS__, $colonne['fonction'])) {
315
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
316
			} elseif($colonne['fonction']) {
317
				die("méthode {$colonne['fonction']} introuvable");
318
			}
319
			// fonction pour obtenir des champs (étendus)
320
			elseif(function_exists($colonne['fonction_data'])) {
321
				$valeur = $colonne['fonction_data']($obs);
322
			}
1687 raphael 323
			elseif(method_exists(__CLASS__, $colonne['fonction_data'])) {
1654 aurelien 324
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
325
			}
326
 
327
			// // cette section devrait être vide:
328
			// // cas particuliers ingérable avec l'architecture actuelle:
329
			if(false && $abbrev == 'date_observation' && $valeur == "0000-00-00") {
330
				/* blah */
331
			}
1765 raphael 332
			// ici à cause du passage de $cel ($this->utilisateur)
1656 raphael 333
			if($abbrev == 'images') {
1765 raphael 334
				$valeur = FormateurGroupeColonne::getImages($obs, $cel->id_utilisateur);
1656 raphael 335
			}
1685 raphael 336
			if($abbrev == 'nom-commun') {
1765 raphael 337
				$valeur = FormateurGroupeColonne::getNomCommun_v4($obs);
1685 raphael 338
			}
1654 aurelien 339
 
340
			if($valeur == null) {
341
				$valeur = "";
342
			}
343
 
344
			// // fin de section "cas particuliers"
345
			$ligne_formatee[] = $valeur;
346
		}
1694 raphael 347
 
1702 raphael 348
		// uniquement les champŝ dynamiques
349
		foreach($colonnes as $abbrev => $colonne) {
350
			$valeur = null;
351
			if(is_null($colonne['dyna'])) continue;
1706 raphael 352
			// XXX: PHP-5.3
353
			call_user_func_array($colonne['dyna'],
1765 raphael 354
								 array($obs, &$ligne_formatee));
1702 raphael 355
		}
1694 raphael 356
 
1654 aurelien 357
		return $ligne_formatee;
358
	}
359
 
360
	/*
361
	* Wrapper générant un tableau associatif:
1694 raphael 362
	* Ne pas changer les valeurs par défaut du prototype sans réflexion sur l'implication pour nomEnsembleVersListeColonnes()
1654 aurelien 363
 
364
	* @param $abbrev (obligatoire): nom court de colonne, largement utilisé lors de l'import.
365
	*		  En effet chaque ligne importée est accessible à l'aide du `define` de $abbrev en majuscule, préfixé de "C_"
366
	*		  Exemple: $ligne[C_LONGITUDE] pour "longitude".
367
	*		  cf: ImportXLS::detectionEntete()
368
 
369
	* @param $nom (obligatoire): nom complet de colonne (utilisé pour la ligne d'en-tête)
1702 raphael 370
	*		  Les définition de champs dynamique (correspondant à de multiples colonnes) doivent laisser cette valeur
371
	*		  vide afin de ne pas créer une colonne supplémentaire erronée.
1654 aurelien 372
 
373
	* @param $is_extra:
374
	* Si 0, la colonne est une colonne standard
375
	* Si 1, la colonne est extra [le plus souvent générée automatiquement]
376
	*		 (auquel cas une bordure bleue entoure son nom dans la ligne d'entête)
377
	* Si 2, la colonne n'est pas traité à l'export, mais une définition peut lui être donnée
378
	*		 qui pourra être utilisée à l'import, exemple: "image"
379
 
380
	* @param $fonction (optionnel): un nom d'un fonction de préprocessing
381
	* 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
382
 
383
	* @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
384
	* 		  $fonction_data doit prendre comme premier argument le tableau des champs de l'enregistrement existant
385
	*		  $fonction_data doit retourner une valeur
386
 
387
	* @param $importable (optionnel): défini si la colonne est traitée (ou absolument ignorée par PHPExcel) lors de
388
	*		  l'import.
1694 raphael 389
 
390
	* @param $preload (optionnel): défini une fonction de préchargement massif de donnée potentiellement utilisable par $fonction_data.
391
	*		  Utile, notamment, dans le cadre de l'export
1702 raphael 392
 
393
	* @param $fonction_dynamique (optionnel): défini une fonction ajoutant un nombre arbitraire de colonnes à une ligne donnée
394
	*		  Utile, notamment, dans le cadre de l'export des champs étendus ou des données baseflor
395
	*		  La fonction doit TOUJOURS alterer la ligne en lui ajoutant une nombre CONSTANT d'éléments (NULL ou non)
1765 raphael 396
	*		  La fonction doit prendre comme arguments ($obs, &$ligne_formatee)
1654 aurelien 397
	*/
1757 raphael 398
	static function GenColInfo($args) {
399
		$default = Array('abbrev' => NULL,
400
						 'nom' => NULL,
401
						 'extra' => 0,
402
						 'fonction' => NULL,
403
						 'fonction_data' => NULL,
404
						 'importable' => TRUE,
405
						 'preload' => NULL,
406
						 'dyna' => NULL);
407
		$ret = array_intersect_key($args, $default);
408
		return array_merge($default, $ret);
1654 aurelien 409
	}
410
 
1656 raphael 411
	static function formaterDate($date_heure_mysql) {
1671 aurelien 412
		//return "";
1707 raphael 413
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") return NULL;
1671 aurelien 414
		// malheureusement pas disponible en php < 5.3
415
		//$date_format = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql);
416
		$val = explode(' ', $date_heure_mysql);
417
		$date = explode('-', $val[0]);
418
		$heure = explode(':', $val[1]);
419
		$timestamp = mktime((int) $heure[0], (int) $heure[1], (int) $heure[2], (int) $date[1], (int) $date[2], (int) $date[0]);
1707 raphael 420
		if(!$timestamp) return NULL;
1656 raphael 421
		// TODO: les widgets ne font malheureusement pas usage de l'heure dans le CEL
422
		// TODO: si modification, ne pas oublier de modifier le format d'import correspondant
1698 raphael 423
		//	dans ImportXLS, traiterDateObs() (actuellement: "Y/m/d" car utilisation de strtotime() qui ne lit pas tout)
424
		// $date_formatee = strftime('%d/%m/%Y', $timestamp);
425
		$date_formatee = strftime('%Y/%m/%d', $timestamp);
1654 aurelien 426
		if(!$date_formatee) return "00/00/0000";
427
		return $date_formatee;
428
	}
1757 raphael 429
 
1759 raphael 430
	static function getImages_preload($cel, $obsids) {
431
		if(!$obsids) return;
432
		$rec = $cel->requeter(
433
			sprintf("SELECT o.id_observation, GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i " .
434
					"FROM cel_images i LEFT JOIN cel_obs_images oi ON (i.id_image = oi.id_image) LEFT JOIN cel_obs o ON (oi.id_observation = o.id_observation) " .
435
					"WHERE o.ce_utilisateur = %d AND o.id_observation IN (%s) " .
436
					"GROUP BY id_observation",
437
					SEPARATEUR_IMAGES,
438
					$cel->id_utilisateur,
439
					implode(',', $obsids)));
440
		foreach($rec as $v) {
441
			self::$cache['getImages'][$v['id_observation']] = $v['i'];
442
		}
443
		return NULL;
444
	}
445
 
1765 raphael 446
	static function getImages($obs, $id_utilisateur) {
1656 raphael 447
		if(! $id_utilisateur) return NULL;
1759 raphael 448
		if(isset(self::$cache['getImages'][$obs['id_observation']]))
449
			return self::$cache['getImages'][$obs['id_observation']];
450
 
1765 raphael 451
		$rec = Cel::db()->requeter(
1759 raphael 452
			sprintf("SELECT GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i FROM cel_images i"
1656 raphael 453
					." LEFT JOIN cel_obs_images oi ON (i.id_image = oi.id_image)"
454
					." LEFT JOIN cel_obs o ON (oi.id_observation = o.id_observation)"
1757 raphael 455
					." WHERE o.ce_utilisateur = %d AND o.id_observation = %d LIMIT 1",
1656 raphael 456
					SEPARATEUR_IMAGES,
1757 raphael 457
					$id_utilisateur,
458
					$obs['id_observation']));
459
		return $rec ? $rec[0]['i'] : NULL;
1654 aurelien 460
	}
461
 
462
	public static function convertirCodeZoneGeoVersDepartement($code_zone_geo) {
463
		$code_departement = '';
464
		if(self::estUnCodeInseeDepartement($code_zone_geo)) {
465
			$code_departement = substr(ltrim($code_zone_geo,'INSEE-C:'),0,2);
466
		}
467
 
468
		return $code_departement;
469
	}
1757 raphael 470
 
471
	public static function trim0($lonlat) {
472
		return trim(trim($lonlat, "0"), ".");
473
	}
474
 
475
	public static function boolOuiNon($transmission) {
476
		return $transmission ? 'oui' : '';
477
	}
1654 aurelien 478
 
479
	public static function estUnCodeInseeDepartement($code_a_tester) {
480
		return preg_match('/^INSEE-C:[0-9]{5}/',$code_a_tester);
481
	}
482
 
483
 
484
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
485
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
486
	// Par exemple, la variable pour "nva" ?
487
	function getNomCommun($obs) {
488
		$langue = 'fra';
489
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
490
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
491
		else return '';
492
 
493
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 494
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 495
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 496
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 497
		}
498
		// pas de cache:
499
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
500
 
501
		// pour bdtfx:
502
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
503
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
504
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
1656 raphael 505
						   Array($referentiel, $obs['nt'], $langue),
1657 raphael 506
						   self::$config['eflore']['url_service_nom_attribution']) . // TODO !
1656 raphael 507
			"&retour.champs=num_statut";
1654 aurelien 508
		$noms = @json_decode(file_get_contents($url));
509
		if(! $noms) return '';
1673 raphael 510
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
1654 aurelien 511
		$nom = array_pop($noms)->nom_vernaculaire;
512
 
513
		// cache
1657 raphael 514
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 515
		return $nom;
516
	}
517
 
1671 aurelien 518
	private function retournerNumStatutUn(&$item) {
519
		return ($item->num_statut == 1);
520
	}
1673 raphael 521
 
522
	private function retournerNumStatutUnArr(&$item) {
523
		return ($item['num_statut'] == 1);
524
	}
1671 aurelien 525
 
1656 raphael 526
	// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
527
	/* require_once('/home/raphael/eflore/framework/framework/Framework.php');
528
	Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
529
	Framework::setInfoAppli(Config::get('info'));
530
	require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
1654 aurelien 531
 
532
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
1656 raphael 533
	   NomsVernaculaires pour obtenir le nom commun */
1654 aurelien 534
	function getNomCommun_v2($obs) {
535
		static $service;
1656 raphael 536
		$service = new Projets();
1654 aurelien 537
 
538
		$langue = 'fra';
539
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
540
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
541
		else return '';
542
 
543
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 544
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 545
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 546
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 547
		}
548
		// pas de cache:
549
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
550
 
1656 raphael 551
		$donnees = Array('masque.nt' => $obs['nt'],
552
						 'masque.lg' => $langue,
553
						 'retour.champs' => 'num_statut');
1654 aurelien 554
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $donnees);
555
 
556
		if(! $noms) return '';
1673 raphael 557
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
1654 aurelien 558
		$nom = array_pop($noms)->nom_vernaculaire;
559
 
1656 raphael 560
		// cache
1657 raphael 561
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 562
		return $nom;
563
	}
564
 
565
 
566
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
1656 raphael 567
	   n'est pas aussi retentissant qu'espéré */
1654 aurelien 568
	static $service;
569
	function getNomCommun_v3($obs) {
570
		if(! $this->service) $this->service = new Projets();
571
 
572
		$langue = 'fra';
573
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
574
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
575
		else return '';
576
 
577
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 578
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 579
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 580
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 581
		}
582
		// pas de cache:
1656 raphael 583
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
1654 aurelien 584
 
585
		$donnees = Array('masque.nt' => $obs['nt'],
1656 raphael 586
						 'masque.lg' => $langue,
587
						 'retour.champs' => 'conseil_emploi');
588
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $donnees);
1654 aurelien 589
		try {
1656 raphael 590
			$noms = $this->service->traiterRessources();
591
		} catch(Exception $e) {
592
			return '';
1654 aurelien 593
		}
1656 raphael 594
		if(! $noms) return '';
1673 raphael 595
		$noms = array_filter($noms['resultat'], array($this, retournerNumStatutUnArr)); // XXX: php 5.3
1656 raphael 596
		$premier_nom = array_pop($noms);
1654 aurelien 597
		$nom = $premier_nom['nom_vernaculaire'];
598
 
599
		// cache
1657 raphael 600
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 601
		return $nom;
602
	}
1685 raphael 603
 
1694 raphael 604
	/* Cette fonction initialise le cache des noms communs en 1 fois, sur la liste des observations à exporter.
1702 raphael 605
	   Ainsi, les appels successifs à getNomCommun_v4() ne sont pas couteux (pas de requête SQL) */
1694 raphael 606
	static function getNomCommun_preload($cel, $obsids) {
607
		if(!$obsids) return;
1765 raphael 608
		if(!self::referenceTableExiste()) return NULL;
1694 raphael 609
 
610
		// CREATE INDEX i_nom_referentiel ON cel_obs (nom_referentiel(5));
611
		$req = sprintf("SELECT r.referentiel, r.num_taxon, r.nom_commun FROM cel_references r" .
612
					   " INNER JOIN cel_obs c ON (r.referentiel = substring_index(c.nom_referentiel, ':', 1) and r.num_taxon = c.nt)" .
613
					   " WHERE c.id_observation IN (%s)",
614
					   implode(',', $obsids));
1765 raphael 615
		$res = Cel::db()->requeter($req);
1694 raphael 616
		foreach($res as $v) {
617
			self::$cache['getNomCommun'][$v['referentiel'] . '-' . $v['num_taxon'] . '-' . 'fra'] = $v['nom_commun'];
618
		}
619
		return NULL;
620
	}
1702 raphael 621
 
1765 raphael 622
	static function referenceTableExiste() {
1702 raphael 623
		if(!self::$is_table) {
624
			// une seule fois
1765 raphael 625
			if(! Cel::db()->executerRequete("SHOW TABLES LIKE 'cel_references'", Cel::SQL_RETOUR_LIGNE)) return FALSE;
1702 raphael 626
			self::$is_table = TRUE;
627
		}
628
		return TRUE;
629
	}
1694 raphael 630
 
1765 raphael 631
	static function getNomCommun_v4($obs) {
1685 raphael 632
		if(! $obs['nt']) return NULL;
1765 raphael 633
		if(! self::referenceTableExiste()) return NULL;
1689 raphael 634
 
1685 raphael 635
		$langue = 'fra';
636
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
637
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
638
 
1757 raphael 639
		// cache:
640
		if(isset($cache['getNomCommun'])) {
641
			if(isset(self::$cache['getNomCommun'][$cache_id])) return self::$cache['getNomCommun'][$cache_id];
642
			// XXX: problème de valeurs NULL ?
643
			if(array_key_exists($cache_id, self::$cache['getNomCommun'])) return self::$cache['getNomCommun'][$cache_id];
644
		}
1685 raphael 645
 
646
		// pas de cache:
1765 raphael 647
		$nom = Cel::db()->executerRequete(sprintf("SELECT nom_commun FROM cel_references " .
648
												  "WHERE referentiel = '%s' AND num_taxon = %d LIMIT 1",
649
												  $referentiel,
650
												  $obs['nt']),
651
										  Cel::SQL_RETOUR_LIGNE);
1685 raphael 652
 
653
		if(! $nom) return NULL;
654
		$nom = $nom["nom_commun"];
655
 
656
		// cache
657
		self::$cache['getNomCommun'][$cache_id] = $nom;
658
		return $nom;
659
	}
1702 raphael 660
 
661
 
662
	/* Cette fonction initialise le cache des données baseflor en 1 fois, sur la liste des observations à exporter.
663
	   Ainsi, les appels successifs à baseflor_ligne() ne sont pas couteux (pas de requête SQL) */
664
	static function baseflor_preload($cel, $obsids) {
665
		if(!$obsids) return;
1765 raphael 666
		if(!self::referenceTableExiste()) return NULL;
1702 raphael 667
 
668
		$req = sprintf("SELECT referentiel, num_nom_retenu, %s FROM cel_references r" .
669
					   " INNER JOIN cel_obs c ON (r.num_nom_retenu = c.nom_ret_nn)" .
670
					   " WHERE c.id_observation IN (%s)",
671
					   //" AND catminat_code IS NOT NULL", // TODO: suppression des NULL ici signifie que le cache sera partiel...
672
					   implode(',', array_keys(self::$baseflor_col)),
673
					   implode(',', $obsids));
1765 raphael 674
		$res = Cel::db()->requeter($req);
1706 raphael 675
		if(!$res) return NULL;
1702 raphael 676
 
677
		foreach($res as $v) {
678
			$data = $v;
679
			unset($data['referentiel']); // non nécessaire
680
			unset($data['num_nom_retenu']); // non nécessaire
681
			self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']] = $data;
682
		}
683
 
684
		return NULL;
685
	}
1654 aurelien 686
 
1685 raphael 687
 
1765 raphael 688
	static function baseflor_ligne($obs, &$ligne) {
1702 raphael 689
		if(! $obs['nom_ret_nn']) {
1706 raphael 690
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
1702 raphael 691
			return;
692
		}
693
 
1765 raphael 694
		if(! self::referenceTableExiste()) {
1706 raphael 695
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
1702 raphael 696
			return;
697
		}
698
 
699
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
700
		$cache_id = $referentiel . '-' . $obs['nom_ret_nn'];
701
 
702
		// XXX: problème de valeurs NULL pour utiliser simplement isset() ?
703
		// @ car getBaseflor[] n'est peut-être pas encore initialisé
704
		if(@array_key_exists($cache_id, self::$cache['getBaseflor'])) {
705
			$ligne = array_merge($ligne, self::$cache['getBaseflor'][$cache_id]);
706
			return;
707
		}
708
 
709
		// pas de cache:
1765 raphael 710
		$data = Cel::db()->executerRequete(sprintf("SELECT %s FROM cel_references " .
1702 raphael 711
											 "WHERE referentiel = '%s' AND num_nom_retenu = %d LIMIT 1",
712
											 implode(', ', array_keys(self::$baseflor_col)),
713
											 $referentiel,
714
											 $obs['nom_ret_nn']),
715
									 Cel::SQL_RETOUR_LIGNE);
716
 
717
		if(! $data) {
1706 raphael 718
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
1702 raphael 719
			return;
720
		}
721
 
722
		// cache
723
		self::$cache['getBaseflor'][$cache_id] = $data;
724
		$ligne = array_merge($ligne, $data);
725
	}
1715 raphael 726
 
727
	static function champsEtendus_preload($cel, $obsids) {
728
		$gestion_champs_etendus = new GestionChampsEtendus($cel->config, 'obs');
1718 raphael 729
		$colonnes_champs_supp_par_obs = $gestion_champs_etendus->consulterClesParLots($obsids);
1741 raphael 730
		// ces deux lignes réordonnent l'ordre des colonnes des champs étendus en fonction de l'ordre (très spécifique)
731
		// de self::$ordre_champ_etendus_Florileges, les champs non-mentionnés sont ajoutés à la fin.
732
		$colonnes_champs_supp_par_obs = self::sortArrayByArray(array_flip($colonnes_champs_supp_par_obs),
733
															   self::$ordre_champ_etendus_Florileges);
734
		$colonnes_champs_supp_par_obs = array_keys($colonnes_champs_supp_par_obs);
735
 
1718 raphael 736
		// si le SELECT des clefs ne retourne rien, une autre requêtes est inutile
737
		// TODO: optimize, 1 seule requête
738
		if(!$colonnes_champs_supp_par_obs) return Array('header' => array(), 'data' => array());
739
 
1715 raphael 740
		$champs_supp_par_obs = $gestion_champs_etendus->consulterParLots($obsids);
1741 raphael 741
 
1715 raphael 742
		self::$cache['champsEtendus']['header'] = $colonnes_champs_supp_par_obs;
743
		foreach($champs_supp_par_obs as &$v) {
744
			$v = self::champsEtendus_aplatir($v);
745
		}
746
		self::$cache['champsEtendus']['data'] = $champs_supp_par_obs;
747
		// ce return est temporaire,
748
		// le temps que toutes les fonctions bougent ici et utilise plutôt le cache statique
1716 raphael 749
		// encore utilisé pour les entêtes (self::$cache['champsEtendus']['header'])
1715 raphael 750
		return self::$cache['champsEtendus'];
751
	}
752
 
753
	// XXX: PHP-5.3, fonction anonyme + array_map
754
	static function champsEtendus_aplatir($ligne_champs_etendus) {
755
		$champs_etendus_fmt = array();
756
		if(!$ligne_champs_etendus) return $champs_etendus_fmt;
757
		foreach($ligne_champs_etendus as $champ) {
758
			$champs_etendus_fmt[$champ->cle] = $champ->valeur;
759
		}
760
		return $champs_etendus_fmt;
761
	}
1716 raphael 762
 
1765 raphael 763
	static function champsEtendus_ligne($obs, &$ligne) {
1716 raphael 764
		// si header n'est pas défini, aucune observation ne possède de champ étendu
765
		// et nous n'ajoutons ni colonnes, ni valeurs.
766
		if(! isset(self::$cache['champsEtendus']['header'])) return;
1736 raphael 767
		$ligne_etendue_aplatie = @self::$cache['champsEtendus']['data'][$obs['id_observation']];
1716 raphael 768
 
769
		$ligne_supp = array_fill(0, count(self::$cache['champsEtendus']['header']), '');
770
		$ligne_etendue_fmt = array();
771
 
772
		// si, cependant cette seule observation n'a pas de champs étendus,
773
		// nous devons rajouter des blancs (notamment dans le cas ou d'autres
774
		// champs viennent à être ajoutés en aval à l'avenir
775
		// cf: $fonction_dynamique dans FormateurGroupeColonne::GenColInfo()
776
		if(! $ligne_etendue_aplatie) {
777
			$ligne = array_merge($ligne, $ligne_supp);
778
			return;
779
		}
780
 
781
		foreach(self::$cache['champsEtendus']['header'] as $colonne) {
782
			if(!isset($ligne_etendue_aplatie[$colonne])) {
783
				$ligne_etendue_fmt[$colonne] = '';
784
			} else {
785
				$ligne_etendue_fmt[$colonne] = $ligne_etendue_aplatie[$colonne];
786
			}
787
		}
788
 
789
		// XXX/ array_merge() ?
790
		$ligne += $ligne_etendue_fmt;
791
	}
1741 raphael 792
 
793
	/* HELPERS */
794
 
795
	// http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
796
	// XXX; redéfinition, utilisé aussi par ExportXLS
797
	static function sortArrayByArray($array, $orderArray) {
798
		$ordered = array();
799
		foreach($orderArray as $key) {
800
			if(array_key_exists($key, $array)) {
801
				$ordered[$key] = $array[$key];
802
				unset($array[$key]);
803
			}
804
		}
805
		return $ordered + $array;
806
	}
807
 
1715 raphael 808
}