Subversion Repositories eFlore/Applications.cel

Rev

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