Subversion Repositories eFlore/Applications.cel

Rev

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

Rev Author Line No. Line
416 aurelien 1
<?php
2
/**
3
 * Service fournissant des informations concernant le CEL au format RSS1, RSS2 ou ATOM.
4
 * Encodage en entrée : utf8
5
 * Encodage en sortie : utf8
6
 * Format du service :
7
 * /CelSyndicationObservation/liste-des-flux
8
 * /CelSyndicationObservation/opml
9
 * /CelSyndicationObservation/par-defaut/(rss1|rss2|atom)?start=0&limit=150
10
 * /CelSyndicationObservation/pour-admin/(rss1|rss2|atom)?start=0&limit=150
11
 * /CelSyndicationObservation/par-mots-cles/(rss1|rss2|atom)/mot-cle?start=0&limit=150
12
 * /CelSyndicationObservation/par-commune/(rss1|rss2|atom)/nom-commune?start=0&limit=150
13
 *
14
 * Les paramêtres :
15
 *  - "start" indique le numéro du premier item à afficher
16
 *  - "limit" nombre d'items à afficher
17
 *
18
 * @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
19
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
20
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
21
 * @version $Id$
22
 * @copyright 2010
23
 */
24
class CelSyndicationObservation extends Cel {
25
 
26
	private $format = null;
27
	private $service = null;
502 aurelien 28
	public $parametres = null;
416 aurelien 29
	private $squelette = null;
30
	private $squelette_dossier = null;
31
	private $flux = array();
32
 
33
	/**
34
	 * Méthode appelée avec une requête de type GET.
35
	 */
36
	public function getElement($params = array()) {
37
		// Initialisation des variables
38
		$info = array();
39
		$contenu = '';
40
 
41
		// Pré traitement des paramêtres
42
		$pour_bdd = false;
43
		$p = $this->traiterParametres(array('service', 'format'), $params, $pour_bdd);
44
		extract($p);
45
		$this->parametres = $params;
46
		$this->squelette_dossier = dirname(__FILE__).DIRECTORY_SEPARATOR.'squelettes'.DIRECTORY_SEPARATOR;
47
 
48
		// Récupération de la liste des flux
49
		$this->chargerListeDesFlux();
50
 
51
		// Chargement du bon type de service demandé
52
		if (isset($service)) {
53
			$this->service = $this->traiterNomService($service);
54
			$methode = $this->getNomMethodeService();
55
			if (method_exists($this, $methode)) {
56
				if (isset($format) && preg_match('/^(?:rss1|rss2|atom)$/i', $format)) {
57
					// Mise en minuscule de l'indication du format
58
					$this->format = strtolower($format);
59
					// Définition du fichier squelette demandé
60
					$this->squelette = $this->squelette_dossier.$this->format.'.tpl.xml';
61
				} else if (isset($this->flux[$this->service])) {
62
					$this->format = '';
63
					$this->messages[] = "Le service CEL Syndication nécessite d'indiquer en second paramètre le format : rss1, rss2 ou atom.";
64
				}
65
 
66
				if (!isset($this->flux[$this->service]) || isset($this->format)) {
67
					// Suppression des paramêtres inutile pour le reste des méthodes
68
					array_shift($this->parametres);
69
					array_shift($this->parametres);
70
 
71
					// Récupération du contenu à renvoyer
72
					$contenu = $this->$methode();
73
				}
74
			} else {
75
				$this->messages[] = "Le type d'information demandé '$this->service' n'est pas disponible.";
76
			}
77
		} else {
78
			$this->messages[] = "Le service CEL Syndication Observation nécessite d'indiquer en premier paramètre le type d'information demandé.";
79
		}
80
 
81
		// Envoie sur la sortie standard
82
		$encodage = 'utf-8';
83
		$mime = $this->getTypeMime();
84
		$formatage_json = $this->getFormatageJson();
85
		$this->envoyer($contenu, $mime, $encodage, $formatage_json);
86
	}
87
 
88
	private function getUrlBase() {
89
		$url_base = sprintf($this->config['settings']['baseURLAbsoluDyn'], get_class($this).'/');
90
		return $url_base;
91
	}
92
 
93
	private function getUrlServiceBase() {
94
		$url_service = $this->getUrlBase().$this->service.'/'.$this->format;
95
		return $url_service;
96
	}
97
 
98
	private function traiterNomService($nom) {
99
		$nom = strtolower($nom);
100
		return $nom;
101
	}
102
 
103
	private function getNomMethodeService() {
104
		$methode = '';
105
		$service_formate = str_replace(' ', '', ucwords(implode(' ', explode('-', $this->service))));
106
		$methode = 'getService'.$service_formate;
107
		return $methode;
108
	}
109
 
110
	private function getTypeMime() {
111
		$mime = '';
112
		$test = isset($this->format) ? $this->format : $this->service;
113
		switch ($test) {
114
			case 'atom' :
115
				$mime = 'application/atom+xml';
116
				break;
117
			case 'rss1' :
118
			case 'rss2' :
119
				$mime = 'application/rss+xml';
120
				break;
121
			case 'opml' :
122
				$mime = 'text/x-opml';
123
				break;
124
			default:
125
				$mime = 'text/html';
126
		}
127
		return $mime;
128
	}
129
 
130
	private function getFormatageJson() {
131
		$json = false;
132
		switch ($this->service) {
133
			case 'liste-des-flux' :
134
				$json = true;
135
				break;
136
			default:
137
				$json = false;
138
		}
139
		return $json;
140
	}
141
 
142
	private function getFlux($nom) {
143
		return isset($this->flux[$nom]) ? $this->flux[$nom] : array();
144
	}
145
 
146
	private function setFlux($nom, $titre, $description) {
147
		$url_base = $this->getUrlBase();
148
		$formats = array('atom', 'rss2', 'rss1');
149
		$flux = array();
150
		foreach ($formats as $format) {
151
			$url = $url_base.$nom.'/'.$format;
152
			$flux[$format] = $url;
153
		}
154
		$this->flux[$nom] = array('titre' => $titre, 'description' => $description, 'urls' => $flux);
155
	}
156
 
157
	private function chargerListeDesFlux() {
158
		$this->setFlux('par-defaut', 'Flux de syndication des observations publiques du CEL',
159
			'Ce flux fournit des informations sur les observations du CEL.');
160
		$this->setFlux('par-mots-cles', 'Flux de syndication des observations publiques du CEL filtrées par mots clés',
161
			"Ce flux fournit des informations sur les observations du CEL filtrées par mots-clés. Il nécessite d'être
162
			paramétré en indiquant en dernier position de l'url le mot-clé à rechercher.");
163
		$this->setFlux('par-commune','Flux de syndication des observations publiques du CEL filtrées par commune',
164
			"Ce flux fournit des informations sur les observations du CEL filtrées par commune. Il nécessite d'être
165
			paramétré en indiquant en dernier position de l'url le nom de la commune à rechercher.");
166
	}
167
 
168
	private function getServiceListeDesFlux() {
169
		return $this->flux;
170
	}
171
 
172
	private function getServiceOpml() {
173
		$donnees = array();
174
		$id = 1;
175
		foreach ($this->flux as $flux_nom => $flux){
176
			$info = array();
177
			$info['type'] = 'atom';
178
			$info['titre'] = $flux['titre'];
179
			$info['texte'] = "CEL - Obs - $flux_nom";
180
			$info['description'] = $flux['description'];
181
			$info['url_xml'] = $this->getUrlBase().$flux_nom.'/atom';
182
			$info['url_html'] = $this->config['settings']['aideCelUrl'].'FluxSyndication';
183
			$donnees['liste_flux'][] = $info;
184
		}
185
 
186
		$this->squelette = $this->squelette_dossier.'opml.tpl.xml';
187
		$contenu = Cel::traiterSquelettePhp($this->squelette, $donnees);
188
		return $contenu;
189
	}
190
 
191
	private function getServiceParDefaut() {
192
		// Construction de la requête
193
		$requete = 	(($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' * '.
194
			'FROM cel_inventory '.
195
			'WHERE transmission = 1 '.
196
			'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'date_modification DESC').' '.
197
			"LIMIT $this->start,$this->limit ";
198
 
199
		$elements = $this->executerRequete($requete);
200
 
201
		// Création du contenu
202
		$contenu = $this->executerService($elements);
203
		return $contenu;
204
	}
205
 
206
	private function getServicePourAdmin() {
207
		$contenu = '';
208
		if ($this->authentifier()) {
209
			// Construction de la requête
210
			$requete = 	(($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' * '.
211
				'FROM cel_inventory '.
212
				'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'date_modification DESC').' '.
213
				"LIMIT $this->start,$this->limit ";
214
 
215
			$elements = $this->executerRequete($requete);
216
 
217
			// Création du contenu
218
			$contenu = $this->executerService($elements);
219
		}
220
		return $contenu;
221
	}
222
 
223
	private function getServiceParMotsCles() {
224
		$contenu = '';
225
		$mot_cle = $this->parametres[0];
226
 
227
		if (isset($mot_cle)) {
228
			$mot_cle_encode = $this->bdd->quote($this->encoderMotCle($mot_cle));
229
 
230
			// Construction de la requête
231
			$requete = 	'SELECT * '.
232
				'FROM cel_mots_cles_obs '.
233
				"WHERE cmc_id_mot_cle_general = $mot_cle_encode ";
234
			$elements = $this->executerRequete($requete);
235
 
236
			if ($elements != false && count($elements) > 0) {
237
				// Pré-construction du where de la requête
238
				$tpl_where = '(mots_cles LIKE "%%%s%%" AND identifiant = %s )';
239
				$requete_where = array();
240
				foreach ($elements as $occurence) {
241
					$requete_where[] = sprintf($tpl_where, $occurence['cmc_id_mot_cle_utilisateur'], $this->bdd->quote($occurence['cmc_id_proprietaire']));
242
				}
243
 
244
				// Construction de la requête
245
				$requete = 	'SELECT * '.
246
					'FROM cel_inventory '.
247
					'WHERE transmission = 1 '.
248
					'AND '.implode(" \nOR ", $requete_where).' '.
249
					'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'date_modification, date_creation DESC').' '.
250
					"LIMIT $this->start,$this->limit ";
251
				$elements = $this->executerRequete($requete);
252
 
253
				// Création du contenu
254
				$contenu = $this->executerService($elements);
255
			} else {
256
				$this->messages[] = "Aucune observation ne correspond à ce mot clé.";
257
			}
258
		} else {
259
			$this->messages[] = "Le service demandé nécessite d'indiquer un mot-clé en dernier paramêtre.";
260
		}
261
		return $contenu;
262
	}
263
 
264
	private function getServiceParCommune() {
265
		$contenu = '';
266
		$commune = $this->parametres[0];
267
		if (isset($commune)) {
268
			$commune = $this->bdd->quote($commune);
269
 
270
			// Construction de la requête
271
			$requete = 	(($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' * '.
272
				'FROM cel_inventory '.
273
				'WHERE transmission = 1 '.
274
				"AND location = $commune ".
275
				'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'date_modification DESC, location ASC').' '.
276
				"LIMIT $this->start,$this->limit ";
277
 
278
			$elements = $this->executerRequete($requete);
279
 
280
			// Création du contenu
281
			$contenu = $this->executerService($elements);
282
		} else {
283
			$this->messages[] = "Le service demandé nécessite d'indiquer une nom de commune en dernier paramêtre.";
284
		}
285
		return $contenu;
286
	}
287
 
288
	private function executerService($elements) {
289
		$contenu = '';
290
		if (is_array($elements)) {
291
			// Prétraitement des données
292
			$donnees = $this->construireDonneesCommunesAuFlux($elements);
293
 
294
			foreach ($elements as $element) {
295
				$donnees['items'][] = $this->construireDonneesCommunesAuxItems($element);
296
			}
297
 
298
			// Création du contenu à partir d'un template PHP
299
			if (isset($this->squelette)) {
300
				$contenu = Cel::traiterSquelettePhp($this->squelette, $donnees);
301
			}
302
		}
303
		return $contenu;
304
	}
305
 
306
	private function construireDonneesCommunesAuFlux($observations) {
307
		$donnees = $this->getFlux($this->service);
308
		$donnees['guid'] = $this->getUrlServiceBase();
309
		$donnees['lien_service'] = $this->creerUrlService();
310
		$donnees['lien_cel'] = $this->config['settings']['celUrlAbsolu'];
311
		$donnees['editeur'] = $this->config['settings']['editeur'];
312
		$derniere_info_en_date = reset($observations);
313
		$date_modification_timestamp = strtotime($derniere_info_en_date['date_modification']);
314
		$donnees['date_maj_RSS'] = date(DATE_RSS, $date_modification_timestamp);
315
		$donnees['date_maj_ATOM'] = date(DATE_ATOM, $date_modification_timestamp);
316
		$donnees['date_maj_W3C'] = date(DATE_W3C, $date_modification_timestamp);
317
		$donnees['annee_courante'] = date('Y');
318
		$donnees['generateur'] = 'CEL - Jrest - CelSyndicationObservation';
319
		preg_match('/([0-9]+)/', '$Revision$', $match);
320
		$donnees['generateur_version'] = $match[1];
321
		return $donnees;
322
	}
323
 
324
	private function construireDonneesCommunesAuxItems($observation) {
325
		$item = array();
326
		$date_modification_timestamp = strtotime($observation['date_modification']);
327
		$item['date_maj_simple'] = strftime('%A %d %B %Y à %H:%M', $date_modification_timestamp);
328
		$item['date_maj_RSS'] = date(DATE_RSS, $date_modification_timestamp);
329
		$item['date_maj_ATOM'] = date(DATE_ATOM, $date_modification_timestamp);
330
		$item['date_maj_W3C'] = date(DATE_W3C, $date_modification_timestamp);
331
		$item['date_creation_simple'] = strftime('%A %d %B %Y à %H:%M', strtotime($observation['date_creation']));
332
		$item['titre'] = $this->creerTitre($observation);
333
		$item['guid'] = $this->creerGuidItem($observation);
334
		$item['lien'] = $this->creerLienItem($observation);
335
		$item['description'] = $this->creerDescription($observation, $item);
336
		$item['categorie'] = $this->creerCategorie($item);
337
		$item['description_encodee'] = htmlspecialchars($item['description']);
522 jpm 338
		$item['modifier_par'] = $this->creerAuteur($observation['identifiant'], $this->etreFluxAdmin());
416 aurelien 339
		return $item;
340
	}
341
 
342
	private function creerTitre($obs) {
343
		$nom_plante = $obs['nom_sel'].' [nn'.$obs['num_nom_sel'].']';
344
		$lieu = $obs['location'].' ('.$obs['id_location'].')';
522 jpm 345
		$utilisateur = $this->creerAuteur($obs['identifiant'], $this->etreFluxAdmin());
416 aurelien 346
		$titre = "$nom_plante à $lieu par $utilisateur";
347
		$titre = $this->nettoyerTexte($titre);
348
		return $titre;
349
	}
350
 
351
	private function creerGuidItem($element) {
352
		$guid = sprintf($this->config['settings']['guidObsTpl'], 'obs'.$element['id']);
353
		return $guid;
354
	}
355
 
356
	private function creerLienItem($element) {
506 jpm 357
		$lien = null;
358
		if ($element['num_nom_sel'] != 0) {
359
			$lien = sprintf($this->config['settings']['efloreUrlTpl'], urlencode($element['num_nom_sel']));
360
		}
416 aurelien 361
		return $lien;
362
	}
363
 
364
	private function creerDescription($obs, $item) {
365
		$lien_correction = sprintf($this->config['settings']['phpEditUrlTpl'], $obs['id']);
366
		$description =
367
			'<ul>'.
368
			'	<li>Nom saisi : '.$obs['nom_sel'].'</li>'.
369
			(($obs['nom_sel'] != $obs['nom_ret']) ? '	<li>Nom retenu : '.$obs['nom_ret'].'</li>' : '').
370
			'	<li>Lieu : '.$obs['location'].' ('.$obs['id_location'].')</li>'.
371
			($this->etreNull($obs['station']) ? '': '	<li>Station : '.$obs['station'].'</li>').
372
			($this->etreNull($obs['milieu']) ? '': '	<li>Milieu : '.$obs['milieu'].'</li>').
373
			($this->etreNull($obs['commentaire']) ? '': '	<li>Commentaire : '.$obs['commentaire'].'</li>').
374
			(($this->etreFluxAdmin()) ? '	<li>Transmis (= public) : '.($obs['transmission'] == 1 ? 'oui' : 'non').'</li>' : '').
375
			'	<li>Modifiée le : '.$item['date_maj_simple'].'</li>'.
376
			'	<li>Créée le : '.$item['date_creation_simple'].'</li>'.
377
			(($this->etreFluxAdmin()) ? '	<li><a href="'.$lien_correction.'">Corriger cette observation</a></li>' : '').
378
			'</ul>';
379
		$description = $this->nettoyerTexte($description);
380
		return $description;
381
	}
382
 
383
	private function creerCategorie($element) {
384
		$categorie = '';
385
		$categorie = 'Observation';
386
		$categorie = $this->nettoyerTexte($categorie);
387
		return $categorie;
388
	}
389
 
390
	private function etreFluxAdmin() {
391
		return ($this->service == 'pour-admin') ? true : false;
392
	}
393
 
394
	private function creerUrlService() {
395
		$url_service = $this->getUrlServiceBase();
396
		if (isset($this->start) || isset($this->limit)) {
397
			$arguments = array();
398
			if (isset($this->start) && isset($_GET['start'])) {
399
				$arguments[] = 'start='.$this->start;
400
			}
401
			if (isset($this->limit) && isset($_GET['limit'])) {
402
				$arguments[] = 'limit='.($this->limit);
403
			}
404
			if (count($arguments) > 0) {
405
				$url_service .= '?'.implode('&', $arguments);
406
			}
407
		}
408
		return $url_service;
409
	}
410
}