Subversion Repositories eFlore/Applications.cel

Rev

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