Subversion Repositories eFlore/Applications.cel

Rev

Rev 3915 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3910 killian 1
<?php
2
// declare(encoding='UTF-8');
3
/**
4
 * Service fournissant permettant de visualiser ou télécharger des images du CEL
5
 * Spécifiquement pour le format O (original) tout en supprimant les EXIF
6
 * de façon à protéger les espèces protégées floutées
7
 *
8
 * @internal   Mininum PHP version : 5.2
9
 * @category   CEL
10
 * @package    Services
11
 * @subpackage Images
12
 * @version    0.1
13
 * @author     Mathias CHOUET <mathias@tela-botanica.org>
14
 * @author     Jean-Pascal MILCENT <jpm@tela-botanica.org>
15
 * @author     Aurelien PERONNET <aurelien@tela-botanica.org>
16
 * @license    GPL v3 <http://www.gnu.org/licenses/gpl.txt>
17
 * @license    CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
18
 * @copyright  1999-2014 Tela Botanica <accueil@tela-botanica.org>
19
 */
3915 killian 20
class CelImageFormatO {
3910 killian 21
 
22
	private $config;
23
	// @TODO tirer ça de la config
24
	private $formats = array('O');
25
	const METHODE_TELECHARGEMENT = 'telecharger';
26
	const METHODE_AFFICHAGE = 'afficher';
27
 
28
	// Pas besoin d'étendre Cel ici, surtout que le constructeur
29
	// de la classe Cel instancie toujours une connexion à la bdd
30
	// dont on a pas besoin ici. Ceci évite de planter le service
31
	// quand la bdd est surchargée.
32
	public function __construct($config) {
33
		$this->config = $config;
34
	}
35
 
36
	public function getRessource() {
37
		header('Content-Type: application/json');
38
		echo json_encode($this->obtenirDescriptionService());
39
	}
40
 
41
	/**
42
	* Méthode appelée avec une requête de type GET.
43
	*/
44
	public function getElement($params) {
45
		// suppression des 0 non significatifs à gauche
46
		$id = ltrim($params[0], '0');
47
		$format = isset($_GET['format']) ? $_GET['format'] : 'M';
48
		$methode_livraison = isset($_GET['methode']) ? $_GET['methode'] : self::METHODE_AFFICHAGE;
49
 
50
		if($this->verifierParametres($id, $format, $methode_livraison)) {
51
			$gestion_formats_images = new ImageRecreation($this->config);
52
			$image_binaire = $gestion_formats_images->creerOuRenvoyerImage($params[0], $format);
53
 
54
			if($image_binaire) {
55
				$this->envoyerImage($id, $image_binaire, $format, $methode_livraison);
56
			} else {
57
				header("HTTP/1.0 404 Not Found");
58
				echo 'Aucune image ne correspond à cet identifiant';
59
			}
60
		}
61
	}
62
 
63
	private function verifierParametres($id, $format, $methode_livraison) {
64
		$ok = true;
65
		$message = '';
66
		if(!is_numeric($id)) {
67
			$message .= "L'identifiant de format doit être un entier. ";
68
			$ok = false;
69
		}
70
 
71
		if(!in_array($format, $this->formats)) {
72
			$message .= "Le format d'image est inconnu, les formats acceptés sont ".implode(',', $this->formats).". ";
73
			$ok = false;
74
		}
75
 
76
		$types_methode_livraison = array(self::METHODE_AFFICHAGE, self::METHODE_TELECHARGEMENT);
77
		if (!in_array($methode_livraison, $types_methode_livraison)) {
78
			$message .= "Le format de methode de livraison ".$methode_livraison." n'est pas acceptée par le service. ".
79
					" Seuls les methodes suivantes sont gérés : ".implode(',', $types_methode_livraison);
80
			$ok = false;
81
		}
82
 
83
		if(!empty($message)) {
84
			header("HTTP/1.0 400 Bad Request");
85
			echo $message;
86
		}
87
		return $ok;
88
	}
89
 
90
	private function envoyerImage($id, $image_binaire, $format, $methode) {
3923 killian 91
		$gestion_formats_images = new ImageRecreation($this->config);
92
		$dossier = $gestion_formats_images->obtenirDossierPourFormat($id, $format);
93
		$nom_fichier = $gestion_formats_images->convertirIdBddVersNomFichier($id, $format);
94
 
95
		$last_modified_time = filemtime($dossier.'/'.$nom_fichier);
96
 
97
		// On génère l'ETAG faible
98
		$etag = 'W/"' . md5($last_modified_time) . '"';
99
 
100
		// On définit les bons headers
101
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $last_modified_time) . " GMT");
102
		header('Cache-Control: public, max-age=604800'); // On peut ici changer la durée de validité du cache
103
		header("Etag: $etag");
104
 
105
		// On vérifie les headers envoyés dans la requête
106
		if (
107
		(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) === $last_modified_time) ||
108
		(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $etag === trim($_SERVER['HTTP_IF_NONE_MATCH']))
109
		) {
110
			// On renvoit une 304 si on n'a rien modifié depuis
111
			header('HTTP/1.1 304 Not Modified');
112
			exit();
113
		}
114
 
3910 killian 115
		if ($methode == self::METHODE_AFFICHAGE) {
116
			header('Content-Type: image/jpeg');
117
		} else {
118
			$this->envoyerHeadersTelechargement($id, $image_binaire, $format);
119
		}
120
 
121
		echo $image_binaire;
122
		exit();
123
	}
124
 
125
	private function envoyerHeadersTelechargement($id, $image_binaire, $format) {
126
		if (function_exists('mb_strlen')) {
127
			$taille = mb_strlen($image_binaire, '8bit');
128
		} else {
129
			$taille = strlen($image_binaire);
130
		}
131
 
132
		// creation du format original
133
		$id_avec_zeros = sprintf('%09s', $id) ;
134
		$id_avec_zeros_underscores = wordwrap($id_avec_zeros, 3 , '_', true) ;
135
		$nom_fichier = $id_avec_zeros_underscores.'_'.$format.'.jpg';
136
 
137
		header('Content-Description: File Transfer');
138
		header('Content-Type: application/octet-stream');
139
		header('Content-Disposition: attachment; filename="'.$nom_fichier.'"');
140
		header('Content-Transfer-Encoding: binary');
141
		header('Connection: Keep-Alive');
142
		header('Expires: 0');
143
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
144
		header('Pragma: public');
145
		header('Content-Length: '.$taille);
146
	}
147
 
148
	private function obtenirDescriptionService() {
149
		$retour = array('description' => 'Ce service peut être appelé afin de visualiser ou bien télécharger les images du cel',
150
			'formats' => $this->formats,
151
			'utilisation' => 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']."/{id} où {id} est l'identifiant numérique de l'image désirée",
152
			'parametres' => array(
153
				'methode' => "Valeurs : afficher, telecharger. Permet de préciser si l'image doit être affichée ou téléchargée",
154
				'format' => "Valeurs : voir la liste ci dessous. Permet de demander un format précis de l'image parmi ceux disponibles ")
155
		);
156
 
157
		// ^^ c'est marrant non ?
158
		$format_formates = array();
159
		foreach ($this->formats as $format) {
160
			if ($format == "O") {
161
				$format_formates["O"] = array("hauteur" => "dépend de l'image originale",
162
						"largeur" => "dépend de l'image originale",
163
						"notes"	=> "Image dans son ratio et sa résolution originale (elle peut éventuellement avoir été compressée en qualité)"
164
				);
165
			} else {
166
				$description = array();
167
				if (strpos($format, 'R') !== false) {
168
					$description[] = "Format carré, rogné pour ne garder que le centre de l'image.";
169
				}
170
				if (strpos($format, 'C') !== false) {
171
					$description[] = "Format carré, si le format contient R, il est rogné, sinon des bandes blanches sont ajoutées pour conserver le ratio.";
172
				}
173
 
174
				if (empty($description)) {
175
					$description[] = "Format standard, le ratio original de l'image est conservé";
176
				}
177
 
178
				$resolution = $this->config['cel']['format_'.$format];
179
				$resolution = explode("_", $resolution);
180
				$format_formates[$format] = array("hauteur" => $resolution[0],
181
						"largeur" => $resolution[1],
182
						"notes"	=> implode(' ', $description)
183
				);
184
			}
185
		}
186
 
187
		$retour['resolutions'] = $format_formates;
188
		return $retour;
189
	}
190
}