-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
Response.php
282 lines (233 loc) 路 7.05 KB
/
Response.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
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Http;
use Nette;
use Nette\Utils\DateTime;
/**
* HttpResponse class.
*
* @property-read array $headers
*/
final class Response implements IResponse
{
use Nette\SmartObject;
/** The domain in which the cookie will be available */
public string $cookieDomain = '';
/** The path in which the cookie will be available */
public string $cookiePath = '/';
/** Whether the cookie is available only through HTTPS */
public bool $cookieSecure = false;
/** Whether warn on possible problem with data in output buffer */
public bool $warnOnBuffer = true;
/** HTTP response code */
private int $code = self::S200_OK;
public function __construct()
{
if (is_int($code = http_response_code())) {
$this->code = $code;
}
}
/**
* Sets HTTP response code.
* @throws Nette\InvalidArgumentException if code is invalid
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function setCode(int $code, ?string $reason = null): static
{
if ($code < 100 || $code > 599) {
throw new Nette\InvalidArgumentException("Bad HTTP response '$code'.");
}
self::checkHeaders();
$this->code = $code;
$protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1';
$reason ??= self::ReasonPhrases[$code] ?? 'Unknown status';
header("$protocol $code $reason");
return $this;
}
/**
* Returns HTTP response code.
*/
public function getCode(): int
{
return $this->code;
}
/**
* Sends an HTTP header and overwrites previously sent header of the same name.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function setHeader(string $name, ?string $value): static
{
self::checkHeaders();
if ($value === null) {
header_remove($name);
} elseif (strcasecmp($name, 'Content-Length') === 0 && ini_get('zlib.output_compression')) {
// ignore, PHP bug #44164
} else {
header($name . ': ' . $value);
}
return $this;
}
/**
* Sends an HTTP header and doesn't overwrite previously sent header of the same name.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function addHeader(string $name, string $value): static
{
self::checkHeaders();
header($name . ': ' . $value, replace: false);
return $this;
}
/**
* Deletes a previously sent HTTP header.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function deleteHeader(string $name): static
{
self::checkHeaders();
header_remove($name);
return $this;
}
/**
* Sends a Content-type HTTP header.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function setContentType(string $type, ?string $charset = null): static
{
$this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : ''));
return $this;
}
/**
* Response should be downloaded with 'Save as' dialog.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function sendAsFile(string $fileName): static
{
$this->setHeader(
'Content-Disposition',
'attachment; filename="' . str_replace('"', '', $fileName) . '"; '
. "filename*=utf-8''" . rawurlencode($fileName),
);
return $this;
}
/**
* Redirects to another URL. Don't forget to quit the script then.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function redirect(string $url, int $code = self::S302_Found): void
{
$this->setCode($code);
$this->setHeader('Location', $url);
if (preg_match('#^https?:|^\s*+[a-z0-9+.-]*+[^:]#i', $url)) {
$escapedUrl = htmlspecialchars($url, ENT_IGNORE | ENT_QUOTES, 'UTF-8');
echo "<h1>Redirect</h1>\n\n<p><a href=\"$escapedUrl\">Please click here to continue</a>.</p>";
}
}
/**
* Sets the expiration of the HTTP document using the `Cache-Control` and `Expires` headers.
* The parameter is either a time interval (as text) or `null`, which disables caching.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function setExpiration(?string $expire): static
{
$this->setHeader('Pragma', null);
if (!$expire) { // no cache
$this->setHeader('Cache-Control', 's-maxage=0, max-age=0, must-revalidate');
$this->setHeader('Expires', 'Mon, 23 Jan 1978 10:00:00 GMT');
return $this;
}
$expire = DateTime::from($expire);
$this->setHeader('Cache-Control', 'max-age=' . ($expire->format('U') - time()));
$this->setHeader('Expires', Helpers::formatDate($expire));
return $this;
}
/**
* Returns whether headers have already been sent from the server to the browser,
* so it is no longer possible to send headers or change the response code.
*/
public function isSent(): bool
{
return headers_sent();
}
/**
* Returns the sent HTTP header, or `null` if it does not exist. The parameter is case-insensitive.
*/
public function getHeader(string $header): ?string
{
$header .= ':';
$len = strlen($header);
foreach (headers_list() as $item) {
if (strncasecmp($item, $header, $len) === 0) {
return ltrim(substr($item, $len));
}
}
return null;
}
/**
* Returns all sent HTTP headers as associative array.
*/
public function getHeaders(): array
{
$headers = [];
foreach (headers_list() as $header) {
$a = strpos($header, ':');
$headers[substr($header, 0, $a)] = substr($header, $a + 2);
}
return $headers;
}
/**
* Sends a cookie.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function setCookie(
string $name,
string $value,
string|int|\DateTimeInterface|null $expire,
?string $path = null,
?string $domain = null,
?bool $secure = null,
bool $httpOnly = true,
string $sameSite = self::SameSiteLax,
): static
{
self::checkHeaders();
setcookie($name, $value, [
'expires' => $expire ? (int) DateTime::from($expire)->format('U') : 0,
'path' => $path ?? ($domain ? '/' : $this->cookiePath),
'domain' => $domain ?? ($path ? '' : $this->cookieDomain),
'secure' => $secure ?? $this->cookieSecure,
'httponly' => $httpOnly,
'samesite' => $sameSite,
]);
return $this;
}
/**
* Deletes a cookie.
* @throws Nette\InvalidStateException if HTTP headers have been sent
*/
public function deleteCookie(
string $name,
?string $path = null,
?string $domain = null,
?bool $secure = null,
): void
{
$this->setCookie($name, '', 0, $path, $domain, $secure);
}
private function checkHeaders(): void
{
if (PHP_SAPI === 'cli') {
} elseif (headers_sent($file, $line)) {
throw new Nette\InvalidStateException('Cannot send header after HTTP headers have been sent' . ($file ? " (output started at $file:$line)." : '.'));
} elseif (
$this->warnOnBuffer &&
ob_get_length() &&
!array_filter(ob_get_status(true), fn(array $i): bool => !$i['chunk_size'])
) {
trigger_error('Possible problem: you are sending a HTTP header while already having some data in output buffer. Try Tracy\OutputDebugger or send cookies/start session earlier.');
}
}
}