Subversion Repositories eFlore/Applications.cel

Rev

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