Completed
Push — remove-intl-polyfills ( 129df4...a6e727 )
by Alexander
16:22 queued 12:49
created

Request::getQueryParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
ccs 4
cts 4
cp 1
cc 2
eloc 4
nc 2
nop 0
crap 2
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\ServerRequestInterface;
11
use Psr\Http\Message\StreamInterface;
12
use Psr\Http\Message\UploadedFileInterface;
13
use Psr\Http\Message\UriInterface;
14
use Yii;
15
use yii\base\InvalidConfigException;
16
use yii\di\Instance;
17
use yii\helpers\ArrayHelper;
18
use yii\http\Cookie;
19
use yii\http\CookieCollection;
20
use yii\http\FileStream;
21
use yii\http\MemoryStream;
22
use yii\http\MessageTrait;
23
use yii\http\UploadedFile;
24
use yii\http\Uri;
25
use yii\validators\IpValidator;
26
27
/**
28
 * The web Request class represents an HTTP request.
29
 *
30
 * It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.
31
 * Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST
32
 * parameters sent via other HTTP methods like PUT or DELETE.
33
 *
34
 * Request is configured as an application component in [[\yii\web\Application]] by default.
35
 * You can access that instance via `Yii::$app->request`.
36
 *
37
 * For more details and usage information on Request, see the [guide article on requests](guide:runtime-requests).
38
 *
39
 * @property string $absoluteUrl The currently requested absolute URL. This property is read-only.
40
 * @property array $acceptableContentTypes The content types ordered by the quality score. Types with the
41
 * highest scores will be returned first. The array keys are the content types, while the array values are the
42
 * corresponding quality score and other parameters as given in the header.
43
 * @property array $acceptableLanguages The languages ordered by the preference level. The first element
44
 * represents the most preferred language.
45
 * @property string|null $authPassword The password sent via HTTP authentication, null if the password is not
46
 * given. This property is read-only.
47
 * @property string|null $authUser The username sent via HTTP authentication, null if the username is not
48
 * given. This property is read-only.
49
 * @property string $baseUrl The relative URL for the application.
50
 * @property array $parsedBody The request parameters given in the request body.
51
 * @property string $contentType Request content-type. Null is returned if this information is not available.
52
 * This property is read-only.
53
 * @property CookieCollection $cookies The cookie collection. This property is read-only.
54
 * @property string $csrfToken The token used to perform CSRF validation. This property is read-only.
55
 * @property string $csrfTokenFromHeader The CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned
56
 * if no such header is sent. This property is read-only.
57
 * @property array $eTags The entity tags. This property is read-only.
58
 * @property string|null $hostInfo Schema and hostname part (with port number if needed) of the request URL
59
 * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. See
60
 * [[getHostInfo()]] for security related notes on this property.
61
 * @property string|null $hostName Hostname part of the request URL (e.g. `www.yiiframework.com`). This
62
 * property is read-only.
63
 * @property bool $isAjax Whether this is an AJAX (XMLHttpRequest) request. This property is read-only.
64
 * @property bool $isDelete Whether this is a DELETE request. This property is read-only.
65
 * @property bool $isFlash Whether this is an Adobe Flash or Adobe Flex request. This property is read-only.
66
 * @property bool $isGet Whether this is a GET request. This property is read-only.
67
 * @property bool $isHead Whether this is a HEAD request. This property is read-only.
68
 * @property bool $isOptions Whether this is a OPTIONS request. This property is read-only.
69
 * @property bool $isPatch Whether this is a PATCH request. This property is read-only.
70
 * @property bool $isPost Whether this is a POST request. This property is read-only.
71
 * @property bool $isPut Whether this is a PUT request. This property is read-only.
72
 * @property bool $isSecureConnection If the request is sent via secure channel (https). This property is
73
 * read-only.
74
 * @property string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is
75
 * turned into upper case.
76
 * @property UriInterface $uri the URI instance.
77
 * @property mixed $requestTarget the message's request target.
78
 * @property string $pathInfo Part of the request URL that is after the entry script and before the question
79
 * mark. Note, the returned path info is already URL-decoded.
80
 * @property int $port Port number for insecure requests.
81
 * @property array $queryParams The request GET parameter values.
82
 * @property string $queryString Part of the request URL that is after the question mark. This property is
83
 * read-only.
84
 * @property string $rawBody The request body.
85
 * @property string|null $referrer URL referrer, null if not available. This property is read-only.
86
 * @property string|null $origin URL origin, null if not available. This property is read-only.
87
 * @property string $scriptFile The entry script file path.
88
 * @property string $scriptUrl The relative URL of the entry script.
89
 * @property int $securePort Port number for secure requests.
90
 * @property string $serverName Server name, null if not available. This property is read-only.
91
 * @property int|null $serverPort Server port number, null if not available. This property is read-only.
92
 * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded
93
 * depending on the client.
94
 * @property array $uploadedFiles Uploaded files for this request. See [[getUploadedFiles()]] for details.
95
 * @property string|null $userAgent User agent, null if not available. This property is read-only.
96
 * @property string|null $userHost User host name, null if not available. This property is read-only.
97
 * @property string|null $userIP User IP address, null if not available. This property is read-only.
98
 *
99
 * @author Qiang Xue <[email protected]>
100
 * @since 2.0
101
 * @SuppressWarnings(PHPMD.SuperGlobals)
102
 */
103
class Request extends \yii\base\Request implements ServerRequestInterface
104
{
105
    use MessageTrait;
106
107
    /**
108
     * The name of the HTTP header for sending CSRF token.
109
     */
110
    const CSRF_HEADER = 'X-CSRF-Token';
111
112
    /**
113
     * @var bool whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true.
114
     * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated
115
     * from the same application. If not, a 400 HTTP exception will be raised.
116
     *
117
     * Note, this feature requires that the user client accepts cookie. Also, to use this feature,
118
     * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfParam]].
119
     * You may use [[\yii\helpers\Html::beginForm()]] to generate his hidden input.
120
     *
121
     * In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and
122
     * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered.
123
     * You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]].
124
     *
125
     * @see Controller::enableCsrfValidation
126
     * @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
127
     */
128
    public $enableCsrfValidation = true;
129
    /**
130
     * @var string the name of the token used to prevent CSRF. Defaults to '_csrf'.
131
     * This property is used only when [[enableCsrfValidation]] is true.
132
     */
133
    public $csrfParam = '_csrf';
134
    /**
135
     * @var array the configuration for creating the CSRF [[Cookie|cookie]]. This property is used only when
136
     * both [[enableCsrfValidation]] and [[enableCsrfCookie]] are true.
137
     */
138
    public $csrfCookie = ['httpOnly' => true];
139
    /**
140
     * @var bool whether to use cookie to persist CSRF token. If false, CSRF token will be stored
141
     * in session under the name of [[csrfParam]]. Note that while storing CSRF tokens in session increases
142
     * security, it requires starting a session for every page, which will degrade your site performance.
143
     */
144
    public $enableCsrfCookie = true;
145
    /**
146
     * @var bool whether cookies should be validated to ensure they are not tampered. Defaults to true.
147
     */
148
    public $enableCookieValidation = true;
149
    /**
150
     * @var string a secret key used for cookie validation. This property must be set if [[enableCookieValidation]] is true.
151
     */
152
    public $cookieValidationKey;
153
    /**
154
     * @var string the name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE
155
     * request tunneled through POST. Defaults to '_method'.
156
     * @see getMethod()
157
     * @see getParsedBody()
158
     */
159
    public $methodParam = '_method';
160
    /**
161
     * @var array the parsers for converting the raw HTTP request body into [[bodyParams]].
162
     * The array keys are the request `Content-Types`, and the array values are the
163
     * corresponding configurations for [[Yii::createObject|creating the parser objects]].
164
     * A parser must implement the [[RequestParserInterface]].
165
     *
166
     * To enable parsing for JSON requests you can use the [[JsonParser]] class like in the following example:
167
     *
168
     * ```
169
     * [
170
     *     'application/json' => \yii\web\JsonParser::class,
171
     * ]
172
     * ```
173
     *
174
     * To register a parser for parsing all request types you can use `'*'` as the array key.
175
     * This one will be used as a fallback in case no other types match.
176
     *
177
     * @see getParsedBody()
178
     */
179
    public $parsers = [];
180
    /**
181
     * @var string name of the class to be used for uploaded file instantiation.
182
     * This class should implement [[UploadedFileInterface]].
183
     * @since 2.1.0
184
     */
185
    public $uploadedFileClass = UploadedFile::class;
186
    /**
187
     * @var array the configuration for trusted security related headers.
188
     *
189
     * An array key is an IPv4 or IPv6 IP address in CIDR notation for matching a client.
190
     *
191
     * An array value is a list of headers to trust. These will be matched against
192
     * [[secureHeaders]] to determine which headers are allowed to be sent by a specified host.
193
     * The case of the header names must be the same as specified in [[secureHeaders]].
194
     *
195
     * For example, to trust all headers listed in [[secureHeaders]] for IP addresses
196
     * in range `192.168.0.0-192.168.0.254` write the following:
197
     *
198
     * ```php
199
     * [
200
     *     '192.168.0.0/24',
201
     * ]
202
     * ```
203
     *
204
     * To trust just the `X-Forwarded-For` header from `10.0.0.1`, use:
205
     *
206
     * ```
207
     * [
208
     *     '10.0.0.1' => ['X-Forwarded-For']
209
     * ]
210
     * ```
211
     *
212
     * Default is to trust all headers except those listed in [[secureHeaders]] from all hosts.
213
     * Matches are tried in order and searching is stopped when IP matches.
214
     *
215
     * > Info: Matching is performed using [[IpValidator]].
216
     *   See [[IpValidator::::setRanges()|IpValidator::setRanges()]]
217
     *   and [[IpValidator::networks]] for advanced matching.
218
     *
219
     * @see $secureHeaders
220
     * @since 2.0.13
221
     */
222
    public $trustedHosts = [];
223
    /**
224
     * @var array lists of headers that are, by default, subject to the trusted host configuration.
225
     * These headers will be filtered unless explicitly allowed in [[trustedHosts]].
226
     * The match of header names is case-insensitive.
227
     * @see https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
228
     * @see $trustedHosts
229
     * @since 2.0.13
230
     */
231
    public $secureHeaders = [
232
        // Common:
233
        'X-Forwarded-For',
234
        'X-Forwarded-Host',
235
        'X-Forwarded-Proto',
236
237
        // Microsoft:
238
        'Front-End-Https',
239
        'X-Rewrite-Url',
240
    ];
241
    /**
242
     * @var string[] List of headers where proxies store the real client IP.
243
     * It's not advisable to put insecure headers here.
244
     * The match of header names is case-insensitive.
245
     * @see $trustedHosts
246
     * @see $secureHeaders
247
     * @since 2.0.13
248
     */
249
    public $ipHeaders = [
250
        'X-Forwarded-For', // Common
251
    ];
252
    /**
253
     * @var array list of headers to check for determining whether the connection is made via HTTPS.
254
     * The array keys are header names and the array value is a list of header values that indicate a secure connection.
255
     * The match of header names and values is case-insensitive.
256
     * It's not advisable to put insecure headers here.
257
     * @see $trustedHosts
258
     * @see $secureHeaders
259
     * @since 2.0.13
260
     */
261
    public $secureProtocolHeaders = [
262
        'X-Forwarded-Proto' => ['https'], // Common
263
        'Front-End-Https' => ['on'], // Microsoft
264
    ];
265
266
    /**
267
     * @var array attributes derived from the request.
268
     * @since 2.1.0
269
     */
270
    private $_attributes;
271
    /**
272
     * @var array server parameters.
273
     * @since 2.1.0
274
     */
275
    private $_serverParams;
276
    /**
277
     * @var array the cookies sent by the client to the server.
278
     * @since 2.1.0
279
     */
280
    private $_cookieParams;
281
    /**
282
     * @var CookieCollection Collection of request cookies.
283
     */
284
    private $_cookies;
285
    /**
286
     * @var string the HTTP method of the request.
287
     */
288
    private $_method;
289
    /**
290
     * @var UriInterface the URI instance associated with request.
291
     */
292
    private $_uri;
293
    /**
294
     * @var mixed the message's request target.
295
     */
296
    private $_requestTarget;
297
    /**
298
     * @var array uploaded files.
299
     * @since 2.1.0
300
     */
301
    private $_uploadedFiles;
302
303
304
    /**
305
     * Resolves the current request into a route and the associated parameters.
306
     * @return array the first element is the route, and the second is the associated parameters.
307
     * @throws NotFoundHttpException if the request cannot be resolved.
308
     */
309 1
    public function resolve()
310
    {
311 1
        $result = Yii::$app->getUrlManager()->parseRequest($this);
312 1
        if ($result !== false) {
313 1
            [$route, $params] = $result;
0 ignored issues
show
Bug introduced by
The variable $route 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 $params 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...
314 1
            if ($this->_queryParams === null) {
315 1
                $_GET = $params + $_GET; // preserve numeric keys
316
            } else {
317 1
                $this->_queryParams = $params + $this->_queryParams;
318
            }
319
320 1
            return [$route, $this->getQueryParams()];
321
        }
322
323
        throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
324
    }
325
326
    /**
327
     * Filters headers according to the [[trustedHosts]].
328
     * @param array $rawHeaders
329
     * @return array filtered headers
330
     * @since 2.0.13
331
     */
332 144
    protected function filterHeaders($rawHeaders)
333
    {
334
        // do not trust any of the [[secureHeaders]] by default
335 144
        $trustedHeaders = [];
336
337
        // check if the client is a trusted host
338 144
        if (!empty($this->trustedHosts)) {
339 25
            $validator = $this->getIpValidator();
340 25
            $ip = $this->getRemoteIP();
341 25
            foreach ($this->trustedHosts as $cidr => $headers) {
342 25
                if (!is_array($headers)) {
343 25
                    $cidr = $headers;
344 25
                    $headers = $this->secureHeaders;
345
                }
346 25
                $validator->setRanges($cidr);
347 25
                if ($validator->validate($ip)) {
348 5
                    $trustedHeaders = $headers;
349 25
                    break;
350
                }
351
            }
352
        }
353
354 144
        $rawHeaders = array_change_key_case($rawHeaders, CASE_LOWER);
355
356
        // filter all secure headers unless they are trusted
357 144
        foreach ($this->secureHeaders as $secureHeader) {
358 144
            if (!in_array($secureHeader, $trustedHeaders)) {
359 144
                unset($rawHeaders[strtolower($secureHeader)]);
360
            }
361
        }
362
363 144
        return $rawHeaders;
364
    }
365
366
    /**
367
     * Creates instance of [[IpValidator]].
368
     * You can override this method to adjust validator or implement different matching strategy.
369
     *
370
     * @return IpValidator
371
     * @since 2.0.13
372
     */
373 25
    protected function getIpValidator()
374
    {
375 25
        return new IpValidator();
376
    }
377
378
    /**
379
     * Returns default message's headers, which should be present once [[headerCollection]] is instantiated.
380
     * @return string[][] an associative array of the message's headers.
381
     */
382 144
    protected function defaultHeaders()
383
    {
384 144
        if (function_exists('getallheaders')) {
385
            $headers = getallheaders();
386 144
        } elseif (function_exists('http_get_request_headers')) {
387
            $headers = http_get_request_headers();
388
        } else {
389 144
            $headers = [];
390 144
            foreach ($_SERVER as $name => $value) {
391 141
                if (strncmp($name, 'HTTP_', 5) === 0) {
392 34
                    $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
393 141
                    $headers[$name] = $value;
394
                }
395
            }
396
        }
397
398 144
        return $this->filterHeaders($headers);
399
    }
400
401
    /**
402
     * {@inheritdoc}
403
     * @since 2.1.0
404
     */
405
    public function getRequestTarget()
406
    {
407
        if ($this->_requestTarget === null) {
408
            $this->_requestTarget = $this->getUri()->__toString();
409
        }
410
        return $this->_requestTarget;
411
    }
412
413
    /**
414
     * Specifies the message's request target
415
     * @param mixed $requestTarget the message's request target.
416
     * @since 2.1.0
417
     */
418
    public function setRequestTarget($requestTarget)
419
    {
420
        $this->_requestTarget = $requestTarget;
421
    }
422
423
    /**
424
     * {@inheritdoc}
425
     * @since 2.1.0
426
     */
427
    public function withRequestTarget($requestTarget)
428
    {
429
        if ($this->getRequestTarget() === $requestTarget) {
430
            return $this;
431
        }
432
433
        $newInstance = clone $this;
434
        $newInstance->setRequestTarget($requestTarget);
435
        return $newInstance;
436
    }
437
438
    /**
439
     * {@inheritdoc}
440
     */
441 55
    public function getMethod()
442
    {
443 55
        if ($this->_method === null) {
444 45
            if (isset($_POST[$this->methodParam])) {
445 1
                $this->_method = $_POST[$this->methodParam];
446 44
            } elseif ($this->hasHeader('x-http-method-override')) {
447 1
                $this->_method = $this->getHeaderLine('x-http-method-override');
448
            } else {
449 43
                $this->_method = $this->getServerParam('REQUEST_METHOD', 'GET');
450
            }
451
        }
452 55
        return $this->_method;
453
    }
454
455
    /**
456
     * Specifies request HTTP method.
457
     * @param string $method case-sensitive HTTP method.
458
     * @since 2.1.0
459
     */
460 12
    public function setMethod($method)
461
    {
462 12
        $this->_method =  $method;
463 12
    }
464
465
    /**
466
     * {@inheritdoc}
467
     * @since 2.1.0
468
     */
469 1
    public function withMethod($method)
470
    {
471 1
        if ($this->getMethod() === $method) {
472
            return $this;
473
        }
474
475 1
        $newInstance = clone $this;
476 1
        $newInstance->setMethod($method);
477 1
        return $newInstance;
478
    }
479
480
    /**
481
     * {@inheritdoc}
482
     * @since 2.1.0
483
     */
484
    public function getUri()
485
    {
486
        if (!$this->_uri instanceof UriInterface) {
487
            if ($this->_uri === null) {
488
                $uri = new Uri(['string' => $this->getAbsoluteUrl()]);
489
            } elseif ($this->_uri instanceof \Closure) {
490
                $uri = call_user_func($this->_uri, $this);
491
            } else {
492
                $uri = $this->_uri;
493
            }
494
495
            $this->_uri = Instance::ensure($uri, UriInterface::class);
496
        }
497
        return $this->_uri;
498
    }
499
500
    /**
501
     * Specifies the URI instance.
502
     * @param UriInterface|\Closure|array $uri URI instance or its DI compatible configuration.
503
     * @since 2.1.0
504
     */
505
    public function setUri($uri)
506
    {
507
        $this->_uri = $uri;
0 ignored issues
show
Documentation Bug introduced by
It seems like $uri can also be of type object<Closure> or array. However, the property $_uri is declared as type object<Psr\Http\Message\UriInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
508
    }
509
510
    /**
511
     * {@inheritdoc}
512
     * @since 2.1.0
513
     */
514
    public function withUri(UriInterface $uri, $preserveHost = false)
515
    {
516
        if ($this->getUri() === $uri) {
517
            return $this;
518
        }
519
520
        $newInstance = clone $this;
521
522
        $newInstance->setUri($uri);
523
        if (!$preserveHost) {
524
            return $newInstance->withHeader('host', $uri->getHost());
525
        }
526
        return $newInstance;
527
    }
528
529
    /**
530
     * Returns whether this is a GET request.
531
     * @return bool whether this is a GET request.
532
     */
533 2
    public function getIsGet()
534
    {
535 2
        return $this->getMethod() === 'GET';
536
    }
537
538
    /**
539
     * Returns whether this is an OPTIONS request.
540
     * @return bool whether this is a OPTIONS request.
541
     */
542 2
    public function getIsOptions()
543
    {
544 2
        return $this->getMethod() === 'OPTIONS';
545
    }
546
547
    /**
548
     * Returns whether this is a HEAD request.
549
     * @return bool whether this is a HEAD request.
550
     */
551
    public function getIsHead()
552
    {
553
        return $this->getMethod() === 'HEAD';
554
    }
555
556
    /**
557
     * Returns whether this is a POST request.
558
     * @return bool whether this is a POST request.
559
     */
560
    public function getIsPost()
561
    {
562
        return $this->getMethod() === 'POST';
563
    }
564
565
    /**
566
     * Returns whether this is a DELETE request.
567
     * @return bool whether this is a DELETE request.
568
     */
569
    public function getIsDelete()
570
    {
571
        return $this->getMethod() === 'DELETE';
572
    }
573
574
    /**
575
     * Returns whether this is a PUT request.
576
     * @return bool whether this is a PUT request.
577
     */
578
    public function getIsPut()
579
    {
580
        return $this->getMethod() === 'PUT';
581
    }
582
583
    /**
584
     * Returns whether this is a PATCH request.
585
     * @return bool whether this is a PATCH request.
586
     */
587
    public function getIsPatch()
588
    {
589
        return $this->getMethod() === 'PATCH';
590
    }
591
592
    /**
593
     * Returns whether this is an AJAX (XMLHttpRequest) request.
594
     *
595
     * Note that jQuery doesn't set the header in case of cross domain
596
     * requests: https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header
597
     *
598
     * @return bool whether this is an AJAX (XMLHttpRequest) request.
599
     */
600 13
    public function getIsAjax()
601
    {
602 13
        return $this->getHeaderLine('x-requested-with') === 'XMLHttpRequest';
603
    }
604
605
    /**
606
     * Returns whether this is an Adobe Flash or Flex request.
607
     * @return bool whether this is an Adobe Flash or Adobe Flex request.
608
     */
609
    public function getIsFlash()
610
    {
611
        $userAgent = $this->getUserAgent();
612
        if ($userAgent === null) {
613
            return false;
614
        }
615
        return (stripos($userAgent, 'Shockwave') !== false || stripos($userAgent, 'Flash') !== false);
616
    }
617
618
    /**
619
     * Returns default message body to be used in case it is not explicitly set.
620
     * @return StreamInterface default body instance.
621
     */
622 3
    protected function defaultBody()
623
    {
624 3
        return new FileStream([
625 3
            'filename' => 'php://input',
626
            'mode' => 'r',
627
        ]);
628
    }
629
630
    /**
631
     * Returns the raw HTTP request body.
632
     * @return string the request body
633
     */
634
    public function getRawBody()
635
    {
636
        return $this->getBody()->__toString();
637
    }
638
639
    /**
640
     * Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
641
     * @param string $rawBody the request body
642
     */
643 6
    public function setRawBody($rawBody)
644
    {
645 6
        $body = new MemoryStream();
646 6
        $body->write($rawBody);
647 6
        $this->setBody($body);
648 6
    }
649
650
    private $_parsedBody = false;
651
652
    /**
653
     * Returns the request parameters given in the request body.
654
     *
655
     * Request parameters are determined using the parsers configured in [[parsers]] property.
656
     * If no parsers are configured for the current [[contentType]] it uses the PHP function `mb_parse_str()`
657
     * to parse the [[rawBody|request body]].
658
     *
659
     * Since 2.1.0 body params also include result of [[getUploadedFiles()]].
660
     *
661
     * @return array|null the request parameters given in the request body. A `null` value indicates
662
     * the absence of body content.
663
     * @throws InvalidConfigException if a registered parser does not implement the [[RequestParserInterface]].
664
     * @throws UnsupportedMediaTypeHttpException if unable to parse raw body.
665
     * @see getMethod()
666
     * @see getParsedBodyParam()
667
     * @see setParsedBody()
668
     */
669 16
    public function getParsedBody()
670
    {
671 16
        if ($this->_parsedBody === false) {
672 13
            if (isset($_POST[$this->methodParam])) {
673 1
                $this->_parsedBody = $_POST;
674 1
                unset($this->_parsedBody[$this->methodParam]);
675 1
                return $this->_parsedBody;
676
            }
677
678 12
            $contentType = $this->getContentType();
679 12
            if (($pos = strpos($contentType, ';')) !== false) {
680
                // e.g. text/html; charset=UTF-8
681 2
                $contentType = trim(substr($contentType, 0, $pos));
682
            }
683
684 12
            if (isset($this->parsers[$contentType])) {
685 2
                $parser = Yii::createObject($this->parsers[$contentType]);
686 2
                if (!($parser instanceof RequestParserInterface)) {
687
                    throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
688
                }
689 2
                $this->_parsedBody = $parser->parse($this);
0 ignored issues
show
Documentation Bug introduced by
It seems like $parser->parse($this) of type array is incompatible with the declared type boolean of property $_parsedBody.

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...
690 10
            } elseif (isset($this->parsers['*'])) {
691
                $parser = Yii::createObject($this->parsers['*']);
692
                if (!($parser instanceof RequestParserInterface)) {
693
                    throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.');
694
                }
695
                $this->_parsedBody = $parser->parse($this);
696 10
            } elseif ($this->getMethod() === 'POST') {
697 6
                if ($contentType !== 'application/x-www-form-urlencoded' && $contentType !== 'multipart/form-data') {
698 1
                    throw new UnsupportedMediaTypeHttpException();
699
                }
700
                // PHP has already parsed the body so we have all params in $_POST
701 6
                $this->_parsedBody = $_POST;
702
703 6
                if ($contentType === 'multipart/form-data') {
704 6
                    $this->_parsedBody = ArrayHelper::merge($this->_parsedBody, $this->getUploadedFiles());
0 ignored issues
show
Documentation Bug introduced by
It seems like \yii\helpers\ArrayHelper...is->getUploadedFiles()) of type array is incompatible with the declared type boolean of property $_parsedBody.

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...
705
                }
706 5
            } elseif (empty($contentType) && ($this->getBody()->getSize() === 0 || $this->getBody()->getSize() === null)) {
707 4
                $this->_parsedBody = null;
708
            } else {
709 2
                if ($contentType !== 'application/x-www-form-urlencoded') {
710 2
                    throw new UnsupportedMediaTypeHttpException();
711
                }
712 1
                $this->_parsedBody = [];
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type boolean of property $_parsedBody.

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...
713 1
                mb_parse_str($this->getBody()->__toString(), $this->_parsedBody);
714
            }
715
        }
716
717 15
        return $this->_parsedBody;
718
    }
719
720
    /**
721
     * Sets the request body parameters.
722
     * @param array $values the request body parameters (name-value pairs)
723
     * @see getParsedBodyParam()
724
     * @see getParsedBody()
725
     */
726 7
    public function setParsedBody($values)
727
    {
728 7
        $this->_parsedBody = $values;
0 ignored issues
show
Documentation Bug introduced by
It seems like $values of type array is incompatible with the declared type boolean of property $_parsedBody.

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...
729 7
    }
730
731
    /**
732
     * {@inheritdoc}
733
     * @since 2.1.0
734
     */
735
    public function withParsedBody($data)
736
    {
737
        $newInstance = clone $this;
738
        $newInstance->setParsedBody($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 735 can also be of type null or object; however, yii\web\Request::setParsedBody() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
739
        return $newInstance;
740
    }
741
742
    /**
743
     * Returns the named request body parameter value.
744
     * If the parameter does not exist, the second parameter passed to this method will be returned.
745
     * @param string $name the parameter name
746
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
747
     * @return mixed the parameter value
748
     * @see getParsedBody()
749
     * @see setParsedBody()
750
     */
751 8
    public function getParsedBodyParam($name, $defaultValue = null)
752
    {
753 8
        $params = $this->getParsedBody();
754
755 8
        if (is_object($params)) {
756
            // unable to use `ArrayHelper::getValue()` due to different dots in key logic and lack of exception handling
757
            try {
758 1
                return $params->{$name};
759 1
            } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) { ...return $defaultValue; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
760 1
                return $defaultValue;
761
            }
762
        }
763
764 8
        return $params[$name] ?? $defaultValue;
765
    }
766
767
    /**
768
     * Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters.
769
     *
770
     * @param string $name the parameter name
771
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
772
     * @return array|mixed
773
     */
774
    public function post($name = null, $defaultValue = null)
775
    {
776
        if ($name === null) {
777
            return $this->getParsedBody();
778
        }
779
780
        return $this->getParsedBodyParam($name, $defaultValue);
781
    }
782
783
    private $_queryParams;
784
785
    /**
786
     * Returns the request parameters given in the [[queryString]].
787
     *
788
     * This method will return the contents of `$_GET` if params where not explicitly set.
789
     * @return array the request GET parameter values.
790
     * @see setQueryParams()
791
     */
792 19
    public function getQueryParams()
793
    {
794 19
        if ($this->_queryParams === null) {
795 15
            return $_GET;
796
        }
797
798 5
        return $this->_queryParams;
799
    }
800
801
    /**
802
     * Sets the request [[queryString]] parameters.
803
     * @param array $values the request query parameters (name-value pairs)
804
     * @see getQueryParam()
805
     * @see getQueryParams()
806
     */
807 5
    public function setQueryParams($values)
808
    {
809 5
        $this->_queryParams = $values;
810 5
    }
811
812
    /**
813
     * {@inheritdoc}
814
     */
815
    public function withQueryParams(array $query)
816
    {
817
        if ($this->getQueryParams() === $query) {
818
            return $this;
819
        }
820
821
        $newInstance = clone $this;
822
        $newInstance->setQueryParams($query);
823
        return $newInstance;
824
    }
825
826
    /**
827
     * Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.
828
     *
829
     * @param string $name the parameter name
830
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
831
     * @return array|mixed
832
     */
833 7
    public function get($name = null, $defaultValue = null)
834
    {
835 7
        if ($name === null) {
836
            return $this->getQueryParams();
837
        }
838
839 7
        return $this->getQueryParam($name, $defaultValue);
840
    }
841
842
    /**
843
     * Returns the named GET parameter value.
844
     * If the GET parameter does not exist, the second parameter passed to this method will be returned.
845
     * @param string $name the GET parameter name.
846
     * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
847
     * @return mixed the GET parameter value
848
     * @see getParsedBodyParam()
849
     */
850 10
    public function getQueryParam($name, $defaultValue = null)
851
    {
852 10
        $params = $this->getQueryParams();
853
854 10
        return $params[$name] ?? $defaultValue;
855
    }
856
857
    /**
858
     * Sets the data related to the incoming request environment.
859
     * @param array $serverParams server parameters.
860
     * @since 2.1.0
861
     */
862 4
    public function setServerParams(array $serverParams)
863
    {
864 4
        $this->_serverParams = $serverParams;
865 4
    }
866
867
    /**
868
     * {@inheritdoc}
869
     * @since 2.1.0
870
     */
871 127
    public function getServerParams()
872
    {
873 127
        if ($this->_serverParams === null) {
874 124
            $this->_serverParams = $_SERVER;
875
        }
876 127
        return $this->_serverParams;
877
    }
878
879
    /**
880
     * Return the server environment parameter by name.
881
     * @param string $name parameter name.
882
     * @param mixed $default default value to return if the parameter does not exist.
883
     * @return mixed parameter value.
884
     * @since 2.1.0
885
     */
886 127
    public function getServerParam($name, $default = null)
887
    {
888 127
        $params = $this->getServerParams();
889 127
        if (!isset($params[$name])) {
890 106
            return $default;
891
        }
892 45
        return $params[$name];
893
    }
894
895
    /**
896
     * Specifies cookies.
897
     * @param array $cookies array of key/value pairs representing cookies.
898
     * @since 2.1.0
899
     */
900
    public function setCookieParams(array $cookies)
901
    {
902
        $this->_cookieParams = $cookies;
903
        $this->_cookies = null;
904
    }
905
906
    /**
907
     * {@inheritdoc}
908
     * @since 2.1.0
909
     */
910 42
    public function getCookieParams()
911
    {
912 42
        if ($this->_cookieParams === null) {
913 42
            $this->_cookieParams = $_COOKIE;
914
        }
915 42
        return $this->_cookieParams;
916
    }
917
918
    /**
919
     * {@inheritdoc}
920
     * @since 2.1.0
921
     */
922
    public function withCookieParams(array $cookies)
923
    {
924
        if ($this->getCookieParams() === $cookies) {
925
            return $this;
926
        }
927
928
        $newInstance = clone $this;
929
        $newInstance->setCookieParams($cookies);
930
        return $newInstance;
931
    }
932
933
    private $_hostInfo;
934
    private $_hostName;
935
936
    /**
937
     * Returns the schema and host part of the current request URL.
938
     *
939
     * The returned URL does not have an ending slash.
940
     *
941
     * By default this value is based on the user request information. This method will
942
     * return the value of `$_SERVER['HTTP_HOST']` if it is available or `$_SERVER['SERVER_NAME']` if not.
943
     * You may want to check out the [PHP documentation](http://php.net/manual/en/reserved.variables.server.php)
944
     * for more information on these variables.
945
     *
946
     * You may explicitly specify it by setting the [[setHostInfo()|hostInfo]] property.
947
     *
948
     * > Warning: Dependent on the server configuration this information may not be
949
     * > reliable and [may be faked by the user sending the HTTP request](https://www.acunetix.com/vulnerabilities/web/host-header-attack).
950
     * > If the webserver is configured to serve the same site independent of the value of
951
     * > the `Host` header, this value is not reliable. In such situations you should either
952
     * > fix your webserver configuration or explicitly set the value by setting the [[setHostInfo()|hostInfo]] property.
953
     * > If you don't have access to the server configuration, you can setup [[\yii\filters\HostControl]] filter at
954
     * > application level in order to protect against such kind of attack.
955
     *
956
     * @property string|null schema and hostname part (with port number if needed) of the request URL
957
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
958
     * See [[getHostInfo()]] for security related notes on this property.
959
     * @return string|null schema and hostname part (with port number if needed) of the request URL
960
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
961
     * @see setHostInfo()
962
     */
963 24
    public function getHostInfo()
964
    {
965 24
        if ($this->_hostInfo === null) {
966 20
            $secure = $this->getIsSecureConnection();
967 20
            $http = $secure ? 'https' : 'http';
968
969 20
            if ($this->hasHeader('X-Forwarded-Host')) {
970 2
                $this->_hostInfo = $http . '://' . trim(explode(',', $this->getHeaderLine('X-Forwarded-Host'))[0]);
971 18
            } elseif ($this->hasHeader('Host')) {
972 9
                $this->_hostInfo = $http . '://' . $this->getHeaderLine('Host');
973 9
            } elseif (($serverName = $this->getServerParam('SERVER_NAME')) !== null) {
974 1
                $this->_hostInfo = $http . '://' . $serverName;
975 1
                $port = $secure ? $this->getSecurePort() : $this->getPort();
976 1
                if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
977
                    $this->_hostInfo .= ':' . $port;
978
                }
979
            }
980
        }
981
982 24
        return $this->_hostInfo;
983
    }
984
985
    /**
986
     * Sets the schema and host part of the application URL.
987
     * This setter is provided in case the schema and hostname cannot be determined
988
     * on certain Web servers.
989
     * @param string|null $value the schema and host part of the application URL. The trailing slashes will be removed.
990
     * @see getHostInfo() for security related notes on this property.
991
     */
992 47
    public function setHostInfo($value)
993
    {
994 47
        $this->_hostName = null;
995 47
        $this->_hostInfo = $value === null ? null : rtrim($value, '/');
996 47
    }
997
998
    /**
999
     * Returns the host part of the current request URL.
1000
     * Value is calculated from current [[getHostInfo()|hostInfo]] property.
1001
     *
1002
     * > Warning: The content of this value may not be reliable, dependent on the server
1003
     * > configuration. Please refer to [[getHostInfo()]] for more information.
1004
     *
1005
     * @return string|null hostname part of the request URL (e.g. `www.yiiframework.com`)
1006
     * @see getHostInfo()
1007
     * @since 2.0.10
1008
     */
1009 17
    public function getHostName()
1010
    {
1011 17
        if ($this->_hostName === null) {
1012 17
            $this->_hostName = parse_url($this->getHostInfo(), PHP_URL_HOST);
1013
        }
1014
1015 17
        return $this->_hostName;
1016
    }
1017
1018
    private $_baseUrl;
1019
1020
    /**
1021
     * Returns the relative URL for the application.
1022
     * This is similar to [[scriptUrl]] except that it does not include the script file name,
1023
     * and the ending slashes are removed.
1024
     * @return string the relative URL for the application
1025
     * @see setScriptUrl()
1026
     */
1027 255
    public function getBaseUrl()
1028
    {
1029 255
        if ($this->_baseUrl === null) {
1030 254
            $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/');
1031
        }
1032
1033 255
        return $this->_baseUrl;
1034
    }
1035
1036
    /**
1037
     * Sets the relative URL for the application.
1038
     * By default the URL is determined based on the entry script URL.
1039
     * This setter is provided in case you want to change this behavior.
1040
     * @param string $value the relative URL for the application
1041
     */
1042 1
    public function setBaseUrl($value)
1043
    {
1044 1
        $this->_baseUrl = $value;
1045 1
    }
1046
1047
    private $_scriptUrl;
1048
1049
    /**
1050
     * Returns the relative URL of the entry script.
1051
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
1052
     * @return string the relative URL of the entry script.
1053
     * @throws InvalidConfigException if unable to determine the entry script URL
1054
     */
1055 256
    public function getScriptUrl()
1056
    {
1057 256
        if ($this->_scriptUrl === null) {
1058 2
            $scriptFile = $this->getScriptFile();
1059 1
            $scriptName = basename($scriptFile);
1060 1
            $serverParams = $this->getServerParams();
1061 1
            if (isset($serverParams['SCRIPT_NAME']) && basename($serverParams['SCRIPT_NAME']) === $scriptName) {
1062 1
                $this->_scriptUrl = $serverParams['SCRIPT_NAME'];
1063
            } elseif (isset($serverParams['PHP_SELF']) && basename($serverParams['PHP_SELF']) === $scriptName) {
1064
                $this->_scriptUrl = $serverParams['PHP_SELF'];
1065
            } elseif (isset($serverParams['ORIG_SCRIPT_NAME']) && basename($serverParams['ORIG_SCRIPT_NAME']) === $scriptName) {
1066
                $this->_scriptUrl = $serverParams['ORIG_SCRIPT_NAME'];
1067
            } elseif (isset($serverParams['PHP_SELF']) && ($pos = strpos($serverParams['PHP_SELF'], '/' . $scriptName)) !== false) {
1068
                $this->_scriptUrl = substr($serverParams['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
1069
            } elseif (!empty($serverParams['DOCUMENT_ROOT']) && strpos($scriptFile, $serverParams['DOCUMENT_ROOT']) === 0) {
1070
                $this->_scriptUrl = str_replace([$serverParams['DOCUMENT_ROOT'], '\\'], ['', '/'], $scriptFile);
1071
            } else {
1072
                throw new InvalidConfigException('Unable to determine the entry script URL.');
1073
            }
1074
        }
1075
1076 255
        return $this->_scriptUrl;
1077
    }
1078
1079
    /**
1080
     * Sets the relative URL for the application entry script.
1081
     * This setter is provided in case the entry script URL cannot be determined
1082
     * on certain Web servers.
1083
     * @param string $value the relative URL for the application entry script.
1084
     */
1085 266
    public function setScriptUrl($value)
1086
    {
1087 266
        $this->_scriptUrl = $value === null ? null : '/' . trim($value, '/');
1088 266
    }
1089
1090
    private $_scriptFile;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
1091
1092
    /**
1093
     * Returns the entry script file path.
1094
     * The default implementation will simply return `$_SERVER['SCRIPT_FILENAME']`.
1095
     * @return string the entry script file path
1096
     * @throws InvalidConfigException
1097
     */
1098 257
    public function getScriptFile()
1099
    {
1100 257
        if (isset($this->_scriptFile)) {
1101 245
            return $this->_scriptFile;
1102
        }
1103
1104 13
        if (($scriptFilename = $this->getServerParam('SCRIPT_FILENAME')) !== null) {
1105 11
            return $scriptFilename;
1106
        }
1107
1108 2
        throw new InvalidConfigException('Unable to determine the entry script file path.');
1109
    }
1110
1111
    /**
1112
     * Sets the entry script file path.
1113
     * The entry script file path normally can be obtained from `$_SERVER['SCRIPT_FILENAME']`.
1114
     * If your server configuration does not return the correct value, you may configure
1115
     * this property to make it right.
1116
     * @param string $value the entry script file path.
1117
     */
1118 245
    public function setScriptFile($value)
1119
    {
1120 245
        $this->_scriptFile = $value;
1121 245
    }
1122
1123
    private $_pathInfo;
1124
1125
    /**
1126
     * Returns the path info of the currently requested URL.
1127
     * A path info refers to the part that is after the entry script and before the question mark (query string).
1128
     * The starting and ending slashes are both removed.
1129
     * @return string part of the request URL that is after the entry script and before the question mark.
1130
     * Note, the returned path info is already URL-decoded.
1131
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
1132
     */
1133 17
    public function getPathInfo()
1134
    {
1135 17
        if ($this->_pathInfo === null) {
1136
            $this->_pathInfo = $this->resolvePathInfo();
1137
        }
1138
1139 17
        return $this->_pathInfo;
1140
    }
1141
1142
    /**
1143
     * Sets the path info of the current request.
1144
     * This method is mainly provided for testing purpose.
1145
     * @param string $value the path info of the current request
1146
     */
1147 18
    public function setPathInfo($value)
1148
    {
1149 18
        $this->_pathInfo = $value === null ? null : ltrim($value, '/');
1150 18
    }
1151
1152
    /**
1153
     * Resolves the path info part of the currently requested URL.
1154
     * A path info refers to the part that is after the entry script and before the question mark (query string).
1155
     * The starting slashes are both removed (ending slashes will be kept).
1156
     * @return string part of the request URL that is after the entry script and before the question mark.
1157
     * Note, the returned path info is decoded.
1158
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
1159
     */
1160
    protected function resolvePathInfo()
1161
    {
1162
        $pathInfo = $this->getUrl();
1163
1164
        if (($pos = strpos($pathInfo, '?')) !== false) {
1165
            $pathInfo = substr($pathInfo, 0, $pos);
1166
        }
1167
1168
        $pathInfo = urldecode($pathInfo);
1169
1170
        // try to encode in UTF8 if not so
1171
        // http://w3.org/International/questions/qa-forms-utf-8.html
1172
        if (!preg_match('%^(?:
1173
            [\x09\x0A\x0D\x20-\x7E]              # ASCII
1174
            | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
1175
            | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
1176
            | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
1177
            | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
1178
            | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
1179
            | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
1180
            | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
1181
            )*$%xs', $pathInfo)
1182
        ) {
1183
            $pathInfo = utf8_encode($pathInfo);
1184
        }
1185
1186
        $scriptUrl = $this->getScriptUrl();
1187
        $baseUrl = $this->getBaseUrl();
1188
        if (strpos($pathInfo, $scriptUrl) === 0) {
1189
            $pathInfo = substr($pathInfo, strlen($scriptUrl));
1190
        } elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) {
1191
            $pathInfo = substr($pathInfo, strlen($baseUrl));
1192
        } elseif (($phpSelf = $this->getServerParam('PHP_SELF')) !== null && strpos($phpSelf, $scriptUrl) === 0) {
1193
            $pathInfo = substr($phpSelf, strlen($scriptUrl));
1194
        } else {
1195
            throw new InvalidConfigException('Unable to determine the path info of the current request.');
1196
        }
1197
1198
        if (substr($pathInfo, 0, 1) === '/') {
1199
            $pathInfo = substr($pathInfo, 1);
1200
        }
1201
1202
        return (string) $pathInfo;
1203
    }
1204
1205
    /**
1206
     * Returns the currently requested absolute URL.
1207
     * This is a shortcut to the concatenation of [[hostInfo]] and [[url]].
1208
     * @return string the currently requested absolute URL.
1209
     */
1210
    public function getAbsoluteUrl()
1211
    {
1212
        return $this->getHostInfo() . $this->getUrl();
1213
    }
1214
1215
    private $_url;
1216
1217
    /**
1218
     * Returns the currently requested relative URL.
1219
     * This refers to the portion of the URL that is after the [[hostInfo]] part.
1220
     * It includes the [[queryString]] part if any.
1221
     * @return string the currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.
1222
     * @throws InvalidConfigException if the URL cannot be determined due to unusual server configuration
1223
     */
1224 9
    public function getUrl()
1225
    {
1226 9
        if ($this->_url === null) {
1227 2
            $this->_url = $this->resolveRequestUri();
1228
        }
1229
1230 9
        return $this->_url;
1231
    }
1232
1233
    /**
1234
     * Sets the currently requested relative URL.
1235
     * The URI must refer to the portion that is after [[hostInfo]].
1236
     * Note that the URI should be URL-encoded.
1237
     * @param string $value the request URI to be set
1238
     */
1239 24
    public function setUrl($value)
1240
    {
1241 24
        $this->_url = $value;
1242 24
    }
1243
1244
    /**
1245
     * Resolves the request URI portion for the currently requested URL.
1246
     * This refers to the portion that is after the [[hostInfo]] part. It includes the [[queryString]] part if any.
1247
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
1248
     * @return string|bool the request URI portion for the currently requested URL.
1249
     * Note that the URI returned may be URL-encoded depending on the client.
1250
     * @throws InvalidConfigException if the request URI cannot be determined due to unusual server configuration
1251
     */
1252 2
    protected function resolveRequestUri()
1253
    {
1254 2
        $serverParams = $this->getServerParams();
1255
1256 2
        if ($this->hasHeader('x-rewrite-url')) { // IIS
1257
            $requestUri = $this->getHeaderLine('x-rewrite-url');
1258 2
        } elseif (isset($serverParams['REQUEST_URI'])) {
1259 2
            $requestUri = $serverParams['REQUEST_URI'];
1260 2
            if ($requestUri !== '' && $requestUri[0] !== '/') {
1261 2
                $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
1262
            }
1263
        } elseif (isset($serverParams['ORIG_PATH_INFO'])) { // IIS 5.0 CGI
1264
            $requestUri = $serverParams['ORIG_PATH_INFO'];
1265
            if (!empty($serverParams['QUERY_STRING'])) {
1266
                $requestUri .= '?' . $serverParams['QUERY_STRING'];
1267
            }
1268
        } else {
1269
            throw new InvalidConfigException('Unable to determine the request URI.');
1270
        }
1271
1272 2
        return $requestUri;
1273
    }
1274
1275
    /**
1276
     * Returns part of the request URL that is after the question mark.
1277
     * @return string part of the request URL that is after the question mark
1278
     */
1279
    public function getQueryString()
1280
    {
1281
        return $this->getServerParam('QUERY_STRING', '');
1282
    }
1283
1284
    /**
1285
     * Return if the request is sent via secure channel (https).
1286
     * @return bool if the request is sent via secure channel (https)
1287
     */
1288 37
    public function getIsSecureConnection()
1289
    {
1290 37
        $https = $this->getServerParam('HTTPS');
1291 37
        if ($https !== null && (strcasecmp($https, 'on') === 0 || $https == 1)) {
1292 2
            return true;
1293
        }
1294 35
        foreach ($this->secureProtocolHeaders as $header => $values) {
1295 35
            if ($this->hasHeader($header)) {
1296 2
                foreach ($values as $value) {
1297 2
                    if (strcasecmp($this->getHeaderLine($header), $value) === 0) {
1298 35
                        return true;
1299
                    }
1300
                }
1301
            }
1302
        }
1303
1304 33
        return false;
1305
    }
1306
1307
    /**
1308
     * Returns the server name.
1309
     * @return string server name, null if not available
1310
     */
1311 1
    public function getServerName()
1312
    {
1313 1
        return $this->getServerParam('SERVER_NAME');
1314
    }
1315
1316
    /**
1317
     * Returns the server port number.
1318
     * @return int|null server port number, null if not available
1319
     */
1320 2
    public function getServerPort()
1321
    {
1322 2
        $port = $this->getServerParam('SERVER_PORT');
1323 2
        return $port === null ? null : (int) $port;
1324
    }
1325
1326
    /**
1327
     * Returns the URL referrer.
1328
     * @return string|null URL referrer, null if not available
1329
     */
1330
    public function getReferrer()
1331
    {
1332
        if (!$this->hasHeader('Referer')) {
1333
            return null;
1334
        }
1335
        return $this->getHeaderLine('Referer');
1336
    }
1337
1338
    /**
1339
     * Returns the URL origin of a CORS request.
1340
     *
1341
     * The return value is taken from the `Origin` [[getHeaders()|header]] sent by the browser.
1342
     *
1343
     * Note that the origin request header indicates where a fetch originates from.
1344
     * It doesn't include any path information, but only the server name.
1345
     * It is sent with a CORS requests, as well as with POST requests.
1346
     * It is similar to the referer header, but, unlike this header, it doesn't disclose the whole path.
1347
     * Please refer to <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin> for more information.
1348
     *
1349
     * @return string|null URL origin of a CORS request, `null` if not available.
1350
     * @see getHeaders()
1351
     * @since 2.0.13
1352
     */
1353 1
    public function getOrigin()
1354
    {
1355 1
        return $this->getHeaderLine('origin');
1356
    }
1357
1358
    /**
1359
     * Returns the user agent.
1360
     * @return string|null user agent, null if not available
1361
     */
1362
    public function getUserAgent()
1363
    {
1364
        if (!$this->hasHeader('User-Agent')) {
1365
            return null;
1366
        }
1367
        return $this->getHeaderLine('User-Agent');
1368
    }
1369
1370
    /**
1371
     * Returns the user IP address.
1372
     * The IP is determined using headers and / or `$_SERVER` variables.
1373
     * @return string|null user IP address, null if not available
1374
     */
1375 37
    public function getUserIP()
1376
    {
1377 37
        foreach ($this->ipHeaders as $ipHeader) {
1378 37
            if ($this->hasHeader($ipHeader)) {
1379 37
                return trim(explode(',', $this->getHeaderLine($ipHeader))[0]);
1380
            }
1381
        }
1382
1383 36
        return $this->getRemoteIP();
1384
    }
1385
1386
    /**
1387
     * Returns the user host name.
1388
     * The HOST is determined using headers and / or `$_SERVER` variables.
1389
     * @return string|null user host name, null if not available
1390
     */
1391
    public function getUserHost()
1392
    {
1393
        foreach ($this->ipHeaders as $ipHeader) {
1394
            if ($this->hasHeader($ipHeader)) {
1395
                return gethostbyaddr(trim(explode(',', $this->getHeaderLine($ipHeader))[0]));
1396
            }
1397
        }
1398
1399
        return $this->getRemoteHost();
1400
    }
1401
1402
    /**
1403
     * Returns the IP on the other end of this connection.
1404
     * This is always the next hop, any headers are ignored.
1405
     * @return string|null remote IP address, `null` if not available.
1406
     * @since 2.0.13
1407
     */
1408 58
    public function getRemoteIP()
1409
    {
1410 58
        return $this->getServerParam('REMOTE_ADDR');
1411
    }
1412
1413
    /**
1414
     * Returns the host name of the other end of this connection.
1415
     * This is always the next hop, any headers are ignored.
1416
     * @return string|null remote host name, `null` if not available
1417
     * @see getUserHost()
1418
     * @see getRemoteIP()
1419
     * @since 2.0.13
1420
     */
1421
    public function getRemoteHost()
1422
    {
1423
        return $this->getServerParam('REMOTE_HOST');
1424
    }
1425
1426
    /**
1427
     * @return string|null the username sent via HTTP authentication, `null` if the username is not given
1428
     * @see getAuthCredentials() to get both username and password in one call
1429
     */
1430 9
    public function getAuthUser()
1431
    {
1432 9
        return $this->getAuthCredentials()[0];
1433
    }
1434
1435
    /**
1436
     * @return string|null the password sent via HTTP authentication, `null` if the password is not given
1437
     * @see getAuthCredentials() to get both username and password in one call
1438
     */
1439 9
    public function getAuthPassword()
1440
    {
1441 9
        return $this->getAuthCredentials()[1];
1442
    }
1443
1444
    /**
1445
     * @return array that contains exactly two elements:
1446
     * - 0: the username sent via HTTP authentication, `null` if the username is not given
1447
     * - 1: the password sent via HTTP authentication, `null` if the password is not given
1448
     * @see getAuthUser() to get only username
1449
     * @see getAuthPassword() to get only password
1450
     * @since 2.0.13
1451
     */
1452 19
    public function getAuthCredentials()
1453
    {
1454 19
        $username = $this->getServerParam('PHP_AUTH_USER');
1455 19
        $password = $this->getServerParam('PHP_AUTH_PW');
1456 19
        if ($username !== null || $password !== null) {
1457 11
            return [$username, $password];
1458
        }
1459
1460
        /*
1461
         * Apache with php-cgi does not pass HTTP Basic authentication to PHP by default.
1462
         * To make it work, add the following line to to your .htaccess file:
1463
         *
1464
         * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
1465
         */
1466 8
        $auth_token = $this->getHeader('HTTP_AUTHORIZATION') ?: $this->getHeader('REDIRECT_HTTP_AUTHORIZATION');
1467 8
        if ($auth_token !== [] && strncasecmp($auth_token[0], 'basic', 5) === 0) {
1468 8
            $parts = array_map(function ($value) {
1469 8
                return strlen($value) === 0 ? null : $value;
1470 8
            }, explode(':', base64_decode(mb_substr($auth_token[0], 6)), 2));
1471
1472 8
            if (count($parts) < 2) {
1473 2
                return [$parts[0], null];
1474
            }
1475
1476 6
            return $parts;
1477
        }
1478
1479
        return [null, null];
1480
    }
1481
1482
    private $_port;
1483
1484
    /**
1485
     * Returns the port to use for insecure requests.
1486
     * Defaults to 80, or the port specified by the server if the current
1487
     * request is insecure.
1488
     * @return int port number for insecure requests.
1489
     * @see setPort()
1490
     */
1491 1
    public function getPort()
1492
    {
1493 1
        if ($this->_port === null) {
1494 1
            $serverPort = $this->getServerPort();
1495 1
            $this->_port = !$this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 80;
1496
        }
1497
1498 1
        return $this->_port;
1499
    }
1500
1501
    /**
1502
     * Sets the port to use for insecure requests.
1503
     * This setter is provided in case a custom port is necessary for certain
1504
     * server configurations.
1505
     * @param int $value port number.
1506
     */
1507
    public function setPort($value)
1508
    {
1509
        if ($value != $this->_port) {
1510
            $this->_port = (int) $value;
1511
            $this->_hostInfo = null;
1512
        }
1513
    }
1514
1515
    private $_securePort;
1516
1517
    /**
1518
     * Returns the port to use for secure requests.
1519
     * Defaults to 443, or the port specified by the server if the current
1520
     * request is secure.
1521
     * @return int port number for secure requests.
1522
     * @see setSecurePort()
1523
     */
1524
    public function getSecurePort()
1525
    {
1526
        if ($this->_securePort === null) {
1527
            $serverPort = $this->getServerPort();
1528
            $this->_securePort = $this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 443;
1529
        }
1530
1531
        return $this->_securePort;
1532
    }
1533
1534
    /**
1535
     * Sets the port to use for secure requests.
1536
     * This setter is provided in case a custom port is necessary for certain
1537
     * server configurations.
1538
     * @param int $value port number.
1539
     */
1540
    public function setSecurePort($value)
1541
    {
1542
        if ($value != $this->_securePort) {
1543
            $this->_securePort = (int) $value;
1544
            $this->_hostInfo = null;
1545
        }
1546
    }
1547
1548
    private $_contentTypes;
1549
1550
    /**
1551
     * Returns the content types acceptable by the end user.
1552
     *
1553
     * This is determined by the `Accept` HTTP header. For example,
1554
     *
1555
     * ```php
1556
     * $_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1557
     * $types = $request->getAcceptableContentTypes();
1558
     * print_r($types);
1559
     * // displays:
1560
     * // [
1561
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1562
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1563
     * //           'text/plain' => ['q' => 0.5],
1564
     * // ]
1565
     * ```
1566
     *
1567
     * @return array the content types ordered by the quality score. Types with the highest scores
1568
     * will be returned first. The array keys are the content types, while the array values
1569
     * are the corresponding quality score and other parameters as given in the header.
1570
     */
1571 2
    public function getAcceptableContentTypes()
1572
    {
1573 2
        if ($this->_contentTypes === null) {
1574 2
            if ($this->hasHeader('Accept')) {
1575 2
                $this->_contentTypes = $this->parseAcceptHeader($this->getHeaderLine('Accept'));
1576
            } else {
1577 1
                $this->_contentTypes = [];
1578
            }
1579
        }
1580
1581 2
        return $this->_contentTypes;
1582
    }
1583
1584
    /**
1585
     * Sets the acceptable content types.
1586
     * Please refer to [[getAcceptableContentTypes()]] on the format of the parameter.
1587
     * @param array $value the content types that are acceptable by the end user. They should
1588
     * be ordered by the preference level.
1589
     * @see getAcceptableContentTypes()
1590
     * @see parseAcceptHeader()
1591
     */
1592
    public function setAcceptableContentTypes($value)
1593
    {
1594
        $this->_contentTypes = $value;
1595
    }
1596
1597
    /**
1598
     * Returns request content-type
1599
     * The Content-Type header field indicates the MIME type of the data
1600
     * contained in [[getBody()]] or, in the case of the HEAD method, the
1601
     * media type that would have been sent had the request been a GET.
1602
     * For the MIME-types the user expects in response, see [[acceptableContentTypes]].
1603
     * @return string request content-type. Empty string is returned if this information is not available.
1604
     * @link https://tools.ietf.org/html/rfc2616#section-14.17
1605
     * HTTP 1.1 header field definitions
1606
     */
1607 16
    public function getContentType()
1608
    {
1609 16
        return $this->getHeaderLine('Content-Type');
1610
    }
1611
1612
    private $_languages;
1613
1614
    /**
1615
     * Returns the languages acceptable by the end user.
1616
     * This is determined by the `Accept-Language` HTTP header.
1617
     * @return array the languages ordered by the preference level. The first element
1618
     * represents the most preferred language.
1619
     */
1620 1
    public function getAcceptableLanguages()
1621
    {
1622 1
        if ($this->_languages === null) {
1623
            if ($this->hasHeader('Accept-Language')) {
1624
                $this->_languages = array_keys($this->parseAcceptHeader($this->getHeaderLine('Accept-Language')));
1625
            } else {
1626
                $this->_languages = [];
1627
            }
1628
        }
1629
1630 1
        return $this->_languages;
1631
    }
1632
1633
    /**
1634
     * @param array $value the languages that are acceptable by the end user. They should
1635
     * be ordered by the preference level.
1636
     */
1637 1
    public function setAcceptableLanguages($value)
1638
    {
1639 1
        $this->_languages = $value;
1640 1
    }
1641
1642
    /**
1643
     * Parses the given `Accept` (or `Accept-Language`) header.
1644
     *
1645
     * This method will return the acceptable values with their quality scores and the corresponding parameters
1646
     * as specified in the given `Accept` header. The array keys of the return value are the acceptable values,
1647
     * while the array values consisting of the corresponding quality scores and parameters. The acceptable
1648
     * values with the highest quality scores will be returned first. For example,
1649
     *
1650
     * ```php
1651
     * $header = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1652
     * $accepts = $request->parseAcceptHeader($header);
1653
     * print_r($accepts);
1654
     * // displays:
1655
     * // [
1656
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1657
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1658
     * //           'text/plain' => ['q' => 0.5],
1659
     * // ]
1660
     * ```
1661
     *
1662
     * @param string $header the header to be parsed
1663
     * @return array the acceptable values ordered by their quality score. The values with the highest scores
1664
     * will be returned first.
1665
     */
1666 3
    public function parseAcceptHeader($header)
1667
    {
1668 3
        $accepts = [];
1669 3
        foreach (explode(',', $header) as $i => $part) {
1670 3
            $params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY);
1671 3
            if (empty($params)) {
1672 1
                continue;
1673
            }
1674
            $values = [
1675 3
                'q' => [$i, array_shift($params), 1],
1676
            ];
1677 3
            foreach ($params as $param) {
1678 2
                if (strpos($param, '=') !== false) {
1679 2
                    [$key, $value] = explode('=', $param, 2);
0 ignored issues
show
Bug introduced by
The variable $key 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 $value does not exist. Did you mean $values?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1680 2
                    if ($key === 'q') {
1681 2
                        $values['q'][2] = (float) $value;
0 ignored issues
show
Bug introduced by
The variable $value does not exist. Did you mean $values?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1682
                    } else {
1683 2
                        $values[$key] = $value;
0 ignored issues
show
Bug introduced by
The variable $value does not exist. Did you mean $values?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1684
                    }
1685
                } else {
1686 2
                    $values[] = $param;
1687
                }
1688
            }
1689 3
            $accepts[] = $values;
1690
        }
1691
1692 3
        usort($accepts, function ($a, $b) {
1693 3
            $a = $a['q']; // index, name, q
1694 3
            $b = $b['q'];
1695 3
            if ($a[2] > $b[2]) {
1696 2
                return -1;
1697
            }
1698
1699 2
            if ($a[2] < $b[2]) {
1700 1
                return 1;
1701
            }
1702
1703 2
            if ($a[1] === $b[1]) {
1704
                return $a[0] > $b[0] ? 1 : -1;
1705
            }
1706
1707 2
            if ($a[1] === '*/*') {
1708
                return 1;
1709
            }
1710
1711 2
            if ($b[1] === '*/*') {
1712
                return -1;
1713
            }
1714
1715 2
            $wa = $a[1][strlen($a[1]) - 1] === '*';
1716 2
            $wb = $b[1][strlen($b[1]) - 1] === '*';
1717 2
            if ($wa xor $wb) {
1718
                return $wa ? 1 : -1;
1719
            }
1720
1721 2
            return $a[0] > $b[0] ? 1 : -1;
1722 3
        });
1723
1724 3
        $result = [];
1725 3
        foreach ($accepts as $accept) {
1726 3
            $name = $accept['q'][1];
1727 3
            $accept['q'] = $accept['q'][2];
1728 3
            $result[$name] = $accept;
1729
        }
1730
1731 3
        return $result;
1732
    }
1733
1734
    /**
1735
     * Returns the user-preferred language that should be used by this application.
1736
     * The language resolution is based on the user preferred languages and the languages
1737
     * supported by the application. The method will try to find the best match.
1738
     * @param array $languages a list of the languages supported by the application. If this is empty, the current
1739
     * application language will be returned without further processing.
1740
     * @return string the language that the application should use.
1741
     */
1742 1
    public function getPreferredLanguage(array $languages = [])
1743
    {
1744 1
        if (empty($languages)) {
1745 1
            return Yii::$app->language;
1746
        }
1747 1
        foreach ($this->getAcceptableLanguages() as $acceptableLanguage) {
1748 1
            $acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
1749 1
            foreach ($languages as $language) {
1750 1
                $normalizedLanguage = str_replace('_', '-', strtolower($language));
1751
1752
                if (
1753 1
                    $normalizedLanguage === $acceptableLanguage // en-us==en-us
1754 1
                    || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us
1755 1
                    || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en
1756
                ) {
1757 1
                    return $language;
1758
                }
1759
            }
1760
        }
1761
1762 1
        return reset($languages);
1763
    }
1764
1765
    /**
1766
     * Gets the Etags.
1767
     *
1768
     * @return array The entity tags
1769
     */
1770
    public function getETags()
1771
    {
1772
        if ($this->hasHeader('if-none-match')) {
1773
            return preg_split('/[\s,]+/', str_replace('-gzip', '', $this->getHeaderLine('if-none-match')), -1, PREG_SPLIT_NO_EMPTY);
1774
        }
1775
1776
        return [];
1777
    }
1778
1779
    /**
1780
     * Returns the cookie collection.
1781
     *
1782
     * Through the returned cookie collection, you may access a cookie using the following syntax:
1783
     *
1784
     * ```php
1785
     * $cookie = $request->cookies['name']
1786
     * if ($cookie !== null) {
1787
     *     $value = $cookie->value;
1788
     * }
1789
     *
1790
     * // alternatively
1791
     * $value = $request->cookies->getValue('name');
1792
     * ```
1793
     *
1794
     * @return CookieCollection the cookie collection.
1795
     */
1796 43
    public function getCookies()
1797
    {
1798 43
        if ($this->_cookies === null) {
1799 43
            $this->_cookies = new CookieCollection($this->loadCookies(), [
1800 42
                'readOnly' => true,
1801
            ]);
1802
        }
1803
1804 42
        return $this->_cookies;
1805
    }
1806
1807
    /**
1808
     * Converts [[cookieParams]] into an array of [[Cookie]].
1809
     * @return array the cookies obtained from request
1810
     * @throws InvalidConfigException if [[cookieValidationKey]] is not set when [[enableCookieValidation]] is true
1811
     */
1812 43
    protected function loadCookies()
1813
    {
1814 43
        $cookies = [];
1815 43
        if ($this->enableCookieValidation) {
1816 42
            if ($this->cookieValidationKey == '') {
1817 1
                throw new InvalidConfigException(get_class($this) . '::$cookieValidationKey must be configured with a secret key.');
1818
            }
1819 41
            foreach ($this->getCookieParams() as $name => $value) {
1820
                if (!is_string($value)) {
1821
                    continue;
1822
                }
1823
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
1824
                if ($data === false) {
1825
                    continue;
1826
                }
1827
                $data = @unserialize($data);
1828
                if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
1829
                    $cookies[$name] = Yii::createObject([
1830 41
                        '__class' => \yii\http\Cookie::class,
1831
                        'name' => $name,
1832
                        'value' => $data[1],
1833
                        'expire' => null,
1834
                    ]);
1835
                }
1836
            }
1837
        } else {
1838 1
            foreach ($this->getCookieParams() as $name => $value) {
1839 1
                $cookies[$name] = Yii::createObject([
1840 1
                    '__class' => \yii\http\Cookie::class,
1841 1
                    'name' => $name,
1842 1
                    'value' => $value,
1843
                    'expire' => null,
1844
                ]);
1845
            }
1846
        }
1847
1848 42
        return $cookies;
1849
    }
1850
1851
    /**
1852
     * {@inheritdoc}
1853
     * @since 2.1.0
1854
     */
1855 12
    public function getUploadedFiles()
1856
    {
1857 12
        if ($this->_uploadedFiles === null) {
1858 6
            $this->getParsedBody(); // uploaded files are the part of the body and may be set while its parsing
1859 6
            if ($this->_uploadedFiles === null) {
1860 6
                $this->_uploadedFiles = $this->defaultUploadedFiles();
1861
            }
1862
        }
1863 12
        return $this->_uploadedFiles;
1864
    }
1865
1866
    /**
1867
     * Sets uploaded files for this request.
1868
     * Data structure for the uploaded files should follow [PSR-7 Uploaded Files specs](http://www.php-fig.org/psr/psr-7/#16-uploaded-files).
1869
     * @param array|null $uploadedFiles uploaded files.
1870
     * @since 2.1.0
1871
     */
1872 6
    public function setUploadedFiles($uploadedFiles)
1873
    {
1874 6
        $this->_uploadedFiles = $uploadedFiles;
0 ignored issues
show
Documentation Bug introduced by
It seems like $uploadedFiles can be null. However, the property $_uploadedFiles is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

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

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
1875 6
    }
1876
1877
    /**
1878
     * {@inheritdoc}
1879
     * @since 2.1.0
1880
     */
1881
    public function withUploadedFiles(array $uploadedFiles)
1882
    {
1883
        $newInstance = clone $this;
1884
        $newInstance->setUploadedFiles($uploadedFiles);
1885
        return $newInstance;
1886
    }
1887
1888
    /**
1889
     * Initializes default uploaded files data structure parsing super-global $_FILES.
1890
     * @see http://www.php-fig.org/psr/psr-7/#16-uploaded-files
1891
     * @return array uploaded files.
1892
     * @since 2.1.0
1893
     */
1894 6
    protected function defaultUploadedFiles()
1895
    {
1896 6
        $files = [];
1897 6
        foreach ($_FILES as $class => $info) {
1898 3
            $files[$class] = [];
1899 3
            $this->populateUploadedFileRecursive($files[$class], $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
1900
        }
1901
1902 6
        return $files;
1903
    }
1904
1905
    /**
1906
     * Populates uploaded files array from $_FILE data structure recursively.
1907
     * @param array $files uploaded files array to be populated.
1908
     * @param mixed $names file names provided by PHP
1909
     * @param mixed $tempNames temporary file names provided by PHP
1910
     * @param mixed $types file types provided by PHP
1911
     * @param mixed $sizes file sizes provided by PHP
1912
     * @param mixed $errors uploading issues provided by PHP
1913
     * @since 2.1.0
1914
     */
1915 3
    private function populateUploadedFileRecursive(&$files, $names, $tempNames, $types, $sizes, $errors)
1916
    {
1917 3
        if (is_array($names)) {
1918 2
            foreach ($names as $i => $name) {
1919 2
                $files[$i] = [];
1920 2
                $this->populateUploadedFileRecursive($files[$i], $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
1921
            }
1922
        } else {
1923 3
            $files = Yii::createObject([
1924 3
                '__class' => $this->uploadedFileClass,
1925 3
                'clientFilename' => $names,
1926 3
                'tempFilename' => $tempNames,
1927 3
                'clientMediaType' => $types,
1928 3
                'size' => $sizes,
1929 3
                'error' => $errors,
1930
            ]);
1931
        }
1932 3
    }
1933
1934
    /**
1935
     * Returns an uploaded file according to the given name.
1936
     * Name can be either a string HTML form input name, e.g. 'Item[file]' or array path, e.g. `['Item', 'file']`.
1937
     * Note: this method returns `null` in case given name matches multiple files.
1938
     * @param string|array $name HTML form input name or array path.
1939
     * @return UploadedFileInterface|null uploaded file instance, `null` - if not found.
1940
     * @since 2.1.0
1941
     */
1942 1
    public function getUploadedFileByName($name)
1943
    {
1944 1
        $uploadedFile = $this->findUploadedFiles($name);
1945 1
        if ($uploadedFile instanceof UploadedFileInterface) {
1946 1
            return $uploadedFile;
1947
        }
1948 1
        return null;
1949
    }
1950
1951
    /**
1952
     * Returns the list of uploaded file instances according to the given name.
1953
     * Name can be either a string HTML form input name, e.g. 'Item[file]' or array path, e.g. `['Item', 'file']`.
1954
     * Note: this method does NOT preserve uploaded files structure - it returns instances in single-level array (list),
1955
     * even if they are set by nested keys.
1956
     * @param string|array $name HTML form input name or array path.
1957
     * @return UploadedFileInterface[] list of uploaded file instances.
1958
     * @since 2.1.0
1959
     */
1960 1
    public function getUploadedFilesByName($name)
1961
    {
1962 1
        $uploadedFiles = $this->findUploadedFiles($name);
1963 1
        if ($uploadedFiles === null) {
1964
            return [];
1965
        }
1966 1
        if ($uploadedFiles instanceof UploadedFileInterface) {
1967 1
            return [$uploadedFiles];
1968
        }
1969 1
        return $this->reduceUploadedFiles($uploadedFiles);
1970
    }
1971
1972
    /**
1973
     * Finds the uploaded file or set of uploaded files inside [[$uploadedFiles]] according to given name.
1974
     * Name can be either a string HTML form input name, e.g. 'Item[file]' or array path, e.g. `['Item', 'file']`.
1975
     * @param string|array $name HTML form input name or array path.
1976
     * @return UploadedFileInterface|array|null
1977
     * @since 2.1.0
1978
     */
1979 2
    private function findUploadedFiles($name)
1980
    {
1981 2
        if (!is_array($name)) {
1982 2
            $name = preg_split('/\\]\\[|\\[|\\]/s', $name, -1, PREG_SPLIT_NO_EMPTY);
1983
        }
1984 2
        return ArrayHelper::getValue($this->getUploadedFiles(), $name);
1985
    }
1986
1987
    /**
1988
     * Reduces complex uploaded files structure to the single-level array (list).
1989
     * @param array $uploadedFiles raw set of the uploaded files.
1990
     * @return UploadedFileInterface[] list of uploaded files.
1991
     * @since 2.1.0
1992
     */
1993
    private function reduceUploadedFiles($uploadedFiles)
1994
    {
1995 1
        return array_reduce($uploadedFiles, function ($carry, $item) {
1996 1
            if ($item instanceof UploadedFileInterface) {
1997 1
                $carry[] = $item;
1998
            } else {
1999 1
                $carry = array_merge($carry, $this->reduceUploadedFiles($item));
2000
            }
2001 1
            return $carry;
2002 1
        }, []);
2003
    }
2004
2005
    private $_csrfToken;
2006
2007
    /**
2008
     * Returns the token used to perform CSRF validation.
2009
     *
2010
     * This token is generated in a way to prevent [BREACH attacks](http://breachattack.com/). It may be passed
2011
     * along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.
2012
     * @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time
2013
     * this method is called, a new CSRF token will be generated and persisted (in session or cookie).
2014
     * @return string the token used to perform CSRF validation.
2015
     */
2016 49
    public function getCsrfToken($regenerate = false)
2017
    {
2018 49
        if ($this->_csrfToken === null || $regenerate) {
2019 49
            $token = $this->loadCsrfToken();
2020 48
            if ($regenerate || empty($token)) {
2021 45
                $token = $this->generateCsrfToken();
2022
            }
2023 48
            $this->_csrfToken = Yii::$app->security->maskToken($token);
2024
        }
2025
2026 48
        return $this->_csrfToken;
2027
    }
2028
2029
    /**
2030
     * Loads the CSRF token from cookie or session.
2031
     * @return string the CSRF token loaded from cookie or session. Null is returned if the cookie or session
2032
     * does not have CSRF token.
2033
     */
2034 49
    protected function loadCsrfToken()
2035
    {
2036 49
        if ($this->enableCsrfCookie) {
2037 45
            return $this->getCookies()->getValue($this->csrfParam);
2038
        }
2039
2040 4
        return Yii::$app->getSession()->get($this->csrfParam);
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
2041
    }
2042
2043
    /**
2044
     * Generates an unmasked random token used to perform CSRF validation.
2045
     * @return string the random token for CSRF validation.
2046
     */
2047 45
    protected function generateCsrfToken()
2048
    {
2049 45
        $token = Yii::$app->getSecurity()->generateRandomString();
2050 45
        if ($this->enableCsrfCookie) {
2051 44
            $cookie = $this->createCsrfCookie($token);
2052 44
            Yii::$app->getResponse()->getCookies()->add($cookie);
2053
        } else {
2054 1
            Yii::$app->getSession()->set($this->csrfParam, $token);
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
2055
        }
2056
2057 45
        return $token;
2058
    }
2059
2060
    /**
2061
     * @return string the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent.
2062
     */
2063 3
    public function getCsrfTokenFromHeader()
2064
    {
2065 3
        return $this->getHeaderLine(static::CSRF_HEADER);
2066
    }
2067
2068
    /**
2069
     * Creates a cookie with a randomly generated CSRF token.
2070
     * Initial values specified in [[csrfCookie]] will be applied to the generated cookie.
2071
     * @param string $token the CSRF token
2072
     * @return Cookie the generated cookie
2073
     * @see enableCsrfValidation
2074
     */
2075 44
    protected function createCsrfCookie($token)
2076
    {
2077 44
        $options = $this->csrfCookie;
2078 44
        return Yii::createObject(array_merge($options, [
2079 44
            '__class' => \yii\http\Cookie::class,
2080 44
            'name' => $this->csrfParam,
2081 44
            'value' => $token,
2082
        ]));
2083
    }
2084
2085
    /**
2086
     * Performs the CSRF validation.
2087
     *
2088
     * This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session.
2089
     * This method is mainly called in [[Controller::beforeAction()]].
2090
     *
2091
     * Note that the method will NOT perform CSRF validation if [[enableCsrfValidation]] is false or the HTTP method
2092
     * is among GET, HEAD or OPTIONS.
2093
     *
2094
     * @param string $clientSuppliedToken the user-provided CSRF token to be validated. If null, the token will be retrieved from
2095
     * the [[csrfParam]] POST field or HTTP header.
2096
     * This parameter is available since version 2.0.4.
2097
     * @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.
2098
     */
2099 36
    public function validateCsrfToken($clientSuppliedToken = null)
2100
    {
2101 36
        $method = $this->getMethod();
2102
        // only validate CSRF token on non-"safe" methods https://tools.ietf.org/html/rfc2616#section-9.1.1
2103 36
        if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
2104 35
            return true;
2105
        }
2106
2107 4
        $trueToken = $this->getCsrfToken();
2108
2109 4
        if ($clientSuppliedToken !== null) {
2110 2
            return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken);
2111
        }
2112
2113 3
        return $this->validateCsrfTokenInternal($this->getParsedBodyParam($this->csrfParam), $trueToken)
2114 3
            || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
2115
    }
2116
2117
    /**
2118
     * Validates CSRF token.
2119
     *
2120
     * @param string $clientSuppliedToken The masked client-supplied token.
2121
     * @param string $trueToken The masked true token.
2122
     * @return bool
2123
     */
2124 4
    private function validateCsrfTokenInternal($clientSuppliedToken, $trueToken)
2125
    {
2126 4
        if (!is_string($clientSuppliedToken)) {
2127 3
            return false;
2128
        }
2129
2130 4
        $security = Yii::$app->security;
2131
2132 4
        return $security->unmaskToken($clientSuppliedToken) === $security->unmaskToken($trueToken);
2133
    }
2134
2135
    /**
2136
     * {@inheritdoc}
2137
     * @since 2.1.0
2138
     */
2139 3
    public function getAttributes()
2140
    {
2141 3
        if ($this->_attributes === null) {
2142
            $this->_attributes = $this->defaultAttributes();
2143
        }
2144 3
        return $this->_attributes;
2145
    }
2146
2147
    /**
2148
     * @param array $attributes attributes derived from the request.
2149
     */
2150 3
    public function setAttributes(array $attributes)
2151
    {
2152 3
        $this->_attributes = $attributes;
2153 3
    }
2154
2155
    /**
2156
     * {@inheritdoc}
2157
     * @since 2.1.0
2158
     */
2159 1
    public function getAttribute($name, $default = null)
2160
    {
2161 1
        $attributes = $this->getAttributes();
2162 1
        if (!array_key_exists($name, $attributes)) {
2163 1
            return $default;
2164
        }
2165
2166 1
        return $attributes[$name];
2167
    }
2168
2169
    /**
2170
     * {@inheritdoc}
2171
     * @since 2.1.0
2172
     */
2173 1
    public function withAttribute($name, $value)
2174
    {
2175 1
        $attributes = $this->getAttributes();
2176 1
        if (array_key_exists($name, $attributes) && $attributes[$name] === $value) {
2177
            return $this;
2178
        }
2179
2180 1
        $attributes[$name] = $value;
2181
2182 1
        $newInstance = clone $this;
2183 1
        $newInstance->setAttributes($attributes);
2184 1
        return $newInstance;
2185
    }
2186
2187
    /**
2188
     * {@inheritdoc}
2189
     * @since 2.1.0
2190
     */
2191 1
    public function withoutAttribute($name)
2192
    {
2193 1
        $attributes = $this->getAttributes();
2194 1
        if (!array_key_exists($name, $attributes)) {
2195
            return $this;
2196
        }
2197
2198 1
        unset($attributes[$name]);
2199
2200 1
        $newInstance = clone $this;
2201 1
        $newInstance->setAttributes($attributes);
2202 1
        return $newInstance;
2203
    }
2204
2205
    /**
2206
     * Returns default server request attributes to be used in case they are not explicitly set.
2207
     * @return array attributes derived from the request.
2208
     * @since 2.1.0
2209
     */
2210
    protected function defaultAttributes()
2211
    {
2212
        return [];
2213
    }
2214
2215
    /**
2216
     * {@inheritdoc}
2217
     */
2218 4
    public function __clone()
2219
    {
2220 4
        parent::__clone();
2221
2222 4
        $this->cloneHttpMessageInternals();
2223
2224 4
        if (is_object($this->_cookies)) {
2225
            $this->_cookies = clone $this->_cookies;
2226
        }
2227
2228 4
        $this->_parsedBody = false;
2229 4
    }
2230
}
2231