]> git.mxchange.org Git - core.git/blob - framework/main/classes/response/class_BaseResponse.php
Continued:
[core.git] / framework / main / classes / response / class_BaseResponse.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\Object\BaseFrameworkSystem;
9 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
10
11 /**
12  * A generic request class
13  *
14  * @author              Roland Haeder <webmaster@shipsimu.org>
15  * @version             0.0.0
16  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
17  * @license             GNU GPL 3.0 or any newer version
18  * @link                http://www.shipsimu.org
19  *
20  * This program is free software: you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation, either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program. If not, see <http://www.gnu.org/licenses/>.
32  *
33  * The extended headers are taken from phpMyAdmin setup tool, written by
34  * Michal Cihar <michal@cihar.com>, licensed under GNU GPL 2.0.
35  */
36 abstract class BaseResponse extends BaseFrameworkSystem {
37         /**
38          * Response status
39          */
40         private $responseStatus = '200 OK';
41
42         /**
43          * Array with all headers
44          */
45         private $responseHeaders = [];
46
47         /**
48          * Cookies we shall sent out
49          */
50         private $cookies = [];
51
52         /**
53          * Body of the response
54          */
55         private $responseBody = '';
56
57         /**
58          * Response type
59          */
60         private $responseType = 'invalid';
61
62         /**
63          * Protected constructor
64          *
65          * @param       $className      Name of the concrete response
66          * @return      void
67          */
68         protected function __construct (string $className) {
69                 // Call parent constructor
70                 parent::__construct($className);
71         }
72
73         /**
74          * Setter for status
75          *
76          * @param       $status         New response status
77          * @return      void
78          */
79         public final function setResponseStatus (string $status) {
80                 $this->responseStatus = $status;
81         }
82
83         /**
84          * Add header element
85          *
86          * @param       $name   Name of header element
87          * @param       $value  Value of header element
88          * @return      void
89          */
90         public final function addHeader (string $name, $value) {
91                 $this->responseHeaders[$name] = $value;
92         }
93
94         /**
95          * Reset the header array
96          *
97          * @return      void
98          */
99         public final function resetResponseHeaders () {
100                 $this->responseHeaders = [];
101         }
102
103         /**
104          * "Writes" data to the response body
105          *
106          * @param       $output         Output we shall sent in the HTTP response
107          * @return      void
108          */
109         public final function writeToBody (string $output) {
110                 $this->responseBody .= $output;
111         }
112
113         /**
114          * Sets the response body to something new
115          *
116          * @param       $output         Output we shall sent in the HTTP response
117          * @return      void
118          */
119         public final function setResponseBody ($output) {
120                 $this->responseBody = $output;
121         }
122
123         /**
124          * Setter for response type
125          *
126          * @param       $responseType   Response type
127          * @return      void
128          */
129         protected final function setResponseType (string $responseType) {
130                 $this->responseType = $responseType;
131         }
132
133         /**
134          * Getter for response type
135          *
136          * @param       $responseType   Response type
137          * @return      void
138          */
139         public final function getResponseType () {
140                 return $this->responseType;
141         }
142
143         /**
144          * Adds a fatal message id to the response. The added messages can then be
145          * processed and outputed to the world
146          *
147          * @param       $messageId      The message id we shall add
148          * @return      void
149          */
150         public final function addFatalMessage (string $messageId) {
151                 // Adds the resolved message id to the fatal message list
152                 $this->addFatalMessagePlain(FrameworkBootstrap::getLanguageInstance()->getMessage($messageId));
153         }
154
155         /**
156          * Adds a plain fatal message id to the response
157          *
158          * @param       $message        The plain message we shall add
159          * @return      void
160          */
161         public final function addFatalMessagePlain (string $message) {
162                 // Adds the resolved message id to the fatal message list
163                 $this->pushValueToGenericArrayKey('fatal_messages', 'generic', 'message', $message);
164         }
165
166         /**
167          * Flushs the cached HTTP response to the outer world
168          *
169          * @param       $force  Whether we shall force the output or abort if headers are
170          *                                      already sent with an exception
171          * @return      void
172          * @throws      ResponseHeadersAlreadySentException             Thrown if headers are
173          *                                                                                                      already sent
174          */
175         public function flushBuffer (bool $force = false) {
176                 // Get application instance
177                 $applicationInstance = ApplicationHelper::getSelfInstance();
178
179                 // Headers already sent?
180                 if ((headers_sent()) && ($force === false)) {
181                         // Headers are already sent!
182                         throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
183                 } elseif (!headers_sent()) {
184                         // Send headers out
185                         header('HTTP/1.1 ' . $this->responseStatus);
186
187                         // Used later
188                         $now = gmdate('D, d M Y H:i:s') . ' GMT';
189
190                         // General header for no caching
191                         $this->addHeader('Expired', $now); // RFC2616 - Section 14.21
192                         $this->addHeader('Last-Modified', $now);
193                         $this->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
194                         $this->addHeader('Pragma', 'no-cache'); // HTTP/1.0
195
196                         // Define the charset to be used
197                         //$this->addHeader('Content-type:', sprintf("text/html; charset=%s", FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('header_charset')));
198
199                         // Send all headers
200                         foreach ($this->responseHeaders as $name => $value) {
201                                 header($name . ': ' . $value);
202                                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('name=' . $name . ',value=' . $value);
203                         }
204
205                         // Send cookies out?
206                         if (count($this->cookies) > 0) {
207                                 // Send all cookies
208                                 $cookieString = implode(' ', $this->cookies);
209                                 header('Set-Cookie: ' . $cookieString);
210
211                                 // Remove them all
212                                 $this->cookies = [];
213                         }
214                 }
215
216                 // Are there some error messages?
217                 if ((!$this->isValidGenericArrayKey('fatal_messages', 'generic', 'message')) || ($this->countGenericArrayElements('fatal_messages', 'generic', 'message') == 0)) {
218                         // Flush the output to the world
219                         $this->getWebOutputInstance()->output($this->responseBody);
220                 } else {
221                         // Display all error messages
222                         $applicationInstance->handleFatalMessages($this->getGenericArrayKey('fatal_messages', 'generic', 'message'));
223
224                         // Send the error messages out to the world
225                         $this->getWebOutputInstance()->output($this->responseBody);
226                 }
227
228                 // Clear response header and body
229                 $this->setResponseBody('');
230                 $this->resetResponseHeaders();
231         }
232
233         /**
234          * "Getter" for default command
235          *
236          * @return      $defaultCommand         Default command for this response
237          */
238         public function determineDefaultCommand () {
239                 // Get application instance
240                 $applicationInstance = ApplicationHelper::getSelfInstance();
241
242                 // Generate config key
243                 $configKey = sprintf('default_%s_%s_command',
244                         $applicationInstance->getAppShortName(),
245                         $this->getResponseType()
246                 );
247
248                 // Get default command response
249                 $defaultCommand = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configKey);
250
251                 // Return it
252                 return $defaultCommand;
253         }
254
255 }