Subversion Repositories eFlore/Applications.cel

Rev

Rev 1736 | Rev 1754 | 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
*/
11
define('SEPARATEUR_IMAGES', ",");
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
	*
1714 raphael 100
	* @TODO: noms communs à part, gestion des champs étendus
1654 aurelien 101
	*
102
	*/
103
	static function nomEnsembleVersListeColonnes($groupe_de_champs = 'standard') {
104
		if(! $groupe_de_champs) $groupe_de_champs = 'standard';
1711 raphael 105
		if(is_string($groupe_de_champs)) {
106
			$groupe_de_champs = array_flip(explode(',', $groupe_de_champs));
107
		}
108
		elseif(is_array($groupe_de_champs)) {
109
			$groupe_de_champs = array_flip($groupe_de_champs);
110
		}
111
		else {
112
			return NULL;
113
		}
1714 raphael 114
		$groupe_de_champs = array_intersect_key(array_flip(self::$fieldGroups),
1711 raphael 115
												$groupe_de_champs);
116
		if(!$groupe_de_champs) return NULL;
117
 
1656 raphael 118
		$colonnes = Array();
1654 aurelien 119
 
120
		if(isset($groupe_de_champs['standard'])) {
121
			$colonnes += Array(
122
				'nom_sel'			=> self::GenColInfo('nom_sel', 'Espèce'),
123
				'nom_sel_nn'		=> self::GenColInfo('nom_sel_nn', 'Numéro nomenclatural', 0, NULL, NULL, FALSE),
1656 raphael 124
				'nom_ret'			=> self::GenColInfo('nom_ret', 'Nom retenu', 0, NULL, NULL, FALSE),
125
				'nom_ret_nn'		=> self::GenColInfo('nom_ret_nn', 'Numéro nomenclatural nom retenu', 0, NULL, NULL, FALSE),
126
				'nt'				=> self::GenColInfo('nt', 'Numéro taxonomique', 0, NULL, NULL, FALSE),
127
				'famille'			=> self::GenColInfo('famille', 'Famille', 0, NULL, NULL, FALSE),
128
				'nom_referentiel'	=> self::GenColInfo('nom_referentiel', 'Referentiel taxonomique'),
129
				'zone_geo'			=> self::GenColInfo('zone_geo', 'Commune'),
1654 aurelien 130
				'ce_zone_geo'		=> self::GenColInfo('ce_zone_geo', 'Identifiant Commune', 0, 'convertirCodeZoneGeoVersDepartement'),
1656 raphael 131
				'date_observation'	=> self::GenColInfo('date_observation', 'Date', 0, 'formaterDate'),
132
				'lieudit'			=> self::GenColInfo('lieudit', 'Lieu-dit'),
133
				'station'			=> self::GenColInfo('station', 'Station'),
134
				'milieu'			=> self::GenColInfo('milieu', 'Milieu'),
135
				'commentaire'		=> self::GenColInfo('commentaire', 'Notes'),
136
				'latitude'			=> self::GenColInfo('latitude', 'Latitude', 1),
1654 aurelien 137
				'longitude'			=> self::GenColInfo('longitude', 'Longitude', 1),
1699 raphael 138
				'altitude'			=> self::GenColInfo('altitude', 'Altitude', 1),
1654 aurelien 139
				'geodatum'			=> self::GenColInfo('geodatum', 'Référentiel Géographique', 1, NULL, NULL, FALSE),
140
			);
141
		}
142
 
143
		if(isset($groupe_de_champs['avance'])) {
1656 raphael 144
			$colonnes += array(
145
			   // TODO: importable = FALSE car pas de merge de données importées
146
			   'ordre'				=> self::GenColInfo('ordre', 'Ordre', 1, NULL, NULL, FALSE),
147
			   'id_observation'		=> self::GenColInfo('id_observation', 'Identifiant', 1, NULL, NULL, FALSE),
148
 
149
			   'mots_cles_texte'	=> self::GenColInfo('mots_cles_texte', 'Mots Clés', 1),
150
			   'commentaire'		=> self::GenColInfo('commentaire', 'Commentaires', 1),
151
			   'date_creation'		=> self::GenColInfo('date_creation', 'Date Création', 1, NULL, NULL, FALSE),
152
			   'date_modification'	=> self::GenColInfo('date_modification', 'Date Modification', 1, NULL, NULL, FALSE),
153
 
154
			   // rappel transmission = 1, signifie simplement "public"
155
			   // des données importées peuvent être d'emblée "publiques"
156
			   // "importable" = TRUE
157
			   'transmission'		=> self::GenColInfo('transmission', 'Transmis', 1),
158
			   'date_transmission'	=> self::GenColInfo('date_transmission', 'Date Transmission', 1, NULL, NULL, FALSE),
159
			   'abondance'			=> self::GenColInfo('abondance', 'Abondance', 1),
160
			   'certitude'			=> self::GenColInfo('certitude', 'Certitude', 1),
161
			   'phenologie'			=> self::GenColInfo('phenologie', 'Phénologie', 1),
162
 
163
			   // XXX: getImages() dépend du contexte de Cel, et doit être appelée comme cas particulier
164
			   // cf ExportXLS::traiterLigneObservation()
1687 raphael 165
			   'images'				=> self::GenColInfo('images', 'Image(s)', 1, NULL, NULL /* cas particulier 'getImages' */, TRUE),
1685 raphael 166
 
167
			   /* 'nom_commun'			=> self::GenColInfo('nom_commun', 'Nom Commun', 1, NULL, 'getNomCommun', FALSE),
168
				  'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun_v2'),
169
				  'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun_v3'), */
1702 raphael 170
			   'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, NULL /* cas particu 'getNomCommun_v4' */, TRUE, array(__CLASS__, 'getNomCommun_preload')),
171
			);
172
		}
1685 raphael 173
 
1702 raphael 174
		if(isset($groupe_de_champs['baseflor'])) {
175
			$colonnes += array(
176
				// champ dynamique
177
				'baseflor'			=> self::GenColInfo('baseflor', '', 1, NULL, NULL, FALSE, array(__CLASS__, 'baseflor_preload'), array(__CLASS__, 'baseflor_ligne')),
1654 aurelien 178
			);
1702 raphael 179
		}
1656 raphael 180
 
1714 raphael 181
		if(isset($groupe_de_champs['etendu'])) {
182
			$colonnes += array(
183
				// champ dynamique
1716 raphael 184
				'etendu'			=> self::GenColInfo('etendu', '', 1, NULL, NULL, FALSE, array(__CLASS__, 'champsEtendus_preload'), array(__CLASS__, 'champsEtendus_ligne')),
1714 raphael 185
			);
186
		}
187
 
1654 aurelien 188
		return $colonnes;
189
	}
1694 raphael 190
 
191
	static function preload($colonnes, $cel, $ids) {
192
		$result = array();
193
		foreach($colonnes as $abbrev => $colonne) {
194
			if(!$colonne['preload']) continue;
1702 raphael 195
			$result[$abbrev] = call_user_func($colonne['preload'], $cel, $ids);
1694 raphael 196
		}
197
		return $result;
198
	}
1654 aurelien 199
 
1656 raphael 200
	public static function getIntitulesColonnes($colonnes) {
1702 raphael 201
		// array_filter pour supprimer les colonnes "dynamique" n'ayant pas défini $nom (cf GenColInfo())
202
		return array_filter(array_map(array('FormateurGroupeColonne', 'retournerNomItem'), $colonnes));
1654 aurelien 203
	}
204
 
1671 aurelien 205
	public static function retournerNomItem(&$item) {
206
		return $item['nom'];
207
	}
1694 raphael 208
 
1656 raphael 209
	public static function getLigneObservation(&$obs, &$colonnes, $cel = false) {
1659 aurelien 210
 
1654 aurelien 211
		$ligne_formatee = array();
212
		foreach($colonnes as $abbrev => $colonne) {
213
			$valeur = null;
1702 raphael 214
			if($colonne['extra'] == 2 || ! is_null($colonne['dyna'])) continue;
1654 aurelien 215
 
216
			// valeur direct depuis cel_obs ?
217
			if(isset($obs[$abbrev])) $valeur = $obs[$abbrev];
218
 
219
			// pré-processeur de la champs
220
			if(function_exists($colonne['fonction'])) {
221
				$valeur = $colonne['fonction']($valeur);
222
			} elseif(method_exists(__CLASS__, $colonne['fonction'])) {
223
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
224
			} elseif($colonne['fonction']) {
225
				die("méthode {$colonne['fonction']} introuvable");
226
			}
227
			// fonction pour obtenir des champs (étendus)
228
			elseif(function_exists($colonne['fonction_data'])) {
229
				$valeur = $colonne['fonction_data']($obs);
230
			}
1687 raphael 231
			elseif(method_exists(__CLASS__, $colonne['fonction_data'])) {
1654 aurelien 232
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
233
			}
234
 
235
			// // cette section devrait être vide:
236
			// // cas particuliers ingérable avec l'architecture actuelle:
237
			if(false && $abbrev == 'date_observation' && $valeur == "0000-00-00") {
238
				/* blah */
239
			}
1685 raphael 240
			// ici à cause du passage de $cel ($this), TODO: DB en Singleton !
1656 raphael 241
			if($abbrev == 'images') {
242
				$valeur = FormateurGroupeColonne::getImages($obs, $cel->id_utilisateur, $cel);
243
			}
1685 raphael 244
			if($abbrev == 'nom-commun') {
245
				$valeur = FormateurGroupeColonne::getNomCommun_v4($obs, $cel);
246
			}
1654 aurelien 247
 
248
			if($valeur == null) {
249
				$valeur = "";
250
			}
251
 
252
			// // fin de section "cas particuliers"
253
			$ligne_formatee[] = $valeur;
254
		}
1694 raphael 255
 
1702 raphael 256
		// uniquement les champŝ dynamiques
257
		foreach($colonnes as $abbrev => $colonne) {
258
			$valeur = null;
259
			if(is_null($colonne['dyna'])) continue;
1706 raphael 260
			// XXX: PHP-5.3
261
			call_user_func_array($colonne['dyna'],
262
								 array($cel, $obs, &$ligne_formatee));
1702 raphael 263
		}
1694 raphael 264
 
1654 aurelien 265
		return $ligne_formatee;
266
	}
267
 
268
	/*
269
	* Wrapper générant un tableau associatif:
1694 raphael 270
	* Ne pas changer les valeurs par défaut du prototype sans réflexion sur l'implication pour nomEnsembleVersListeColonnes()
1654 aurelien 271
 
272
	* @param $abbrev (obligatoire): nom court de colonne, largement utilisé lors de l'import.
273
	*		  En effet chaque ligne importée est accessible à l'aide du `define` de $abbrev en majuscule, préfixé de "C_"
274
	*		  Exemple: $ligne[C_LONGITUDE] pour "longitude".
275
	*		  cf: ImportXLS::detectionEntete()
276
 
277
	* @param $nom (obligatoire): nom complet de colonne (utilisé pour la ligne d'en-tête)
1702 raphael 278
	*		  Les définition de champs dynamique (correspondant à de multiples colonnes) doivent laisser cette valeur
279
	*		  vide afin de ne pas créer une colonne supplémentaire erronée.
1654 aurelien 280
 
281
	* @param $is_extra:
282
	* Si 0, la colonne est une colonne standard
283
	* Si 1, la colonne est extra [le plus souvent générée automatiquement]
284
	*		 (auquel cas une bordure bleue entoure son nom dans la ligne d'entête)
285
	* Si 2, la colonne n'est pas traité à l'export, mais une définition peut lui être donnée
286
	*		 qui pourra être utilisée à l'import, exemple: "image"
287
 
288
	* @param $fonction (optionnel): un nom d'un fonction de préprocessing
289
	* 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
290
 
291
	* @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
292
	* 		  $fonction_data doit prendre comme premier argument le tableau des champs de l'enregistrement existant
293
	*		  $fonction_data doit retourner une valeur
294
 
295
	* @param $importable (optionnel): défini si la colonne est traitée (ou absolument ignorée par PHPExcel) lors de
296
	*		  l'import.
1694 raphael 297
 
298
	* @param $preload (optionnel): défini une fonction de préchargement massif de donnée potentiellement utilisable par $fonction_data.
299
	*		  Utile, notamment, dans le cadre de l'export
1702 raphael 300
 
301
	* @param $fonction_dynamique (optionnel): défini une fonction ajoutant un nombre arbitraire de colonnes à une ligne donnée
302
	*		  Utile, notamment, dans le cadre de l'export des champs étendus ou des données baseflor
303
	*		  La fonction doit TOUJOURS alterer la ligne en lui ajoutant une nombre CONSTANT d'éléments (NULL ou non)
304
	*		  La fonction doit prendre comme arguments ($cel, $obs, &$ligne_formatee)
1654 aurelien 305
	*/
1702 raphael 306
	static function GenColInfo($abbrev, $nom, $is_extra = 0, $fonction = NULL, $fonction_data = NULL, $importable = TRUE, $preload = NULL, $fonction_dynamique = NULL) {
1654 aurelien 307
		return Array('abbrev' => $abbrev,
1656 raphael 308
					 'nom' => $nom,
309
					 'extra' => $is_extra ? 1 : 0,
310
					 'fonction' => $fonction,
311
					 'fonction_data' => $fonction_data,
1694 raphael 312
					 'importable' => $importable,
313
					 'preload' => $preload,
1702 raphael 314
					 'dyna' => $fonction_dynamique,
1654 aurelien 315
		);
316
	}
317
 
1656 raphael 318
	static function formaterDate($date_heure_mysql) {
1671 aurelien 319
		//return "";
1707 raphael 320
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") return NULL;
1671 aurelien 321
		// malheureusement pas disponible en php < 5.3
322
		//$date_format = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql);
323
		$val = explode(' ', $date_heure_mysql);
324
		$date = explode('-', $val[0]);
325
		$heure = explode(':', $val[1]);
326
		$timestamp = mktime((int) $heure[0], (int) $heure[1], (int) $heure[2], (int) $date[1], (int) $date[2], (int) $date[0]);
1707 raphael 327
		if(!$timestamp) return NULL;
1656 raphael 328
		// TODO: les widgets ne font malheureusement pas usage de l'heure dans le CEL
329
		// TODO: si modification, ne pas oublier de modifier le format d'import correspondant
1698 raphael 330
		//	dans ImportXLS, traiterDateObs() (actuellement: "Y/m/d" car utilisation de strtotime() qui ne lit pas tout)
331
		// $date_formatee = strftime('%d/%m/%Y', $timestamp);
332
		$date_formatee = strftime('%Y/%m/%d', $timestamp);
1654 aurelien 333
		if(!$date_formatee) return "00/00/0000";
334
		return $date_formatee;
335
	}
336
 
1656 raphael 337
	static function getImages($obs, $id_utilisateur, $cel) {
338
		if(! $id_utilisateur) return NULL;
339
		$rec = $cel->requeter(
1654 aurelien 340
			sprintf("SELECT GROUP_CONCAT(nom_original SEPARATOR '%s') FROM cel_images i"
1656 raphael 341
					." LEFT JOIN cel_obs_images oi ON (i.id_image = oi.id_image)"
342
					." LEFT JOIN cel_obs o ON (oi.id_observation = o.id_observation)"
343
					." WHERE ce_utilisateur = %d",
344
					SEPARATEUR_IMAGES,
345
					$id_utilisateur));
346
		return $rec ? array_pop($rec) : NULL;
1654 aurelien 347
	}
348
 
349
	public static function convertirCodeZoneGeoVersDepartement($code_zone_geo) {
350
		$code_departement = '';
351
		if(self::estUnCodeInseeDepartement($code_zone_geo)) {
352
			$code_departement = substr(ltrim($code_zone_geo,'INSEE-C:'),0,2);
353
		}
354
 
355
		return $code_departement;
356
	}
357
 
358
	public static function estUnCodeInseeDepartement($code_a_tester) {
359
		return preg_match('/^INSEE-C:[0-9]{5}/',$code_a_tester);
360
	}
361
 
362
 
363
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
364
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
365
	// Par exemple, la variable pour "nva" ?
366
	function getNomCommun($obs) {
367
		$langue = 'fra';
368
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
369
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
370
		else return '';
371
 
372
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 373
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 374
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 375
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 376
		}
377
		// pas de cache:
378
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
379
 
380
		// pour bdtfx:
381
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
382
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
383
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
1656 raphael 384
						   Array($referentiel, $obs['nt'], $langue),
1657 raphael 385
						   self::$config['eflore']['url_service_nom_attribution']) . // TODO !
1656 raphael 386
			"&retour.champs=num_statut";
1654 aurelien 387
		$noms = @json_decode(file_get_contents($url));
388
		if(! $noms) return '';
1673 raphael 389
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
1654 aurelien 390
		$nom = array_pop($noms)->nom_vernaculaire;
391
 
392
		// cache
1657 raphael 393
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 394
		return $nom;
395
	}
396
 
1671 aurelien 397
	private function retournerNumStatutUn(&$item) {
398
		return ($item->num_statut == 1);
399
	}
1673 raphael 400
 
401
	private function retournerNumStatutUnArr(&$item) {
402
		return ($item['num_statut'] == 1);
403
	}
1671 aurelien 404
 
1656 raphael 405
	// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
406
	/* require_once('/home/raphael/eflore/framework/framework/Framework.php');
407
	Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
408
	Framework::setInfoAppli(Config::get('info'));
409
	require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
1654 aurelien 410
 
411
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
1656 raphael 412
	   NomsVernaculaires pour obtenir le nom commun */
1654 aurelien 413
	function getNomCommun_v2($obs) {
414
		static $service;
1656 raphael 415
		$service = new Projets();
1654 aurelien 416
 
417
		$langue = 'fra';
418
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
419
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
420
		else return '';
421
 
422
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 423
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 424
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 425
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 426
		}
427
		// pas de cache:
428
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
429
 
1656 raphael 430
		$donnees = Array('masque.nt' => $obs['nt'],
431
						 'masque.lg' => $langue,
432
						 'retour.champs' => 'num_statut');
1654 aurelien 433
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $donnees);
434
 
435
		if(! $noms) return '';
1673 raphael 436
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
1654 aurelien 437
		$nom = array_pop($noms)->nom_vernaculaire;
438
 
1656 raphael 439
		// cache
1657 raphael 440
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 441
		return $nom;
442
	}
443
 
444
 
445
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
1656 raphael 446
	   n'est pas aussi retentissant qu'espéré */
1654 aurelien 447
	static $service;
448
	function getNomCommun_v3($obs) {
449
		if(! $this->service) $this->service = new Projets();
450
 
451
		$langue = 'fra';
452
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
453
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
454
		else return '';
455
 
456
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 457
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 458
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 459
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 460
		}
461
		// pas de cache:
1656 raphael 462
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
1654 aurelien 463
 
464
		$donnees = Array('masque.nt' => $obs['nt'],
1656 raphael 465
						 'masque.lg' => $langue,
466
						 'retour.champs' => 'conseil_emploi');
467
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $donnees);
1654 aurelien 468
		try {
1656 raphael 469
			$noms = $this->service->traiterRessources();
470
		} catch(Exception $e) {
471
			return '';
1654 aurelien 472
		}
1656 raphael 473
		if(! $noms) return '';
1673 raphael 474
		$noms = array_filter($noms['resultat'], array($this, retournerNumStatutUnArr)); // XXX: php 5.3
1656 raphael 475
		$premier_nom = array_pop($noms);
1654 aurelien 476
		$nom = $premier_nom['nom_vernaculaire'];
477
 
478
		// cache
1657 raphael 479
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 480
		return $nom;
481
	}
1685 raphael 482
 
1694 raphael 483
	/* Cette fonction initialise le cache des noms communs en 1 fois, sur la liste des observations à exporter.
1702 raphael 484
	   Ainsi, les appels successifs à getNomCommun_v4() ne sont pas couteux (pas de requête SQL) */
1694 raphael 485
	static function getNomCommun_preload($cel, $obsids) {
486
		if(!$obsids) return;
1702 raphael 487
		if(!self::referenceTableExiste($cel)) return NULL;
1694 raphael 488
 
489
		// CREATE INDEX i_nom_referentiel ON cel_obs (nom_referentiel(5));
490
		$req = sprintf("SELECT r.referentiel, r.num_taxon, r.nom_commun FROM cel_references r" .
491
					   " INNER JOIN cel_obs c ON (r.referentiel = substring_index(c.nom_referentiel, ':', 1) and r.num_taxon = c.nt)" .
492
					   " WHERE c.id_observation IN (%s)",
493
					   implode(',', $obsids));
494
		$res = $cel->requeter($req);
495
		foreach($res as $v) {
496
			self::$cache['getNomCommun'][$v['referentiel'] . '-' . $v['num_taxon'] . '-' . 'fra'] = $v['nom_commun'];
497
		}
498
		return NULL;
499
	}
1702 raphael 500
 
501
	static function referenceTableExiste($cel) {
502
		if(!self::$is_table) {
503
			// une seule fois
504
			if(! $cel->executerRequete("SHOW TABLES LIKE 'cel_references'", Cel::SQL_RETOUR_LIGNE)) return FALSE;
505
			self::$is_table = TRUE;
506
		}
507
		return TRUE;
508
	}
1694 raphael 509
 
1685 raphael 510
	static function getNomCommun_v4($obs, $cel) {
511
		if(! $obs['nt']) return NULL;
1702 raphael 512
		if(! self::referenceTableExiste($cel)) return NULL;
1689 raphael 513
 
1685 raphael 514
		$langue = 'fra';
515
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
516
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
517
 
518
		if(isset(self::$cache['getNomCommun'][$cache_id])) return self::$cache['getNomCommun'][$cache_id];
1695 raphael 519
		// XXX: problème de valeurs NULL ?
520
		if(array_key_exists($cache_id, self::$cache['getNomCommun'])) return self::$cache['getNomCommun'][$cache_id];
1685 raphael 521
 
522
		// pas de cache:
523
		$nom = $cel->executerRequete(sprintf("SELECT nom_commun FROM cel_references " .
524
											 "WHERE referentiel = '%s' AND num_taxon = %d LIMIT 1",
525
											 $referentiel,
526
											 $obs['nt']),
527
									 Cel::SQL_RETOUR_LIGNE);
528
 
529
		if(! $nom) return NULL;
530
		$nom = $nom["nom_commun"];
531
 
532
		// cache
533
		self::$cache['getNomCommun'][$cache_id] = $nom;
534
		return $nom;
535
	}
1702 raphael 536
 
537
 
538
	/* Cette fonction initialise le cache des données baseflor en 1 fois, sur la liste des observations à exporter.
539
	   Ainsi, les appels successifs à baseflor_ligne() ne sont pas couteux (pas de requête SQL) */
540
	static function baseflor_preload($cel, $obsids) {
541
		if(!$obsids) return;
542
		if(!self::referenceTableExiste($cel)) return NULL;
543
 
544
		$req = sprintf("SELECT referentiel, num_nom_retenu, %s FROM cel_references r" .
545
					   " INNER JOIN cel_obs c ON (r.num_nom_retenu = c.nom_ret_nn)" .
546
					   " WHERE c.id_observation IN (%s)",
547
					   //" AND catminat_code IS NOT NULL", // TODO: suppression des NULL ici signifie que le cache sera partiel...
548
					   implode(',', array_keys(self::$baseflor_col)),
549
					   implode(',', $obsids));
550
		$res = $cel->requeter($req);
1706 raphael 551
		if(!$res) return NULL;
1702 raphael 552
 
553
		foreach($res as $v) {
554
			$data = $v;
555
			unset($data['referentiel']); // non nécessaire
556
			unset($data['num_nom_retenu']); // non nécessaire
557
			self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']] = $data;
558
		}
559
 
560
		return NULL;
561
	}
1654 aurelien 562
 
1685 raphael 563
 
1702 raphael 564
	static function baseflor_ligne($cel, $obs, &$ligne) {
565
		if(! $obs['nom_ret_nn']) {
1706 raphael 566
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
1702 raphael 567
			return;
568
		}
569
 
570
		if(! self::referenceTableExiste($cel)) {
1706 raphael 571
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
1702 raphael 572
			return;
573
		}
574
 
575
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
576
		$cache_id = $referentiel . '-' . $obs['nom_ret_nn'];
577
 
578
		// XXX: problème de valeurs NULL pour utiliser simplement isset() ?
579
		// @ car getBaseflor[] n'est peut-être pas encore initialisé
580
		if(@array_key_exists($cache_id, self::$cache['getBaseflor'])) {
581
			$ligne = array_merge($ligne, self::$cache['getBaseflor'][$cache_id]);
582
			return;
583
		}
584
 
585
		// pas de cache:
586
		$data = $cel->executerRequete(sprintf("SELECT %s FROM cel_references " .
587
											 "WHERE referentiel = '%s' AND num_nom_retenu = %d LIMIT 1",
588
											 implode(', ', array_keys(self::$baseflor_col)),
589
											 $referentiel,
590
											 $obs['nom_ret_nn']),
591
									 Cel::SQL_RETOUR_LIGNE);
592
 
593
		if(! $data) {
1706 raphael 594
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
1702 raphael 595
			return;
596
		}
597
 
598
		// cache
599
		self::$cache['getBaseflor'][$cache_id] = $data;
600
		$ligne = array_merge($ligne, $data);
601
	}
1715 raphael 602
 
603
	static function champsEtendus_preload($cel, $obsids) {
604
		$gestion_champs_etendus = new GestionChampsEtendus($cel->config, 'obs');
1718 raphael 605
		$colonnes_champs_supp_par_obs = $gestion_champs_etendus->consulterClesParLots($obsids);
1741 raphael 606
		// ces deux lignes réordonnent l'ordre des colonnes des champs étendus en fonction de l'ordre (très spécifique)
607
		// de self::$ordre_champ_etendus_Florileges, les champs non-mentionnés sont ajoutés à la fin.
608
		$colonnes_champs_supp_par_obs = self::sortArrayByArray(array_flip($colonnes_champs_supp_par_obs),
609
															   self::$ordre_champ_etendus_Florileges);
610
		$colonnes_champs_supp_par_obs = array_keys($colonnes_champs_supp_par_obs);
611
 
1718 raphael 612
		// si le SELECT des clefs ne retourne rien, une autre requêtes est inutile
613
		// TODO: optimize, 1 seule requête
614
		if(!$colonnes_champs_supp_par_obs) return Array('header' => array(), 'data' => array());
615
 
1715 raphael 616
		$champs_supp_par_obs = $gestion_champs_etendus->consulterParLots($obsids);
1741 raphael 617
 
1715 raphael 618
		self::$cache['champsEtendus']['header'] = $colonnes_champs_supp_par_obs;
619
		foreach($champs_supp_par_obs as &$v) {
620
			$v = self::champsEtendus_aplatir($v);
621
		}
622
		self::$cache['champsEtendus']['data'] = $champs_supp_par_obs;
623
		// ce return est temporaire,
624
		// le temps que toutes les fonctions bougent ici et utilise plutôt le cache statique
1716 raphael 625
		// encore utilisé pour les entêtes (self::$cache['champsEtendus']['header'])
1715 raphael 626
		return self::$cache['champsEtendus'];
627
	}
628
 
629
	// XXX: PHP-5.3, fonction anonyme + array_map
630
	static function champsEtendus_aplatir($ligne_champs_etendus) {
631
		$champs_etendus_fmt = array();
632
		if(!$ligne_champs_etendus) return $champs_etendus_fmt;
633
		foreach($ligne_champs_etendus as $champ) {
634
			$champs_etendus_fmt[$champ->cle] = $champ->valeur;
635
		}
636
		return $champs_etendus_fmt;
637
	}
1716 raphael 638
 
639
	static function champsEtendus_ligne($cel, $obs, &$ligne) {
640
		// si header n'est pas défini, aucune observation ne possède de champ étendu
641
		// et nous n'ajoutons ni colonnes, ni valeurs.
642
		if(! isset(self::$cache['champsEtendus']['header'])) return;
1736 raphael 643
		$ligne_etendue_aplatie = @self::$cache['champsEtendus']['data'][$obs['id_observation']];
1716 raphael 644
 
645
		$ligne_supp = array_fill(0, count(self::$cache['champsEtendus']['header']), '');
646
		$ligne_etendue_fmt = array();
647
 
648
		// si, cependant cette seule observation n'a pas de champs étendus,
649
		// nous devons rajouter des blancs (notamment dans le cas ou d'autres
650
		// champs viennent à être ajoutés en aval à l'avenir
651
		// cf: $fonction_dynamique dans FormateurGroupeColonne::GenColInfo()
652
		if(! $ligne_etendue_aplatie) {
653
			$ligne = array_merge($ligne, $ligne_supp);
654
			return;
655
		}
656
 
657
		foreach(self::$cache['champsEtendus']['header'] as $colonne) {
658
			if(!isset($ligne_etendue_aplatie[$colonne])) {
659
				$ligne_etendue_fmt[$colonne] = '';
660
			} else {
661
				$ligne_etendue_fmt[$colonne] = $ligne_etendue_aplatie[$colonne];
662
			}
663
		}
664
 
665
		// XXX/ array_merge() ?
666
		$ligne += $ligne_etendue_fmt;
667
	}
1741 raphael 668
 
669
	/* HELPERS */
670
 
671
	// http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
672
	// XXX; redéfinition, utilisé aussi par ExportXLS
673
	static function sortArrayByArray($array, $orderArray) {
674
		$ordered = array();
675
		foreach($orderArray as $key) {
676
			if(array_key_exists($key, $array)) {
677
				$ordered[$key] = $array[$key];
678
				unset($array[$key]);
679
			}
680
		}
681
		return $ordered + $array;
682
	}
683
 
1715 raphael 684
}