Subversion Repositories eFlore/Applications.cel

Rev

Rev 474 | Go to most recent revision | Details | 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;
28
	private $parametres = null;
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']);
338
		$item['modifier_par'] = $this->creerAuteur($observation['identifiant']);
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'].')';
345
		$utilisateur = $this->creerAuteur($obs['identifiant']);
346
		$titre = "$nom_plante à $lieu par $utilisateur";
347
		$titre = $this->nettoyerTexte($titre);
348
		return $titre;
349
	}
350
 
351
	private function creerAuteur($courriel) {
352
		$auteur = ($this->etreFluxAdmin()) ? $courriel : $this->traiterCourriel($courriel);
353
		return $auteur;
354
	}
355
 
356
	private function traiterCourriel($courriel) {
357
		$courriel = preg_replace('/[^@]+$/i', '...', $courriel);
358
		return $courriel;
359
	}
360
 
361
	private function nettoyerTexte($txt) {
362
		$txt = preg_replace('/&(?!(a-z+|#0-9+|#x0-9a-f+);)/i', '&amp;', $txt);
363
		$txt = preg_replace('/000null/i', '', $txt);
364
		return $txt;
365
	}
366
 
367
	private function creerGuidItem($element) {
368
		$guid = sprintf($this->config['settings']['guidObsTpl'], 'obs'.$element['id']);
369
		return $guid;
370
	}
371
 
372
	private function creerLienItem($element) {
373
		$lien = sprintf($this->config['settings']['efloreUrlTpl'], urlencode($element['num_nom_sel']));
374
		return $lien;
375
	}
376
 
377
	private function creerDescription($obs, $item) {
378
		$lien_correction = sprintf($this->config['settings']['phpEditUrlTpl'], $obs['id']);
379
		$description =
380
			'<ul>'.
381
			'	<li>Nom saisi : '.$obs['nom_sel'].'</li>'.
382
			(($obs['nom_sel'] != $obs['nom_ret']) ? '	<li>Nom retenu : '.$obs['nom_ret'].'</li>' : '').
383
			'	<li>Lieu : '.$obs['location'].' ('.$obs['id_location'].')</li>'.
384
			($this->etreNull($obs['station']) ? '': '	<li>Station : '.$obs['station'].'</li>').
385
			($this->etreNull($obs['milieu']) ? '': '	<li>Milieu : '.$obs['milieu'].'</li>').
386
			($this->etreNull($obs['commentaire']) ? '': '	<li>Commentaire : '.$obs['commentaire'].'</li>').
387
			(($this->etreFluxAdmin()) ? '	<li>Transmis (= public) : '.($obs['transmission'] == 1 ? 'oui' : 'non').'</li>' : '').
388
			'	<li>Modifiée le : '.$item['date_maj_simple'].'</li>'.
389
			'	<li>Créée le : '.$item['date_creation_simple'].'</li>'.
390
			(($this->etreFluxAdmin()) ? '	<li><a href="'.$lien_correction.'">Corriger cette observation</a></li>' : '').
391
			'</ul>';
392
		$description = $this->nettoyerTexte($description);
393
		return $description;
394
	}
395
 
396
	private function creerCategorie($element) {
397
		$categorie = '';
398
		$categorie = 'Observation';
399
		$categorie = $this->nettoyerTexte($categorie);
400
		return $categorie;
401
	}
402
 
403
	private function etreFluxAdmin() {
404
		return ($this->service == 'pour-admin') ? true : false;
405
	}
406
 
407
	private function etreNull($valeur) {
408
		$etre_null = false;
409
		if ($valeur == '' || $valeur == null || $valeur == '000null' || $valeur == 'null') {
410
			$etre_null = true;
411
		}
412
		return $etre_null;
413
	}
414
 
415
	private function creerUrlService() {
416
		$url_service = $this->getUrlServiceBase();
417
		if (isset($this->start) || isset($this->limit)) {
418
			$arguments = array();
419
			if (isset($this->start) && isset($_GET['start'])) {
420
				$arguments[] = 'start='.$this->start;
421
			}
422
			if (isset($this->limit) && isset($_GET['limit'])) {
423
				$arguments[] = 'limit='.($this->limit);
424
			}
425
			if (count($arguments) > 0) {
426
				$url_service .= '?'.implode('&', $arguments);
427
			}
428
		}
429
		return $url_service;
430
	}
431
}