3 * A class for an image response on an HTTP request
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, this is free software
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * The extended headers are taken from phpMyAdmin setup tool, written by
25 * Michal Cihar <michal@cihar.com>, licensed under GNU GPL 2.0.
27 class ImageResponse extends BaseFrameworkSystem implements Responseable {
31 private $responseStatus = "200 OK";
34 * Array with all headers
36 private $responseHeaders = array();
39 * Cookies we shall sent out
41 private $cookies = array();
44 * Body of the response
46 private $responseBody = "";
49 * Fatal resolved messages from filters and so on
51 private $fatalMessages = array();
54 * Instance of the image
56 private $imageInstance = null;
59 * Protected constructor
63 protected function __construct () {
64 // Call parent constructor
65 parent::__construct(__CLASS__);
68 $this->removeNumberFormaters();
69 $this->removeSystemArray();
73 * Creates an object of this class
75 * @param $appInstance An instance of a manageable application
76 * @return $responseInstance A prepared instance of this class
78 public final static function createImageResponse (ManageableApplication $appInstance) {
80 $responseInstance = new ImageResponse();
82 // Set the application instance
83 $responseInstance->setApplicationInstance($appInstance);
85 // Initialize the template engine here
86 $responseInstance->initTemplateEngine($appInstance);
88 // Return the prepared instance
89 return $responseInstance;
95 * @param $status New response status
98 public final function setResponseStatus ($status) {
99 $this->responseStatus = (string) $status;
105 * @param $name Name of header element
106 * @param $value Value of header element
109 public final function addHeader ($name, $value) {
110 $this->responseHeaders[$name] = $value;
114 * Reset the header array
118 public final function resetResponseHeaders () {
119 $this->responseHeaders = array();
123 * "Writes" data to the response body
125 * @param $output Output we shall sent in the HTTP response
128 public function writeToBody ($output) {
129 $this->responseBody .= $output;
133 * Sets the response body to something new
135 * @param $output Output we shall sent in the HTTP response
138 public function setResponseBody ($output) {
139 $this->responseBody = $output;
143 * Flushs the cached HTTP response to the outer world
145 * @param $force Wether we shall force the output or abort if headers are
146 * already sent with an exception
148 * @todo Add support for fatal messages in image response
149 * @throws ResponseHeadersAlreadySentException Thrown if headers are
152 public function flushBuffer ($force=false) {
153 if ((headers_sent()) && (!$force)) {
154 // Headers are already sent!
155 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
156 } elseif (!headers_sent()) {
158 header("HTTP/1.1 {$this->responseStatus}");
161 $now = gmdate('D, d M Y H:i:s') . ' GMT';
163 // General header for no caching
164 $this->addHeader('Expired', $now); // rfc2616 - Section 14.21
165 $this->addHeader('Last-Modified', $now);
166 $this->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
167 $this->addHeader('Pragma', 'no-cache'); // HTTP/1.0
168 $this->addHeader('Content-type', 'image/'.$this->imageInstance->getImageType());
170 // Define the charset to be used
171 //$this->addHeader('Content-Type:', sprintf("text/html; charset=%s", $this->getConfigInstance()->readConfig('header_charset')));
173 foreach ($this->responseHeaders as $name=>$value) {
174 header("{$name}: {$value}");
178 if (count($this->cookies) > 0) {
180 $cookieString = implode(" ", $this->cookies);
181 header("Set-Cookie: {$cookieString}");
184 $this->cookies = array();
188 // Are there some error messages?
189 if (count($this->fatalMessages) == 0) {
190 // Get image content from cache
191 $imageContent = $this->imageInstance->getContent();
194 // Display all error messages
195 $this->partialStub("Fatal messages are currently unsupported in image response.");
198 // Clear response header and body
199 $this->setResponseBody("");
200 $this->resetResponseHeaders();
204 * Initializes the template engine instance
206 * @param $appInstance An instance of a manageable application
209 public final function initTemplateEngine (ManageableApplication $appInstance) {
210 // Get config instance
211 $cfg = $this->getConfigInstance();
213 // Set new template engine
214 $cfg->setConfigEntry('template_class' , $cfg->readConfig('image_template_class'));
215 $cfg->setConfigEntry('raw_template_extension' , ".img");
216 $cfg->setConfigEntry('code_template_extension', ".itp");
217 $cfg->setConfigEntry('tpl_base_path' , "templates/images/");
218 $cfg->setConfigEntry('code_template_type' , "image");
220 // Get a prepared instance
221 $this->setTemplateInstance($this->prepareTemplateInstance($appInstance));
225 * Adds a fatal message id to the response. The added messages can then be
226 * processed and outputed to the world
228 * @param $messageId The message id we shall add
231 public final function addFatalMessage ($messageId) {
232 // Adds the resolved message id to the fatal message list
233 $this->fatalMessages[] = $this->getApplicationInstance()->getLanguageInstance()->getMessage($messageId);
237 * Adds a cookie to the response
239 * @param $cookieName Cookie's name
240 * @param $cookieValue Value to store in the cookie
241 * @param $encrypted Do some extra encryption on the value
242 * @param $expires Timestamp of expiration (default: configured)
244 * @throws ResponseHeadersAlreadySentException If headers are already sent
245 * @todo Encryption of cookie data not yet supported.
246 * @todo Why are these parameters conflicting?
247 * @todo If the return statement is removed and setcookie() commented out,
248 * @todo this will send only one cookie out, the first one.
250 public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = null) {
251 // Are headers already sent?
252 if (headers_sent()) {
253 // Throw an exception here
254 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
257 // Shall we encrypt the cookie?
258 if ($encrypted === true) {
261 // For slow browsers set the cookie array element first
262 $_COOKIE[$cookieName] = $cookieValue;
264 // Get all config entries
265 if (is_null($expires)) {
266 $expires = (time() + $this->getConfigInstance()->readConfig('cookie_expire'));
269 $path = $this->getConfigInstance()->readConfig('cookie_path');
270 $domain = $this->getConfigInstance()->readConfig('cookie_domain');
272 setcookie($cookieName, $cookieValue, $expires);
273 //, $path, $domain, (isset($_SERVER['HTTPS']))
276 // Now construct the full header
277 $cookieString = $cookieName . "=" . $cookieValue . "; ";
278 $cookieString .= "expires=" . date("D, d-F-Y H:i:s", $expires) . " GMT";
279 // $cookieString .= "; path=".$path."; domain=".$domain;
281 // Set the cookie as a header
282 $this->cookies[$cookieName] = $cookieString;
286 * Redirect to a configured URL. The URL can be absolute or relative. In
287 * case of relative URL it will be extended automatically.
289 * @param $configEntry The configuration entry which holds our URL
291 * @throws ResponseHeadersAlreadySentException If headers are already sent
293 public function redirectToConfiguredUrl ($configEntry) {
294 // Is the header not yet sent?
295 if (headers_sent()) {
296 // Throw an exception here
297 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
300 // Get the url from config
301 $url = $this->getConfigInstance()->readConfig($configEntry);
303 // Do we have a "http" in front of the URL?
304 if (substr(strtolower($url), 0, 4) != "http") {
305 // Is there a / in front of the relative URL?
306 if (substr($url, 0, 1) == "/") $url = substr($url, 1);
308 // No, then extend it with our base URL
309 $url = $this->getConfigInstance()->readConfig('base_url') . "/" . $url;
312 // Add redirect header
313 $this->addHeader("Location", $url);
315 // Set correct response status
316 $this->setResponseStatus("301 Moved Permanently");
319 $this->setResponseBody("");
322 $this->flushBuffer();
329 * Expires the given cookie if it is set
331 * @param $cookieName Cookie to expire
334 public function expireCookie ($cookieName) {
335 // Is the cookie there?
336 if (isset($_COOKIE[$cookieName])) {
337 // Then expire it with 20 minutes past
338 $this->addCookie($cookieName, "", false, (time() - 1200));
340 // Remove it from array
341 unset($_COOKIE[$cookieName]);
346 * Refreshs a given cookie. This will make the cookie live longer
348 * @param $cookieName Cookie to refresh
351 public function refreshCookie ($cookieName) {
352 // Only update existing cookies
353 if (isset($_COOKIE[$cookieName])) {
355 $this->addCookie($cookieName, $_COOKIE[$cookieName], false);
360 * Setter for image instanxe
362 * @param $imageInstance An instance of an image
365 public final function setImageInstance (BaseImage $imageInstance) {
366 $this->imageInstance = $imageInstance;
370 * Getter for default command
372 * @return $defaultCommand Default command for this response
374 public function getDefaultCommand () {
375 $defaultCommand = $this->getConfigInstance()->readConfig('default_image_command');
376 return $defaultCommand;