Completed
Push — remove-yii-autoloader ( 560d61...5f8600 )
by Alexander
27:04 queued 23:12
created

Response::sendContent()   D

Complexity

Conditions 9
Paths 9

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 4.909
c 0
b 0
f 0
cc 9
eloc 25
nc 9
nop 0
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 Psr\Http\Message\ResponseInterface;
11
use Yii;
12
use yii\base\InvalidArgumentException;
13
use yii\base\InvalidConfigException;
14
use yii\helpers\FileHelper;
15
use yii\helpers\Inflector;
16
use yii\helpers\StringHelper;
17
use yii\helpers\Url;
18
use yii\http\CookieCollection;
19
use yii\http\HeaderCollection;
20
use yii\http\MemoryStream;
21
use yii\http\MessageTrait;
22
use yii\http\ResourceStream;
23
24
/**
25
 * The web Response class represents an HTTP response
26
 *
27
 * It holds the [[headers]], [[cookies]] and [[content]] that is to be sent to the client.
28
 * It also controls the HTTP [[statusCode|status code]].
29
 *
30
 * Response is configured as an application component in [[\yii\web\Application]] by default.
31
 * You can access that instance via `Yii::$app->response`.
32
 *
33
 * You can modify its configuration by adding an array to your application config under `components`
34
 * as it is shown in the following example:
35
 *
36
 * ```php
37
 * 'response' => [
38
 *     'format' => yii\web\Response::FORMAT_JSON,
39
 *     'charset' => 'UTF-8',
40
 *     // ...
41
 * ]
42
 * ```
43
 *
44
 * For more details and usage information on Response, see the [guide article on responses](guide:runtime-responses).
45
 *
46
 * @property CookieCollection $cookies The cookie collection. This property is read-only.
47
 * @property string $downloadHeaders The attachment file name. This property is write-only.
48
 * @property bool $isClientError Whether this response indicates a client error. This property is read-only.
49
 * @property bool $isEmpty Whether this response is empty. This property is read-only.
50
 * @property bool $isForbidden Whether this response indicates the current request is forbidden. This property
51
 * is read-only.
52
 * @property bool $isInformational Whether this response is informational. This property is read-only.
53
 * @property bool $isInvalid Whether this response has a valid [[statusCode]]. This property is read-only.
54
 * @property bool $isNotFound Whether this response indicates the currently requested resource is not found.
55
 * This property is read-only.
56
 * @property bool $isOk Whether this response is OK. This property is read-only.
57
 * @property bool $isRedirection Whether this response is a redirection. This property is read-only.
58
 * @property bool $isServerError Whether this response indicates a server error. This property is read-only.
59
 * @property bool $isSuccessful Whether this response is successful. This property is read-only.
60
 * @property int $statusCode The HTTP status code to send with the response.
61
 * @property \Exception|\Error $statusCodeByException The exception object. This property is write-only.
62
 * @property string $content body content string.
63
 *
64
 * @author Qiang Xue <[email protected]>
65
 * @author Carsten Brandt <[email protected]>
66
 * @since 2.0
67
 */
68
class Response extends \yii\base\Response implements ResponseInterface
69
{
70
    use MessageTrait;
71
72
    /**
73
     * @event ResponseEvent an event that is triggered at the beginning of [[send()]].
74
     */
75
    const EVENT_BEFORE_SEND = 'beforeSend';
76
    /**
77
     * @event ResponseEvent an event that is triggered at the end of [[send()]].
78
     */
79
    const EVENT_AFTER_SEND = 'afterSend';
80
    /**
81
     * @event ResponseEvent an event that is triggered right after [[prepare()]] is called in [[send()]].
82
     * You may respond to this event to filter the response content before it is sent to the client.
83
     */
84
    const EVENT_AFTER_PREPARE = 'afterPrepare';
85
    const FORMAT_RAW = 'raw';
86
    const FORMAT_HTML = 'html';
87
    const FORMAT_JSON = 'json';
88
    const FORMAT_JSONP = 'jsonp';
89
    const FORMAT_XML = 'xml';
90
91
    /**
92
     * @var string the response format. This determines how to convert [[data]] into [[content]]
93
     * when the latter is not set. The value of this property must be one of the keys declared in the [[formatters]] array.
94
     * By default, the following formats are supported:
95
     *
96
     * - [[FORMAT_RAW]]: the data will be treated as the response content without any conversion.
97
     *   No extra HTTP header will be added.
98
     * - [[FORMAT_HTML]]: the data will be treated as the response content without any conversion.
99
     *   The "Content-Type" header will set as "text/html".
100
     * - [[FORMAT_JSON]]: the data will be converted into JSON format, and the "Content-Type"
101
     *   header will be set as "application/json".
102
     * - [[FORMAT_JSONP]]: the data will be converted into JSONP format, and the "Content-Type"
103
     *   header will be set as "text/javascript". Note that in this case `$data` must be an array
104
     *   with "data" and "callback" elements. The former refers to the actual data to be sent,
105
     *   while the latter refers to the name of the JavaScript callback.
106
     * - [[FORMAT_XML]]: the data will be converted into XML format. Please refer to [[XmlResponseFormatter]]
107
     *   for more details.
108
     *
109
     * You may customize the formatting process or support additional formats by configuring [[formatters]].
110
     * @see formatters
111
     */
112
    public $format = self::FORMAT_HTML;
113
    /**
114
     * @var string the MIME type (e.g. `application/json`) from the request ACCEPT header chosen for this response.
115
     * This property is mainly set by [[\yii\filters\ContentNegotiator]].
116
     */
117
    public $acceptMimeType;
118
    /**
119
     * @var array the parameters (e.g. `['q' => 1, 'version' => '1.0']`) associated with the [[acceptMimeType|chosen MIME type]].
120
     * This is a list of name-value pairs associated with [[acceptMimeType]] from the ACCEPT HTTP header.
121
     * This property is mainly set by [[\yii\filters\ContentNegotiator]].
122
     */
123
    public $acceptParams = [];
124
    /**
125
     * @var array the formatters for converting data into the response content of the specified [[format]].
126
     * The array keys are the format names, and the array values are the corresponding configurations
127
     * for creating the formatter objects.
128
     * @see format
129
     * @see defaultFormatters
130
     */
131
    public $formatters = [];
132
    /**
133
     * @var mixed the original response data. When this is not null, it will be converted into [[content]]
134
     * according to [[format]] when the response is being sent out.
135
     * @see content
136
     */
137
    public $data;
138
    /**
139
     * @var array the stream range to be applied on [[send()]]. This should be an array of the begin position and the end position.
140
     * Note that when this property is set, the [[data]] property will be ignored by [[send()]].
141
     */
142
    public $bodyRange;
143
    /**
144
     * @var string the charset of the text response. If not set, it will use
145
     * the value of [[Application::charset]].
146
     */
147
    public $charset;
148
    /**
149
     * @var string the HTTP status description that comes together with the status code.
150
     * @see httpStatuses
151
     */
152
    public $reasonPhrase = 'OK';
153
    /**
154
     * @var bool whether the response has been sent. If this is true, calling [[send()]] will do nothing.
155
     */
156
    public $isSent = false;
157
    /**
158
     * @var array list of HTTP status codes and the corresponding texts
159
     */
160
    public static $httpStatuses = [
161
        100 => 'Continue',
162
        101 => 'Switching Protocols',
163
        102 => 'Processing',
164
        118 => 'Connection timed out',
165
        200 => 'OK',
166
        201 => 'Created',
167
        202 => 'Accepted',
168
        203 => 'Non-Authoritative',
169
        204 => 'No Content',
170
        205 => 'Reset Content',
171
        206 => 'Partial Content',
172
        207 => 'Multi-Status',
173
        208 => 'Already Reported',
174
        210 => 'Content Different',
175
        226 => 'IM Used',
176
        300 => 'Multiple Choices',
177
        301 => 'Moved Permanently',
178
        302 => 'Found',
179
        303 => 'See Other',
180
        304 => 'Not Modified',
181
        305 => 'Use Proxy',
182
        306 => 'Reserved',
183
        307 => 'Temporary Redirect',
184
        308 => 'Permanent Redirect',
185
        310 => 'Too many Redirect',
186
        400 => 'Bad Request',
187
        401 => 'Unauthorized',
188
        402 => 'Payment Required',
189
        403 => 'Forbidden',
190
        404 => 'Not Found',
191
        405 => 'Method Not Allowed',
192
        406 => 'Not Acceptable',
193
        407 => 'Proxy Authentication Required',
194
        408 => 'Request Time-out',
195
        409 => 'Conflict',
196
        410 => 'Gone',
197
        411 => 'Length Required',
198
        412 => 'Precondition Failed',
199
        413 => 'Request Entity Too Large',
200
        414 => 'Request-URI Too Long',
201
        415 => 'Unsupported Media Type',
202
        416 => 'Requested range unsatisfiable',
203
        417 => 'Expectation failed',
204
        418 => 'I\'m a teapot',
205
        421 => 'Misdirected Request',
206
        422 => 'Unprocessable entity',
207
        423 => 'Locked',
208
        424 => 'Method failure',
209
        425 => 'Unordered Collection',
210
        426 => 'Upgrade Required',
211
        428 => 'Precondition Required',
212
        429 => 'Too Many Requests',
213
        431 => 'Request Header Fields Too Large',
214
        449 => 'Retry With',
215
        450 => 'Blocked by Windows Parental Controls',
216
        451 => 'Unavailable For Legal Reasons',
217
        500 => 'Internal Server Error',
218
        501 => 'Not Implemented',
219
        502 => 'Bad Gateway or Proxy Error',
220
        503 => 'Service Unavailable',
221
        504 => 'Gateway Time-out',
222
        505 => 'HTTP Version not supported',
223
        507 => 'Insufficient storage',
224
        508 => 'Loop Detected',
225
        509 => 'Bandwidth Limit Exceeded',
226
        510 => 'Not Extended',
227
        511 => 'Network Authentication Required',
228
    ];
229
230
    /**
231
     * @var int the HTTP status code to send with the response.
232
     */
233
    private $_statusCode = 200;
234
235
236
    /**
237
     * Initializes this component.
238
     */
239
    public function init()
240
    {
241
        if ($this->charset === null) {
242
            $this->charset = Yii::$app->charset;
243
        }
244
        $this->formatters = array_merge($this->defaultFormatters(), $this->formatters);
245
    }
246
247
    /**
248
     * {@inheritdoc}
249
     */
250
    public function getStatusCode()
251
    {
252
        return $this->_statusCode;
253
    }
254
255
    /**
256
     * Sets the response status code.
257
     * This method will set the corresponding status text if `$text` is null.
258
     * @param int $code the status code
259
     * @param string $reasonPhrase the status text. If not set, it will be set automatically based on the status code.
260
     * @throws InvalidArgumentException if the status code is invalid.
261
     * @return $this the response object itself
262
     */
263
    public function setStatusCode($code, $reasonPhrase = null)
264
    {
265
        if ($code === null) {
266
            $code = 200;
267
        }
268
        $this->_statusCode = (int) $code;
269
        if ($this->getIsInvalid()) {
270
            throw new InvalidArgumentException("The HTTP status code is invalid: $code");
271
        }
272
        if (empty($reasonPhrase)) {
273
            $this->reasonPhrase = isset(static::$httpStatuses[$this->_statusCode]) ? static::$httpStatuses[$this->_statusCode] : '';
274
        } else {
275
            $this->reasonPhrase = $reasonPhrase;
276
        }
277
        return $this;
278
    }
279
280
    /**
281
     * {@inheritdoc}
282
     */
283
    public function withStatus($code, $reasonPhrase = '')
284
    {
285
        if ($this->getStatusCode() === $code && $this->reasonPhrase === $reasonPhrase) {
286
            return $this;
287
        }
288
289
        $newInstance = clone $this;
290
        $newInstance->setStatusCode($code, $reasonPhrase);
291
        return $newInstance;
292
    }
293
294
    /**
295
     * {@inheritdoc}
296
     */
297
    public function getReasonPhrase()
298
    {
299
        return $this->reasonPhrase;
300
    }
301
302
    /**
303
     * Sets the response status code based on the exception.
304
     * @param \Exception|\Error $e the exception object.
305
     * @throws InvalidArgumentException if the status code is invalid.
306
     * @return $this the response object itself
307
     * @since 2.0.12
308
     */
309
    public function setStatusCodeByException($e)
310
    {
311
        if ($e instanceof HttpException) {
312
            $this->setStatusCode($e->statusCode);
313
        } else {
314
            $this->setStatusCode(500);
315
        }
316
        return $this;
317
    }
318
319
    /**
320
     * @return string body content string.
321
     * @since 2.1.0
322
     */
323
    public function getContent()
324
    {
325
        return $this->getBody()->__toString();
326
    }
327
328
    /**
329
     * @param string $content body content string.
330
     * @since 2.1.0
331
     */
332
    public function setContent($content)
333
    {
334
        $body = new MemoryStream();
335
        $body->write($content);
336
        $this->setBody($body);
337
    }
338
339
    /**
340
     * Sends the response to the client.
341
     */
342
    public function send()
343
    {
344
        if ($this->isSent) {
345
            return;
346
        }
347
        $this->trigger(self::EVENT_BEFORE_SEND);
348
        $this->prepare();
349
        $this->trigger(self::EVENT_AFTER_PREPARE);
350
        $this->sendHeaders();
351
        $this->sendContent();
352
        $this->trigger(self::EVENT_AFTER_SEND);
353
        $this->isSent = true;
354
    }
355
356
    /**
357
     * Clears the headers, cookies, content, status code of the response.
358
     */
359
    public function clear()
360
    {
361
        $this->_headerCollection = null;
362
        $this->_cookies = null;
363
        $this->_statusCode = 200;
364
        $this->reasonPhrase = 'OK';
365
        $this->data = null;
366
        $this->bodyRange = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $bodyRange.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
367
        $this->isSent = false;
368
        $this->setBody(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object<Psr\Http\Message\...>|object<Closure>|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
369
    }
370
371
    /**
372
     * Sends the response headers to the client
373
     */
374
    protected function sendHeaders()
375
    {
376
        if (headers_sent()) {
377
            return;
378
        }
379
        if ($this->_headerCollection) {
380
            $headers = $this->getHeaders();
381
            foreach ($headers as $name => $values) {
382
                $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
383
                // set replace for first occurrence of header but false afterwards to allow multiple
384
                $replace = true;
385
                foreach ($values as $value) {
386
                    header("$name: $value", $replace);
387
                    $replace = false;
388
                }
389
            }
390
        }
391
        $statusCode = $this->getStatusCode();
392
        $protocolVersion = $this->getProtocolVersion();
393
        header("HTTP/{$protocolVersion} {$statusCode} {$this->reasonPhrase}");
394
        $this->sendCookies();
395
    }
396
397
    /**
398
     * Sends the cookies to the client.
399
     */
400
    protected function sendCookies()
401
    {
402
        if ($this->_cookies === null) {
403
            return;
404
        }
405
        $request = Yii::$app->getRequest();
406
        if ($request->enableCookieValidation) {
407
            if ($request->cookieValidationKey == '') {
408
                throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
409
            }
410
            $validationKey = $request->cookieValidationKey;
411
        }
412
        foreach ($this->getCookies() as $cookie) {
0 ignored issues
show
Bug introduced by
The expression $this->getCookies() of type object<yii\http\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...
413
            $value = $cookie->value;
414
            if ($cookie->expire != 1 && isset($validationKey)) {
415
                $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
416
            }
417
            setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
418
        }
419
    }
420
421
    /**
422
     * Sends the response content to the client
423
     */
424
    protected function sendContent()
425
    {
426
        $body = $this->getBody();
427
        if (!$body->isReadable()) {
428
            throw new \RuntimeException('Unable to send content: body stream is not readable.');
429
        }
430
431
        set_time_limit(0); // Reset time limit for big files
432
        $chunkSize = 8 * 1024 * 1024; // 8MB per chunk
433
434
        if (is_array($this->bodyRange)) {
435
            [$begin, $end] = $this->bodyRange;
0 ignored issues
show
Bug introduced by
The variable $begin does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $end does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
436
437
            if (!$body->isSeekable()) {
438
                throw new \RuntimeException('Unable to send content in range: body stream is not seekable.');
439
            }
440
441
            $body->seek($begin);
442
            while (!$body->eof() && ($pos = $body->tell()) <= $end) {
443
                if ($pos + $chunkSize > $end) {
444
                    $chunkSize = $end - $pos + 1;
445
                }
446
                echo $body->read($chunkSize);
447
                flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
448
            }
449
            $body->close();
450
        } else {
451
            if ($body->isSeekable()) {
452
                $body->seek(0);
453
            }
454
            while (!$body->eof()) {
455
                echo $body->read($chunkSize);
456
                flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
457
            }
458
            $body->close();
459
            return;
460
        }
461
    }
462
463
    /**
464
     * Sends a file to the browser.
465
     *
466
     * Note that this method only prepares the response for file sending. The file is not sent
467
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
468
     *
469
     * The following is an example implementation of a controller action that allows requesting files from a directory
470
     * that is not accessible from web:
471
     *
472
     * ```php
473
     * public function actionFile($filename)
474
     * {
475
     *     $storagePath = Yii::getAlias('@app/files');
476
     *
477
     *     // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
478
     *     if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
479
     *         throw new \yii\web\NotFoundHttpException('The file does not exists.');
480
     *     }
481
     *     return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
482
     * }
483
     * ```
484
     *
485
     * @param string $filePath the path of the file to be sent.
486
     * @param string $attachmentName the file name shown to the user. If null, it will be determined from `$filePath`.
487
     * @param array $options additional options for sending the file. The following options are supported:
488
     *
489
     *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
490
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
491
     *    meaning a download dialog will pop up.
492
     *
493
     * @return $this the response object itself
494
     * @see sendContentAsFile()
495
     * @see sendStreamAsFile()
496
     * @see xSendFile()
497
     */
498
    public function sendFile($filePath, $attachmentName = null, $options = [])
499
    {
500
        if (!isset($options['mimeType'])) {
501
            $options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath);
502
        }
503
        if ($attachmentName === null) {
504
            $attachmentName = basename($filePath);
505
        }
506
        $handle = fopen($filePath, 'rb');
507
        $this->sendStreamAsFile($handle, $attachmentName, $options);
508
509
        return $this;
510
    }
511
512
    /**
513
     * Sends the specified content as a file to the browser.
514
     *
515
     * Note that this method only prepares the response for file sending. The file is not sent
516
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
517
     *
518
     * @param string $content the content to be sent. The existing [[content]] will be discarded.
519
     * @param string $attachmentName the file name shown to the user.
520
     * @param array $options additional options for sending the file. The following options are supported:
521
     *
522
     *  - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
523
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
524
     *    meaning a download dialog will pop up.
525
     *
526
     * @return $this the response object itself
527
     * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
528
     * @see sendFile() for an example implementation.
529
     */
530
    public function sendContentAsFile($content, $attachmentName, $options = [])
531
    {
532
        $contentLength = StringHelper::byteLength($content);
533
        $range = $this->getHttpRange($contentLength);
534
535
        if ($range === false) {
536
            $this->setHeader('Content-Range', "bytes */$contentLength");
537
            throw new RangeNotSatisfiableHttpException();
538
        }
539
540
        [$begin, $end] = $range;
0 ignored issues
show
Bug introduced by
The variable $begin does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $end does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
541
        $body = new MemoryStream();
542
        if ($begin != 0 || $end != $contentLength - 1) {
543
            $this->setStatusCode(206);
544
            $this->setHeader('Content-Range', "bytes $begin-$end/$contentLength");
545
            $body->write(StringHelper::byteSubstr($content, $begin, $end - $begin + 1));
546
        } else {
547
            $this->setStatusCode(200);
548
            $body->write($content);
549
        }
550
551
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
552
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
553
554
        $this->format = self::FORMAT_RAW;
555
        $this->setBody($body);
556
        return $this;
557
    }
558
559
    /**
560
     * Sends the specified stream as a file to the browser.
561
     *
562
     * Note that this method only prepares the response for file sending. The file is not sent
563
     * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
564
     *
565
     * @param resource $handle the handle of the stream to be sent.
566
     * @param string $attachmentName the file name shown to the user.
567
     * @param array $options additional options for sending the file. The following options are supported:
568
     *
569
     *  - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
570
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
571
     *    meaning a download dialog will pop up.
572
     *  - `fileSize`: the size of the content to stream this is useful when size of the content is known
573
     *    and the content is not seekable. Defaults to content size using `ftell()`.
574
     *    This option is available since version 2.0.4.
575
     *
576
     * @return $this the response object itself
577
     * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
578
     * @see sendFile() for an example implementation.
579
     */
580
    public function sendStreamAsFile($handle, $attachmentName, $options = [])
581
    {
582
        if (isset($options['fileSize'])) {
583
            $fileSize = $options['fileSize'];
584
        } else {
585
            fseek($handle, 0, SEEK_END);
586
            $fileSize = ftell($handle);
587
        }
588
589
        $range = $this->getHttpRange($fileSize);
590
        if ($range === false) {
591
            $this->setHeader('Content-Range', "bytes */$fileSize");
592
            throw new RangeNotSatisfiableHttpException();
593
        }
594
595
        [$begin, $end] = $range;
0 ignored issues
show
Bug introduced by
The variable $begin does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $end does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
596
        if ($begin != 0 || $end != $fileSize - 1) {
597
            $this->setStatusCode(206);
598
            $this->setHeader('Content-Range', "bytes $begin-$end/$fileSize");
599
        } else {
600
            $this->setStatusCode(200);
601
        }
602
603
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
604
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
605
606
        $this->format = self::FORMAT_RAW;
607
        $this->bodyRange = [$begin, $end];
608
609
        $body = new ResourceStream();
610
        $body->resource = $handle;
611
612
        $this->setBody($body);
613
        return $this;
614
    }
615
616
    /**
617
     * Sets a default set of HTTP headers for file downloading purpose.
618
     * @param string $attachmentName the attachment file name
619
     * @param string $mimeType the MIME type for the response. If null, `Content-Type` header will NOT be set.
620
     * @param bool $inline whether the browser should open the file within the browser window. Defaults to false,
621
     * meaning a download dialog will pop up.
622
     * @param int $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set.
623
     * @return $this the response object itself
624
     */
625
    public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null)
626
    {
627
        $disposition = $inline ? 'inline' : 'attachment';
628
629
        $headers = [
630
            'Pragma' => 'public',
631
            'Accept-Ranges' => 'bytes',
632
            'Expires' => '0',
633
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
634
            'Content-Disposition' => $this->getDispositionHeaderValue($disposition, $attachmentName),
635
        ];
636
637
        if ($mimeType !== null) {
638
            $headers['Content-Type'] = $mimeType;
639
        }
640
641
        if ($contentLength !== null) {
642
            $headers['Content-Length'] = $contentLength;
643
        }
644
645
        foreach ($headers as $name => $value) {
646
            if (!$this->hasHeader($name)) {
647
                $this->setHeader($name, $value);
648
            }
649
        }
650
651
        return $this;
652
    }
653
654
    /**
655
     * Determines the HTTP range given in the request.
656
     * @param int $fileSize the size of the file that will be used to validate the requested HTTP range.
657
     * @return array|bool the range (begin, end), or false if the range request is invalid.
658
     */
659
    protected function getHttpRange($fileSize)
660
    {
661
        if (!isset($_SERVER['HTTP_RANGE']) || $_SERVER['HTTP_RANGE'] === '-') {
662
            return [0, $fileSize - 1];
663
        }
664
        if (!preg_match('/^bytes=(\d*)-(\d*)$/', $_SERVER['HTTP_RANGE'], $matches)) {
665
            return false;
666
        }
667
        if ($matches[1] === '') {
668
            $start = $fileSize - $matches[2];
669
            $end = $fileSize - 1;
670
        } elseif ($matches[2] !== '') {
671
            $start = $matches[1];
672
            $end = $matches[2];
673
            if ($end >= $fileSize) {
674
                $end = $fileSize - 1;
675
            }
676
        } else {
677
            $start = $matches[1];
678
            $end = $fileSize - 1;
679
        }
680
        if ($start < 0 || $start > $end) {
681
            return false;
682
        }
683
684
        return [$start, $end];
685
    }
686
687
    /**
688
     * Sends existing file to a browser as a download using x-sendfile.
689
     *
690
     * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
691
     * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
692
     * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
693
     * increase in performance as the web application is allowed to terminate earlier while the webserver is
694
     * handling the request.
695
     *
696
     * The request is sent to the server through a special non-standard HTTP-header.
697
     * When the web server encounters the presence of such header it will discard all output and send the file
698
     * specified by that header using web server internals including all optimizations like caching-headers.
699
     *
700
     * As this header directive is non-standard different directives exists for different web servers applications:
701
     *
702
     * - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
703
     * - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
704
     * - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
705
     * - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
706
     * - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
707
     *
708
     * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
709
     * a proper xHeader should be sent.
710
     *
711
     * **Note**
712
     *
713
     * This option allows to download files that are not under web folders, and even files that are otherwise protected
714
     * (deny from all) like `.htaccess`.
715
     *
716
     * **Side effects**
717
     *
718
     * If this option is disabled by the web server, when this method is called a download configuration dialog
719
     * will open but the downloaded file will have 0 bytes.
720
     *
721
     * **Known issues**
722
     *
723
     * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
724
     * an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
725
     * is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
726
     *
727
     * **Example**
728
     *
729
     * ```php
730
     * Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
731
     * ```
732
     *
733
     * @param string $filePath file name with full path
734
     * @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
735
     * @param array $options additional options for sending the file. The following options are supported:
736
     *
737
     *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
738
     *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
739
     *    meaning a download dialog will pop up.
740
     *  - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
741
     *
742
     * @return $this the response object itself
743
     * @see sendFile()
744
     */
745
    public function xSendFile($filePath, $attachmentName = null, $options = [])
746
    {
747
        if ($attachmentName === null) {
748
            $attachmentName = basename($filePath);
749
        }
750
        if (isset($options['mimeType'])) {
751
            $mimeType = $options['mimeType'];
752
        } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
753
            $mimeType = 'application/octet-stream';
754
        }
755
        if (isset($options['xHeader'])) {
756
            $xHeader = $options['xHeader'];
757
        } else {
758
            $xHeader = 'X-Sendfile';
759
        }
760
761
        $disposition = empty($options['inline']) ? 'attachment' : 'inline';
762
763
        $headers = [
764
            $xHeader => $filePath,
765
            'Content-Type' => $mimeType,
766
            'Content-Disposition' => $this->getDispositionHeaderValue($disposition, $attachmentName),
767
        ];
768
769
        foreach ($headers as $name => $value) {
770
            if (!$this->hasHeader($name)) {
771
                $this->setHeader($name, $value);
772
            }
773
        }
774
775
        $this->format = self::FORMAT_RAW;
776
777
        return $this;
778
    }
779
780
    /**
781
     * Returns Content-Disposition header value that is safe to use with both old and new browsers
782
     *
783
     * Fallback name:
784
     *
785
     * - Causes issues if contains non-ASCII characters with codes less than 32 or more than 126.
786
     * - Causes issues if contains urlencoded characters (starting with `%`) or `%` character. Some browsers interpret
787
     *   `filename="X"` as urlencoded name, some don't.
788
     * - Causes issues if contains path separator characters such as `\` or `/`.
789
     * - Since value is wrapped with `"`, it should be escaped as `\"`.
790
     * - Since input could contain non-ASCII characters, fallback is obtained by transliteration.
791
     *
792
     * UTF name:
793
     *
794
     * - Causes issues if contains path separator characters such as `\` or `/`.
795
     * - Should be urlencoded since headers are ASCII-only.
796
     * - Could be omitted if it exactly matches fallback name.
797
     *
798
     * @param string $disposition
799
     * @param string $attachmentName
800
     * @return string
801
     *
802
     * @since 2.0.10
803
     */
804
    protected function getDispositionHeaderValue($disposition, $attachmentName)
805
    {
806
        $fallbackName = str_replace('"', '\\"', str_replace(['%', '/', '\\'], '_', Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE)));
807
        $utfName = rawurlencode(str_replace(['%', '/', '\\'], '', $attachmentName));
808
809
        $dispositionHeader = "{$disposition}; filename=\"{$fallbackName}\"";
810
        if ($utfName !== $fallbackName) {
811
            $dispositionHeader .= "; filename*=utf-8''{$utfName}";
812
        }
813
        return $dispositionHeader;
814
    }
815
816
    /**
817
     * Redirects the browser to the specified URL.
818
     *
819
     * This method adds a "Location" header to the current response. Note that it does not send out
820
     * the header until [[send()]] is called. In a controller action you may use this method as follows:
821
     *
822
     * ```php
823
     * return Yii::$app->getResponse()->redirect($url);
824
     * ```
825
     *
826
     * In other places, if you want to send out the "Location" header immediately, you should use
827
     * the following code:
828
     *
829
     * ```php
830
     * Yii::$app->getResponse()->redirect($url)->send();
831
     * return;
832
     * ```
833
     *
834
     * In AJAX mode, this normally will not work as expected unless there are some
835
     * client-side JavaScript code handling the redirection. To help achieve this goal,
836
     * this method will send out a "X-Redirect" header instead of "Location".
837
     *
838
     * If you use the "yii" JavaScript module, it will handle the AJAX redirection as
839
     * described above. Otherwise, you should write the following JavaScript code to
840
     * handle the redirection:
841
     *
842
     * ```javascript
843
     * $document.ajaxComplete(function (event, xhr, settings) {
844
     *     var url = xhr && xhr.getResponseHeader('X-Redirect');
845
     *     if (url) {
846
     *         window.location = url;
847
     *     }
848
     * });
849
     * ```
850
     *
851
     * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
852
     *
853
     * - a string representing a URL (e.g. "http://example.com")
854
     * - a string representing a URL alias (e.g. "@example.com")
855
     * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`).
856
     *   Note that the route is with respect to the whole application, instead of relative to a controller or module.
857
     *   [[Url::to()]] will be used to convert the array into a URL.
858
     *
859
     * Any relative URL that starts with a single forward slash "/" will be converted
860
     * into an absolute one by prepending it with the host info of the current request.
861
     *
862
     * @param int $statusCode the HTTP status code. Defaults to 302.
863
     * See <https://tools.ietf.org/html/rfc2616#section-10>
864
     * for details about HTTP status code
865
     * @param bool $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true,
866
     * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser
867
     * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as
868
     * an AJAX/PJAX response, may NOT cause browser redirection.
869
     * Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent.
870
     * @return $this the response object itself
871
     */
872
    public function redirect($url, $statusCode = 302, $checkAjax = true)
873
    {
874
        if (is_array($url) && isset($url[0])) {
875
            // ensure the route is absolute
876
            $url[0] = '/' . ltrim($url[0], '/');
877
        }
878
        $url = Url::to($url);
879
        if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) {
880
            $url = Yii::$app->getRequest()->getHostInfo() . $url;
881
        }
882
883
        if ($checkAjax) {
884
            if (Yii::$app->getRequest()->getIsAjax()) {
885
                if (Yii::$app->getRequest()->hasHeader('X-Ie-Redirect-Compatibility') && $statusCode === 302) {
886
                    // Ajax 302 redirect in IE does not work. Change status code to 200. See https://github.com/yiisoft/yii2/issues/9670
887
                    $statusCode = 200;
888
                }
889
                if (Yii::$app->getRequest()->getIsPjax()) {
890
                    $this->setHeader('X-Pjax-Url', $url);
891
                } else {
892
                    $this->setHeader('X-Redirect', $url);
893
                }
894
            } else {
895
                $this->setHeader('Location', $url);
896
            }
897
        } else {
898
            $this->setHeader('Location', $url);
899
        }
900
901
        $this->setStatusCode($statusCode);
902
903
        return $this;
904
    }
905
906
    /**
907
     * Refreshes the current page.
908
     * The effect of this method call is the same as the user pressing the refresh button of his browser
909
     * (without re-posting data).
910
     *
911
     * In a controller action you may use this method like this:
912
     *
913
     * ```php
914
     * return Yii::$app->getResponse()->refresh();
915
     * ```
916
     *
917
     * @param string $anchor the anchor that should be appended to the redirection URL.
918
     * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
919
     * @return Response the response object itself
920
     */
921
    public function refresh($anchor = '')
922
    {
923
        return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
924
    }
925
926
    private $_cookies;
927
928
    /**
929
     * Returns the cookie collection.
930
     * Through the returned cookie collection, you add or remove cookies as follows,
931
     *
932
     * ```php
933
     * // add a cookie
934
     * $response->cookies->add(new Cookie([
935
     *     'name' => $name,
936
     *     'value' => $value,
937
     * ]);
938
     *
939
     * // remove a cookie
940
     * $response->cookies->remove('name');
941
     * // alternatively
942
     * unset($response->cookies['name']);
943
     * ```
944
     *
945
     * @return CookieCollection the cookie collection.
946
     */
947
    public function getCookies()
948
    {
949
        if ($this->_cookies === null) {
950
            $this->_cookies = new CookieCollection();
951
        }
952
        return $this->_cookies;
953
    }
954
955
    /**
956
     * @return bool whether this response has a valid [[statusCode]].
957
     */
958
    public function getIsInvalid()
959
    {
960
        return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
961
    }
962
963
    /**
964
     * @return bool whether this response is informational
965
     */
966
    public function getIsInformational()
967
    {
968
        return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
969
    }
970
971
    /**
972
     * @return bool whether this response is successful
973
     */
974
    public function getIsSuccessful()
975
    {
976
        return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
977
    }
978
979
    /**
980
     * @return bool whether this response is a redirection
981
     */
982
    public function getIsRedirection()
983
    {
984
        return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
985
    }
986
987
    /**
988
     * @return bool whether this response indicates a client error
989
     */
990
    public function getIsClientError()
991
    {
992
        return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
993
    }
994
995
    /**
996
     * @return bool whether this response indicates a server error
997
     */
998
    public function getIsServerError()
999
    {
1000
        return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
1001
    }
1002
1003
    /**
1004
     * @return bool whether this response is OK
1005
     */
1006
    public function getIsOk()
1007
    {
1008
        return $this->getStatusCode() == 200;
1009
    }
1010
1011
    /**
1012
     * @return bool whether this response indicates the current request is forbidden
1013
     */
1014
    public function getIsForbidden()
1015
    {
1016
        return $this->getStatusCode() == 403;
1017
    }
1018
1019
    /**
1020
     * @return bool whether this response indicates the currently requested resource is not found
1021
     */
1022
    public function getIsNotFound()
1023
    {
1024
        return $this->getStatusCode() == 404;
1025
    }
1026
1027
    /**
1028
     * @return bool whether this response is empty
1029
     */
1030
    public function getIsEmpty()
1031
    {
1032
        return in_array($this->getStatusCode(), [201, 204, 304]);
1033
    }
1034
1035
    /**
1036
     * @return array the formatters that are supported by default
1037
     */
1038
    protected function defaultFormatters()
1039
    {
1040
        return [
1041
            self::FORMAT_HTML => [
1042
                'class' => HtmlResponseFormatter::class,
1043
            ],
1044
            self::FORMAT_XML => [
1045
                'class' => XmlResponseFormatter::class,
1046
            ],
1047
            self::FORMAT_JSON => [
1048
                'class' => JsonResponseFormatter::class,
1049
            ],
1050
            self::FORMAT_JSONP => [
1051
                'class' => JsonResponseFormatter::class,
1052
                'useJsonp' => true,
1053
            ],
1054
        ];
1055
    }
1056
1057
    /**
1058
     * Prepares for sending the response.
1059
     * The default implementation will convert [[data]] into [[content]] and set headers accordingly.
1060
     * @throws InvalidConfigException if the formatter for the specified format is invalid or [[format]] is not supported
1061
     */
1062
    protected function prepare()
1063
    {
1064
        if ($this->bodyRange !== null) {
1065
            return;
1066
        }
1067
1068
        if (isset($this->formatters[$this->format])) {
1069
            $formatter = $this->formatters[$this->format];
1070
            if (!is_object($formatter)) {
1071
                $this->formatters[$this->format] = $formatter = Yii::createObject($formatter);
1072
            }
1073
            if ($formatter instanceof ResponseFormatterInterface) {
1074
                $formatter->format($this);
1075
                return;
1076
            }
1077
            throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
1078
        } elseif ($this->format !== self::FORMAT_RAW) {
1079
            throw new InvalidConfigException("Unsupported response format: {$this->format}");
1080
        }
1081
1082
        if ($this->data !== null) {
1083
            if (is_array($this->data)) {
1084
                throw new InvalidArgumentException('Response raw data must not be an array.');
1085
            } elseif (is_object($this->data)) {
1086
                if (method_exists($this->data, '__toString')) {
1087
                    $content = $this->data->__toString();
1088
                } else {
1089
                    throw new InvalidArgumentException('Response raw data must be a string or an object implementing '
1090
                        . ' __toString().');
1091
                }
1092
            } else {
1093
                $content = $this->data;
1094
            }
1095
1096
            $body = new MemoryStream();
1097
            $body->write($content);
1098
            $this->setBody($body);
1099
        }
1100
    }
1101
1102
    /**
1103
     * {@inheritdoc}
1104
     */
1105
    public function __clone()
1106
    {
1107
        parent::__clone();
1108
1109
        $this->cloneHttpMessageInternals();
1110
1111
        if (is_object($this->_cookies)) {
1112
            $this->_cookies = clone $this->_cookies;
1113
        }
1114
    }
1115
}
1116