Subversion Repositories eFlore/Applications.cel

Rev

Rev 3120 | Rev 3200 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3120 delphine 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 Saisie2 extends WidgetCommun {
24
 
25
	const DS = DIRECTORY_SEPARATOR;
26
	const SERVICE_DEFAUT = 'saisie';
27
	const LANGUE_DEFAUT = 'fr';
28
	const PROJET_DEFAUT = 'base';
29
	const WS_NOM = 'noms';
30
	const EFLORE_API_VERSION = '0.1';
31
	private $cel_url_tpl = null;
32
	/** Si spécifié, on ajoute une barre de navigation inter-applications */
33
	private $bar;
34
	//private $parametres_autorises = array('projet', 'type', 'langue', 'order');
35
	private $parametres_autorises = array(
36
			'projet' => 'projet',
37
			'type' => 'type',
38
			'langue' => 'langue',
39
			'order' => 'order'
40
	);
41
	/**
42
	 * Méthode appelée par défaut pour charger ce widget.
43
	 */
44
	public function executer() {
45
		$retour = null;
46
		// Pour la création de l'id du cache nous ne tenons pas compte du paramètre de l'url callback
47
		unset($this->parametres['callback']);
48
		extract($this->parametres);
49
		$this->bar = (isset($bar)) ? $bar : false;
50
		/* Le fichier Framework.php du Framework de Tela Botanica doit être appelé avant tout autre chose dans l'application.
51
		 Sinon, rien ne sera chargé.
52
		 L'emplacement du Framework peut varier en fonction de l'environnement (test, prod...). Afin de faciliter la configuration
53
		 de l'emplacement du Framework, un fichier framework.defaut.php doit être renommé en framework.php et configuré pour chaque installation de
54
		 l'application.
55
		 Chemin du fichier chargeant le framework requis */
56
		$framework = dirname(__FILE__).'/framework.php';
57
		if (!file_exists($framework)) {
58
			$e = "Veuillez paramêtrer l'emplacement et la version du Framework dans le fichier $framework";
59
			trigger_error($e, E_USER_ERROR);
60
		} else {
61
			// Inclusion du Framework
62
			require_once $framework;
63
			// Ajout d'information concernant cette application
64
			Framework::setCheminAppli(__FILE__);// Obligatoire
65
			Framework::setInfoAppli(Config::get('info'));// Optionnel
66
 
67
		}
68
		$langue = (isset($langue)) ? $langue : self::LANGUE_DEFAUT;
69
		$this->langue = I18n::setLangue($langue);
70
		$this->parametres['langue'] = $langue;
71
 
72
		if (!isset($mode)) {
73
			$mode = self::SERVICE_DEFAUT;
74
		}
75
		if (!isset($projet)) {
76
			$this->parametres['projet'] = self::PROJET_DEFAUT;
77
		}
78
 
79
		$methode = $this->traiterNomMethodeExecuter($mode);
80
		if (method_exists($this, $methode)) {
81
			$retour = $this->$methode();
82
		} else {
83
			$this->messages[] = "Ce type de service '$methode' n'est pas disponible.";
84
		}
85
 
86
		$contenu = '';
87
		if (is_null($retour)) {
88
			$this->messages[] = 'La ressource demandée a retourné une valeur nulle.';
89
		} else {
90
			if (isset($retour['donnees'])) {
91
				$retour['donnees']['prod'] = ($this->config['parametres']['modeServeur'] == "prod");
92
				$retour['donnees']['bar'] = $this->bar;
93
				$retour['donnees']['url_base'] = sprintf($this->config['chemins']['baseURLAbsoluDyn'], '');
94
				$retour['donnees']['url_ws_annuaire'] = sprintf($this->config['chemins']['baseURLServicesAnnuaireTpl'], 'utilisateur/identite-par-courriel/');
95
				$retour['donnees']['mode'] = $mode;
96
				$squelette = dirname(__FILE__).self::DS.'squelettes'.self::DS.$retour['squelette'].'.tpl.html';
97
				$contenu = $this->traiterSquelettePhp($squelette, $retour['donnees']);
98
			} else {
99
				$this->messages[] = 'Les données à transmettre au squelette sont nulles.';
100
			}
101
		}
102
		$this->envoyer($contenu);
103
	}
104
 
105
 
106
	private function executerSaisie() {
107
		$retour = '';
108
		$retour['squelette'] = 'saisie';
109
		$retour['donnees']['general'] = I18n::get('General');
110
		$retour['donnees']['aide'] = I18n::get('Aide');
111
		$retour['donnees']['observateur'] = I18n::get('Observateur');
112
		$retour['donnees']['observation'] = I18n::get('Observation');
113
		$retour['donnees']['widget'] = $this->rechercherProjet();
114
		return $retour;
115
	}
116
 
117
	/* Recherche si le projet existe sinon va chercher les infos de base */
118
	private function rechercherProjet() {
119
		// projet avec un squelette défini (et non juste un mot-clé d'observation)
120
		$estProjetDefini = true; $tab = "";
121
		$url = $this->config['manager']['celUrlTpl'].'?projet='.$this->parametres['projet'].'&langue='.$this->parametres['langue'];
122
		$json = $this->getDao()->consulter($url);
123
		if ($json == false) {
124
			$url = $this->config['manager']['celUrlTpl'].'?projet=base&langue='.$this->parametres['langue'];
125
			$json = $this->getDao()->consulter($url);
126
			$estProjetDefini = false;
127
		} else {
128
			$tab = $this->rechercherChampsSupp();
129
		}
130
		$tableau = json_decode($json, true);
131
		$tableau = $this->traiterParametres($estProjetDefini, $tableau[0]);
132
		$tableau['especes'] = $this->rechercherInfosEspeces($tableau);
133
		if ($tableau['milieux'] != "") {
134
			$tableau['milieux']= explode(";", $tableau['milieux']);
135
		} else {
136
			$tableau['milieux'] = array();
137
		}
138
		$tableau['chpSupp'] = $tab;
139
		return $tableau;
140
	}
141
 
142
	/* Recherche si un projet a des champs de saisie supplémentaire */
143
	private function rechercherChampsSupp() {
144
		$retour = "";
145
		$url = $this->config['manager']['celChpSupTpl'].'groupes?groupe='.$this->parametres['projet'].'&langue='.$this->parametres['langue'];
146
		$json = $this->getDao()->consulter($url);
147
		$tableau = (array) json_decode($json, true);
148
		if ($tableau != false) {
149
			foreach ($tableau[0]['champs'] as $champ) {
150
				switch ($champ['type']) {
151
					case "select" :
152
						if ($champ['valeur'] != "") {
153
							$valeurs = split(";", $champ['valeur']);
154
							$html = '<label for="'.$champ['cle'].'" class="col-sm-3" >'.$champ['label'].'</label>'.
155
								'<div class="col-sm-8 input-group" >'.
156
								'<select class="form-control obs-chp-etendu" id="'.$champ['cle'].'"></div>';
157
							foreach ( $valeurs as $valeur) {
158
								$html .= '<option>'.$valeur.'</option>';
159
							}
160
							$html .= "</select>";
161
							$retour[] = $html;
162
						}
163
						break;
3163 delphine 164
					case "text" :
165
							$valeurs = split(";", $champ['valeur']);
166
							$html = '<label for="'.$champ['cle'].'" class="col-sm-3" >'.$champ['label'].'</label>'.
167
								'<div class="input-group col-sm-8">'.
168
									'<input id="'.$champ['cle'].'" name="'.$champ['cle'].'" class="form-control" type="text"/>
169
								</div>';
170
							$retour[] = $html;
171
						break;
3120 delphine 172
					default :
173
						//$this->verifierChampsCachés();
174
						break;
175
				}
176
			}
177
		}
178
		return $retour;
179
	}
180
 
181
	// remplace certains parametres définis en bd par les parametres définis dans l'url
182
	private function traiterParametres($estProjetDefini, $tableau) {
183
		$criteres = array('tag', 'motcle', 'projet', 'titre', 'logo');
184
		$criteresProjetNonDefini = array('commune', 'num_nom', 'referentiel');
185
		foreach($this->parametres as $nom_critere => $valeur_critere) {
186
			if (($estProjetDefini == false || $tableau['projet'] == "base") && in_array($nom_critere, $criteresProjetNonDefini)) {
187
				$tableau[$nom_critere] = $valeur_critere;
188
			} else if (in_array($nom_critere, $criteres)) {
189
				$tableau[$nom_critere] = $valeur_critere;
190
			}
191
		}
192
		return $tableau;
193
	}
194
 
195
 
196
	private function rechercherInfosEspeces($infos_projets) { //print_r($infos_projets);exit;
197
		$retour = ""; $referentiel = $infos_projets['referentiel'];
198
		$urlWsNsTpl = $this->config['chemins']['baseURLServicesEfloreTpl'];
199
		$urlWsNs = sprintf($urlWsNsTpl, self::EFLORE_API_VERSION, $referentiel, self::WS_NOM);
200
		$urlWsNsSansRef = sprintf($urlWsNsTpl, self::EFLORE_API_VERSION, '{referentiel}', self::WS_NOM);
201
		$retour['url_ws_autocompletion_ns'] = $urlWsNs;
202
		$retour['url_ws_autocompletion_ns_tpl'] = $urlWsNsSansRef;
203
		$retour['ns_referentiel'] = $referentiel;
204
 
205
		if (isset($infos_projets['type_especes'])) {
206
			switch ($infos_projets['type_especes']) {
207
				case "referentiel" : $referentiel = $infos_projets['referentiel']; break;
208
				case "liste" : $referentiel = $infos_projets['referentiel']; break;
209
				case "fixe" :
210
					$retour['especes'] = $this->chargerInfosTaxon($infos_projets['referentiel'], $infos_projets['especes']);
211
					break;
212
			}
213
		} else if (isset($infos_projets['referentiel'])) {
214
			$referentiel = $infos_projets['referentiel'];
215
			if (isset($infos_projets['num_nom'])) {
216
				$retour['especes'] = $this->chargerInfosTaxon($infos_projets['referentiel'], $infos_projets['num_nom']);
217
			}
218
		}
219
 
220
		$projetsAListeDeNoms = $this->transformerEnTableau($this->config['projets']['liste_noms']);
221
		if (in_array($this->projet, $projetsAListeDeNoms) && !$this->especeEstImposee()) {
222
			$projetsAListeDeNomsSciEtVerna = $this->transformerEnTableau($this->config['projets']['liste_noms_sci_et_verna']);
223
			if (in_array($this->projet, $projetsAListeDeNomsSciEtVerna)) {
224
				$retour['taxons'] = $this->recupererListeNoms();
225
			} else {
226
				$retour['taxons'] = $this->recupererListeNomsSci();
227
			}
228
		}
229
		return $retour;
230
	}
231
 
232
	/**
233
	 * Consulte un webservice pour obtenir des informations sur le taxon dont le
234
	 * numéro nomenclatural est $num_nom (ce sont donc plutôt des infos sur le nom
235
	 * et non le taxon?)
236
	 * @param string|int $num_nom
237
	 * @return array
238
	 */
239
	protected function chargerInfosTaxon($referentiel, $num_nom) {
240
		$url_service_infos = sprintf($this->config['chemins']['infosTaxonUrl'], $referentiel, $num_nom);
241
		$infos = json_decode(file_get_contents($url_service_infos));
242
		// trop de champs injectés dans les infos espèces peuvent
243
		// faire planter javascript
244
		$champs_a_garder = array('id', 'nom_sci','nom_sci_complet', 'nom_complet',
245
				'famille','nom_retenu.id', 'nom_retenu_complet', 'num_taxonomique');
246
		$resultat = array();
247
		$retour = array();
248
		if (isset($infos) && !empty($infos)) {
249
			$infos = (array)$infos;
250
			if (isset($infos['nom_sci']) && $infos['nom_sci'] != '') {
251
				$resultat = array_intersect_key($infos, array_flip($champs_a_garder));
252
				$resultat['retenu'] = ($infos['id'] == $infos['nom_retenu.id']) ? "true" : "false";
253
				$retour['espece_imposee'] = true;
254
				$retour['nn_espece_defaut'] = $nnEspeceImposee;
255
				$retour['nom_sci_espece_defaut'] = $resultat['nom_complet'];
256
				$retour['infos_espece'] = $this->array2js($resultat, true);
257
			}
258
		}
259
		return $retour;
260
	}
261
 
262
	protected function getReferentielImpose() {
263
		$referentiel_impose = true;
264
		if (!empty($_GET['referentiel']) && $_GET['referentiel'] != "autre") {
265
			$this->ns_referentiel = $_GET['referentiel'];
266
		} else if (isset($this->configProjet['referentiel'])) {
267
			$this->ns_referentiel = $this->configProjet['referentiel'];
268
		} else if (isset($this->configMission['referentiel'])) {
269
			$this->ns_referentiel = $this->configMission['referentiel'];
270
		} else {
271
			$referentiel_impose = false;
272
		}
273
		return $referentiel_impose;
274
	}
275
 
276
	/**
277
	 * Trie par nom français les taxons lus dans le fichier tsv
278
	 */
279
	protected function recupererListeNomsSci() {
280
		$taxons = $this->recupererListeTaxon();
281
		if (is_array($taxons)) {
282
			$taxons = self::trierTableauMd($taxons, array('nom_fr' => SORT_ASC));
283
		}
284
		return $taxons;
285
	}
286
 
287
	/**
288
	 * @TODO documenter
289
	 * @return array
290
	 */
291
	protected function recupererListeNoms() {
292
		$taxons = $this->recupererListeTaxon();
293
		$nomsAAfficher = array();
294
		$nomsSpeciaux = array();
295
		if (is_array($taxons)) {
296
			foreach ($taxons as $taxon) {
297
				$nomSciTitle = $taxon['nom_ret'].
298
				($taxon['nom_fr'] != '' ? ' - '.$taxon['nom_fr'] : '' ).
299
				($taxon['nom_fr_autre'] != '' ? ' - '.$taxon['nom_fr_autre'] : '' );
300
				$nomFrTitle = $taxon['nom_sel'].
301
				($taxon['nom_ret'] != $taxon['nom_sel']? ' - '.$taxon['nom_ret'] : '' ).
302
				($taxon['nom_fr_autre'] != '' ? ' - '.$taxon['nom_fr_autre'] : '' );
303
 
304
				if ($taxon['groupe'] == 'special') {
305
					$nomsSpeciaux[] = array(
306
							'num_nom' => $taxon['num_nom_sel'],
307
							'nom_a_afficher' => $taxon['nom_fr'],
308
							'nom_a_sauver' => $taxon['nom_sel'],
309
							'nom_title' => $nomSciTitle,
310
							'nom_type' => 'nom-special');
311
				} else {
312
					$nomsAAfficher[] = array(
313
							'num_nom' => $taxon['num_nom_sel'],
314
							'nom_a_afficher' => $taxon['nom_sel'],
315
							'nom_a_sauver' => $taxon['nom_sel'],
316
							'nom_title' => $nomSciTitle,
317
							'nom_type' => 'nom-sci');
318
					$nomsAAfficher[] = array(
319
							'num_nom' => $taxon['num_nom_sel'],
320
							'nom_a_afficher' => $taxon['nom_fr'],
321
							'nom_a_sauver' => $taxon['nom_fr'],
322
							'nom_title' => $nomFrTitle,
323
							'nom_type' => 'nom-fr');
324
				}
325
			}
326
			$nomsAAfficher = self::trierTableauMd($nomsAAfficher, array('nom_a_afficher' => SORT_ASC));
327
			$nomsSpeciaux = self::trierTableauMd($nomsSpeciaux, array('nom_a_afficher' => SORT_ASC));
328
		}
329
		return array('speciaux' => $nomsSpeciaux, 'sci-et-fr' => $nomsAAfficher);
330
	}
331
 
332
	/**
333
	 * Lit une liste de taxons depuis un fichier tsv fourni
334
	 */
335
	protected function recupererListeTaxon() {
336
		$taxons = array();
337
		if ($this->projet == 'missions-flore') {
338
			$fichier_tsv = dirname(__FILE__).self::DS.'configurations'.self::DS.$this->projet.'_'.$this->mission.'_taxons.tsv';
339
		} else {
340
			$fichier_tsv = dirname(__FILE__).self::DS.'configurations'.self::DS.$this->projet.'_taxons.tsv';
341
		}
342
		if (file_exists($fichier_tsv) && is_readable($fichier_tsv)) {
343
			$taxons = $this->decomposerFichierTsv($fichier_tsv);
344
		} else {
345
			$this->debug[] = "Impossible d'ouvrir le fichier '$fichier_tsv'.";
346
		}
347
		return $taxons;
348
	}
349
 
350
	/**
351
	 * Découpe un fihcier tsv
352
	 */
353
	protected function decomposerFichierTsv($fichier, $delimiter = "\t"){
354
		$header = null;
355
		$data = array();
356
		if (($handle = fopen($fichier, 'r')) !== FALSE) {
357
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
358
				if (!$header) {
359
					$header = $row;
360
				} else {
361
					$data[] = array_combine($header, $row);
362
				}
363
			}
364
			fclose($handle);
365
		}
366
		return $data;
367
	}
368
 
369
	/**
370
	 * Convertit un tableau PHP en Javascript - @WTF pourquoi ne pas faire un json_encode ?
371
	 * @param array $array
372
	 * @param boolean $show_keys
373
	 * @return une portion de JSON représentant le tableau
374
	 */
375
	protected function array2js($array,$show_keys) {
376
		$tableauJs = '{}';
377
		if (!empty($array)) {
378
			$total = count($array) - 1;
379
			$i = 0;
380
			$dimensions = array();
381
			foreach ($array as $key => $value) {
382
				if (is_array($value)) {
383
					$dimensions[$i] = array2js($value,$show_keys);
384
					if ($show_keys) {
385
						$dimensions[$i] = '"'.$key.'":'.$dimensions[$i];
386
					}
387
				} else {
388
					$dimensions[$i] = '"'.addslashes($value).'"';
389
					if ($show_keys) {
390
						$dimensions[$i] = '"'.$key.'":'.$dimensions[$i];
391
					}
392
				}
393
				if ($i == 0) {
394
					$dimensions[$i] = '{'.$dimensions[$i];
395
				}
396
				if ($i == $total) {
397
					$dimensions[$i].= '}';
398
				}
399
				$i++;
400
			}
401
			$tableauJs = implode(',', $dimensions);
402
		}
403
		return $tableauJs;
404
	}
405
 
406
 
407
}
408
?>