Subversion Repositories eFlore/Applications.cel

Rev

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