& should not be part of URLs...
[core.git] / inc / classes / main / response / image / 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, 2009 Core Developer Team
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 BaseResponse implements Responseable {
28         /**
29          * Instance of the image
30          */
31         private $imageInstance = null;
32
33         /**
34          * Protected constructor
35          *
36          * @return      void
37          */
38         protected function __construct () {
39                 // Call parent constructor
40                 parent::__construct(__CLASS__);
41         }
42
43         /**
44          * Creates an object of this class
45          *
46          * @param       $appInstance            An instance of a manageable application
47          * @return      $responseInstance       A prepared instance of this class
48          */
49         public final static function createImageResponse (ManageableApplication $appInstance) {
50                 // Get a new instance
51                 $responseInstance = new ImageResponse();
52
53                 // Set the application instance
54                 $responseInstance->setApplicationInstance($appInstance);
55
56                 // Initialize the template engine here
57                 $responseInstance->initTemplateEngine($appInstance);
58
59                 // Return the prepared instance
60                 return $responseInstance;
61         }
62
63         /**
64          * Initializes the template engine instance
65          *
66          * @param       $appInstance    An instance of a manageable application
67          * @return      void
68          */
69         public final function initTemplateEngine (ManageableApplication $appInstance) {
70                 // Get config instance
71                 $cfg = $this->getConfigInstance();
72
73                 // Set new template engine
74                 $cfg->setConfigEntry('template_class'         , $cfg->getConfigEntry('image_template_class'));
75                 $cfg->setConfigEntry('raw_template_extension' , '.img');
76                 $cfg->setConfigEntry('code_template_extension', '.xml');
77                 $cfg->setConfigEntry('tpl_base_path'          , 'templates/images/');
78                 $cfg->setConfigEntry('code_template_type'     , 'image');
79
80                 // Get a prepared instance
81                 $this->setTemplateInstance($this->prepareTemplateInstance($appInstance));
82         }
83
84         /**
85          * Adds a cookie to the response
86          *
87          * @param       $cookieName             Cookie's name
88          * @param       $cookieValue    Value to store in the cookie
89          * @param       $encrypted              Do some extra encryption on the value
90          * @param       $expires                Timestamp of expiration (default: configured)
91          * @return      void
92          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
93          * @todo        Encryption of cookie data not yet supported.
94          * @todo        Why are these parameters conflicting?
95          * @todo        If the return statement is removed and setcookie() commented out,
96          * @todo        this will send only one cookie out, the first one.
97          */
98         public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = null) {
99                 // Are headers already sent?
100                 if (headers_sent()) {
101                         // Throw an exception here
102                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
103                 } // END - if
104
105                 // Shall we encrypt the cookie?
106                 if ($encrypted === true) {
107                         // Unsupported at the moment
108                         $this->partialStub('Encryption is unsupported at the moment.');
109                 } // END - if
110
111                 // For slow browsers set the cookie array element first
112                 $_COOKIE[$cookieName] = $cookieValue;
113
114                 // Get all config entries
115                 if (is_null($expires)) {
116                         $expires = (time() + $this->getConfigInstance()->getConfigEntry('cookie_expire'));
117                 } // END - if
118
119                 $path = $this->getConfigInstance()->getConfigEntry('cookie_path');
120                 $domain = $this->getConfigInstance()->getConfigEntry('cookie_domain');
121
122                 setcookie($cookieName, $cookieValue, $expires);
123                 //, $path, $domain, (isset($_SERVER['HTTPS']))
124                 return;
125
126                 // Now construct the full header
127                 $cookieString = $cookieName . '=' . $cookieValue . '; ';
128                 $cookieString .= "expires=" . date("D, d-F-Y H:i:s", $expires) . " GMT";
129                 // $cookieString .= "; path=".$path."; domain=".$domain;
130
131                 // Set the cookie as a header
132                 $this->cookies[$cookieName] = $cookieString;
133         }
134
135         /**
136          * Redirect to a configured URL. The URL can be absolute or relative. In
137          * case of relative URL it will be extended automatically.
138          *
139          * @param       $configEntry    The configuration entry which holds our URL
140          * @return      void
141          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
142          */
143         public function redirectToConfiguredUrl ($configEntry) {
144                 // Is the header not yet sent?
145                 if (headers_sent()) {
146                         // Throw an exception here
147                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
148                 } // END - if
149
150                 // Assign application data
151                 $this->getTemplateInstance()->assignApplicationData($this->getApplicationInstance());
152
153                 // Get the url from config
154                 $url = $this->getConfigInstance()->getConfigEntry($configEntry . "_url");
155
156                 // Compile the URL
157                 $url = $this->getTemplateInstance()->compileRawCode($url);
158
159                 // Do we have a 'http' in front of the URL?
160                 if (substr(strtolower($url), 0, 4) != 'http') {
161                         // Is there a / in front of the relative URL?
162                         if (substr($url, 0, 1) == '/') $url = substr($url, 1);
163
164                         // No, then extend it with our base URL
165                         $url = $this->getConfigInstance()->getConfigEntry('base_url') . '/' . $url;
166                 } // END - if
167
168                 // Add redirect header
169                 $this->addHeader('Location', str_replace('&amp;', '&', $url));
170
171                 // Set correct response status
172                 $this->setResponseStatus('301 Moved Permanently');
173
174                 // Clear the body
175                 $this->setResponseBody('');
176
177                 // Flush the result
178                 $this->flushBuffer();
179
180                 // All done here...
181                 exit();
182         }
183
184         /**
185          * Flushs the cached HTTP response to the outer world
186          *
187          * @param       $force  Wether we shall force the output or abort if headers are
188          *                                      already sent with an exception
189          * @return      void
190          */
191         public function flushBuffer ($force = false) {
192                 // Finish the image
193                 $this->getImageInstance()->finishImage();
194
195                 // Get image content
196                 $content = $this->getImageInstance()->getContent();
197
198                 // Set it as response body
199                 $this->setResponseBody($content);
200
201                 // Set content type
202                 $this->addHeader('Content-type', 'image/' . $this->getImageInstance()->getImageType());
203
204                 // Call parent method
205                 parent::flushBuffer($force);
206         }
207
208         /**
209          * Expires the given cookie if it is set
210          *
211          * @param       $cookieName             Cookie to expire
212          * @return      void
213          */
214         public function expireCookie ($cookieName) {
215                 // Is the cookie there?
216                 if (isset($_COOKIE[$cookieName])) {
217                         // Then expire it with 20 minutes past
218                         $this->addCookie($cookieName, '', false, (time() - 1200));
219
220                         // Remove it from array
221                         unset($_COOKIE[$cookieName]);
222                 } // END - if
223         }
224
225         /**
226          * Refreshs a given cookie. This will make the cookie live longer
227          *
228          * @param       $cookieName             Cookie to refresh
229          * @return      void
230          */
231         public function refreshCookie ($cookieName) {
232                 // Only update existing cookies
233                 if (isset($_COOKIE[$cookieName])) {
234                         // Update the cookie
235                         $this->addCookie($cookieName, $_COOKIE[$cookieName], false);
236                 } // END - if
237         }
238
239         /**
240          * Setter for image instanxe
241          *
242          * @param       $imageInstance  An instance of an image
243          * @return      void
244          */
245         public final function setImageInstance (BaseImage $imageInstance) {
246                 $this->imageInstance = $imageInstance;
247         }
248
249         /**
250          * Getter for image instanxe
251          *
252          * @return      $imageInstance  An instance of an image
253          */
254         public final function getImageInstance () {
255                 return $this->imageInstance;
256         }
257
258         /**
259          * Getter for default command
260          *
261          * @return      $defaultCommand         Default command for this response
262          */
263         public function getDefaultCommand () {
264                 $defaultCommand = $this->getConfigInstance()->getConfigEntry('default_image_command');
265                 return $defaultCommand;
266         }
267 }
268
269 // [EOF]
270 ?>