Image generator added, first CAPTCHA added with missing controller (partly work)
[shipsimu.git] / inc / classes / main / response / class_ImageResponse.php
1 <?php
2 /**
3  * A class for an image response on an HTTP request
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  *
24  * The extended headers are taken from phpMyAdmin setup tool, written by
25  * Michal Cihar <michal@cihar.com>, licensed under GNU GPL 2.0.
26  */
27 class ImageResponse extends BaseFrameworkSystem implements Responseable {
28         /**
29          * Response status
30          */
31         private $responseStatus = "200 OK";
32
33         /**
34          * Array with all headers
35          */
36         private $responseHeaders = array();
37
38         /**
39          * Cookies we shall sent out
40          */
41         private $cookies = array();
42
43         /**
44          * Body of the response
45          */
46         private $responseBody = "";
47
48         /**
49          * Instance of the template engine
50          */
51         private $templateEngine = null;
52
53         /**
54          * Fatal resolved messages from filters and so on
55          */
56         private $fatalMessages = array();
57
58         /**
59          * Instance of the image
60          */
61         private $imageInstance = null;
62
63         /**
64          * Protected constructor
65          *
66          * @return      void
67          */
68         protected function __construct () {
69                 // Call parent constructor
70                 parent::__construct(__CLASS__);
71
72                 // Set part description
73                 $this->setObjectDescription("HTTP response");
74
75                 // Create unique ID number
76                 $this->generateUniqueId();
77
78                 // Clean up a little
79                 $this->removeNumberFormaters();
80                 $this->removeSystemArray();
81         }
82
83         /**
84          * Creates an object of this class
85          *
86          * @param       $appInstance            An instance of a manageable application
87          * @return      $responseInstance       A prepared instance of this class
88          */
89         public final static function createImageResponse (ManageableApplication $appInstance) {
90                 // Get a new instance
91                 $responseInstance = new ImageResponse();
92
93                 // Set the application instance
94                 $responseInstance->setApplicationInstance($appInstance);
95
96                 // Initialize the template engine here
97                 $responseInstance->initTemplateEngine($appInstance);
98
99                 // Return the prepared instance
100                 return $responseInstance;
101         }
102
103         /**
104          * Setter for status
105          *
106          * @param       $status         New response status
107          * @return      void
108          */
109         public final function setResponseStatus ($status) {
110                 $this->responseStatus = (string) $status;
111         }
112
113         /**
114          * Add header element
115          *
116          * @param       $name   Name of header element
117          * @param       $value  Value of header element
118          * @return      void
119          */
120         public final function addHeader ($name, $value) {
121                 $this->responseHeaders[$name] = $value;
122         }
123
124         /**
125          * Reset the header array
126          *
127          * @return      void
128          */
129         public final function resetResponseHeaders () {
130                 $this->responseHeaders = array();
131         }
132
133         /**
134          * "Writes" data to the response body
135          *
136          * @param       $output         Output we shall sent in the HTTP response
137          * @return      void
138          */
139         public function writeToBody ($output) {
140                 $this->responseBody .= $output;
141         }
142
143         /**
144          * Sets the response body to something new
145          *
146          * @param       $output         Output we shall sent in the HTTP response
147          * @return      void
148          */
149         public function setResponseBody ($output) {
150                 $this->responseBody = $output;
151         }
152
153         /**
154          * Flushs the cached HTTP response to the outer world
155          *
156          * @param       $force  Wether we shall force the output or abort if headers are
157          *                                      already sent with an exception
158          * @return      void
159          * @throws      ResponseHeadersAlreadySentException             Thrown if headers are
160          *                                                                                                      already sent
161          */
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()) {
167                         // Send headers out
168                         header("HTTP/1.1 {$this->responseStatus}");
169
170                         // Used later
171                         $now = gmdate('D, d M Y H:i:s') . ' GMT';
172
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());
179
180                         // Define the charset to be used
181                         //$this->addHeader('Content-Type:', sprintf("text/html; charset=%s", $this->getConfigInstance()->readConfig('header_charset')));
182
183                         foreach ($this->responseHeaders as $name=>$value) {
184                                 header("{$name}: {$value}");
185                         } // END - foreach
186
187                         // Send cookies out?
188                         if (count($this->cookies) > 0) {
189                                 // Send all cookies
190                                 $cookieString = implode(" ", $this->cookies);
191                                 header("Set-Cookie: {$cookieString}");
192
193                                 // Remove them all
194                                 $this->cookies = array();
195                         } // END - if
196                 }
197
198                 // Are there some error messages?
199                 if (count($this->fatalMessages) == 0) {
200                         // Get image content from cache
201                         $imageContent = $this->imageInstance->getContent();
202                         die($imageContent);
203                 } else {
204                         // Display all error messages
205                         $this->partialStub("Fatal messages are currently unsupported in image response.");
206                 }
207
208                 // Clear response header and body
209                 $this->setResponseBody("");
210                 $this->resetResponseHeaders();
211         }
212
213         /**
214          * Initializes the template engine instance
215          *
216          * @param       $appInstance    An instance of a manageable application
217          * @return      void
218          */
219         public final function initTemplateEngine (ManageableApplication $appInstance) {
220                 // Get config instance
221                 $cfg = $this->getConfigInstance();
222
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");
229
230                 // Get a prepared instance
231                 $this->templateEngine = $this->prepareTemplateEngine($appInstance);
232         }
233
234         /**
235          * Getter for the template engine instance
236          *
237          * @return      $templateEngine         An instance of the used template engine
238          */
239         public final function getTemplateEngine () {
240                 return $this->templateEngine;
241         }
242
243         /**
244          * Adds a fatal message id to the response. The added messages can then be
245          * processed and outputed to the world
246          *
247          * @param       $messageId      The message id we shall add
248          * @return      void
249          */
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);
253         }
254
255         /**
256          * Adds a cookie to the response
257          *
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)
262          * @return      void
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.
268          */
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);
274                 } // END - if
275
276                 // Shall we encrypt the cookie?
277                 if ($encrypted === true) {
278                 } // END - if
279
280                 // For slow browsers set the cookie array element first
281                 $_COOKIE[$cookieName] = $cookieValue;
282
283                 // Get all config entries
284                 if (is_null($expires)) {
285                         $expires = (time() + $this->getConfigInstance()->readConfig('cookie_expire'));
286                 } // END - if
287
288                 $path = $this->getConfigInstance()->readConfig('cookie_path');
289                 $domain = $this->getConfigInstance()->readConfig('cookie_domain');
290
291                 setcookie($cookieName, $cookieValue, $expires);
292                 //, $path, $domain, (isset($_SERVER['HTTPS']))
293                 return;
294
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;
299
300                 // Set the cookie as a header
301                 $this->cookies[$cookieName] = $cookieString;
302         }
303
304         /**
305          * Redirect to a configured URL. The URL can be absolute or relative. In
306          * case of relative URL it will be extended automatically.
307          *
308          * @param       $configEntry    The configuration entry which holds our URL
309          * @return      void
310          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
311          */
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);
317                 } // END - if
318
319                 // Get the url from config
320                 $url = $this->getConfigInstance()->readConfig($configEntry);
321
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);
326
327                         // No, then extend it with our base URL
328                         $url = $this->getConfigInstance()->readConfig('base_url') . "/" . $url;
329                 } // END - if
330
331                 // Add redirect header
332                 $this->addHeader("Location", $url);
333
334                 // Set correct response status
335                 $this->setResponseStatus("301 Moved Permanently");
336
337                 // Clear the body
338                 $this->setResponseBody("");
339
340                 // Flush the result
341                 $this->flushBuffer();
342
343                 // All done here...
344                 exit();
345         }
346
347         /**
348          * Expires the given cookie if it is set
349          *
350          * @param       $cookieName             Cookie to expire
351          * @return      void
352          */
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));
358
359                         // Remove it from array
360                         unset($_COOKIE[$cookieName]);
361                 } // END - if
362         }
363
364         /**
365          * Refreshs a given cookie. This will make the cookie live longer
366          *
367          * @param       $cookieName             Cookie to refresh
368          * @return      void
369          */
370         public function refreshCookie ($cookieName) {
371                 // Only update existing cookies
372                 if (isset($_COOKIE[$cookieName])) {
373                         // Update the cookie
374                         $this->addCookie($cookieName, $_COOKIE[$cookieName], false);
375                 } // END - if
376         }
377
378         /**
379          * Setter for image instanxe
380          *
381          * @param       $imageInstance  An instance of an image
382          * @return      void
383          */
384         public final function setImageInstance (BaseImage $imageInstance) {
385                 $this->imageInstance = $imageInstance;
386         }
387 }
388
389 // [EOF]
390 ?>