Subversion Repositories eFlore/Applications.cel

Rev

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

Rev 3142 Rev 3147
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
				'nom_sel'			=> self::GenColInfo(Array('abbrev' => 'nom_sel',
141
				'nom_sel'			=> self::GenColInfo(Array('abbrev' => 'nom_sel',
142
															  'nom' => 'Espèce')),
142
															  'nom' => 'Espèce')),
143
				'nom_sel_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_sel_nn',
143
				'nom_sel_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_sel_nn',
144
															  'nom' => 'Numéro nomenclatural',
144
															  'nom' => 'Numéro nomenclatural',
145
															  'importable' => FALSE)),
145
															  'importable' => FALSE)),
146
				'nom_ret'			=> self::GenColInfo(Array('abbrev' => 'nom_ret',
146
				'nom_ret'			=> self::GenColInfo(Array('abbrev' => 'nom_ret',
147
															  'nom' => 'Nom retenu',
147
															  'nom' => 'Nom retenu',
148
															  'importable' => FALSE)),
148
															  'importable' => FALSE)),
149
				'nom_ret_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_ret_nn',
149
				'nom_ret_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_ret_nn',
150
															  'nom' => 'Numéro nomenclatural nom retenu',
150
															  'nom' => 'Numéro nomenclatural nom retenu',
151
															  'importable' => FALSE)),
151
															  'importable' => FALSE)),
152
				'nt'				=> self::GenColInfo(Array('abbrev' => 'nt',
152
				'nt'				=> self::GenColInfo(Array('abbrev' => 'nt',
153
															  'nom' => 'Numéro taxonomique',
153
															  'nom' => 'Numéro taxonomique',
154
															  'importable' => FALSE)),
154
															  'importable' => FALSE)),
155
				'famille'			=> self::GenColInfo(Array('abbrev' => 'famille',
155
				'famille'			=> self::GenColInfo(Array('abbrev' => 'famille',
156
															  'nom' => 'Famille',
156
															  'nom' => 'Famille',
157
															  'importable' => FALSE)),
157
															  'importable' => FALSE)),
158
				'nom_referentiel'	=> self::GenColInfo(Array('abbrev' => 'nom_referentiel',
158
				'nom_referentiel'	=> self::GenColInfo(Array('abbrev' => 'nom_referentiel',
159
															  'nom' => 'Referentiel taxonomique')),
159
															  'nom' => 'Referentiel taxonomique')),
160
				'pays'				=> self::GenColInfo(Array('abbrev' => 'pays',
160
				'pays'				=> self::GenColInfo(Array('abbrev' => 'pays',
161
															  'nom' => 'Pays')),
161
															  'nom' => 'Pays')),
162
				'zone_geo'			=> self::GenColInfo(Array('abbrev' => 'zone_geo',
162
				'zone_geo'			=> self::GenColInfo(Array('abbrev' => 'zone_geo',
163
															  'nom' => 'Commune')),
163
															  'nom' => 'Commune')),
164
				'ce_zone_geo'		=> self::GenColInfo(Array('abbrev' => 'ce_zone_geo',
164
				'ce_zone_geo'		=> self::GenColInfo(Array('abbrev' => 'ce_zone_geo',
165
															  'nom' => 'Identifiant Commune',
165
															  'nom' => 'Identifiant Commune',
166
															  'fonction' => 'convertirCodeZoneGeoVersDepartement')),
166
															  'fonction' => 'convertirCodeZoneGeoVersDepartement')),
167
				'date_observation'	=> self::GenColInfo(Array('abbrev' => 'date_observation',
167
				'date_observation'	=> self::GenColInfo(Array('abbrev' => 'date_observation',
168
															  'nom' => 'Date',
168
															  'nom' => 'Date',
169
															  'fonction' => 'formaterDate')),
169
															  'fonction' => 'formaterDate')),
170
				'lieudit'			=> self::GenColInfo(Array('abbrev' => 'lieudit',
170
				'lieudit'			=> self::GenColInfo(Array('abbrev' => 'lieudit',
171
															  'nom' => 'Lieu-dit')),
171
															  'nom' => 'Lieu-dit')),
172
				'station'			=> self::GenColInfo(Array('abbrev' => 'station',
172
				'station'			=> self::GenColInfo(Array('abbrev' => 'station',
173
															  'nom' => 'Station')),
173
															  'nom' => 'Station')),
174
				'milieu'			=> self::GenColInfo(Array('abbrev' => 'milieu',
174
				'milieu'			=> self::GenColInfo(Array('abbrev' => 'milieu',
175
															  'nom' => 'Milieu')),
175
															  'nom' => 'Milieu')),
176
				'commentaire'		=> self::GenColInfo(Array('abbrev' => 'commentaire',
176
				'commentaire'		=> self::GenColInfo(Array('abbrev' => 'commentaire',
177
															  'nom' => 'Notes')),
177
															  'nom' => 'Notes')),
178
				'latitude'			=> self::GenColInfo(Array('abbrev' => 'latitude',
178
				'latitude'			=> self::GenColInfo(Array('abbrev' => 'latitude',
179
															  'nom' => 'Latitude',
179
															  'nom' => 'Latitude',
180
															  'extra' => 1,
180
															  'extra' => 1,
181
															  'fonction' => 'trim0')),
181
															  'fonction' => 'trim0')),
182
				'longitude'			=> self::GenColInfo(Array('abbrev' => 'longitude',
182
				'longitude'			=> self::GenColInfo(Array('abbrev' => 'longitude',
183
															  'nom' => 'Longitude',
183
															  'nom' => 'Longitude',
184
															  'extra' => 1,
184
															  'extra' => 1,
185
															  'fonction' => 'trim0')),
185
															  'fonction' => 'trim0')),
186
				'altitude'			=> self::GenColInfo(Array('abbrev' => 'altitude',
186
				'altitude'			=> self::GenColInfo(Array('abbrev' => 'altitude',
187
															  'nom' => 'Altitude',
187
															  'nom' => 'Altitude',
188
															  'extra' => 1)), // pas de trim0 car INT(5) en DB
188
															  'extra' => 1)), // pas de trim0 car INT(5) en DB
189
				'geodatum'			=> self::GenColInfo(Array('abbrev' => 'geodatum',
189
				'geodatum'			=> self::GenColInfo(Array('abbrev' => 'geodatum',
190
															  'nom' => 'Référentiel Géographique',
190
															  'nom' => 'Référentiel Géographique',
191
															  'extra' => 1,
191
															  'extra' => 1,
192
															  'importable' => FALSE)),
192
															  'importable' => FALSE)),
193
				'programme'			=> self::GenColInfo(Array('abbrev' => 'programme',
193
				'programme'			=> self::GenColInfo(Array('abbrev' => 'programme',
194
																'nom' => 'Programme de sciences participatives ou observatoire citoyen',
194
																'nom' => 'Programme de sciences participatives ou observatoire citoyen',
195
																'importable' => FALSE)),
195
																'importable' => FALSE)),
196
				'mots_cles_texte'	=> self::GenColInfo(Array('abbrev' => 'mots_cles_texte',
196
				'mots_cles_texte'	=> self::GenColInfo(Array('abbrev' => 'mots_cles_texte',
197
																'nom' => 'Mots Clés',
197
																'nom' => 'Mots Clés',
198
																'importable' => FALSE)),
198
																'importable' => FALSE)),
199
				'certitude'			=> self::GenColInfo(Array('abbrev' => 'certitude',
199
				'certitude'			=> self::GenColInfo(Array('abbrev' => 'certitude',
200
															'nom' => 'Certitude',
200
															'nom' => 'Certitude',
201
															'extra' => 1)),
201
															'extra' => 1)),
202
				'images'			=> self::GenColInfo(Array('abbrev' => 'images',
202
				'image'			=> self::GenColInfo(Array('abbrev' => 'image',
203
															'nom' => 'Image(s)',
203
															'nom' => 'Image(s)',
204
															'extra' => 1)),
204
															'extra' => 1)),
205
				'validation_identiplante'			=> self::GenColInfo(Array('abbrev' => 'validation_identiplante',
205
				'validation_identiplante'			=> self::GenColInfo(Array('abbrev' => 'validation_identiplante',
206
															'nom' => 'Détermination validée sur IdentiPlante',
206
															'nom' => 'Détermination validée sur IdentiPlante',
207
															'importable' => FALSE)),
207
															'importable' => FALSE)),
208
				'url_identiplante'			=> self::GenColInfo(Array('abbrev' => 'url_identiplante',
208
				'url_identiplante'			=> self::GenColInfo(Array('abbrev' => 'url_identiplante',
209
															'nom' => "Lien vers l'observation sur IdentiPlante",
209
															'nom' => "Lien vers l'observation sur IdentiPlante",
210
															'importable' => FALSE)),
210
															'importable' => FALSE)),
211
			);
211
			);
212
		} elseif (isset($groupe_de_champs['standard'])) {
212
		} elseif (isset($groupe_de_champs['standard'])) {
213
			$colonnes += Array(
213
			$colonnes += Array(
214
					'nom_sel'			=> self::GenColInfo(Array('abbrev' => 'nom_sel',
214
					'nom_sel'			=> self::GenColInfo(Array('abbrev' => 'nom_sel',
215
							'nom' => 'Espèce')),
215
							'nom' => 'Espèce')),
216
					'nom_sel_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_sel_nn',
216
					'nom_sel_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_sel_nn',
217
							'nom' => 'Numéro nomenclatural',
217
							'nom' => 'Numéro nomenclatural',
218
							'importable' => FALSE)),
218
							'importable' => FALSE)),
219
					'nom_ret'			=> self::GenColInfo(Array('abbrev' => 'nom_ret',
219
					'nom_ret'			=> self::GenColInfo(Array('abbrev' => 'nom_ret',
220
							'nom' => 'Nom retenu',
220
							'nom' => 'Nom retenu',
221
							'importable' => FALSE)),
221
							'importable' => FALSE)),
222
					'nom_ret_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_ret_nn',
222
					'nom_ret_nn'		=> self::GenColInfo(Array('abbrev' => 'nom_ret_nn',
223
							'nom' => 'Numéro nomenclatural nom retenu',
223
							'nom' => 'Numéro nomenclatural nom retenu',
224
							'importable' => FALSE)),
224
							'importable' => FALSE)),
225
					'nt'				=> self::GenColInfo(Array('abbrev' => 'nt',
225
					'nt'				=> self::GenColInfo(Array('abbrev' => 'nt',
226
							'nom' => 'Numéro taxonomique',
226
							'nom' => 'Numéro taxonomique',
227
							'importable' => FALSE)),
227
							'importable' => FALSE)),
228
					'famille'			=> self::GenColInfo(Array('abbrev' => 'famille',
228
					'famille'			=> self::GenColInfo(Array('abbrev' => 'famille',
229
							'nom' => 'Famille',
229
							'nom' => 'Famille',
230
							'importable' => FALSE)),
230
							'importable' => FALSE)),
231
					'nom_referentiel'	=> self::GenColInfo(Array('abbrev' => 'nom_referentiel',
231
					'nom_referentiel'	=> self::GenColInfo(Array('abbrev' => 'nom_referentiel',
232
							'nom' => 'Referentiel taxonomique')),
232
							'nom' => 'Referentiel taxonomique')),
233
					'pays'				=> self::GenColInfo(Array('abbrev' => 'pays',
233
					'pays'				=> self::GenColInfo(Array('abbrev' => 'pays',
234
							'nom' => 'Pays')),
234
							'nom' => 'Pays')),
235
					'zone_geo'			=> self::GenColInfo(Array('abbrev' => 'zone_geo',
235
					'zone_geo'			=> self::GenColInfo(Array('abbrev' => 'zone_geo',
236
							'nom' => 'Commune')),
236
							'nom' => 'Commune')),
237
					'ce_zone_geo'		=> self::GenColInfo(Array('abbrev' => 'ce_zone_geo',
237
					'ce_zone_geo'		=> self::GenColInfo(Array('abbrev' => 'ce_zone_geo',
238
							'nom' => 'Identifiant Commune',
238
							'nom' => 'Identifiant Commune',
239
							'fonction' => 'convertirCodeZoneGeoVersDepartement')),
239
							'fonction' => 'convertirCodeZoneGeoVersDepartement')),
240
					'date_observation'	=> self::GenColInfo(Array('abbrev' => 'date_observation',
240
					'date_observation'	=> self::GenColInfo(Array('abbrev' => 'date_observation',
241
							'nom' => 'Date',
241
							'nom' => 'Date',
242
							'fonction' => 'formaterDate')),
242
							'fonction' => 'formaterDate')),
243
					'lieudit'			=> self::GenColInfo(Array('abbrev' => 'lieudit',
243
					'lieudit'			=> self::GenColInfo(Array('abbrev' => 'lieudit',
244
							'nom' => 'Lieu-dit')),
244
							'nom' => 'Lieu-dit')),
245
					'station'			=> self::GenColInfo(Array('abbrev' => 'station',
245
					'station'			=> self::GenColInfo(Array('abbrev' => 'station',
246
							'nom' => 'Station')),
246
							'nom' => 'Station')),
247
					'milieu'			=> self::GenColInfo(Array('abbrev' => 'milieu',
247
					'milieu'			=> self::GenColInfo(Array('abbrev' => 'milieu',
248
							'nom' => 'Milieu')),
248
							'nom' => 'Milieu')),
249
					'commentaire'		=> self::GenColInfo(Array('abbrev' => 'commentaire',
249
					'commentaire'		=> self::GenColInfo(Array('abbrev' => 'commentaire',
250
							'nom' => 'Notes')),
250
							'nom' => 'Notes')),
251
					'latitude'			=> self::GenColInfo(Array('abbrev' => 'latitude',
251
					'latitude'			=> self::GenColInfo(Array('abbrev' => 'latitude',
252
							'nom' => 'Latitude',
252
							'nom' => 'Latitude',
253
							'extra' => 1,
253
							'extra' => 1,
254
							'fonction' => 'trim0')),
254
							'fonction' => 'trim0')),
255
					'longitude'			=> self::GenColInfo(Array('abbrev' => 'longitude',
255
					'longitude'			=> self::GenColInfo(Array('abbrev' => 'longitude',
256
							'nom' => 'Longitude',
256
							'nom' => 'Longitude',
257
							'extra' => 1,
257
							'extra' => 1,
258
							'fonction' => 'trim0')),
258
							'fonction' => 'trim0')),
259
					'altitude'			=> self::GenColInfo(Array('abbrev' => 'altitude',
259
					'altitude'			=> self::GenColInfo(Array('abbrev' => 'altitude',
260
							'nom' => 'Altitude',
260
							'nom' => 'Altitude',
261
							'extra' => 1)), // pas de trim0 car INT(5) en DB
261
							'extra' => 1)), // pas de trim0 car INT(5) en DB
262
					'geodatum'			=> self::GenColInfo(Array('abbrev' => 'geodatum',
262
					'geodatum'			=> self::GenColInfo(Array('abbrev' => 'geodatum',
263
							'nom' => 'Référentiel Géographique',
263
							'nom' => 'Référentiel Géographique',
264
							'extra' => 1,
264
							'extra' => 1,
265
							'importable' => FALSE)),
265
							'importable' => FALSE)),
266
					);
266
					);
267
		}
267
		}
268
 
268
 
269
		if(isset($groupe_de_champs['avance'])) {
269
		if(isset($groupe_de_champs['avance'])) {
270
			$colonnes += array(
270
			$colonnes += array(
271
				// TODO: importable = FALSE car pas de merge de données importées
271
				// TODO: importable = FALSE car pas de merge de données importées
272
				'ordre'				=> self::GenColInfo(Array('abbrev' => 'ordre',
272
				'ordre'				=> self::GenColInfo(Array('abbrev' => 'ordre',
273
															  'nom' => 'Ordre',
273
															  'nom' => 'Ordre',
274
															  'extra' => 1,
274
															  'extra' => 1,
275
															  'importable' => FALSE)),
275
															  'importable' => FALSE)),
276
				'id_observation'	=> self::GenColInfo(Array('abbrev' => 'id_observation',
276
				'id_observation'	=> self::GenColInfo(Array('abbrev' => 'id_observation',
277
															  'nom' => 'Identifiant',
277
															  'nom' => 'Identifiant',
278
															  'extra' => 1,
278
															  'extra' => 1,
279
															  'importable' => FALSE)),
279
															  'importable' => FALSE)),
280
 
280
 
281
				'mots_cles_texte'	=> self::GenColInfo(Array('abbrev' => 'mots_cles_texte',
281
				'mots_cles_texte'	=> self::GenColInfo(Array('abbrev' => 'mots_cles_texte',
282
															  'nom' => 'Mots Clés',
282
															  'nom' => 'Mots Clés',
283
															  'extra' => 1)),
283
															  'extra' => 1)),
284
				'date_creation'		=> self::GenColInfo(Array('abbrev' => 'date_creation',
284
				'date_creation'		=> self::GenColInfo(Array('abbrev' => 'date_creation',
285
															  'nom' => 'Date Création',
285
															  'nom' => 'Date Création',
286
															  'extra' => 1,
286
															  'extra' => 1,
287
															  'importable' => FALSE)),
287
															  'importable' => FALSE)),
288
				'date_modification'	=> self::GenColInfo(Array('abbrev' => 'date_modification',
288
				'date_modification'	=> self::GenColInfo(Array('abbrev' => 'date_modification',
289
															  'nom' => 'Date Modification',
289
															  'nom' => 'Date Modification',
290
															  'extra' => 1,
290
															  'extra' => 1,
291
															  'importable' => FALSE)),
291
															  'importable' => FALSE)),
292
 
292
 
293
				// rappel transmission = 1, signifie simplement "public"
293
				// rappel transmission = 1, signifie simplement "public"
294
				// des données importées peuvent être d'emblée "publiques"
294
				// des données importées peuvent être d'emblée "publiques"
295
				// "importable" = TRUE
295
				// "importable" = TRUE
296
				'transmission'		=> self::GenColInfo(Array('abbrev' => 'transmission',
296
				'transmission'		=> self::GenColInfo(Array('abbrev' => 'transmission',
297
															  'nom' => 'Transmis',
297
															  'nom' => 'Transmis',
298
															  'extra' => 1,
298
															  'extra' => 1,
299
															  'fonction' => 'boolOuiNon')),
299
															  'fonction' => 'boolOuiNon')),
300
				'date_transmission'	=> self::GenColInfo(Array('abbrev' => 'date_transmission',
300
				'date_transmission'	=> self::GenColInfo(Array('abbrev' => 'date_transmission',
301
															  'nom' => 'Date Transmission',
301
															  'nom' => 'Date Transmission',
302
															  'extra' => 1,
302
															  'extra' => 1,
303
															  'importable' => FALSE)),
303
															  'importable' => FALSE)),
304
				'abondance'			=> self::GenColInfo(Array('abbrev' => 'abondance',
304
				'abondance'			=> self::GenColInfo(Array('abbrev' => 'abondance',
305
															  'nom' => 'Abondance',
305
															  'nom' => 'Abondance',
306
															  'extra' => 1)),
306
															  'extra' => 1)),
307
				'certitude'			=> self::GenColInfo(Array('abbrev' => 'certitude',
307
				'certitude'			=> self::GenColInfo(Array('abbrev' => 'certitude',
308
															  'nom' => 'Certitude',
308
															  'nom' => 'Certitude',
309
															  'extra' => 1)),
309
															  'extra' => 1)),
310
				'phenologie'		=> self::GenColInfo(Array('abbrev' => 'phenologie',
310
				'phenologie'		=> self::GenColInfo(Array('abbrev' => 'phenologie',
311
															  'nom' => 'Phénologie',
311
															  'nom' => 'Phénologie',
312
															  'extra' => 1)),
312
															  'extra' => 1)),
313
 
313
 
314
				// XXX: getImages() dépend du contexte de Cel, et doit être appelée comme cas particulier
314
				// XXX: getImages() dépend du contexte de Cel, et doit être appelée comme cas particulier
315
				// cf ExportXLS::traiterLigneObservation()
315
				// cf ExportXLS::traiterLigneObservation()
316
				'images'			=> self::GenColInfo(Array('abbrev' => 'images',
316
				'images'			=> self::GenColInfo(Array('abbrev' => 'images',
317
															  'nom' => 'Image(s)',
317
															  'nom' => 'Image(s)',
318
															  'extra' => 1,
318
															  'extra' => 1,
319
															  'fonction_data' => NULL /* cas particulier 'getImages' */,
319
															  'fonction_data' => NULL /* cas particulier 'getImages' */,
320
															  'importable' => TRUE,
320
															  'importable' => TRUE,
321
															  //'preload' => array(__CLASS__, 'getImages_preload')//TODO
321
															  //'preload' => array(__CLASS__, 'getImages_preload')//TODO
322
				)),
322
				)),
323
 
323
 
324
				/* 'nom_commun'			=> self::GenColInfo(Array('abbrev' => 'nom_commun',
324
				/* 'nom_commun'			=> self::GenColInfo(Array('abbrev' => 'nom_commun',
325
				   'nom' => 'Nom Commun',
325
				   'nom' => 'Nom Commun',
326
				   'extra' => 1,
326
				   'extra' => 1,
327
				   'fonction_data' => 'getNomCommun',
327
				   'fonction_data' => 'getNomCommun',
328
				   'importable' => FALSE),
328
				   'importable' => FALSE),
329
 
329
 
330
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
330
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
331
				   'nom' => 'Nom Commun',
331
				   'nom' => 'Nom Commun',
332
				   'extra' => 1,
332
				   'extra' => 1,
333
				   'fonction_data' => 'getNomCommun_v2'),
333
				   'fonction_data' => 'getNomCommun_v2'),
334
 
334
 
335
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
335
				   'nom-commun'			=> self::GenColInfo(Array('abbrev' => 'nom-commun',
336
				   'nom' => 'Nom Commun',
336
				   'nom' => 'Nom Commun',
337
				   'extra' => 1,
337
				   'extra' => 1,
338
				   'fonction_data' => 'getNomCommun_v3'),
338
				   'fonction_data' => 'getNomCommun_v3'),
339
				   'importable' => FALSE), */
339
				   'importable' => FALSE), */
340
				'nom-commun' => self::GenColInfo(array(
340
				'nom-commun' => self::GenColInfo(array(
341
					'abbrev' => 'nom-commun',
341
					'abbrev' => 'nom-commun',
342
					'nom' => 'Nom Commun',
342
					'nom' => 'Nom Commun',
343
					'extra' => 1,
343
					'extra' => 1,
344
					'fonction_data' => null /* cas particu 'getNomCommun_v4' */,
344
					'fonction_data' => null /* cas particu 'getNomCommun_v4' */,
345
					'preload' => array(__CLASS__, 'getNomCommun_preload')))
345
					'preload' => array(__CLASS__, 'getNomCommun_preload')))
346
			);
346
			);
347
		}
347
		}
348
 
348
 
349
		if(isset($groupe_de_champs['baseflor'])) {
349
		if(isset($groupe_de_champs['baseflor'])) {
350
			$colonnes += array(
350
			$colonnes += array(
351
				// champ dynamique
351
				// champ dynamique
352
				'baseflor' => self::GenColInfo(array(
352
				'baseflor' => self::GenColInfo(array(
353
					'abbrev' => 'baseflor',
353
					'abbrev' => 'baseflor',
354
					'nom' => '',
354
					'nom' => '',
355
					'extra' => 1,
355
					'extra' => 1,
356
					'importable' => false,
356
					'importable' => false,
357
					'preload' => array(__CLASS__, 'baseflor_preload'),
357
					'preload' => array(__CLASS__, 'baseflor_preload'),
358
					'dyna' => array(__CLASS__, 'baseflor_ligne'))),
358
					'dyna' => array(__CLASS__, 'baseflor_ligne'))),
359
			);
359
			);
360
		}
360
		}
361
 
361
 
362
		if (isset($groupe_de_champs['etendu'])) {
362
		if (isset($groupe_de_champs['etendu'])) {
363
			$colonnes += array(
363
			$colonnes += array(
364
				// champ dynamique
364
				// champ dynamique
365
				'etendu' => self::GenColInfo(array(
365
				'etendu' => self::GenColInfo(array(
366
					'abbrev' => 'etendu',
366
					'abbrev' => 'etendu',
367
					'nom' => '',
367
					'nom' => '',
368
					'extra' => 1,
368
					'extra' => 1,
369
					'importable' => false,
369
					'importable' => false,
370
					'preload' => array(__CLASS__, 'champsEtendus_preload'),
370
					'preload' => array(__CLASS__, 'champsEtendus_preload'),
371
					'dyna' => array(__CLASS__, 'champsEtendus_ligne'))),
371
					'dyna' => array(__CLASS__, 'champsEtendus_ligne'))),
372
			);
372
			);
373
		}
373
		}
374
 
374
 
375
		if (isset($groupe_de_champs['auteur'])) {
375
		if (isset($groupe_de_champs['auteur'])) {
376
			$colonnes += array(
376
			$colonnes += array(
377
				'observateur' => self::GenColInfo(array(
377
				'observateur' => self::GenColInfo(array(
378
					'abbrev' => 'observateur',
378
					'abbrev' => 'observateur',
379
					'nom' => 'Observateur',
379
					'nom' => 'Observateur',
380
					'extra' => 1,
380
					'extra' => 1,
381
					'fonction_data' => 'formaterUrlUser',
381
					'fonction_data' => 'formaterUrlUser',
382
					'importable' => false)),
382
					'importable' => false)),
383
			);
383
			);
384
		}
384
		}
385
		return $colonnes;
385
		return $colonnes;
386
	}
386
	}
387
 
387
 
388
	static function preload($colonnes, $cel, $ids) {
388
	static function preload($colonnes, $cel, $ids) {
389
		$result = array();
389
		$result = array();
390
		foreach ($colonnes as $abbrev => $colonne) {
390
		foreach ($colonnes as $abbrev => $colonne) {
391
			if (!$colonne['preload']) {
391
			if (!$colonne['preload']) {
392
				continue;
392
				continue;
393
			}
393
			}
394
			$result[$abbrev] = call_user_func($colonne['preload'], $cel, $ids);
394
			$result[$abbrev] = call_user_func($colonne['preload'], $cel, $ids);
395
		}
395
		}
396
		return $result;
396
		return $result;
397
	}
397
	}
398
 
398
 
399
	public static function getIntitulesColonnes($colonnes) {
399
	public static function getIntitulesColonnes($colonnes) {
400
		// array_filter pour supprimer les colonnes "dynamique" n'ayant pas défini $nom (cf GenColInfo())
400
		// array_filter pour supprimer les colonnes "dynamique" n'ayant pas défini $nom (cf GenColInfo())
401
		return array_filter(array_map(array('FormateurGroupeColonne', 'retournerNomItem'), $colonnes));
401
		return array_filter(array_map(array('FormateurGroupeColonne', 'retournerNomItem'), $colonnes));
402
	}
402
	}
403
 
403
 
404
	public static function retournerNomItem(&$item) {
404
	public static function retournerNomItem(&$item) {
405
		return $item['nom'];
405
		return $item['nom'];
406
	}
406
	}
407
 
407
 
408
	public static function getLigneObservation(&$obs, &$colonnes, $cel = false) {
408
	public static function getLigneObservation(&$obs, &$colonnes, $cel = false) {
409
		$ligne_formatee = array();
409
		$ligne_formatee = array();
410
		foreach($colonnes as $abbrev => $colonne) {
410
		foreach($colonnes as $abbrev => $colonne) {
411
			$valeur = null;
411
			$valeur = null;
412
			if ($colonne['extra'] == 2 || ! is_null($colonne['dyna'])) {
412
			if ($colonne['extra'] == 2 || ! is_null($colonne['dyna'])) {
413
				continue;
413
				continue;
414
			}
414
			}
415
 
415
 
416
			// valeur directe depuis cel_obs ?
416
			// valeur directe depuis cel_obs ?
417
			if (isset($obs[$abbrev])) {
417
			if (isset($obs[$abbrev])) {
418
				$valeur = $obs[$abbrev];
418
				$valeur = $obs[$abbrev];
419
			}
419
			}
420
 
420
 
421
			// pré-processeur des champs
421
			// pré-processeur des champs
422
			if (function_exists($colonne['fonction'])) {
422
			if (function_exists($colonne['fonction'])) {
423
				$valeur = $colonne['fonction']($valeur);
423
				$valeur = $colonne['fonction']($valeur);
424
			} else if(method_exists(__CLASS__, $colonne['fonction'])) {
424
			} else if(method_exists(__CLASS__, $colonne['fonction'])) {
425
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
425
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction']), $valeur);
426
			} else if($colonne['fonction']) {
426
			} else if($colonne['fonction']) {
427
				die("méthode {$colonne['fonction']} introuvable");
427
				die("méthode {$colonne['fonction']} introuvable");
428
			} else if(function_exists($colonne['fonction_data'])) {// fonction pour obtenir des champs (étendus)
428
			} else if(function_exists($colonne['fonction_data'])) {// fonction pour obtenir des champs (étendus)
429
				$valeur = $colonne['fonction_data']($obs);
429
				$valeur = $colonne['fonction_data']($obs);
430
			} else if(method_exists(__CLASS__, $colonne['fonction_data'])) {
430
			} else if(method_exists(__CLASS__, $colonne['fonction_data'])) {
431
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
431
				$valeur = call_user_func(array(__CLASS__, $colonne['fonction_data']), $obs);
432
			}
432
			}
433
 
433
 
434
			// // cette section devrait être vide:
434
			// // cette section devrait être vide:
435
			// // cas particuliers ingérable avec l'architecture actuelle:
435
			// // cas particuliers ingérable avec l'architecture actuelle:
436
			if (false && $abbrev == 'date_observation' && $valeur == '0000-00-00') {
436
			if (false && $abbrev == 'date_observation' && $valeur == '0000-00-00') {
437
				/* blah */
437
				/* blah */
438
			}
438
			}
439
			// ici à cause du passage de $cel ($this->utilisateur)
439
			// ici à cause du passage de $cel ($this->utilisateur)
440
			if ($abbrev == 'images') {
440
			if ($abbrev == 'images') {
441
				$valeur = FormateurGroupeColonne::getImages($obs, $cel->id_utilisateur);
441
				$valeur = FormateurGroupeColonne::getImages($obs, $cel->id_utilisateur);
442
			}
442
			}
443
			if ($abbrev == 'nom-commun') {
443
			if ($abbrev == 'nom-commun') {
444
				$valeur = FormateurGroupeColonne::getNomCommun_v4($obs);
444
				$valeur = FormateurGroupeColonne::getNomCommun_v4($obs);
445
			}
445
			}
446
 
446
 
447
			if ($valeur == null) {
447
			if ($valeur == null) {
448
				$valeur = '';
448
				$valeur = '';
449
			}
449
			}
450
 
450
 
451
			// fin de section "cas particuliers"
451
			// fin de section "cas particuliers"
452
			$ligne_formatee[] = $valeur;
452
			$ligne_formatee[] = $valeur;
453
		}
453
		}
454
 
454
 
455
		// uniquement les champs dynamiques
455
		// uniquement les champs dynamiques
456
		foreach($colonnes as $abbrev => $colonne) {
456
		foreach($colonnes as $abbrev => $colonne) {
457
			$valeur = null;
457
			$valeur = null;
458
			if (is_null($colonne['dyna'])) {
458
			if (is_null($colonne['dyna'])) {
459
				continue;
459
				continue;
460
			}
460
			}
461
			call_user_func_array($colonne['dyna'], array($obs, &$ligne_formatee));
461
			call_user_func_array($colonne['dyna'], array($obs, &$ligne_formatee));
462
		}
462
		}
463
		return $ligne_formatee;
463
		return $ligne_formatee;
464
	}
464
	}
465
 
465
 
466
	/*
466
	/*
467
	* Wrapper générant un tableau associatif:
467
	* Wrapper générant un tableau associatif:
468
	* Ne pas changer les valeurs par défaut du prototype sans réflexion sur l'implication pour nomEnsembleVersListeColonnes()
468
	* Ne pas changer les valeurs par défaut du prototype sans réflexion sur l'implication pour nomEnsembleVersListeColonnes()
469
 
469
 
470
	* @param $abbrev (obligatoire): nom court de colonne, largement utilisé lors de l'import.
470
	* @param $abbrev (obligatoire): nom court de colonne, largement utilisé lors de l'import.
471
	*		  En effet chaque ligne importée est accessible à l'aide du `define` de $abbrev en majuscule, préfixé de "C_"
471
	*		  En effet chaque ligne importée est accessible à l'aide du `define` de $abbrev en majuscule, préfixé de "C_"
472
	*		  Exemple: $ligne[C_LONGITUDE] pour "longitude".
472
	*		  Exemple: $ligne[C_LONGITUDE] pour "longitude".
473
	*		  cf: ImportXLS::detectionEntete()
473
	*		  cf: ImportXLS::detectionEntete()
474
 
474
 
475
	* @param $nom (obligatoire): nom complet de colonne (utilisé pour la ligne d'en-tête)
475
	* @param $nom (obligatoire): nom complet de colonne (utilisé pour la ligne d'en-tête)
476
	*		  Les définition de champs dynamique (correspondant à de multiples colonnes) doivent laisser cette valeur
476
	*		  Les définition de champs dynamique (correspondant à de multiples colonnes) doivent laisser cette valeur
477
	*		  vide afin de ne pas créer une colonne supplémentaire erronée.
477
	*		  vide afin de ne pas créer une colonne supplémentaire erronée.
478
 
478
 
479
	* @param $is_extra:
479
	* @param $is_extra:
480
	* Si 0, la colonne est une colonne standard
480
	* Si 0, la colonne est une colonne standard
481
	* Si 1, la colonne est extra [le plus souvent générée automatiquement]
481
	* Si 1, la colonne est extra [le plus souvent générée automatiquement]
482
	*		 (auquel cas une bordure bleue entoure son nom dans la ligne d'entête)
482
	*		 (auquel cas une bordure bleue entoure son nom dans la ligne d'entête)
483
	* Si 2, la colonne n'est pas traité à l'export, mais une définition peut lui être donnée
483
	* Si 2, la colonne n'est pas traité à l'export, mais une définition peut lui être donnée
484
	*		 qui pourra être utilisée à l'import, exemple: "image"
484
	*		 qui pourra être utilisée à l'import, exemple: "image"
485
 
485
 
486
	* @param $fonction (optionnel): un nom d'un fonction de préprocessing
486
	* @param $fonction (optionnel): un nom d'un fonction de préprocessing
487
	* 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
487
	* 		  $fonction doit prendre comme seul argument la valeur d'origine et retourner la valeur transformée
488
 
488
 
489
	* @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
489
	* @param $fonction_data (optionnel): une *méthode* d'obtention de donnée
490
	* 		  $fonction_data doit prendre comme premier argument le tableau des champs de l'enregistrement existant
490
	* 		  $fonction_data doit prendre comme premier argument le tableau des champs de l'enregistrement existant
491
	*		  $fonction_data doit retourner une valeur
491
	*		  $fonction_data doit retourner une valeur
492
 
492
 
493
	* @param $importable (optionnel): défini si la colonne est traitée (ou absolument ignorée par PHPExcel) lors de
493
	* @param $importable (optionnel): défini si la colonne est traitée (ou absolument ignorée par PHPExcel) lors de
494
	*		  l'import.
494
	*		  l'import.
495
 
495
 
496
	* @param $preload (optionnel): défini une fonction de préchargement massif de donnée potentiellement utilisable par $fonction_data.
496
	* @param $preload (optionnel): défini une fonction de préchargement massif de donnée potentiellement utilisable par $fonction_data.
497
	*		  Utile, notamment, dans le cadre de l'export
497
	*		  Utile, notamment, dans le cadre de l'export
498
 
498
 
499
	* @param $fonction_dynamique (optionnel): défini une fonction ajoutant un nombre arbitraire de colonnes à une ligne donnée
499
	* @param $fonction_dynamique (optionnel): défini une fonction ajoutant un nombre arbitraire de colonnes à une ligne donnée
500
	*		  Utile, notamment, dans le cadre de l'export des champs étendus ou des données baseflor
500
	*		  Utile, notamment, dans le cadre de l'export des champs étendus ou des données baseflor
501
	*		  La fonction doit TOUJOURS alterer la ligne en lui ajoutant une nombre CONSTANT d'éléments (NULL ou non)
501
	*		  La fonction doit TOUJOURS alterer la ligne en lui ajoutant une nombre CONSTANT d'éléments (NULL ou non)
502
	*		  La fonction doit prendre comme arguments ($obs, &$ligne_formatee)
502
	*		  La fonction doit prendre comme arguments ($obs, &$ligne_formatee)
503
	*/
503
	*/
504
	static function GenColInfo($args) {
504
	static function GenColInfo($args) {
505
		$default = array(
505
		$default = array(
506
			'abbrev' => null,
506
			'abbrev' => null,
507
			'nom' => null,
507
			'nom' => null,
508
			'extra' => 0,
508
			'extra' => 0,
509
			'fonction' => null,
509
			'fonction' => null,
510
			'fonction_data' => null,
510
			'fonction_data' => null,
511
			'importable' => true,
511
			'importable' => true,
512
			'preload' => null,
512
			'preload' => null,
513
			'dyna' => null);
513
			'dyna' => null);
514
		$ret = array_intersect_key($args, $default);
514
		$ret = array_intersect_key($args, $default);
515
		return array_merge($default, $ret);
515
		return array_merge($default, $ret);
516
	}
516
	}
517
 
517
 
518
	static function formaterDate($date_heure_mysql) {
518
	static function formaterDate($date_heure_mysql) {
519
		//return "";
519
		//return "";
520
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") {
520
		if (!$date_heure_mysql || $date_heure_mysql == "0000-00-00 00:00:00") {
521
			return null;
521
			return null;
522
		}
522
		}
523
		// malheureusement pas disponible en php < 5.3
523
		// malheureusement pas disponible en php < 5.3
524
		//$date_format = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql);
524
		//$date_format = DateTime::createFromFormat("Y-m-d H:i:s", $date_heure_mysql);
525
		$val = explode(' ', $date_heure_mysql);
525
		$val = explode(' ', $date_heure_mysql);
526
		$date = explode('-', $val[0]);
526
		$date = explode('-', $val[0]);
527
		$heure = explode(':', $val[1]);
527
		$heure = explode(':', $val[1]);
528
		$timestamp = mktime((int) $heure[0], (int) $heure[1], (int) $heure[2], (int) $date[1], (int) $date[2], (int) $date[0]);
528
		$timestamp = mktime((int) $heure[0], (int) $heure[1], (int) $heure[2], (int) $date[1], (int) $date[2], (int) $date[0]);
529
		if (!$timestamp) {
529
		if (!$timestamp) {
530
			return null;
530
			return null;
531
		}
531
		}
532
		// TODO: les widgets ne font malheureusement pas usage de l'heure dans le CEL
532
		// TODO: les widgets ne font malheureusement pas usage de l'heure dans le CEL
533
		// TODO: si modification, ne pas oublier de modifier le format d'import correspondant
533
		// TODO: si modification, ne pas oublier de modifier le format d'import correspondant
534
		//	dans ImportXLS, traiterDateObs() (actuellement: "Y/m/d" car utilisation de strtotime() qui ne lit pas tout)
534
		//	dans ImportXLS, traiterDateObs() (actuellement: "Y/m/d" car utilisation de strtotime() qui ne lit pas tout)
535
		// $date_formatee = strftime('%d/%m/%Y', $timestamp);
535
		// $date_formatee = strftime('%d/%m/%Y', $timestamp);
536
		$date_formatee = strftime('%Y/%m/%d', $timestamp);
536
		$date_formatee = strftime('%Y/%m/%d', $timestamp);
537
		if (!$date_formatee) {
537
		if (!$date_formatee) {
538
			return '00/00/0000';
538
			return '00/00/0000';
539
		}
539
		}
540
		return $date_formatee;
540
		return $date_formatee;
541
	}
541
	}
542
 
542
 
543
	static function formaterUrlUser($obs) {
543
	static function formaterUrlUser($obs) {
544
		$is_id = is_numeric($obs['ce_utilisateur']);
544
		$is_id = is_numeric($obs['ce_utilisateur']);
545
		return sprintf("%s %s <%s>%s",
545
		return sprintf("%s %s <%s>%s",
546
			$obs['prenom_utilisateur'],
546
			$obs['prenom_utilisateur'],
547
			$obs['nom_utilisateur'],
547
			$obs['nom_utilisateur'],
548
			preg_replace(';@.*;', '@...', $obs['courriel_utilisateur']),
548
			preg_replace(';@.*;', '@...', $obs['courriel_utilisateur']),
549
			$is_id ? sprintf(' (' . USER_BASEURL . ')', $obs['ce_utilisateur']) : '');
549
			$is_id ? sprintf(' (' . USER_BASEURL . ')', $obs['ce_utilisateur']) : '');
550
	}
550
	}
551
 
551
 
552
	static function getImages_preload($cel, $obsids) {
552
	static function getImages_preload($cel, $obsids) {
553
		if (!$obsids) return;
553
		if (!$obsids) return;
554
		$rec = Cel::db()->requeter(
554
		$rec = Cel::db()->requeter(
555
			sprintf("SELECT o.id_observation, GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i " .
555
			sprintf("SELECT o.id_observation, GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i " .
556
					"FROM cel_images i LEFT JOIN cel_obs o ON (i.ce_observation = o.id_observation) " .
556
					"FROM cel_images i LEFT JOIN cel_obs o ON (i.ce_observation = o.id_observation) " .
557
					"WHERE o.ce_utilisateur = %d AND o.id_observation IN (%s) " .
557
					"WHERE o.ce_utilisateur = %d AND o.id_observation IN (%s) " .
558
					"GROUP BY id_observation",
558
					"GROUP BY id_observation",
559
					SEPARATEUR_IMAGES,
559
					SEPARATEUR_IMAGES,
560
					$cel->id_utilisateur,
560
					$cel->id_utilisateur,
561
					implode(',', $obsids)));
561
					implode(',', $obsids)));
562
		foreach ($rec as $v) {
562
		foreach ($rec as $v) {
563
			self::$cache['getImages'][$v['id_observation']] = $v['i'];
563
			self::$cache['getImages'][$v['id_observation']] = $v['i'];
564
		}
564
		}
565
		return null;
565
		return null;
566
	}
566
	}
567
 
567
 
568
	static function getImages($obs, $id_utilisateur) {
568
	static function getImages($obs, $id_utilisateur) {
569
		if(! $id_utilisateur) return NULL;
569
		if(! $id_utilisateur) return NULL;
570
		if(isset(self::$cache['getImages'][$obs['id_observation']]))
570
		if(isset(self::$cache['getImages'][$obs['id_observation']]))
571
			return self::$cache['getImages'][$obs['id_observation']];
571
			return self::$cache['getImages'][$obs['id_observation']];
572
 
572
 
573
		$rec = Cel::db()->requeter(
573
		$rec = Cel::db()->requeter(
574
			sprintf("SELECT GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i ".
574
			sprintf("SELECT GROUP_CONCAT(nom_original ORDER BY nom_original ASC SEPARATOR '%s') AS i ".
575
					"FROM cel_images i ".
575
					"FROM cel_images i ".
576
					"	LEFT JOIN cel_obs o ON (i.ce_observation = o.id_observation) ".
576
					"	LEFT JOIN cel_obs o ON (i.ce_observation = o.id_observation) ".
577
					"WHERE o.ce_utilisateur = %d ".
577
					"WHERE o.ce_utilisateur = %d ".
578
					"	AND o.id_observation = %d ".
578
					"	AND o.id_observation = %d ".
579
					'LIMIT 1',
579
					'LIMIT 1',
580
					SEPARATEUR_IMAGES,
580
					SEPARATEUR_IMAGES,
581
					$id_utilisateur,
581
					$id_utilisateur,
582
					$obs['id_observation']));
582
					$obs['id_observation']));
583
		return $rec ? $rec[0]['i'] : NULL;
583
		return $rec ? $rec[0]['i'] : NULL;
584
	}
584
	}
585
 
585
 
586
	public static function convertirCodeZoneGeoVersDepartement($code_zone_geo) {
586
	public static function convertirCodeZoneGeoVersDepartement($code_zone_geo) {
587
		$code_departement = '';
587
		$code_departement = '';
588
		if(self::estUnCodeInseeDepartement($code_zone_geo)) {
588
		if(self::estUnCodeInseeDepartement($code_zone_geo)) {
589
			$code_departement = substr(ltrim($code_zone_geo,'INSEE-C:'),0,2);
589
			$code_departement = substr(ltrim($code_zone_geo,'INSEE-C:'),0,2);
590
		}
590
		}
591
 
591
 
592
		return $code_departement;
592
		return $code_departement;
593
	}
593
	}
594
 
594
 
595
	/**
595
	/**
596
	 * Enlève les zéros excédentaires (devenus nomades) au début et à la fin d'une
596
	 * Enlève les zéros excédentaires (devenus nomades) au début et à la fin d'une
597
	 * latitude ou longitude, en prenant garde à ne pas foirer les nombres 0.xyz
597
	 * latitude ou longitude, en prenant garde à ne pas foirer les nombres 0.xyz
598
	 */
598
	 */
599
	public static function trim0($lonlat) {
599
	public static function trim0($lonlat) {
600
		$retour = trim($lonlat, "0");
600
		$retour = trim($lonlat, "0");
601
		// si on a trop enlevé de zéros à gauche, on en remet un (mode synthobois)
601
		// si on a trop enlevé de zéros à gauche, on en remet un (mode synthobois)
602
		if (substr($retour, 0, 1) == ".") {
602
		if (substr($retour, 0, 1) == ".") {
603
			$retour = "0" . $retour;
603
			$retour = "0" . $retour;
604
		}
604
		}
605
		return $retour;
605
		return $retour;
606
	}
606
	}
607
 
607
 
608
	public static function boolOuiNon($transmission) {
608
	public static function boolOuiNon($transmission) {
609
		return $transmission ? 'oui' : '';
609
		return $transmission ? 'oui' : '';
610
	}
610
	}
611
 
611
 
612
	public static function estUnCodeInseeDepartement($code_a_tester) {
612
	public static function estUnCodeInseeDepartement($code_a_tester) {
613
		return preg_match('/^INSEE-C:[0-9]{5}/',$code_a_tester);
613
		return preg_match('/^INSEE-C:[0-9]{5}/',$code_a_tester);
614
	}
614
	}
615
 
615
 
616
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
616
	// TODO: référentiel ne devrait pas être généré au moment d'un Config::get,
617
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
617
	// comme dans Config::get('nomsVernaRechercheLimiteeTpl')
618
	// Par exemple, la variable pour "nva" ?
618
	// Par exemple, la variable pour "nva" ?
619
	function getNomCommun($obs) {
619
	function getNomCommun($obs) {
620
		$langue = 'fra';
620
		$langue = 'fra';
621
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
621
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
622
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
622
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
623
		else return '';
623
		else return '';
624
 
624
 
625
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
625
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
626
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
626
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
627
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
627
			//debug: error_log("require url_service_nom_attribution: OK ! (pour \"{$obs['nom_ret']}\")");
628
			return self::$cache['getNomCommun'][$cache_id];
628
			return self::$cache['getNomCommun'][$cache_id];
629
		}
629
		}
630
		// pas de cache:
630
		// pas de cache:
631
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
631
		//debug: error_log("require url_service_nom_attribution pour \"{$obs['nom_ret']}\"");
632
 
632
 
633
		// pour bdtfx:
633
		// pour bdtfx:
634
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
634
		// /service:eflore:0.1/nvjfl/noms-vernaculaires/attributions?masque.nt=X&masque.lg=fra&retour.champs=num_statut
635
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
635
		// /projet/services/modules/0.1/nvjfl/NomsVernaculaires.php
636
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
636
		$url = str_replace(Array('{referentiel}', '{valeur}', '{langue}'),
637
						   Array($referentiel, $obs['nt'], $langue),
637
						   Array($referentiel, $obs['nt'], $langue),
638
						   self::$config['eflore']['url_service_nom_attribution']) . // TODO !
638
						   self::$config['eflore']['url_service_nom_attribution']) . // TODO !
639
			"&retour.champs=num_statut";
639
			"&retour.champs=num_statut";
640
		$noms = @json_decode(file_get_contents($url));
640
		$noms = @json_decode(file_get_contents($url));
641
		if(! $noms) return '';
641
		if(! $noms) return '';
642
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
642
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
643
		$nom = array_pop($noms)->nom_vernaculaire;
643
		$nom = array_pop($noms)->nom_vernaculaire;
644
 
644
 
645
		// cache
645
		// cache
646
		self::$cache['getNomCommun'][$cache_id] = $nom;
646
		self::$cache['getNomCommun'][$cache_id] = $nom;
647
		return $nom;
647
		return $nom;
648
	}
648
	}
649
 
649
 
650
	private function retournerNumStatutUn(&$item) {
650
	private function retournerNumStatutUn(&$item) {
651
		return ($item->num_statut == 1);
651
		return ($item->num_statut == 1);
652
	}
652
	}
653
 
653
 
654
	private function retournerNumStatutUnArr(&$item) {
654
	private function retournerNumStatutUnArr(&$item) {
655
		return ($item['num_statut'] == 1);
655
		return ($item['num_statut'] == 1);
656
	}
656
	}
657
 
657
 
658
	// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
658
	// si getNomCommun_v2 ou getNomCommun_v3 sont utilisés
659
	/* require_once('/home/raphael/eflore/framework/framework/Framework.php');
659
	/* require_once('/home/raphael/eflore/framework/framework/Framework.php');
660
	Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
660
	Framework::setCheminAppli("/home/raphael/eflore/projets/services/index.php");
661
	Framework::setInfoAppli(Config::get('info'));
661
	Framework::setInfoAppli(Config::get('info'));
662
	require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
662
	require_once('/home/raphael/eflore/projets/services/modules/0.1/Projets.php');*/
663
 
663
 
664
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
664
	/* Tente de bootstraper le framework au plus court et d'initialiser une instance de
665
	   NomsVernaculaires pour obtenir le nom commun */
665
	   NomsVernaculaires pour obtenir le nom commun */
666
	function getNomCommun_v2($obs) {
666
	function getNomCommun_v2($obs) {
667
		static $service;
667
		static $service;
668
		$service = new Projets();
668
		$service = new Projets();
669
 
669
 
670
		$langue = 'fra';
670
		$langue = 'fra';
671
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
671
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
672
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
672
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
673
		else return '';
673
		else return '';
674
 
674
 
675
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
675
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
676
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
676
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
677
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
677
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
678
			return self::$cache['getNomCommun'][$cache_id];
678
			return self::$cache['getNomCommun'][$cache_id];
679
		}
679
		}
680
		// pas de cache:
680
		// pas de cache:
681
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
681
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
682
 
682
 
683
		$donnees = Array('masque.nt' => $obs['nt'],
683
		$donnees = Array('masque.nt' => $obs['nt'],
684
						 'masque.lg' => $langue,
684
						 'masque.lg' => $langue,
685
						 'retour.champs' => 'num_statut');
685
						 'retour.champs' => 'num_statut');
686
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $donnees);
686
		$noms = $service->consulter(Array('nvjfl', 'noms-vernaculaires'), $donnees);
687
 
687
 
688
		if(! $noms) return '';
688
		if(! $noms) return '';
689
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
689
		$noms = array_filter((array)($noms->resultat), array($this, retournerNumStatutUn)); // XXX: php 5.3
690
		$nom = array_pop($noms)->nom_vernaculaire;
690
		$nom = array_pop($noms)->nom_vernaculaire;
691
 
691
 
692
		// cache
692
		// cache
693
		self::$cache['getNomCommun'][$cache_id] = $nom;
693
		self::$cache['getNomCommun'][$cache_id] = $nom;
694
		return $nom;
694
		return $nom;
695
	}
695
	}
696
 
696
 
697
 
697
 
698
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
698
	/* Effectue un bootstraping plus sage que ci-dessus, mais le gain d'efficacité
699
	   n'est pas aussi retentissant qu'espéré */
699
	   n'est pas aussi retentissant qu'espéré */
700
	static $service;
700
	static $service;
701
	function getNomCommun_v3($obs) {
701
	function getNomCommun_v3($obs) {
702
		if(! $this->service) $this->service = new Projets();
702
		if(! $this->service) $this->service = new Projets();
703
 
703
 
704
		$langue = 'fra';
704
		$langue = 'fra';
705
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
705
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
706
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
706
		if($referentiel == 'bdtfx') $referentiel = 'nvjfl';
707
		else return '';
707
		else return '';
708
 
708
 
709
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
709
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
710
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
710
		if(isset(self::$cache['getNomCommun'][$cache_id])) {
711
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
711
			error_log("require NomsVernaculaires.php: OK ! (pour \"{$obs['nom_ret']}\")");
712
			return self::$cache['getNomCommun'][$cache_id];
712
			return self::$cache['getNomCommun'][$cache_id];
713
		}
713
		}
714
		// pas de cache:
714
		// pas de cache:
715
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
715
		error_log("require NomsVernaculaires.php pour \"{$obs['nom_ret']}\"");
716
 
716
 
717
		$donnees = Array('masque.nt' => $obs['nt'],
717
		$donnees = Array('masque.nt' => $obs['nt'],
718
						 'masque.lg' => $langue,
718
						 'masque.lg' => $langue,
719
						 'retour.champs' => 'conseil_emploi');
719
						 'retour.champs' => 'conseil_emploi');
720
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $donnees);
720
		$this->service->initialiserRessourcesEtParametres(Array('nvjfl', 'noms-vernaculaires', 'attributions'), $donnees);
721
		try {
721
		try {
722
			$noms = $this->service->traiterRessources();
722
			$noms = $this->service->traiterRessources();
723
		} catch(Exception $e) {
723
		} catch(Exception $e) {
724
			return '';
724
			return '';
725
		}
725
		}
726
		if(! $noms) return '';
726
		if(! $noms) return '';
727
		$noms = array_filter($noms['resultat'], array($this, retournerNumStatutUnArr)); // XXX: php 5.3
727
		$noms = array_filter($noms['resultat'], array($this, retournerNumStatutUnArr)); // XXX: php 5.3
728
		$premier_nom = array_pop($noms);
728
		$premier_nom = array_pop($noms);
729
		$nom = $premier_nom['nom_vernaculaire'];
729
		$nom = $premier_nom['nom_vernaculaire'];
730
 
730
 
731
		// cache
731
		// cache
732
		self::$cache['getNomCommun'][$cache_id] = $nom;
732
		self::$cache['getNomCommun'][$cache_id] = $nom;
733
		return $nom;
733
		return $nom;
734
	}
734
	}
735
 
735
 
736
	/* Cette fonction initialise le cache des noms communs en 1 fois, sur la liste des observations à exporter.
736
	/* Cette fonction initialise le cache des noms communs en 1 fois, sur la liste des observations à exporter.
737
	   Ainsi, les appels successifs à getNomCommun_v4() ne sont pas couteux (pas de requête SQL) */
737
	   Ainsi, les appels successifs à getNomCommun_v4() ne sont pas couteux (pas de requête SQL) */
738
	static function getNomCommun_preload($cel, $obsids) {
738
	static function getNomCommun_preload($cel, $obsids) {
739
		if(!$obsids) return;
739
		if(!$obsids) return;
740
		if(!self::referenceTableExiste()) return NULL;
740
		if(!self::referenceTableExiste()) return NULL;
741
 
741
 
742
		// CREATE INDEX i_nom_referentiel ON cel_obs (nom_referentiel(5));
742
		// CREATE INDEX i_nom_referentiel ON cel_obs (nom_referentiel(5));
743
		$req = sprintf("SELECT r.referentiel, r.num_taxon, r.nom_commun FROM cel_references r" .
743
		$req = sprintf("SELECT r.referentiel, r.num_taxon, r.nom_commun FROM cel_references r" .
744
					   " INNER JOIN cel_obs c ON (r.referentiel = substring_index(c.nom_referentiel, ':', 1) and r.num_taxon = c.nt)" .
744
					   " INNER JOIN cel_obs c ON (r.referentiel = substring_index(c.nom_referentiel, ':', 1) and r.num_taxon = c.nt)" .
745
					   " WHERE c.id_observation IN (%s)",
745
					   " WHERE c.id_observation IN (%s)",
746
					   implode(',', $obsids));
746
					   implode(',', $obsids));
747
		$res = Cel::db()->requeter($req);
747
		$res = Cel::db()->requeter($req);
748
		foreach($res as $v) {
748
		foreach($res as $v) {
749
			self::$cache['getNomCommun'][$v['referentiel'] . '-' . $v['num_taxon'] . '-' . 'fra'] = $v['nom_commun'];
749
			self::$cache['getNomCommun'][$v['referentiel'] . '-' . $v['num_taxon'] . '-' . 'fra'] = $v['nom_commun'];
750
		}
750
		}
751
		return NULL;
751
		return NULL;
752
	}
752
	}
753
 
753
 
754
	static function referenceTableExiste() {
754
	static function referenceTableExiste() {
755
		if (!self::$is_table) {
755
		if (!self::$is_table) {
756
			// une seule fois
756
			// une seule fois
757
			if (! Cel::db()->requeterLigne("SHOW TABLES LIKE 'cel_references'")) return FALSE;
757
			if (! Cel::db()->requeterLigne("SHOW TABLES LIKE 'cel_references'")) return FALSE;
758
			self::$is_table = TRUE;
758
			self::$is_table = TRUE;
759
		}
759
		}
760
		return TRUE;
760
		return TRUE;
761
	}
761
	}
762
 
762
 
763
	static function getNomCommun_v4($obs) {
763
	static function getNomCommun_v4($obs) {
764
		// Attention la fonction suppose que l'on ait fait appel à getNomCommun_preload avant
764
		// Attention la fonction suppose que l'on ait fait appel à getNomCommun_preload avant
765
		// d'être appelée
765
		// d'être appelée
766
		if(! $obs['nt']) return NULL;
766
		if(! $obs['nt']) return NULL;
767
		if(! self::referenceTableExiste()) return NULL;
767
		if(! self::referenceTableExiste()) return NULL;
768
 
768
 
769
		$langue = 'fra';
769
		$langue = 'fra';
770
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
770
		list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
771
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
771
		$cache_id = $referentiel . '-' . $obs['nt'] . '-' . $langue;
772
 
772
 
773
		$nom = null;
773
		$nom = null;
774
		// cache:
774
		// cache:
775
		if(isset(self::$cache['getNomCommun'])) {
775
		if(isset(self::$cache['getNomCommun'])) {
776
			if(isset(self::$cache['getNomCommun'][$cache_id])) return self::$cache['getNomCommun'][$cache_id];
776
			if(isset(self::$cache['getNomCommun'][$cache_id])) return self::$cache['getNomCommun'][$cache_id];
777
			// XXX: problème de valeurs NULL ?
777
			// XXX: problème de valeurs NULL ?
778
			if(array_key_exists($cache_id, self::$cache['getNomCommun'])) {
778
			if(array_key_exists($cache_id, self::$cache['getNomCommun'])) {
779
				$nom = self::$cache['getNomCommun'][$cache_id];
779
				$nom = self::$cache['getNomCommun'][$cache_id];
780
			}
780
			}
781
		}
781
		}
782
 
782
 
783
		return $nom;
783
		return $nom;
784
	}
784
	}
785
 
785
 
786
 
786
 
787
	/* Cette fonction initialise le cache des données baseflor en 1 fois, sur la liste des observations à exporter.
787
	/* Cette fonction initialise le cache des données baseflor en 1 fois, sur la liste des observations à exporter.
788
	   Ainsi, les appels successifs à baseflor_ligne() ne sont pas couteux (pas de requête SQL) */
788
	   Ainsi, les appels successifs à baseflor_ligne() ne sont pas couteux (pas de requête SQL) */
789
	static function baseflor_preload($cel, $obsids) {
789
	static function baseflor_preload($cel, $obsids) {
790
		if(!$obsids) return;
790
		if(!$obsids) return;
791
		if(!self::referenceTableExiste()) return NULL;
791
		if(!self::referenceTableExiste()) return NULL;
792
 
792
 
793
		// Attention (en attendant de faire une meilleure table et une meilleure requete) le distinct est très important
793
		// Attention (en attendant de faire une meilleure table et une meilleure requete) le distinct est très important
794
		$req = sprintf("SELECT DISTINCT referentiel, num_nom_retenu, %s FROM cel_references r" .
794
		$req = sprintf("SELECT DISTINCT referentiel, num_nom_retenu, %s FROM cel_references r" .
795
						" INNER JOIN cel_obs c ON (r.num_nom_retenu = c.nom_ret_nn)" .
795
						" INNER JOIN cel_obs c ON (r.num_nom_retenu = c.nom_ret_nn)" .
796
						" AND r.referentiel = IF(LOCATE(':', c.nom_referentiel) = 0, c.nom_referentiel, SUBSTR(c.nom_referentiel FROM 1 FOR LOCATE(':', c.nom_referentiel) - 1))" .
796
						" AND r.referentiel = IF(LOCATE(':', c.nom_referentiel) = 0, c.nom_referentiel, SUBSTR(c.nom_referentiel FROM 1 FOR LOCATE(':', c.nom_referentiel) - 1))" .
797
						" WHERE c.id_observation IN (%s)",
797
						" WHERE c.id_observation IN (%s)",
798
						//" AND catminat_code IS NOT NULL", // TODO: suppression des NULL ici signifie que le cache sera partiel...
798
						//" AND catminat_code IS NOT NULL", // TODO: suppression des NULL ici signifie que le cache sera partiel...
799
						implode(',', array_keys(self::$baseflor_col)),
799
						implode(',', array_keys(self::$baseflor_col)),
800
						implode(',', $obsids));
800
						implode(',', $obsids));
801
		$res = Cel::db()->requeter($req);
801
		$res = Cel::db()->requeter($req);
802
		if(!$res) return NULL;
802
		if(!$res) return NULL;
803
 
803
 
804
		foreach($res as $v) {
804
		foreach($res as $v) {
805
			$data = $v;
805
			$data = $v;
806
			unset($data['referentiel']); // non nécessaire
806
			unset($data['referentiel']); // non nécessaire
807
			unset($data['num_nom_retenu']); // non nécessaire
807
			unset($data['num_nom_retenu']); // non nécessaire
808
 
808
 
809
			// Des fois les synonymes ont des valeurs pour baseflor et pas le nom retenu et vice versa
809
			// Des fois les synonymes ont des valeurs pour baseflor et pas le nom retenu et vice versa
810
			// on les fusionne pour avoir le maximum d'infos, en attendant de repenser la table référence
810
			// on les fusionne pour avoir le maximum d'infos, en attendant de repenser la table référence
811
			if(isset(self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']])) {
811
			if(isset(self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']])) {
812
				$orig  = array_filter(self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']], 'strlen');
812
				$orig  = array_filter(self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']], 'strlen');
813
				$data  = array_filter($data , 'strlen');
813
				$data  = array_filter($data , 'strlen');
814
				$data = array_merge($orig, $data);
814
				$data = array_merge($orig, $data);
815
			}
815
			}
816
 
816
 
817
			self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']] = $data;
817
			self::$cache['getBaseflor'][$v['referentiel'] . '-' . $v['num_nom_retenu']] = $data;
818
		}
818
		}
819
 
819
 
820
		return NULL;
820
		return NULL;
821
	}
821
	}
822
 
822
 
823
	/**
823
	/**
824
	 * Attention la fonction suppose que l'on ait fait appel à baseflor_preload avant
824
	 * Attention la fonction suppose que l'on ait fait appel à baseflor_preload avant
825
	 * d'être appelée
825
	 * d'être appelée
826
	 * @CASSECOUILLES elle pourrait le détecter et le faire elle-même
826
	 * @CASSECOUILLES elle pourrait le détecter et le faire elle-même
827
	 */
827
	 */
828
	static function baseflor_ligne($obs, &$ligne) {
828
	static function baseflor_ligne($obs, &$ligne) {
829
		$clefsBF = array_keys(self::$baseflor_col);
829
		$clefsBF = array_keys(self::$baseflor_col);
830
		// par défaut des colonnes vides pour ne pas décaler le bousin
830
		// par défaut des colonnes vides pour ne pas décaler le bousin
831
		$donneesBF = array_fill_keys($clefsBF, "");
831
		$donneesBF = array_fill_keys($clefsBF, "");
832
 
832
 
833
		// s'il y a des données baseflor
833
		// s'il y a des données baseflor
834
		if ($obs['nom_ret_nn'] && self::referenceTableExiste() && count(self::$cache['getBaseflor']) > 0) {
834
		if ($obs['nom_ret_nn'] && self::referenceTableExiste() && count(self::$cache['getBaseflor']) > 0) {
835
			// l'astuce à un franc vingt
835
			// l'astuce à un franc vingt
836
			list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
836
			list($referentiel) = explode(':', strtolower($obs['nom_referentiel']));
837
			$cache_id = $referentiel . '-' . $obs['nom_ret_nn'];
837
			$cache_id = $referentiel . '-' . $obs['nom_ret_nn'];
838
 
838
 
839
			// si les données baseflor existent dans le cache pour ce nom_ret_nn
839
			// si les données baseflor existent dans le cache pour ce nom_ret_nn
840
			if (array_key_exists($cache_id, self::$cache['getBaseflor'])) {
840
			if (array_key_exists($cache_id, self::$cache['getBaseflor'])) {
841
				$donneesBFATrous = self::$cache['getBaseflor'][$cache_id];
841
				$donneesBFATrous = self::$cache['getBaseflor'][$cache_id];
842
				foreach($clefsBF as $colbf) { // remplit les trous tout en préservant l'ordre
842
				foreach($clefsBF as $colbf) { // remplit les trous tout en préservant l'ordre
843
					if(array_key_exists($colbf, $donneesBFATrous)) {
843
					if(array_key_exists($colbf, $donneesBFATrous)) {
844
						$donneesBF[$colbf] = $donneesBFATrous[$colbf];
844
						$donneesBF[$colbf] = $donneesBFATrous[$colbf];
845
					} else {
845
					} else {
846
						$donneesBF[$colbf] = "";
846
						$donneesBF[$colbf] = "";
847
					}
847
					}
848
				}
848
				}
849
			}
849
			}
850
		}
850
		}
851
 
851
 
852
		// Quand les données sont prêtes, on les fusionne
852
		// Quand les données sont prêtes, on les fusionne
853
		$ligne = array_merge($ligne, $donneesBF);
853
		$ligne = array_merge($ligne, $donneesBF);
854
	}
854
	}
855
 
855
 
856
	static function champsEtendus_preload($cel, $obsids) {
856
	static function champsEtendus_preload($cel, $obsids) {
857
		$gestion_champs_etendus = new GestionChampsEtendus($cel->config, 'obs');
857
		$gestion_champs_etendus = new GestionChampsEtendus($cel->config, 'obs');
858
		$colonnes_champs_supp_par_obs = $gestion_champs_etendus->consulterClesParLots($obsids);
858
		$colonnes_champs_supp_par_obs = $gestion_champs_etendus->consulterClesParLots($obsids);
859
 
859
 
860
		// Supprime les champs étendus considérés comme privés dans le cas de l'export public en chargeant
860
		// Supprime les champs étendus considérés comme privés dans le cas de l'export public en chargeant
861
		// le catalogue et en excluant ceux qui sont explicitement privés
861
		// le catalogue et en excluant ceux qui sont explicitement privés
862
		if(!$cel->export_prive) {
862
		if(!$cel->export_prive) {
863
			$indices_a_supprimer = array();
863
			$indices_a_supprimer = array();
864
			$catalogue_champs_etendus = $gestion_champs_etendus->consulterCatalogueChampsEtendusPredefinis();
864
			$catalogue_champs_etendus = $gestion_champs_etendus->consulterCatalogueChampsEtendusPredefinis();
865
			foreach($catalogue_champs_etendus as $champ_catalogue) {
865
			foreach($catalogue_champs_etendus as $champ_catalogue) {
866
				if($champ_catalogue['options']['prive'] == 1) {
866
				if($champ_catalogue['options']['prive'] == 1) {
867
					// Les champs étendus peuvent avoir des variantes lorsqu'ils apparaissent de multiples fois.
867
					// Les champs étendus peuvent avoir des variantes lorsqu'ils apparaissent de multiples fois.
868
					// Vont donc matcher monChamp mais aussi monChamp:1, monChamp:2 ou bien monChamp1, monChamp: etc...
868
					// Vont donc matcher monChamp mais aussi monChamp:1, monChamp:2 ou bien monChamp1, monChamp: etc...
869
					// 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)
869
					// 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)
870
					$entrees = preg_grep("/".$champ_catalogue['cle']."(?::?\d*)?$/", $colonnes_champs_supp_par_obs);
870
					$entrees = preg_grep("/".$champ_catalogue['cle']."(?::?\d*)?$/", $colonnes_champs_supp_par_obs);
871
					$indices_a_supprimer = array_merge($indices_a_supprimer, array_keys($entrees));
871
					$indices_a_supprimer = array_merge($indices_a_supprimer, array_keys($entrees));
872
				}
872
				}
873
			}
873
			}
874
			// les champs étendus sont renvoyés dans l'export suivant les colonnes présentes dans ce tableau
874
			// les champs étendus sont renvoyés dans l'export suivant les colonnes présentes dans ce tableau
875
			// les éliminer de la liste des colonnes suffit à les faire ignorer par l'export
875
			// les éliminer de la liste des colonnes suffit à les faire ignorer par l'export
876
			foreach($indices_a_supprimer as $indice_supp) {
876
			foreach($indices_a_supprimer as $indice_supp) {
877
				unset($colonnes_champs_supp_par_obs[$indice_supp]);
877
				unset($colonnes_champs_supp_par_obs[$indice_supp]);
878
			}
878
			}
879
		}
879
		}
880
 
880
 
881
		// ces deux lignes réordonnent l'ordre des colonnes des champs étendus en fonction de l'ordre (très spécifique)
881
		// ces deux lignes réordonnent l'ordre des colonnes des champs étendus en fonction de l'ordre (très spécifique)
882
		// de self::$ordre_champ_etendus_Florileges, les champs non-mentionnés sont ajoutés à la fin.
882
		// de self::$ordre_champ_etendus_Florileges, les champs non-mentionnés sont ajoutés à la fin.
883
		$colonnes_champs_supp_par_obs = self::sortArrayByArray(array_flip($colonnes_champs_supp_par_obs),
883
		$colonnes_champs_supp_par_obs = self::sortArrayByArray(array_flip($colonnes_champs_supp_par_obs),
884
															   self::$ordre_champ_etendus_Florileges);
884
															   self::$ordre_champ_etendus_Florileges);
885
		$colonnes_champs_supp_par_obs = array_keys($colonnes_champs_supp_par_obs);
885
		$colonnes_champs_supp_par_obs = array_keys($colonnes_champs_supp_par_obs);
886
 
886
 
887
		// si le SELECT des clefs ne retourne rien, une autre requêtes est inutile
887
		// si le SELECT des clefs ne retourne rien, une autre requêtes est inutile
888
		// TODO: optimize, 1 seule requête
888
		// TODO: optimize, 1 seule requête
889
		if(!$colonnes_champs_supp_par_obs) return Array('header' => array(), 'data' => array());
889
		if(!$colonnes_champs_supp_par_obs) return Array('header' => array(), 'data' => array());
890
 
890
 
891
		$champs_supp_par_obs = $gestion_champs_etendus->consulterParLots($obsids);
891
		$champs_supp_par_obs = $gestion_champs_etendus->consulterParLots($obsids);
892
 
892
 
893
		self::$cache['champsEtendus']['header'] = self::champsEtendus_prefixHeader($colonnes_champs_supp_par_obs);
893
		self::$cache['champsEtendus']['header'] = self::champsEtendus_prefixHeader($colonnes_champs_supp_par_obs);
894
 
894
 
895
		foreach($champs_supp_par_obs as &$v) {
895
		foreach($champs_supp_par_obs as &$v) {
896
			$v = self::champsEtendus_aplatir($v);
896
			$v = self::champsEtendus_aplatir($v);
897
		}
897
		}
898
		self::$cache['champsEtendus']['data'] = $champs_supp_par_obs;
898
		self::$cache['champsEtendus']['data'] = $champs_supp_par_obs;
899
		// ce return est temporaire,
899
		// ce return est temporaire,
900
		// le temps que toutes les fonctions bougent ici et utilise plutôt le cache statique
900
		// le temps que toutes les fonctions bougent ici et utilise plutôt le cache statique
901
		// encore utilisé pour les entêtes (self::$cache['champsEtendus']['header'])
901
		// encore utilisé pour les entêtes (self::$cache['champsEtendus']['header'])
902
		return self::$cache['champsEtendus'];
902
		return self::$cache['champsEtendus'];
903
	}
903
	}
904
 
904
 
905
	// XXX: PHP-5.3, fonction anonyme + array_map
905
	// XXX: PHP-5.3, fonction anonyme + array_map
906
	static function champsEtendus_prefixHeader($array) {
906
	static function champsEtendus_prefixHeader($array) {
907
		return array_map(create_function('$v', 'return "' . PREFIX_CHAMPS_ETENDUS . '".$v;'), $array);
907
		return array_map(create_function('$v', 'return "' . PREFIX_CHAMPS_ETENDUS . '".$v;'), $array);
908
	}
908
	}
909
 
909
 
910
	// XXX: PHP-5.3, fonction anonyme + array_map
910
	// XXX: PHP-5.3, fonction anonyme + array_map
911
	static function champsEtendus_aplatir($ligne_champs_etendus) {
911
	static function champsEtendus_aplatir($ligne_champs_etendus) {
912
		$champs_etendus_fmt = array();
912
		$champs_etendus_fmt = array();
913
		if(!$ligne_champs_etendus) return $champs_etendus_fmt;
913
		if(!$ligne_champs_etendus) return $champs_etendus_fmt;
914
		foreach($ligne_champs_etendus as $champ) {
914
		foreach($ligne_champs_etendus as $champ) {
915
			$champs_etendus_fmt[PREFIX_CHAMPS_ETENDUS . $champ->cle] = $champ->valeur;
915
			$champs_etendus_fmt[PREFIX_CHAMPS_ETENDUS . $champ->cle] = $champ->valeur;
916
		}
916
		}
917
		return $champs_etendus_fmt;
917
		return $champs_etendus_fmt;
918
	}
918
	}
919
 
919
 
920
	static function champsEtendus_ligne($obs, &$ligne) {
920
	static function champsEtendus_ligne($obs, &$ligne) {
921
		// si header n'est pas défini, aucune observation ne possède de champ étendu
921
		// si header n'est pas défini, aucune observation ne possède de champ étendu
922
		// et nous n'ajoutons ni colonnes, ni valeurs.
922
		// et nous n'ajoutons ni colonnes, ni valeurs.
923
		if(! isset(self::$cache['champsEtendus']['header'])) return;
923
		if(! isset(self::$cache['champsEtendus']['header'])) return;
924
		$ligne_etendue_aplatie = @self::$cache['champsEtendus']['data'][$obs['id_observation']];
924
		$ligne_etendue_aplatie = @self::$cache['champsEtendus']['data'][$obs['id_observation']];
925
 
925
 
926
		$ligne_supp = array_fill(0, count(self::$cache['champsEtendus']['header']), '');
926
		$ligne_supp = array_fill(0, count(self::$cache['champsEtendus']['header']), '');
927
		$ligne_etendue_fmt = array();
927
		$ligne_etendue_fmt = array();
928
 
928
 
929
		// si, cependant cette seule observation n'a pas de champs étendus,
929
		// si, cependant cette seule observation n'a pas de champs étendus,
930
		// nous devons rajouter des blancs (notamment dans le cas ou d'autres
930
		// nous devons rajouter des blancs (notamment dans le cas ou d'autres
931
		// champs viennent à être ajoutés en aval à l'avenir
931
		// champs viennent à être ajoutés en aval à l'avenir
932
		// cf: $fonction_dynamique dans FormateurGroupeColonne::GenColInfo()
932
		// cf: $fonction_dynamique dans FormateurGroupeColonne::GenColInfo()
933
		if(! $ligne_etendue_aplatie) {
933
		if(! $ligne_etendue_aplatie) {
934
			$ligne = array_merge($ligne, $ligne_supp);
934
			$ligne = array_merge($ligne, $ligne_supp);
935
			return;
935
			return;
936
		}
936
		}
937
 
937
 
938
		foreach(self::$cache['champsEtendus']['header'] as $colonne) {
938
		foreach(self::$cache['champsEtendus']['header'] as $colonne) {
939
			if(!isset($ligne_etendue_aplatie[$colonne])) {
939
			if(!isset($ligne_etendue_aplatie[$colonne])) {
940
				$ligne_etendue_fmt[$colonne] = '';
940
				$ligne_etendue_fmt[$colonne] = '';
941
			} else {
941
			} else {
942
				$ligne_etendue_fmt[$colonne] = $ligne_etendue_aplatie[$colonne];
942
				$ligne_etendue_fmt[$colonne] = $ligne_etendue_aplatie[$colonne];
943
			}
943
			}
944
		}
944
		}
945
 
945
 
946
		// XXX/ array_merge() ?
946
		// XXX/ array_merge() ?
947
		$ligne += $ligne_etendue_fmt;
947
		$ligne += $ligne_etendue_fmt;
948
	}
948
	}
949
 
949
 
950
	/* HELPERS */
950
	/* HELPERS */
951
 
951
 
952
	// http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
952
	// http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array
953
	// XXX; redéfinition, utilisé aussi par ExportXLS
953
	// XXX; redéfinition, utilisé aussi par ExportXLS
954
	static function sortArrayByArray($array, $orderArray) {
954
	static function sortArrayByArray($array, $orderArray) {
955
		$ordered = array();
955
		$ordered = array();
956
		foreach($orderArray as $key) {
956
		foreach($orderArray as $key) {
957
			if(array_key_exists($key, $array)) {
957
			if(array_key_exists($key, $array)) {
958
				$ordered[$key] = $array[$key];
958
				$ordered[$key] = $array[$key];
959
				unset($array[$key]);
959
				unset($array[$key]);
960
			}
960
			}
961
		}
961
		}
962
		return $ordered + $array;
962
		return $ordered + $array;
963
	}
963
	}
964
}
964
}