Subversion Repositories eFlore/Applications.cel

Rev

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