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 * Instance of the template engine
51 private $templateEngine = null;
54 * Fatal resolved messages from filters and so on
56 private $fatalMessages = array();
59 * Instance of the image
61 private $imageInstance = null;
64 * Protected constructor
68 protected function __construct () {
69 // Call parent constructor
70 parent::__construct(__CLASS__);
72 // Set part description
73 $this->setObjectDescription("HTTP response");
75 // Create unique ID number
76 $this->generateUniqueId();
79 $this->removeNumberFormaters();
80 $this->removeSystemArray();
84 * Creates an object of this class
86 * @param $appInstance An instance of a manageable application
87 * @return $responseInstance A prepared instance of this class
89 public final static function createImageResponse (ManageableApplication $appInstance) {
91 $responseInstance = new ImageResponse();
93 // Set the application instance
94 $responseInstance->setApplicationInstance($appInstance);
96 // Initialize the template engine here
97 $responseInstance->initTemplateEngine($appInstance);
99 // Return the prepared instance
100 return $responseInstance;
106 * @param $status New response status
109 public final function setResponseStatus ($status) {
110 $this->responseStatus = (string) $status;
116 * @param $name Name of header element
117 * @param $value Value of header element
120 public final function addHeader ($name, $value) {
121 $this->responseHeaders[$name] = $value;
125 * Reset the header array
129 public final function resetResponseHeaders () {
130 $this->responseHeaders = array();
134 * "Writes" data to the response body
136 * @param $output Output we shall sent in the HTTP response
139 public function writeToBody ($output) {
140 $this->responseBody .= $output;
144 * Sets the response body to something new
146 * @param $output Output we shall sent in the HTTP response
149 public function setResponseBody ($output) {
150 $this->responseBody = $output;
154 * Flushs the cached HTTP response to the outer world
156 * @param $force Wether we shall force the output or abort if headers are
157 * already sent with an exception
159 * @throws ResponseHeadersAlreadySentException Thrown if headers are
162 public function flushBuffer ($force=false) {
163 if ((headers_sent()) && (!$force)) {
164 // Headers are already sent!
165 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
166 } elseif (!headers_sent()) {
168 header("HTTP/1.1 {$this->responseStatus}");
171 $now = gmdate('D, d M Y H:i:s') . ' GMT';
173 // General header for no caching
174 $this->addHeader('Expired', $now); // rfc2616 - Section 14.21
175 $this->addHeader('Last-Modified', $now);
176 $this->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
177 $this->addHeader('Pragma', 'no-cache'); // HTTP/1.0
178 $this->addHeader('Content-type', 'image/'.$this->imageInstance->getImageType());
180 // Define the charset to be used
181 //$this->addHeader('Content-Type:', sprintf("text/html; charset=%s", $this->getConfigInstance()->readConfig('header_charset')));
183 foreach ($this->responseHeaders as $name=>$value) {
184 header("{$name}: {$value}");
188 if (count($this->cookies) > 0) {
190 $cookieString = implode(" ", $this->cookies);
191 header("Set-Cookie: {$cookieString}");
194 $this->cookies = array();
198 // Are there some error messages?
199 if (count($this->fatalMessages) == 0) {
200 // Get image content from cache
201 $imageContent = $this->imageInstance->getContent();
204 // Display all error messages
205 $this->partialStub("Fatal messages are currently unsupported in image response.");
208 // Clear response header and body
209 $this->setResponseBody("");
210 $this->resetResponseHeaders();
214 * Initializes the template engine instance
216 * @param $appInstance An instance of a manageable application
219 public final function initTemplateEngine (ManageableApplication $appInstance) {
220 // Get config instance
221 $cfg = $this->getConfigInstance();
223 // Set new template engine
224 $cfg->setConfigEntry('template_class', "ImageTemplateEngine");
225 $cfg->setConfigEntry('raw_template_extension', ".itp");
226 $cfg->setConfigEntry('code_template_extension', ".itp");
227 $cfg->setConfigEntry('tpl_base_path', "templates/images/");
228 $cfg->setConfigEntry('code_template_type', "image");
230 // Get a prepared instance
231 $this->templateEngine = $this->prepareTemplateEngine($appInstance);
235 * Getter for the template engine instance
237 * @return $templateEngine An instance of the used template engine
239 public final function getTemplateEngine () {
240 return $this->templateEngine;
244 * Adds a fatal message id to the response. The added messages can then be
245 * processed and outputed to the world
247 * @param $messageId The message id we shall add
250 public final function addFatalMessage ($messageId) {
251 // Adds the resolved message id to the fatal message list
252 $this->fatalMessages[] = $this->getApplicationInstance()->getLanguageInstance()->getMessage($messageId);
256 * Adds a cookie to the response
258 * @param $cookieName Cookie's name
259 * @param $cookieValue Value to store in the cookie
260 * @param $encrypted Do some extra encryption on the value
261 * @param $expires Timestamp of expiration (default: configured)
263 * @throws ResponseHeadersAlreadySentException If headers are already sent
264 * @todo Encryption of cookie data not yet supported.
265 * @todo Why are these parameters conflicting?
266 * @todo If the return statement is removed and setcookie() commented out,
267 * @todo this will send only one cookie out, the first one.
269 public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = null) {
270 // Are headers already sent?
271 if (headers_sent()) {
272 // Throw an exception here
273 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
276 // Shall we encrypt the cookie?
277 if ($encrypted === true) {
280 // For slow browsers set the cookie array element first
281 $_COOKIE[$cookieName] = $cookieValue;
283 // Get all config entries
284 if (is_null($expires)) {
285 $expires = (time() + $this->getConfigInstance()->readConfig('cookie_expire'));
288 $path = $this->getConfigInstance()->readConfig('cookie_path');
289 $domain = $this->getConfigInstance()->readConfig('cookie_domain');
291 setcookie($cookieName, $cookieValue, $expires);
292 //, $path, $domain, (isset($_SERVER['HTTPS']))
295 // Now construct the full header
296 $cookieString = $cookieName . "=" . $cookieValue . "; ";
297 $cookieString .= "expires=" . date("D, d-F-Y H:i:s", $expires) . " GMT";
298 // $cookieString .= "; path=".$path."; domain=".$domain;
300 // Set the cookie as a header
301 $this->cookies[$cookieName] = $cookieString;
305 * Redirect to a configured URL. The URL can be absolute or relative. In
306 * case of relative URL it will be extended automatically.
308 * @param $configEntry The configuration entry which holds our URL
310 * @throws ResponseHeadersAlreadySentException If headers are already sent
312 public function redirectToConfiguredUrl ($configEntry) {
313 // Is the header not yet sent?
314 if (headers_sent()) {
315 // Throw an exception here
316 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
319 // Get the url from config
320 $url = $this->getConfigInstance()->readConfig($configEntry);
322 // Do we have a "http" in front of the URL?
323 if (substr(strtolower($url), 0, 4) != "http") {
324 // Is there a / in front of the relative URL?
325 if (substr($url, 0, 1) == "/") $url = substr($url, 1);
327 // No, then extend it with our base URL
328 $url = $this->getConfigInstance()->readConfig('base_url') . "/" . $url;
331 // Add redirect header
332 $this->addHeader("Location", $url);
334 // Set correct response status
335 $this->setResponseStatus("301 Moved Permanently");
338 $this->setResponseBody("");
341 $this->flushBuffer();
348 * Expires the given cookie if it is set
350 * @param $cookieName Cookie to expire
353 public function expireCookie ($cookieName) {
354 // Is the cookie there?
355 if (isset($_COOKIE[$cookieName])) {
356 // Then expire it with 20 minutes past
357 $this->addCookie($cookieName, "", false, (time() - 1200));
359 // Remove it from array
360 unset($_COOKIE[$cookieName]);
365 * Refreshs a given cookie. This will make the cookie live longer
367 * @param $cookieName Cookie to refresh
370 public function refreshCookie ($cookieName) {
371 // Only update existing cookies
372 if (isset($_COOKIE[$cookieName])) {
374 $this->addCookie($cookieName, $_COOKIE[$cookieName], false);
379 * Setter for image instanxe
381 * @param $imageInstance An instance of an image
384 public final function setImageInstance (BaseImage $imageInstance) {
385 $this->imageInstance = $imageInstance;
389 * Getter for default command
391 * @return $defaultCommand Default command for this response
393 public function getDefaultCommand () {
394 $defaultCommand = $this->getConfigInstance()->readConfig('default_image_command');
395 return $defaultCommand;