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