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