Completed
Push — fix-wrong-response-code-in-err... ( c1bff3...60af75 )
by Alexander
20:09
created

Response::getStatusCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
cc 1
eloc 2
nc 1
nop 0
crap 1
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\InvalidConfigException;
12
use yii\base\InvalidParamException;
13
use yii\helpers\Inflector;
14
use yii\helpers\Url;
15
use yii\helpers\FileHelper;
16
use yii\helpers\StringHelper;
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
 *
57
 * @author Qiang Xue <[email protected]>
58
 * @author Carsten Brandt <[email protected]>
59
 * @since 2.0
60
 */
61
class Response extends \yii\base\Response
62
{
63
    /**
64
     * @event ResponseEvent an event that is triggered at the beginning of [[send()]].
65
     */
66
    const EVENT_BEFORE_SEND = 'beforeSend';
67
    /**
68
     * @event ResponseEvent an event that is triggered at the end of [[send()]].
69
     */
70
    const EVENT_AFTER_SEND = 'afterSend';
71
    /**
72
     * @event ResponseEvent an event that is triggered right after [[prepare()]] is called in [[send()]].
73
     * You may respond to this event to filter the response content before it is sent to the client.
74
     */
75
    const EVENT_AFTER_PREPARE = 'afterPrepare';
76
    const FORMAT_RAW = 'raw';
77
    const FORMAT_HTML = 'html';
78
    const FORMAT_JSON = 'json';
79
    const FORMAT_JSONP = 'jsonp';
80
    const FORMAT_XML = 'xml';
81
82
    /**
83
     * @var string the response format. This determines how to convert [[data]] into [[content]]
84
     * when the latter is not set. The value of this property must be one of the keys declared in the [[formatters]] array.
85
     * By default, the following formats are supported:
86
     *
87
     * - [[FORMAT_RAW]]: the data will be treated as the response content without any conversion.
88
     *   No extra HTTP header will be added.
89
     * - [[FORMAT_HTML]]: the data will be treated as the response content without any conversion.
90
     *   The "Content-Type" header will set as "text/html".
91
     * - [[FORMAT_JSON]]: the data will be converted into JSON format, and the "Content-Type"
92
     *   header will be set as "application/json".
93
     * - [[FORMAT_JSONP]]: the data will be converted into JSONP format, and the "Content-Type"
94
     *   header will be set as "text/javascript". Note that in this case `$data` must be an array
95
     *   with "data" and "callback" elements. The former refers to the actual data to be sent,
96
     *   while the latter refers to the name of the JavaScript callback.
97
     * - [[FORMAT_XML]]: the data will be converted into XML format. Please refer to [[XmlResponseFormatter]]
98
     *   for more details.
99
     *
100
     * You may customize the formatting process or support additional formats by configuring [[formatters]].
101
     * @see formatters
102
     */
103
    public $format = self::FORMAT_HTML;
104
    /**
105
     * @var string the MIME type (e.g. `application/json`) from the request ACCEPT header chosen for this response.
106
     * This property is mainly set by [[\yii\filters\ContentNegotiator]].
107
     */
108
    public $acceptMimeType;
109
    /**
110
     * @var array the parameters (e.g. `['q' => 1, 'version' => '1.0']`) associated with the [[acceptMimeType|chosen MIME type]].
111
     * This is a list of name-value pairs associated with [[acceptMimeType]] from the ACCEPT HTTP header.
112
     * This property is mainly set by [[\yii\filters\ContentNegotiator]].
113
     */
114
    public $acceptParams = [];
115
    /**
116
     * @var array the formatters for converting data into the response content of the specified [[format]].
117
     * The array keys are the format names, and the array values are the corresponding configurations
118
     * for creating the formatter objects.
119
     * @see format
120
     * @see defaultFormatters
121
     */
122
    public $formatters = [];
123
    /**
124
     * @var mixed the original response data. When this is not null, it will be converted into [[content]]
125
     * according to [[format]] when the response is being sent out.
126
     * @see content
127
     */
128
    public $data;
129
    /**
130
     * @var string the response content. When [[data]] is not null, it will be converted into [[content]]
131
     * according to [[format]] when the response is being sent out.
132
     * @see data
133
     */
134
    public $content;
135
    /**
136
     * @var resource|array the stream to be sent. This can be a stream handle or an array of stream handle,
137
     * the begin position and the end position. Note that when this property is set, the [[data]] and [[content]]
138
     * properties will be ignored by [[send()]].
139
     */
140
    public $stream;
141
    /**
142
     * @var string the charset of the text response. If not set, it will use
143
     * the value of [[Application::charset]].
144
     */
145
    public $charset;
146
    /**
147
     * @var string the HTTP status description that comes together with the status code.
148
     * @see httpStatuses
149
     */
150
    public $statusText = 'OK';
151
    /**
152
     * @var string the version of the HTTP protocol to use. If not set, it will be determined via `$_SERVER['SERVER_PROTOCOL']`,
153
     * or '1.1' if that is not available.
154
     */
155
    public $version;
156
    /**
157
     * @var bool whether the response has been sent. If this is true, calling [[send()]] will do nothing.
158
     */
159
    public $isSent = false;
160
    /**
161
     * @var array list of HTTP status codes and the corresponding texts
162
     */
163
    public static $httpStatuses = [
164
        100 => 'Continue',
165
        101 => 'Switching Protocols',
166
        102 => 'Processing',
167
        118 => 'Connection timed out',
168
        200 => 'OK',
169
        201 => 'Created',
170
        202 => 'Accepted',
171
        203 => 'Non-Authoritative',
172
        204 => 'No Content',
173
        205 => 'Reset Content',
174
        206 => 'Partial Content',
175
        207 => 'Multi-Status',
176
        208 => 'Already Reported',
177
        210 => 'Content Different',
178
        226 => 'IM Used',
179
        300 => 'Multiple Choices',
180
        301 => 'Moved Permanently',
181
        302 => 'Found',
182
        303 => 'See Other',
183
        304 => 'Not Modified',
184
        305 => 'Use Proxy',
185
        306 => 'Reserved',
186
        307 => 'Temporary Redirect',
187
        308 => 'Permanent Redirect',
188
        310 => 'Too many Redirect',
189
        400 => 'Bad Request',
190
        401 => 'Unauthorized',
191
        402 => 'Payment Required',
192
        403 => 'Forbidden',
193
        404 => 'Not Found',
194
        405 => 'Method Not Allowed',
195
        406 => 'Not Acceptable',
196
        407 => 'Proxy Authentication Required',
197
        408 => 'Request Time-out',
198
        409 => 'Conflict',
199
        410 => 'Gone',
200
        411 => 'Length Required',
201
        412 => 'Precondition Failed',
202
        413 => 'Request Entity Too Large',
203
        414 => 'Request-URI Too Long',
204
        415 => 'Unsupported Media Type',
205
        416 => 'Requested range unsatisfiable',
206
        417 => 'Expectation failed',
207
        418 => 'I\'m a teapot',
208
        421 => 'Misdirected Request',
209
        422 => 'Unprocessable entity',
210
        423 => 'Locked',
211
        424 => 'Method failure',
212
        425 => 'Unordered Collection',
213
        426 => 'Upgrade Required',
214
        428 => 'Precondition Required',
215
        429 => 'Too Many Requests',
216
        431 => 'Request Header Fields Too Large',
217
        449 => 'Retry With',
218
        450 => 'Blocked by Windows Parental Controls',
219
        500 => 'Internal Server Error',
220
        501 => 'Not Implemented',
221
        502 => 'Bad Gateway or Proxy Error',
222
        503 => 'Service Unavailable',
223
        504 => 'Gateway Time-out',
224
        505 => 'HTTP Version not supported',
225
        507 => 'Insufficient storage',
226
        508 => 'Loop Detected',
227
        509 => 'Bandwidth Limit Exceeded',
228
        510 => 'Not Extended',
229
        511 => 'Network Authentication Required',
230
    ];
231
232
    /**
233
     * @var int the HTTP status code to send with the response.
234
     */
235
    private $_statusCode = 200;
236
    /**
237
     * @var HeaderCollection
238
     */
239
    private $_headers;
240
241
242
    /**
243
     * Initializes this component.
244
     */
245 140
    public function init()
246
    {
247 140
        if ($this->version === null) {
248 140
            if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.0') {
249
                $this->version = '1.0';
250
            } else {
251 140
                $this->version = '1.1';
252
            }
253 140
        }
254 140
        if ($this->charset === null) {
255 140
            $this->charset = Yii::$app->charset;
256 140
        }
257 140
        $this->formatters = array_merge($this->defaultFormatters(), $this->formatters);
258 140
    }
259
260
    /**
261
     * @return int the HTTP status code to send with the response.
262
     */
263 31
    public function getStatusCode()
264
    {
265 31
        return $this->_statusCode;
266
    }
267
268
    /**
269
     * Sets the response status code.
270
     * This method will set the corresponding status text if `$text` is null.
271
     * @param int $value the status code
272
     * @param string $text the status text. If not set, it will be set automatically based on the status code.
273
     * @throws InvalidParamException if the status code is invalid.
274
     * @return $this the response object itself
275
     */
276 29
    public function setStatusCode($value, $text = null)
277
    {
278 29
        if ($value === null) {
279
            $value = 200;
280
        }
281 29
        $this->_statusCode = (int) $value;
282 29
        if ($this->getIsInvalid()) {
283
            throw new InvalidParamException("The HTTP status code is invalid: $value");
284
        }
285 29
        if ($text === null) {
286 25
            $this->statusText = isset(static::$httpStatuses[$this->_statusCode]) ? static::$httpStatuses[$this->_statusCode] : '';
287 25
        } else {
288 4
            $this->statusText = $text;
289
        }
290 29
        return $this;
291
    }
292
293
    /**
294
     * Sets the response status code based on the exception.
295
     * @param \Exception $e
296
     * @throws InvalidParamException if the status code is invalid.
297
     * @return $this the response object itself
298
     *
299
     * @since 2.0.12
300
     */
301 7
    public function setStatusCodeByException(\Exception $e)
302
    {
303 7
        if ($e instanceof HttpException) {
304 3
            $this->setStatusCode($e->statusCode);
305 3
        } else {
306 4
            $this->setStatusCode(500);
307
        }
308 7
        return $this;
309
    }
310
311
    /**
312
     * Returns the header collection.
313
     * The header collection contains the currently registered HTTP headers.
314
     * @return HeaderCollection the header collection
315
     */
316 75
    public function getHeaders()
317
    {
318 75
        if ($this->_headers === null) {
319 75
            $this->_headers = new HeaderCollection;
320 75
        }
321 75
        return $this->_headers;
322
    }
323
324
    /**
325
     * Sends the response to the client.
326
     */
327 21
    public function send()
328
    {
329 21
        if ($this->isSent) {
330 3
            return;
331
        }
332 21
        $this->trigger(self::EVENT_BEFORE_SEND);
333 21
        $this->prepare();
334 21
        $this->trigger(self::EVENT_AFTER_PREPARE);
335 21
        $this->sendHeaders();
336 21
        $this->sendContent();
337 21
        $this->trigger(self::EVENT_AFTER_SEND);
338 21
        $this->isSent = true;
339 21
    }
340
341
    /**
342
     * Clears the headers, cookies, content, status code of the response.
343
     */
344
    public function clear()
345
    {
346
        $this->_headers = null;
347
        $this->_cookies = null;
348
        $this->_statusCode = 200;
349
        $this->statusText = 'OK';
350
        $this->data = null;
351
        $this->stream = null;
352
        $this->content = null;
353
        $this->isSent = false;
354
    }
355
356
    /**
357
     * Sends the response headers to the client
358
     */
359 21
    protected function sendHeaders()
360
    {
361 21
        if (headers_sent()) {
362 21
            return;
363
        }
364
        if ($this->_headers) {
365
            $headers = $this->getHeaders();
366
            foreach ($headers as $name => $values) {
367
                $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
368
                // set replace for first occurrence of header but false afterwards to allow multiple
369
                $replace = true;
370
                foreach ($values as $value) {
371
                    header("$name: $value", $replace);
372
                    $replace = false;
373
                }
374
            }
375
        }
376
        $statusCode = $this->getStatusCode();
377
        header("HTTP/{$this->version} {$statusCode} {$this->statusText}");
378
        $this->sendCookies();
379
    }
380
381
    /**
382
     * Sends the cookies to the client.
383
     */
384
    protected function sendCookies()
385
    {
386
        if ($this->_cookies === null) {
387
            return;
388
        }
389
        $request = Yii::$app->getRequest();
390
        if ($request->enableCookieValidation) {
391
            if ($request->cookieValidationKey == '') {
392
                throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
393
            }
394
            $validationKey = $request->cookieValidationKey;
395
        }
396
        foreach ($this->getCookies() as $cookie) {
0 ignored issues
show
Bug introduced by
The expression $this->getCookies() of type object<yii\web\CookieCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
397
            $value = $cookie->value;
398
            if ($cookie->expire != 1  && isset($validationKey)) {
399
                $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
400
            }
401
            setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
402
        }
403
    }
404
405
    /**
406
     * Sends the response content to the client
407
     */
408 21
    protected function sendContent()
409
    {
410 21
        if ($this->stream === null) {
411 18
            echo $this->content;
412
413 18
            return;
414
        }
415
416 3
        set_time_limit(0); // Reset time limit for big files
417 3
        $chunkSize = 8 * 1024 * 1024; // 8MB per chunk
418
419 3
        if (is_array($this->stream)) {
420 3
            list ($handle, $begin, $end) = $this->stream;
421 3
            fseek($handle, $begin);
422 3
            while (!feof($handle) && ($pos = ftell($handle)) <= $end) {
423 3
                if ($pos + $chunkSize > $end) {
424 3
                    $chunkSize = $end - $pos + 1;
425 3
                }
426 3
                echo fread($handle, $chunkSize);
427 3
                flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
428 3
            }
429 3
            fclose($handle);
430 3
        } else {
431
            while (!feof($this->stream)) {
432
                echo fread($this->stream, $chunkSize);
433
                flush();
434
            }
435
            fclose($this->stream);
436
        }
437 3
    }
438
439
    /**
440
     * Sends a file to the browser.
441
     *
442
     * Note that this method only prepares the response for file sending. The file is not sent
443
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
444
     *
445
     * The following is an example implementation of a controller action that allows requesting files from a directory
446
     * that is not accessible from web:
447
     *
448
     * ```php
449
     * public function actionFile($filename)
450
     * {
451
     *     $storagePath = Yii::getAlias('@app/files');
452
     *
453
     *     // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
454
     *     if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
455
     *         throw new \yii\web\NotFoundHttpException('The file does not exists.');
456
     *     }
457
     *     return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
458
     * }
459
     * ```
460
     *
461
     * @param string $filePath the path of the file to be sent.
462
     * @param string $attachmentName the file name shown to the user. If null, it will be determined from `$filePath`.
463
     * @param array $options additional options for sending the file. The following options are supported:
464
     *
465
     *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
466
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
467
     *    meaning a download dialog will pop up.
468
     *
469
     * @return $this the response object itself
470
     * @see sendContentAsFile()
471
     * @see sendStreamAsFile()
472
     * @see xSendFile()
473
     */
474 7
    public function sendFile($filePath, $attachmentName = null, $options = [])
475
    {
476 7
        if (!isset($options['mimeType'])) {
477 7
            $options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath);
478 7
        }
479 7
        if ($attachmentName === null) {
480 7
            $attachmentName = basename($filePath);
481 7
        }
482 7
        $handle = fopen($filePath, 'rb');
483 7
        $this->sendStreamAsFile($handle, $attachmentName, $options);
484
485 3
        return $this;
486
    }
487
488
    /**
489
     * Sends the specified content as a file to the browser.
490
     *
491
     * Note that this method only prepares the response for file sending. The file is not sent
492
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
493
     *
494
     * @param string $content the content to be sent. The existing [[content]] will be discarded.
495
     * @param string $attachmentName the file name shown to the user.
496
     * @param array $options additional options for sending the file. The following options are supported:
497
     *
498
     *  - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
499
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
500
     *    meaning a download dialog will pop up.
501
     *
502
     * @return $this the response object itself
503
     * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
504
     * @see sendFile() for an example implementation.
505
     */
506 1
    public function sendContentAsFile($content, $attachmentName, $options = [])
507
    {
508 1
        $headers = $this->getHeaders();
509
510 1
        $contentLength = StringHelper::byteLength($content);
511 1
        $range = $this->getHttpRange($contentLength);
512
513 1
        if ($range === false) {
514
            $headers->set('Content-Range', "bytes */$contentLength");
515
            throw new RangeNotSatisfiableHttpException();
516
        }
517
518 1
        list($begin, $end) = $range;
519 1
        if ($begin != 0 || $end != $contentLength - 1) {
520
            $this->setStatusCode(206);
521
            $headers->set('Content-Range', "bytes $begin-$end/$contentLength");
522
            $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
523
        } else {
524 1
            $this->setStatusCode(200);
525 1
            $this->content = $content;
526
        }
527
528 1
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
529 1
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
530
531 1
        $this->format = self::FORMAT_RAW;
532
533 1
        return $this;
534
    }
535
536
    /**
537
     * Sends the specified stream 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 resource $handle the handle of the stream to be sent.
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
     *  - `fileSize`: the size of the content to stream this is useful when size of the content is known
550
     *    and the content is not seekable. Defaults to content size using `ftell()`.
551
     *    This option is available since version 2.0.4.
552
     *
553
     * @return $this the response object itself
554
     * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
555
     * @see sendFile() for an example implementation.
556
     */
557 7
    public function sendStreamAsFile($handle, $attachmentName, $options = [])
558
    {
559 7
        $headers = $this->getHeaders();
560 7
        if (isset($options['fileSize'])) {
561
            $fileSize = $options['fileSize'];
562
        } else {
563 7
            fseek($handle, 0, SEEK_END);
564 7
            $fileSize = ftell($handle);
565
        }
566
567 7
        $range = $this->getHttpRange($fileSize);
568 7
        if ($range === false) {
569 4
            $headers->set('Content-Range', "bytes */$fileSize");
570 4
            throw new RangeNotSatisfiableHttpException();
571
        }
572
573 3
        list($begin, $end) = $range;
574 3
        if ($begin != 0 || $end != $fileSize - 1) {
575 3
            $this->setStatusCode(206);
576 3
            $headers->set('Content-Range', "bytes $begin-$end/$fileSize");
577 3
        } else {
578
            $this->setStatusCode(200);
579
        }
580
581 3
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
582 3
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
583
584 3
        $this->format = self::FORMAT_RAW;
585 3
        $this->stream = [$handle, $begin, $end];
586
587 3
        return $this;
588
    }
589
590
    /**
591
     * Sets a default set of HTTP headers for file downloading purpose.
592
     * @param string $attachmentName the attachment file name
593
     * @param string $mimeType the MIME type for the response. If null, `Content-Type` header will NOT be set.
594
     * @param bool $inline whether the browser should open the file within the browser window. Defaults to false,
595
     * meaning a download dialog will pop up.
596
     * @param int $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set.
597
     * @return $this the response object itself
598
     */
599 4
    public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null)
600
    {
601 4
        $headers = $this->getHeaders();
602
603 4
        $disposition = $inline ? 'inline' : 'attachment';
604 4
        $headers->setDefault('Pragma', 'public')
605 4
            ->setDefault('Accept-Ranges', 'bytes')
606 4
            ->setDefault('Expires', '0')
607 4
            ->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
608 4
            ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
609
610 4
        if ($mimeType !== null) {
611 4
            $headers->setDefault('Content-Type', $mimeType);
612 4
        }
613
614 4
        if ($contentLength !== null) {
615 4
            $headers->setDefault('Content-Length', $contentLength);
616 4
        }
617
618 4
        return $this;
619
    }
620
621
    /**
622
     * Determines the HTTP range given in the request.
623
     * @param int $fileSize the size of the file that will be used to validate the requested HTTP range.
624
     * @return array|bool the range (begin, end), or false if the range request is invalid.
625
     */
626 8
    protected function getHttpRange($fileSize)
627
    {
628 8
        if (!isset($_SERVER['HTTP_RANGE']) || $_SERVER['HTTP_RANGE'] === '-') {
629 1
            return [0, $fileSize - 1];
630
        }
631 7
        if (!preg_match('/^bytes=(\d*)-(\d*)$/', $_SERVER['HTTP_RANGE'], $matches)) {
632 1
            return false;
633
        }
634 6
        if ($matches[1] === '') {
635 2
            $start = $fileSize - $matches[2];
636 2
            $end = $fileSize - 1;
637 6
        } elseif ($matches[2] !== '') {
638 2
            $start = $matches[1];
639 2
            $end = $matches[2];
640 2
            if ($end >= $fileSize) {
641
                $end = $fileSize - 1;
642
            }
643 2
        } else {
644 2
            $start = $matches[1];
645 2
            $end = $fileSize - 1;
646
        }
647 6
        if ($start < 0 || $start > $end) {
648 3
            return false;
649
        } else {
650 3
            return [$start, $end];
651
        }
652
    }
653
654
    /**
655
     * Sends existing file to a browser as a download using x-sendfile.
656
     *
657
     * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
658
     * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
659
     * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
660
     * increase in performance as the web application is allowed to terminate earlier while the webserver is
661
     * handling the request.
662
     *
663
     * The request is sent to the server through a special non-standard HTTP-header.
664
     * When the web server encounters the presence of such header it will discard all output and send the file
665
     * specified by that header using web server internals including all optimizations like caching-headers.
666
     *
667
     * As this header directive is non-standard different directives exists for different web servers applications:
668
     *
669
     * - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
670
     * - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
671
     * - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
672
     * - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
673
     * - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
674
     *
675
     * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
676
     * a proper xHeader should be sent.
677
     *
678
     * **Note**
679
     *
680
     * This option allows to download files that are not under web folders, and even files that are otherwise protected
681
     * (deny from all) like `.htaccess`.
682
     *
683
     * **Side effects**
684
     *
685
     * If this option is disabled by the web server, when this method is called a download configuration dialog
686
     * will open but the downloaded file will have 0 bytes.
687
     *
688
     * **Known issues**
689
     *
690
     * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
691
     * an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
692
     * is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
693
     *
694
     * **Example**
695
     *
696
     * ```php
697
     * Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
698
     * ```
699
     *
700
     * @param string $filePath file name with full path
701
     * @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
702
     * @param array $options additional options for sending the file. The following options are supported:
703
     *
704
     *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
705
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
706
     *    meaning a download dialog will pop up.
707
     *  - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
708
     *
709
     * @return $this the response object itself
710
     * @see sendFile()
711
     */
712
    public function xSendFile($filePath, $attachmentName = null, $options = [])
713
    {
714
        if ($attachmentName === null) {
715
            $attachmentName = basename($filePath);
716
        }
717
        if (isset($options['mimeType'])) {
718
            $mimeType = $options['mimeType'];
719
        } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
720
            $mimeType = 'application/octet-stream';
721
        }
722
        if (isset($options['xHeader'])) {
723
            $xHeader = $options['xHeader'];
724
        } else {
725
            $xHeader = 'X-Sendfile';
726
        }
727
728
        $disposition = empty($options['inline']) ? 'attachment' : 'inline';
729
        $this->getHeaders()
730
            ->setDefault($xHeader, $filePath)
731
            ->setDefault('Content-Type', $mimeType)
732
            ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
733
734
        $this->format = self::FORMAT_RAW;
735
736
        return $this;
737
    }
738
739
    /**
740
     * Returns Content-Disposition header value that is safe to use with both old and new browsers
741
     *
742
     * Fallback name:
743
     *
744
     * - Causes issues if contains non-ASCII characters with codes less than 32 or more than 126.
745
     * - Causes issues if contains urlencoded characters (starting with `%`) or `%` character. Some browsers interpret
746
     *   `filename="X"` as urlencoded name, some don't.
747
     * - Causes issues if contains path separator characters such as `\` or `/`.
748
     * - Since value is wrapped with `"`, it should be escaped as `\"`.
749
     * - Since input could contain non-ASCII characters, fallback is obtained by transliteration.
750
     *
751
     * UTF name:
752
     *
753
     * - Causes issues if contains path separator characters such as `\` or `/`.
754
     * - Should be urlencoded since headers are ASCII-only.
755
     * - Could be omitted if it exactly matches fallback name.
756
     *
757
     * @param string $disposition
758
     * @param string $attachmentName
759
     * @return string
760
     *
761
     * @since 2.0.10
762
     */
763 4
    protected function getDispositionHeaderValue($disposition, $attachmentName)
764
    {
765 4
        $fallbackName = str_replace('"', '\\"', str_replace(['%', '/', '\\'], '_', Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE)));
766 4
        $utfName = rawurlencode(str_replace(['%', '/', '\\'], '', $attachmentName));
767
768 4
        $dispositionHeader = "{$disposition}; filename=\"{$fallbackName}\"";
769 4
        if ($utfName !== $fallbackName) {
770
            $dispositionHeader .= "; filename*=utf-8''{$utfName}";
771
        }
772 4
        return $dispositionHeader;
773
    }
774
775
    /**
776
     * Redirects the browser to the specified URL.
777
     *
778
     * This method adds a "Location" header to the current response. Note that it does not send out
779
     * the header until [[send()]] is called. In a controller action you may use this method as follows:
780
     *
781
     * ```php
782
     * return Yii::$app->getResponse()->redirect($url);
783
     * ```
784
     *
785
     * In other places, if you want to send out the "Location" header immediately, you should use
786
     * the following code:
787
     *
788
     * ```php
789
     * Yii::$app->getResponse()->redirect($url)->send();
790
     * return;
791
     * ```
792
     *
793
     * In AJAX mode, this normally will not work as expected unless there are some
794
     * client-side JavaScript code handling the redirection. To help achieve this goal,
795
     * this method will send out a "X-Redirect" header instead of "Location".
796
     *
797
     * If you use the "yii" JavaScript module, it will handle the AJAX redirection as
798
     * described above. Otherwise, you should write the following JavaScript code to
799
     * handle the redirection:
800
     *
801
     * ```javascript
802
     * $document.ajaxComplete(function (event, xhr, settings) {
803
     *     var url = xhr && xhr.getResponseHeader('X-Redirect');
804
     *     if (url) {
805
     *         window.location = url;
806
     *     }
807
     * });
808
     * ```
809
     *
810
     * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
811
     *
812
     * - a string representing a URL (e.g. "http://example.com")
813
     * - a string representing a URL alias (e.g. "@example.com")
814
     * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`).
815
     *   Note that the route is with respect to the whole application, instead of relative to a controller or module.
816
     *   [[Url::to()]] will be used to convert the array into a URL.
817
     *
818
     * Any relative URL will be converted into an absolute one by prepending it with the host info
819
     * of the current request.
820
     *
821
     * @param int $statusCode the HTTP status code. Defaults to 302.
822
     * See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
823
     * for details about HTTP status code
824
     * @param bool $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true,
825
     * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser
826
     * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as
827
     * an AJAX/PJAX response, may NOT cause browser redirection.
828
     * Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent.
829
     * @return $this the response object itself
830
     */
831 3
    public function redirect($url, $statusCode = 302, $checkAjax = true)
832
    {
833 3
        if (is_array($url) && isset($url[0])) {
834
            // ensure the route is absolute
835 2
            $url[0] = '/' . ltrim($url[0], '/');
836 2
        }
837 3
        $url = Url::to($url);
838 3
        if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) {
839 3
            $url = Yii::$app->getRequest()->getHostInfo() . $url;
840 3
        }
841
842 3
        if ($checkAjax) {
843 3
            if (Yii::$app->getRequest()->getIsAjax()) {
844 1
                if (Yii::$app->getRequest()->getHeaders()->get('X-Ie-Redirect-Compatibility') !== null && $statusCode === 302) {
845
                    // Ajax 302 redirect in IE does not work. Change status code to 200. See https://github.com/yiisoft/yii2/issues/9670
846
                    $statusCode = 200;
847
                }
848 1
                if (Yii::$app->getRequest()->getIsPjax()) {
849
                    $this->getHeaders()->set('X-Pjax-Url', $url);
850
                } else {
851 1
                    $this->getHeaders()->set('X-Redirect', $url);
852
                }
853 1
            } else {
854 3
                $this->getHeaders()->set('Location', $url);
855
            }
856 3
        } else {
857
            $this->getHeaders()->set('Location', $url);
858
        }
859
860 3
        $this->setStatusCode($statusCode);
861
862 3
        return $this;
863
    }
864
865
    /**
866
     * Refreshes the current page.
867
     * The effect of this method call is the same as the user pressing the refresh button of his browser
868
     * (without re-posting data).
869
     *
870
     * In a controller action you may use this method like this:
871
     *
872
     * ```php
873
     * return Yii::$app->getResponse()->refresh();
874
     * ```
875
     *
876
     * @param string $anchor the anchor that should be appended to the redirection URL.
877
     * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
878
     * @return Response the response object itself
879
     */
880
    public function refresh($anchor = '')
881
    {
882
        return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
883
    }
884
885
    private $_cookies;
886
887
    /**
888
     * Returns the cookie collection.
889
     * Through the returned cookie collection, you add or remove cookies as follows,
890
     *
891
     * ```php
892
     * // add a cookie
893
     * $response->cookies->add(new Cookie([
894
     *     'name' => $name,
895
     *     'value' => $value,
896
     * ]);
897
     *
898
     * // remove a cookie
899
     * $response->cookies->remove('name');
900
     * // alternatively
901
     * unset($response->cookies['name']);
902
     * ```
903
     *
904
     * @return CookieCollection the cookie collection.
905
     */
906 33
    public function getCookies()
907
    {
908 33
        if ($this->_cookies === null) {
909 33
            $this->_cookies = new CookieCollection;
910 33
        }
911 33
        return $this->_cookies;
912
    }
913
914
    /**
915
     * @return bool whether this response has a valid [[statusCode]].
916
     */
917 29
    public function getIsInvalid()
918
    {
919 29
        return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
920
    }
921
922
    /**
923
     * @return bool whether this response is informational
924
     */
925
    public function getIsInformational()
926
    {
927
        return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
928
    }
929
930
    /**
931
     * @return bool whether this response is successful
932
     */
933
    public function getIsSuccessful()
934
    {
935
        return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
936
    }
937
938
    /**
939
     * @return bool whether this response is a redirection
940
     */
941 1
    public function getIsRedirection()
942
    {
943 1
        return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
944
    }
945
946
    /**
947
     * @return bool whether this response indicates a client error
948
     */
949
    public function getIsClientError()
950
    {
951
        return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
952
    }
953
954
    /**
955
     * @return bool whether this response indicates a server error
956
     */
957
    public function getIsServerError()
958
    {
959
        return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
960
    }
961
962
    /**
963
     * @return bool whether this response is OK
964
     */
965
    public function getIsOk()
966
    {
967
        return $this->getStatusCode() == 200;
968
    }
969
970
    /**
971
     * @return bool whether this response indicates the current request is forbidden
972
     */
973
    public function getIsForbidden()
974
    {
975
        return $this->getStatusCode() == 403;
976
    }
977
978
    /**
979
     * @return bool whether this response indicates the currently requested resource is not found
980
     */
981
    public function getIsNotFound()
982
    {
983
        return $this->getStatusCode() == 404;
984
    }
985
986
    /**
987
     * @return bool whether this response is empty
988
     */
989
    public function getIsEmpty()
990
    {
991
        return in_array($this->getStatusCode(), [201, 204, 304]);
992
    }
993
994
    /**
995
     * @return array the formatters that are supported by default
996
     */
997 140
    protected function defaultFormatters()
998
    {
999
        return [
1000 140
            self::FORMAT_HTML => 'yii\web\HtmlResponseFormatter',
1001 140
            self::FORMAT_XML => 'yii\web\XmlResponseFormatter',
1002 140
            self::FORMAT_JSON => 'yii\web\JsonResponseFormatter',
1003 140
            self::FORMAT_JSONP => [
1004 140
                'class' => 'yii\web\JsonResponseFormatter',
1005 140
                'useJsonp' => true,
1006 140
            ],
1007 140
        ];
1008
    }
1009
1010
    /**
1011
     * Prepares for sending the response.
1012
     * The default implementation will convert [[data]] into [[content]] and set headers accordingly.
1013
     * @throws InvalidConfigException if the formatter for the specified format is invalid or [[format]] is not supported
1014
     */
1015 21
    protected function prepare()
1016
    {
1017 21
        if ($this->stream !== null) {
1018 3
            return;
1019
        }
1020
1021 18
        if (isset($this->formatters[$this->format])) {
1022 17
            $formatter = $this->formatters[$this->format];
1023 17
            if (!is_object($formatter)) {
1024 17
                $this->formatters[$this->format] = $formatter = Yii::createObject($formatter);
1025 17
            }
1026 17
            if ($formatter instanceof ResponseFormatterInterface) {
1027 17
                $formatter->format($this);
1028 17
            } else {
1029
                throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
1030
            }
1031 18
        } elseif ($this->format === self::FORMAT_RAW) {
1032 1
            if ($this->data !== null) {
1033
                $this->content = $this->data;
1034
            }
1035 1
        } else {
1036
            throw new InvalidConfigException("Unsupported response format: {$this->format}");
1037
        }
1038
1039 18
        if (is_array($this->content)) {
1040
            throw new InvalidParamException('Response content must not be an array.');
1041 18
        } elseif (is_object($this->content)) {
1042
            if (method_exists($this->content, '__toString')) {
1043
                $this->content = $this->content->__toString();
1044
            } else {
1045
                throw new InvalidParamException('Response content must be a string or an object implementing __toString().');
1046
            }
1047
        }
1048 18
    }
1049
}
1050