Subversion Repositories eFlore/Applications.cel

Rev

Rev 473 | 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
 *
7
 * @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
8
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
9
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
10
 * @version $Id$
11
 * @copyright 2010
12
 */
13
class CelSyndicationImage extends Cel {
14
 
15
	private $format = null;
16
	private $service = null;
17
	private $squelette = null;
18
	private $squelette_dossier = null;
19
	private $flux = array();
20
 
21
	private $format_image = 'L';
22
 
23
	/**
24
	 * Méthode appelée avec une requête de type GET.
25
	 */
26
	public function getElement($param = array()) {
27
		// Initialisation des variables
28
		$info = array();
29
		$contenu = '';
30
 
31
		// Pré traitement des paramêtres
32
		$pour_bdd = false;
33
		$p = $this->traiterParametres(array('service', 'format'), $param, $pour_bdd);
34
		unset($param[0]);
35
		unset($param[1]);
36
 
37
		sort($param);
38
 
39
		extract($p);
40
 
41
		// Récupération de la liste des flux
42
		$this->chargerListeDesFlux();
43
 
44
		// Chargement du bon type de service demandé
45
		if (isset($service)) {
46
			$this->service = $service;
47
			$methode = $this->getNomMethodeService();
48
			if (method_exists($this, $methode)) {
49
				if ($this->service != 'liste_des_flux') {
50
					if (isset($format) && preg_match('/^(?:rss1|rss2|atom)$/i', $format)) {
51
						// Multiplication par deux de la limite car nous récupérons deux lignes par item
52
						$this->limit = $this->limit*2;
53
						// Mise en minuscule de l'indication du format
54
						$this->format = strtolower($format);
55
						// Définition du fichier squelette demandé
56
						$this->squelette_dossier = dirname(__FILE__).DIRECTORY_SEPARATOR.'squelettes'.DIRECTORY_SEPARATOR;
57
						$this->squelette = $this->squelette_dossier.$this->format.'.tpl.xml';
58
					} else {
59
						$this->format = '';
60
						$this->messages[] = "Le service CEL Syndication nécessite d'indiquer en second paramètre le format : rss1, rss2 ou atom.";
61
					}
62
				}
63
				// Récupération du contenu à renvoyer
64
				$contenu = $this->$methode($param);
65
			} else {
66
				$this->messages[] = "Le type d'information demandé '$this->service' n'est pas disponible.";
67
			}
68
		} else {
69
			$this->messages[] = "Le service CEL Syndication Image nécessite d'indiquer en premier paramètre le type d'information demandé.";
70
		}
71
 
72
		// Envoie sur la sortie standard
73
		$encodage = 'utf-8';
74
		$mime = $this->getTypeMime();
75
		$formatage_json = $this->getFormatageJson();
76
		$this->envoyer($contenu, $mime, $encodage, $formatage_json);
77
	}
78
 
79
	private function getUrlServiceBase() {
80
		$url_service = $this->config['settings']['baseURLAbsoluDyn'].'CelSyndicationImage/'.$this->service.'/'.$this->format;
81
		return $url_service;
82
	}
83
 
84
	private function getUrlImageBase($id, $format = 'L') {
85
 
86
			$chemin_sur_serveur = $this->config['cel_db']['url_images'];
87
 
88
			$id = sprintf('%09s', $id) ;
89
            $id = wordwrap($id, 3 , '_', true) ;
90
 
91
            $id_fichier = $id.".jpg" ;
92
 
93
            $niveauDossier = split("_", $id) ;
94
 
95
            $dossierNiveau1 = $niveauDossier[0] ;
96
            $dossierNiveau2 = $niveauDossier[1] ;
97
 
98
            $chemin_sur_serveur_final = $chemin_sur_serveur.'/'.$dossierNiveau1.'/'.$dossierNiveau2 ;
99
            $chemin_fichier = $chemin_sur_serveur_final.'/'.$format.'/'.$id.'_'.$format.'.jpg';
100
 
101
            return $chemin_fichier;
102
	}
103
 
104
	private function getNomMethodeService() {
105
		$methode = '';
106
		$service_formate = str_replace(' ', '', ucwords(implode(' ', explode('_', $this->service))));
107
		$methode = 'getService'.$service_formate;
108
		return $methode;
109
	}
110
 
111
	private function getTypeMime() {
112
		$mime = '';
113
		switch ($this->format) {
114
			case 'atom' :
115
				$mime = 'application/atom+xml';
116
				break;
117
			case 'rss1' :
118
			case 'rss2' :
119
				$mime = 'application/rss+xml';
120
				break;
121
			default:
122
				$mime = 'text/html';
123
		}
124
		return $mime;
125
	}
126
 
127
	private function getFormatageJson() {
128
		$json = false;
129
		switch ($this->service) {
130
			case 'liste_des_flux' :
131
				$json = true;
132
				break;
133
			default:
134
				$json = false;
135
		}
136
		return $json;
137
	}
138
 
139
	private function getFlux($nom) {
140
		return isset($this->flux[$nom]) ? $this->flux[$nom] : array();
141
	}
142
 
143
	private function setFlux($nom, $titre, $description) {
144
		$url_base = $this->config['settings']['baseURLAbsoluDyn'].'CoelSyndicationImage/';
145
		$formats = array('atom', 'rss2', 'rss1');
146
		$flux = array();
147
		foreach ($formats as $format) {
148
			$url = $url_base.$nom.'/'.$format;
149
			$flux[$format] = $url;
150
		}
151
		$this->flux[$nom] = array('titre' => $titre, 'description' => $description, 'urls' => $flux);
152
	}
153
 
154
	private function chargerListeDesFlux() {
155
		$this->setFlux('RssParDefaut', 'Flux de syndication par défaut',
156
			'Ce flux fournit des informations sur les images du CEL.');
157
		$this->setFlux('RssParMotsCles', 'Flux des images filtré par mots clés',
158
			'Ce flux fournit des informations sur les images du CEL filtrées par mots-clés.');
159
		$this->setFlux('RssParLocalisation','Flux des images filtré par localisation',
160
			'Ce flux fournit des informations sur les images du CEL filtrées par localisation.');
161
	}
162
 
163
	private function getServiceListeDesFlux() {
164
		return $this->flux;
165
	}
166
 
167
	private function getServiceParDefaut() {
168
		// Construction de la requête
169
		$requete = 	(($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' * '.
170
			'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'date_modification DESC').' '.
171
			"LIMIT $this->start,$this->limit ";
172
 
173
		$elements = $this->executerRequete($requete);
174
 
175
		// Création du contenu
176
		$contenu = $this->executerService($elements);
177
		return $contenu;
178
	}
179
 
180
	private function getServiceSimple($params) {
181
 
182
		if(isset($params[0])) {
183
			$this->format_image = $params[0];
184
		}
185
 
186
		$this->start = 0;
187
		$this->limit = 10;
188
 
189
		// Construction de la requête
190
		$requete = 	(($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' * '.
191
			'FROM cel_obs_images a '.
192
			'INNER JOIN cel_inventory b '.
193
				'ON a.coi_ce_observation = b.ordre AND a.coi_ce_utilisateur = b.identifiant '.
194
			'INNER JOIN cel_images c '.
195
				'ON a.coi_ce_image = c.ci_id_image AND a.coi_ce_utilisateur = c.ci_ce_utilisateur '.
196
			'WHERE b.transmission = 1 AND b.identifiant = c.ci_ce_utilisateur '.
197
			'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'ci_meta_date_ajout DESC').' '.
198
			"LIMIT $this->start,$this->limit ";
199
 
200
		$elements = $this->executerRequete($requete);
201
 
202
		// Création du contenu
203
		$contenu = $this->executerService($elements);
204
		return $contenu;
205
	}
206
 
207
	protected function executerRequete($requete) {
208
		try {
209
			$infos = $this->bdd->query($requete)->fetchAll(PDO::FETCH_ASSOC);
210
			if ($infos === false) {
211
				$this->messages[] = "La requête suivante a retourné aucun résultat :\n$requete";
212
			}
213
		} catch (PDOException $e) {
214
			$this->messages[] = sprintf($this->getTxt('sql_erreur'), $e->getFile(), $e->getLine(), $e->getMessage());
215
		}
216
		return $infos;
217
	}
218
 
219
	private function executerService($elements) {
220
 
221
		// Prétraitement des données
222
		$donnees = $this->construireDonneesCommunesAuFlux($elements);
223
 
224
		foreach ($elements as $element) {
225
			$donnees['items'][] = $this->construireDonneesCommunesAuxItems($element);
226
		}
227
 
228
		// Création du contenu à partir d'un template PHP
229
		$contenu = Cel::traiterSquelettePhp($this->squelette, $donnees);
230
 
231
		return $contenu;
232
	}
233
 
234
	private function construireDonneesCommunesAuFlux($infos) {
235
		$donnees = $this->getFlux($this->service);
236
		$donnees['guid'] = $this->getUrlServiceBase();
237
		$donnees['lien_service'] = $this->creerUrlService();
238
		$donnees['lien_cel'] = sprintf($this->config['settings']['efloreUrlTpl'], $infos['num_nom_sel']);
239
		$donnees['editeur'] = $this->config['settings']['editeur'];
240
		$derniere_info_en_date = reset($infos);
241
		$date_modification_timestamp = strtotime($derniere_info_en_date['ci_meta_date_ajout']);
242
		$donnees['date_maj_RSS'] = date(DATE_RSS, $date_modification_timestamp);
243
		$donnees['date_maj_ATOM'] = date(DATE_ATOM, $date_modification_timestamp);
244
		$donnees['date_maj_W3C'] = date(DATE_W3C, $date_modification_timestamp);
245
		$donnees['annee_courante'] = date('Y');
246
		$donnees['generateur'] = 'CEL - Jrest - CelSyndicationImage';
247
		preg_match('/([0-9]+)/', '$Revision$', $match);
248
		$donnees['generateur_version'] = $match[1];
249
		return $donnees;
250
	}
251
 
252
	private function construireDonneesCommunesAuxItems($info) {
253
 
254
		$item = array();
255
		$date_modification_timestamp = strtotime($info['ci_meta_date_ajout']);
256
		$item['date_maj_simple'] = strftime('%A %d %B %Y à %H:%M', $date_modification_timestamp);
257
		$item['date_maj_RSS'] = date(DATE_RSS, $date_modification_timestamp);
258
		$item['date_maj_ATOM'] = date(DATE_ATOM, $date_modification_timestamp);
259
		$item['date_maj_W3C'] = date(DATE_W3C, $date_modification_timestamp);
260
		$item['titre'] = $this->creerTitre($info);
261
		$item['guid'] = $this->creerGuidItem($info);
262
		$item['lien'] = $this->creerLienItem($info);
263
		$item['description'] = $this->creerDescription($info);
264
		$item['description_encodee'] = htmlspecialchars($item['description']);
265
		return $item;
266
	}
267
 
268
	private function creerTitre($element) {
269
 
270
		$titre = '';
271
		$titre = $element['nom_sel'].' [nn'.$element['num_nom_sel'].'] par '.$this->creerAuteur($element['identifiant']);
272
 
273
		return $titre;
274
	}
275
 
276
	private function nettoyerTexte($txt) {
277
		$txt = preg_replace('/&(?!(a-z+|#0-9+|#x0-9a-f+);)/i', '&amp;', $txt, -1);
278
		return $txt;
279
	}
280
 
281
	private function creerGuidItem($element) {
282
		$guid = sprintf($this->config['settings']['guidImgTpl'], $element['ci_id_image']);
283
		return $guid;
284
	}
285
 
286
	private function creerLienItem($element) {
287
 
288
		$lien = $this->getUrlImageBase($element['ci_id_image'],$this->format_image);
289
		return $lien;
290
	}
291
 
292
	private function creerDescription($element) {
293
 
294
		$description = sprintf($this->config['settings']['efloreUrlTpl'], urlencode($element['num_nom_sel']));
295
		$description = $this->nettoyerTexte($description);
296
 
297
		return $description;
298
	}
299
 
300
	private function creerAuteur($courriel) {
301
		$auteur = ($this->etreFluxAdmin()) ? $courriel : $this->traiterCourriel($courriel);
302
		return $auteur;
303
	}
304
 
305
	private function traiterCourriel($courriel) {
306
		$courriel = preg_replace('/[^@]+$/i', '...', $courriel);
307
		return $courriel;
308
	}
309
 
310
	private function etreFluxAdmin() {
311
		return ($this->service == 'pour-admin') ? true : false;
312
	}
313
 
314
	private function etreNull($valeur) {
315
		$etre_null = false;
316
		if ($valeur == '' || $valeur == null || $valeur == '000null' || $valeur == 'null') {
317
			$etre_null = true;
318
		}
319
		return $etre_null;
320
	}
321
 
322
	private function creerUrlService() {
323
		$url_service = $this->getUrlServiceBase();
324
		if (isset($this->start) || isset($this->limit)) {
325
			$arguments = array();
326
			if (isset($this->start) && isset($_GET['start'])) {
327
				$arguments[] = 'start='.$this->start;
328
			}
329
			if (isset($this->limit) && isset($_GET['limit'])) {
330
				$arguments[] = 'limit='.($this->limit/2);
331
			}
332
			if (count($arguments) > 0) {
333
				$url_service .= '?'.implode('&', $arguments);
334
			}
335
		}
336
		return $url_service;
337
	}
338
 
339
	function calculerDimensions($tailleXY, $tailleoR = 300) {
340
 
341
        if($tailleXY[1] == 0) {
342
            $tailleXY[1] = $tailleOr;
343
        }
344
 
345
        if($tailleXY[0] == 0) {
346
            $tailleXY[0] = $tailleOr;
347
        }
348
 
349
        $maxTaille = max($tailleXY[1],$tailleXY[0]) ;
350
 
351
        if($maxTaille == $tailleXY[1]) {
352
 
353
            $rapport = $tailleXY[1]/$tailleXY[0] ;
354
            $tailleXY[1] = $tailleOr ;
355
            $tailleXY[0] = round($tailleXY[1]/$rapport,0) ;
356
 
357
        }else {
358
            $rapport = $tailleXY[0]/$tailleXY[1] ;
359
            $tailleXY[0] = $tailleOr ;
360
            $tailleXY[1] = round($tailleXY[0]/$rapport,0) ;
361
        }
362
 
363
        return $tailleXY ;
364
    }
365
}