Subversion Repositories eFlore/Applications.cel

Rev

Rev 2221 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 2221 Rev 2301
1
<?php
1
<?php
2
 
2
 
3
/**
3
/**
4
* @category  PHP
4
* @category  PHP
5
* @package   jrest
5
* @package   jrest
6
* @author    Raphaël Droz <raphael@tela-botania.org>
6
* @author    Raphaël Droz <raphael@tela-botania.org>
7
* @copyright 2013 Tela-Botanica
7
* @copyright 2013 Tela-Botanica
8
* @license   http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
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>
9
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
10
*/
10
*/
11
define('SEPARATEUR_IMAGES', " / ");
11
define('SEPARATEUR_IMAGES', " / ");
12
define('PREFIX_CHAMPS_ETENDUS', "ext:");
12
define('PREFIX_CHAMPS_ETENDUS', "ext:");
13
// utilisé par formaterUrlUser() [ nécessaire pour le widget d'export)
13
// utilisé par formaterUrlUser() [ nécessaire pour le widget d'export)
14
define('USER_BASEURL', 'http://www.tela-botanica.org/profil:%d');
14
define('USER_BASEURL', 'http://www.tela-botanica.org/profil:%d');
15
 
15
 
16
Class FormateurGroupeColonne {
16
Class FormateurGroupeColonne {
17
 
17
 
18
	// cache pour les données des fonctions
18
	// cache pour les données des fonctions
19
	static $cache = Array();
19
	static $cache = Array();
20
 
20
 
21
	// test sur la table cel_references, mis à TRUE si la table existe
21
	// test sur la table cel_references, mis à TRUE si la table existe
22
	static $is_table = false;
22
	static $is_table = false;
23
 
23
 
24
	// les groupes de champs utilisables
24
	// les groupes de champs utilisables
25
	static $fieldGroups = array(
25
	static $fieldGroups = array(
26
		'standard',
26
		'standard',
27
		'avance',
27
		'avance',
28
		'etendu',
28
		'etendu',
29
		'baseflor',
29
		'baseflor',
30
		'auteur'
30
		'auteur'
31
	);
31
	);
32
 
32
 
33
	// les données baseflor à récupérer: colonnes présentes dans cel_references
33
	// les données baseflor à récupérer: colonnes présentes dans cel_references
34
	// et intitulés associés
34
	// et intitulés associés
35
	static $baseflor_col = array(
35
	static $baseflor_col = array(
36
		"ve_lumiere" => "Lumière",
36
		"ve_lumiere" => "Lumière",
37
		"ve_temperature" => "Température",
37
		"ve_temperature" => "Température",
38
		"ve_continentalite" => "Continentalité",
38
		"ve_continentalite" => "Continentalité",
39
		"ve_humidite_atmos" => "Humidité Atmosphérique",
39
		"ve_humidite_atmos" => "Humidité Atmosphérique",
40
		"ve_humidite_edaph" => "Humidité",
40
		"ve_humidite_edaph" => "Humidité",
41
		"ve_reaction_sol" => "Réaction (pH)",
41
		"ve_reaction_sol" => "Réaction (pH)",
42
		"ve_nutriments_sol" => "Nutriments",
42
		"ve_nutriments_sol" => "Nutriments",
43
		"ve_salinite" => "Salinité",
43
		"ve_salinite" => "Salinité",
44
		"ve_texture_sol" => "Texture" ,
44
		"ve_texture_sol" => "Texture" ,
45
		"ve_mat_org_sol" => "Matière Organique",
45
		"ve_mat_org_sol" => "Matière Organique",
46
		"catminat_code" => "Code Catminat",
46
		"catminat_code" => "Code Catminat",
47
		"syntaxon" => "Syntaxon",
47
		"syntaxon" => "Syntaxon",
48
	);
48
	);
49
 
49
 
50
	// TODO: dirty, ordre des champs étendus... souhaité pour florilèges:
50
	// TODO: dirty, ordre des champs étendus... souhaité pour florilèges:
51
	static $ordre_champ_etendus_Florileges = array(
51
	static $ordre_champ_etendus_Florileges = array(
52
		"personneStructure",
52
		"personneStructure",
53
		"personneService",
53
		"personneService",
54
		"personneFonction",
54
		"personneFonction",
55
		"adresse",
55
		"adresse",
56
		"latitudeDebutRue",
56
		"latitudeDebutRue",
57
		"longitudeDebutRue",
57
		"longitudeDebutRue",
58
		"latitudeFinRue",
58
		"latitudeFinRue",
59
		"longitudeFinRue",
59
		"longitudeFinRue",
60
		"typoUrbaine",
60
		"typoUrbaine",
61
		"revetementSol",
61
		"revetementSol",
62
		"presenceZoneVegetalise",
62
		"presenceZoneVegetalise",
63
		"hauteurBatimentAvoisinant",
63
		"hauteurBatimentAvoisinant",
64
		"intensiteGestion",
64
		"intensiteGestion",
65
		"periodiciteTraitementPhyto",
65
		"periodiciteTraitementPhyto",
66
		"dateArretTraitementPhyto",
66
		"dateArretTraitementPhyto",
67
		"itineraireGestion",
67
		"itineraireGestion",
68
		"dateDerniereIntervention",
68
		"dateDerniereIntervention",
69
		"hauteurPlante",
69
		"hauteurPlante",
70
		"resistanceTraitementPhyto",
70
		"resistanceTraitementPhyto",
71
		"vitesseCroissance",
71
		"vitesseCroissance",
72
		"perceptionTechnicien",
72
		"perceptionTechnicien",
73
		"perceptionRiverainMauvaise",
73
		"perceptionRiverainMauvaise",
74
	);
74
	);
75
 
75
 
76
	static function colGroupsValidation($groupe_de_champs = 'standard,avance') {
76
	static function colGroupsValidation($groupe_de_champs = 'standard,avance') {
77
		if(! $groupe_de_champs) return FALSE;
77
		if(! $groupe_de_champs) return FALSE;
78
		if(is_string($groupe_de_champs)) {
78
		if(is_string($groupe_de_champs)) {
79
			$groupe_de_champs = array_flip(explode(',', $groupe_de_champs));
79
			$groupe_de_champs = array_flip(explode(',', $groupe_de_champs));
80
		}
80
		}
81
		elseif(is_array($groupe_de_champs)) {
81
		elseif(is_array($groupe_de_champs)) {
82
			$groupe_de_champs = array_flip($groupe_de_champs);
82
			$groupe_de_champs = array_flip($groupe_de_champs);
83
		}
83
		}
84
		else {
84
		else {
85
			return NULL;
85
			return NULL;
86
		}
86
		}
87
		$groupe_de_champs = array_intersect_key(array_flip(self::$fieldGroups),
87
		$groupe_de_champs = array_intersect_key(array_flip(self::$fieldGroups),
88
												$groupe_de_champs);
88
												$groupe_de_champs);
89
		if(!$groupe_de_champs) return FALSE;
89
		if(!$groupe_de_champs) return FALSE;
90
		// toujours ajouter standard
90
		// toujours ajouter standard
91
		$groupe_de_champs['standard'] = TRUE;
91
		$groupe_de_champs['standard'] = TRUE;
92
		return implode(',', array_keys($groupe_de_champs));
92
		return implode(',', array_keys($groupe_de_champs));
93
	}
93
	}
94
 
94
 
95
	/*
95
	/*
96
	* @param $fieldSets: un liste de noms de colonnes ou de sets de colonnes
96
	* @param $fieldSets: un liste de noms de colonnes ou de sets de colonnes
97
	*		séparés par des virgules
97
	*		séparés par des virgules
98
	* 		eg: "espece" ou "champs-etendus", ...
98
	* 		eg: "espece" ou "champs-etendus", ...
99
	*
99
	*
100
	* @return: un tableau associatif déjà ordonné
100
	* @return: un tableau associatif déjà ordonné
101
	* 		clé: abbrev [machine-name] de la colonne (eg: "espece" ou "mot-clef")
101
	* 		clé: abbrev [machine-name] de la colonne (eg: "espece" ou "mot-clef")
102
	* 		valeur: des données relative à cette colonne, cf GenColInfo
102
	* 		valeur: des données relative à cette colonne, cf GenColInfo
103
	*
103
	*
104
	* Si la colonne n'utilise pas de fonction de récupération particulière
104
	* Si la colonne n'utilise pas de fonction de récupération particulière
105
	* (ie: si le champ exportés [ou importé] correspond exactement au champ dans la base de donnée)
105
	* (ie: si le champ exportés [ou importé] correspond exactement au champ dans la base de donnée)
106
	* Alors 'abbrev' doit avoir la même valeur que le nom de la colonne dans la table mysql `cel_obs`.
106
	* Alors 'abbrev' doit avoir la même valeur que le nom de la colonne dans la table mysql `cel_obs`.
107
	*
107
	*
108
	*/
108
	*/
109
	static function nomEnsembleVersListeColonnes($groupe_de_champs = 'standard') {
109
	static function nomEnsembleVersListeColonnes($groupe_de_champs = 'standard') {
110
		if(! $groupe_de_champs) $groupe_de_champs = 'standard';
110
		if(! $groupe_de_champs) $groupe_de_champs = 'standard';
111
		if(is_string($groupe_de_champs)) {
111
		if(is_string($groupe_de_champs)) {
112
			$groupe_de_champs = array_flip(explode(',', $groupe_de_champs));
112
			$groupe_de_champs = array_flip(explode(',', $groupe_de_champs));
113
		}
113
		}
114
		elseif(is_array($groupe_de_champs)) {
114
		elseif(is_array($groupe_de_champs)) {
115
			$groupe_de_champs = array_flip($groupe_de_champs);
115
			$groupe_de_champs = array_flip($groupe_de_champs);
116
		}
116
		}
117
		else {
117
		else {
118
			return NULL;
118
			return NULL;
119
		}
119
		}
120
		$groupe_de_champs = array_intersect_key(array_flip(self::$fieldGroups),
120
		$groupe_de_champs = array_intersect_key(array_flip(self::$fieldGroups),
121
												$groupe_de_champs);
121
												$groupe_de_champs);
122
		if(!$groupe_de_champs) return NULL;
122
		if(!$groupe_de_champs) return NULL;
123
 
123
 
124
		$colonnes = Array();
124
		$colonnes = Array();
125
 
125
 
126
		if(isset($groupe_de_champs['standard'])) {
126
		if(isset($groupe_de_champs['standard'])) {
127
			$colonnes += Array(
127
			$colonnes += Array(
128
				'nom_sel'			=> self::GenColInfo(Array('abbrev' => 'nom_sel',
128
				'nom_sel'			=> self::GenColInfo(Array('abbrev' => 'nom_sel',
129
															  'nom' => 'Espèce')),
129
															  'nom' => 'Espèce')),
130
				'nom_sel_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_sel_nn',
130
				'nom_sel_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_sel_nn',
131
															  'nom' => 'Numéro nomenclatural',
131
															  'nom' => 'Numéro nomenclatural',
132
															  'importable' => FALSE)),
132
															  'importable' => FALSE)),
133
				'nom_ret'			=> self::GenColInfo(Array('abbrev' => 'nom_ret',
133
				'nom_ret'			=> self::GenColInfo(Array('abbrev' => 'nom_ret',
134
															  'nom' => 'Nom retenu',
134
															  'nom' => 'Nom retenu',
135
															  'importable' => FALSE)),
135
															  'importable' => FALSE)),
136
				'nom_ret_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_ret_nn',
136
				'nom_ret_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_ret_nn',
137
															  'nom' => 'Numéro nomenclatural nom retenu',
137
															  'nom' => 'Numéro nomenclatural nom retenu',
138
															  'importable' => FALSE)),
138
															  'importable' => FALSE)),
139
				'nt'				=> self::GenColInfo(Array('abbrev' => 'nt',
139
				'nt'				=> self::GenColInfo(Array('abbrev' => 'nt',
140
															  'nom' => 'Numéro taxonomique',
140
															  'nom' => 'Numéro taxonomique',
141
															  'importable' => FALSE)),
141
															  'importable' => FALSE)),
142
				'famille'			=> self::GenColInfo(Array('abbrev' => 'famille',
142
				'famille'			=> self::GenColInfo(Array('abbrev' => 'famille',
143
															  'nom' => 'Famille',
143
															  'nom' => 'Famille',
144
															  'importable' => FALSE)),
144
															  'importable' => FALSE)),
145
				'nom_referentiel'	=> self::GenColInfo(Array('abbrev' => 'nom_referentiel',
145
				'nom_referentiel'	=> self::GenColInfo(Array('abbrev' => 'nom_referentiel',
146
															  'nom' => 'Referentiel taxonomique')),
146
															  'nom' => 'Referentiel taxonomique')),
147
				'zone_geo'			=> self::GenColInfo(Array('abbrev' => 'zone_geo',
147
				'zone_geo'			=> self::GenColInfo(Array('abbrev' => 'zone_geo',
148
															  'nom' => 'Commune')),
148
															  'nom' => 'Commune')),
149
				'ce_zone_geo'		=> self::GenColInfo(Array('abbrev' => 'ce_zone_geo',
149
				'ce_zone_geo'		=> self::GenColInfo(Array('abbrev' => 'ce_zone_geo',
150
															  'nom' => 'Identifiant Commune',
150
															  'nom' => 'Identifiant Commune',
151
															  'fonction' => 'convertirCodeZoneGeoVersDepartement')),
151
															  'fonction' => 'convertirCodeZoneGeoVersDepartement')),
152
				'date_observation'	=> self::GenColInfo(Array('abbrev' => 'date_observation',
152
				'date_observation'	=> self::GenColInfo(Array('abbrev' => 'date_observation',
153
															  'nom' => 'Date',
153
															  'nom' => 'Date',
154
															  'fonction' => 'formaterDate')),
154
															  'fonction' => 'formaterDate')),
155
				'lieudit'			=> self::GenColInfo(Array('abbrev' => 'lieudit',
155
				'lieudit'			=> self::GenColInfo(Array('abbrev' => 'lieudit',
156
															  'nom' => 'Lieu-dit')),
156
															  'nom' => 'Lieu-dit')),
157
				'station'			=> self::GenColInfo(Array('abbrev' => 'station',
157
				'station'			=> self::GenColInfo(Array('abbrev' => 'station',
158
															  'nom' => 'Station')),
158
															  'nom' => 'Station')),
159
				'milieu'			=> self::GenColInfo(Array('abbrev' => 'milieu',
159
				'milieu'			=> self::GenColInfo(Array('abbrev' => 'milieu',
160
															  'nom' => 'Milieu')),
160
															  'nom' => 'Milieu')),
161
				'commentaire'		=> self::GenColInfo(Array('abbrev' => 'commentaire',
161
				'commentaire'		=> self::GenColInfo(Array('abbrev' => 'commentaire',
162
															  'nom' => 'Notes')),
162
															  'nom' => 'Notes')),
163
				'latitude'			=> self::GenColInfo(Array('abbrev' => 'latitude',
163
				'latitude'			=> self::GenColInfo(Array('abbrev' => 'latitude',
164
															  'nom' => 'Latitude',
164
															  'nom' => 'Latitude',
165
															  'extra' => 1,
165
															  'extra' => 1,
166
															  'fonction' => 'trim0')),
166
															  'fonction' => 'trim0')),
167
				'longitude'			=> self::GenColInfo(Array('abbrev' => 'longitude',
167
				'longitude'			=> self::GenColInfo(Array('abbrev' => 'longitude',
168
															  'nom' => 'Longitude',
168
															  'nom' => 'Longitude',
169
															  'extra' => 1,
169
															  'extra' => 1,
170
															  'fonction' => 'trim0')),
170
															  'fonction' => 'trim0')),
171
				'altitude'			=> self::GenColInfo(Array('abbrev' => 'altitude',
171
				'altitude'			=> self::GenColInfo(Array('abbrev' => 'altitude',
172
															  'nom' => 'Altitude',
172
															  'nom' => 'Altitude',
173
															  'extra' => 1)), // pas de trim0 car INT(5) en DB
173
															  'extra' => 1)), // pas de trim0 car INT(5) en DB
174
				'geodatum'			=> self::GenColInfo(Array('abbrev' => 'geodatum',
174
				'geodatum'			=> self::GenColInfo(Array('abbrev' => 'geodatum',
175
															  'nom' => 'Référentiel Géographique',
175
															  'nom' => 'Référentiel Géographique',
176
															  'extra' => 1,
176
															  'extra' => 1,
177
															  'importable' => FALSE)),
177
															  'importable' => FALSE)),
178
			);
178
			);
179
		}
179
		}
180
 
180
 
181
		if(isset($groupe_de_champs['avance'])) {
181
		if(isset($groupe_de_champs['avance'])) {
182
			$colonnes += array(
182
			$colonnes += array(
183
				// TODO: importable = FALSE car pas de merge de données importées
183
				// TODO: importable = FALSE car pas de merge de données importées
184
				'ordre'				=> self::GenColInfo(Array('abbrev' => 'ordre',
184
				'ordre'				=> self::GenColInfo(Array('abbrev' => 'ordre',
185
															  'nom' => 'Ordre',
185
															  'nom' => 'Ordre',
186
															  'extra' => 1,
186
															  'extra' => 1,
187
															  'importable' => FALSE)),
187
															  'importable' => FALSE)),
188
				'id_observation'	=> self::GenColInfo(Array('abbrev' => 'id_observation',
188
				'id_observation'	=> self::GenColInfo(Array('abbrev' => 'id_observation',
189
															  'nom' => 'Identifiant',
189
															  'nom' => 'Identifiant',
190
															  'extra' => 1,
190
															  'extra' => 1,
191
															  'importable' => FALSE)),
191
															  'importable' => FALSE)),
192
 
192
 
193
				'mots_cles_texte'	=> self::GenColInfo(Array('abbrev' => 'mots_cles_texte',
193
				'mots_cles_texte'	=> self::GenColInfo(Array('abbrev' => 'mots_cles_texte',
194
															  'nom' => 'Mots Clés',
194
															  'nom' => 'Mots Clés',
195
															  'extra' => 1)),
195
															  'extra' => 1)),
196
				'date_creation'		=> self::GenColInfo(Array('abbrev' => 'date_creation',
196
				'date_creation'		=> self::GenColInfo(Array('abbrev' => 'date_creation',
197
															  'nom' => 'Date Création',
197
															  'nom' => 'Date Création',
198
															  'extra' => 1,
198
															  'extra' => 1,
199
															  'importable' => FALSE)),
199
															  'importable' => FALSE)),
200
				'date_modification'	=> self::GenColInfo(Array('abbrev' => 'date_modification',
200
				'date_modification'	=> self::GenColInfo(Array('abbrev' => 'date_modification',
201
															  'nom' => 'Date Modification',
201
															  'nom' => 'Date Modification',
202
															  'extra' => 1,
202
															  'extra' => 1,
203
															  'importable' => FALSE)),
203
															  'importable' => FALSE)),
204
 
204
 
205
				// rappel transmission = 1, signifie simplement "public"
205
				// rappel transmission = 1, signifie simplement "public"
206
				// des données importées peuvent être d'emblée "publiques"
206
				// des données importées peuvent être d'emblée "publiques"
207
				// "importable" = TRUE
207
				// "importable" = TRUE
208
				'transmission'		=> self::GenColInfo(Array('abbrev' => 'transmission',
208
				'transmission'		=> self::GenColInfo(Array('abbrev' => 'transmission',
209
															  'nom' => 'Transmis',
209
															  'nom' => 'Transmis',
210
															  'extra' => 1,
210
															  'extra' => 1,
211
															  'fonction' => 'boolOuiNon')),
211
															  'fonction' => 'boolOuiNon')),
212
				'date_transmission'	=> self::GenColInfo(Array('abbrev' => 'date_transmission',
212
				'date_transmission'	=> self::GenColInfo(Array('abbrev' => 'date_transmission',
213
															  'nom' => 'Date Transmission',
213
															  'nom' => 'Date Transmission',
214
															  'extra' => 1,
214
															  'extra' => 1,
215
															  'importable' => FALSE)),
215
															  'importable' => FALSE)),
216
				'abondance'			=> self::GenColInfo(Array('abbrev' => 'abondance',
216
				'abondance'			=> self::GenColInfo(Array('abbrev' => 'abondance',
217
															  'nom' => 'Abondance',
217
															  'nom' => 'Abondance',
218
															  'extra' => 1)),
218
															  'extra' => 1)),
219
				'certitude'			=> self::GenColInfo(Array('abbrev' => 'certitude',
219
				'certitude'			=> self::GenColInfo(Array('abbrev' => 'certitude',
220
															  'nom' => 'Certitude',
220
															  'nom' => 'Certitude',
221
															  'extra' => 1)),
221
															  'extra' => 1)),
222
				'phenologie'		=> self::GenColInfo(Array('abbrev' => 'phenologie',
222
				'phenologie'		=> self::GenColInfo(Array('abbrev' => 'phenologie',
223
															  'nom' => 'Phénologie',
223
															  'nom' => 'Phénologie',
224
															  'extra' => 1)),
224
															  'extra' => 1)),
225
 
225
 
226
				// XXX: getImages() dépend du contexte de Cel, et doit être appelée comme cas particulier
226
				// XXX: getImages() dépend du contexte de Cel, et doit être appelée comme cas particulier
227
				// cf ExportXLS::traiterLigneObservation()
227
				// cf ExportXLS::traiterLigneObservation()
228
				'images'			=> self::GenColInfo(Array('abbrev' => 'images',
228
				'images'			=> self::GenColInfo(Array('abbrev' => 'images',
229
															  'nom' => 'Image(s)',
229
															  'nom' => 'Image(s)',
230
															  'extra' => 1,
230
															  'extra' => 1,
231
															  'fonction_data' => NULL /* cas particulier 'getImages' */,
231
															  'fonction_data' => NULL /* cas particulier 'getImages' */,
232
															  'importable' => TRUE,
232
															  'importable' => TRUE,
233
															  //'preload' => array(__CLASS__, 'getImages_preload')//TODO
233
															  //'preload' => array(__CLASS__, 'getImages_preload')//TODO
234
				)),
234
				)),
235
 
235
 
236
				/* 'nom_commun'			=> self::GenColInfo(Array('abbrev' => 'nom_commun',
236
				/* 'nom_commun'			=> self::GenColInfo(Array('abbrev' => 'nom_commun',
237
				   'nom' => 'Nom Commun',
237
				   'nom' => 'Nom Commun',
238
				   'extra' => 1,
238
				   'extra' => 1,
239
				   'fonction_data' => 'getNomCommun',
239
				   'fonction_data' => 'getNomCommun',
240
				   'importable' => FALSE),
240
				   'importable' => FALSE),
241
 
241
 
242
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
242
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
243
				   'nom' => 'Nom Commun',
243
				   'nom' => 'Nom Commun',
244
				   'extra' => 1,
244
				   'extra' => 1,
245
				   'fonction_data' => 'getNomCommun_v2'),
245
				   'fonction_data' => 'getNomCommun_v2'),
246
 
246
 
247
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
247
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
248
				   'nom' => 'Nom Commun',
248
				   'nom' => 'Nom Commun',
249
				   'extra' => 1,
249
				   'extra' => 1,
250
				   'fonction_data' => 'getNomCommun_v3'),
250
				   'fonction_data' => 'getNomCommun_v3'),
251
				   'importable' => FALSE), */
251
				   'importable' => FALSE), */
252
				'nom-commun'		=> self::GenColInfo(Array('abbrev' => 'nom-commun',
252
				'nom-commun'		=> self::GenColInfo(Array('abbrev' => 'nom-commun',
253
															  'nom' => 'Nom Commun',
253
															  'nom' => 'Nom Commun',
254
															  'extra' => 1,
254
															  'extra' => 1,
255
															  'fonction_data' => NULL /* cas particu 'getNomCommun_v4' */,
255
															  'fonction_data' => NULL /* cas particu 'getNomCommun_v4' */,
256
															  'preload' => array(__CLASS__, 'getNomCommun_preload')))
256
															  'preload' => array(__CLASS__, 'getNomCommun_preload')))
257
			);
257
			);
258
		}
258
		}
259
 
259
 
260
		if(isset($groupe_de_champs['baseflor'])) {
260
		if(isset($groupe_de_champs['baseflor'])) {
261
			$colonnes += array(
261
			$colonnes += array(
262
				// champ dynamique
262
				// champ dynamique
263
				'baseflor'			=> self::GenColInfo(Array('abbrev' => 'baseflor',
263
				'baseflor'			=> self::GenColInfo(Array('abbrev' => 'baseflor',
264
															  'nom' => '',
264
															  'nom' => '',
265
															  'extra' => 1,
265
															  'extra' => 1,
266
															  'importable' => FALSE,
266
															  'importable' => FALSE,
267
															  'preload' => array(__CLASS__, 'baseflor_preload'),
267
															  'preload' => array(__CLASS__, 'baseflor_preload'),
268
															  'dyna' => array(__CLASS__, 'baseflor_ligne'))),
268
															  'dyna' => array(__CLASS__, 'baseflor_ligne'))),
269
			);
269
			);
270
		}
270
		}
271
 
271
 
272
		if(isset($groupe_de_champs['etendu'])) {
272
		if(isset($groupe_de_champs['etendu'])) {
273
			$colonnes += array(
273
			$colonnes += array(
274
				// champ dynamique
274
				// champ dynamique
275
				'etendu'			=> self::GenColInfo(Array('abbrev' => 'etendu',
275
				'etendu'			=> self::GenColInfo(Array('abbrev' => 'etendu',
276
															  'nom' => '',
276
															  'nom' => '',
277
															  'extra' => 1,
277
															  'extra' => 1,
278
															  'importable' => FALSE,
278
															  'importable' => FALSE,
279
															  'preload' => array(__CLASS__, 'champsEtendus_preload'),
279
															  'preload' => array(__CLASS__, 'champsEtendus_preload'),
280
															  'dyna' => array(__CLASS__, 'champsEtendus_ligne'))),
280
															  'dyna' => array(__CLASS__, 'champsEtendus_ligne'))),
281
			);
281
			);
282
		}
282
		}
283
 
283
 
284
		if(isset($groupe_de_champs['auteur'])) {
284
		if(isset($groupe_de_champs['auteur'])) {
285
			$colonnes += array(
285
			$colonnes += array(
286
				'observateur'	=> self::GenColInfo(Array('abbrev' => 'observateur',
286
				'observateur'	=> self::GenColInfo(Array('abbrev' => 'observateur',
287
														  'nom' => 'Observateur',
287
														  'nom' => 'Observateur',
288
														  'extra' => 1,
288
														  'extra' => 1,
289
														  'fonction_data' => 'formaterUrlUser',
289
														  'fonction_data' => 'formaterUrlUser',
290
														  'importable' => FALSE)),
290
														  'importable' => FALSE)),
291
			);
291
			);
292
		}
292
		}
293
 
293
 
294
		return $colonnes;
294
		return $colonnes;
295
	}
295
	}
296
 
296
 
297
	static function preload($colonnes, $cel, $ids) {
297
	static function preload($colonnes, $cel, $ids) {
298
		$result = array();
298
		$result = array();
299
		foreach($colonnes as $abbrev => $colonne) {
299
		foreach($colonnes as $abbrev => $colonne) {
300
			if(!$colonne['preload']) continue;
300
			if(!$colonne['preload']) continue;
301
			$result[$abbrev] = call_user_func($colonne['preload'], $cel, $ids);
301
			$result[$abbrev] = call_user_func($colonne['preload'], $cel, $ids);
302
		}
302
		}
303
		return $result;
303
		return $result;
304
	}
304
	}
305
 
305
 
306
	public static function getIntitulesColonnes($colonnes) {
306
	public static function getIntitulesColonnes($colonnes) {
307
		// array_filter pour supprimer les colonnes "dynamique" n'ayant pas défini $nom (cf GenColInfo())
307
		// array_filter pour supprimer les colonnes "dynamique" n'ayant pas défini $nom (cf GenColInfo())
308
		return array_filter(array_map(array('FormateurGroupeColonne', 'retournerNomItem'), $colonnes));
308
		return array_filter(array_map(array('FormateurGroupeColonne', 'retournerNomItem'), $colonnes));
309
	}
309
	}
310
 
310
 
311
	public static function retournerNomItem(&$item) {
311
	public static function retournerNomItem(&$item) {
312
		return $item['nom'];
312
		return $item['nom'];
313
	}
313
	}
314
 
314
 
315
	public static function getLigneObservation(&$obs, &$colonnes, $cel = false) {
315
	public static function getLigneObservation(&$obs, &$colonnes, $cel = false) {
316
		$ligne_formatee = array();
316
		$ligne_formatee = array();
317
		foreach($colonnes as $abbrev => $colonne) {
317
		foreach($colonnes as $abbrev => $colonne) {
318
			$valeur = null;
318
			$valeur = null;
319
			if($colonne['extra'] == 2 || ! is_null($colonne['dyna'])) continue;
319
			if($colonne['extra'] == 2 || ! is_null($colonne['dyna'])) continue;
320
 
320
 
321
			// valeur directe depuis cel_obs ?
321
			// valeur directe depuis cel_obs ?
322
			if(isset($obs[$abbrev])) $valeur = $obs[$abbrev];
322
			if(isset($obs[$abbrev])) $valeur = $obs[$abbrev];
323
 
323
 
324
			// pré-processeur des champs
324
			// pré-processeur des champs
325
			if(function_exists($colonne['fonction'])) {
325
			if(function_exists($colonne['fonction'])) {
326
				$valeur = $colonne['fonction']($valeur);
326
				$valeur = $colonne['fonction']($valeur);
327
			} elseif(method_exists(__CLASS__, $colonne['fonction'])) {
327
			} elseif(method_exists(__CLASS__, $colonne['fonction'])) {
328
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
328
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
329
			} elseif($colonne['fonction']) {
329
			} elseif($colonne['fonction']) {
330
				die("méthode {$colonne['fonction']} introuvable");
330
				die("méthode {$colonne['fonction']} introuvable");
331
			}
331
			}
332
			// fonction pour obtenir des champs (étendus)
332
			// fonction pour obtenir des champs (étendus)
333
			elseif(function_exists($colonne['fonction_data'])) {
333
			elseif(function_exists($colonne['fonction_data'])) {
334
				$valeur = $colonne['fonction_data']($obs);
334
				$valeur = $colonne['fonction_data']($obs);
335
			}
335
			}
336
			elseif(method_exists(__CLASS__, $colonne['fonction_data'])) {
336
			elseif(method_exists(__CLASS__, $colonne['fonction_data'])) {
337
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
337
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
338
			}
338
			}
339
 
339
 
340
			// // cette section devrait être vide:
340
			// // cette section devrait être vide:
341
			// // cas particuliers ingérable avec l'architecture actuelle:
341
			// // cas particuliers ingérable avec l'architecture actuelle:
342
			if(false && $abbrev == 'date_observation' && $valeur == "0000-00-00") {
342
			if(false && $abbrev == 'date_observation' && $valeur == "0000-00-00") {
343
				/* blah */
343
				/* blah */
344
			}
344
			}
345
			// ici à cause du passage de $cel ($this->utilisateur)
345
			// ici à cause du passage de $cel ($this->utilisateur)
346
			if($abbrev == 'images') {
346
			if($abbrev == 'images') {
347
				$valeur = FormateurGroupeColonne::getImages($obs, $cel->id_utilisateur);
347
				$valeur = FormateurGroupeColonne::getImages($obs, $cel->id_utilisateur);
348
			}
348
			}
349
			if($abbrev == 'nom-commun') {
349
			if($abbrev == 'nom-commun') {
350
				$valeur = FormateurGroupeColonne::getNomCommun_v4($obs);
350
				$valeur = FormateurGroupeColonne::getNomCommun_v4($obs);
351
			}
351
			}
352
 
352
 
353
			if($valeur == null) {
353
			if($valeur == null) {
354
				$valeur = "";
354
				$valeur = "";
355
			}
355
			}
356
 
356
 
357
			// // fin de section "cas particuliers"
357
			// // fin de section "cas particuliers"
358
			$ligne_formatee[] = $valeur;
358
			$ligne_formatee[] = $valeur;
359
		}
359
		}
360
 
360
 
361
		// uniquement les champs dynamiques
361
		// uniquement les champs dynamiques
362
		foreach($colonnes as $abbrev => $colonne) {
362
		foreach($colonnes as $abbrev => $colonne) {
363
			$valeur = null;
363
			$valeur = null;
364
			if(is_null($colonne['dyna'])) continue;
364
			if(is_null($colonne['dyna'])) continue;
365
			// XXX: PHP-5.3
365
			// XXX: PHP-5.3
366
			call_user_func_array($colonne['dyna'],
366
			call_user_func_array($colonne['dyna'],
367
								 array($obs, &$ligne_formatee));
367
								 array($obs, &$ligne_formatee));
368
		}
368
		}
369
 
369
 
370
		return $ligne_formatee;
370
		return $ligne_formatee;
371
	}
371
	}
372
 
372
 
373
	/*
373
	/*
374
	* Wrapper générant un tableau associatif:
374
	* Wrapper générant un tableau associatif:
375
	* Ne pas changer les valeurs par défaut du prototype sans réflexion sur l'implication pour nomEnsembleVersListeColonnes()
375
	* Ne pas changer les valeurs par défaut du prototype sans réflexion sur l'implication pour nomEnsembleVersListeColonnes()
376
 
376
 
377
	* @param $abbrev (obligatoire): nom court de colonne, largement utilisé lors de l'import.
377
	* @param $abbrev (obligatoire): nom court de colonne, largement utilisé lors de l'import.
378
	*		  En effet chaque ligne importée est accessible à l'aide du `define` de $abbrev en majuscule, préfixé de "C_"
378
	*		  En effet chaque ligne importée est accessible à l'aide du `define` de $abbrev en majuscule, préfixé de "C_"
379
	*		  Exemple: $ligne[C_LONGITUDE] pour "longitude".
379
	*		  Exemple: $ligne[C_LONGITUDE] pour "longitude".
380
	*		  cf: ImportXLS::detectionEntete()
380
	*		  cf: ImportXLS::detectionEntete()
381
 
381
 
382
	* @param $nom (obligatoire): nom complet de colonne (utilisé pour la ligne d'en-tête)
382
	* @param $nom (obligatoire): nom complet de colonne (utilisé pour la ligne d'en-tête)
383
	*		  Les définition de champs dynamique (correspondant à de multiples colonnes) doivent laisser cette valeur
383
	*		  Les définition de champs dynamique (correspondant à de multiples colonnes) doivent laisser cette valeur
384
	*		  vide afin de ne pas créer une colonne supplémentaire erronée.
384
	*		  vide afin de ne pas créer une colonne supplémentaire erronée.
385
 
385
 
386
	* @param $is_extra:
386
	* @param $is_extra:
387
	* Si 0, la colonne est une colonne standard
387
	* Si 0, la colonne est une colonne standard
388
	* Si 1, la colonne est extra [le plus souvent générée automatiquement]
388
	* Si 1, la colonne est extra [le plus souvent générée automatiquement]
389
	*		 (auquel cas une bordure bleue entoure son nom dans la ligne d'entête)
389
	*		 (auquel cas une bordure bleue entoure son nom dans la ligne d'entête)
390
	* Si 2, la colonne n'est pas traité à l'export, mais une définition peut lui être donnée
390
	* Si 2, la colonne n'est pas traité à l'export, mais une définition peut lui être donnée
391
	*		 qui pourra être utilisée à l'import, exemple: "image"
391
	*		 qui pourra être utilisée à l'import, exemple: "image"
392
 
392
 
393
	* @param $fonction (optionnel): un nom d'un fonction de préprocessing
393
	* @param $fonction (optionnel): un nom d'un fonction de préprocessing
394
	* 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
394
	* 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
395
 
395
 
396
	* @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
396
	* @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
397
	* 		  $fonction_data doit prendre comme premier argument le tableau des champs de l'enregistrement existant
397
	* 		  $fonction_data doit prendre comme premier argument le tableau des champs de l'enregistrement existant
398
	*		  $fonction_data doit retourner une valeur
398
	*		  $fonction_data doit retourner une valeur
399
 
399
 
400
	* @param $importable (optionnel): défini si la colonne est traitée (ou absolument ignorée par PHPExcel) lors de
400
	* @param $importable (optionnel): défini si la colonne est traitée (ou absolument ignorée par PHPExcel) lors de
401
	*		  l'import.
401
	*		  l'import.
402
 
402
 
403
	* @param $preload (optionnel): défini une fonction de préchargement massif de donnée potentiellement utilisable par $fonction_data.
403
	* @param $preload (optionnel): défini une fonction de préchargement massif de donnée potentiellement utilisable par $fonction_data.
404
	*		  Utile, notamment, dans le cadre de l'export
404
	*		  Utile, notamment, dans le cadre de l'export
405
 
405
 
406
	* @param $fonction_dynamique (optionnel): défini une fonction ajoutant un nombre arbitraire de colonnes à une ligne donnée
406
	* @param $fonction_dynamique (optionnel): défini une fonction ajoutant un nombre arbitraire de colonnes à une ligne donnée
407
	*		  Utile, notamment, dans le cadre de l'export des champs étendus ou des données baseflor
407
	*		  Utile, notamment, dans le cadre de l'export des champs étendus ou des données baseflor
408
	*		  La fonction doit TOUJOURS alterer la ligne en lui ajoutant une nombre CONSTANT d'éléments (NULL ou non)
408
	*		  La fonction doit TOUJOURS alterer la ligne en lui ajoutant une nombre CONSTANT d'éléments (NULL ou non)
409
	*		  La fonction doit prendre comme arguments ($obs, &$ligne_formatee)
409
	*		  La fonction doit prendre comme arguments ($obs, &$ligne_formatee)
410
	*/
410
	*/
411
	static function GenColInfo($args) {
411
	static function GenColInfo($args) {
412
		$default = Array('abbrev' => NULL,
412
		$default = Array('abbrev' => NULL,
413
						 'nom' => NULL,
413
						 'nom' => NULL,
414
						 'extra' => 0,
414
						 'extra' => 0,
415
						 'fonction' => NULL,
415
						 'fonction' => NULL,
416
						 'fonction_data' => NULL,
416
						 'fonction_data' => NULL,
417
						 'importable' => TRUE,
417
						 'importable' => TRUE,
418
						 'preload' => NULL,
418
						 'preload' => NULL,
419
						 'dyna' => NULL);
419
						 'dyna' => NULL);
420
		$ret = array_intersect_key($args, $default);
420
		$ret = array_intersect_key($args, $default);
421
		return array_merge($default, $ret);
421
		return array_merge($default, $ret);
422
	}
422
	}
423
 
423
 
424
	static function formaterDate($date_heure_mysql) {
424
	static function formaterDate($date_heure_mysql) {
425
		//return "";
425
		//return "";
426
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") return NULL;
426
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") return NULL;
427
		// malheureusement pas disponible en php < 5.3
427
		// malheureusement pas disponible en php < 5.3
428
		//$date_format = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql);
428
		//$date_format = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql);
429
		$val = explode(' ', $date_heure_mysql);
429
		$val = explode(' ', $date_heure_mysql);
430
		$date = explode('-', $val[0]);
430
		$date = explode('-', $val[0]);
431
		$heure = explode(':', $val[1]);
431
		$heure = explode(':', $val[1]);
432
		$timestamp = mktime((int) $heure[0], (int) $heure[1], (int) $heure[2], (int) $date[1], (int) $date[2], (int) $date[0]);
432
		$timestamp = mktime((int) $heure[0], (int) $heure[1], (int) $heure[2], (int) $date[1], (int) $date[2], (int) $date[0]);
433
		if(!$timestamp) return NULL;
433
		if(!$timestamp) return NULL;
434
		// TODO: les widgets ne font malheureusement pas usage de l'heure dans le CEL
434
		// TODO: les widgets ne font malheureusement pas usage de l'heure dans le CEL
435
		// TODO: si modification, ne pas oublier de modifier le format d'import correspondant
435
		// TODO: si modification, ne pas oublier de modifier le format d'import correspondant
436
		//	dans ImportXLS, traiterDateObs() (actuellement: "Y/m/d" car utilisation de strtotime() qui ne lit pas tout)
436
		//	dans ImportXLS, traiterDateObs() (actuellement: "Y/m/d" car utilisation de strtotime() qui ne lit pas tout)
437
		// $date_formatee = strftime('%d/%m/%Y', $timestamp);
437
		// $date_formatee = strftime('%d/%m/%Y', $timestamp);
438
		$date_formatee = strftime('%Y/%m/%d', $timestamp);
438
		$date_formatee = strftime('%Y/%m/%d', $timestamp);
439
		if(!$date_formatee) return "00/00/0000";
439
		if(!$date_formatee) return "00/00/0000";
440
		return $date_formatee;
440
		return $date_formatee;
441
	}
441
	}
442
 
442
 
443
	static function formaterUrlUser($obs) {
443
	static function formaterUrlUser($obs) {
444
		$is_id = is_numeric($obs['ce_utilisateur']);
444
		$is_id = is_numeric($obs['ce_utilisateur']);
445
		return sprintf("%s %s <%s>%s",
445
		return sprintf("%s %s <%s>%s",
446
					   $obs['prenom_utilisateur'],
446
					   $obs['prenom_utilisateur'],
447
					   $obs['nom_utilisateur'],
447
					   $obs['nom_utilisateur'],
448
					   preg_replace(';@.*;', '@...', $obs['courriel_utilisateur']),
448
					   preg_replace(';@.*;', '@...', $obs['courriel_utilisateur']),
449
					   $is_id ? sprintf(' (' . USER_BASEURL . ')', $obs['ce_utilisateur']) : '');
449
					   $is_id ? sprintf(' (' . USER_BASEURL . ')', $obs['ce_utilisateur']) : '');
450
	}
450
	}
451
 
451
 
452
	static function getImages_preload($cel, $obsids) {
452
	static function getImages_preload($cel, $obsids) {
453
		if(!$obsids) return;
453
		if(!$obsids) return;
454
		$rec = Cel::db()->requeter(
454
		$rec = Cel::db()->requeter(
455
			sprintf("SELECT o.id_observation, GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i " .
455
			sprintf("SELECT o.id_observation, GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i " .
456
					"FROM cel_images i LEFT JOIN cel_obs_images oi ON (i.id_image = oi.id_image) LEFT JOIN cel_obs o ON (oi.id_observation = o.id_observation) " .
456
					"FROM cel_images i LEFT JOIN cel_obs_images oi ON (i.id_image = oi.id_image) LEFT JOIN cel_obs o ON (oi.id_observation = o.id_observation) " .
457
					"WHERE o.ce_utilisateur = %d AND o.id_observation IN (%s) " .
457
					"WHERE o.ce_utilisateur = %d AND o.id_observation IN (%s) " .
458
					"GROUP BY id_observation",
458
					"GROUP BY id_observation",
459
					SEPARATEUR_IMAGES,
459
					SEPARATEUR_IMAGES,
460
					$cel->id_utilisateur,
460
					$cel->id_utilisateur,
461
					implode(',', $obsids)));
461
					implode(',', $obsids)));
462
		foreach($rec as $v) {
462
		foreach($rec as $v) {
463
			self::$cache['getImages'][$v['id_observation']] = $v['i'];
463
			self::$cache['getImages'][$v['id_observation']] = $v['i'];
464
		}
464
		}
465
		return NULL;
465
		return NULL;
466
	}
466
	}
467
 
467
 
468
	static function getImages($obs, $id_utilisateur) {
468
	static function getImages($obs, $id_utilisateur) {
469
		if(! $id_utilisateur) return NULL;
469
		if(! $id_utilisateur) return NULL;
470
		if(isset(self::$cache['getImages'][$obs['id_observation']]))
470
		if(isset(self::$cache['getImages'][$obs['id_observation']]))
471
			return self::$cache['getImages'][$obs['id_observation']];
471
			return self::$cache['getImages'][$obs['id_observation']];
472
 
472
 
473
		$rec = Cel::db()->requeter(
473
		$rec = Cel::db()->requeter(
474
			sprintf("SELECT GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i FROM cel_images i"
474
			sprintf("SELECT GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i FROM cel_images i"
475
					." LEFT JOIN cel_obs_images oi ON (i.id_image = oi.id_image)"
475
					." LEFT JOIN cel_obs_images oi ON (i.id_image = oi.id_image)"
476
					." LEFT JOIN cel_obs o ON (oi.id_observation = o.id_observation)"
476
					." LEFT JOIN cel_obs o ON (oi.id_observation = o.id_observation)"
477
					." WHERE o.ce_utilisateur = %d AND o.id_observation = %d LIMIT 1",
477
					." WHERE o.ce_utilisateur = %d AND o.id_observation = %d LIMIT 1",
478
					SEPARATEUR_IMAGES,
478
					SEPARATEUR_IMAGES,
479
					$id_utilisateur,
479
					$id_utilisateur,
480
					$obs['id_observation']));
480
					$obs['id_observation']));
481
		return $rec ? $rec[0]['i'] : NULL;
481
		return $rec ? $rec[0]['i'] : NULL;
482
	}
482
	}
483
 
483
 
484
	public static function convertirCodeZoneGeoVersDepartement($code_zone_geo) {
484
	public static function convertirCodeZoneGeoVersDepartement($code_zone_geo) {
485
		$code_departement = '';
485
		$code_departement = '';
486
		if(self::estUnCodeInseeDepartement($code_zone_geo)) {
486
		if(self::estUnCodeInseeDepartement($code_zone_geo)) {
487
			$code_departement = substr(ltrim($code_zone_geo,'INSEE-C:'),0,2);
487
			$code_departement = substr(ltrim($code_zone_geo,'INSEE-C:'),0,2);
488
		}
488
		}
489
 
489
 
490
		return $code_departement;
490
		return $code_departement;
491
	}
491
	}
492
 
492
 
493
	public static function trim0($lonlat) {
493
	public static function trim0($lonlat) {
494
		return trim(trim($lonlat, "0"), ".");
494
		return trim(trim($lonlat, "0"), ".");
495
	}
495
	}
496
 
496
 
497
	public static function boolOuiNon($transmission) {
497
	public static function boolOuiNon($transmission) {
498
		return $transmission ? 'oui' : '';
498
		return $transmission ? 'oui' : '';
499
	}
499
	}
500
 
500
 
501
	public static function estUnCodeInseeDepartement($code_a_tester) {
501
	public static function estUnCodeInseeDepartement($code_a_tester) {
502
		return preg_match('/^INSEE-C:[0-9]{5}/',$code_a_tester);
502
		return preg_match('/^INSEE-C:[0-9]{5}/',$code_a_tester);
503
	}
503
	}
504
 
504
 
505
 
505
 
506
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
506
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
507
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
507
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
508
	// Par exemple, la variable pour "nva" ?
508
	// Par exemple, la variable pour "nva" ?
509
	function getNomCommun($obs) {
509
	function getNomCommun($obs) {
510
		$langue = 'fra';
510
		$langue = 'fra';
511
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
511
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
512
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
512
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
513
		else return '';
513
		else return '';
514
 
514
 
515
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
515
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
516
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
516
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
517
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
517
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
518
			return self::$cache['getNomCommun'][$cache_id];
518
			return self::$cache['getNomCommun'][$cache_id];
519
		}
519
		}
520
		// pas de cache:
520
		// pas de cache:
521
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
521
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
522
 
522
 
523
		// pour bdtfx:
523
		// pour bdtfx:
524
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
524
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
525
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
525
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
526
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
526
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
527
						   Array($referentiel, $obs['nt'], $langue),
527
						   Array($referentiel, $obs['nt'], $langue),
528
						   self::$config['eflore']['url_service_nom_attribution']) . // TODO !
528
						   self::$config['eflore']['url_service_nom_attribution']) . // TODO !
529
			"&retour.champs=num_statut";
529
			"&retour.champs=num_statut";
530
		$noms = @json_decode(file_get_contents($url));
530
		$noms = @json_decode(file_get_contents($url));
531
		if(! $noms) return '';
531
		if(! $noms) return '';
532
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
532
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
533
		$nom = array_pop($noms)->nom_vernaculaire;
533
		$nom = array_pop($noms)->nom_vernaculaire;
534
 
534
 
535
		// cache
535
		// cache
536
		self::$cache['getNomCommun'][$cache_id] = $nom;
536
		self::$cache['getNomCommun'][$cache_id] = $nom;
537
		return $nom;
537
		return $nom;
538
	}
538
	}
539
 
539
 
540
	private function retournerNumStatutUn(&$item) {
540
	private function retournerNumStatutUn(&$item) {
541
		return ($item->num_statut == 1);
541
		return ($item->num_statut == 1);
542
	}
542
	}
543
 
543
 
544
	private function retournerNumStatutUnArr(&$item) {
544
	private function retournerNumStatutUnArr(&$item) {
545
		return ($item['num_statut'] == 1);
545
		return ($item['num_statut'] == 1);
546
	}
546
	}
547
 
547
 
548
	// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
548
	// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
549
	/* require_once('/home/raphael/eflore/framework/framework/Framework.php');
549
	/* require_once('/home/raphael/eflore/framework/framework/Framework.php');
550
	Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
550
	Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
551
	Framework::setInfoAppli(Config::get('info'));
551
	Framework::setInfoAppli(Config::get('info'));
552
	require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
552
	require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
553
 
553
 
554
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
554
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
555
	   NomsVernaculaires pour obtenir le nom commun */
555
	   NomsVernaculaires pour obtenir le nom commun */
556
	function getNomCommun_v2($obs) {
556
	function getNomCommun_v2($obs) {
557
		static $service;
557
		static $service;
558
		$service = new Projets();
558
		$service = new Projets();
559
 
559
 
560
		$langue = 'fra';
560
		$langue = 'fra';
561
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
561
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
562
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
562
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
563
		else return '';
563
		else return '';
564
 
564
 
565
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
565
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
566
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
566
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
567
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
567
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
568
			return self::$cache['getNomCommun'][$cache_id];
568
			return self::$cache['getNomCommun'][$cache_id];
569
		}
569
		}
570
		// pas de cache:
570
		// pas de cache:
571
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
571
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
572
 
572
 
573
		$donnees = Array('masque.nt' => $obs['nt'],
573
		$donnees = Array('masque.nt' => $obs['nt'],
574
						 'masque.lg' => $langue,
574
						 'masque.lg' => $langue,
575
						 'retour.champs' => 'num_statut');
575
						 'retour.champs' => 'num_statut');
576
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $donnees);
576
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $donnees);
577
 
577
 
578
		if(! $noms) return '';
578
		if(! $noms) return '';
579
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
579
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
580
		$nom = array_pop($noms)->nom_vernaculaire;
580
		$nom = array_pop($noms)->nom_vernaculaire;
581
 
581
 
582
		// cache
582
		// cache
583
		self::$cache['getNomCommun'][$cache_id] = $nom;
583
		self::$cache['getNomCommun'][$cache_id] = $nom;
584
		return $nom;
584
		return $nom;
585
	}
585
	}
586
 
586
 
587
 
587
 
588
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
588
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
589
	   n'est pas aussi retentissant qu'espéré */
589
	   n'est pas aussi retentissant qu'espéré */
590
	static $service;
590
	static $service;
591
	function getNomCommun_v3($obs) {
591
	function getNomCommun_v3($obs) {
592
		if(! $this->service) $this->service = new Projets();
592
		if(! $this->service) $this->service = new Projets();
593
 
593
 
594
		$langue = 'fra';
594
		$langue = 'fra';
595
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
595
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
596
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
596
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
597
		else return '';
597
		else return '';
598
 
598
 
599
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
599
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
600
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
600
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
601
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
601
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
602
			return self::$cache['getNomCommun'][$cache_id];
602
			return self::$cache['getNomCommun'][$cache_id];
603
		}
603
		}
604
		// pas de cache:
604
		// pas de cache:
605
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
605
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
606
 
606
 
607
		$donnees = Array('masque.nt' => $obs['nt'],
607
		$donnees = Array('masque.nt' => $obs['nt'],
608
						 'masque.lg' => $langue,
608
						 'masque.lg' => $langue,
609
						 'retour.champs' => 'conseil_emploi');
609
						 'retour.champs' => 'conseil_emploi');
610
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $donnees);
610
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $donnees);
611
		try {
611
		try {
612
			$noms = $this->service->traiterRessources();
612
			$noms = $this->service->traiterRessources();
613
		} catch(Exception $e) {
613
		} catch(Exception $e) {
614
			return '';
614
			return '';
615
		}
615
		}
616
		if(! $noms) return '';
616
		if(! $noms) return '';
617
		$noms = array_filter($noms['resultat'], array($this, retournerNumStatutUnArr)); // XXX: php 5.3
617
		$noms = array_filter($noms['resultat'], array($this, retournerNumStatutUnArr)); // XXX: php 5.3
618
		$premier_nom = array_pop($noms);
618
		$premier_nom = array_pop($noms);
619
		$nom = $premier_nom['nom_vernaculaire'];
619
		$nom = $premier_nom['nom_vernaculaire'];
620
 
620
 
621
		// cache
621
		// cache
622
		self::$cache['getNomCommun'][$cache_id] = $nom;
622
		self::$cache['getNomCommun'][$cache_id] = $nom;
623
		return $nom;
623
		return $nom;
624
	}
624
	}
625
 
625
 
626
	/* Cette fonction initialise le cache des noms communs en 1 fois, sur la liste des observations à exporter.
626
	/* Cette fonction initialise le cache des noms communs en 1 fois, sur la liste des observations à exporter.
627
	   Ainsi, les appels successifs à getNomCommun_v4() ne sont pas couteux (pas de requête SQL) */
627
	   Ainsi, les appels successifs à getNomCommun_v4() ne sont pas couteux (pas de requête SQL) */
628
	static function getNomCommun_preload($cel, $obsids) {
628
	static function getNomCommun_preload($cel, $obsids) {
629
		if(!$obsids) return;
629
		if(!$obsids) return;
630
		if(!self::referenceTableExiste()) return NULL;
630
		if(!self::referenceTableExiste()) return NULL;
631
 
631
 
632
		// CREATE INDEX i_nom_referentiel ON cel_obs (nom_referentiel(5));
632
		// CREATE INDEX i_nom_referentiel ON cel_obs (nom_referentiel(5));
633
		$req = sprintf("SELECT r.referentiel, r.num_taxon, r.nom_commun FROM cel_references r" .
633
		$req = sprintf("SELECT r.referentiel, r.num_taxon, r.nom_commun FROM cel_references r" .
634
					   " INNER JOIN cel_obs c ON (r.referentiel = substring_index(c.nom_referentiel, ':', 1) and r.num_taxon = c.nt)" .
634
					   " INNER JOIN cel_obs c ON (r.referentiel = substring_index(c.nom_referentiel, ':', 1) and r.num_taxon = c.nt)" .
635
					   " WHERE c.id_observation IN (%s)",
635
					   " WHERE c.id_observation IN (%s)",
636
					   implode(',', $obsids));
636
					   implode(',', $obsids));
637
		$res = Cel::db()->requeter($req);
637
		$res = Cel::db()->requeter($req);
638
		foreach($res as $v) {
638
		foreach($res as $v) {
639
			self::$cache['getNomCommun'][$v['referentiel'] . '-' . $v['num_taxon'] . '-' . 'fra'] = $v['nom_commun'];
639
			self::$cache['getNomCommun'][$v['referentiel'] . '-' . $v['num_taxon'] . '-' . 'fra'] = $v['nom_commun'];
640
		}
640
		}
641
		return NULL;
641
		return NULL;
642
	}
642
	}
643
 
643
 
644
	static function referenceTableExiste() {
644
	static function referenceTableExiste() {
645
		if (!self::$is_table) {
645
		if (!self::$is_table) {
646
			// une seule fois
646
			// une seule fois
647
			if (! Cel::db()->requeterLigne("SHOW TABLES LIKE 'cel_references'")) return FALSE;
647
			if (! Cel::db()->requeterLigne("SHOW TABLES LIKE 'cel_references'")) return FALSE;
648
			self::$is_table = TRUE;
648
			self::$is_table = TRUE;
649
		}
649
		}
650
		return TRUE;
650
		return TRUE;
651
	}
651
	}
652
 
652
 
653
	static function getNomCommun_v4($obs) {
653
	static function getNomCommun_v4($obs) {
-
 
654
		// Attention la fonction suppose que l'on ait fait appel à getNomCommun_preload avant
-
 
655
		// d'être appelée
654
		if(! $obs['nt']) return NULL;
656
		if(! $obs['nt']) return NULL;
655
		if(! self::referenceTableExiste()) return NULL;
657
		if(! self::referenceTableExiste()) return NULL;
656
 
658
 
657
		$langue = 'fra';
659
		$langue = 'fra';
658
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
660
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
659
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
661
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
-
 
662
 
660
 
663
		$nom = null;
661
		// cache:
664
		// cache:
662
		if(isset($cache['getNomCommun'])) {
665
		if(isset(self::$cache['getNomCommun'])) {
663
			if(isset(self::$cache['getNomCommun'][$cache_id])) return self::$cache['getNomCommun'][$cache_id];
666
			if(isset(self::$cache['getNomCommun'][$cache_id])) return self::$cache['getNomCommun'][$cache_id];
664
			// XXX: problème de valeurs NULL ?
667
			// XXX: problème de valeurs NULL ?
-
 
668
			if(array_key_exists($cache_id, self::$cache['getNomCommun'])) {
-
 
669
				$nom = self::$cache['getNomCommun'][$cache_id];
665
			if(array_key_exists($cache_id, self::$cache['getNomCommun'])) return self::$cache['getNomCommun'][$cache_id];
670
			}
666
		}
-
 
667
 
-
 
668
		// pas de cache:
-
 
669
		$nom = Cel::db()->requeterLigne(sprintf("SELECT nom_commun FROM cel_references " .
-
 
670
												  "WHERE referentiel = '%s' AND num_taxon = %d LIMIT 1",
-
 
671
												  $referentiel,
-
 
672
												  $obs['nt']));
-
 
673
 
-
 
674
		if(! $nom) return NULL;
-
 
675
		$nom = $nom["nom_commun"];
-
 
676
 
-
 
677
		// cache
671
		}
678
		self::$cache['getNomCommun'][$cache_id] = $nom;
672
 
679
		return $nom;
673
		return $nom;
680
	}
674
	}
681
 
675
 
682
 
676
 
683
	/* Cette fonction initialise le cache des données baseflor en 1 fois, sur la liste des observations à exporter.
677
	/* Cette fonction initialise le cache des données baseflor en 1 fois, sur la liste des observations à exporter.
684
	   Ainsi, les appels successifs à baseflor_ligne() ne sont pas couteux (pas de requête SQL) */
678
	   Ainsi, les appels successifs à baseflor_ligne() ne sont pas couteux (pas de requête SQL) */
685
	static function baseflor_preload($cel, $obsids) {
679
	static function baseflor_preload($cel, $obsids) {
686
		if(!$obsids) return;
680
		if(!$obsids) return;
687
		if(!self::referenceTableExiste()) return NULL;
681
		if(!self::referenceTableExiste()) return NULL;
-
 
682
 
688
 
683
		// Attention (en attendant de faire une meilleure table et une meilleure requete) le distinct est très important
689
		$req = sprintf("SELECT referentiel, num_nom_retenu, %s FROM cel_references r" .
684
		$req = sprintf("SELECT DISTINCT referentiel, num_nom_retenu, %s FROM cel_references r" .
-
 
685
						" INNER JOIN cel_obs c ON (r.num_nom_retenu = c.nom_ret_nn)" .
690
					   " INNER JOIN cel_obs c ON (r.num_nom_retenu = c.nom_ret_nn)" .
686
						" AND r.referentiel = IF(LOCATE(':', c.nom_referentiel) = 0, c.nom_referentiel, SUBSTR(c.nom_referentiel FROM 1 FOR LOCATE(':', c.nom_referentiel) - 1))" .
691
					   " WHERE c.id_observation IN (%s)",
687
						" WHERE c.id_observation IN (%s)",
692
					   //" AND catminat_code IS NOT NULL", // TODO: suppression des NULL ici signifie que le cache sera partiel...
688
						//" AND catminat_code IS NOT NULL", // TODO: suppression des NULL ici signifie que le cache sera partiel...
693
					   implode(',', array_keys(self::$baseflor_col)),
689
						implode(',', array_keys(self::$baseflor_col)),
694
					   implode(',', $obsids));
690
						implode(',', $obsids));
695
		$res = Cel::db()->requeter($req);
691
		$res = Cel::db()->requeter($req);
696
		if(!$res) return NULL;
692
		if(!$res) return NULL;
697
 
693
 
698
		foreach($res as $v) {
694
		foreach($res as $v) {
699
			$data = $v;
695
			$data = $v;
700
			unset($data['referentiel']); // non nécessaire
696
			unset($data['referentiel']); // non nécessaire
701
			unset($data['num_nom_retenu']); // non nécessaire
697
			unset($data['num_nom_retenu']); // non nécessaire
-
 
698
			
-
 
699
			// Des fois les synonymes ont des valeurs pour baseflor et pas le nom retenu et vice versa
-
 
700
			// on les fusionne pour avoir le maximum d'infos, en attendant de repenser la table référence 
-
 
701
			if(isset(self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']])) {
-
 
702
				$orig  = array_filter(self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']], 'strlen');
-
 
703
				$data  = array_filter($data , 'strlen');
-
 
704
				$data = array_merge($orig, $data);
-
 
705
			}
-
 
706
			
702
			self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']] = $data;
707
			self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']] = $data;
703
		}
708
		}
704
 
709
 
705
		return NULL;
710
		return NULL;
706
	}
711
	}
707
 
-
 
708
 
712
 
-
 
713
	static function baseflor_ligne($obs, &$ligne) {
-
 
714
		// Attention la fonction suppose que l'on ait fait appel à baseflor_preload avant 
709
	static function baseflor_ligne($obs, &$ligne) {
715
		// d'être appelée
710
		if(! $obs['nom_ret_nn']) {
716
		if(! $obs['nom_ret_nn']) {
711
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
717
			$ligne = array_merge($ligne, array_fill("", count(self::$baseflor_col), NULL));
712
			return;
718
			return;
713
		}
719
		}
714
 
720
 
715
		if(! self::referenceTableExiste()) {
721
		if(! self::referenceTableExiste()) {
716
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
722
			$ligne = array_merge($ligne, array_fill("", count(self::$baseflor_col), NULL));
717
			return;
723
			return;
718
		}
724
		}
719
 
725
 
720
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
726
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
721
		$cache_id = $referentiel . '-' . $obs['nom_ret_nn'];
727
		$cache_id = $referentiel . '-' . $obs['nom_ret_nn'];
722
 
728
 
723
		// XXX: problème de valeurs NULL pour utiliser simplement isset() ?
729
		// XXX: problème de valeurs NULL pour utiliser simplement isset() ?
724
		// @ car getBaseflor[] n'est peut-être pas encore initialisé
730
		// @ car getBaseflor[] n'est peut-être pas encore initialisé
725
		if(@array_key_exists($cache_id, self::$cache['getBaseflor'])) {
731
		if(@array_key_exists($cache_id, self::$cache['getBaseflor'])) {
726
			$ligne = array_merge($ligne, self::$cache['getBaseflor'][$cache_id]);
732
			$ligne = array_merge($ligne, self::$cache['getBaseflor'][$cache_id]);
727
			return;
733
			return;
728
		}
-
 
729
 
-
 
730
		// pas de cache:
-
 
731
		$data = Cel::db()->requeterLigne(sprintf("SELECT %s FROM cel_references " .
-
 
732
											 "WHERE referentiel = '%s' AND num_nom_retenu = %d LIMIT 1",
-
 
733
											 implode(', ', array_keys(self::$baseflor_col)),
-
 
734
											 $referentiel,
-
 
735
											 $obs['nom_ret_nn']));
-
 
736
 
-
 
737
		if(! $data) {
734
		} else {
738
			$ligne = array_merge($ligne, array_fill(0, count(self::$baseflor_col), NULL));
735
			$ligne = array_merge($ligne, array_fill("", count(self::$baseflor_col), NULL));
739
			return;
736
			return;
740
		}
737
		}
741
 
-
 
742
		// cache
-
 
743
		self::$cache['getBaseflor'][$cache_id] = $data;
-
 
744
		$ligne = array_merge($ligne, $data);
-
 
745
	}
738
	}
746
 
739
 
747
	static function champsEtendus_preload($cel, $obsids) {
740
	static function champsEtendus_preload($cel, $obsids) {
748
		$gestion_champs_etendus = new GestionChampsEtendus($cel->config, 'obs');
741
		$gestion_champs_etendus = new GestionChampsEtendus($cel->config, 'obs');
749
		$colonnes_champs_supp_par_obs = $gestion_champs_etendus->consulterClesParLots($obsids);
742
		$colonnes_champs_supp_par_obs = $gestion_champs_etendus->consulterClesParLots($obsids);
750
		// ces deux lignes réordonnent l'ordre des colonnes des champs étendus en fonction de l'ordre (très spécifique)
743
		// ces deux lignes réordonnent l'ordre des colonnes des champs étendus en fonction de l'ordre (très spécifique)
751
		// de self::$ordre_champ_etendus_Florileges, les champs non-mentionnés sont ajoutés à la fin.
744
		// de self::$ordre_champ_etendus_Florileges, les champs non-mentionnés sont ajoutés à la fin.
752
		$colonnes_champs_supp_par_obs = self::sortArrayByArray(array_flip($colonnes_champs_supp_par_obs),
745
		$colonnes_champs_supp_par_obs = self::sortArrayByArray(array_flip($colonnes_champs_supp_par_obs),
753
															   self::$ordre_champ_etendus_Florileges);
746
															   self::$ordre_champ_etendus_Florileges);
754
		$colonnes_champs_supp_par_obs = array_keys($colonnes_champs_supp_par_obs);
747
		$colonnes_champs_supp_par_obs = array_keys($colonnes_champs_supp_par_obs);
755
 
748
 
756
		// si le SELECT des clefs ne retourne rien, une autre requêtes est inutile
749
		// si le SELECT des clefs ne retourne rien, une autre requêtes est inutile
757
		// TODO: optimize, 1 seule requête
750
		// TODO: optimize, 1 seule requête
758
		if(!$colonnes_champs_supp_par_obs) return Array('header' => array(), 'data' => array());
751
		if(!$colonnes_champs_supp_par_obs) return Array('header' => array(), 'data' => array());
759
 
752
 
760
		$champs_supp_par_obs = $gestion_champs_etendus->consulterParLots($obsids);
753
		$champs_supp_par_obs = $gestion_champs_etendus->consulterParLots($obsids);
761
 
754
 
762
		self::$cache['champsEtendus']['header'] = self::champsEtendus_prefixHeader($colonnes_champs_supp_par_obs);
755
		self::$cache['champsEtendus']['header'] = self::champsEtendus_prefixHeader($colonnes_champs_supp_par_obs);
763
 
756
 
764
		foreach($champs_supp_par_obs as &$v) {
757
		foreach($champs_supp_par_obs as &$v) {
765
			$v = self::champsEtendus_aplatir($v);
758
			$v = self::champsEtendus_aplatir($v);
766
		}
759
		}
767
		self::$cache['champsEtendus']['data'] = $champs_supp_par_obs;
760
		self::$cache['champsEtendus']['data'] = $champs_supp_par_obs;
768
		// ce return est temporaire,
761
		// ce return est temporaire,
769
		// le temps que toutes les fonctions bougent ici et utilise plutôt le cache statique
762
		// le temps que toutes les fonctions bougent ici et utilise plutôt le cache statique
770
		// encore utilisé pour les entêtes (self::$cache['champsEtendus']['header'])
763
		// encore utilisé pour les entêtes (self::$cache['champsEtendus']['header'])
771
		return self::$cache['champsEtendus'];
764
		return self::$cache['champsEtendus'];
772
	}
765
	}
773
 
766
 
774
	// XXX: PHP-5.3, fonction anonyme + array_map
767
	// XXX: PHP-5.3, fonction anonyme + array_map
775
	static function champsEtendus_prefixHeader($array) {
768
	static function champsEtendus_prefixHeader($array) {
776
		return array_map(create_function('$v', 'return "' . PREFIX_CHAMPS_ETENDUS . '".$v;'), $array);
769
		return array_map(create_function('$v', 'return "' . PREFIX_CHAMPS_ETENDUS . '".$v;'), $array);
777
	}
770
	}
778
 
771
 
779
	// XXX: PHP-5.3, fonction anonyme + array_map
772
	// XXX: PHP-5.3, fonction anonyme + array_map
780
	static function champsEtendus_aplatir($ligne_champs_etendus) {
773
	static function champsEtendus_aplatir($ligne_champs_etendus) {
781
		$champs_etendus_fmt = array();
774
		$champs_etendus_fmt = array();
782
		if(!$ligne_champs_etendus) return $champs_etendus_fmt;
775
		if(!$ligne_champs_etendus) return $champs_etendus_fmt;
783
		foreach($ligne_champs_etendus as $champ) {
776
		foreach($ligne_champs_etendus as $champ) {
784
			$champs_etendus_fmt[PREFIX_CHAMPS_ETENDUS . $champ->cle] = $champ->valeur;
777
			$champs_etendus_fmt[PREFIX_CHAMPS_ETENDUS . $champ->cle] = $champ->valeur;
785
		}
778
		}
786
		return $champs_etendus_fmt;
779
		return $champs_etendus_fmt;
787
	}
780
	}
788
 
781
 
789
	static function champsEtendus_ligne($obs, &$ligne) {
782
	static function champsEtendus_ligne($obs, &$ligne) {
790
		// si header n'est pas défini, aucune observation ne possède de champ étendu
783
		// si header n'est pas défini, aucune observation ne possède de champ étendu
791
		// et nous n'ajoutons ni colonnes, ni valeurs.
784
		// et nous n'ajoutons ni colonnes, ni valeurs.
792
		if(! isset(self::$cache['champsEtendus']['header'])) return;
785
		if(! isset(self::$cache['champsEtendus']['header'])) return;
793
		$ligne_etendue_aplatie = @self::$cache['champsEtendus']['data'][$obs['id_observation']];
786
		$ligne_etendue_aplatie = @self::$cache['champsEtendus']['data'][$obs['id_observation']];
794
 
787
 
795
		$ligne_supp = array_fill(0, count(self::$cache['champsEtendus']['header']), '');
788
		$ligne_supp = array_fill(0, count(self::$cache['champsEtendus']['header']), '');
796
		$ligne_etendue_fmt = array();
789
		$ligne_etendue_fmt = array();
797
 
790
 
798
		// si, cependant cette seule observation n'a pas de champs étendus,
791
		// si, cependant cette seule observation n'a pas de champs étendus,
799
		// nous devons rajouter des blancs (notamment dans le cas ou d'autres
792
		// nous devons rajouter des blancs (notamment dans le cas ou d'autres
800
		// champs viennent à être ajoutés en aval à l'avenir
793
		// champs viennent à être ajoutés en aval à l'avenir
801
		// cf: $fonction_dynamique dans FormateurGroupeColonne::GenColInfo()
794
		// cf: $fonction_dynamique dans FormateurGroupeColonne::GenColInfo()
802
		if(! $ligne_etendue_aplatie) {
795
		if(! $ligne_etendue_aplatie) {
803
			$ligne = array_merge($ligne, $ligne_supp);
796
			$ligne = array_merge($ligne, $ligne_supp);
804
			return;
797
			return;
805
		}
798
		}
806
 
799
 
807
		foreach(self::$cache['champsEtendus']['header'] as $colonne) {
800
		foreach(self::$cache['champsEtendus']['header'] as $colonne) {
808
			if(!isset($ligne_etendue_aplatie[$colonne])) {
801
			if(!isset($ligne_etendue_aplatie[$colonne])) {
809
				$ligne_etendue_fmt[$colonne] = '';
802
				$ligne_etendue_fmt[$colonne] = '';
810
			} else {
803
			} else {
811
				$ligne_etendue_fmt[$colonne] = $ligne_etendue_aplatie[$colonne];
804
				$ligne_etendue_fmt[$colonne] = $ligne_etendue_aplatie[$colonne];
812
			}
805
			}
813
		}
806
		}
814
 
807
 
815
		// XXX/ array_merge() ?
808
		// XXX/ array_merge() ?
816
		$ligne += $ligne_etendue_fmt;
809
		$ligne += $ligne_etendue_fmt;
817
	}
810
	}
818
 
811
 
819
	/* HELPERS */
812
	/* HELPERS */
820
 
813
 
821
	// http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
814
	// http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
822
	// XXX; redéfinition, utilisé aussi par ExportXLS
815
	// XXX; redéfinition, utilisé aussi par ExportXLS
823
	static function sortArrayByArray($array, $orderArray) {
816
	static function sortArrayByArray($array, $orderArray) {
824
		$ordered = array();
817
		$ordered = array();
825
		foreach($orderArray as $key) {
818
		foreach($orderArray as $key) {
826
			if(array_key_exists($key, $array)) {
819
			if(array_key_exists($key, $array)) {
827
				$ordered[$key] = $array[$key];
820
				$ordered[$key] = $array[$key];
828
				unset($array[$key]);
821
				unset($array[$key]);
829
			}
822
			}
830
		}
823
		}
831
		return $ordered + $array;
824
		return $ordered + $array;
832
	}
825
	}
833
 
826
 
834
}
827
}