Debug mailer finished and debug messages removed:
[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          * Fatal resolved messages from filters and so on
50          */
51         private $fatalMessages = array();
52
53         /**
54          * Instance of the image
55          */
56         private $imageInstance = null;
57
58         /**
59          * Protected constructor
60          *
61          * @return      void
62          */
63         protected function __construct () {
64                 // Call parent constructor
65                 parent::__construct(__CLASS__);
66
67                 // Set part description
68                 $this->setObjectDescription("HTTP response");
69
70                 // Create unique ID number
71                 $this->generateUniqueId();
72
73                 // Clean up a little
74                 $this->removeNumberFormaters();
75                 $this->removeSystemArray();
76         }
77
78         /**
79          * Creates an object of this class
80          *
81          * @param       $appInstance            An instance of a manageable application
82          * @return      $responseInstance       A prepared instance of this class
83          */
84         public final static function createImageResponse (ManageableApplication $appInstance) {
85                 // Get a new instance
86                 $responseInstance = new ImageResponse();
87
88                 // Set the application instance
89                 $responseInstance->setApplicationInstance($appInstance);
90
91                 // Initialize the template engine here
92                 $responseInstance->initTemplateEngine($appInstance);
93
94                 // Return the prepared instance
95                 return $responseInstance;
96         }
97
98         /**
99          * Setter for status
100          *
101          * @param       $status         New response status
102          * @return      void
103          */
104         public final function setResponseStatus ($status) {
105                 $this->responseStatus = (string) $status;
106         }
107
108         /**
109          * Add header element
110          *
111          * @param       $name   Name of header element
112          * @param       $value  Value of header element
113          * @return      void
114          */
115         public final function addHeader ($name, $value) {
116                 $this->responseHeaders[$name] = $value;
117         }
118
119         /**
120          * Reset the header array
121          *
122          * @return      void
123          */
124         public final function resetResponseHeaders () {
125                 $this->responseHeaders = array();
126         }
127
128         /**
129          * "Writes" data to the response body
130          *
131          * @param       $output         Output we shall sent in the HTTP response
132          * @return      void
133          */
134         public function writeToBody ($output) {
135                 $this->responseBody .= $output;
136         }
137
138         /**
139          * Sets the response body to something new
140          *
141          * @param       $output         Output we shall sent in the HTTP response
142          * @return      void
143          */
144         public function setResponseBody ($output) {
145                 $this->responseBody = $output;
146         }
147
148         /**
149          * Flushs the cached HTTP response to the outer world
150          *
151          * @param       $force  Wether we shall force the output or abort if headers are
152          *                                      already sent with an exception
153          * @return      void
154          * @throws      ResponseHeadersAlreadySentException             Thrown if headers are
155          *                                                                                                      already sent
156          */
157         public function flushBuffer ($force=false) {
158                 if ((headers_sent()) && (!$force)) {
159                         // Headers are already sent!
160                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
161                 } elseif (!headers_sent()) {
162                         // Send headers out
163                         header("HTTP/1.1 {$this->responseStatus}");
164
165                         // Used later
166                         $now = gmdate('D, d M Y H:i:s') . ' GMT';
167
168                         // General header for no caching
169                         $this->addHeader('Expired', $now); // rfc2616 - Section 14.21
170                         $this->addHeader('Last-Modified', $now);
171                         $this->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
172                         $this->addHeader('Pragma', 'no-cache'); // HTTP/1.0
173                         $this->addHeader('Content-type', 'image/'.$this->imageInstance->getImageType());
174
175                         // Define the charset to be used
176                         //$this->addHeader('Content-Type:', sprintf("text/html; charset=%s", $this->getConfigInstance()->readConfig('header_charset')));
177
178                         foreach ($this->responseHeaders as $name=>$value) {
179                                 header("{$name}: {$value}");
180                         } // END - foreach
181
182                         // Send cookies out?
183                         if (count($this->cookies) > 0) {
184                                 // Send all cookies
185                                 $cookieString = implode(" ", $this->cookies);
186                                 header("Set-Cookie: {$cookieString}");
187
188                                 // Remove them all
189                                 $this->cookies = array();
190                         } // END - if
191                 }
192
193                 // Are there some error messages?
194                 if (count($this->fatalMessages) == 0) {
195                         // Get image content from cache
196                         $imageContent = $this->imageInstance->getContent();
197                         die($imageContent);
198                 } else {
199                         // Display all error messages
200                         $this->partialStub("Fatal messages are currently unsupported in image response.");
201                 }
202
203                 // Clear response header and body
204                 $this->setResponseBody("");
205                 $this->resetResponseHeaders();
206         }
207
208         /**
209          * Initializes the template engine instance
210          *
211          * @param       $appInstance    An instance of a manageable application
212          * @return      void
213          */
214         public final function initTemplateEngine (ManageableApplication $appInstance) {
215                 // Get config instance
216                 $cfg = $this->getConfigInstance();
217
218                 // Set new template engine
219                 $cfg->setConfigEntry('template_class'         , $cfg->readConfig('image_template_class'));
220                 $cfg->setConfigEntry('raw_template_extension' , ".img");
221                 $cfg->setConfigEntry('code_template_extension', ".itp");
222                 $cfg->setConfigEntry('tpl_base_path'          , "templates/images/");
223                 $cfg->setConfigEntry('code_template_type'     , "image");
224
225                 // Get a prepared instance
226                 $this->setTemplateInstance($this->prepareTemplateInstance($appInstance));
227         }
228
229         /**
230          * Adds a fatal message id to the response. The added messages can then be
231          * processed and outputed to the world
232          *
233          * @param       $messageId      The message id we shall add
234          * @return      void
235          */
236         public final function addFatalMessage ($messageId) {
237                 // Adds the resolved message id to the fatal message list
238                 $this->fatalMessages[] = $this->getApplicationInstance()->getLanguageInstance()->getMessage($messageId);
239         }
240
241         /**
242          * Adds a cookie to the response
243          *
244          * @param       $cookieName             Cookie's name
245          * @param       $cookieValue    Value to store in the cookie
246          * @param       $encrypted              Do some extra encryption on the value
247          * @param       $expires                Timestamp of expiration (default: configured)
248          * @return      void
249          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
250          * @todo        Encryption of cookie data not yet supported.
251          * @todo        Why are these parameters conflicting?
252          * @todo        If the return statement is removed and setcookie() commented out,
253          * @todo        this will send only one cookie out, the first one.
254          */
255         public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = null) {
256                 // Are headers already sent?
257                 if (headers_sent()) {
258                         // Throw an exception here
259                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
260                 } // END - if
261
262                 // Shall we encrypt the cookie?
263                 if ($encrypted === true) {
264                 } // END - if
265
266                 // For slow browsers set the cookie array element first
267                 $_COOKIE[$cookieName] = $cookieValue;
268
269                 // Get all config entries
270                 if (is_null($expires)) {
271                         $expires = (time() + $this->getConfigInstance()->readConfig('cookie_expire'));
272                 } // END - if
273
274                 $path = $this->getConfigInstance()->readConfig('cookie_path');
275                 $domain = $this->getConfigInstance()->readConfig('cookie_domain');
276
277                 setcookie($cookieName, $cookieValue, $expires);
278                 //, $path, $domain, (isset($_SERVER['HTTPS']))
279                 return;
280
281                 // Now construct the full header
282                 $cookieString = $cookieName . "=" . $cookieValue . "; ";
283                 $cookieString .= "expires=" . date("D, d-F-Y H:i:s", $expires) . " GMT";
284                 // $cookieString .= "; path=".$path."; domain=".$domain;
285
286                 // Set the cookie as a header
287                 $this->cookies[$cookieName] = $cookieString;
288         }
289
290         /**
291          * Redirect to a configured URL. The URL can be absolute or relative. In
292          * case of relative URL it will be extended automatically.
293          *
294          * @param       $configEntry    The configuration entry which holds our URL
295          * @return      void
296          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
297          */
298         public function redirectToConfiguredUrl ($configEntry) {
299                 // Is the header not yet sent?
300                 if (headers_sent()) {
301                         // Throw an exception here
302                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
303                 } // END - if
304
305                 // Get the url from config
306                 $url = $this->getConfigInstance()->readConfig($configEntry);
307
308                 // Do we have a "http" in front of the URL?
309                 if (substr(strtolower($url), 0, 4) != "http") {
310                         // Is there a / in front of the relative URL?
311                         if (substr($url, 0, 1) == "/") $url = substr($url, 1);
312
313                         // No, then extend it with our base URL
314                         $url = $this->getConfigInstance()->readConfig('base_url') . "/" . $url;
315                 } // END - if
316
317                 // Add redirect header
318                 $this->addHeader("Location", $url);
319
320                 // Set correct response status
321                 $this->setResponseStatus("301 Moved Permanently");
322
323                 // Clear the body
324                 $this->setResponseBody("");
325
326                 // Flush the result
327                 $this->flushBuffer();
328
329                 // All done here...
330                 exit();
331         }
332
333         /**
334          * Expires the given cookie if it is set
335          *
336          * @param       $cookieName             Cookie to expire
337          * @return      void
338          */
339         public function expireCookie ($cookieName) {
340                 // Is the cookie there?
341                 if (isset($_COOKIE[$cookieName])) {
342                         // Then expire it with 20 minutes past
343                         $this->addCookie($cookieName, "", false, (time() - 1200));
344
345                         // Remove it from array
346                         unset($_COOKIE[$cookieName]);
347                 } // END - if
348         }
349
350         /**
351          * Refreshs a given cookie. This will make the cookie live longer
352          *
353          * @param       $cookieName             Cookie to refresh
354          * @return      void
355          */
356         public function refreshCookie ($cookieName) {
357                 // Only update existing cookies
358                 if (isset($_COOKIE[$cookieName])) {
359                         // Update the cookie
360                         $this->addCookie($cookieName, $_COOKIE[$cookieName], false);
361                 } // END - if
362         }
363
364         /**
365          * Setter for image instanxe
366          *
367          * @param       $imageInstance  An instance of an image
368          * @return      void
369          */
370         public final function setImageInstance (BaseImage $imageInstance) {
371                 $this->imageInstance = $imageInstance;
372         }
373
374         /**
375          * Getter for default command
376          *
377          * @return      $defaultCommand         Default command for this response
378          */
379         public function getDefaultCommand () {
380                 $defaultCommand = $this->getConfigInstance()->readConfig('default_image_command');
381                 return $defaultCommand;
382         }
383 }
384
385 // [EOF]
386 ?>