Subversion Repositories eFlore/Applications.cel

Rev

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