Subversion Repositories eFlore/Applications.cel

Rev

Rev 1657 | Rev 1671 | 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
 
12
define('SEPARATEUR_IMAGES', ",");
13
 
1654 aurelien 14
Class FormateurGroupeColonne {
1656 raphael 15
 
16
	static $cache = Array();
17
 
1654 aurelien 18
	/*
19
	* @param $fieldSets: un liste de noms de colonnes ou de sets de colonnes
20
	*		séparés par des virgules
21
	* 		eg: "espece" ou "champs-etendus", ...
22
	*
23
	* @return: un tableau associatif déjà ordonné
24
	* 		clé: abbrev [machine-name] de la colonne (eg: "espece" ou "mot-clef")
25
	* 		valeur: des données relative à cette colonne, cf GenColInfo
26
	*
27
	* @TODO: fonction commune à la génération en CSV
28
	*
29
	*/
30
	static function nomEnsembleVersListeColonnes($groupe_de_champs = 'standard') {
31
		if(! $groupe_de_champs) $groupe_de_champs = 'standard';
32
		$groupe_de_champs = array_flip(explode(',', $groupe_de_champs));
1656 raphael 33
		$colonnes = Array();
1654 aurelien 34
 
35
		if(isset($groupe_de_champs['standard'])) {
36
			$colonnes += Array(
37
				'nom_sel'			=> self::GenColInfo('nom_sel', 'Espèce'),
38
				'nom_sel_nn'		=> self::GenColInfo('nom_sel_nn', 'Numéro nomenclatural', 0, NULL, NULL, FALSE),
1656 raphael 39
				'nom_ret'			=> self::GenColInfo('nom_ret', 'Nom retenu', 0, NULL, NULL, FALSE),
40
				'nom_ret_nn'		=> self::GenColInfo('nom_ret_nn', 'Numéro nomenclatural nom retenu', 0, NULL, NULL, FALSE),
41
				'nt'				=> self::GenColInfo('nt', 'Numéro taxonomique', 0, NULL, NULL, FALSE),
42
				'famille'			=> self::GenColInfo('famille', 'Famille', 0, NULL, NULL, FALSE),
43
				'nom_referentiel'	=> self::GenColInfo('nom_referentiel', 'Referentiel taxonomique'),
44
				'zone_geo'			=> self::GenColInfo('zone_geo', 'Commune'),
1654 aurelien 45
				'ce_zone_geo'		=> self::GenColInfo('ce_zone_geo', 'Identifiant Commune', 0, 'convertirCodeZoneGeoVersDepartement'),
1656 raphael 46
				'date_observation'	=> self::GenColInfo('date_observation', 'Date', 0, 'formaterDate'),
47
				'lieudit'			=> self::GenColInfo('lieudit', 'Lieu-dit'),
48
				'station'			=> self::GenColInfo('station', 'Station'),
49
				'milieu'			=> self::GenColInfo('milieu', 'Milieu'),
50
				'commentaire'		=> self::GenColInfo('commentaire', 'Notes'),
51
				'latitude'			=> self::GenColInfo('latitude', 'Latitude', 1),
1654 aurelien 52
				'longitude'			=> self::GenColInfo('longitude', 'Longitude', 1),
53
				'geodatum'			=> self::GenColInfo('geodatum', 'Référentiel Géographique', 1, NULL, NULL, FALSE),
54
			);
55
		}
56
 
57
		if(isset($groupe_de_champs['avance'])) {
1656 raphael 58
			$colonnes += array(
59
			   // TODO: importable = FALSE car pas de merge de données importées
60
			   'ordre'				=> self::GenColInfo('ordre', 'Ordre', 1, NULL, NULL, FALSE),
61
			   'id_observation'		=> self::GenColInfo('id_observation', 'Identifiant', 1, NULL, NULL, FALSE),
62
 
63
			   'mots_cles_texte'	=> self::GenColInfo('mots_cles_texte', 'Mots Clés', 1),
64
			   'commentaire'		=> self::GenColInfo('commentaire', 'Commentaires', 1),
65
			   'date_creation'		=> self::GenColInfo('date_creation', 'Date Création', 1, NULL, NULL, FALSE),
66
			   'date_modification'	=> self::GenColInfo('date_modification', 'Date Modification', 1, NULL, NULL, FALSE),
67
 
68
			   // rappel transmission = 1, signifie simplement "public"
69
			   // des données importées peuvent être d'emblée "publiques"
70
			   // "importable" = TRUE
71
			   'transmission'		=> self::GenColInfo('transmission', 'Transmis', 1),
72
			   'date_transmission'	=> self::GenColInfo('date_transmission', 'Date Transmission', 1, NULL, NULL, FALSE),
73
			   'abondance'			=> self::GenColInfo('abondance', 'Abondance', 1),
74
			   'certitude'			=> self::GenColInfo('certitude', 'Certitude', 1),
75
			   'phenologie'			=> self::GenColInfo('phenologie', 'Phénologie', 1),
76
 
77
			   // XXX: getImages() dépend du contexte de Cel, et doit être appelée comme cas particulier
78
			   // cf ExportXLS::traiterLigneObservation()
79
			   'images'				=> self::GenColInfo('images', 'Image(s)', 1, NULL, 'getImages', TRUE),
1654 aurelien 80
			);
81
		}
1656 raphael 82
 
83
		/* 'nom_commun'			=> self::GenColInfo('nom_commun', 'Nom Commun', 1, NULL, 'getNomCommun', FALSE),
84
		   'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun_v2'),
85
		   'nom-commun'			=> self::GenColInfo('nom-commun', 'Nom Commun', 1, NULL, 'getNomCommun_v3'), */
86
 
1654 aurelien 87
		return $colonnes;
88
	}
89
 
1656 raphael 90
	public static function getIntitulesColonnes($colonnes) {
91
		return array_map(function($item) { return $item['nom']; }, $colonnes);
1654 aurelien 92
	}
93
 
1656 raphael 94
	public static function getLigneObservation(&$obs, &$colonnes, $cel = false) {
1659 aurelien 95
 
1654 aurelien 96
		$ligne_formatee = array();
97
		foreach($colonnes as $abbrev => $colonne) {
98
			$valeur = null;
99
			if($colonne['extra'] == 2) continue;
100
 
101
			// valeur direct depuis cel_obs ?
102
			if(isset($obs[$abbrev])) $valeur = $obs[$abbrev];
103
 
104
			// pré-processeur de la champs
105
			if(function_exists($colonne['fonction'])) {
106
				$valeur = $colonne['fonction']($valeur);
107
			} elseif(method_exists(__CLASS__, $colonne['fonction'])) {
108
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
109
			} elseif($colonne['fonction']) {
110
				die("méthode {$colonne['fonction']} introuvable");
111
			}
112
			// fonction pour obtenir des champs (étendus)
113
			elseif(function_exists($colonne['fonction_data'])) {
114
				$valeur = $colonne['fonction_data']($obs);
115
			}
1659 aurelien 116
			elseif($abbrev != 'images' && method_exists(__CLASS__, $colonne['fonction_data'])) {
1654 aurelien 117
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
118
			}
119
 
120
			// // cette section devrait être vide:
121
			// // cas particuliers ingérable avec l'architecture actuelle:
122
			if(false && $abbrev == 'date_observation' && $valeur == "0000-00-00") {
123
				/* blah */
124
			}
1656 raphael 125
			if($abbrev == 'images') {
126
				$valeur = FormateurGroupeColonne::getImages($obs, $cel->id_utilisateur, $cel);
127
			}
1654 aurelien 128
 
129
			if($valeur == null) {
130
				$valeur = "";
131
			}
132
 
133
			// // fin de section "cas particuliers"
134
			$ligne_formatee[] = $valeur;
135
		}
136
		return $ligne_formatee;
137
	}
138
 
139
	/*
140
	* Wrapper générant un tableau associatif:
141
 
142
	* @param $abbrev (obligatoire): nom court de colonne, largement utilisé lors de l'import.
143
	*		  En effet chaque ligne importée est accessible à l'aide du `define` de $abbrev en majuscule, préfixé de "C_"
144
	*		  Exemple: $ligne[C_LONGITUDE] pour "longitude".
145
	*		  cf: ImportXLS::detectionEntete()
146
 
147
	* @param $nom (obligatoire): nom complet de colonne (utilisé pour la ligne d'en-tête)
148
 
149
	* @param $is_extra:
150
	* Si 0, la colonne est une colonne standard
151
	* Si 1, la colonne est extra [le plus souvent générée automatiquement]
152
	*		 (auquel cas une bordure bleue entoure son nom dans la ligne d'entête)
153
	* Si 2, la colonne n'est pas traité à l'export, mais une définition peut lui être donnée
154
	*		 qui pourra être utilisée à l'import, exemple: "image"
155
 
156
	* @param $fonction (optionnel): un nom d'un fonction de préprocessing
157
	* 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
158
 
159
	* @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
160
	* 		  $fonction_data doit prendre comme premier argument le tableau des champs de l'enregistrement existant
161
	*		  $fonction_data doit retourner une valeur
162
 
163
	* @param $importable (optionnel): défini si la colonne est traitée (ou absolument ignorée par PHPExcel) lors de
164
	*		  l'import.
165
 
166
	*/
167
	static function GenColInfo($abbrev, $nom, $is_extra = 0, $fonction = NULL, $fonction_data = NULL, $importable = TRUE) {
168
		return Array('abbrev' => $abbrev,
1656 raphael 169
					 'nom' => $nom,
170
					 'extra' => $is_extra ? 1 : 0,
171
					 'fonction' => $fonction,
172
					 'fonction_data' => $fonction_data,
173
					 'importable' => $importable
1654 aurelien 174
		);
175
	}
176
 
1656 raphael 177
	static function formaterDate($date_heure_mysql) {
1654 aurelien 178
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") return "00/00/0000";
179
		$date_format = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql);
180
		$timestamp = @$date_format->getTimestamp();
181
		if(!$timestamp) return "00/00/0000";
1656 raphael 182
		// TODO: les widgets ne font malheureusement pas usage de l'heure dans le CEL
183
		// TODO: si modification, ne pas oublier de modifier le format d'import correspondant
184
		//	dans ImportXLS (actuellement: "d/m/Y")
185
		$date_formatee = strftime('%d/%m/%Y', $timestamp);
1654 aurelien 186
		if(!$date_formatee) return "00/00/0000";
187
		return $date_formatee;
188
	}
189
 
1656 raphael 190
	static function getImages($obs, $id_utilisateur, $cel) {
191
		if(! $id_utilisateur) return NULL;
192
		$rec = $cel->requeter(
1654 aurelien 193
			sprintf("SELECT GROUP_CONCAT(nom_original SEPARATOR '%s') FROM cel_images i"
1656 raphael 194
					." LEFT JOIN cel_obs_images oi ON (i.id_image = oi.id_image)"
195
					." LEFT JOIN cel_obs o ON (oi.id_observation = o.id_observation)"
196
					." WHERE ce_utilisateur = %d",
197
					SEPARATEUR_IMAGES,
198
					$id_utilisateur));
199
		return $rec ? array_pop($rec) : NULL;
1654 aurelien 200
	}
201
 
202
	public static function convertirCodeZoneGeoVersDepartement($code_zone_geo) {
203
		$code_departement = '';
204
		if(self::estUnCodeInseeDepartement($code_zone_geo)) {
205
			$code_departement = substr(ltrim($code_zone_geo,'INSEE-C:'),0,2);
206
		}
207
 
208
		return $code_departement;
209
	}
210
 
211
	public static function estUnCodeInseeDepartement($code_a_tester) {
212
		return preg_match('/^INSEE-C:[0-9]{5}/',$code_a_tester);
213
	}
214
 
215
 
216
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
217
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
218
	// Par exemple, la variable pour "nva" ?
219
	function getNomCommun($obs) {
220
		$langue = 'fra';
221
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
222
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
223
		else return '';
224
 
225
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 226
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 227
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 228
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 229
		}
230
		// pas de cache:
231
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
232
 
233
		// pour bdtfx:
234
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
235
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
236
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
1656 raphael 237
						   Array($referentiel, $obs['nt'], $langue),
1657 raphael 238
						   self::$config['eflore']['url_service_nom_attribution']) . // TODO !
1656 raphael 239
			"&retour.champs=num_statut";
1654 aurelien 240
		$noms = @json_decode(file_get_contents($url));
241
		if(! $noms) return '';
1656 raphael 242
		$noms = array_filter((array)($noms->resultat), function($item) { return ($item->num_statut == 1); });
1654 aurelien 243
		$nom = array_pop($noms)->nom_vernaculaire;
244
 
245
		// cache
1657 raphael 246
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 247
		return $nom;
248
	}
249
 
1656 raphael 250
	// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
251
	/* require_once('/home/raphael/eflore/framework/framework/Framework.php');
252
	Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
253
	Framework::setInfoAppli(Config::get('info'));
254
	require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
1654 aurelien 255
 
256
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
1656 raphael 257
	   NomsVernaculaires pour obtenir le nom commun */
1654 aurelien 258
	function getNomCommun_v2($obs) {
259
		static $service;
1656 raphael 260
		$service = new Projets();
1654 aurelien 261
 
262
		$langue = 'fra';
263
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
264
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
265
		else return '';
266
 
267
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 268
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 269
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 270
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 271
		}
272
		// pas de cache:
273
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
274
 
1656 raphael 275
		$donnees = Array('masque.nt' => $obs['nt'],
276
						 'masque.lg' => $langue,
277
						 'retour.champs' => 'num_statut');
1654 aurelien 278
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $donnees);
279
 
280
		if(! $noms) return '';
1656 raphael 281
		$noms = array_filter((array)($noms->resultat), function($item) { return ($item->num_statut == 1); });
1654 aurelien 282
		$nom = array_pop($noms)->nom_vernaculaire;
283
 
1656 raphael 284
		// cache
1657 raphael 285
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 286
		return $nom;
287
	}
288
 
289
 
290
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
1656 raphael 291
	   n'est pas aussi retentissant qu'espéré */
1654 aurelien 292
	static $service;
293
	function getNomCommun_v3($obs) {
294
		if(! $this->service) $this->service = new Projets();
295
 
296
		$langue = 'fra';
297
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
298
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
299
		else return '';
300
 
301
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
1657 raphael 302
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
1656 raphael 303
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
1657 raphael 304
			return self::$cache['getNomCommun'][$cache_id];
1654 aurelien 305
		}
306
		// pas de cache:
1656 raphael 307
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
1654 aurelien 308
 
309
		$donnees = Array('masque.nt' => $obs['nt'],
1656 raphael 310
						 'masque.lg' => $langue,
311
						 'retour.champs' => 'conseil_emploi');
312
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $donnees);
1654 aurelien 313
		try {
1656 raphael 314
			$noms = $this->service->traiterRessources();
315
		} catch(Exception $e) {
316
			return '';
1654 aurelien 317
		}
1656 raphael 318
		if(! $noms) return '';
319
		$noms = array_filter($noms['resultat'], function($item) { return ($item['num_statut'] == 1); });
320
		$premier_nom = array_pop($noms);
1654 aurelien 321
		$nom = $premier_nom['nom_vernaculaire'];
322
 
323
		// cache
1657 raphael 324
		self::$cache['getNomCommun'][$cache_id] = $nom;
1654 aurelien 325
		return $nom;
326
	}
327
 
328
}