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