976fe75e2cef8ba104e1dc520ed17c044b6a9cbf
[core.git] / framework / main / classes / response / image / class_ImageResponse.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Response;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
7 use Org\Mxchange\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          * @return      $responseInstance       A prepared instance of this class
52          */
53         public static final function createImageResponse () {
54                 // Get a new instance
55                 $responseInstance = new ImageResponse();
56
57                 // Init web output instance
58                 $responseInstance->initWebOutputInstance();
59
60                 // Return the prepared instance
61                 return $responseInstance;
62         }
63
64         /**
65          * Initializes the template engine instance
66          *
67          * @param       $applicationInstance    An instance of a manageable application
68          * @return      void
69          */
70         public final function initTemplateEngine (ManageableApplication $applicationInstance) {
71                 // Get config instance
72                 $cfg = $this->getConfigInstance();
73
74                 // Set new template engine
75                 $cfg->setConfigEntry('html_template_class'    , $cfg->getConfigEntry('image_template_class'));
76                 $cfg->setConfigEntry('raw_template_extension' , '.img');
77                 $cfg->setConfigEntry('code_template_extension', '.xml');
78                 $cfg->setConfigEntry('tpl_base_path'          , 'templates/images/');
79                 // @TODO Please fix this
80                 $cfg->setConfigEntry('code_template_type'     , 'image');
81
82                 // Get a prepared instance
83                 $this->setTemplateInstance($this->prepareTemplateInstance($applicationInstance));
84         }
85
86         /**
87          * Adds a cookie to the response
88          *
89          * @param       $cookieName             Cookie's name
90          * @param       $cookieValue    Value to store in the cookie
91          * @param       $encrypted              Do some extra encryption on the value
92          * @param       $expires                Timestamp of expiration (default: configured)
93          * @return      void
94          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
95          * @todo        Encryption of cookie data not yet supported.
96          * @todo        Why are these parameters conflicting?
97          * @todo        If the return statement is removed and setcookie() commented out,
98          * @todo        this will send only one cookie out, the first one.
99          */
100         public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = NULL) {
101                 // Are headers already sent?
102                 if (headers_sent()) {
103                         // Throw an exception here
104                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
105                 } // END - if
106
107                 // Shall we encrypt the cookie?
108                 if ($encrypted === true) {
109                         // Unsupported at the moment
110                         $this->partialStub('Encryption is unsupported at the moment.');
111                 } // END - if
112
113                 // For slow browsers set the cookie array element first
114                 $_COOKIE[$cookieName] = $cookieValue;
115
116                 // Get all config entries
117                 if (is_null($expires)) {
118                         $expires = (time() + $this->getConfigInstance()->getConfigEntry('cookie_expire'));
119                 } // END - if
120
121                 $path = $this->getConfigInstance()->getConfigEntry('cookie_path');
122                 $domain = $this->getConfigInstance()->getConfigEntry('cookie_domain');
123
124                 setcookie($cookieName, $cookieValue, $expires);
125                 //, $path, $domain, (isset($_SERVER['HTTPS']))
126                 return;
127
128                 // Now construct the full header
129                 $cookieString = $cookieName . '=' . $cookieValue . '; ';
130                 $cookieString .= 'expires=' . date('D, d-F-Y H:i:s', $expires) . ' GMT';
131                 // TODO Why is this not always working? $cookieString .= '; path=' . $path . '; domain=' . $domain;
132
133                 // Set the cookie as a header
134                 $this->cookies[$cookieName] = $cookieString;
135         }
136
137         /**
138          * Redirect to a configured URL. The URL can be absolute or relative. In
139          * case of relative URL it will be extended automatically.
140          *
141          * @param       $configEntry    The configuration entry which holds our URL
142          * @return      void
143          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
144          */
145         public function redirectToConfiguredUrl ($configEntry) {
146                 // Get application instance
147                 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
148
149                 // Is the header not yet sent?
150                 if (headers_sent()) {
151                         // Throw an exception here
152                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
153                 } // END - if
154
155                 // Assign application data
156                 $this->getTemplateInstance()->assignApplicationData($applicationInstance());
157
158                 // Get the url from config
159                 $url = $this->getConfigInstance()->getConfigEntry($configEntry . '_url');
160
161                 // Compile the URL
162                 $url = $this->getTemplateInstance()->compileRawCode($url);
163
164                 // Do we have a 'http' in front of the URL?
165                 if (substr(strtolower($url), 0, 4) != 'http') {
166                         // Is there a / in front of the relative URL?
167                         if (substr($url, 0, 1) == '/') $url = substr($url, 1);
168
169                         // No, then extend it with our base URL
170                         $url = $this->getConfigInstance()->getConfigEntry('base_url') . '/' . $url;
171                 } // END - if
172
173                 // Add redirect header
174                 $this->addHeader('Location', str_replace('&amp;', '&', $url));
175
176                 // Set correct response status
177                 $this->setResponseStatus('301 Moved Permanently');
178
179                 // Clear the body
180                 $this->setResponseBody('');
181
182                 // Flush the result
183                 $this->flushBuffer();
184
185                 // All done here...
186                 exit();
187         }
188
189         /**
190          * Flushs the cached HTTP response to the outer world
191          *
192          * @param       $force  Whether we shall force the output or abort if headers are
193          *                                      already sent with an exception
194          * @return      void
195          */
196         public function flushBuffer ($force = false) {
197                 // Finish the image
198                 $this->getImageInstance()->finishImage();
199
200                 // Get image content
201                 $content = $this->getImageInstance()->getContent();
202
203                 // Set it as response body
204                 $this->setResponseBody($content);
205
206                 // Set content type
207                 $this->addHeader('Content-type', 'image/' . $this->getImageInstance()->getImageType());
208
209                 // Call parent method
210                 parent::flushBuffer($force);
211         }
212
213         /**
214          * Expires the given cookie if it is set
215          *
216          * @param       $cookieName             Cookie to expire
217          * @return      void
218          */
219         public function expireCookie ($cookieName) {
220                 // Is the cookie there?
221                 if (isset($_COOKIE[$cookieName])) {
222                         // Then expire it with 20 minutes past
223                         $this->addCookie($cookieName, '', false, (time() - 1200));
224
225                         // Remove it from array
226                         unset($_COOKIE[$cookieName]);
227                 } // END - if
228         }
229
230         /**
231          * Refreshs a given cookie. This will make the cookie live longer
232          *
233          * @param       $cookieName             Cookie to refresh
234          * @return      void
235          */
236         public function refreshCookie ($cookieName) {
237                 // Only update existing cookies
238                 if (isset($_COOKIE[$cookieName])) {
239                         // Update the cookie
240                         $this->addCookie($cookieName, $_COOKIE[$cookieName], false);
241                 } // END - if
242         }
243
244 }