]> git.mxchange.org Git - core.git/blob - framework/main/classes/response/image/class_ImageResponse.php
Continued:
[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\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
8 use Org\Mxchange\CoreFramework\Image\BaseImage;
9 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
10 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
11 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
12 use Org\Mxchange\CoreFramework\Response\Responseable;
13
14 /**
15  * A class for an image response on an HTTP request
16  *
17  * @author              Roland Haeder <webmaster@shipsimu.org>
18  * @version             0.0.0
19  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
20  * @license             GNU GPL 3.0 or any newer version
21  * @link                http://www.shipsimu.org
22  *
23  * This program is free software: you can redistribute it and/or modify
24  * it under the terms of the GNU General Public License as published by
25  * the Free Software Foundation, either version 3 of the License, or
26  * (at your option) any later version.
27  *
28  * This program is distributed in the hope that it will be useful,
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31  * GNU General Public License for more details.
32  *
33  * You should have received a copy of the GNU General Public License
34  * along with this program. If not, see <http://www.gnu.org/licenses/>.
35  *
36  * The extended headers are taken from phpMyAdmin setup tool, written by
37  * Michal Cihar <michal@cihar.com>, licensed under GNU GPL 2.0.
38  */
39 class ImageResponse extends BaseResponse implements Responseable {
40         /**
41          * Instance of the image
42          */
43         private $imageInstance = NULL;
44
45         /**
46          * Protected constructor
47          *
48          * @return      void
49          */
50         private function __construct () {
51                 // Call parent constructor
52                 parent::__construct(__CLASS__);
53
54                 // Set response type
55                 $this->setResponseType('image');
56         }
57
58         /**
59          * Creates an object of this class
60          *
61          * @return      $responseInstance       A prepared instance of this class
62          */
63         public static final function createImageResponse () {
64                 // Get a new instance
65                 $responseInstance = new ImageResponse();
66
67                 // Return the prepared instance
68                 return $responseInstance;
69         }
70
71         /**
72          * Setter for image instance
73          *
74          * @param       $imageInstance  An instance of an image
75          * @return      void
76          */
77         public final function setImageInstance (BaseImage $imageInstance) {
78                 $this->imageInstance = $imageInstance;
79         }
80
81         /**
82          * Getter for image instance
83          *
84          * @return      $imageInstance  An instance of an image
85          */
86         public final function getImageInstance () {
87                 return $this->imageInstance;
88         }
89
90         /**
91          * Adds a cookie to the response
92          *
93          * @param       $cookieName             Cookie's name
94          * @param       $cookieValue    Value to store in the cookie
95          * @param       $encrypted              Do some extra encryption on the value
96          * @param       $expires                Timestamp of expiration (default: configured)
97          * @return      void
98          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
99          * @todo        Encryption of cookie data not yet supported.
100          * @todo        If the return statement is removed and setcookie() commented out,
101          * @todo        this will send only one cookie out, the first one.
102          */
103         public function addCookie (string $cookieName, $cookieValue, bool $encrypted = FALSE, int $expires = NULL) {
104                 // Are headers already sent?
105                 if (headers_sent()) {
106                         // Throw an exception here
107                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
108                 }
109
110                 // Shall we encrypt the cookie?
111                 if ($encrypted) {
112                         // Unsupported at the moment
113                         DebugMiddleware::getSelfInstance()->partialStub('Encryption is unsupported at the moment.');
114                 }
115
116                 // For slow browsers set the cookie array element first
117                 $_COOKIE[$cookieName] = $cookieValue;
118
119                 // Get all config entries
120                 if (is_null($expires)) {
121                         $expires = (time() + FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_expire'));
122                 }
123
124                 $path = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_path');
125                 $domain = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_domain');
126
127                 setcookie($cookieName, $cookieValue, $expires);
128                 //, $path, $domain, (isset($_SERVER['HTTPS']))
129                 return;
130
131                 // Now construct the full header
132                 $cookieString = $cookieName . '=' . $cookieValue . '; ';
133                 $cookieString .= 'expires=' . date('D, d-F-Y H:i:s', $expires) . ' GMT';
134                 // TODO Why is this not always working? $cookieString .= '; path=' . $path . '; domain=' . $domain;
135
136                 // Set the cookie as a header
137                 $this->cookies[$cookieName] = $cookieString;
138         }
139
140         /**
141          * Redirect to a configured URL. The URL can be absolute or relative. In
142          * case of relative URL it will be extended automatically.
143          *
144          * @param       $configEntry    The configuration entry which holds our URL
145          * @return      void
146          * @throws      ResponseHeadersAlreadySentException             If headers are already sent
147          */
148         public function redirectToConfiguredUrl (string $configEntry) {
149                 // Get application instance
150                 $applicationInstance = ApplicationHelper::getSelfInstance();
151
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                 }
157
158                 // Assign application data
159                 $this->getTemplateInstance()->assignApplicationData($applicationInstance);
160
161                 // Get the url from config
162                 $url = FrameworkBootstrap::getConfigurationInstance()->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 = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('base_url') . '/' . $url;
174                 }
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 (bool $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 (string $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                 }
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 (string $cookieName) {
240                 // Only update existing cookies
241                 if (isset($_COOKIE[$cookieName])) {
242                         // Update the cookie
243                         $this->addCookie($cookieName, $_COOKIE[$cookieName], false);
244                 }
245         }
246
247 }