Subversion Repositories eFlore/Applications.cel

Rev

Rev 3480 | Rev 3482 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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