GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 3bd813...b7079d )
by Robert
13:06
created

Response::getHttpRange()   C

Complexity

Conditions 8
Paths 10

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 8

Importance

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