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