1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license https://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\web; |
9
|
|
|
|
10
|
|
|
use Yii; |
11
|
|
|
use yii\base\InvalidArgumentException; |
12
|
|
|
use yii\base\InvalidConfigException; |
13
|
|
|
use yii\base\InvalidRouteException; |
14
|
|
|
use yii\helpers\FileHelper; |
15
|
|
|
use yii\helpers\Inflector; |
16
|
|
|
use yii\helpers\StringHelper; |
17
|
|
|
use yii\helpers\Url; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* The web Response class represents an HTTP response. |
21
|
|
|
* |
22
|
|
|
* It holds the [[headers]], [[cookies]] and [[content]] that is to be sent to the client. |
23
|
|
|
* It also controls the HTTP [[statusCode|status code]]. |
24
|
|
|
* |
25
|
|
|
* Response is configured as an application component in [[\yii\web\Application]] by default. |
26
|
|
|
* You can access that instance via `Yii::$app->response`. |
27
|
|
|
* |
28
|
|
|
* You can modify its configuration by adding an array to your application config under `components` |
29
|
|
|
* as it is shown in the following example: |
30
|
|
|
* |
31
|
|
|
* ```php |
32
|
|
|
* 'response' => [ |
33
|
|
|
* 'format' => yii\web\Response::FORMAT_JSON, |
34
|
|
|
* 'charset' => 'UTF-8', |
35
|
|
|
* // ... |
36
|
|
|
* ] |
37
|
|
|
* ``` |
38
|
|
|
* |
39
|
|
|
* For more details and usage information on Response, see the [guide article on responses](guide:runtime-responses). |
40
|
|
|
* |
41
|
|
|
* @property-read CookieCollection $cookies The cookie collection. |
42
|
|
|
* @property-write string $downloadHeaders The attachment file name. |
43
|
|
|
* @property-read HeaderCollection $headers The header collection. |
44
|
|
|
* @property-read bool $isClientError Whether this response indicates a client error. |
45
|
|
|
* @property-read bool $isEmpty Whether this response is empty. |
46
|
|
|
* @property-read bool $isForbidden Whether this response indicates the current request is forbidden. |
47
|
|
|
* @property-read bool $isInformational Whether this response is informational. |
48
|
|
|
* @property-read bool $isInvalid Whether this response has a valid [[statusCode]]. |
49
|
|
|
* @property-read bool $isNotFound Whether this response indicates the currently requested resource is not |
50
|
|
|
* found. |
51
|
|
|
* @property-read bool $isOk Whether this response is OK. |
52
|
|
|
* @property-read bool $isRedirection Whether this response is a redirection. |
53
|
|
|
* @property-read bool $isServerError Whether this response indicates a server error. |
54
|
|
|
* @property-read bool $isSuccessful Whether this response is successful. |
55
|
|
|
* @property int $statusCode The HTTP status code to send with the response. |
56
|
|
|
* @property-write \Throwable $statusCodeByException The exception object. |
57
|
|
|
* |
58
|
|
|
* @author Qiang Xue <[email protected]> |
59
|
|
|
* @author Carsten Brandt <[email protected]> |
60
|
|
|
* @since 2.0 |
61
|
|
|
*/ |
62
|
|
|
class Response extends \yii\base\Response |
63
|
|
|
{ |
64
|
|
|
/** |
65
|
|
|
* @event \yii\base\Event an event that is triggered at the beginning of [[send()]]. |
66
|
|
|
*/ |
67
|
|
|
const EVENT_BEFORE_SEND = 'beforeSend'; |
68
|
|
|
/** |
69
|
|
|
* @event \yii\base\Event an event that is triggered at the end of [[send()]]. |
70
|
|
|
*/ |
71
|
|
|
const EVENT_AFTER_SEND = 'afterSend'; |
72
|
|
|
/** |
73
|
|
|
* @event \yii\base\Event an event that is triggered right after [[prepare()]] is called in [[send()]]. |
74
|
|
|
* You may respond to this event to filter the response content before it is sent to the client. |
75
|
|
|
*/ |
76
|
|
|
const EVENT_AFTER_PREPARE = 'afterPrepare'; |
77
|
|
|
const FORMAT_RAW = 'raw'; |
78
|
|
|
const FORMAT_HTML = 'html'; |
79
|
|
|
const FORMAT_JSON = 'json'; |
80
|
|
|
const FORMAT_JSONP = 'jsonp'; |
81
|
|
|
const FORMAT_XML = 'xml'; |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @var string the response format. This determines how to convert [[data]] into [[content]] |
85
|
|
|
* when the latter is not set. The value of this property must be one of the keys declared in the [[formatters]] array. |
86
|
|
|
* By default, the following formats are supported: |
87
|
|
|
* |
88
|
|
|
* - [[FORMAT_RAW]]: the data will be treated as the response content without any conversion. |
89
|
|
|
* No extra HTTP header will be added. |
90
|
|
|
* - [[FORMAT_HTML]]: the data will be treated as the response content without any conversion. |
91
|
|
|
* The "Content-Type" header will set as "text/html". |
92
|
|
|
* - [[FORMAT_JSON]]: the data will be converted into JSON format, and the "Content-Type" |
93
|
|
|
* header will be set as "application/json". |
94
|
|
|
* - [[FORMAT_JSONP]]: the data will be converted into JSONP format, and the "Content-Type" |
95
|
|
|
* header will be set as "text/javascript". Note that in this case `$data` must be an array |
96
|
|
|
* with "data" and "callback" elements. The former refers to the actual data to be sent, |
97
|
|
|
* while the latter refers to the name of the JavaScript callback. |
98
|
|
|
* - [[FORMAT_XML]]: the data will be converted into XML format. Please refer to [[XmlResponseFormatter]] |
99
|
|
|
* for more details. |
100
|
|
|
* |
101
|
|
|
* You may customize the formatting process or support additional formats by configuring [[formatters]]. |
102
|
|
|
* @see formatters |
103
|
|
|
*/ |
104
|
|
|
public $format = self::FORMAT_HTML; |
105
|
|
|
/** |
106
|
|
|
* @var string the MIME type (e.g. `application/json`) from the request ACCEPT header chosen for this response. |
107
|
|
|
* This property is mainly set by [[\yii\filters\ContentNegotiator]]. |
108
|
|
|
*/ |
109
|
|
|
public $acceptMimeType; |
110
|
|
|
/** |
111
|
|
|
* @var array the parameters (e.g. `['q' => 1, 'version' => '1.0']`) associated with the [[acceptMimeType|chosen MIME type]]. |
112
|
|
|
* This is a list of name-value pairs associated with [[acceptMimeType]] from the ACCEPT HTTP header. |
113
|
|
|
* This property is mainly set by [[\yii\filters\ContentNegotiator]]. |
114
|
|
|
*/ |
115
|
|
|
public $acceptParams = []; |
116
|
|
|
/** |
117
|
|
|
* @var array the formatters for converting data into the response content of the specified [[format]]. |
118
|
|
|
* The array keys are the format names, and the array values are the corresponding configurations |
119
|
|
|
* for creating the formatter objects. |
120
|
|
|
* @see format |
121
|
|
|
* @see defaultFormatters |
122
|
|
|
*/ |
123
|
|
|
public $formatters = []; |
124
|
|
|
/** |
125
|
|
|
* @var mixed the original response data. When this is not null, it will be converted into [[content]] |
126
|
|
|
* according to [[format]] when the response is being sent out. |
127
|
|
|
* @see content |
128
|
|
|
*/ |
129
|
|
|
public $data; |
130
|
|
|
/** |
131
|
|
|
* @var string|null the response content. When [[data]] is not null, it will be converted into [[content]] |
132
|
|
|
* according to [[format]] when the response is being sent out. |
133
|
|
|
* @see data |
134
|
|
|
*/ |
135
|
|
|
public $content; |
136
|
|
|
/** |
137
|
|
|
* @var resource|array|callable the stream to be sent. This can be a stream handle or an array of stream handle, |
138
|
|
|
* the begin position and the end position. Alternatively it can be set to a callable, which returns |
139
|
|
|
* (or [yields](https://www.php.net/manual/en/language.generators.syntax.php)) an array of strings that should |
140
|
|
|
* be echoed and flushed out one by one. |
141
|
|
|
* |
142
|
|
|
* Note that when this property is set, the [[data]] and [[content]] properties will be ignored by [[send()]]. |
143
|
|
|
*/ |
144
|
|
|
public $stream; |
145
|
|
|
/** |
146
|
|
|
* @var string|null the charset of the text response. If not set, it will use |
147
|
|
|
* the value of [[Application::charset]]. |
148
|
|
|
*/ |
149
|
|
|
public $charset; |
150
|
|
|
/** |
151
|
|
|
* @var string the HTTP status description that comes together with the status code. |
152
|
|
|
* @see httpStatuses |
153
|
|
|
*/ |
154
|
|
|
public $statusText = 'OK'; |
155
|
|
|
/** |
156
|
|
|
* @var string|null the version of the HTTP protocol to use. If not set, it will be determined via `$_SERVER['SERVER_PROTOCOL']`, |
157
|
|
|
* or '1.1' if that is not available. |
158
|
|
|
*/ |
159
|
|
|
public $version; |
160
|
|
|
/** |
161
|
|
|
* @var bool whether the response has been sent. If this is true, calling [[send()]] will do nothing. |
162
|
|
|
*/ |
163
|
|
|
public $isSent = false; |
164
|
|
|
/** |
165
|
|
|
* @var array list of HTTP status codes and the corresponding texts |
166
|
|
|
*/ |
167
|
|
|
public static $httpStatuses = [ |
168
|
|
|
100 => 'Continue', |
169
|
|
|
101 => 'Switching Protocols', |
170
|
|
|
102 => 'Processing', |
171
|
|
|
118 => 'Connection timed out', |
172
|
|
|
200 => 'OK', |
173
|
|
|
201 => 'Created', |
174
|
|
|
202 => 'Accepted', |
175
|
|
|
203 => 'Non-Authoritative', |
176
|
|
|
204 => 'No Content', |
177
|
|
|
205 => 'Reset Content', |
178
|
|
|
206 => 'Partial Content', |
179
|
|
|
207 => 'Multi-Status', |
180
|
|
|
208 => 'Already Reported', |
181
|
|
|
210 => 'Content Different', |
182
|
|
|
226 => 'IM Used', |
183
|
|
|
300 => 'Multiple Choices', |
184
|
|
|
301 => 'Moved Permanently', |
185
|
|
|
302 => 'Found', |
186
|
|
|
303 => 'See Other', |
187
|
|
|
304 => 'Not Modified', |
188
|
|
|
305 => 'Use Proxy', |
189
|
|
|
306 => 'Reserved', |
190
|
|
|
307 => 'Temporary Redirect', |
191
|
|
|
308 => 'Permanent Redirect', |
192
|
|
|
310 => 'Too many Redirect', |
193
|
|
|
400 => 'Bad Request', |
194
|
|
|
401 => 'Unauthorized', |
195
|
|
|
402 => 'Payment Required', |
196
|
|
|
403 => 'Forbidden', |
197
|
|
|
404 => 'Not Found', |
198
|
|
|
405 => 'Method Not Allowed', |
199
|
|
|
406 => 'Not Acceptable', |
200
|
|
|
407 => 'Proxy Authentication Required', |
201
|
|
|
408 => 'Request Time-out', |
202
|
|
|
409 => 'Conflict', |
203
|
|
|
410 => 'Gone', |
204
|
|
|
411 => 'Length Required', |
205
|
|
|
412 => 'Precondition Failed', |
206
|
|
|
413 => 'Request Entity Too Large', |
207
|
|
|
414 => 'Request-URI Too Long', |
208
|
|
|
415 => 'Unsupported Media Type', |
209
|
|
|
416 => 'Requested range unsatisfiable', |
210
|
|
|
417 => 'Expectation failed', |
211
|
|
|
418 => 'I\'m a teapot', |
212
|
|
|
421 => 'Misdirected Request', |
213
|
|
|
422 => 'Unprocessable entity', |
214
|
|
|
423 => 'Locked', |
215
|
|
|
424 => 'Method failure', |
216
|
|
|
425 => 'Unordered Collection', |
217
|
|
|
426 => 'Upgrade Required', |
218
|
|
|
428 => 'Precondition Required', |
219
|
|
|
429 => 'Too Many Requests', |
220
|
|
|
431 => 'Request Header Fields Too Large', |
221
|
|
|
449 => 'Retry With', |
222
|
|
|
450 => 'Blocked by Windows Parental Controls', |
223
|
|
|
451 => 'Unavailable For Legal Reasons', |
224
|
|
|
500 => 'Internal Server Error', |
225
|
|
|
501 => 'Not Implemented', |
226
|
|
|
502 => 'Bad Gateway or Proxy Error', |
227
|
|
|
503 => 'Service Unavailable', |
228
|
|
|
504 => 'Gateway Time-out', |
229
|
|
|
505 => 'HTTP Version not supported', |
230
|
|
|
507 => 'Insufficient storage', |
231
|
|
|
508 => 'Loop Detected', |
232
|
|
|
509 => 'Bandwidth Limit Exceeded', |
233
|
|
|
510 => 'Not Extended', |
234
|
|
|
511 => 'Network Authentication Required', |
235
|
|
|
]; |
236
|
|
|
|
237
|
|
|
/** |
238
|
|
|
* @var int the HTTP status code to send with the response. |
239
|
|
|
*/ |
240
|
|
|
private $_statusCode = 200; |
241
|
|
|
/** |
242
|
|
|
* @var HeaderCollection |
243
|
|
|
*/ |
244
|
|
|
private $_headers; |
245
|
|
|
|
246
|
|
|
|
247
|
|
|
/** |
248
|
|
|
* Initializes this component. |
249
|
|
|
*/ |
250
|
355 |
|
public function init() |
251
|
|
|
{ |
252
|
355 |
|
if ($this->version === null) { |
253
|
355 |
|
if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.0') { |
254
|
|
|
$this->version = '1.0'; |
255
|
|
|
} else { |
256
|
355 |
|
$this->version = '1.1'; |
257
|
|
|
} |
258
|
|
|
} |
259
|
355 |
|
if ($this->charset === null) { |
260
|
355 |
|
$this->charset = Yii::$app->charset; |
261
|
|
|
} |
262
|
355 |
|
$this->formatters = array_merge($this->defaultFormatters(), $this->formatters); |
263
|
355 |
|
} |
264
|
|
|
|
265
|
|
|
/** |
266
|
|
|
* @return int the HTTP status code to send with the response. |
267
|
|
|
*/ |
268
|
65 |
|
public function getStatusCode() |
269
|
|
|
{ |
270
|
65 |
|
return $this->_statusCode; |
271
|
|
|
} |
272
|
|
|
|
273
|
|
|
/** |
274
|
|
|
* Sets the response status code. |
275
|
|
|
* This method will set the corresponding status text if `$text` is null. |
276
|
|
|
* @param int $value the status code |
277
|
|
|
* @param string|null $text the status text. If not set, it will be set automatically based on the status code. |
278
|
|
|
* @throws InvalidArgumentException if the status code is invalid. |
279
|
|
|
* @return $this the response object itself |
280
|
|
|
*/ |
281
|
56 |
|
public function setStatusCode($value, $text = null) |
282
|
|
|
{ |
283
|
56 |
|
if ($value === null) { |
|
|
|
|
284
|
|
|
$value = 200; |
285
|
|
|
} |
286
|
56 |
|
$this->_statusCode = (int) $value; |
287
|
56 |
|
if ($this->getIsInvalid()) { |
288
|
|
|
throw new InvalidArgumentException("The HTTP status code is invalid: $value"); |
289
|
|
|
} |
290
|
56 |
|
if ($text === null) { |
291
|
52 |
|
$this->statusText = isset(static::$httpStatuses[$this->_statusCode]) ? static::$httpStatuses[$this->_statusCode] : ''; |
292
|
|
|
} else { |
293
|
4 |
|
$this->statusText = $text; |
294
|
|
|
} |
295
|
|
|
|
296
|
56 |
|
return $this; |
297
|
|
|
} |
298
|
|
|
|
299
|
|
|
/** |
300
|
|
|
* Sets the response status code based on the exception. |
301
|
|
|
* @param \Throwable $e the exception object. |
302
|
|
|
* @throws InvalidArgumentException if the status code is invalid. |
303
|
|
|
* @return $this the response object itself |
304
|
|
|
* @since 2.0.12 |
305
|
|
|
*/ |
306
|
18 |
|
public function setStatusCodeByException($e) |
307
|
|
|
{ |
308
|
18 |
|
if ($e instanceof HttpException) { |
309
|
10 |
|
$this->setStatusCode($e->statusCode); |
310
|
|
|
} else { |
311
|
8 |
|
$this->setStatusCode(500); |
312
|
|
|
} |
313
|
|
|
|
314
|
18 |
|
return $this; |
315
|
|
|
} |
316
|
|
|
|
317
|
|
|
/** |
318
|
|
|
* Returns the header collection. |
319
|
|
|
* The header collection contains the currently registered HTTP headers. |
320
|
|
|
* @return HeaderCollection the header collection |
321
|
|
|
*/ |
322
|
131 |
|
public function getHeaders() |
323
|
|
|
{ |
324
|
131 |
|
if ($this->_headers === null) { |
325
|
131 |
|
$this->_headers = new HeaderCollection(); |
326
|
|
|
} |
327
|
|
|
|
328
|
131 |
|
return $this->_headers; |
329
|
|
|
} |
330
|
|
|
|
331
|
|
|
/** |
332
|
|
|
* Sends the response to the client. |
333
|
|
|
*/ |
334
|
38 |
|
public function send() |
335
|
|
|
{ |
336
|
38 |
|
if ($this->isSent) { |
337
|
3 |
|
return; |
338
|
|
|
} |
339
|
38 |
|
$this->trigger(self::EVENT_BEFORE_SEND); |
340
|
38 |
|
$this->prepare(); |
341
|
38 |
|
$this->trigger(self::EVENT_AFTER_PREPARE); |
342
|
38 |
|
$this->sendHeaders(); |
343
|
38 |
|
$this->sendContent(); |
344
|
38 |
|
$this->trigger(self::EVENT_AFTER_SEND); |
345
|
38 |
|
$this->isSent = true; |
346
|
38 |
|
} |
347
|
|
|
|
348
|
|
|
/** |
349
|
|
|
* Clears the headers, cookies, content, status code of the response. |
350
|
|
|
*/ |
351
|
|
|
public function clear() |
352
|
|
|
{ |
353
|
|
|
$this->_headers = null; |
354
|
|
|
$this->_cookies = null; |
355
|
|
|
$this->_statusCode = 200; |
356
|
|
|
$this->statusText = 'OK'; |
357
|
|
|
$this->data = null; |
358
|
|
|
$this->stream = null; |
359
|
|
|
$this->content = null; |
360
|
|
|
$this->isSent = false; |
361
|
|
|
} |
362
|
|
|
|
363
|
|
|
/** |
364
|
|
|
* Sends the response headers to the client. |
365
|
|
|
*/ |
366
|
38 |
|
protected function sendHeaders() |
367
|
|
|
{ |
368
|
38 |
|
if (headers_sent($file, $line)) { |
369
|
|
|
throw new HeadersAlreadySentException($file, $line); |
370
|
|
|
} |
371
|
38 |
|
if ($this->_headers) { |
372
|
33 |
|
foreach ($this->getHeaders() as $name => $values) { |
373
|
33 |
|
$name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name))); |
374
|
|
|
// set replace for first occurrence of header but false afterwards to allow multiple |
375
|
33 |
|
$replace = true; |
376
|
33 |
|
foreach ($values as $value) { |
377
|
33 |
|
header("$name: $value", $replace); |
378
|
33 |
|
$replace = false; |
379
|
|
|
} |
380
|
|
|
} |
381
|
|
|
} |
382
|
38 |
|
$statusCode = $this->getStatusCode(); |
383
|
38 |
|
header("HTTP/{$this->version} {$statusCode} {$this->statusText}"); |
384
|
38 |
|
$this->sendCookies(); |
385
|
38 |
|
} |
386
|
|
|
|
387
|
|
|
/** |
388
|
|
|
* Sends the cookies to the client. |
389
|
|
|
*/ |
390
|
38 |
|
protected function sendCookies() |
391
|
|
|
{ |
392
|
38 |
|
if ($this->_cookies === null) { |
393
|
31 |
|
return; |
394
|
|
|
} |
395
|
7 |
|
$request = Yii::$app->getRequest(); |
396
|
7 |
|
if ($request->enableCookieValidation) { |
|
|
|
|
397
|
7 |
|
if ($request->cookieValidationKey == '') { |
|
|
|
|
398
|
|
|
throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.'); |
399
|
|
|
} |
400
|
7 |
|
$validationKey = $request->cookieValidationKey; |
401
|
|
|
} |
402
|
7 |
|
foreach ($this->getCookies() as $cookie) { |
403
|
7 |
|
$value = $cookie->value; |
404
|
7 |
|
$expire = $cookie->expire; |
405
|
7 |
|
if (is_string($expire)) { |
406
|
1 |
|
$expire = strtotime($expire); |
407
|
|
|
} |
408
|
7 |
|
if ($expire === null || $expire === false) { |
409
|
|
|
$expire = 0; |
410
|
|
|
} |
411
|
7 |
|
if ($expire != 1 && isset($validationKey)) { |
412
|
7 |
|
$value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey); |
413
|
|
|
} |
414
|
7 |
|
if (PHP_VERSION_ID >= 70300) { |
415
|
7 |
|
setcookie($cookie->name, $value, [ |
416
|
7 |
|
'expires' => $expire, |
417
|
7 |
|
'path' => $cookie->path, |
418
|
7 |
|
'domain' => $cookie->domain, |
419
|
7 |
|
'secure' => $cookie->secure, |
420
|
7 |
|
'httpOnly' => $cookie->httpOnly, |
421
|
7 |
|
'sameSite' => !empty($cookie->sameSite) ? $cookie->sameSite : null, |
422
|
|
|
]); |
423
|
|
|
} else { |
424
|
|
|
// Work around for setting sameSite cookie prior PHP 7.3 |
425
|
|
|
// https://stackoverflow.com/questions/39750906/php-setcookie-samesite-strict/46971326#46971326 |
426
|
|
|
$cookiePath = $cookie->path; |
427
|
|
|
if (!is_null($cookie->sameSite)) { |
428
|
|
|
$cookiePath .= '; samesite=' . $cookie->sameSite; |
429
|
|
|
} |
430
|
|
|
setcookie($cookie->name, $value, $expire, $cookiePath, $cookie->domain, $cookie->secure, $cookie->httpOnly); |
431
|
|
|
} |
432
|
|
|
} |
433
|
7 |
|
} |
434
|
|
|
|
435
|
|
|
/** |
436
|
|
|
* Sends the response content to the client. |
437
|
|
|
*/ |
438
|
38 |
|
protected function sendContent() |
439
|
|
|
{ |
440
|
38 |
|
if ($this->stream === null) { |
441
|
34 |
|
echo $this->content; |
442
|
|
|
|
443
|
34 |
|
return; |
444
|
|
|
} |
445
|
|
|
|
446
|
|
|
// Try to reset time limit for big files |
447
|
4 |
|
if (!function_exists('set_time_limit') || !@set_time_limit(0)) { |
448
|
|
|
Yii::warning('set_time_limit() is not available', __METHOD__); |
449
|
|
|
} |
450
|
|
|
|
451
|
4 |
|
if (is_callable($this->stream)) { |
452
|
|
|
$data = call_user_func($this->stream); |
|
|
|
|
453
|
|
|
foreach ($data as $datum) { |
454
|
|
|
echo $datum; |
455
|
|
|
flush(); |
456
|
|
|
} |
457
|
|
|
return; |
458
|
|
|
} |
459
|
|
|
|
460
|
4 |
|
$chunkSize = 8 * 1024 * 1024; // 8MB per chunk |
461
|
|
|
|
462
|
4 |
|
if (is_array($this->stream)) { |
463
|
4 |
|
list($handle, $begin, $end) = $this->stream; |
464
|
|
|
|
465
|
|
|
// only seek if stream is seekable |
466
|
4 |
|
if ($this->isSeekable($handle)) { |
467
|
3 |
|
fseek($handle, $begin); |
468
|
|
|
} |
469
|
|
|
|
470
|
4 |
|
while (!feof($handle) && ($pos = ftell($handle)) <= $end) { |
471
|
3 |
|
if ($pos + $chunkSize > $end) { |
472
|
3 |
|
$chunkSize = $end - $pos + 1; |
473
|
|
|
} |
474
|
3 |
|
echo fread($handle, $chunkSize); |
475
|
3 |
|
flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit. |
476
|
|
|
} |
477
|
4 |
|
fclose($handle); |
478
|
|
|
} else { |
479
|
|
|
while (!feof($this->stream)) { |
|
|
|
|
480
|
|
|
echo fread($this->stream, $chunkSize); |
|
|
|
|
481
|
|
|
flush(); |
482
|
|
|
} |
483
|
|
|
fclose($this->stream); |
|
|
|
|
484
|
|
|
} |
485
|
4 |
|
} |
486
|
|
|
|
487
|
|
|
/** |
488
|
|
|
* Sends a file to the browser. |
489
|
|
|
* |
490
|
|
|
* Note that this method only prepares the response for file sending. The file is not sent |
491
|
|
|
* until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action. |
492
|
|
|
* |
493
|
|
|
* The following is an example implementation of a controller action that allows requesting files from a directory |
494
|
|
|
* that is not accessible from web: |
495
|
|
|
* |
496
|
|
|
* ```php |
497
|
|
|
* public function actionFile($filename) |
498
|
|
|
* { |
499
|
|
|
* $storagePath = Yii::getAlias('@app/files'); |
500
|
|
|
* |
501
|
|
|
* // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files) |
502
|
|
|
* if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) { |
503
|
|
|
* throw new \yii\web\NotFoundHttpException('The file does not exists.'); |
504
|
|
|
* } |
505
|
|
|
* return Yii::$app->response->sendFile("$storagePath/$filename", $filename); |
506
|
|
|
* } |
507
|
|
|
* ``` |
508
|
|
|
* |
509
|
|
|
* @param string $filePath the path of the file to be sent. |
510
|
|
|
* @param string|null $attachmentName the file name shown to the user. If null, it will be determined from `$filePath`. |
511
|
|
|
* @param array $options additional options for sending the file. The following options are supported: |
512
|
|
|
* |
513
|
|
|
* - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath` |
514
|
|
|
* - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false, |
515
|
|
|
* meaning a download dialog will pop up. |
516
|
|
|
* |
517
|
|
|
* @return $this the response object itself |
518
|
|
|
* @see sendContentAsFile() |
519
|
|
|
* @see sendStreamAsFile() |
520
|
|
|
* @see xSendFile() |
521
|
|
|
*/ |
522
|
10 |
|
public function sendFile($filePath, $attachmentName = null, $options = []) |
523
|
|
|
{ |
524
|
10 |
|
if (!isset($options['mimeType'])) { |
525
|
10 |
|
$options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath); |
526
|
|
|
} |
527
|
10 |
|
if ($attachmentName === null) { |
528
|
9 |
|
$attachmentName = basename($filePath); |
529
|
|
|
} |
530
|
10 |
|
$handle = fopen($filePath, 'rb'); |
531
|
10 |
|
$this->sendStreamAsFile($handle, $attachmentName, $options); |
532
|
|
|
|
533
|
6 |
|
return $this; |
534
|
|
|
} |
535
|
|
|
|
536
|
|
|
/** |
537
|
|
|
* Sends the specified content as a file to the browser. |
538
|
|
|
* |
539
|
|
|
* Note that this method only prepares the response for file sending. The file is not sent |
540
|
|
|
* until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action. |
541
|
|
|
* |
542
|
|
|
* @param string $content the content to be sent. The existing [[content]] will be discarded. |
543
|
|
|
* @param string $attachmentName the file name shown to the user. |
544
|
|
|
* @param array $options additional options for sending the file. The following options are supported: |
545
|
|
|
* |
546
|
|
|
* - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'. |
547
|
|
|
* - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false, |
548
|
|
|
* meaning a download dialog will pop up. |
549
|
|
|
* |
550
|
|
|
* @return $this the response object itself |
551
|
|
|
* @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable |
552
|
|
|
* @see sendFile() for an example implementation. |
553
|
|
|
*/ |
554
|
1 |
|
public function sendContentAsFile($content, $attachmentName, $options = []) |
555
|
|
|
{ |
556
|
1 |
|
$headers = $this->getHeaders(); |
557
|
|
|
|
558
|
1 |
|
$contentLength = StringHelper::byteLength($content); |
559
|
1 |
|
$range = $this->getHttpRange($contentLength); |
560
|
|
|
|
561
|
1 |
|
if ($range === false) { |
|
|
|
|
562
|
|
|
$headers->set('Content-Range', "bytes */$contentLength"); |
563
|
|
|
throw new RangeNotSatisfiableHttpException(); |
564
|
|
|
} |
565
|
|
|
|
566
|
1 |
|
list($begin, $end) = $range; |
567
|
1 |
|
if ($begin != 0 || $end != $contentLength - 1) { |
568
|
|
|
$this->setStatusCode(206); |
569
|
|
|
$headers->set('Content-Range', "bytes $begin-$end/$contentLength"); |
570
|
|
|
$this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1); |
571
|
|
|
} else { |
572
|
1 |
|
$this->setStatusCode(200); |
573
|
1 |
|
$this->content = $content; |
574
|
|
|
} |
575
|
|
|
|
576
|
1 |
|
$mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream'; |
577
|
1 |
|
$this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1); |
578
|
|
|
|
579
|
1 |
|
$this->format = self::FORMAT_RAW; |
580
|
|
|
|
581
|
1 |
|
return $this; |
582
|
|
|
} |
583
|
|
|
|
584
|
|
|
/** |
585
|
|
|
* Sends the specified stream as a file to the browser. |
586
|
|
|
* |
587
|
|
|
* Note that this method only prepares the response for file sending. The file is not sent |
588
|
|
|
* until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action. |
589
|
|
|
* |
590
|
|
|
* @param resource $handle the handle of the stream to be sent. |
591
|
|
|
* @param string $attachmentName the file name shown to the user. |
592
|
|
|
* @param array $options additional options for sending the file. The following options are supported: |
593
|
|
|
* |
594
|
|
|
* - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'. |
595
|
|
|
* - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false, |
596
|
|
|
* meaning a download dialog will pop up. |
597
|
|
|
* - `fileSize`: the size of the content to stream this is useful when size of the content is known |
598
|
|
|
* and the content is not seekable. Defaults to content size using `ftell()`. |
599
|
|
|
* This option is available since version 2.0.4. |
600
|
|
|
* |
601
|
|
|
* @return $this the response object itself |
602
|
|
|
* @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable |
603
|
|
|
* @see sendFile() for an example implementation. |
604
|
|
|
*/ |
605
|
11 |
|
public function sendStreamAsFile($handle, $attachmentName, $options = []) |
606
|
|
|
{ |
607
|
11 |
|
$headers = $this->getHeaders(); |
608
|
11 |
|
if (isset($options['fileSize'])) { |
609
|
|
|
$fileSize = $options['fileSize']; |
610
|
|
|
} else { |
611
|
11 |
|
if ($this->isSeekable($handle)) { |
612
|
10 |
|
fseek($handle, 0, SEEK_END); |
613
|
10 |
|
$fileSize = ftell($handle); |
614
|
|
|
} else { |
615
|
1 |
|
$fileSize = 0; |
616
|
|
|
} |
617
|
|
|
} |
618
|
|
|
|
619
|
11 |
|
$range = $this->getHttpRange($fileSize); |
620
|
11 |
|
if ($range === false) { |
|
|
|
|
621
|
4 |
|
$headers->set('Content-Range', "bytes */$fileSize"); |
622
|
4 |
|
throw new RangeNotSatisfiableHttpException(); |
623
|
|
|
} |
624
|
|
|
|
625
|
7 |
|
list($begin, $end) = $range; |
626
|
7 |
|
if ($begin != 0 || $end != $fileSize - 1) { |
627
|
3 |
|
$this->setStatusCode(206); |
628
|
3 |
|
$headers->set('Content-Range', "bytes $begin-$end/$fileSize"); |
629
|
|
|
} else { |
630
|
4 |
|
$this->setStatusCode(200); |
631
|
|
|
} |
632
|
|
|
|
633
|
7 |
|
$mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream'; |
634
|
7 |
|
$this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1); |
635
|
|
|
|
636
|
7 |
|
$this->format = self::FORMAT_RAW; |
637
|
7 |
|
$this->stream = [$handle, $begin, $end]; |
638
|
|
|
|
639
|
7 |
|
return $this; |
640
|
|
|
} |
641
|
|
|
|
642
|
|
|
/** |
643
|
|
|
* Sets a default set of HTTP headers for file downloading purpose. |
644
|
|
|
* @param string $attachmentName the attachment file name |
645
|
|
|
* @param string|null $mimeType the MIME type for the response. If null, `Content-Type` header will NOT be set. |
646
|
|
|
* @param bool $inline whether the browser should open the file within the browser window. Defaults to false, |
647
|
|
|
* meaning a download dialog will pop up. |
648
|
|
|
* @param int|null $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set. |
649
|
|
|
* @return $this the response object itself |
650
|
|
|
*/ |
651
|
8 |
|
public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null) |
652
|
|
|
{ |
653
|
8 |
|
$headers = $this->getHeaders(); |
654
|
|
|
|
655
|
8 |
|
$disposition = $inline ? 'inline' : 'attachment'; |
656
|
8 |
|
$headers->setDefault('Pragma', 'public') |
657
|
8 |
|
->setDefault('Accept-Ranges', 'bytes') |
658
|
8 |
|
->setDefault('Expires', '0') |
659
|
8 |
|
->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') |
660
|
8 |
|
->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName)); |
661
|
|
|
|
662
|
8 |
|
if ($mimeType !== null) { |
663
|
8 |
|
$headers->setDefault('Content-Type', $mimeType); |
664
|
|
|
} |
665
|
|
|
|
666
|
8 |
|
if ($contentLength !== null) { |
667
|
8 |
|
$headers->setDefault('Content-Length', $contentLength); |
668
|
|
|
} |
669
|
|
|
|
670
|
8 |
|
return $this; |
671
|
|
|
} |
672
|
|
|
|
673
|
|
|
/** |
674
|
|
|
* Determines the HTTP range given in the request. |
675
|
|
|
* @param int $fileSize the size of the file that will be used to validate the requested HTTP range. |
676
|
|
|
* @return array|bool the range (begin, end), or false if the range request is invalid. |
677
|
|
|
*/ |
678
|
12 |
|
protected function getHttpRange($fileSize) |
679
|
|
|
{ |
680
|
12 |
|
$rangeHeader = Yii::$app->getRequest()->getHeaders()->get('Range', '-'); |
|
|
|
|
681
|
12 |
|
if ($rangeHeader === '-') { |
682
|
5 |
|
return [0, $fileSize - 1]; |
683
|
|
|
} |
684
|
7 |
|
if (!preg_match('/^bytes=(\d*)-(\d*)$/', $rangeHeader, $matches)) { |
|
|
|
|
685
|
1 |
|
return false; |
686
|
|
|
} |
687
|
6 |
|
if ($matches[1] === '') { |
688
|
2 |
|
$start = $fileSize - $matches[2]; |
689
|
2 |
|
$end = $fileSize - 1; |
690
|
4 |
|
} elseif ($matches[2] !== '') { |
691
|
2 |
|
$start = $matches[1]; |
692
|
2 |
|
$end = $matches[2]; |
693
|
2 |
|
if ($end >= $fileSize) { |
694
|
2 |
|
$end = $fileSize - 1; |
695
|
|
|
} |
696
|
|
|
} else { |
697
|
2 |
|
$start = $matches[1]; |
698
|
2 |
|
$end = $fileSize - 1; |
699
|
|
|
} |
700
|
6 |
|
if ($start < 0 || $start > $end) { |
701
|
3 |
|
return false; |
702
|
|
|
} |
703
|
|
|
|
704
|
3 |
|
return [$start, $end]; |
705
|
|
|
} |
706
|
|
|
|
707
|
|
|
/** |
708
|
|
|
* Sends existing file to a browser as a download using x-sendfile. |
709
|
|
|
* |
710
|
|
|
* X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver |
711
|
|
|
* that in turn processes the request, this way eliminating the need to perform tasks like reading the file |
712
|
|
|
* and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great |
713
|
|
|
* increase in performance as the web application is allowed to terminate earlier while the webserver is |
714
|
|
|
* handling the request. |
715
|
|
|
* |
716
|
|
|
* The request is sent to the server through a special non-standard HTTP-header. |
717
|
|
|
* When the web server encounters the presence of such header it will discard all output and send the file |
718
|
|
|
* specified by that header using web server internals including all optimizations like caching-headers. |
719
|
|
|
* |
720
|
|
|
* As this header directive is non-standard different directives exists for different web servers applications: |
721
|
|
|
* |
722
|
|
|
* - Apache: [X-Sendfile](https://tn123.org/mod_xsendfile/) |
723
|
|
|
* - Lighttpd v1.4: [X-LIGHTTPD-send-file](https://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file) |
724
|
|
|
* - Lighttpd v1.5: [X-Sendfile](https://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file) |
725
|
|
|
* - Nginx: [X-Accel-Redirect](https://www.nginx.com/resources/wiki/XSendfile) |
726
|
|
|
* - Cherokee: [X-Sendfile and X-Accel-Redirect](https://cherokee-project.com/doc/other_goodies.html#x-sendfile) |
727
|
|
|
* |
728
|
|
|
* So for this method to work the X-SENDFILE option/module should be enabled by the web server and |
729
|
|
|
* a proper xHeader should be sent. |
730
|
|
|
* |
731
|
|
|
* **Note** |
732
|
|
|
* |
733
|
|
|
* This option allows to download files that are not under web folders, and even files that are otherwise protected |
734
|
|
|
* (deny from all) like `.htaccess`. |
735
|
|
|
* |
736
|
|
|
* **Side effects** |
737
|
|
|
* |
738
|
|
|
* If this option is disabled by the web server, when this method is called a download configuration dialog |
739
|
|
|
* will open but the downloaded file will have 0 bytes. |
740
|
|
|
* |
741
|
|
|
* **Known issues** |
742
|
|
|
* |
743
|
|
|
* There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show |
744
|
|
|
* an error message like this: "Internet Explorer was not able to open this Internet site. The requested site |
745
|
|
|
* is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header. |
746
|
|
|
* |
747
|
|
|
* **Example** |
748
|
|
|
* |
749
|
|
|
* ```php |
750
|
|
|
* Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg'); |
751
|
|
|
* ``` |
752
|
|
|
* |
753
|
|
|
* @param string $filePath file name with full path |
754
|
|
|
* @param string|null $attachmentName file name shown to the user. If null, it will be determined from `$filePath`. |
755
|
|
|
* @param array $options additional options for sending the file. The following options are supported: |
756
|
|
|
* |
757
|
|
|
* - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath` |
758
|
|
|
* - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false, |
759
|
|
|
* meaning a download dialog will pop up. |
760
|
|
|
* - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile". |
761
|
|
|
* |
762
|
|
|
* @return $this the response object itself |
763
|
|
|
* @see sendFile() |
764
|
|
|
*/ |
765
|
|
|
public function xSendFile($filePath, $attachmentName = null, $options = []) |
766
|
|
|
{ |
767
|
|
|
if ($attachmentName === null) { |
768
|
|
|
$attachmentName = basename($filePath); |
769
|
|
|
} |
770
|
|
|
if (isset($options['mimeType'])) { |
771
|
|
|
$mimeType = $options['mimeType']; |
772
|
|
|
} elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) { |
773
|
|
|
$mimeType = 'application/octet-stream'; |
774
|
|
|
} |
775
|
|
|
if (isset($options['xHeader'])) { |
776
|
|
|
$xHeader = $options['xHeader']; |
777
|
|
|
} else { |
778
|
|
|
$xHeader = 'X-Sendfile'; |
779
|
|
|
} |
780
|
|
|
|
781
|
|
|
$disposition = empty($options['inline']) ? 'attachment' : 'inline'; |
782
|
|
|
$this->getHeaders() |
783
|
|
|
->setDefault($xHeader, $filePath) |
784
|
|
|
->setDefault('Content-Type', $mimeType) |
785
|
|
|
->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName)); |
786
|
|
|
|
787
|
|
|
$this->format = self::FORMAT_RAW; |
788
|
|
|
|
789
|
|
|
return $this; |
790
|
|
|
} |
791
|
|
|
|
792
|
|
|
/** |
793
|
|
|
* Returns Content-Disposition header value that is safe to use with both old and new browsers. |
794
|
|
|
* |
795
|
|
|
* Fallback name: |
796
|
|
|
* |
797
|
|
|
* - Causes issues if contains non-ASCII characters with codes less than 32 or more than 126. |
798
|
|
|
* - Causes issues if contains urlencoded characters (starting with `%`) or `%` character. Some browsers interpret |
799
|
|
|
* `filename="X"` as urlencoded name, some don't. |
800
|
|
|
* - Causes issues if contains path separator characters such as `\` or `/`. |
801
|
|
|
* - Since value is wrapped with `"`, it should be escaped as `\"`. |
802
|
|
|
* - Since input could contain non-ASCII characters, fallback is obtained by transliteration. |
803
|
|
|
* |
804
|
|
|
* UTF name: |
805
|
|
|
* |
806
|
|
|
* - Causes issues if contains path separator characters such as `\` or `/`. |
807
|
|
|
* - Should be urlencoded since headers are ASCII-only. |
808
|
|
|
* - Could be omitted if it exactly matches fallback name. |
809
|
|
|
* |
810
|
|
|
* @param string $disposition |
811
|
|
|
* @param string $attachmentName |
812
|
|
|
* @return string |
813
|
|
|
* |
814
|
|
|
* @since 2.0.10 |
815
|
|
|
*/ |
816
|
8 |
|
protected function getDispositionHeaderValue($disposition, $attachmentName) |
817
|
|
|
{ |
818
|
8 |
|
$fallbackName = str_replace( |
819
|
8 |
|
['%', '/', '\\', '"', "\x7F"], |
820
|
8 |
|
['_', '_', '_', '\\"', '_'], |
821
|
8 |
|
Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE) |
822
|
|
|
); |
823
|
8 |
|
$utfName = rawurlencode(str_replace(['%', '/', '\\'], '', $attachmentName)); |
824
|
|
|
|
825
|
8 |
|
$dispositionHeader = "{$disposition}; filename=\"{$fallbackName}\""; |
826
|
8 |
|
if ($utfName !== $fallbackName) { |
827
|
1 |
|
$dispositionHeader .= "; filename*=utf-8''{$utfName}"; |
828
|
|
|
} |
829
|
|
|
|
830
|
8 |
|
return $dispositionHeader; |
831
|
|
|
} |
832
|
|
|
|
833
|
|
|
/** |
834
|
|
|
* Redirects the browser to the specified URL. |
835
|
|
|
* |
836
|
|
|
* This method adds a "Location" header to the current response. Note that it does not send out |
837
|
|
|
* the header until [[send()]] is called. In a controller action you may use this method as follows: |
838
|
|
|
* |
839
|
|
|
* ```php |
840
|
|
|
* return Yii::$app->getResponse()->redirect($url); |
841
|
|
|
* ``` |
842
|
|
|
* |
843
|
|
|
* In other places, if you want to send out the "Location" header immediately, you should use |
844
|
|
|
* the following code: |
845
|
|
|
* |
846
|
|
|
* ```php |
847
|
|
|
* Yii::$app->getResponse()->redirect($url)->send(); |
848
|
|
|
* return; |
849
|
|
|
* ``` |
850
|
|
|
* |
851
|
|
|
* In AJAX mode, this normally will not work as expected unless there are some |
852
|
|
|
* client-side JavaScript code handling the redirection. To help achieve this goal, |
853
|
|
|
* this method will send out a "X-Redirect" header instead of "Location". |
854
|
|
|
* |
855
|
|
|
* If you use the "yii" JavaScript module, it will handle the AJAX redirection as |
856
|
|
|
* described above. Otherwise, you should write the following JavaScript code to |
857
|
|
|
* handle the redirection: |
858
|
|
|
* |
859
|
|
|
* ```javascript |
860
|
|
|
* $document.ajaxComplete(function (event, xhr, settings) { |
861
|
|
|
* var url = xhr && xhr.getResponseHeader('X-Redirect'); |
862
|
|
|
* if (url) { |
863
|
|
|
* window.location = url; |
864
|
|
|
* } |
865
|
|
|
* }); |
866
|
|
|
* ``` |
867
|
|
|
* |
868
|
|
|
* @param string|array $url the URL to be redirected to. This can be in one of the following formats: |
869
|
|
|
* |
870
|
|
|
* - a string representing a URL (e.g. "https://example.com") |
871
|
|
|
* - a string representing a URL alias (e.g. "@example.com") |
872
|
|
|
* - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`). |
873
|
|
|
* Note that the route is with respect to the whole application, instead of relative to a controller or module. |
874
|
|
|
* [[Url::to()]] will be used to convert the array into a URL. |
875
|
|
|
* |
876
|
|
|
* Any relative URL that starts with a single forward slash "/" will be converted |
877
|
|
|
* into an absolute one by prepending it with the host info of the current request. |
878
|
|
|
* |
879
|
|
|
* @param int $statusCode the HTTP status code. Defaults to 302. |
880
|
|
|
* See <https://tools.ietf.org/html/rfc2616#section-10> |
881
|
|
|
* for details about HTTP status code |
882
|
|
|
* @param bool $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true, |
883
|
|
|
* meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser |
884
|
|
|
* to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as |
885
|
|
|
* an AJAX/PJAX response, may NOT cause browser redirection. |
886
|
|
|
* Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent. |
887
|
|
|
* @return $this the response object itself |
888
|
|
|
*/ |
889
|
10 |
|
public function redirect($url, $statusCode = 302, $checkAjax = true) |
890
|
|
|
{ |
891
|
10 |
|
if (is_array($url) && isset($url[0])) { |
892
|
|
|
// ensure the route is absolute |
893
|
8 |
|
$url[0] = '/' . ltrim($url[0], '/'); |
894
|
|
|
} |
895
|
10 |
|
$request = Yii::$app->getRequest(); |
896
|
10 |
|
$normalizedUrl = Url::to($url); |
897
|
10 |
|
if ($normalizedUrl !== null) { |
|
|
|
|
898
|
10 |
|
if (preg_match('/\n/', $normalizedUrl)) { |
899
|
1 |
|
throw new InvalidRouteException('Route with new line character detected "' . $normalizedUrl . '".'); |
900
|
|
|
} |
901
|
9 |
|
if (strncmp($normalizedUrl, '/', 1) === 0 && strncmp($normalizedUrl, '//', 2) !== 0) { |
902
|
9 |
|
$normalizedUrl = $request->getHostInfo() . $normalizedUrl; |
|
|
|
|
903
|
|
|
} |
904
|
|
|
} |
905
|
|
|
|
906
|
9 |
|
if ($checkAjax && $request->getIsAjax()) { |
|
|
|
|
907
|
|
|
if ( |
908
|
7 |
|
in_array($statusCode, [301, 302]) |
909
|
7 |
|
&& preg_match('/Trident\/|MSIE /', (string)$request->userAgent) |
|
|
|
|
910
|
|
|
) { |
911
|
3 |
|
$statusCode = 200; |
912
|
|
|
} |
913
|
7 |
|
if ($request->getIsPjax()) { |
|
|
|
|
914
|
6 |
|
$this->getHeaders()->set('X-Pjax-Url', $normalizedUrl); |
915
|
|
|
} else { |
916
|
7 |
|
$this->getHeaders()->set('X-Redirect', $normalizedUrl); |
917
|
|
|
} |
918
|
|
|
} else { |
919
|
3 |
|
$this->getHeaders()->set('Location', $normalizedUrl); |
920
|
|
|
} |
921
|
|
|
|
922
|
9 |
|
$this->setStatusCode($statusCode); |
923
|
|
|
|
924
|
9 |
|
return $this; |
925
|
|
|
} |
926
|
|
|
|
927
|
|
|
/** |
928
|
|
|
* Refreshes the current page. |
929
|
|
|
* The effect of this method call is the same as the user pressing the refresh button of his browser |
930
|
|
|
* (without re-posting data). |
931
|
|
|
* |
932
|
|
|
* In a controller action you may use this method like this: |
933
|
|
|
* |
934
|
|
|
* ```php |
935
|
|
|
* return Yii::$app->getResponse()->refresh(); |
936
|
|
|
* ``` |
937
|
|
|
* |
938
|
|
|
* @param string $anchor the anchor that should be appended to the redirection URL. |
939
|
|
|
* Defaults to empty. Make sure the anchor starts with '#' if you want to specify it. |
940
|
|
|
* @return Response the response object itself |
941
|
|
|
*/ |
942
|
|
|
public function refresh($anchor = '') |
943
|
|
|
{ |
944
|
|
|
return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor); |
|
|
|
|
945
|
|
|
} |
946
|
|
|
|
947
|
|
|
private $_cookies; |
948
|
|
|
|
949
|
|
|
/** |
950
|
|
|
* Returns the cookie collection. |
951
|
|
|
* |
952
|
|
|
* Through the returned cookie collection, you add or remove cookies as follows, |
953
|
|
|
* |
954
|
|
|
* ```php |
955
|
|
|
* // add a cookie |
956
|
|
|
* $response->cookies->add(new Cookie([ |
957
|
|
|
* 'name' => $name, |
958
|
|
|
* 'value' => $value, |
959
|
|
|
* ]); |
960
|
|
|
* |
961
|
|
|
* // remove a cookie |
962
|
|
|
* $response->cookies->remove('name'); |
963
|
|
|
* // alternatively |
964
|
|
|
* unset($response->cookies['name']); |
965
|
|
|
* ``` |
966
|
|
|
* |
967
|
|
|
* @return CookieCollection the cookie collection. |
968
|
|
|
*/ |
969
|
89 |
|
public function getCookies() |
970
|
|
|
{ |
971
|
89 |
|
if ($this->_cookies === null) { |
972
|
89 |
|
$this->_cookies = new CookieCollection(); |
973
|
|
|
} |
974
|
|
|
|
975
|
89 |
|
return $this->_cookies; |
976
|
|
|
} |
977
|
|
|
|
978
|
|
|
/** |
979
|
|
|
* @return bool whether this response has a valid [[statusCode]]. |
980
|
|
|
*/ |
981
|
56 |
|
public function getIsInvalid() |
982
|
|
|
{ |
983
|
56 |
|
return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600; |
984
|
|
|
} |
985
|
|
|
|
986
|
|
|
/** |
987
|
|
|
* @return bool whether this response is informational |
988
|
|
|
*/ |
989
|
|
|
public function getIsInformational() |
990
|
|
|
{ |
991
|
|
|
return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200; |
992
|
|
|
} |
993
|
|
|
|
994
|
|
|
/** |
995
|
|
|
* @return bool whether this response is successful |
996
|
|
|
*/ |
997
|
|
|
public function getIsSuccessful() |
998
|
|
|
{ |
999
|
|
|
return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300; |
1000
|
|
|
} |
1001
|
|
|
|
1002
|
|
|
/** |
1003
|
|
|
* @return bool whether this response is a redirection |
1004
|
|
|
*/ |
1005
|
1 |
|
public function getIsRedirection() |
1006
|
|
|
{ |
1007
|
1 |
|
return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400; |
1008
|
|
|
} |
1009
|
|
|
|
1010
|
|
|
/** |
1011
|
|
|
* @return bool whether this response indicates a client error |
1012
|
|
|
*/ |
1013
|
|
|
public function getIsClientError() |
1014
|
|
|
{ |
1015
|
|
|
return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500; |
1016
|
|
|
} |
1017
|
|
|
|
1018
|
|
|
/** |
1019
|
|
|
* @return bool whether this response indicates a server error |
1020
|
|
|
*/ |
1021
|
|
|
public function getIsServerError() |
1022
|
|
|
{ |
1023
|
|
|
return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600; |
1024
|
|
|
} |
1025
|
|
|
|
1026
|
|
|
/** |
1027
|
|
|
* @return bool whether this response is OK |
1028
|
|
|
*/ |
1029
|
|
|
public function getIsOk() |
1030
|
|
|
{ |
1031
|
|
|
return $this->getStatusCode() == 200; |
1032
|
|
|
} |
1033
|
|
|
|
1034
|
|
|
/** |
1035
|
|
|
* @return bool whether this response indicates the current request is forbidden |
1036
|
|
|
*/ |
1037
|
|
|
public function getIsForbidden() |
1038
|
|
|
{ |
1039
|
|
|
return $this->getStatusCode() == 403; |
1040
|
|
|
} |
1041
|
|
|
|
1042
|
|
|
/** |
1043
|
|
|
* @return bool whether this response indicates the currently requested resource is not found |
1044
|
|
|
*/ |
1045
|
|
|
public function getIsNotFound() |
1046
|
|
|
{ |
1047
|
|
|
return $this->getStatusCode() == 404; |
1048
|
|
|
} |
1049
|
|
|
|
1050
|
|
|
/** |
1051
|
|
|
* @return bool whether this response is empty |
1052
|
|
|
*/ |
1053
|
|
|
public function getIsEmpty() |
1054
|
|
|
{ |
1055
|
|
|
return in_array($this->getStatusCode(), [201, 204, 304]); |
1056
|
|
|
} |
1057
|
|
|
|
1058
|
|
|
/** |
1059
|
|
|
* @return array the formatters that are supported by default |
1060
|
|
|
*/ |
1061
|
355 |
|
protected function defaultFormatters() |
1062
|
|
|
{ |
1063
|
|
|
return [ |
1064
|
355 |
|
self::FORMAT_HTML => [ |
1065
|
355 |
|
'class' => 'yii\web\HtmlResponseFormatter', |
1066
|
|
|
], |
1067
|
355 |
|
self::FORMAT_XML => [ |
1068
|
|
|
'class' => 'yii\web\XmlResponseFormatter', |
1069
|
|
|
], |
1070
|
355 |
|
self::FORMAT_JSON => [ |
1071
|
|
|
'class' => 'yii\web\JsonResponseFormatter', |
1072
|
|
|
], |
1073
|
355 |
|
self::FORMAT_JSONP => [ |
1074
|
|
|
'class' => 'yii\web\JsonResponseFormatter', |
1075
|
|
|
'useJsonp' => true, |
1076
|
|
|
], |
1077
|
|
|
]; |
1078
|
|
|
} |
1079
|
|
|
|
1080
|
|
|
/** |
1081
|
|
|
* Prepares for sending the response. |
1082
|
|
|
* The default implementation will convert [[data]] into [[content]] and set headers accordingly. |
1083
|
|
|
* @throws InvalidConfigException if the formatter for the specified format is invalid or [[format]] is not supported |
1084
|
|
|
* |
1085
|
|
|
* @see https://tools.ietf.org/html/rfc7231#page-53 |
1086
|
|
|
* @see https://tools.ietf.org/html/rfc7232#page-18 |
1087
|
|
|
*/ |
1088
|
38 |
|
protected function prepare() |
1089
|
|
|
{ |
1090
|
38 |
|
if (in_array($this->getStatusCode(), [204, 304])) { |
1091
|
|
|
// A 204/304 response cannot contain a message body according to rfc7231/rfc7232 |
1092
|
6 |
|
$this->content = ''; |
1093
|
6 |
|
$this->stream = null; |
1094
|
6 |
|
return; |
1095
|
|
|
} |
1096
|
|
|
|
1097
|
32 |
|
if ($this->stream !== null) { |
1098
|
4 |
|
return; |
1099
|
|
|
} |
1100
|
|
|
|
1101
|
28 |
|
if (isset($this->formatters[$this->format])) { |
1102
|
26 |
|
$formatter = $this->formatters[$this->format]; |
1103
|
26 |
|
if (!is_object($formatter)) { |
1104
|
26 |
|
$this->formatters[$this->format] = $formatter = Yii::createObject($formatter); |
1105
|
|
|
} |
1106
|
26 |
|
if ($formatter instanceof ResponseFormatterInterface) { |
1107
|
26 |
|
$formatter->format($this); |
1108
|
|
|
} else { |
1109
|
26 |
|
throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface."); |
1110
|
|
|
} |
1111
|
2 |
|
} elseif ($this->format === self::FORMAT_RAW) { |
1112
|
2 |
|
if ($this->data !== null) { |
1113
|
2 |
|
$this->content = $this->data; |
1114
|
|
|
} |
1115
|
|
|
} else { |
1116
|
|
|
throw new InvalidConfigException("Unsupported response format: {$this->format}"); |
1117
|
|
|
} |
1118
|
|
|
|
1119
|
28 |
|
if (is_array($this->content)) { |
|
|
|
|
1120
|
|
|
throw new InvalidArgumentException('Response content must not be an array.'); |
1121
|
28 |
|
} elseif (is_object($this->content)) { |
1122
|
|
|
if (method_exists($this->content, '__toString')) { |
1123
|
|
|
$this->content = $this->content->__toString(); |
1124
|
|
|
} else { |
1125
|
|
|
throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().'); |
1126
|
|
|
} |
1127
|
|
|
} |
1128
|
28 |
|
} |
1129
|
|
|
|
1130
|
|
|
/** |
1131
|
|
|
* Checks if a stream is seekable |
1132
|
|
|
* |
1133
|
|
|
* @param $handle |
1134
|
|
|
* @return bool |
1135
|
|
|
*/ |
1136
|
11 |
|
private function isSeekable($handle) |
1137
|
|
|
{ |
1138
|
11 |
|
if (!is_resource($handle)) { |
1139
|
|
|
return true; |
1140
|
|
|
} |
1141
|
|
|
|
1142
|
11 |
|
$metaData = stream_get_meta_data($handle); |
1143
|
11 |
|
return isset($metaData['seekable']) && $metaData['seekable'] === true; |
1144
|
|
|
} |
1145
|
|
|
} |
1146
|
|
|
|