/
HTTPResponse.php
470 lines (435 loc) · 12.5 KB
/
HTTPResponse.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
<?php
namespace SilverStripe\Control;
use InvalidArgumentException;
use Monolog\Handler\HandlerInterface;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\View\Requirements;
/**
* Represents a response returned by a controller.
*/
class HTTPResponse
{
use Injectable;
/**
* @var array
*/
protected static $status_codes = [
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
103 => 'Early Hints',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
208 => 'Already Reported',
226 => 'IM Used',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Request Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a Teapot',
421 => 'Misdirected Request',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
451 => 'Unavailable For Legal Reasons',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Unsufficient Storage',
508 => 'Loop Detected',
510 => 'Not Extended',
511 => 'Network Authentication Required',
];
/**
* @var array
*/
protected static $redirect_codes = [
301,
302,
303,
304,
305,
307,
308,
];
/**
* @var string
*/
protected $protocolVersion = '1.0';
/**
* @var int
*/
protected $statusCode = 200;
/**
* @var string
*/
protected $statusDescription = "OK";
/**
* HTTP Headers like "content-type: text/xml"
*
* @see http://en.wikipedia.org/wiki/List_of_HTTP_headers
* @var array
*/
protected $headers = [
"content-type" => "text/html; charset=utf-8",
];
/**
* @var string
*/
protected $body = null;
/**
* Create a new HTTP response
*
* @param string $body The body of the response
* @param int $statusCode The numeric status code - 200, 404, etc
* @param string $statusDescription The text to be given alongside the status code.
* See {@link setStatusCode()} for more information.
* @param string $protocolVersion
*/
public function __construct($body = null, $statusCode = null, $statusDescription = null, $protocolVersion = null)
{
$this->setBody($body);
if ($statusCode) {
$this->setStatusCode($statusCode, $statusDescription);
}
if (!$protocolVersion) {
if (preg_match('/HTTP\/(?<version>\d+(\.\d+)?)/i', $_SERVER['SERVER_PROTOCOL'] ?? '', $matches)) {
$protocolVersion = $matches['version'];
}
}
if ($protocolVersion) {
$this->setProtocolVersion($protocolVersion);
}
}
/**
* The HTTP version used to respond to this request (typically 1.0 or 1.1)
*
* @param string $protocolVersion
*
* @return $this
*/
public function setProtocolVersion($protocolVersion)
{
$this->protocolVersion = $protocolVersion;
return $this;
}
/**
* @param int $code
* @param string $description Optional. See {@link setStatusDescription()}.
* No newlines are allowed in the description.
* If omitted, will default to the standard HTTP description
* for the given $code value (see {@link $status_codes}).
*
* @return $this
*/
public function setStatusCode($code, $description = null)
{
if (isset(self::$status_codes[$code])) {
$this->statusCode = $code;
} else {
throw new InvalidArgumentException("Unrecognised HTTP status code '$code'");
}
if ($description) {
$this->statusDescription = $description;
} else {
$this->statusDescription = self::$status_codes[$code];
}
return $this;
}
/**
* The text to be given alongside the status code ("reason phrase").
* Caution: Will be overwritten by {@link setStatusCode()}.
*
* @param string $description
*
* @return $this
*/
public function setStatusDescription($description)
{
$this->statusDescription = $description;
return $this;
}
/**
* @return string
*/
public function getProtocolVersion()
{
return $this->protocolVersion;
}
/**
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* @return string Description for a HTTP status code
*/
public function getStatusDescription()
{
return str_replace(["\r", "\n"], '', $this->statusDescription ?? '');
}
/**
* Returns true if this HTTP response is in error
*
* @return bool
*/
public function isError()
{
$statusCode = $this->getStatusCode();
return $statusCode && ($statusCode < 200 || $statusCode > 399);
}
/**
* @param string $body
*
* @return $this
*/
public function setBody($body)
{
$this->body = $body ? (string)$body : $body; // Don't type-cast false-ish values, eg null is null not ''
return $this;
}
/**
* @return string
*/
public function getBody()
{
return $this->body;
}
/**
* Add a HTTP header to the response, replacing any header of the same name.
*
* @param string $header Example: "content-type"
* @param string $value Example: "text/xml"
*
* @return $this
*/
public function addHeader($header, $value)
{
$header = strtolower($header ?? '');
$this->headers[$header] = $this->sanitiseHeader($value);
return $this;
}
/**
* Return the HTTP header of the given name.
*
* @param string $header
*
* @return string
*/
public function getHeader($header)
{
$header = strtolower($header ?? '');
if (isset($this->headers[$header])) {
return $this->headers[$header];
}
return null;
}
/**
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Remove an existing HTTP header by its name,
* e.g. "Content-Type".
*
* @param string $header
*
* @return $this
*/
public function removeHeader($header)
{
$header = strtolower($header ?? '');
unset($this->headers[$header]);
return $this;
}
/**
* Sanitise header values to avoid possible XSS vectors
*/
private function sanitiseHeader(string $value): string
{
return preg_replace('/\v/', '', $value);
}
/**
* @param string $dest
* @param int $code
*
* @return $this
*/
public function redirect($dest, $code = 302)
{
if (!in_array($code, self::$redirect_codes)) {
trigger_error("Invalid HTTP redirect code {$code}", E_USER_WARNING);
$code = 302;
}
$this->setStatusCode($code);
$this->addHeader('location', $dest);
return $this;
}
/**
* Send this HTTPResponse to the browser
*/
public function output()
{
// Attach appropriate X-Include-JavaScript and X-Include-CSS headers
if (Director::is_ajax()) {
Requirements::include_in_response($this);
}
if ($this->isRedirect() && headers_sent()) {
$this->htmlRedirect();
} else {
$this->outputHeaders();
$this->outputBody();
}
}
/**
* Generate a browser redirect without setting headers
*/
protected function htmlRedirect()
{
$headersSent = headers_sent($file, $line);
$location = $this->getHeader('location');
$url = Director::absoluteURL($location);
$urlATT = Convert::raw2htmlatt($url);
$urlJS = Convert::raw2js($url);
$title = (Director::isDev() && $headersSent)
? "{$urlATT}... (output started on {$file}, line {$line})"
: "{$urlATT}...";
echo <<<EOT
<p>Redirecting to <a href="{$urlATT}" title="Click this link if your browser does not redirect you">{$title}</a></p>
<meta http-equiv="refresh" content="1; url={$urlATT}" />
<script type="application/javascript">setTimeout(function(){
window.location.href = "{$urlJS}";
}, 50);</script>
EOT
;
}
/**
* Output HTTP headers to the browser
*/
protected function outputHeaders()
{
$headersSent = headers_sent($file, $line);
if (!$headersSent) {
$method = sprintf(
"%s %d %s",
$_SERVER['SERVER_PROTOCOL'],
$this->getStatusCode(),
$this->getStatusDescription()
);
header($method ?? '');
foreach ($this->getHeaders() as $header => $value) {
header("{$header}: {$value}", true, $this->getStatusCode() ?? 0);
}
} elseif ($this->getStatusCode() >= 300) {
// It's critical that these status codes are sent; we need to report a failure if not.
user_error(
sprintf(
"Couldn't set response type to %d because of output on line %s of %s",
$this->getStatusCode(),
$line,
$file
),
E_USER_WARNING
);
}
}
/**
* Output body of this response to the browser
*/
protected function outputBody()
{
// Only show error pages or generic "friendly" errors if the status code signifies
// an error, and the response doesn't have any body yet that might contain
// a more specific error description.
$body = $this->getBody();
if ($this->isError() && empty($body)) {
/** @var HandlerInterface $handler */
$handler = Injector::inst()->get(HandlerInterface::class);
$formatter = $handler->getFormatter();
echo $formatter->format([
'code' => $this->statusCode,
]);
} else {
echo $this->body;
}
}
/**
* Returns true if this response is "finished", that is, no more script execution should be done.
* Specifically, returns true if a redirect has already been requested
*
* @return bool
*/
public function isFinished()
{
return $this->isRedirect() || $this->isError();
}
/**
* Determine if this response is a redirect
*
* @return bool
*/
public function isRedirect()
{
return in_array($this->getStatusCode(), self::$redirect_codes);
}
/**
* The HTTP response represented as a raw string
*
* @return string
*/
public function __toString()
{
$headers = [];
foreach ($this->getHeaders() as $header => $values) {
foreach ((array)$values as $value) {
$headers[] = sprintf('%s: %s', $header, $value);
}
}
return
sprintf('HTTP/%s %s %s', $this->getProtocolVersion(), $this->getStatusCode(), $this->getStatusDescription()) . "\r\n" .
implode("\r\n", $headers) . "\r\n" . "\r\n" .
$this->getBody();
}
}