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