Subversion Repositories eFlore/Applications.cel

Rev

Rev 3354 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3312 idir 1
 <?php
2
// declare(encoding='UTF-8');
3
/**
4
 * Service affichant les dernières photo publiques du CEL ouvrable sous forme de diaporama.
5
 * Encodage en entrée : utf8
6
 * Encodage en sortie : utf8
7
 *
8
 * Cas d'utilisation et documentation :
9
 * @link http://www.tela-botanica.org/wikini/eflore/wakka.php?wiki=AideCELWidgetPhoto
10
 *
11
 * Paramètres :
12
 * ===> extra = booléen (1 ou 0)  [par défaut : 1]
13
 * Affiche / Cache la vignette en taille plus importante au bas du widget.
14
 * ===> vignette = [0-9]+,[0-9]+  [par défaut : 4,3]
15
 * Indique le nombre de vignette par ligne et le nombre de ligne.
16
 *
17
 * @author		Jean-Pascal MILCENT <jpm@tela-botanica.org>
18
 * @license	GPL v3 <http://www.gnu.org/licenses/gpl.txt>
19
 * @license	CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
20
 * @version	$Id$
21
 * @copyright	Copyright (c) 2010, Tela Botanica (accueil@tela-botanica.org)
22
 */
23
class Apa extends WidgetCommun {
24
 
25
	const DS = DIRECTORY_SEPARATOR;
26
	const SERVICE_DEFAUT = 'saisie';
27
	const WS_SAISIE = 'CelWidgetSaisie';
28
	const WS_UPLOAD = 'CelWidgetUploadImageTemp';
29
	const WS_IMG_LIST = 'celImage';
30
	const WS_OBS = 'CelObs';
31
	const WS_OBS_LIST = 'InventoryObservationList';
32
	const LANGUE_DEFAUT = 'fr';
33
	const PROJET_DEFAUT = 'apa';
34
	const WS_NOM = 'noms';
35
	const EFLORE_API_VERSION = '0.1';
36
	private $cel_url_tpl = null;
37
	/** Si spécifié, on ajoute une barre de navigation inter-applications */
38
	private $bar;
39
	//private $parametres_autorises = array('projet', 'type', 'langue', 'order');
40
	private $parametres_autorises = array(
41
			'projet' => 'projet',
42
			'type' => 'type',
43
			'langue' => 'langue',
44
			'order' => 'order'
45
	);
46
	/**
47
	 * Méthode appelée par défaut pour charger ce widget.
48
	 */
49
	public function executer() {
50
		$retour = null;
51
		// Pour la création de l'id du cache nous ne tenons pas compte du paramètre de l'url callback
52
		unset($this->parametres['callback']);
53
		extract($this->parametres);
54
		$this->bar = (isset($bar)) ? $bar : false;
55
		/* Le fichier Framework.php du Framework de Tela Botanica doit être appelé avant tout autre chose dans l'application.
56
		 Sinon, rien ne sera chargé.
57
		 L'emplacement du Framework peut varier en fonction de l'environnement (test, prod...). Afin de faciliter la configuration
58
		 de l'emplacement du Framework, un fichier framework.defaut.php doit être renommé en framework.php et configuré pour chaque installation de
59
		 l'application.
60
		 Chemin du fichier chargeant le framework requis */
61
		$framework = dirname(__FILE__).'/framework.php';
62
		if (!file_exists($framework)) {
63
			$e = "Veuillez paramêtrer l'emplacement et la version du Framework dans le fichier $framework";
64
			trigger_error($e, E_USER_ERROR);
65
		} else {
66
			// Inclusion du Framework
67
			require_once $framework;
68
			// Ajout d'information concernant cette application
69
			Framework::setCheminAppli(__FILE__);// Obligatoire
70
			Framework::setInfoAppli(Config::get('info'));// Optionnel
71
 
72
		}
73
		$langue = (isset($langue)) ? $langue : self::LANGUE_DEFAUT;
74
		$this->langue = I18n::setLangue($langue);
75
		$this->parametres['langue'] = $langue;
76
 
77
		if (!isset($mode)) {
78
			$mode = self::SERVICE_DEFAUT;
79
		}
80
		if (!isset($projet)) {
81
			$this->parametres['projet'] = self::PROJET_DEFAUT;
82
		}
83
 
84
		$methode = $this->traiterNomMethodeExecuter($mode);
85
		if (method_exists($this, $methode)) {
86
			$retour = $this->$methode();
87
		} else {
88
			$this->messages[] = "Ce type de service '$methode' n'est pas disponible.";
89
		}
90
 
91
		$contenu = '';
92
		if (is_null($retour)) {
93
			$this->messages[] = 'La ressource demandée a retourné une valeur nulle.';
94
		} else {
95
			if (isset($retour['donnees'])) {
96
				$retour['donnees']['conf_mode'] = $this->config['parametres']['modeServeur'];
97
				$retour['donnees']['prod'] = ($this->config['parametres']['modeServeur'] == 'prod');
98
				$retour['donnees']['bar'] = $this->bar;
99
				$retour['donnees']['url_base'] = sprintf($this->config['chemins']['baseURLAbsoluDyn'], $this->config['apa']['cheminDos']);
100
				$retour['donnees']['url_ws_annuaire'] = sprintf($this->config['chemins']['baseURLServicesAnnuaireTpl'], 'utilisateur/identite-par-courriel/');
101
				$retour['donnees']['url_ws_apa'] = sprintf($this->config['chemins']['baseURLServicesCelTpl'], self::WS_SAISIE);
102
				$retour['donnees']['url_ws_obs'] = sprintf($this->config['chemins']['baseURLServicesCelTpl'], self::WS_OBS);
103
				$retour['donnees']['url_ws_obs_list'] = sprintf($this->config['chemins']['baseURLServicesCelTpl'], self::WS_OBS_LIST);
104
				$retour['donnees']['url_ws_upload'] = sprintf($this->config['chemins']['baseURLServicesCelTpl'], self::WS_UPLOAD);
105
				$retour['donnees']['url_ws_cel_imgs'] = sprintf($this->config['chemins']['baseURLServicesCelTpl'], self::WS_IMG_LIST) . '/liste-ids?obsId=';
106
				$retour['donnees']['url_ws_cel_img_url'] = str_replace ( '%s.jpg', '{id}XS', $this->config['chemins']['celImgUrlTpl'] );
107
				$retour['donnees']['mode'] = $mode;
108
				$retour['donnees']['langue'] = $langue;
109
				if( isset( $this->parametres['squelette'] ) ) {
110
					$squelette = dirname(__FILE__).self::DS.'squelettes'.self::DS. $this->parametres['squelette'].'.tpl.html';
111
				} else {
112
					$squelette = dirname(__FILE__).self::DS.'squelettes'.self::DS.$retour['squelette'].'.tpl.html';
113
				}
114
				$contenu = $this->traiterSquelettePhp($squelette, $retour['donnees']);
115
			} else {
116
				$this->messages[] = 'Les données à transmettre au squelette sont nulles.';
117
			}
118
		}
119
		$this->envoyer($contenu);
120
	}
121
 
122
 
123
	private function executerSaisie() {
124
		$retour = array();
125
		$retour['squelette'] = 'apa';
126
		$retour['donnees']['general'] = I18n::get('General');
127
		$retour['donnees']['observateur'] = I18n::get('Observateur');
128
        $retour['donnees']['observation'] = I18n::get('Observation');
129
        $retour['donnees']['arbres'] = I18n::get('Arbres');
130
        $retour['donnees']['image'] = I18n::get('Image');
131
        $retour['donnees']['plantes'] = I18n::get('Plantes');
132
        $retour['donnees']['lichens'] = I18n::get('Lichens');
133
        $retour['donnees']['chpsupp'] = I18n::get('Chpsupp');
134
        $retour['donnees']['resume'] = I18n::get('Resume');
135
		$retour['donnees']['widget'] = $this->rechercherProjet();
136
		return $retour;
137
	}
138
 
139
	/* Recherche si le projet existe sinon va chercher les infos de base */
140
	private function rechercherProjet() {
141
		$tab = array();
142
		$url = $this->config['apa']['celUrlTpl'].'?projet='.$this->parametres['projet'].'&langue='.$this->parametres['langue'];
143
		$json = $this->getDao()->consulter($url);
144
		$tableau = json_decode($json, true);
3363 idir 145
		$tableau = $this->traiterParametres($tableau[0]);
146
		if (
147
			isset($this->parametres['squelette']) &&
148
			($this->parametres['squelette'] === 'plantes' || $this->parametres['squelette'] === 'lichens')
149
		) {
3312 idir 150
			$tableau['type_especes'] = 'liste';
3354 idir 151
			if ( $this->parametres['squelette'] === 'lichens' ) {
152
				$tableau['referentiel'] = 'taxref';
153
			}
3312 idir 154
		}
155
		$tableau['especes'] = $this->rechercherInfosEspeces($tableau);
156
		if ($tableau['milieux'] != "") {
157
			$tableau['milieux'] = explode(";", $tableau['milieux']);
158
		} else {
159
			$tableau['milieux'] = array();
160
		}
161
		if (isset($tableau['motscles'])) {
162
		    $tableau['tag-obs'] = $tableau['tag-img'] = $tableau['motscles'];
163
		}
164
		$tableau['chpSupp'] = $tab;
165
		$langue_projet_url = ( isset ( $this->parametres['langue'] ) && $this->parametres['langue'] !== 'fr' ) ? '_' . $this->parametres['langue'] : '';
3315 idir 166
		$tableau['chemin_fichiers'] = sprintf( $this->config['chemins']['baseURLAbsoluDyn'], $this->config['apa']['imgProjet'] . '/' );
3312 idir 167
		return $tableau;
168
	}
169
 
170
	// remplace certains parametres définis en bd par les parametres définis dans l'url
3363 idir 171
	private function traiterParametres($tableau) {
3312 idir 172
		$criteres = array('tag-obs', 'tag-img', 'projet', 'titre', 'logo');
173
		foreach($this->parametres as $nom_critere => $valeur_critere) {
3363 idir 174
			if (in_array($nom_critere, $criteres)) {
3312 idir 175
				$tableau[$nom_critere] = $valeur_critere;
176
			}
177
		}
178
		return $tableau;
179
	}
180
 
181
	private function rechercherInfosEspeces( $infos_projets ) { //print_r($infos_projets);exit;
182
		$retour = array();
183
		$referentiel = $infos_projets['referentiel'];
184
		$urlWsNsTpl = $this->config['chemins']['baseURLServicesEfloreTpl'];
185
		$retour['url_ws_autocompletion_ns'] = sprintf( $urlWsNsTpl, self::EFLORE_API_VERSION, $referentiel, self::WS_NOM );;
186
		$retour['url_ws_autocompletion_ns_tpl'] = sprintf( $urlWsNsTpl, self::EFLORE_API_VERSION, '{referentiel}', self::WS_NOM );
187
		$retour['ns_referentiel'] = $referentiel;
188
 
189
		if ( isset( $infos_projets['type_especes'] ) ) {
190
 
191
			switch ( $infos_projets['type_especes'] ) {
192
				case 'fixe' :
193
					$retour = $this->chargerInfosTaxon( $infos_projets['referentiel'], $infos_projets['especes'] );
194
					break;
195
				case 'referentiel' : break;
196
				case 'liste' :
197
					$referentiel = $infos_projets['referentiel'];
198
					$retour['taxons'] = $this->recupererListeNomsSci();
199
					break;
200
			}
201
		} else if ( isset( $infos_projets['referentiel'] ) ) {
202
			$referentiel = $infos_projets['referentiel'];
203
			if ( isset($infos_projets['num_nom'] ) ) {
204
				$retour = $this->chargerInfosTaxon( $infos_projets['referentiel'], $infos_projets['num_nom'] );
205
			}
206
		}
207
		return $retour;
208
	}
209
 
210
	/**
211
	 * Consulte un webservice pour obtenir des informations sur le taxon dont le
212
	 * numéro nomenclatural est $num_nom (ce sont donc plutôt des infos sur le nom
213
	 * et non le taxon?)
214
	 * @param string|int $num_nom
215
	 * @return array
216
	 */
217
	protected function chargerInfosTaxon( $referentiel, $num_nom ) {
218
		$url_service_infos = sprintf( $this->config['chemins']['infosTaxonUrl'], $referentiel, $num_nom );
219
		$infos = json_decode( file_get_contents( $url_service_infos ) );
220
		// trop de champs injectés dans les infos espèces peuvent
221
		// faire planter javascript
222
		$champs_a_garder = array( 'id', 'nom_sci','nom_sci_complet', 'nom_complet', 'famille','nom_retenu.id', 'nom_retenu_complet', 'num_taxonomique' );
223
		$resultat = array();
224
		$retour = array();
225
		if ( isset( $infos ) && !empty( $infos ) ) {
226
			$infos = (array) $infos;
227
			if ( isset( $infos['nom_sci'] ) && $infos['nom_sci'] !== '' ) {
228
				$resultat = array_intersect_key( $infos, array_flip($champs_a_garder ) );
229
				$resultat['retenu'] = ( $infos['id'] == $infos['nom_retenu.id'] ) ? 'true' : 'false';
230
				$retour['espece_imposee'] = true;
231
				$retour['nn_espece_defaut'] = $nnEspeceImposee;
232
				$retour['nom_sci_espece_defaut'] = $resultat['nom_complet'];
233
				$retour['infos_espece'] = $this->array2js( $resultat, true );
234
			}
235
		}
236
		return $retour;
237
	}
238
 
239
	protected function getReferentielImpose() {
240
		$referentiel_impose = true;
241
		if (!empty($_GET['referentiel']) && $_GET['referentiel'] !== 'autre') {
242
			$this->ns_referentiel = $_GET['referentiel'];
243
		} else if (isset($this->configProjet['referentiel'])) {
244
			$this->ns_referentiel = $this->configProjet['referentiel'];
245
		} else if (isset($this->configMission['referentiel'])) {
246
			$this->ns_referentiel = $this->configMission['referentiel'];
247
		} else {
248
			$referentiel_impose = false;
249
		}
250
		return $referentiel_impose;
251
	}
252
 
253
	/**
254
	 * Trie par nom français les taxons lus dans le fichier tsv
255
	 */
256
	protected function recupererListeNomsSci() {
257
		$taxons = $this->recupererListeTaxon();
258
		if (is_array($taxons)) {
259
			$taxons = self::trierTableauMd($taxons, array('nom_fr' => SORT_ASC));
260
		}
261
		return $taxons;
262
	}
263
 
264
	/**
265
	 * @TODO documenter
266
	 * @return array
267
	 */
268
	protected function recupererListeNoms() {
269
		$taxons = $this->recupererListeTaxon();
270
		$nomsAAfficher = array();
271
		$nomsSpeciaux = array();
272
		if (is_array($taxons)) {
273
			foreach ($taxons as $taxon) {
274
				$nomSciTitle = $taxon['nom_ret'].
275
				($taxon['nom_fr'] != '' ? ' - '.$taxon['nom_fr'] : '' ).
276
				($taxon['nom_fr_autre'] != '' ? ' - '.$taxon['nom_fr_autre'] : '' );
277
				$nomFrTitle = $taxon['nom_sel'].
278
				($taxon['nom_ret'] != $taxon['nom_sel']? ' - '.$taxon['nom_ret'] : '' ).
279
				($taxon['nom_fr_autre'] != '' ? ' - '.$taxon['nom_fr_autre'] : '' );
280
 
281
				if ($taxon['groupe'] == 'special') {
282
					$nomsSpeciaux[] = array(
283
							'num_nom' => $taxon['num_nom_sel'],
284
							'nom_a_afficher' => $taxon['nom_fr'],
285
							'nom_a_sauver' => $taxon['nom_sel'],
286
							'nom_title' => $nomSciTitle,
287
							'nom_type' => 'nom-special');
288
				} else {
289
					$nomsAAfficher[] = array(
290
							'num_nom' => $taxon['num_nom_sel'],
291
							'nom_a_afficher' => $taxon['nom_sel'],
292
							'nom_a_sauver' => $taxon['nom_sel'],
293
							'nom_title' => $nomSciTitle,
294
							'nom_type' => 'nom-sci');
295
					$nomsAAfficher[] = array(
296
							'num_nom' => $taxon['num_nom_sel'],
297
							'nom_a_afficher' => $taxon['nom_fr'],
298
							'nom_a_sauver' => $taxon['nom_fr'],
299
							'nom_title' => $nomFrTitle,
300
							'nom_type' => 'nom-fr');
301
				}
302
			}
303
			$nomsAAfficher = self::trierTableauMd($nomsAAfficher, array('nom_a_afficher' => SORT_ASC));
304
			$nomsSpeciaux = self::trierTableauMd($nomsSpeciaux, array('nom_a_afficher' => SORT_ASC));
305
		}
306
		return array('speciaux' => $nomsSpeciaux, 'sci-et-fr' => $nomsAAfficher);
307
	}
308
 
309
	/**
310
	 * Lit une liste de taxons depuis un fichier tsv fourni
311
	 */
312
	protected function recupererListeTaxon() {
313
		$taxons = array();
3354 idir 314
		$nom_fichier = ($this->parametres['squelette'] === 'lichens') ? 'lichens_taxons.tsv' : 'sauvages_taxons.tsv';
315
		$fichier_tsv = dirname(__FILE__) . self::DS . 'configurations' . self::DS . $nom_fichier;
3312 idir 316
 
317
		if ( file_exists( $fichier_tsv ) && is_readable( $fichier_tsv ) ) {
318
			$taxons = $this->decomposerFichierTsv( $fichier_tsv );
319
		} else {
320
			$this->debug[] = "Impossible d'ouvrir le fichier '$fichier_tsv'.";
321
		}
322
		return $taxons;
323
	}
324
 
325
	/**
326
	 * Découpe un fihcier csv
327
	 */
328
	protected function decomposerFichierTsv($fichier, $delimiter = "\t"){
329
		$header = null;
330
		$data = array();
331
		if (($handle = fopen($fichier, "r")) !== FALSE) {
332
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
333
				if (!$header) {
334
					$header = $row;
335
				} else {
336
					$data[] = array_combine($header, $row);
337
				}
338
			}
339
			fclose($handle);
340
		}
341
		return $data;
342
	}
343
 
344
	/**
345
	 * Convertit un tableau PHP en Javascript - @WTF pourquoi ne pas faire un json_encode ?
346
	 * @param array $array
347
	 * @param boolean $show_keys
348
	 * @return une portion de JSON représentant le tableau
349
	 */
350
	protected function array2js($array,$show_keys) {
351
		$tableauJs = '{}';
352
		if (!empty($array)) {
353
			$total = count($array) - 1;
354
			$i = 0;
355
			$dimensions = array();
356
			foreach ($array as $key => $value) {
357
				if (is_array($value)) {
358
					$dimensions[$i] = array2js($value,$show_keys);
359
					if ($show_keys) {
360
						$dimensions[$i] = '\"'.$key.'\":'.$dimensions[$i];
361
					}
362
				} else {
363
					$dimensions[$i] = '\"'.addslashes($value).'\"';
364
					if ($show_keys) {
365
						$dimensions[$i] = '\"'.$key.'\":'.$dimensions[$i];
366
					}
367
				}
368
				if ($i == 0) {
369
					$dimensions[$i] = '{'.$dimensions[$i];
370
				}
371
				if ($i == $total) {
372
					$dimensions[$i].= '}';
373
				}
374
				$i++;
375
			}
376
			$tableauJs = implode(',', $dimensions);
377
		}
378
		return $tableauJs;
379
	}
380
}
381
?>