Passed
Push — feature/fix-non-seekable-strea... ( 22bd53 )
by Tobias
10:57
created

Response   F

Complexity

Total Complexity 119

Size/Duplication

Total Lines 1033
Duplicated Lines 0 %

Test Coverage

Coverage 74.48%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 365
c 4
b 1
f 0
dl 0
loc 1033
ccs 216
cts 290
cp 0.7448
rs 2
wmc 119

32 Methods

Rating   Name   Duplication   Size   Complexity  
A sendHeaders() 0 19 5
A getHeaders() 0 7 2
A getStatusCode() 0 3 1
A setStatusCodeByException() 0 9 2
A init() 0 13 5
A setStatusCode() 0 16 5
A send() 0 12 2
A clear() 0 10 1
B sendCookies() 0 33 10
A getIsClientError() 0 3 2
A getIsRedirection() 0 3 2
A sendContentAsFile() 0 28 5
A refresh() 0 3 1
A xSendFile() 0 25 6
A sendFile() 0 12 3
A getIsEmpty() 0 3 1
A getDispositionHeaderValue() 0 15 2
A getIsServerError() 0 3 2
B getHttpRange() 0 27 8
A getIsNotFound() 0 3 1
A getIsOk() 0 3 1
A defaultFormatters() 0 15 1
A getIsInvalid() 0 3 2
A getCookies() 0 7 2
B sendContent() 0 38 11
A getIsForbidden() 0 3 1
A setDownloadHeaders() 0 20 4
A getIsInformational() 0 3 2
B sendStreamAsFile() 0 31 6
B redirect() 0 32 10
B prepare() 0 37 11
A getIsSuccessful() 0 3 2

How to fix   Complexity   

Complex Class

Complex classes like Response often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Response, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://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\helpers\FileHelper;
14
use yii\helpers\Inflector;
15
use yii\helpers\StringHelper;
16
use yii\helpers\Url;
17
18
/**
19
 * The web Response class represents an HTTP response.
20
 *
21
 * It holds the [[headers]], [[cookies]] and [[content]] that is to be sent to the client.
22
 * It also controls the HTTP [[statusCode|status code]].
23
 *
24
 * Response is configured as an application component in [[\yii\web\Application]] by default.
25
 * You can access that instance via `Yii::$app->response`.
26
 *
27
 * You can modify its configuration by adding an array to your application config under `components`
28
 * as it is shown in the following example:
29
 *
30
 * ```php
31
 * 'response' => [
32
 *     'format' => yii\web\Response::FORMAT_JSON,
33
 *     'charset' => 'UTF-8',
34
 *     // ...
35
 * ]
36
 * ```
37
 *
38
 * For more details and usage information on Response, see the [guide article on responses](guide:runtime-responses).
39
 *
40
 * @property CookieCollection $cookies The cookie collection. This property is read-only.
41
 * @property string $downloadHeaders The attachment file name. This property is write-only.
42
 * @property HeaderCollection $headers The header collection. This property is read-only.
43
 * @property bool $isClientError Whether this response indicates a client error. This property is read-only.
44
 * @property bool $isEmpty Whether this response is empty. This property is read-only.
45
 * @property bool $isForbidden Whether this response indicates the current request is forbidden. This property
46
 * is read-only.
47
 * @property bool $isInformational Whether this response is informational. This property is read-only.
48
 * @property bool $isInvalid Whether this response has a valid [[statusCode]]. This property is read-only.
49
 * @property bool $isNotFound Whether this response indicates the currently requested resource is not found.
50
 * This property is read-only.
51
 * @property bool $isOk Whether this response is OK. This property is read-only.
52
 * @property bool $isRedirection Whether this response is a redirection. This property is read-only.
53
 * @property bool $isServerError Whether this response indicates a server error. This property is read-only.
54
 * @property bool $isSuccessful Whether this response is successful. This property is read-only.
55
 * @property int $statusCode The HTTP status code to send with the response.
56
 * @property \Exception|\Error $statusCodeByException The exception object. This property is write-only.
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 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 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. Note that when this property is set, the [[data]] and [[content]]
139
     * properties will be ignored by [[send()]].
140
     */
141
    public $stream;
142
    /**
143
     * @var string the charset of the text response. If not set, it will use
144
     * the value of [[Application::charset]].
145
     */
146
    public $charset;
147
    /**
148
     * @var string the HTTP status description that comes together with the status code.
149
     * @see httpStatuses
150
     */
151
    public $statusText = 'OK';
152
    /**
153
     * @var string the version of the HTTP protocol to use. If not set, it will be determined via `$_SERVER['SERVER_PROTOCOL']`,
154
     * or '1.1' if that is not available.
155
     */
156
    public $version;
157
    /**
158
     * @var bool whether the response has been sent. If this is true, calling [[send()]] will do nothing.
159
     */
160
    public $isSent = false;
161
    /**
162
     * @var array list of HTTP status codes and the corresponding texts
163
     */
164
    public static $httpStatuses = [
165
        100 => 'Continue',
166
        101 => 'Switching Protocols',
167
        102 => 'Processing',
168
        118 => 'Connection timed out',
169
        200 => 'OK',
170
        201 => 'Created',
171
        202 => 'Accepted',
172
        203 => 'Non-Authoritative',
173
        204 => 'No Content',
174
        205 => 'Reset Content',
175
        206 => 'Partial Content',
176
        207 => 'Multi-Status',
177
        208 => 'Already Reported',
178
        210 => 'Content Different',
179
        226 => 'IM Used',
180
        300 => 'Multiple Choices',
181
        301 => 'Moved Permanently',
182
        302 => 'Found',
183
        303 => 'See Other',
184
        304 => 'Not Modified',
185
        305 => 'Use Proxy',
186
        306 => 'Reserved',
187
        307 => 'Temporary Redirect',
188
        308 => 'Permanent Redirect',
189
        310 => 'Too many Redirect',
190
        400 => 'Bad Request',
191
        401 => 'Unauthorized',
192
        402 => 'Payment Required',
193
        403 => 'Forbidden',
194
        404 => 'Not Found',
195
        405 => 'Method Not Allowed',
196
        406 => 'Not Acceptable',
197
        407 => 'Proxy Authentication Required',
198
        408 => 'Request Time-out',
199
        409 => 'Conflict',
200
        410 => 'Gone',
201
        411 => 'Length Required',
202
        412 => 'Precondition Failed',
203
        413 => 'Request Entity Too Large',
204
        414 => 'Request-URI Too Long',
205
        415 => 'Unsupported Media Type',
206
        416 => 'Requested range unsatisfiable',
207
        417 => 'Expectation failed',
208
        418 => 'I\'m a teapot',
209
        421 => 'Misdirected Request',
210
        422 => 'Unprocessable entity',
211
        423 => 'Locked',
212
        424 => 'Method failure',
213
        425 => 'Unordered Collection',
214
        426 => 'Upgrade Required',
215
        428 => 'Precondition Required',
216
        429 => 'Too Many Requests',
217
        431 => 'Request Header Fields Too Large',
218
        449 => 'Retry With',
219
        450 => 'Blocked by Windows Parental Controls',
220
        451 => 'Unavailable For Legal Reasons',
221
        500 => 'Internal Server Error',
222
        501 => 'Not Implemented',
223
        502 => 'Bad Gateway or Proxy Error',
224
        503 => 'Service Unavailable',
225
        504 => 'Gateway Time-out',
226
        505 => 'HTTP Version not supported',
227
        507 => 'Insufficient storage',
228
        508 => 'Loop Detected',
229
        509 => 'Bandwidth Limit Exceeded',
230
        510 => 'Not Extended',
231
        511 => 'Network Authentication Required',
232
    ];
233
234
    /**
235
     * @var int the HTTP status code to send with the response.
236
     */
237
    private $_statusCode = 200;
238
    /**
239
     * @var HeaderCollection
240
     */
241
    private $_headers;
242
243
244
    /**
245
     * Initializes this component.
246
     */
247 322
    public function init()
248
    {
249 322
        if ($this->version === null) {
250 322
            if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.0') {
251
                $this->version = '1.0';
252
            } else {
253 322
                $this->version = '1.1';
254
            }
255
        }
256 322
        if ($this->charset === null) {
257 322
            $this->charset = Yii::$app->charset;
258
        }
259 322
        $this->formatters = array_merge($this->defaultFormatters(), $this->formatters);
260 322
    }
261
262
    /**
263
     * @return int the HTTP status code to send with the response.
264
     */
265 58
    public function getStatusCode()
266
    {
267 58
        return $this->_statusCode;
268
    }
269
270
    /**
271
     * Sets the response status code.
272
     * This method will set the corresponding status text if `$text` is null.
273
     * @param int $value the status code
274
     * @param string $text the status text. If not set, it will be set automatically based on the status code.
275
     * @throws InvalidArgumentException if the status code is invalid.
276
     * @return $this the response object itself
277
     */
278 51
    public function setStatusCode($value, $text = null)
279
    {
280 51
        if ($value === null) {
0 ignored issues
show
introduced by
The condition $value === null is always false.
Loading history...
281
            $value = 200;
282
        }
283 51
        $this->_statusCode = (int) $value;
284 51
        if ($this->getIsInvalid()) {
285
            throw new InvalidArgumentException("The HTTP status code is invalid: $value");
286
        }
287 51
        if ($text === null) {
288 47
            $this->statusText = isset(static::$httpStatuses[$this->_statusCode]) ? static::$httpStatuses[$this->_statusCode] : '';
289
        } else {
290 4
            $this->statusText = $text;
291
        }
292
293 51
        return $this;
294
    }
295
296
    /**
297
     * Sets the response status code based on the exception.
298
     * @param \Exception|\Error $e the exception object.
299
     * @throws InvalidArgumentException if the status code is invalid.
300
     * @return $this the response object itself
301
     * @since 2.0.12
302
     */
303 18
    public function setStatusCodeByException($e)
304
    {
305 18
        if ($e instanceof HttpException) {
306 10
            $this->setStatusCode($e->statusCode);
307
        } else {
308 8
            $this->setStatusCode(500);
309
        }
310
311 18
        return $this;
312
    }
313
314
    /**
315
     * Returns the header collection.
316
     * The header collection contains the currently registered HTTP headers.
317
     * @return HeaderCollection the header collection
318
     */
319 117
    public function getHeaders()
320
    {
321 117
        if ($this->_headers === null) {
322 117
            $this->_headers = new HeaderCollection();
323
        }
324
325 117
        return $this->_headers;
326
    }
327
328
    /**
329
     * Sends the response to the client.
330
     */
331 31
    public function send()
332
    {
333 31
        if ($this->isSent) {
334 3
            return;
335
        }
336 31
        $this->trigger(self::EVENT_BEFORE_SEND);
337 31
        $this->prepare();
338 31
        $this->trigger(self::EVENT_AFTER_PREPARE);
339 31
        $this->sendHeaders();
340 31
        $this->sendContent();
341 31
        $this->trigger(self::EVENT_AFTER_SEND);
342 31
        $this->isSent = true;
343 31
    }
344
345
    /**
346
     * Clears the headers, cookies, content, status code of the response.
347
     */
348
    public function clear()
349
    {
350
        $this->_headers = null;
351
        $this->_cookies = null;
352
        $this->_statusCode = 200;
353
        $this->statusText = 'OK';
354
        $this->data = null;
355
        $this->stream = null;
356
        $this->content = null;
357
        $this->isSent = false;
358
    }
359
360
    /**
361
     * Sends the response headers to the client.
362
     */
363 31
    protected function sendHeaders()
364
    {
365 31
        if (headers_sent($file, $line)) {
366
            throw new HeadersAlreadySentException($file, $line);
367
        }
368 31
        if ($this->_headers) {
369 28
            foreach ($this->getHeaders() as $name => $values) {
370 28
                $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
371
                // set replace for first occurrence of header but false afterwards to allow multiple
372 28
                $replace = true;
373 28
                foreach ($values as $value) {
374 28
                    header("$name: $value", $replace);
375 28
                    $replace = false;
376
                }
377
            }
378
        }
379 31
        $statusCode = $this->getStatusCode();
380 31
        header("HTTP/{$this->version} {$statusCode} {$this->statusText}");
381 31
        $this->sendCookies();
382 31
    }
383
384
    /**
385
     * Sends the cookies to the client.
386
     */
387 31
    protected function sendCookies()
388
    {
389 31
        if ($this->_cookies === null) {
390 26
            return;
391
        }
392 5
        $request = Yii::$app->getRequest();
393 5
        if ($request->enableCookieValidation) {
0 ignored issues
show
Bug Best Practice introduced by
The property enableCookieValidation does not exist on yii\console\Request. Since you implemented __get, consider adding a @property annotation.
Loading history...
394 5
            if ($request->cookieValidationKey == '') {
0 ignored issues
show
Bug Best Practice introduced by
The property cookieValidationKey does not exist on yii\console\Request. Since you implemented __get, consider adding a @property annotation.
Loading history...
395
                throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
396
            }
397 5
            $validationKey = $request->cookieValidationKey;
398
        }
399 5
        foreach ($this->getCookies() as $cookie) {
400 5
            $value = $cookie->value;
401 5
            if ($cookie->expire != 1 && isset($validationKey)) {
402 5
                $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
403
            }
404 5
            if (PHP_VERSION_ID >= 70300) {
405
                setcookie($cookie->name, $value, [
0 ignored issues
show
Bug introduced by
array('expires' => $cook...ookie->sameSite : null) of type array<string,mixed|null> is incompatible with the type integer expected by parameter $expire of setcookie(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

405
                setcookie($cookie->name, $value, /** @scrutinizer ignore-type */ [
Loading history...
406
                    'expires' => $cookie->expire,
407
                    'path' => $cookie->path,
408
                    'domain' => $cookie->domain,
409
                    'secure' => $cookie->secure,
410
                    'httpOnly' => $cookie->httpOnly,
411
                    'sameSite' => !empty($cookie->sameSite) ? $cookie->sameSite : null,
412
                ]);
413
            } else {
414
                // Work around for setting sameSite cookie prior PHP 7.3
415
                // https://stackoverflow.com/questions/39750906/php-setcookie-samesite-strict/46971326#46971326
416 5
                if (!is_null($cookie->sameSite)) {
417 1
                    $cookie->path .= '; samesite=' . $cookie->sameSite;
418
                }
419 5
                setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
420
            }
421
        }
422 5
    }
423
424
    /**
425
     * Sends the response content to the client.
426
     */
427 31
    protected function sendContent()
428
    {
429 31
        if ($this->stream === null) {
430 28
            echo $this->content;
431
432 28
            return;
433
        }
434
435
        // Try to reset time limit for big files
436 3
        if (!function_exists('set_time_limit') || !@set_time_limit(0)) {
437
            Yii::warning('set_time_limit() is not available', __METHOD__);
438
        }
439
440 3
        $chunkSize = 8 * 1024 * 1024; // 8MB per chunk
441
442 3
        if (is_array($this->stream)) {
443 3
            list($handle, $begin, $end) = $this->stream;
444
445
            // only seek if stream is seekable
446 3
            $metaData = stream_get_meta_data($handle);
447 3
            if (isset($metaData['seekable']) && $metaData['seekable'] === true) {
448 3
                fseek($handle, $begin);
449
            }
450
451 3
            while (!feof($handle) && ($pos = ftell($handle)) <= $end) {
452 3
                if ($pos + $chunkSize > $end) {
453 3
                    $chunkSize = $end - $pos + 1;
454
                }
455 3
                echo fread($handle, $chunkSize);
456 3
                flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
457
            }
458 3
            fclose($handle);
459
        } else {
460
            while (!feof($this->stream)) {
461
                echo fread($this->stream, $chunkSize);
462
                flush();
463
            }
464
            fclose($this->stream);
465
        }
466 3
    }
467
468
    /**
469
     * Sends a file to the browser.
470
     *
471
     * Note that this method only prepares the response for file sending. The file is not sent
472
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
473
     *
474
     * The following is an example implementation of a controller action that allows requesting files from a directory
475
     * that is not accessible from web:
476
     *
477
     * ```php
478
     * public function actionFile($filename)
479
     * {
480
     *     $storagePath = Yii::getAlias('@app/files');
481
     *
482
     *     // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
483
     *     if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
484
     *         throw new \yii\web\NotFoundHttpException('The file does not exists.');
485
     *     }
486
     *     return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
487
     * }
488
     * ```
489
     *
490
     * @param string $filePath the path of the file to be sent.
491
     * @param string $attachmentName the file name shown to the user. If null, it will be determined from `$filePath`.
492
     * @param array $options additional options for sending the file. The following options are supported:
493
     *
494
     *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
495
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
496
     *    meaning a download dialog will pop up.
497
     *
498
     * @return $this the response object itself
499
     * @see sendContentAsFile()
500
     * @see sendStreamAsFile()
501
     * @see xSendFile()
502
     */
503 9
    public function sendFile($filePath, $attachmentName = null, $options = [])
504
    {
505 9
        if (!isset($options['mimeType'])) {
506 9
            $options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath);
507
        }
508 9
        if ($attachmentName === null) {
509 8
            $attachmentName = basename($filePath);
510
        }
511 9
        $handle = fopen($filePath, 'rb');
512 9
        $this->sendStreamAsFile($handle, $attachmentName, $options);
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of yii\web\Response::sendStreamAsFile() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

512
        $this->sendStreamAsFile(/** @scrutinizer ignore-type */ $handle, $attachmentName, $options);
Loading history...
513
514 5
        return $this;
515
    }
516
517
    /**
518
     * Sends the specified content as a file to the browser.
519
     *
520
     * Note that this method only prepares the response for file sending. The file is not sent
521
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
522
     *
523
     * @param string $content the content to be sent. The existing [[content]] will be discarded.
524
     * @param string $attachmentName the file name shown to the user.
525
     * @param array $options additional options for sending the file. The following options are supported:
526
     *
527
     *  - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
528
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
529
     *    meaning a download dialog will pop up.
530
     *
531
     * @return $this the response object itself
532
     * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
533
     * @see sendFile() for an example implementation.
534
     */
535 1
    public function sendContentAsFile($content, $attachmentName, $options = [])
536
    {
537 1
        $headers = $this->getHeaders();
538
539 1
        $contentLength = StringHelper::byteLength($content);
540 1
        $range = $this->getHttpRange($contentLength);
541
542 1
        if ($range === false) {
0 ignored issues
show
introduced by
The condition $range === false is always false.
Loading history...
543
            $headers->set('Content-Range', "bytes */$contentLength");
544
            throw new RangeNotSatisfiableHttpException();
545
        }
546
547 1
        list($begin, $end) = $range;
548 1
        if ($begin != 0 || $end != $contentLength - 1) {
549
            $this->setStatusCode(206);
550
            $headers->set('Content-Range', "bytes $begin-$end/$contentLength");
551
            $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
552
        } else {
553 1
            $this->setStatusCode(200);
554 1
            $this->content = $content;
555
        }
556
557 1
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
558 1
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
559
560 1
        $this->format = self::FORMAT_RAW;
561
562 1
        return $this;
563
    }
564
565
    /**
566
     * Sends the specified stream as a file to the browser.
567
     *
568
     * Note that this method only prepares the response for file sending. The file is not sent
569
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
570
     *
571
     * @param resource $handle the handle of the stream to be sent.
572
     * @param string $attachmentName the file name shown to the user.
573
     * @param array $options additional options for sending the file. The following options are supported:
574
     *
575
     *  - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
576
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
577
     *    meaning a download dialog will pop up.
578
     *  - `fileSize`: the size of the content to stream this is useful when size of the content is known
579
     *    and the content is not seekable. Defaults to content size using `ftell()`.
580
     *    This option is available since version 2.0.4.
581
     *
582
     * @return $this the response object itself
583
     * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
584
     * @see sendFile() for an example implementation.
585
     */
586 9
    public function sendStreamAsFile($handle, $attachmentName, $options = [])
587
    {
588 9
        $headers = $this->getHeaders();
589 9
        if (isset($options['fileSize'])) {
590
            $fileSize = $options['fileSize'];
591
        } else {
592 9
            fseek($handle, 0, SEEK_END);
593 9
            $fileSize = ftell($handle);
594
        }
595
596 9
        $range = $this->getHttpRange($fileSize);
597 9
        if ($range === false) {
0 ignored issues
show
introduced by
The condition $range === false is always false.
Loading history...
598 4
            $headers->set('Content-Range', "bytes */$fileSize");
599 4
            throw new RangeNotSatisfiableHttpException();
600
        }
601
602 5
        list($begin, $end) = $range;
603 5
        if ($begin != 0 || $end != $fileSize - 1) {
604 3
            $this->setStatusCode(206);
605 3
            $headers->set('Content-Range', "bytes $begin-$end/$fileSize");
606
        } else {
607 2
            $this->setStatusCode(200);
608
        }
609
610 5
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
611 5
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
612
613 5
        $this->format = self::FORMAT_RAW;
614 5
        $this->stream = [$handle, $begin, $end];
615
616 5
        return $this;
617
    }
618
619
    /**
620
     * Sets a default set of HTTP headers for file downloading purpose.
621
     * @param string $attachmentName the attachment file name
622
     * @param string $mimeType the MIME type for the response. If null, `Content-Type` header will NOT be set.
623
     * @param bool $inline whether the browser should open the file within the browser window. Defaults to false,
624
     * meaning a download dialog will pop up.
625
     * @param int $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set.
626
     * @return $this the response object itself
627
     */
628 6
    public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null)
629
    {
630 6
        $headers = $this->getHeaders();
631
632 6
        $disposition = $inline ? 'inline' : 'attachment';
633 6
        $headers->setDefault('Pragma', 'public')
634 6
            ->setDefault('Accept-Ranges', 'bytes')
635 6
            ->setDefault('Expires', '0')
636 6
            ->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
637 6
            ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
638
639 6
        if ($mimeType !== null) {
640 6
            $headers->setDefault('Content-Type', $mimeType);
641
        }
642
643 6
        if ($contentLength !== null) {
644 6
            $headers->setDefault('Content-Length', $contentLength);
645
        }
646
647 6
        return $this;
648
    }
649
650
    /**
651
     * Determines the HTTP range given in the request.
652
     * @param int $fileSize the size of the file that will be used to validate the requested HTTP range.
653
     * @return array|bool the range (begin, end), or false if the range request is invalid.
654
     */
655 10
    protected function getHttpRange($fileSize)
656
    {
657 10
        $rangeHeader = Yii::$app->getRequest()->getHeaders()->get('Range', '-');
0 ignored issues
show
Bug introduced by
The method getHeaders() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

657
        $rangeHeader = Yii::$app->getRequest()->/** @scrutinizer ignore-call */ getHeaders()->get('Range', '-');
Loading history...
658 10
        if ($rangeHeader === '-') {
659 3
            return [0, $fileSize - 1];
660
        }
661 7
        if (!preg_match('/^bytes=(\d*)-(\d*)$/', $rangeHeader, $matches)) {
0 ignored issues
show
Bug introduced by
It seems like $rangeHeader can also be of type array; however, parameter $subject of preg_match() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

661
        if (!preg_match('/^bytes=(\d*)-(\d*)$/', /** @scrutinizer ignore-type */ $rangeHeader, $matches)) {
Loading history...
662 1
            return false;
663
        }
664 6
        if ($matches[1] === '') {
665 2
            $start = $fileSize - $matches[2];
666 2
            $end = $fileSize - 1;
667 4
        } elseif ($matches[2] !== '') {
668 2
            $start = $matches[1];
669 2
            $end = $matches[2];
670 2
            if ($end >= $fileSize) {
671 2
                $end = $fileSize - 1;
672
            }
673
        } else {
674 2
            $start = $matches[1];
675 2
            $end = $fileSize - 1;
676
        }
677 6
        if ($start < 0 || $start > $end) {
678 3
            return false;
679
        }
680
681 3
        return [$start, $end];
682
    }
683
684
    /**
685
     * Sends existing file to a browser as a download using x-sendfile.
686
     *
687
     * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
688
     * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
689
     * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
690
     * increase in performance as the web application is allowed to terminate earlier while the webserver is
691
     * handling the request.
692
     *
693
     * The request is sent to the server through a special non-standard HTTP-header.
694
     * When the web server encounters the presence of such header it will discard all output and send the file
695
     * specified by that header using web server internals including all optimizations like caching-headers.
696
     *
697
     * As this header directive is non-standard different directives exists for different web servers applications:
698
     *
699
     * - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
700
     * - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
701
     * - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
702
     * - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
703
     * - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
704
     *
705
     * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
706
     * a proper xHeader should be sent.
707
     *
708
     * **Note**
709
     *
710
     * This option allows to download files that are not under web folders, and even files that are otherwise protected
711
     * (deny from all) like `.htaccess`.
712
     *
713
     * **Side effects**
714
     *
715
     * If this option is disabled by the web server, when this method is called a download configuration dialog
716
     * will open but the downloaded file will have 0 bytes.
717
     *
718
     * **Known issues**
719
     *
720
     * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
721
     * an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
722
     * is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
723
     *
724
     * **Example**
725
     *
726
     * ```php
727
     * Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
728
     * ```
729
     *
730
     * @param string $filePath file name with full path
731
     * @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
732
     * @param array $options additional options for sending the file. The following options are supported:
733
     *
734
     *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
735
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
736
     *    meaning a download dialog will pop up.
737
     *  - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
738
     *
739
     * @return $this the response object itself
740
     * @see sendFile()
741
     */
742
    public function xSendFile($filePath, $attachmentName = null, $options = [])
743
    {
744
        if ($attachmentName === null) {
745
            $attachmentName = basename($filePath);
746
        }
747
        if (isset($options['mimeType'])) {
748
            $mimeType = $options['mimeType'];
749
        } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
750
            $mimeType = 'application/octet-stream';
751
        }
752
        if (isset($options['xHeader'])) {
753
            $xHeader = $options['xHeader'];
754
        } else {
755
            $xHeader = 'X-Sendfile';
756
        }
757
758
        $disposition = empty($options['inline']) ? 'attachment' : 'inline';
759
        $this->getHeaders()
760
            ->setDefault($xHeader, $filePath)
761
            ->setDefault('Content-Type', $mimeType)
762
            ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
763
764
        $this->format = self::FORMAT_RAW;
765
766
        return $this;
767
    }
768
769
    /**
770
     * Returns Content-Disposition header value that is safe to use with both old and new browsers.
771
     *
772
     * Fallback name:
773
     *
774
     * - Causes issues if contains non-ASCII characters with codes less than 32 or more than 126.
775
     * - Causes issues if contains urlencoded characters (starting with `%`) or `%` character. Some browsers interpret
776
     *   `filename="X"` as urlencoded name, some don't.
777
     * - Causes issues if contains path separator characters such as `\` or `/`.
778
     * - Since value is wrapped with `"`, it should be escaped as `\"`.
779
     * - Since input could contain non-ASCII characters, fallback is obtained by transliteration.
780
     *
781
     * UTF name:
782
     *
783
     * - Causes issues if contains path separator characters such as `\` or `/`.
784
     * - Should be urlencoded since headers are ASCII-only.
785
     * - Could be omitted if it exactly matches fallback name.
786
     *
787
     * @param string $disposition
788
     * @param string $attachmentName
789
     * @return string
790
     *
791
     * @since 2.0.10
792
     */
793 6
    protected function getDispositionHeaderValue($disposition, $attachmentName)
794
    {
795 6
        $fallbackName = str_replace(
796 6
            ['%', '/', '\\', '"', "\x7F"],
797 6
            ['_', '_', '_', '\\"', '_'],
798 6
            Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE)
799
        );
800 6
        $utfName = rawurlencode(str_replace(['%', '/', '\\'], '', $attachmentName));
801
802 6
        $dispositionHeader = "{$disposition}; filename=\"{$fallbackName}\"";
803 6
        if ($utfName !== $fallbackName) {
804 1
            $dispositionHeader .= "; filename*=utf-8''{$utfName}";
805
        }
806
807 6
        return $dispositionHeader;
808
    }
809
810
    /**
811
     * Redirects the browser to the specified URL.
812
     *
813
     * This method adds a "Location" header to the current response. Note that it does not send out
814
     * the header until [[send()]] is called. In a controller action you may use this method as follows:
815
     *
816
     * ```php
817
     * return Yii::$app->getResponse()->redirect($url);
818
     * ```
819
     *
820
     * In other places, if you want to send out the "Location" header immediately, you should use
821
     * the following code:
822
     *
823
     * ```php
824
     * Yii::$app->getResponse()->redirect($url)->send();
825
     * return;
826
     * ```
827
     *
828
     * In AJAX mode, this normally will not work as expected unless there are some
829
     * client-side JavaScript code handling the redirection. To help achieve this goal,
830
     * this method will send out a "X-Redirect" header instead of "Location".
831
     *
832
     * If you use the "yii" JavaScript module, it will handle the AJAX redirection as
833
     * described above. Otherwise, you should write the following JavaScript code to
834
     * handle the redirection:
835
     *
836
     * ```javascript
837
     * $document.ajaxComplete(function (event, xhr, settings) {
838
     *     var url = xhr && xhr.getResponseHeader('X-Redirect');
839
     *     if (url) {
840
     *         window.location = url;
841
     *     }
842
     * });
843
     * ```
844
     *
845
     * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
846
     *
847
     * - a string representing a URL (e.g. "http://example.com")
848
     * - a string representing a URL alias (e.g. "@example.com")
849
     * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`).
850
     *   Note that the route is with respect to the whole application, instead of relative to a controller or module.
851
     *   [[Url::to()]] will be used to convert the array into a URL.
852
     *
853
     * Any relative URL that starts with a single forward slash "/" will be converted
854
     * into an absolute one by prepending it with the host info of the current request.
855
     *
856
     * @param int $statusCode the HTTP status code. Defaults to 302.
857
     * See <https://tools.ietf.org/html/rfc2616#section-10>
858
     * for details about HTTP status code
859
     * @param bool $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true,
860
     * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser
861
     * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as
862
     * an AJAX/PJAX response, may NOT cause browser redirection.
863
     * Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent.
864
     * @return $this the response object itself
865
     */
866 9
    public function redirect($url, $statusCode = 302, $checkAjax = true)
867
    {
868 9
        if (is_array($url) && isset($url[0])) {
869
            // ensure the route is absolute
870 8
            $url[0] = '/' . ltrim($url[0], '/');
871
        }
872 9
        $request = Yii::$app->getRequest();
873 9
        $url = Url::to($url);
874 9
        if (strncmp($url, '/', 1) === 0 && strncmp($url, '//', 2) !== 0) {
875 9
            $url = $request->getHostInfo() . $url;
0 ignored issues
show
Bug introduced by
The method getHostInfo() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

875
            $url = $request->/** @scrutinizer ignore-call */ getHostInfo() . $url;
Loading history...
876
        }
877
878 9
        if ($checkAjax) {
879 9
            if ($request->getIsAjax()) {
0 ignored issues
show
Bug introduced by
The method getIsAjax() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

879
            if ($request->/** @scrutinizer ignore-call */ getIsAjax()) {
Loading history...
880 7
                if (in_array($statusCode, [301, 302]) && preg_match('/Trident\/|MSIE[ ]/', $request->userAgent)) {
0 ignored issues
show
Bug Best Practice introduced by
The property userAgent does not exist on yii\console\Request. Since you implemented __get, consider adding a @property annotation.
Loading history...
881 3
                    $statusCode = 200;
882
                }
883 7
                if ($request->getIsPjax()) {
0 ignored issues
show
Bug introduced by
The method getIsPjax() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

883
                if ($request->/** @scrutinizer ignore-call */ getIsPjax()) {
Loading history...
884 6
                    $this->getHeaders()->set('X-Pjax-Url', $url);
885
                } else {
886 7
                    $this->getHeaders()->set('X-Redirect', $url);
887
                }
888
            } else {
889 9
                $this->getHeaders()->set('Location', $url);
890
            }
891
        } else {
892
            $this->getHeaders()->set('Location', $url);
893
        }
894
895 9
        $this->setStatusCode($statusCode);
896
897 9
        return $this;
898
    }
899
900
    /**
901
     * Refreshes the current page.
902
     * The effect of this method call is the same as the user pressing the refresh button of his browser
903
     * (without re-posting data).
904
     *
905
     * In a controller action you may use this method like this:
906
     *
907
     * ```php
908
     * return Yii::$app->getResponse()->refresh();
909
     * ```
910
     *
911
     * @param string $anchor the anchor that should be appended to the redirection URL.
912
     * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
913
     * @return Response the response object itself
914
     */
915
    public function refresh($anchor = '')
916
    {
917
        return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
0 ignored issues
show
Bug introduced by
The method getUrl() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

917
        return $this->redirect(Yii::$app->getRequest()->/** @scrutinizer ignore-call */ getUrl() . $anchor);
Loading history...
918
    }
919
920
    private $_cookies;
921
922
    /**
923
     * Returns the cookie collection.
924
     *
925
     * Through the returned cookie collection, you add or remove cookies as follows,
926
     *
927
     * ```php
928
     * // add a cookie
929
     * $response->cookies->add(new Cookie([
930
     *     'name' => $name,
931
     *     'value' => $value,
932
     * ]);
933
     *
934
     * // remove a cookie
935
     * $response->cookies->remove('name');
936
     * // alternatively
937
     * unset($response->cookies['name']);
938
     * ```
939
     *
940
     * @return CookieCollection the cookie collection.
941
     */
942 81
    public function getCookies()
943
    {
944 81
        if ($this->_cookies === null) {
945 81
            $this->_cookies = new CookieCollection();
946
        }
947
948 81
        return $this->_cookies;
949
    }
950
951
    /**
952
     * @return bool whether this response has a valid [[statusCode]].
953
     */
954 51
    public function getIsInvalid()
955
    {
956 51
        return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
957
    }
958
959
    /**
960
     * @return bool whether this response is informational
961
     */
962
    public function getIsInformational()
963
    {
964
        return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
965
    }
966
967
    /**
968
     * @return bool whether this response is successful
969
     */
970
    public function getIsSuccessful()
971
    {
972
        return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
973
    }
974
975
    /**
976
     * @return bool whether this response is a redirection
977
     */
978 1
    public function getIsRedirection()
979
    {
980 1
        return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
981
    }
982
983
    /**
984
     * @return bool whether this response indicates a client error
985
     */
986
    public function getIsClientError()
987
    {
988
        return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
989
    }
990
991
    /**
992
     * @return bool whether this response indicates a server error
993
     */
994
    public function getIsServerError()
995
    {
996
        return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
997
    }
998
999
    /**
1000
     * @return bool whether this response is OK
1001
     */
1002
    public function getIsOk()
1003
    {
1004
        return $this->getStatusCode() == 200;
1005
    }
1006
1007
    /**
1008
     * @return bool whether this response indicates the current request is forbidden
1009
     */
1010
    public function getIsForbidden()
1011
    {
1012
        return $this->getStatusCode() == 403;
1013
    }
1014
1015
    /**
1016
     * @return bool whether this response indicates the currently requested resource is not found
1017
     */
1018
    public function getIsNotFound()
1019
    {
1020
        return $this->getStatusCode() == 404;
1021
    }
1022
1023
    /**
1024
     * @return bool whether this response is empty
1025
     */
1026
    public function getIsEmpty()
1027
    {
1028
        return in_array($this->getStatusCode(), [201, 204, 304]);
1029
    }
1030
1031
    /**
1032
     * @return array the formatters that are supported by default
1033
     */
1034 322
    protected function defaultFormatters()
1035
    {
1036
        return [
1037 322
            self::FORMAT_HTML => [
1038
                'class' => 'yii\web\HtmlResponseFormatter',
1039
            ],
1040 322
            self::FORMAT_XML => [
1041
                'class' => 'yii\web\XmlResponseFormatter',
1042
            ],
1043 322
            self::FORMAT_JSON => [
1044
                'class' => 'yii\web\JsonResponseFormatter',
1045
            ],
1046 322
            self::FORMAT_JSONP => [
1047
                'class' => 'yii\web\JsonResponseFormatter',
1048
                'useJsonp' => true,
1049
            ],
1050
        ];
1051
    }
1052
1053
    /**
1054
     * Prepares for sending the response.
1055
     * The default implementation will convert [[data]] into [[content]] and set headers accordingly.
1056
     * @throws InvalidConfigException if the formatter for the specified format is invalid or [[format]] is not supported
1057
     */
1058 31
    protected function prepare()
1059
    {
1060 31
        if ($this->statusCode === 204) {
1061 3
            $this->content = '';
1062 3
            $this->stream = null;
1063 3
            return;
1064
        }
1065
1066 28
        if ($this->stream !== null) {
1067 3
            return;
1068
        }
1069
1070 25
        if (isset($this->formatters[$this->format])) {
1071 23
            $formatter = $this->formatters[$this->format];
1072 23
            if (!is_object($formatter)) {
1073 23
                $this->formatters[$this->format] = $formatter = Yii::createObject($formatter);
1074
            }
1075 23
            if ($formatter instanceof ResponseFormatterInterface) {
1076 23
                $formatter->format($this);
1077
            } else {
1078 23
                throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
1079
            }
1080 2
        } elseif ($this->format === self::FORMAT_RAW) {
1081 2
            if ($this->data !== null) {
1082 2
                $this->content = $this->data;
1083
            }
1084
        } else {
1085
            throw new InvalidConfigException("Unsupported response format: {$this->format}");
1086
        }
1087
1088 25
        if (is_array($this->content)) {
0 ignored issues
show
introduced by
The condition is_array($this->content) is always false.
Loading history...
1089
            throw new InvalidArgumentException('Response content must not be an array.');
1090 25
        } elseif (is_object($this->content)) {
0 ignored issues
show
introduced by
The condition is_object($this->content) is always false.
Loading history...
1091
            if (method_exists($this->content, '__toString')) {
1092
                $this->content = $this->content->__toString();
1093
            } else {
1094
                throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().');
1095
            }
1096
        }
1097 25
    }
1098
}
1099