Subversion Repositories eFlore/Applications.cel

Rev

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