0b60bb47c9d32af3b16135c9d32da4bdd2f7fc63
[core.git] / inc / main / classes / response / image / class_ImageResponse.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Response;
4
5 // Import framework stuff
6 use CoreFramework\Manager\ManageableApplication;
7
8 /**
9  * A class for an image response on an HTTP request
10  *
11  * @author              Roland Haeder <webmaster@shipsimu.org>
12  * @version             0.0.0
13  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
14  * @license             GNU GPL 3.0 or any newer version
15  * @link                http://www.shipsimu.org
16  *
17  * This program is free software: you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation, either version 3 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program. If not, see <http://www.gnu.org/licenses/>.
29  *
30  * The extended headers are taken from phpMyAdmin setup tool, written by
31  * Michal Cihar <michal@cihar.com>, licensed under GNU GPL 2.0.
32  */
33 class ImageResponse extends BaseResponse implements Responseable {
34         /**
35          * Protected constructor
36          *
37          * @return      void
38          */
39         protected function __construct () {
40                 // Call parent constructor
41                 parent::__construct(__CLASS__);
42
43                 // Set response type
44                 $this->setResponseType('image');
45         }
46
47         /**
48          * Creates an object of this class
49          *
50          * @param       $applicationInstance    An instance of a manageable application
51          * @return      $responseInstance               A prepared instance of this class
52          */
53         public static final function createImageResponse (ManageableApplication $applicationInstance) {
54                 // Get a new instance
55                 $responseInstance = new ImageResponse();
56
57                 // Set the application instance
58                 $responseInstance->setApplicationInstance($applicationInstance);
59
60                 // Initialize the template engine here
61                 $responseInstance->initTemplateEngine($applicationInstance);
62
63                 // Init web output instance
64                 $responseInstance->initWebOutputInstance();
65
66                 // Return the prepared instance
67                 return $responseInstance;
68         }
69
70         /**
71          * Initializes the template engine instance
72          *
73          * @param       $applicationInstance    An instance of a manageable application
74          * @return      void
75          */
76         public final function initTemplateEngine (ManageableApplication $applicationInstance) {
77                 // Get config instance
78                 $cfg = $this->getConfigInstance();
79
80                 // Set new template engine
81                 $cfg->setConfigEntry('html_template_class'    , $cfg->getConfigEntry('image_template_class'));
82                 $cfg->setConfigEntry('raw_template_extension' , '.img');
83                 $cfg->setConfigEntry('code_template_extension', '.xml');
84                 $cfg->setConfigEntry('tpl_base_path'          , 'templates/images/');
85                 // @TODO Please fix this
86                 $cfg->setConfigEntry('code_template_type'     , 'image');
87
88                 // Get a prepared instance
89                 $this->setTemplateInstance($this->prepareTemplateInstance($applicationInstance));
90         }
91
92         /**
93          * Adds a cookie to the response
94          *
95          * @param       $cookieName             Cookie's name
96          * @param       $cookieValue    Value to store in the cookie
97          * @param       $encrypted              Do some extra encryption on the value
98          * @param       $expires                Timestamp of expiration (default: configured)
99          * @return      void
100          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
101          * @todo        Encryption of cookie data not yet supported.
102          * @todo        Why are these parameters conflicting?
103          * @todo        If the return statement is removed and setcookie() commented out,
104          * @todo        this will send only one cookie out, the first one.
105          */
106         public function addCookie ($cookieName, $cookieValue, $encrypted = FALSE, $expires = NULL) {
107                 // Are headers already sent?
108                 if (headers_sent()) {
109                         // Throw an exception here
110                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
111                 } // END - if
112
113                 // Shall we encrypt the cookie?
114                 if ($encrypted === TRUE) {
115                         // Unsupported at the moment
116                         $this->partialStub('Encryption is unsupported at the moment.');
117                 } // END - if
118
119                 // For slow browsers set the cookie array element first
120                 $_COOKIE[$cookieName] = $cookieValue;
121
122                 // Get all config entries
123                 if (is_null($expires)) {
124                         $expires = (time() + $this->getConfigInstance()->getConfigEntry('cookie_expire'));
125                 } // END - if
126
127                 $path = $this->getConfigInstance()->getConfigEntry('cookie_path');
128                 $domain = $this->getConfigInstance()->getConfigEntry('cookie_domain');
129
130                 setcookie($cookieName, $cookieValue, $expires);
131                 //, $path, $domain, (isset($_SERVER['HTTPS']))
132                 return;
133
134                 // Now construct the full header
135                 $cookieString = $cookieName . '=' . $cookieValue . '; ';
136                 $cookieString .= 'expires=' . date('D, d-F-Y H:i:s', $expires) . ' GMT';
137                 // TODO Why is this not always working? $cookieString .= '; path=' . $path . '; domain=' . $domain;
138
139                 // Set the cookie as a header
140                 $this->cookies[$cookieName] = $cookieString;
141         }
142
143         /**
144          * Redirect to a configured URL. The URL can be absolute or relative. In
145          * case of relative URL it will be extended automatically.
146          *
147          * @param       $configEntry    The configuration entry which holds our URL
148          * @return      void
149          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
150          */
151         public function redirectToConfiguredUrl ($configEntry) {
152                 // Is the header not yet sent?
153                 if (headers_sent()) {
154                         // Throw an exception here
155                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
156                 } // END - if
157
158                 // Assign application data
159                 $this->getTemplateInstance()->assignApplicationData($this->getApplicationInstance());
160
161                 // Get the url from config
162                 $url = $this->getConfigInstance()->getConfigEntry($configEntry . '_url');
163
164                 // Compile the URL
165                 $url = $this->getTemplateInstance()->compileRawCode($url);
166
167                 // Do we have a 'http' in front of the URL?
168                 if (substr(strtolower($url), 0, 4) != 'http') {
169                         // Is there a / in front of the relative URL?
170                         if (substr($url, 0, 1) == '/') $url = substr($url, 1);
171
172                         // No, then extend it with our base URL
173                         $url = $this->getConfigInstance()->getConfigEntry('base_url') . '/' . $url;
174                 } // END - if
175
176                 // Add redirect header
177                 $this->addHeader('Location', str_replace('&amp;', '&', $url));
178
179                 // Set correct response status
180                 $this->setResponseStatus('301 Moved Permanently');
181
182                 // Clear the body
183                 $this->setResponseBody('');
184
185                 // Flush the result
186                 $this->flushBuffer();
187
188                 // All done here...
189                 exit();
190         }
191
192         /**
193          * Flushs the cached HTTP response to the outer world
194          *
195          * @param       $force  Whether we shall force the output or abort if headers are
196          *                                      already sent with an exception
197          * @return      void
198          */
199         public function flushBuffer ($force = FALSE) {
200                 // Finish the image
201                 $this->getImageInstance()->finishImage();
202
203                 // Get image content
204                 $content = $this->getImageInstance()->getContent();
205
206                 // Set it as response body
207                 $this->setResponseBody($content);
208
209                 // Set content type
210                 $this->addHeader('Content-type', 'image/' . $this->getImageInstance()->getImageType());
211
212                 // Call parent method
213                 parent::flushBuffer($force);
214         }
215
216         /**
217          * Expires the given cookie if it is set
218          *
219          * @param       $cookieName             Cookie to expire
220          * @return      void
221          */
222         public function expireCookie ($cookieName) {
223                 // Is the cookie there?
224                 if (isset($_COOKIE[$cookieName])) {
225                         // Then expire it with 20 minutes past
226                         $this->addCookie($cookieName, '', FALSE, (time() - 1200));
227
228                         // Remove it from array
229                         unset($_COOKIE[$cookieName]);
230                 } // END - if
231         }
232
233         /**
234          * Refreshs a given cookie. This will make the cookie live longer
235          *
236          * @param       $cookieName             Cookie to refresh
237          * @return      void
238          */
239         public function refreshCookie ($cookieName) {
240                 // Only update existing cookies
241                 if (isset($_COOKIE[$cookieName])) {
242                         // Update the cookie
243                         $this->addCookie($cookieName, $_COOKIE[$cookieName], FALSE);
244                 } // END - if
245         }
246 }
247
248 // [EOF]
249 ?>