3 * A class for an HTTP response on an HTTP request
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * The extended headers are taken from phpMyAdmin setup tool, written by
25 * Michal Cihar <michal@cihar.com>, licensed under GNU GPL 2.0.
27 class HttpResponse extends BaseFrameworkSystem implements Responseable {
31 private $responseStatus = "200 OK";
34 * Array with all headers
36 private $responseHeaders = array();
39 * Cookies we shall sent out
41 private $cookies = array();
44 * Body of the response
46 private $responseBody = "";
49 * Instance of the template engine
51 private $templateEngine = null;
54 * Fatal resolved messages from filters and so on
56 private $fatalMessages = array();
59 * Protected constructor
63 protected function __construct () {
64 // Call parent constructor
65 parent::__construct(__CLASS__);
67 // Set part description
68 $this->setObjectDescription("HTTP response");
70 // Create unique ID number
71 $this->generateUniqueId();
74 $this->removeNumberFormaters();
75 $this->removeSystemArray();
79 * Creates an object of this class
81 * @param $appInstance An instance of a manageable application
82 * @return $responseInstance A prepared instance of this class
84 public final static function createHttpResponse (ManageableApplication $appInstance) {
86 $responseInstance = new HttpResponse();
88 // Set the application instance
89 $responseInstance->setApplicationInstance($appInstance);
91 // Initialize the template engine here
92 $responseInstance->initTemplateEngine($appInstance);
94 // Return the prepared instance
95 return $responseInstance;
101 * @param $status New response status
104 public final function setResponseStatus ($status) {
105 $this->responseStatus = (string) $status;
111 * @param $name Name of header element
112 * @param $value Value of header element
115 public final function addHeader ($name, $value) {
116 $this->responseHeaders[$name] = $value;
120 * Reset the header array
124 public final function resetResponseHeaders () {
125 $this->responseHeaders = array();
129 * "Writes" data to the response body
131 * @param $output Output we shall sent in the HTTP response
134 public function writeToBody ($output) {
135 $this->responseBody .= $output;
139 * Sets the response body to something new
141 * @param $output Output we shall sent in the HTTP response
144 public function setResponseBody ($output) {
145 $this->responseBody = $output;
149 * Flushs the cached HTTP response to the outer world
151 * @param $force Wether we shall force the output or abort if headers are
152 * already sent with an exception
154 * @throws ResponseHeadersAlreadySentException Thrown if headers are
157 public function flushBuffer ($force=false) {
158 if ((headers_sent()) && (!$force)) {
159 // Headers are already sent!
160 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
161 } elseif (!headers_sent()) {
163 header("HTTP/1.1 {$this->responseStatus}");
166 $now = gmdate('D, d M Y H:i:s') . ' GMT';
168 // General header for no caching
169 $this->addHeader('Expired', $now); // rfc2616 - Section 14.21
170 $this->addHeader('Last-Modified', $now);
171 $this->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
172 $this->addHeader('Pragma', 'no-cache'); // HTTP/1.0
174 // Define the charset to be used
175 //$this->addHeader('Content-Type:', sprintf("text/html; charset=%s", $this->getConfigInstance()->readConfig('header_charset')));
177 foreach ($this->responseHeaders as $name=>$value) {
178 header("{$name}: {$value}");
182 if (count($this->cookies) > 0) {
184 $cookieString = implode(" ", $this->cookies);
185 header("Set-Cookie: {$cookieString}");
188 $this->cookies = array();
192 // Are there some error messages?
193 if (count($this->fatalMessages) == 0) {
194 // Flush the output to the world
195 $this->getWebOutputInstance()->output($this->responseBody);
197 // Display all error messages
198 $this->getApplicationInstance()->handleFatalMessages($this->fatalMessages);
200 // Send the error messages out to the world
201 $this->getWebOutputInstance()->output($this->responseBody);
204 // Clear response header and body
205 $this->setResponseBody("");
206 $this->resetResponseHeaders();
210 * Initializes the template engine instance
212 * @param $appInstance An instance of a manageable application
215 public final function initTemplateEngine (ManageableApplication $appInstance) {
216 $this->templateEngine = $this->prepareTemplateEngine($appInstance);
220 * Getter for the template engine instance
222 * @return $templateEngine An instance of the used template engine
224 public final function getTemplateEngine () {
225 return $this->templateEngine;
229 * Adds a fatal message id to the response. The added messages can then be
230 * processed and outputed to the world
232 * @param $messageId The message id we shall add
235 public final function addFatalMessage ($messageId) {
236 // Adds the resolved message id to the fatal message list
237 $this->fatalMessages[] = $this->getApplicationInstance()->getLanguageInstance()->getMessage($messageId);
241 * Adds a cookie to the response
243 * @param $cookieName Cookie's name
244 * @param $cookieValue Value to store in the cookie
245 * @param $encrypted Do some extra encryption on the value
246 * @param $expires Timestamp of expiration (default: configured)
248 * @throws ResponseHeadersAlreadySentException If headers are already sent
250 public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = null) {
251 // Are headers already sent?
252 if (headers_sent()) {
253 // Throw an exception here
254 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
257 // Shall we encrypt the cookie?
258 if ($encrypted === true) {
259 /* @TODO Encryption of cookie data not yet supported */
262 // For slow browsers set the cookie array element first
263 $_COOKIE[$cookieName] = $cookieValue;
265 // Get all config entries
266 if (is_null($expires)) {
267 $expires = (time() + $this->getConfigInstance()->readConfig('cookie_expire'));
270 $path = $this->getConfigInstance()->readConfig('cookie_path');
271 $domain = $this->getConfigInstance()->readConfig('cookie_domain');
273 setcookie($cookieName, $cookieValue, $expires);
274 /* @TODO Why are these parameters conflicting? */
275 //, $path, $domain, (isset($_SERVER['HTTPS']))
277 /* @TODO This will send only one cookie out, the first one. */
279 // Now construct the full header
280 $cookieString = $cookieName . "=" . $cookieValue . "; ";
281 $cookieString .= "expires=" . date("D, d-F-Y H:i:s", $expires) . " GMT";
282 /* @TODO Why are these parameters conflicting? */
283 // $cookieString .= "; path=".$path."; domain=".$domain;
285 // Set the cookie as a header
286 $this->cookies[$cookieName] = $cookieString;
290 * Redirect to a configured URL. The URL can be absolute or relative. In
291 * case of relative URL it will be extended automatically.
293 * @param $configEntry The configuration entry which holds our URL
295 * @throws ResponseHeadersAlreadySentException If headers are already sent
297 public function redirectToConfiguredUrl ($configEntry) {
298 // Is the header not yet sent?
299 if (headers_sent()) {
300 // Throw an exception here
301 throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
304 // Get the url from config
305 $url = $this->getConfigInstance()->readConfig($configEntry);
307 // Do we have a "http" in front of the URL?
308 if (substr(strtolower($url), 0, 4) != "http") {
309 // Is there a / in front of the relative URL?
310 if (substr($url, 0, 1) == "/") $url = substr($url, 1);
312 // No, then extend it with our base URL
313 $url = $this->getConfigInstance()->readConfig('base_url') . "/" . $url;
316 // Add redirect header
317 $this->addHeader("Location", $url);
319 // Set correct response status
320 $this->setResponseStatus("301 Moved Permanently");
323 $this->setResponseBody("");
326 $this->flushBuffer();
333 * Expires the given cookie if it is set
335 * @param $cookieName Cookie to expire
338 public function expireCookie ($cookieName) {
339 // Is the cookie there?
340 if (isset($_COOKIE[$cookieName])) {
341 // Then expire it with 20 minutes past
342 $this->addCookie($cookieName, "", false, (time() - 1200));
344 // Remove it from array
345 unset($_COOKIE[$cookieName]);