Passed
Pull Request — master (#19437)
by Rutger
08:09
created

Request   F

Complexity

Total Complexity 284

Size/Duplication

Total Lines 1892
Duplicated Lines 0 %

Test Coverage

Coverage 77.5%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 533
dl 0
loc 1892
ccs 434
cts 560
cp 0.775
rs 2
c 2
b 0
f 0
wmc 284

83 Methods

Rating   Name   Duplication   Size   Complexity  
A setRawBody() 0 3 1
A getUserAgent() 0 3 1
A setScriptUrl() 0 3 2
A setBaseUrl() 0 3 1
A setUrl() 0 3 1
A getAuthPassword() 0 3 1
A setScriptFile() 0 3 1
A setSecurePort() 0 5 2
A setAcceptableLanguages() 0 3 1
A getSecurePort() 0 8 4
A getServerPort() 0 12 5
A getRemoteIP() 0 3 2
B getPreferredLanguage() 0 21 7
A getIsPut() 0 3 1
B getUserIpFromIpHeaders() 0 24 7
A getPort() 0 8 4
A getIsOptions() 0 3 1
A getIsPost() 0 3 1
A getSecureForwardedHeaderTrustedParts() 0 14 4
C getScriptUrl() 0 21 12
A getIsFlash() 0 5 2
B getAuthCredentials() 0 31 9
A getOrigin() 0 3 1
A validateCsrfTokenInternal() 0 9 2
A utf8Encode() 0 12 4
A createCsrfCookie() 0 7 1
A getIsHead() 0 3 1
A getServerName() 0 3 2
A getAcceptableContentTypes() 0 11 3
B getIsSecureConnection() 0 21 9
C getHostInfo() 0 31 16
A getETags() 0 7 2
A generateCsrfToken() 0 11 2
A get() 0 7 2
A getQueryParams() 0 7 2
A getContentType() 0 8 3
B getSecureForwardedHeaderParts() 0 38 7
A getTrustedHeaders() 0 22 5
A resolve() 0 15 3
A getUserIP() 0 4 2
A getCsrfToken() 0 11 5
A getQueryString() 0 3 2
A setAcceptableContentTypes() 0 3 1
A loadCsrfToken() 0 7 2
A getBodyParam() 0 14 5
A getBaseUrl() 0 7 2
A filterHeaders() 0 8 3
A getIsDelete() 0 3 1
B resolvePathInfo() 0 43 9
B getHeaders() 0 32 9
B getUserIpFromIpHeader() 0 32 8
A post() 0 7 2
B resolveRequestUri() 0 19 7
A getUserHost() 0 7 2
A setPathInfo() 0 3 2
A getSecureForwardedHeaderTrustedPart() 0 11 4
A setHostInfo() 0 4 2
A setQueryParams() 0 3 1
B getBodyParams() 0 39 9
A getIsPjax() 0 3 2
A getHostName() 0 7 2
A getAcceptableLanguages() 0 11 3
A getRemoteHost() 0 3 2
A getScriptFile() 0 11 3
A validateCsrfToken() 0 16 5
A getUrl() 0 7 2
A getIsAjax() 0 3 1
A getRawBody() 0 7 2
A getReferrer() 0 3 1
A getPathInfo() 0 7 2
A getIsGet() 0 3 1
A getAbsoluteUrl() 0 3 1
A getAuthUser() 0 3 1
A getQueryParam() 0 5 2
A getIpValidator() 0 3 1
A setPort() 0 5 2
A getCookies() 0 9 2
C loadCookies() 0 41 12
A getCsrfTokenFromHeader() 0 3 1
A getIsPatch() 0 3 1
A getMethod() 0 20 5
C parseAcceptHeader() 0 66 16
A setBodyParams() 0 3 1

How to fix   Complexity   

Complex Class

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

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

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

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\validators\IpValidator;
13
14
/**
15
 * The web Request class represents an HTTP request.
16
 *
17
 * It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.
18
 * Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST
19
 * parameters sent via other HTTP methods like PUT or DELETE.
20
 *
21
 * Request is configured as an application component in [[\yii\web\Application]] by default.
22
 * You can access that instance via `Yii::$app->request`.
23
 *
24
 * For more details and usage information on Request, see the [guide article on requests](guide:runtime-requests).
25
 *
26
 * @property-read string $absoluteUrl The currently requested absolute URL.
27
 * @property array $acceptableContentTypes The content types ordered by the quality score. Types with the
28
 * highest scores will be returned first. The array keys are the content types, while the array values are the
29
 * corresponding quality score and other parameters as given in the header.
30
 * @property array $acceptableLanguages The languages ordered by the preference level. The first element
31
 * represents the most preferred language.
32
 * @property-read array $authCredentials That contains exactly two elements: - 0: the username sent via HTTP
33
 * authentication, `null` if the username is not given - 1: the password sent via HTTP authentication, `null` if
34
 * the password is not given.
35
 * @property-read string|null $authPassword The password sent via HTTP authentication, `null` if the password
36
 * is not given.
37
 * @property-read string|null $authUser The username sent via HTTP authentication, `null` if the username is
38
 * not given.
39
 * @property string $baseUrl The relative URL for the application.
40
 * @property array|object $bodyParams The request parameters given in the request body. Note that the type of
41
 * this property differs in getter and setter. See [[getBodyParams()]] and [[setBodyParams()]] for details.
42
 * @property-read string $contentType Request content-type. Empty string is returned if this information is
43
 * not available.
44
 * @property-read CookieCollection $cookies The cookie collection.
45
 * @property-read string $csrfToken The token used to perform CSRF validation.
46
 * @property-read string $csrfTokenFromHeader The CSRF token sent via [[CSRF_HEADER]] by browser. Null is
47
 * returned if no such header is sent.
48
 * @property-read array $eTags The entity tags.
49
 * @property-read HeaderCollection $headers The header collection.
50
 * @property string|null $hostInfo Schema and hostname part (with port number if needed) of the request URL
51
 * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. See
52
 * [[getHostInfo()]] for security related notes on this property.
53
 * @property-read string|null $hostName Hostname part of the request URL (e.g. `www.yiiframework.com`).
54
 * @property-read bool $isAjax Whether this is an AJAX (XMLHttpRequest) request.
55
 * @property-read bool $isDelete Whether this is a DELETE request.
56
 * @property-read bool $isFlash Whether this is an Adobe Flash or Adobe Flex request.
57
 * @property-read bool $isGet Whether this is a GET request.
58
 * @property-read bool $isHead Whether this is a HEAD request.
59
 * @property-read bool $isOptions Whether this is a OPTIONS request.
60
 * @property-read bool $isPatch Whether this is a PATCH request.
61
 * @property-read bool $isPjax Whether this is a PJAX request.
62
 * @property-read bool $isPost Whether this is a POST request.
63
 * @property-read bool $isPut Whether this is a PUT request.
64
 * @property-read bool $isSecureConnection If the request is sent via secure channel (https).
65
 * @property-read string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value
66
 * returned is turned into upper case.
67
 * @property-read string|null $origin URL origin of a CORS request, `null` if not available.
68
 * @property string $pathInfo Part of the request URL that is after the entry script and before the question
69
 * mark. Note, the returned path info is already URL-decoded.
70
 * @property int $port Port number for insecure requests.
71
 * @property array $queryParams The request GET parameter values.
72
 * @property-read string $queryString Part of the request URL that is after the question mark.
73
 * @property string $rawBody The request body.
74
 * @property-read string|null $referrer URL referrer, null if not available.
75
 * @property-read string|null $remoteHost Remote host name, `null` if not available.
76
 * @property-read string|null $remoteIP Remote IP address, `null` if not available.
77
 * @property string $scriptFile The entry script file path.
78
 * @property string $scriptUrl The relative URL of the entry script.
79
 * @property int $securePort Port number for secure requests.
80
 * @property-read string $serverName Server name, null if not available.
81
 * @property-read int|null $serverPort Server port number, null if not available.
82
 * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded
83
 * depending on the client.
84
 * @property-read string|null $userAgent User agent, null if not available.
85
 * @property-read string|null $userHost User host name, null if not available.
86
 * @property-read string|null $userIP User IP address, null if not available.
87
 *
88
 * @author Qiang Xue <[email protected]>
89
 * @since 2.0
90
 * @SuppressWarnings(PHPMD.SuperGlobals)
91
 */
92
class Request extends \yii\base\Request
93
{
94
    /**
95
     * The name of the HTTP header for sending CSRF token.
96
     */
97
    const CSRF_HEADER = 'X-CSRF-Token';
98
    /**
99
     * The length of the CSRF token mask.
100
     * @deprecated since 2.0.12. The mask length is now equal to the token length.
101
     */
102
    const CSRF_MASK_LENGTH = 8;
103
104
    /**
105
     * @var bool whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true.
106
     * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated
107
     * from the same application. If not, a 400 HTTP exception will be raised.
108
     *
109
     * Note, this feature requires that the user client accepts cookie. Also, to use this feature,
110
     * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfParam]].
111
     * You may use [[\yii\helpers\Html::beginForm()]] to generate his hidden input.
112
     *
113
     * In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and
114
     * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered.
115
     * You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]].
116
     *
117
     * @see Controller::enableCsrfValidation
118
     * @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
119
     */
120
    public $enableCsrfValidation = true;
121
    /**
122
     * @var string the name of the token used to prevent CSRF. Defaults to '_csrf'.
123
     * This property is used only when [[enableCsrfValidation]] is true.
124
     */
125
    public $csrfParam = '_csrf';
126
    /**
127
     * @var array the configuration for creating the CSRF [[Cookie|cookie]]. This property is used only when
128
     * both [[enableCsrfValidation]] and [[enableCsrfCookie]] are true.
129
     */
130
    public $csrfCookie = ['httpOnly' => true];
131
    /**
132
     * @var bool whether to use cookie to persist CSRF token. If false, CSRF token will be stored
133
     * in session under the name of [[csrfParam]]. Note that while storing CSRF tokens in session increases
134
     * security, it requires starting a session for every page, which will degrade your site performance.
135
     */
136
    public $enableCsrfCookie = true;
137
    /**
138
     * @var bool whether cookies should be validated to ensure they are not tampered. Defaults to true.
139
     */
140
    public $enableCookieValidation = true;
141
    /**
142
     * @var string a secret key used for cookie validation. This property must be set if [[enableCookieValidation]] is true.
143
     */
144
    public $cookieValidationKey;
145
    /**
146
     * @var string the name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE
147
     * request tunneled through POST. Defaults to '_method'.
148
     * @see getMethod()
149
     * @see getBodyParams()
150
     */
151
    public $methodParam = '_method';
152
    /**
153
     * @var array the parsers for converting the raw HTTP request body into [[bodyParams]].
154
     * The array keys are the request `Content-Types`, and the array values are the
155
     * corresponding configurations for [[Yii::createObject|creating the parser objects]].
156
     * A parser must implement the [[RequestParserInterface]].
157
     *
158
     * To enable parsing for JSON requests you can use the [[JsonParser]] class like in the following example:
159
     *
160
     * ```
161
     * [
162
     *     'application/json' => 'yii\web\JsonParser',
163
     * ]
164
     * ```
165
     *
166
     * To register a parser for parsing all request types you can use `'*'` as the array key.
167
     * This one will be used as a fallback in case no other types match.
168
     *
169
     * @see getBodyParams()
170
     */
171
    public $parsers = [];
172
    /**
173
     * @var array the configuration for trusted security related headers.
174
     *
175
     * An array key is an IPv4 or IPv6 IP address in CIDR notation for matching a client.
176
     *
177
     * An array value is a list of headers to trust. These will be matched against
178
     * [[secureHeaders]] to determine which headers are allowed to be sent by a specified host.
179
     * The case of the header names must be the same as specified in [[secureHeaders]].
180
     *
181
     * For example, to trust all headers listed in [[secureHeaders]] for IP addresses
182
     * in range `192.168.0.0-192.168.0.254` write the following:
183
     *
184
     * ```php
185
     * [
186
     *     '192.168.0.0/24',
187
     * ]
188
     * ```
189
     *
190
     * To trust just the `X-Forwarded-For` header from `10.0.0.1`, use:
191
     *
192
     * ```
193
     * [
194
     *     '10.0.0.1' => ['X-Forwarded-For']
195
     * ]
196
     * ```
197
     *
198
     * Default is to trust all headers except those listed in [[secureHeaders]] from all hosts.
199
     * Matches are tried in order and searching is stopped when IP matches.
200
     *
201
     * > Info: Matching is performed using [[IpValidator]].
202
     * See [[IpValidator::::setRanges()|IpValidator::setRanges()]]
203
     * and [[IpValidator::networks]] for advanced matching.
204
     *
205
     * @see secureHeaders
206
     * @since 2.0.13
207
     */
208
    public $trustedHosts = [];
209
    /**
210
     * @var array lists of headers that are, by default, subject to the trusted host configuration.
211
     * These headers will be filtered unless explicitly allowed in [[trustedHosts]].
212
     * If the list contains the `Forwarded` header, processing will be done according to RFC 7239.
213
     * The match of header names is case-insensitive.
214
     * @see https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
215
     * @see https://datatracker.ietf.org/doc/html/rfc7239
216
     * @see trustedHosts
217
     * @since 2.0.13
218
     */
219
    public $secureHeaders = [
220
        // Common:
221
        'X-Forwarded-For',
222
        'X-Forwarded-Host',
223
        'X-Forwarded-Proto',
224
        'X-Forwarded-Port',
225
226
        // Microsoft:
227
        'Front-End-Https',
228
        'X-Rewrite-Url',
229
230
        // ngrok:
231
        'X-Original-Host',
232
    ];
233
    /**
234
     * @var string[] List of headers where proxies store the real client IP.
235
     * It's not advisable to put insecure headers here.
236
     * To use the `Forwarded` header according to RFC 7239, the header must be added to [[secureHeaders]] list.
237
     * The match of header names is case-insensitive.
238
     * @see trustedHosts
239
     * @see secureHeaders
240
     * @since 2.0.13
241
     */
242
    public $ipHeaders = [
243
        'X-Forwarded-For', // Common
244
    ];
245
    /**
246
     * @var string[] List of headers where proxies store the real request port.
247
     * It's not advisable to put insecure headers here.
248
     * To use the `Forwarded Port`, the header must be added to [[secureHeaders]] list.
249
     * The match of header names is case-insensitive.
250
     * @see trustedHosts
251
     * @see secureHeaders
252
     * @since 2.0.46
253
     */
254
    public $portHeaders = [
255
        'X-Forwarded-Port', // Common
256
    ];
257
    /**
258
     * @var array list of headers to check for determining whether the connection is made via HTTPS.
259
     * The array keys are header names and the array value is a list of header values that indicate a secure connection.
260
     * The match of header names and values is case-insensitive.
261
     * It's not advisable to put insecure headers here.
262
     * @see trustedHosts
263
     * @see secureHeaders
264
     * @since 2.0.13
265
     */
266
    public $secureProtocolHeaders = [
267
        'X-Forwarded-Proto' => ['https'], // Common
268
        'Front-End-Https' => ['on'], // Microsoft
269
    ];
270
271
    /**
272
     * @var CookieCollection Collection of request cookies.
273
     */
274
    private $_cookies;
275
    /**
276
     * @var HeaderCollection Collection of request headers.
277
     */
278
    private $_headers;
279
280
281
    /**
282
     * Resolves the current request into a route and the associated parameters.
283
     * @return array the first element is the route, and the second is the associated parameters.
284
     * @throws NotFoundHttpException if the request cannot be resolved.
285
     */
286 1
    public function resolve()
287
    {
288 1
        $result = Yii::$app->getUrlManager()->parseRequest($this);
289 1
        if ($result !== false) {
290 1
            list($route, $params) = $result;
291 1
            if ($this->_queryParams === null) {
292 1
                $_GET = $params + $_GET; // preserve numeric keys
293
            } else {
294 1
                $this->_queryParams = $params + $this->_queryParams;
295
            }
296
297 1
            return [$route, $this->getQueryParams()];
298
        }
299
300
        throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
301
    }
302
303
    /**
304
     * Filters headers according to the [[trustedHosts]].
305
     * @param HeaderCollection $headerCollection
306
     * @since 2.0.13
307
     */
308 260
    protected function filterHeaders(HeaderCollection $headerCollection)
309
    {
310 260
        $trustedHeaders = $this->getTrustedHeaders();
311
312
        // remove all secure headers unless they are trusted
313 260
        foreach ($this->secureHeaders as $secureHeader) {
314 260
            if (!in_array($secureHeader, $trustedHeaders)) {
315 240
                $headerCollection->remove($secureHeader);
316
            }
317
        }
318 260
    }
319
320
    /**
321
     * Trusted headers according to the [[trustedHosts]].
322
     * @return array
323
     * @since 2.0.28
324
     */
325 260
    protected function getTrustedHeaders()
326
    {
327
        // do not trust any of the [[secureHeaders]] by default
328 260
        $trustedHeaders = [];
329
330
        // check if the client is a trusted host
331 260
        if (!empty($this->trustedHosts)) {
332 83
            $validator = $this->getIpValidator();
333 83
            $ip = $this->getRemoteIP();
334 83
            foreach ($this->trustedHosts as $cidr => $headers) {
335 83
                if (!is_array($headers)) {
336 81
                    $cidr = $headers;
337 81
                    $headers = $this->secureHeaders;
338
                }
339 83
                $validator->setRanges($cidr);
340 83
                if ($validator->validate($ip)) {
341 40
                    $trustedHeaders = $headers;
342 40
                    break;
343
                }
344
            }
345
        }
346 260
        return $trustedHeaders;
347
    }
348
349
    /**
350
     * Creates instance of [[IpValidator]].
351
     * You can override this method to adjust validator or implement different matching strategy.
352
     *
353
     * @return IpValidator
354
     * @since 2.0.13
355
     */
356 176
    protected function getIpValidator()
357
    {
358 176
        return new IpValidator();
359
    }
360
361
    /**
362
     * Returns the header collection.
363
     * The header collection contains incoming HTTP headers.
364
     * @return HeaderCollection the header collection
365
     */
366 260
    public function getHeaders()
367
    {
368 260
        if ($this->_headers === null) {
369 260
            $this->_headers = new HeaderCollection();
370 260
            if (function_exists('getallheaders')) {
371
                $headers = getallheaders();
372
                foreach ($headers as $name => $value) {
373
                    $this->_headers->add($name, $value);
374
                }
375 260
            } elseif (function_exists('http_get_request_headers')) {
376
                $headers = http_get_request_headers();
377
                foreach ($headers as $name => $value) {
378
                    $this->_headers->add($name, $value);
379
                }
380
            } else {
381
                // ['prefix' => length]
382 260
                $headerPrefixes = ['HTTP_' => 5, 'REDIRECT_HTTP_' => 14];
383
384 260
                foreach ($_SERVER as $name => $value) {
385 256
                    foreach ($headerPrefixes as $prefix => $length) {
386 256
                        if (strncmp($name, $prefix, $length) === 0) {
387 119
                            $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, $length)))));
388 119
                            $this->_headers->add($name, $value);
389 119
                            continue 2;
390
                        }
391
                    }
392
                }
393
            }
394 260
            $this->filterHeaders($this->_headers);
395
        }
396
397 260
        return $this->_headers;
398
    }
399
400
    /**
401
     * Returns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE).
402
     * @return string request method, such as GET, POST, HEAD, PUT, PATCH, DELETE.
403
     * The value returned is turned into upper case.
404
     */
405 43
    public function getMethod()
406
    {
407
        if (
408 43
            isset($_POST[$this->methodParam])
409
            // Never allow to downgrade request from WRITE methods (POST, PATCH, DELETE, etc)
410
            // to read methods (GET, HEAD, OPTIONS) for security reasons.
411 43
            && !in_array(strtoupper($_POST[$this->methodParam]), ['GET', 'HEAD', 'OPTIONS'], true)
412
        ) {
413 6
            return strtoupper($_POST[$this->methodParam]);
414
        }
415
416 41
        if ($this->headers->has('X-Http-Method-Override')) {
417 1
            return strtoupper($this->headers->get('X-Http-Method-Override'));
0 ignored issues
show
Bug introduced by
It seems like $this->headers->get('X-Http-Method-Override') can also be of type array and null; however, parameter $string of strtoupper() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

417
            return strtoupper(/** @scrutinizer ignore-type */ $this->headers->get('X-Http-Method-Override'));
Loading history...
418
        }
419
420 40
        if (isset($_SERVER['REQUEST_METHOD'])) {
421 10
            return strtoupper($_SERVER['REQUEST_METHOD']);
422
        }
423
424 31
        return 'GET';
425
    }
426
427
    /**
428
     * Returns whether this is a GET request.
429
     * @return bool whether this is a GET request.
430
     */
431 2
    public function getIsGet()
432
    {
433 2
        return $this->getMethod() === 'GET';
434
    }
435
436
    /**
437
     * Returns whether this is an OPTIONS request.
438
     * @return bool whether this is a OPTIONS request.
439
     */
440 3
    public function getIsOptions()
441
    {
442 3
        return $this->getMethod() === 'OPTIONS';
443
    }
444
445
    /**
446
     * Returns whether this is a HEAD request.
447
     * @return bool whether this is a HEAD request.
448
     */
449 15
    public function getIsHead()
450
    {
451 15
        return $this->getMethod() === 'HEAD';
452
    }
453
454
    /**
455
     * Returns whether this is a POST request.
456
     * @return bool whether this is a POST request.
457
     */
458
    public function getIsPost()
459
    {
460
        return $this->getMethod() === 'POST';
461
    }
462
463
    /**
464
     * Returns whether this is a DELETE request.
465
     * @return bool whether this is a DELETE request.
466
     */
467
    public function getIsDelete()
468
    {
469
        return $this->getMethod() === 'DELETE';
470
    }
471
472
    /**
473
     * Returns whether this is a PUT request.
474
     * @return bool whether this is a PUT request.
475
     */
476
    public function getIsPut()
477
    {
478
        return $this->getMethod() === 'PUT';
479
    }
480
481
    /**
482
     * Returns whether this is a PATCH request.
483
     * @return bool whether this is a PATCH request.
484
     */
485
    public function getIsPatch()
486
    {
487
        return $this->getMethod() === 'PATCH';
488
    }
489
490
    /**
491
     * Returns whether this is an AJAX (XMLHttpRequest) request.
492
     *
493
     * Note that in case of cross domain requests, browser doesn't set the X-Requested-With header by default:
494
     * https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header
495
     *
496
     * In case you are using `fetch()`, pass header manually:
497
     *
498
     * ```
499
     * fetch(url, {
500
     *    method: 'GET',
501
     *    headers: {'X-Requested-With': 'XMLHttpRequest'}
502
     * })
503
     * ```
504
     *
505
     * @return bool whether this is an AJAX (XMLHttpRequest) request.
506
     */
507 16
    public function getIsAjax()
508
    {
509 16
        return $this->headers->get('X-Requested-With') === 'XMLHttpRequest';
510
    }
511
512
    /**
513
     * Returns whether this is a PJAX request.
514
     * @return bool whether this is a PJAX request
515
     */
516 3
    public function getIsPjax()
517
    {
518 3
        return $this->getIsAjax() && $this->headers->has('X-Pjax');
519
    }
520
521
    /**
522
     * Returns whether this is an Adobe Flash or Flex request.
523
     * @return bool whether this is an Adobe Flash or Adobe Flex request.
524
     */
525
    public function getIsFlash()
526
    {
527
        $userAgent = $this->headers->get('User-Agent', '');
528
        return stripos($userAgent, 'Shockwave') !== false
0 ignored issues
show
Bug introduced by
It seems like $userAgent can also be of type array and null; however, parameter $haystack of stripos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

528
        return stripos(/** @scrutinizer ignore-type */ $userAgent, 'Shockwave') !== false
Loading history...
529
            || stripos($userAgent, 'Flash') !== false;
530
    }
531
532
    private $_rawBody;
533
534
    /**
535
     * Returns the raw HTTP request body.
536
     * @return string the request body
537
     */
538 7
    public function getRawBody()
539
    {
540 7
        if ($this->_rawBody === null) {
541 4
            $this->_rawBody = file_get_contents('php://input');
542
        }
543
544 7
        return $this->_rawBody;
545
    }
546
547
    /**
548
     * Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
549
     * @param string $rawBody the request body
550
     */
551 3
    public function setRawBody($rawBody)
552
    {
553 3
        $this->_rawBody = $rawBody;
554 3
    }
555
556
    private $_bodyParams;
557
558
    /**
559
     * Returns the request parameters given in the request body.
560
     *
561
     * Request parameters are determined using the parsers configured in [[parsers]] property.
562
     * If no parsers are configured for the current [[contentType]] it uses the PHP function `mb_parse_str()`
563
     * to parse the [[rawBody|request body]].
564
     * @return array|object the request parameters given in the request body.
565
     * @throws \yii\base\InvalidConfigException if a registered parser does not implement the [[RequestParserInterface]].
566
     * @see getMethod()
567
     * @see getBodyParam()
568
     * @see setBodyParams()
569
     */
570 16
    public function getBodyParams()
571
    {
572 16
        if ($this->_bodyParams === null) {
573 8
            if (isset($_POST[$this->methodParam])) {
574 1
                $this->_bodyParams = $_POST;
575 1
                unset($this->_bodyParams[$this->methodParam]);
576 1
                return $this->_bodyParams;
577
            }
578
579 7
            $rawContentType = $this->getContentType();
580 7
            if (($pos = strpos((string)$rawContentType, ';')) !== false) {
581
                // e.g. text/html; charset=UTF-8
582
                $contentType = substr($rawContentType, 0, $pos);
583
            } else {
584 7
                $contentType = $rawContentType;
585
            }
586
587 7
            if (isset($this->parsers[$contentType])) {
588 2
                $parser = Yii::createObject($this->parsers[$contentType]);
589 2
                if (!($parser instanceof RequestParserInterface)) {
590
                    throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
591
                }
592 2
                $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
593 5
            } elseif (isset($this->parsers['*'])) {
594
                $parser = Yii::createObject($this->parsers['*']);
595
                if (!($parser instanceof RequestParserInterface)) {
596
                    throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.');
597
                }
598
                $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
599 5
            } elseif ($this->getMethod() === 'POST') {
600
                // PHP has already parsed the body so we have all params in $_POST
601
                $this->_bodyParams = $_POST;
602
            } else {
603 5
                $this->_bodyParams = [];
604 5
                mb_parse_str($this->getRawBody(), $this->_bodyParams);
605
            }
606
        }
607
608 16
        return $this->_bodyParams;
609
    }
610
611
    /**
612
     * Sets the request body parameters.
613
     *
614
     * @param array|object $values the request body parameters (name-value pairs)
615
     * @see getBodyParams()
616
     */
617 11
    public function setBodyParams($values)
618
    {
619 11
        $this->_bodyParams = $values;
620 11
    }
621
622
    /**
623
     * Returns the named request body parameter value.
624
     *
625
     * If the parameter does not exist, the second parameter passed to this method will be returned.
626
     *
627
     * @param string $name the parameter name
628
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
629
     * @return mixed the parameter value
630
     * @see getBodyParams()
631
     * @see setBodyParams()
632
     */
633 7
    public function getBodyParam($name, $defaultValue = null)
634
    {
635 7
        $params = $this->getBodyParams();
636
637 7
        if (is_object($params)) {
638
            // unable to use `ArrayHelper::getValue()` due to different dots in key logic and lack of exception handling
639
            try {
640 1
                return isset($params->{$name}) ? $params->{$name} : $defaultValue;
641
            } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) is not 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...
642
                return $defaultValue;
643
            }
644
        }
645
646 7
        return isset($params[$name]) ? $params[$name] : $defaultValue;
647
    }
648
649
    /**
650
     * Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters.
651
     *
652
     * @param string $name the parameter name
653
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
654
     * @return array|mixed
655
     */
656
    public function post($name = null, $defaultValue = null)
657
    {
658
        if ($name === null) {
659
            return $this->getBodyParams();
660
        }
661
662
        return $this->getBodyParam($name, $defaultValue);
663
    }
664
665
    private $_queryParams;
666
667
    /**
668
     * Returns the request parameters given in the [[queryString]].
669
     *
670
     * This method will return the contents of `$_GET` if params where not explicitly set.
671
     * @return array the request GET parameter values.
672
     * @see setQueryParams()
673
     */
674 65
    public function getQueryParams()
675
    {
676 65
        if ($this->_queryParams === null) {
677 58
            return $_GET;
678
        }
679
680 9
        return $this->_queryParams;
681
    }
682
683
    /**
684
     * Sets the request [[queryString]] parameters.
685
     * @param array $values the request query parameters (name-value pairs)
686
     * @see getQueryParam()
687
     * @see getQueryParams()
688
     */
689 9
    public function setQueryParams($values)
690
    {
691 9
        $this->_queryParams = $values;
692 9
    }
693
694
    /**
695
     * Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.
696
     *
697
     * @param string $name the parameter name
698
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
699
     * @return array|mixed
700
     */
701 29
    public function get($name = null, $defaultValue = null)
702
    {
703 29
        if ($name === null) {
704
            return $this->getQueryParams();
705
        }
706
707 29
        return $this->getQueryParam($name, $defaultValue);
708
    }
709
710
    /**
711
     * Returns the named GET parameter value.
712
     * If the GET parameter does not exist, the second parameter passed to this method will be returned.
713
     * @param string $name the GET parameter name.
714
     * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
715
     * @return mixed the GET parameter value
716
     * @see getBodyParam()
717
     */
718 32
    public function getQueryParam($name, $defaultValue = null)
719
    {
720 32
        $params = $this->getQueryParams();
721
722 32
        return isset($params[$name]) ? $params[$name] : $defaultValue;
723
    }
724
725
    private $_hostInfo;
726
    private $_hostName;
727
728
    /**
729
     * Returns the schema and host part of the current request URL.
730
     *
731
     * The returned URL does not have an ending slash.
732
     *
733
     * By default this value is based on the user request information. This method will
734
     * return the value of `$_SERVER['HTTP_HOST']` if it is available or `$_SERVER['SERVER_NAME']` if not.
735
     * You may want to check out the [PHP documentation](https://www.php.net/manual/en/reserved.variables.server.php)
736
     * for more information on these variables.
737
     *
738
     * You may explicitly specify it by setting the [[setHostInfo()|hostInfo]] property.
739
     *
740
     * > Warning: Dependent on the server configuration this information may not be
741
     * > reliable and [may be faked by the user sending the HTTP request](https://www.acunetix.com/vulnerabilities/web/host-header-attack).
742
     * > If the webserver is configured to serve the same site independent of the value of
743
     * > the `Host` header, this value is not reliable. In such situations you should either
744
     * > fix your webserver configuration or explicitly set the value by setting the [[setHostInfo()|hostInfo]] property.
745
     * > If you don't have access to the server configuration, you can setup [[\yii\filters\HostControl]] filter at
746
     * > application level in order to protect against such kind of attack.
747
     *
748
     * @property string|null schema and hostname part (with port number if needed) of the request URL
749
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
750
     * See [[getHostInfo()]] for security related notes on this property.
751
     * @return string|null schema and hostname part (with port number if needed) of the request URL
752
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
753
     * @see setHostInfo()
754
     */
755 55
    public function getHostInfo()
756
    {
757 55
        if ($this->_hostInfo === null) {
758 51
            $secure = $this->getIsSecureConnection();
759 51
            $http = $secure ? 'https' : 'http';
760
761 51
            if ($this->getSecureForwardedHeaderTrustedPart('host') !== null) {
762 8
                $this->_hostInfo = $http . '://' . $this->getSecureForwardedHeaderTrustedPart('host');
763 43
            } elseif ($this->headers->has('X-Forwarded-Host')) {
764 3
                $this->_hostInfo = $http . '://' . trim(explode(',', $this->headers->get('X-Forwarded-Host'))[0]);
0 ignored issues
show
Bug introduced by
It seems like $this->headers->get('X-Forwarded-Host') can also be of type array and null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

764
                $this->_hostInfo = $http . '://' . trim(explode(',', /** @scrutinizer ignore-type */ $this->headers->get('X-Forwarded-Host'))[0]);
Loading history...
765 40
            } elseif ($this->headers->has('X-Original-Host')) {
766
                $this->_hostInfo = $http . '://' . trim(explode(',', $this->headers->get('X-Original-Host'))[0]);
767
            } else {
768 40
                if ($this->headers->has('Host')) {
769 15
                    $this->_hostInfo = $http . '://' . $this->headers->get('Host');
0 ignored issues
show
Bug introduced by
Are you sure $this->headers->get('Host') of type array|null|string can be used in concatenation? ( Ignorable by Annotation )

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

769
                    $this->_hostInfo = $http . '://' . /** @scrutinizer ignore-type */ $this->headers->get('Host');
Loading history...
770 25
                } elseif (filter_has_var(INPUT_SERVER, 'SERVER_NAME')) {
771
                    $this->_hostInfo = $http . '://' . filter_input(INPUT_SERVER, 'SERVER_NAME');
772 25
                } elseif (isset($_SERVER['SERVER_NAME'])) {
773 3
                    $this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME'];
774
                }
775
776 40
                if ($this->_hostInfo !== null && !preg_match('/:\d+$/', $this->_hostInfo)) {
777 16
                    $port = $secure ? $this->getSecurePort() : $this->getPort();
778 16
                    if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
779 2
                        $this->_hostInfo .= ':' . $port;
780
                    }
781
                }
782
            }
783
        }
784
785 55
        return $this->_hostInfo;
786
    }
787
788
    /**
789
     * Sets the schema and host part of the application URL.
790
     * This setter is provided in case the schema and hostname cannot be determined
791
     * on certain Web servers.
792
     * @param string|null $value the schema and host part of the application URL. The trailing slashes will be removed.
793
     * @see getHostInfo() for security related notes on this property.
794
     */
795 59
    public function setHostInfo($value)
796
    {
797 59
        $this->_hostName = null;
798 59
        $this->_hostInfo = $value === null ? null : rtrim($value, '/');
799 59
    }
800
801
    /**
802
     * Returns the host part of the current request URL.
803
     * Value is calculated from current [[getHostInfo()|hostInfo]] property.
804
     *
805
     * > Warning: The content of this value may not be reliable, dependent on the server
806
     * > configuration. Please refer to [[getHostInfo()]] for more information.
807
     *
808
     * @return string|null hostname part of the request URL (e.g. `www.yiiframework.com`)
809
     * @see getHostInfo()
810
     * @since 2.0.10
811
     */
812 26
    public function getHostName()
813
    {
814 26
        if ($this->_hostName === null) {
815 26
            $this->_hostName = parse_url((string)$this->getHostInfo(), PHP_URL_HOST);
816
        }
817
818 26
        return $this->_hostName;
819
    }
820
821
    private $_baseUrl;
822
823
    /**
824
     * Returns the relative URL for the application.
825
     * This is similar to [[scriptUrl]] except that it does not include the script file name,
826
     * and the ending slashes are removed.
827
     * @return string the relative URL for the application
828
     * @see setScriptUrl()
829
     */
830 449
    public function getBaseUrl()
831
    {
832 449
        if ($this->_baseUrl === null) {
833 447
            $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/');
834
        }
835
836 449
        return $this->_baseUrl;
837
    }
838
839
    /**
840
     * Sets the relative URL for the application.
841
     * By default the URL is determined based on the entry script URL.
842
     * This setter is provided in case you want to change this behavior.
843
     * @param string $value the relative URL for the application
844
     */
845 2
    public function setBaseUrl($value)
846
    {
847 2
        $this->_baseUrl = $value;
848 2
    }
849
850
    private $_scriptUrl;
851
852
    /**
853
     * Returns the relative URL of the entry script.
854
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
855
     * @return string the relative URL of the entry script.
856
     * @throws InvalidConfigException if unable to determine the entry script URL
857
     */
858 450
    public function getScriptUrl()
859
    {
860 450
        if ($this->_scriptUrl === null) {
861 1
            $scriptFile = $this->getScriptFile();
862
            $scriptName = basename($scriptFile);
863
            if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
864
                $this->_scriptUrl = $_SERVER['SCRIPT_NAME'];
865
            } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $scriptName) {
866
                $this->_scriptUrl = $_SERVER['PHP_SELF'];
867
            } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
868
                $this->_scriptUrl = $_SERVER['ORIG_SCRIPT_NAME'];
869
            } elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
870
                $this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
871
            } elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) {
872
                $this->_scriptUrl = str_replace([$_SERVER['DOCUMENT_ROOT'], '\\'], ['', '/'], $scriptFile);
873
            } else {
874
                throw new InvalidConfigException('Unable to determine the entry script URL.');
875
            }
876
        }
877
878 449
        return $this->_scriptUrl;
879
    }
880
881
    /**
882
     * Sets the relative URL for the application entry script.
883
     * This setter is provided in case the entry script URL cannot be determined
884
     * on certain Web servers.
885
     * @param string $value the relative URL for the application entry script.
886
     */
887 460
    public function setScriptUrl($value)
888
    {
889 460
        $this->_scriptUrl = $value === null ? null : '/' . trim($value, '/');
0 ignored issues
show
introduced by
The condition $value === null is always false.
Loading history...
890 460
    }
891
892
    private $_scriptFile;
893
894
    /**
895
     * Returns the entry script file path.
896
     * The default implementation will simply return `$_SERVER['SCRIPT_FILENAME']`.
897
     * @return string the entry script file path
898
     * @throws InvalidConfigException
899
     */
900 451
    public function getScriptFile()
901
    {
902 451
        if (isset($this->_scriptFile)) {
903 422
            return $this->_scriptFile;
904
        }
905
906 29
        if (isset($_SERVER['SCRIPT_FILENAME'])) {
907 27
            return $_SERVER['SCRIPT_FILENAME'];
908
        }
909
910 2
        throw new InvalidConfigException('Unable to determine the entry script file path.');
911
    }
912
913
    /**
914
     * Sets the entry script file path.
915
     * The entry script file path normally can be obtained from `$_SERVER['SCRIPT_FILENAME']`.
916
     * If your server configuration does not return the correct value, you may configure
917
     * this property to make it right.
918
     * @param string $value the entry script file path.
919
     */
920 422
    public function setScriptFile($value)
921
    {
922 422
        $this->_scriptFile = $value;
923 422
    }
924
925
    private $_pathInfo;
926
927
    /**
928
     * Returns the path info of the currently requested URL.
929
     * A path info refers to the part that is after the entry script and before the question mark (query string).
930
     * The starting and ending slashes are both removed.
931
     * @return string part of the request URL that is after the entry script and before the question mark.
932
     * Note, the returned path info is already URL-decoded.
933
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
934
     */
935 19
    public function getPathInfo()
936
    {
937 19
        if ($this->_pathInfo === null) {
938
            $this->_pathInfo = $this->resolvePathInfo();
939
        }
940
941 19
        return $this->_pathInfo;
942
    }
943
944
    /**
945
     * Sets the path info of the current request.
946
     * This method is mainly provided for testing purpose.
947
     * @param string $value the path info of the current request
948
     */
949 20
    public function setPathInfo($value)
950
    {
951 20
        $this->_pathInfo = $value === null ? null : ltrim($value, '/');
0 ignored issues
show
introduced by
The condition $value === null is always false.
Loading history...
952 20
    }
953
954
    /**
955
     * Resolves the path info part of the currently requested URL.
956
     * A path info refers to the part that is after the entry script and before the question mark (query string).
957
     * The starting slashes are both removed (ending slashes will be kept).
958
     * @return string part of the request URL that is after the entry script and before the question mark.
959
     * Note, the returned path info is decoded.
960
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
961
     */
962
    protected function resolvePathInfo()
963
    {
964
        $pathInfo = $this->getUrl();
965
966
        if (($pos = strpos($pathInfo, '?')) !== false) {
967
            $pathInfo = substr($pathInfo, 0, $pos);
968
        }
969
970
        $pathInfo = urldecode($pathInfo);
971
972
        // try to encode in UTF8 if not so
973
        // http://w3.org/International/questions/qa-forms-utf-8.html
974
        if (!preg_match('%^(?:
975
            [\x09\x0A\x0D\x20-\x7E]              # ASCII
976
            | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
977
            | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
978
            | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
979
            | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
980
            | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
981
            | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
982
            | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
983
            )*$%xs', $pathInfo)
984
        ) {
985
            $pathInfo = $this->utf8Encode($pathInfo);
986
        }
987
988
        $scriptUrl = $this->getScriptUrl();
989
        $baseUrl = $this->getBaseUrl();
990
        if (strpos($pathInfo, $scriptUrl) === 0) {
991
            $pathInfo = substr($pathInfo, strlen($scriptUrl));
992
        } elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) {
993
            $pathInfo = substr($pathInfo, strlen($baseUrl));
994
        } elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0) {
995
            $pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
996
        } else {
997
            throw new InvalidConfigException('Unable to determine the path info of the current request.');
998
        }
999
1000
        if (strncmp($pathInfo, '/', 1) === 0) {
1001
            $pathInfo = substr($pathInfo, 1);
1002
        }
1003
1004
        return (string) $pathInfo;
1005
    }
1006
1007
    /**
1008
     * Encodes an ISO-8859-1 string to UTF-8
1009
     * @param string $s
1010
     * @return string the UTF-8 translation of `s`.
1011
     * @see https://github.com/symfony/polyfill-php72/blob/master/Php72.php#L24
1012
     */
1013
    private function utf8Encode($s)
1014
    {
1015
        $s .= $s;
1016
        $len = \strlen($s);
1017
        for ($i = $len >> 1, $j = 0; $i < $len; ++$i, ++$j) {
1018
            switch (true) {
1019
                case $s[$i] < "\x80": $s[$j] = $s[$i]; break;
1020
                case $s[$i] < "\xC0": $s[$j] = "\xC2"; $s[++$j] = $s[$i]; break;
1021
                default: $s[$j] = "\xC3"; $s[++$j] = \chr(\ord($s[$i]) - 64); break;
1022
            }
1023
        }
1024
        return substr($s, 0, $j);
1025
    }
1026
1027
    /**
1028
     * Returns the currently requested absolute URL.
1029
     * This is a shortcut to the concatenation of [[hostInfo]] and [[url]].
1030
     * @return string the currently requested absolute URL.
1031
     */
1032 1
    public function getAbsoluteUrl()
1033
    {
1034 1
        return $this->getHostInfo() . $this->getUrl();
1035
    }
1036
1037
    private $_url;
1038
1039
    /**
1040
     * Returns the currently requested relative URL.
1041
     * This refers to the portion of the URL that is after the [[hostInfo]] part.
1042
     * It includes the [[queryString]] part if any.
1043
     * @return string the currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.
1044
     * @throws InvalidConfigException if the URL cannot be determined due to unusual server configuration
1045
     */
1046 11
    public function getUrl()
1047
    {
1048 11
        if ($this->_url === null) {
1049 3
            $this->_url = $this->resolveRequestUri();
1050
        }
1051
1052 11
        return $this->_url;
1053
    }
1054
1055
    /**
1056
     * Sets the currently requested relative URL.
1057
     * The URI must refer to the portion that is after [[hostInfo]].
1058
     * Note that the URI should be URL-encoded.
1059
     * @param string $value the request URI to be set
1060
     */
1061 25
    public function setUrl($value)
1062
    {
1063 25
        $this->_url = $value;
1064 25
    }
1065
1066
    /**
1067
     * Resolves the request URI portion for the currently requested URL.
1068
     * This refers to the portion that is after the [[hostInfo]] part. It includes the [[queryString]] part if any.
1069
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
1070
     * @return string|bool the request URI portion for the currently requested URL.
1071
     * Note that the URI returned may be URL-encoded depending on the client.
1072
     * @throws InvalidConfigException if the request URI cannot be determined due to unusual server configuration
1073
     */
1074 3
    protected function resolveRequestUri()
1075
    {
1076 3
        if ($this->headers->has('X-Rewrite-Url')) { // IIS
1077
            $requestUri = $this->headers->get('X-Rewrite-Url');
1078 3
        } elseif (isset($_SERVER['REQUEST_URI'])) {
1079 3
            $requestUri = $_SERVER['REQUEST_URI'];
1080 3
            if ($requestUri !== '' && $requestUri[0] !== '/') {
1081 3
                $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
1082
            }
1083
        } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 CGI
1084
            $requestUri = $_SERVER['ORIG_PATH_INFO'];
1085
            if (!empty($_SERVER['QUERY_STRING'])) {
1086
                $requestUri .= '?' . $_SERVER['QUERY_STRING'];
1087
            }
1088
        } else {
1089
            throw new InvalidConfigException('Unable to determine the request URI.');
1090
        }
1091
1092 3
        return $requestUri;
1093
    }
1094
1095
    /**
1096
     * Returns part of the request URL that is after the question mark.
1097
     * @return string part of the request URL that is after the question mark
1098
     */
1099
    public function getQueryString()
1100
    {
1101
        return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
1102
    }
1103
1104
    /**
1105
     * Return if the request is sent via secure channel (https).
1106
     * @return bool if the request is sent via secure channel (https)
1107
     */
1108 79
    public function getIsSecureConnection()
1109
    {
1110 79
        if (isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)) {
1111 2
            return true;
1112
        }
1113
1114 77
        if (($proto = $this->getSecureForwardedHeaderTrustedPart('proto')) !== null) {
1115 9
            return strcasecmp($proto, 'https') === 0;
1116
        }
1117
1118 68
        foreach ($this->secureProtocolHeaders as $header => $values) {
1119 68
            if (($headerValue = $this->headers->get($header, null)) !== null) {
1120 5
                foreach ($values as $value) {
1121 5
                    if (strcasecmp($headerValue, $value) === 0) {
0 ignored issues
show
Bug introduced by
It seems like $headerValue can also be of type array; however, parameter $string1 of strcasecmp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1121
                    if (strcasecmp(/** @scrutinizer ignore-type */ $headerValue, $value) === 0) {
Loading history...
1122 3
                        return true;
1123
                    }
1124
                }
1125
            }
1126
        }
1127
1128 65
        return false;
1129
    }
1130
1131
    /**
1132
     * Returns the server name.
1133
     * @return string|null server name, null if not available
1134
     */
1135 1
    public function getServerName()
1136
    {
1137 1
        return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
1138
    }
1139
1140
    /**
1141
     * Returns the server port number. If a port is specified via a forwarding header (e.g. 'X-Forwarded-Port')
1142
     * and the remote host is a "trusted host" the that port will be used (see [[portHeaders]]),
1143
     * otherwise the default server port will be returned.
1144
     * @return int|null server port number, null if not available
1145
     * @see portHeaders
1146
     */
1147 23
    public function getServerPort()
1148
    {
1149 23
        foreach ($this->portHeaders as $portHeader) {
1150 23
            if ($this->headers->has($portHeader)) {
1151 2
                $port = $this->headers->get($portHeader);
1152 2
                if ($port !== null) {
1153 2
                    return $port;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $port returns the type array|string which is incompatible with the documented return type integer|null.
Loading history...
1154
                }
1155
            }
1156
        }
1157
1158 21
        return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null;
1159
    }
1160
1161
    /**
1162
     * Returns the URL referrer.
1163
     * @return string|null URL referrer, null if not available
1164
     */
1165
    public function getReferrer()
1166
    {
1167
        return $this->headers->get('Referer');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->headers->get('Referer') also could return the type array which is incompatible with the documented return type null|string.
Loading history...
1168
    }
1169
1170
    /**
1171
     * Returns the URL origin of a CORS request.
1172
     *
1173
     * The return value is taken from the `Origin` [[getHeaders()|header]] sent by the browser.
1174
     *
1175
     * Note that the origin request header indicates where a fetch originates from.
1176
     * It doesn't include any path information, but only the server name.
1177
     * It is sent with a CORS requests, as well as with POST requests.
1178
     * It is similar to the referer header, but, unlike this header, it doesn't disclose the whole path.
1179
     * Please refer to <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin> for more information.
1180
     *
1181
     * @return string|null URL origin of a CORS request, `null` if not available.
1182
     * @see getHeaders()
1183
     * @since 2.0.13
1184
     */
1185 1
    public function getOrigin()
1186
    {
1187 1
        return $this->getHeaders()->get('origin');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getHeaders()->get('origin') also could return the type array which is incompatible with the documented return type null|string.
Loading history...
1188
    }
1189
1190
    /**
1191
     * Returns the user agent.
1192
     * @return string|null user agent, null if not available
1193
     */
1194 1
    public function getUserAgent()
1195
    {
1196 1
        return $this->headers->get('User-Agent');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->headers->get('User-Agent') also could return the type array which is incompatible with the documented return type null|string.
Loading history...
1197
    }
1198
1199
    /**
1200
     * Returns the user IP address from [[ipHeaders]].
1201
     * @return string|null user IP address, null if not available
1202
     * @see ipHeaders
1203
     * @since 2.0.28
1204
     */
1205 105
    protected function getUserIpFromIpHeaders()
1206
    {
1207 105
        $ip = $this->getSecureForwardedHeaderTrustedPart('for');
1208 105
        if ($ip !== null && preg_match(
1209 105
            '/^\[?(?P<ip>(?:(?:(?:[0-9a-f]{1,4}:){1,6}(?:[0-9a-f]{1,4})?(?:(?::[0-9a-f]{1,4}){1,6}))|(?:[\d]{1,3}\.){3}[\d]{1,3}))\]?(?::(?P<port>[\d]+))?$/',
1210
            $ip,
1211
            $matches
1212
        )) {
1213 14
            $ip = $this->getUserIpFromIpHeader($matches['ip']);
1214 14
            if ($ip !== null) {
1215 14
                return $ip;
1216
            }
1217
        }
1218
1219
1220 91
        foreach ($this->ipHeaders as $ipHeader) {
1221 88
            if ($this->headers->has($ipHeader)) {
1222 10
                $ip = $this->getUserIpFromIpHeader($this->headers->get($ipHeader));
0 ignored issues
show
Bug introduced by
It seems like $this->headers->get($ipHeader) can also be of type array; however, parameter $ips of yii\web\Request::getUserIpFromIpHeader() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1222
                $ip = $this->getUserIpFromIpHeader(/** @scrutinizer ignore-type */ $this->headers->get($ipHeader));
Loading history...
1223 10
                if ($ip !== null) {
1224 10
                    return $ip;
1225
                }
1226
            }
1227
        }
1228 81
        return null;
1229
    }
1230
1231
    /**
1232
     * Returns the user IP address.
1233
     * The IP is determined using headers and / or `$_SERVER` variables.
1234
     * @return string|null user IP address, null if not available
1235
     */
1236 105
    public function getUserIP()
1237
    {
1238 105
        $ip = $this->getUserIpFromIpHeaders();
1239 105
        return $ip === null ? $this->getRemoteIP() : $ip;
1240
    }
1241
1242
    /**
1243
     * Return user IP's from IP header.
1244
     *
1245
     * @param string $ips comma separated IP list
1246
     * @return string|null IP as string. Null is returned if IP can not be determined from header.
1247
     * @see getUserHost()
1248
     * @see ipHeaders
1249
     * @see getTrustedHeaders()
1250
     * @since 2.0.28
1251
     */
1252 24
    protected function getUserIpFromIpHeader($ips)
1253
    {
1254 24
        $ips = trim($ips);
1255 24
        if ($ips === '') {
1256
            return null;
1257
        }
1258 24
        $ips = preg_split('/\s*,\s*/', $ips, -1, PREG_SPLIT_NO_EMPTY);
1259 24
        krsort($ips);
1260 24
        $validator = $this->getIpValidator();
1261 24
        $resultIp = null;
1262 24
        foreach ($ips as $ip) {
1263 24
            $validator->setRanges('any');
1264 24
            if (!$validator->validate($ip) /* checking IP format */) {
1265 1
                break;
1266
            }
1267 24
            $resultIp = $ip;
1268 24
            $isTrusted = false;
1269 24
            foreach ($this->trustedHosts as $trustedCidr => $trustedCidrOrHeaders) {
1270 24
                if (!is_array($trustedCidrOrHeaders)) {
1271 24
                    $trustedCidr = $trustedCidrOrHeaders;
1272
                }
1273 24
                $validator->setRanges($trustedCidr);
1274 24
                if ($validator->validate($ip) /* checking trusted range */) {
1275 7
                    $isTrusted = true;
1276 7
                    break;
1277
                }
1278
            }
1279 24
            if (!$isTrusted) {
1280 20
                break;
1281
            }
1282
        }
1283 24
        return $resultIp;
1284
    }
1285
1286
    /**
1287
     * Returns the user host name.
1288
     * The HOST is determined using headers and / or `$_SERVER` variables.
1289
     * @return string|null user host name, null if not available
1290
     */
1291
    public function getUserHost()
1292
    {
1293
        $userIp = $this->getUserIpFromIpHeaders();
1294
        if($userIp === null) {
1295
            return $this->getRemoteHost();
1296
        }
1297
        return gethostbyaddr($userIp);
1298
    }
1299
1300
    /**
1301
     * Returns the IP on the other end of this connection.
1302
     * This is always the next hop, any headers are ignored.
1303
     * @return string|null remote IP address, `null` if not available.
1304
     * @since 2.0.13
1305
     */
1306 148
    public function getRemoteIP()
1307
    {
1308 148
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
1309
    }
1310
1311
    /**
1312
     * Returns the host name of the other end of this connection.
1313
     * This is always the next hop, any headers are ignored.
1314
     * @return string|null remote host name, `null` if not available
1315
     * @see getUserHost()
1316
     * @see getRemoteIP()
1317
     * @since 2.0.13
1318
     */
1319
    public function getRemoteHost()
1320
    {
1321
        return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
1322
    }
1323
1324
    /**
1325
     * @return string|null the username sent via HTTP authentication, `null` if the username is not given
1326
     * @see getAuthCredentials() to get both username and password in one call
1327
     */
1328 9
    public function getAuthUser()
1329
    {
1330 9
        return $this->getAuthCredentials()[0];
1331
    }
1332
1333
    /**
1334
     * @return string|null the password sent via HTTP authentication, `null` if the password is not given
1335
     * @see getAuthCredentials() to get both username and password in one call
1336
     */
1337 9
    public function getAuthPassword()
1338
    {
1339 9
        return $this->getAuthCredentials()[1];
1340
    }
1341
1342
    /**
1343
     * @return array that contains exactly two elements:
1344
     * - 0: the username sent via HTTP authentication, `null` if the username is not given
1345
     * - 1: the password sent via HTTP authentication, `null` if the password is not given
1346
     * @see getAuthUser() to get only username
1347
     * @see getAuthPassword() to get only password
1348
     * @since 2.0.13
1349
     */
1350 39
    public function getAuthCredentials()
1351
    {
1352 39
        $username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
1353 39
        $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
1354 39
        if ($username !== null || $password !== null) {
1355 21
            return [$username, $password];
1356
        }
1357
1358
        /**
1359
         * Apache with php-cgi does not pass HTTP Basic authentication to PHP by default.
1360
         * To make it work, add one of the following lines to to your .htaccess file:
1361
         *
1362
         * SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
1363
         * --OR--
1364
         * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
1365
         */
1366 18
        $auth_token = $this->getHeaders()->get('Authorization');
1367
1368 18
        if ($auth_token !== null && strncasecmp($auth_token, 'basic', 5) === 0) {
0 ignored issues
show
Bug introduced by
It seems like $auth_token can also be of type array; however, parameter $string1 of strncasecmp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1368
        if ($auth_token !== null && strncasecmp(/** @scrutinizer ignore-type */ $auth_token, 'basic', 5) === 0) {
Loading history...
1369
            $parts = array_map(function ($value) {
1370 18
                return strlen($value) === 0 ? null : $value;
1371 18
            }, explode(':', base64_decode(mb_substr($auth_token, 6)), 2));
0 ignored issues
show
Bug introduced by
It seems like $auth_token can also be of type array; however, parameter $string of mb_substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1371
            }, explode(':', base64_decode(mb_substr(/** @scrutinizer ignore-type */ $auth_token, 6)), 2));
Loading history...
1372
1373 18
            if (count($parts) < 2) {
1374 2
                return [$parts[0], null];
1375
            }
1376
1377 16
            return $parts;
1378
        }
1379
1380
        return [null, null];
1381
    }
1382
1383
    private $_port;
1384
1385
    /**
1386
     * Returns the port to use for insecure requests.
1387
     * Defaults to 80, or the port specified by the server if the current
1388
     * request is insecure.
1389
     * @return int port number for insecure requests.
1390
     * @see setPort()
1391
     */
1392 15
    public function getPort()
1393
    {
1394 15
        if ($this->_port === null) {
1395 15
            $serverPort = $this->getServerPort();
1396 15
            $this->_port = !$this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 80;
1397
        }
1398
1399 15
        return $this->_port;
1400
    }
1401
1402
    /**
1403
     * Sets the port to use for insecure requests.
1404
     * This setter is provided in case a custom port is necessary for certain
1405
     * server configurations.
1406
     * @param int $value port number.
1407
     */
1408
    public function setPort($value)
1409
    {
1410
        if ($value != $this->_port) {
1411
            $this->_port = (int) $value;
1412
            $this->_hostInfo = null;
1413
        }
1414
    }
1415
1416
    private $_securePort;
1417
1418
    /**
1419
     * Returns the port to use for secure requests.
1420
     * Defaults to 443, or the port specified by the server if the current
1421
     * request is secure.
1422
     * @return int port number for secure requests.
1423
     * @see setSecurePort()
1424
     */
1425 1
    public function getSecurePort()
1426
    {
1427 1
        if ($this->_securePort === null) {
1428 1
            $serverPort = $this->getServerPort();
1429 1
            $this->_securePort = $this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 443;
1430
        }
1431
1432 1
        return $this->_securePort;
1433
    }
1434
1435
    /**
1436
     * Sets the port to use for secure requests.
1437
     * This setter is provided in case a custom port is necessary for certain
1438
     * server configurations.
1439
     * @param int $value port number.
1440
     */
1441
    public function setSecurePort($value)
1442
    {
1443
        if ($value != $this->_securePort) {
1444
            $this->_securePort = (int) $value;
1445
            $this->_hostInfo = null;
1446
        }
1447
    }
1448
1449
    private $_contentTypes;
1450
1451
    /**
1452
     * Returns the content types acceptable by the end user.
1453
     *
1454
     * This is determined by the `Accept` HTTP header. For example,
1455
     *
1456
     * ```php
1457
     * $_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1458
     * $types = $request->getAcceptableContentTypes();
1459
     * print_r($types);
1460
     * // displays:
1461
     * // [
1462
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1463
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1464
     * //           'text/plain' => ['q' => 0.5],
1465
     * // ]
1466
     * ```
1467
     *
1468
     * @return array the content types ordered by the quality score. Types with the highest scores
1469
     * will be returned first. The array keys are the content types, while the array values
1470
     * are the corresponding quality score and other parameters as given in the header.
1471
     */
1472 5
    public function getAcceptableContentTypes()
1473
    {
1474 5
        if ($this->_contentTypes === null) {
1475 4
            if ($this->headers->get('Accept') !== null) {
1476 2
                $this->_contentTypes = $this->parseAcceptHeader($this->headers->get('Accept'));
0 ignored issues
show
Bug introduced by
It seems like $this->headers->get('Accept') can also be of type array; however, parameter $header of yii\web\Request::parseAcceptHeader() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1476
                $this->_contentTypes = $this->parseAcceptHeader(/** @scrutinizer ignore-type */ $this->headers->get('Accept'));
Loading history...
1477
            } else {
1478 3
                $this->_contentTypes = [];
1479
            }
1480
        }
1481
1482 5
        return $this->_contentTypes;
1483
    }
1484
1485
    /**
1486
     * Sets the acceptable content types.
1487
     * Please refer to [[getAcceptableContentTypes()]] on the format of the parameter.
1488
     * @param array $value the content types that are acceptable by the end user. They should
1489
     * be ordered by the preference level.
1490
     * @see getAcceptableContentTypes()
1491
     * @see parseAcceptHeader()
1492
     */
1493 1
    public function setAcceptableContentTypes($value)
1494
    {
1495 1
        $this->_contentTypes = $value;
1496 1
    }
1497
1498
    /**
1499
     * Returns request content-type
1500
     * The Content-Type header field indicates the MIME type of the data
1501
     * contained in [[getRawBody()]] or, in the case of the HEAD method, the
1502
     * media type that would have been sent had the request been a GET.
1503
     * For the MIME-types the user expects in response, see [[acceptableContentTypes]].
1504
     * @return string request content-type. Empty string is returned if this information is not available.
1505
     * @link https://tools.ietf.org/html/rfc2616#section-14.17
1506
     * HTTP 1.1 header field definitions
1507
     */
1508 7
    public function getContentType()
1509
    {
1510 7
        if (isset($_SERVER['CONTENT_TYPE'])) {
1511 3
            return $_SERVER['CONTENT_TYPE'];
1512
        }
1513
1514
        //fix bug https://bugs.php.net/bug.php?id=66606
1515 4
        return $this->headers->get('Content-Type') ?: '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->headers->get('Content-Type') ?: '' also could return the type array which is incompatible with the documented return type string.
Loading history...
1516
    }
1517
1518
    private $_languages;
1519
1520
    /**
1521
     * Returns the languages acceptable by the end user.
1522
     * This is determined by the `Accept-Language` HTTP header.
1523
     * @return array the languages ordered by the preference level. The first element
1524
     * represents the most preferred language.
1525
     */
1526 2
    public function getAcceptableLanguages()
1527
    {
1528 2
        if ($this->_languages === null) {
1529 1
            if ($this->headers->has('Accept-Language')) {
1530
                $this->_languages = array_keys($this->parseAcceptHeader($this->headers->get('Accept-Language')));
0 ignored issues
show
Bug introduced by
It seems like $this->headers->get('Accept-Language') can also be of type array; however, parameter $header of yii\web\Request::parseAcceptHeader() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1530
                $this->_languages = array_keys($this->parseAcceptHeader(/** @scrutinizer ignore-type */ $this->headers->get('Accept-Language')));
Loading history...
1531
            } else {
1532 1
                $this->_languages = [];
1533
            }
1534
        }
1535
1536 2
        return $this->_languages;
1537
    }
1538
1539
    /**
1540
     * @param array $value the languages that are acceptable by the end user. They should
1541
     * be ordered by the preference level.
1542
     */
1543 1
    public function setAcceptableLanguages($value)
1544
    {
1545 1
        $this->_languages = $value;
1546 1
    }
1547
1548
    /**
1549
     * Parses the given `Accept` (or `Accept-Language`) header.
1550
     *
1551
     * This method will return the acceptable values with their quality scores and the corresponding parameters
1552
     * as specified in the given `Accept` header. The array keys of the return value are the acceptable values,
1553
     * while the array values consisting of the corresponding quality scores and parameters. The acceptable
1554
     * values with the highest quality scores will be returned first. For example,
1555
     *
1556
     * ```php
1557
     * $header = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1558
     * $accepts = $request->parseAcceptHeader($header);
1559
     * print_r($accepts);
1560
     * // displays:
1561
     * // [
1562
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1563
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1564
     * //           'text/plain' => ['q' => 0.5],
1565
     * // ]
1566
     * ```
1567
     *
1568
     * @param string $header the header to be parsed
1569
     * @return array the acceptable values ordered by their quality score. The values with the highest scores
1570
     * will be returned first.
1571
     */
1572 3
    public function parseAcceptHeader($header)
1573
    {
1574 3
        $accepts = [];
1575 3
        foreach (explode(',', $header) as $i => $part) {
1576 3
            $params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY);
1577 3
            if (empty($params)) {
1578 1
                continue;
1579
            }
1580
            $values = [
1581 3
                'q' => [$i, array_shift($params), 1],
1582
            ];
1583 3
            foreach ($params as $param) {
1584 2
                if (strpos($param, '=') !== false) {
1585 2
                    list($key, $value) = explode('=', $param, 2);
1586 2
                    if ($key === 'q') {
1587 2
                        $values['q'][2] = (float) $value;
1588
                    } else {
1589 2
                        $values[$key] = $value;
1590
                    }
1591
                } else {
1592 1
                    $values[] = $param;
1593
                }
1594
            }
1595 3
            $accepts[] = $values;
1596
        }
1597
1598
        usort($accepts, function ($a, $b) {
1599 3
            $a = $a['q']; // index, name, q
1600 3
            $b = $b['q'];
1601 3
            if ($a[2] > $b[2]) {
1602 2
                return -1;
1603
            }
1604
1605 2
            if ($a[2] < $b[2]) {
1606 1
                return 1;
1607
            }
1608
1609 2
            if ($a[1] === $b[1]) {
1610
                return $a[0] > $b[0] ? 1 : -1;
1611
            }
1612
1613 2
            if ($a[1] === '*/*') {
1614
                return 1;
1615
            }
1616
1617 2
            if ($b[1] === '*/*') {
1618
                return -1;
1619
            }
1620
1621 2
            $wa = $a[1][strlen($a[1]) - 1] === '*';
1622 2
            $wb = $b[1][strlen($b[1]) - 1] === '*';
1623 2
            if ($wa xor $wb) {
1624
                return $wa ? 1 : -1;
1625
            }
1626
1627 2
            return $a[0] > $b[0] ? 1 : -1;
1628 3
        });
1629
1630 3
        $result = [];
1631 3
        foreach ($accepts as $accept) {
1632 3
            $name = $accept['q'][1];
1633 3
            $accept['q'] = $accept['q'][2];
1634 3
            $result[$name] = $accept;
1635
        }
1636
1637 3
        return $result;
1638
    }
1639
1640
    /**
1641
     * Returns the user-preferred language that should be used by this application.
1642
     * The language resolution is based on the user preferred languages and the languages
1643
     * supported by the application. The method will try to find the best match.
1644
     * @param array $languages a list of the languages supported by the application. If this is empty, the current
1645
     * application language will be returned without further processing.
1646
     * @return string the language that the application should use.
1647
     */
1648 1
    public function getPreferredLanguage(array $languages = [])
1649
    {
1650 1
        if (empty($languages)) {
1651 1
            return Yii::$app->language;
1652
        }
1653 1
        foreach ($this->getAcceptableLanguages() as $acceptableLanguage) {
1654 1
            $acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
1655 1
            foreach ($languages as $language) {
1656 1
                $normalizedLanguage = str_replace('_', '-', strtolower($language));
1657
1658
                if (
1659 1
                    $normalizedLanguage === $acceptableLanguage // en-us==en-us
1660 1
                    || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us
1661 1
                    || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en
1662
                ) {
1663 1
                    return $language;
1664
                }
1665
            }
1666
        }
1667
1668 1
        return reset($languages);
1669
    }
1670
1671
    /**
1672
     * Gets the Etags.
1673
     *
1674
     * @return array The entity tags
1675
     */
1676
    public function getETags()
1677
    {
1678
        if ($this->headers->has('If-None-Match')) {
1679
            return preg_split('/[\s,]+/', str_replace('-gzip', '', $this->headers->get('If-None-Match')), -1, PREG_SPLIT_NO_EMPTY);
1680
        }
1681
1682
        return [];
1683
    }
1684
1685
    /**
1686
     * Returns the cookie collection.
1687
     *
1688
     * Through the returned cookie collection, you may access a cookie using the following syntax:
1689
     *
1690
     * ```php
1691
     * $cookie = $request->cookies['name']
1692
     * if ($cookie !== null) {
1693
     *     $value = $cookie->value;
1694
     * }
1695
     *
1696
     * // alternatively
1697
     * $value = $request->cookies->getValue('name');
1698
     * ```
1699
     *
1700
     * @return CookieCollection the cookie collection.
1701
     */
1702 83
    public function getCookies()
1703
    {
1704 83
        if ($this->_cookies === null) {
1705 83
            $this->_cookies = new CookieCollection($this->loadCookies(), [
1706 82
                'readOnly' => true,
1707
            ]);
1708
        }
1709
1710 82
        return $this->_cookies;
1711
    }
1712
1713
    /**
1714
     * Converts `$_COOKIE` into an array of [[Cookie]].
1715
     * @return array the cookies obtained from request
1716
     * @throws InvalidConfigException if [[cookieValidationKey]] is not set when [[enableCookieValidation]] is true
1717
     */
1718 83
    protected function loadCookies()
1719
    {
1720 83
        $cookies = [];
1721 83
        if ($this->enableCookieValidation) {
1722 82
            if ($this->cookieValidationKey == '') {
1723 1
                throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
1724
            }
1725 81
            foreach ($_COOKIE as $name => $value) {
1726
                if (!is_string($value)) {
1727
                    continue;
1728
                }
1729
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
1730
                if ($data === false) {
1731
                    continue;
1732
                }
1733
                if (defined('PHP_VERSION_ID') && PHP_VERSION_ID >= 70000) {
1734
                    $data = @unserialize($data, ['allowed_classes' => false]);
1735
                } else {
1736
                    $data = @unserialize($data);
1737
                }
1738
                if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
1739
                    $cookies[$name] = Yii::createObject([
1740
                        'class' => 'yii\web\Cookie',
1741
                        'name' => $name,
1742
                        'value' => $data[1],
1743
                        'expire' => null,
1744
                    ]);
1745
                }
1746
            }
1747
        } else {
1748 1
            foreach ($_COOKIE as $name => $value) {
1749 1
                $cookies[$name] = Yii::createObject([
1750 1
                    'class' => 'yii\web\Cookie',
1751 1
                    'name' => $name,
1752 1
                    'value' => $value,
1753
                    'expire' => null,
1754
                ]);
1755
            }
1756
        }
1757
1758 82
        return $cookies;
1759
    }
1760
1761
    private $_csrfToken;
1762
1763
    /**
1764
     * Returns the token used to perform CSRF validation.
1765
     *
1766
     * This token is generated in a way to prevent [BREACH attacks](http://breachattack.com/). It may be passed
1767
     * along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.
1768
     * @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time
1769
     * this method is called, a new CSRF token will be generated and persisted (in session or cookie).
1770
     * @return string the token used to perform CSRF validation.
1771
     */
1772 89
    public function getCsrfToken($regenerate = false)
1773
    {
1774 89
        if ($this->_csrfToken === null || $regenerate) {
1775 89
            $token = $this->loadCsrfToken();
1776 88
            if ($regenerate || empty($token)) {
1777 85
                $token = $this->generateCsrfToken();
1778
            }
1779 88
            $this->_csrfToken = Yii::$app->security->maskToken($token);
1780
        }
1781
1782 88
        return $this->_csrfToken;
1783
    }
1784
1785
    /**
1786
     * Loads the CSRF token from cookie or session.
1787
     * @return string|null the CSRF token loaded from cookie or session. Null is returned if the cookie or session
1788
     * does not have CSRF token.
1789
     */
1790 89
    protected function loadCsrfToken()
1791
    {
1792 89
        if ($this->enableCsrfCookie) {
1793 85
            return $this->getCookies()->getValue($this->csrfParam);
1794
        }
1795
1796 4
        return Yii::$app->getSession()->get($this->csrfParam);
0 ignored issues
show
Bug introduced by
The method getSession() does not exist on yii\base\Application. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1796
        return Yii::$app->/** @scrutinizer ignore-call */ getSession()->get($this->csrfParam);
Loading history...
Bug introduced by
The method getSession() does not exist on yii\console\Application. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1796
        return Yii::$app->/** @scrutinizer ignore-call */ getSession()->get($this->csrfParam);
Loading history...
1797
    }
1798
1799
    /**
1800
     * Generates an unmasked random token used to perform CSRF validation.
1801
     * @return string the random token for CSRF validation.
1802
     */
1803 85
    protected function generateCsrfToken()
1804
    {
1805 85
        $token = Yii::$app->getSecurity()->generateRandomString();
1806 85
        if ($this->enableCsrfCookie) {
1807 84
            $cookie = $this->createCsrfCookie($token);
1808 84
            Yii::$app->getResponse()->getCookies()->add($cookie);
0 ignored issues
show
Bug introduced by
The method getCookies() does not exist on yii\console\Response. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1808
            Yii::$app->getResponse()->/** @scrutinizer ignore-call */ getCookies()->add($cookie);
Loading history...
1809
        } else {
1810 1
            Yii::$app->getSession()->set($this->csrfParam, $token);
1811
        }
1812
1813 85
        return $token;
1814
    }
1815
1816
    /**
1817
     * @return string|null the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent.
1818
     */
1819 3
    public function getCsrfTokenFromHeader()
1820
    {
1821 3
        return $this->headers->get(static::CSRF_HEADER);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->headers->get(static::CSRF_HEADER) also could return the type array which is incompatible with the documented return type null|string.
Loading history...
1822
    }
1823
1824
    /**
1825
     * Creates a cookie with a randomly generated CSRF token.
1826
     * Initial values specified in [[csrfCookie]] will be applied to the generated cookie.
1827
     * @param string $token the CSRF token
1828
     * @return Cookie the generated cookie
1829
     * @see enableCsrfValidation
1830
     */
1831 84
    protected function createCsrfCookie($token)
1832
    {
1833 84
        $options = $this->csrfCookie;
1834 84
        return Yii::createObject(array_merge($options, [
1835 84
            'class' => 'yii\web\Cookie',
1836 84
            'name' => $this->csrfParam,
1837 84
            'value' => $token,
1838
        ]));
1839
    }
1840
1841
    /**
1842
     * Performs the CSRF validation.
1843
     *
1844
     * This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session.
1845
     * This method is mainly called in [[Controller::beforeAction()]].
1846
     *
1847
     * Note that the method will NOT perform CSRF validation if [[enableCsrfValidation]] is false or the HTTP method
1848
     * is among GET, HEAD or OPTIONS.
1849
     *
1850
     * @param string|null $clientSuppliedToken the user-provided CSRF token to be validated. If null, the token will be retrieved from
1851
     * the [[csrfParam]] POST field or HTTP header.
1852
     * This parameter is available since version 2.0.4.
1853
     * @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.
1854
     */
1855 8
    public function validateCsrfToken($clientSuppliedToken = null)
1856
    {
1857 8
        $method = $this->getMethod();
1858
        // only validate CSRF token on non-"safe" methods https://tools.ietf.org/html/rfc2616#section-9.1.1
1859 8
        if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
1860 7
            return true;
1861
        }
1862
1863 4
        $trueToken = $this->getCsrfToken();
1864
1865 4
        if ($clientSuppliedToken !== null) {
1866 2
            return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken);
1867
        }
1868
1869 3
        return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
1870 3
            || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
1871
    }
1872
1873
    /**
1874
     * Validates CSRF token.
1875
     *
1876
     * @param string $clientSuppliedToken The masked client-supplied token.
1877
     * @param string $trueToken The masked true token.
1878
     * @return bool
1879
     */
1880 4
    private function validateCsrfTokenInternal($clientSuppliedToken, $trueToken)
1881
    {
1882 4
        if (!is_string($clientSuppliedToken)) {
0 ignored issues
show
introduced by
The condition is_string($clientSuppliedToken) is always true.
Loading history...
1883 3
            return false;
1884
        }
1885
1886 4
        $security = Yii::$app->security;
1887
1888 4
        return $security->compareString($security->unmaskToken($clientSuppliedToken), $security->unmaskToken($trueToken));
1889
    }
1890
1891
    /**
1892
     * Gets first `Forwarded` header value for token
1893
     *
1894
     * @param string $token Header token
1895
     *
1896
     * @return string|null
1897
     *
1898
     * @since 2.0.31
1899
     */
1900 172
    protected function getSecureForwardedHeaderTrustedPart($token)
1901
    {
1902 172
        $token = strtolower($token);
1903
1904 172
        if ($parts = $this->getSecureForwardedHeaderTrustedParts()) {
1905 20
            $lastElement = array_pop($parts);
1906 20
            if ($lastElement && isset($lastElement[$token])) {
1907 20
                return $lastElement[$token];
1908
            }
1909
        }
1910 157
        return null;
1911
    }
1912
1913
    /**
1914
     * Gets only trusted `Forwarded` header parts
1915
     *
1916
     * @return array
1917
     *
1918
     * @since 2.0.31
1919
     */
1920 172
    protected function getSecureForwardedHeaderTrustedParts()
1921
    {
1922 172
        $validator = $this->getIpValidator();
1923 172
        $trustedHosts = [];
1924 172
        foreach ($this->trustedHosts as $trustedCidr => $trustedCidrOrHeaders) {
1925 80
            if (!is_array($trustedCidrOrHeaders)) {
1926 78
                $trustedCidr = $trustedCidrOrHeaders;
1927
            }
1928 80
            $trustedHosts[] = $trustedCidr;
1929
        }
1930 172
        $validator->setRanges($trustedHosts);
1931
1932
        return array_filter($this->getSecureForwardedHeaderParts(), function ($headerPart) use ($validator) {
1933 20
            return isset($headerPart['for']) ? !$validator->validate($headerPart['for']) : true;
1934 172
        });
1935
    }
1936
1937
    private $_secureForwardedHeaderParts;
1938
1939
    /**
1940
     * Returns decoded forwarded header
1941
     *
1942
     * @return array
1943
     *
1944
     * @since 2.0.31
1945
     */
1946 172
    protected function getSecureForwardedHeaderParts()
1947
    {
1948 172
        if ($this->_secureForwardedHeaderParts !== null) {
1949 89
            return $this->_secureForwardedHeaderParts;
1950
        }
1951 172
        if (count(preg_grep('/^forwarded$/i', $this->secureHeaders)) === 0) {
1952 109
            return $this->_secureForwardedHeaderParts = [];
1953
        }
1954
        /*
1955
         * First header is always correct, because proxy CAN add headers
1956
         * after last one is found.
1957
         * Keep in mind that it is NOT enforced, therefore we cannot be
1958
         * sure, that this is really a first one.
1959
         *
1960
         * FPM keeps last header sent which is a bug. You need to merge
1961
         * headers together on your web server before letting FPM handle it
1962
         * @see https://bugs.php.net/bug.php?id=78844
1963
         */
1964 63
        $forwarded = $this->headers->get('Forwarded', '');
1965 63
        if ($forwarded === '') {
1966 43
            return $this->_secureForwardedHeaderParts = [];
1967
        }
1968
1969 20
        preg_match_all('/(?:[^",]++|"[^"]++")+/', $forwarded, $forwardedElements);
1970
1971 20
        foreach ($forwardedElements[0] as $forwardedPairs) {
1972 20
            preg_match_all('/(?P<key>\w+)\s*=\s*(?:(?P<value>[^",;]*[^",;\s])|"(?P<value2>[^"]+)")/', $forwardedPairs,
1973 20
                $matches, PREG_SET_ORDER);
1974 20
            $this->_secureForwardedHeaderParts[] = array_reduce($matches, function ($carry, $item) {
1975 20
                $value = $item['value'];
1976 20
                if (isset($item['value2']) && $item['value2'] !== '') {
1977 4
                    $value = $item['value2'];
1978
                }
1979 20
                $carry[strtolower($item['key'])] = $value;
1980 20
                return $carry;
1981 20
            }, []);
1982
        }
1983 20
        return $this->_secureForwardedHeaderParts;
1984
    }
1985
}
1986