Completed
Push — master ( 4c8880...a140b2 )
by Alexander
89:07 queued 86:08
created

Request::utf8Encode()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 8
cp 0
rs 9.8333
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 20
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 string $absoluteUrl The currently requested absolute URL. This property is read-only.
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 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. This property is read-only.
35
 * @property string|null $authPassword The password sent via HTTP authentication, `null` if the password is
36
 * not given. This property is read-only.
37
 * @property string|null $authUser The username sent via HTTP authentication, `null` if the username is not
38
 * given. This property is read-only.
39
 * @property string $baseUrl The relative URL for the application.
40
 * @property array $bodyParams The request parameters given in the request body.
41
 * @property string $contentType Request content-type. Null is returned if this information is not available.
42
 * This property is read-only.
43
 * @property CookieCollection $cookies The cookie collection. This property is read-only.
44
 * @property string $csrfToken The token used to perform CSRF validation. This property is read-only.
45
 * @property string $csrfTokenFromHeader The CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned
46
 * if no such header is sent. This property is read-only.
47
 * @property array $eTags The entity tags. This property is read-only.
48
 * @property HeaderCollection $headers The header collection. This property is read-only.
49
 * @property string|null $hostInfo Schema and hostname part (with port number if needed) of the request URL
50
 * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. See
51
 * [[getHostInfo()]] for security related notes on this property.
52
 * @property string|null $hostName Hostname part of the request URL (e.g. `www.yiiframework.com`). This
53
 * property is read-only.
54
 * @property bool $isAjax Whether this is an AJAX (XMLHttpRequest) request. This property is read-only.
55
 * @property bool $isDelete Whether this is a DELETE request. This property is read-only.
56
 * @property bool $isFlash Whether this is an Adobe Flash or Adobe Flex request. This property is read-only.
57
 * @property bool $isGet Whether this is a GET request. This property is read-only.
58
 * @property bool $isHead Whether this is a HEAD request. This property is read-only.
59
 * @property bool $isOptions Whether this is a OPTIONS request. This property is read-only.
60
 * @property bool $isPatch Whether this is a PATCH request. This property is read-only.
61
 * @property bool $isPjax Whether this is a PJAX request. This property is read-only.
62
 * @property bool $isPost Whether this is a POST request. This property is read-only.
63
 * @property bool $isPut Whether this is a PUT request. This property is read-only.
64
 * @property bool $isSecureConnection If the request is sent via secure channel (https). This property is
65
 * read-only.
66
 * @property string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is
67
 * turned into upper case. This property is read-only.
68
 * @property string|null $origin URL origin of a CORS request, `null` if not available. This property is
69
 * read-only.
70
 * @property string $pathInfo Part of the request URL that is after the entry script and before the question
71
 * mark. Note, the returned path info is already URL-decoded.
72
 * @property int $port Port number for insecure requests.
73
 * @property array $queryParams The request GET parameter values.
74
 * @property string $queryString Part of the request URL that is after the question mark. This property is
75
 * read-only.
76
 * @property string $rawBody The request body.
77
 * @property string|null $referrer URL referrer, null if not available. This property is read-only.
78
 * @property string|null $remoteHost Remote host name, `null` if not available. This property is read-only.
79
 * @property string|null $remoteIP Remote IP address, `null` if not available. This property is read-only.
80
 * @property string $scriptFile The entry script file path.
81
 * @property string $scriptUrl The relative URL of the entry script.
82
 * @property int $securePort Port number for secure requests.
83
 * @property string $serverName Server name, null if not available. This property is read-only.
84
 * @property int|null $serverPort Server port number, null if not available. This property is read-only.
85
 * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded
86
 * depending on the client.
87
 * @property string|null $userAgent User agent, null if not available. This property is read-only.
88
 * @property string|null $userHost User host name, null if not available. This property is read-only.
89
 * @property string|null $userIP User IP address, null if not available. This property is read-only.
90
 *
91
 * @author Qiang Xue <[email protected]>
92
 * @since 2.0
93
 * @SuppressWarnings(PHPMD.SuperGlobals)
94
 */
95
class Request extends \yii\base\Request
96
{
97
    /**
98
     * The name of the HTTP header for sending CSRF token.
99
     */
100
    const CSRF_HEADER = 'X-CSRF-Token';
101
    /**
102
     * The length of the CSRF token mask.
103
     * @deprecated since 2.0.12. The mask length is now equal to the token length.
104
     */
105
    const CSRF_MASK_LENGTH = 8;
106
107
    /**
108
     * @var bool whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true.
109
     * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated
110
     * from the same application. If not, a 400 HTTP exception will be raised.
111
     *
112
     * Note, this feature requires that the user client accepts cookie. Also, to use this feature,
113
     * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfParam]].
114
     * You may use [[\yii\helpers\Html::beginForm()]] to generate his hidden input.
115
     *
116
     * In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and
117
     * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered.
118
     * You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]].
119
     *
120
     * @see Controller::enableCsrfValidation
121
     * @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
122
     */
123
    public $enableCsrfValidation = true;
124
    /**
125
     * @var string the name of the token used to prevent CSRF. Defaults to '_csrf'.
126
     * This property is used only when [[enableCsrfValidation]] is true.
127
     */
128
    public $csrfParam = '_csrf';
129
    /**
130
     * @var array the configuration for creating the CSRF [[Cookie|cookie]]. This property is used only when
131
     * both [[enableCsrfValidation]] and [[enableCsrfCookie]] are true.
132
     */
133
    public $csrfCookie = ['httpOnly' => true];
134
    /**
135
     * @var bool whether to use cookie to persist CSRF token. If false, CSRF token will be stored
136
     * in session under the name of [[csrfParam]]. Note that while storing CSRF tokens in session increases
137
     * security, it requires starting a session for every page, which will degrade your site performance.
138
     */
139
    public $enableCsrfCookie = true;
140
    /**
141
     * @var bool whether cookies should be validated to ensure they are not tampered. Defaults to true.
142
     */
143
    public $enableCookieValidation = true;
144
    /**
145
     * @var string a secret key used for cookie validation. This property must be set if [[enableCookieValidation]] is true.
146
     */
147
    public $cookieValidationKey;
148
    /**
149
     * @var string the name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE
150
     * request tunneled through POST. Defaults to '_method'.
151
     * @see getMethod()
152
     * @see getBodyParams()
153
     */
154
    public $methodParam = '_method';
155
    /**
156
     * @var array the parsers for converting the raw HTTP request body into [[bodyParams]].
157
     * The array keys are the request `Content-Types`, and the array values are the
158
     * corresponding configurations for [[Yii::createObject|creating the parser objects]].
159
     * A parser must implement the [[RequestParserInterface]].
160
     *
161
     * To enable parsing for JSON requests you can use the [[JsonParser]] class like in the following example:
162
     *
163
     * ```
164
     * [
165
     *     'application/json' => 'yii\web\JsonParser',
166
     * ]
167
     * ```
168
     *
169
     * To register a parser for parsing all request types you can use `'*'` as the array key.
170
     * This one will be used as a fallback in case no other types match.
171
     *
172
     * @see getBodyParams()
173
     */
174
    public $parsers = [];
175
    /**
176
     * @var array the configuration for trusted security related headers.
177
     *
178
     * An array key is an IPv4 or IPv6 IP address in CIDR notation for matching a client.
179
     *
180
     * An array value is a list of headers to trust. These will be matched against
181
     * [[secureHeaders]] to determine which headers are allowed to be sent by a specified host.
182
     * The case of the header names must be the same as specified in [[secureHeaders]].
183
     *
184
     * For example, to trust all headers listed in [[secureHeaders]] for IP addresses
185
     * in range `192.168.0.0-192.168.0.254` write the following:
186
     *
187
     * ```php
188
     * [
189
     *     '192.168.0.0/24',
190
     * ]
191
     * ```
192
     *
193
     * To trust just the `X-Forwarded-For` header from `10.0.0.1`, use:
194
     *
195
     * ```
196
     * [
197
     *     '10.0.0.1' => ['X-Forwarded-For']
198
     * ]
199
     * ```
200
     *
201
     * Default is to trust all headers except those listed in [[secureHeaders]] from all hosts.
202
     * Matches are tried in order and searching is stopped when IP matches.
203
     *
204
     * > Info: Matching is performed using [[IpValidator]].
205
     * See [[IpValidator::::setRanges()|IpValidator::setRanges()]]
206
     * and [[IpValidator::networks]] for advanced matching.
207
     *
208
     * @see $secureHeaders
209
     * @since 2.0.13
210
     */
211
    public $trustedHosts = [];
212
    /**
213
     * @var array lists of headers that are, by default, subject to the trusted host configuration.
214
     * These headers will be filtered unless explicitly allowed in [[trustedHosts]].
215
     * The match of header names is case-insensitive.
216
     * @see https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
217
     * @see $trustedHosts
218
     * @since 2.0.13
219
     */
220
    public $secureHeaders = [
221
        // Common:
222
        'X-Forwarded-For',
223
        'X-Forwarded-Host',
224
        'X-Forwarded-Proto',
225
226
        // Microsoft:
227
        'Front-End-Https',
228
        'X-Rewrite-Url',
229
    ];
230
    /**
231
     * @var string[] List of headers where proxies store the real client IP.
232
     * It's not advisable to put insecure headers here.
233
     * The match of header names is case-insensitive.
234
     * @see $trustedHosts
235
     * @see $secureHeaders
236
     * @since 2.0.13
237
     */
238
    public $ipHeaders = [
239
        'X-Forwarded-For', // Common
240
    ];
241
    /**
242
     * @var array list of headers to check for determining whether the connection is made via HTTPS.
243
     * The array keys are header names and the array value is a list of header values that indicate a secure connection.
244
     * The match of header names and values is case-insensitive.
245
     * It's not advisable to put insecure headers here.
246
     * @see $trustedHosts
247
     * @see $secureHeaders
248
     * @since 2.0.13
249
     */
250
    public $secureProtocolHeaders = [
251
        'X-Forwarded-Proto' => ['https'], // Common
252
        'Front-End-Https' => ['on'], // Microsoft
253
    ];
254
255
    /**
256
     * @var CookieCollection Collection of request cookies.
257
     */
258
    private $_cookies;
259
    /**
260
     * @var HeaderCollection Collection of request headers.
261
     */
262
    private $_headers;
263
264
265
    /**
266
     * Resolves the current request into a route and the associated parameters.
267
     * @return array the first element is the route, and the second is the associated parameters.
268
     * @throws NotFoundHttpException if the request cannot be resolved.
269
     */
270 1
    public function resolve()
271
    {
272 1
        $result = Yii::$app->getUrlManager()->parseRequest($this);
273 1
        if ($result !== false) {
274 1
            list($route, $params) = $result;
275 1
            if ($this->_queryParams === null) {
276 1
                $_GET = $params + $_GET; // preserve numeric keys
277
            } else {
278 1
                $this->_queryParams = $params + $this->_queryParams;
279
            }
280
281 1
            return [$route, $this->getQueryParams()];
282
        }
283
284
        throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
285
    }
286
287
    /**
288
     * Filters headers according to the [[trustedHosts]].
289
     * @param HeaderCollection $headerCollection
290
     * @since 2.0.13
291
     */
292 164
    protected function filterHeaders(HeaderCollection $headerCollection)
293
    {
294
        // do not trust any of the [[secureHeaders]] by default
295 164
        $trustedHeaders = [];
296
297
        // check if the client is a trusted host
298 164
        if (!empty($this->trustedHosts)) {
299 25
            $validator = $this->getIpValidator();
300 25
            $ip = $this->getRemoteIP();
301 25
            foreach ($this->trustedHosts as $cidr => $headers) {
302 25
                if (!is_array($headers)) {
303 25
                    $cidr = $headers;
304 25
                    $headers = $this->secureHeaders;
305
                }
306 25
                $validator->setRanges($cidr);
307 25
                if ($validator->validate($ip)) {
308 5
                    $trustedHeaders = $headers;
309 25
                    break;
310
                }
311
            }
312
        }
313
314
        // filter all secure headers unless they are trusted
315 164
        foreach ($this->secureHeaders as $secureHeader) {
316 164
            if (!in_array($secureHeader, $trustedHeaders)) {
317 164
                $headerCollection->remove($secureHeader);
318
            }
319
        }
320 164
    }
321
322
    /**
323
     * Creates instance of [[IpValidator]].
324
     * You can override this method to adjust validator or implement different matching strategy.
325
     *
326
     * @return IpValidator
327
     * @since 2.0.13
328
     */
329 25
    protected function getIpValidator()
330
    {
331 25
        return new IpValidator();
332
    }
333
334
    /**
335
     * Returns the header collection.
336
     * The header collection contains incoming HTTP headers.
337
     * @return HeaderCollection the header collection
338
     */
339 164
    public function getHeaders()
340
    {
341 164
        if ($this->_headers === null) {
342 164
            $this->_headers = new HeaderCollection();
343 164
            if (function_exists('getallheaders')) {
344
                $headers = getallheaders();
345
                foreach ($headers as $name => $value) {
346
                    $this->_headers->add($name, $value);
347
                }
348 164
            } elseif (function_exists('http_get_request_headers')) {
349
                $headers = http_get_request_headers();
350
                foreach ($headers as $name => $value) {
351
                    $this->_headers->add($name, $value);
352
                }
353
            } else {
354 164
                foreach ($_SERVER as $name => $value) {
355 160
                    if (strncmp($name, 'HTTP_', 5) === 0) {
356 42
                        $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
357 160
                        $this->_headers->add($name, $value);
358
                    }
359
                }
360
            }
361 164
            $this->filterHeaders($this->_headers);
362
        }
363
364 164
        return $this->_headers;
365
    }
366
367
    /**
368
     * Returns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE).
369
     * @return string request method, such as GET, POST, HEAD, PUT, PATCH, DELETE.
370
     * The value returned is turned into upper case.
371
     */
372 31
    public function getMethod()
373
    {
374 31
        if (isset($_POST[$this->methodParam])) {
375 4
            return strtoupper($_POST[$this->methodParam]);
376
        }
377
378 28
        if ($this->headers->has('X-Http-Method-Override')) {
379 1
            return strtoupper($this->headers->get('X-Http-Method-Override'));
380
        }
381
382 27
        if (isset($_SERVER['REQUEST_METHOD'])) {
383 6
            return strtoupper($_SERVER['REQUEST_METHOD']);
384
        }
385
386 22
        return 'GET';
387
    }
388
389
    /**
390
     * Returns whether this is a GET request.
391
     * @return bool whether this is a GET request.
392
     */
393 2
    public function getIsGet()
394
    {
395 2
        return $this->getMethod() === 'GET';
396
    }
397
398
    /**
399
     * Returns whether this is an OPTIONS request.
400
     * @return bool whether this is a OPTIONS request.
401
     */
402 2
    public function getIsOptions()
403
    {
404 2
        return $this->getMethod() === 'OPTIONS';
405
    }
406
407
    /**
408
     * Returns whether this is a HEAD request.
409
     * @return bool whether this is a HEAD request.
410
     */
411 11
    public function getIsHead()
412
    {
413 11
        return $this->getMethod() === 'HEAD';
414
    }
415
416
    /**
417
     * Returns whether this is a POST request.
418
     * @return bool whether this is a POST request.
419
     */
420
    public function getIsPost()
421
    {
422
        return $this->getMethod() === 'POST';
423
    }
424
425
    /**
426
     * Returns whether this is a DELETE request.
427
     * @return bool whether this is a DELETE request.
428
     */
429
    public function getIsDelete()
430
    {
431
        return $this->getMethod() === 'DELETE';
432
    }
433
434
    /**
435
     * Returns whether this is a PUT request.
436
     * @return bool whether this is a PUT request.
437
     */
438
    public function getIsPut()
439
    {
440
        return $this->getMethod() === 'PUT';
441
    }
442
443
    /**
444
     * Returns whether this is a PATCH request.
445
     * @return bool whether this is a PATCH request.
446
     */
447
    public function getIsPatch()
448
    {
449
        return $this->getMethod() === 'PATCH';
450
    }
451
452
    /**
453
     * Returns whether this is an AJAX (XMLHttpRequest) request.
454
     *
455
     * Note that jQuery doesn't set the header in case of cross domain
456
     * requests: https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header
457
     *
458
     * @return bool whether this is an AJAX (XMLHttpRequest) request.
459
     */
460 15
    public function getIsAjax()
461
    {
462 15
        return $this->headers->get('X-Requested-With') === 'XMLHttpRequest';
463
    }
464
465
    /**
466
     * Returns whether this is a PJAX request.
467
     * @return bool whether this is a PJAX request
468
     */
469 3
    public function getIsPjax()
470
    {
471 3
        return $this->getIsAjax() && $this->headers->has('X-Pjax');
472
    }
473
474
    /**
475
     * Returns whether this is an Adobe Flash or Flex request.
476
     * @return bool whether this is an Adobe Flash or Adobe Flex request.
477
     */
478
    public function getIsFlash()
479
    {
480
        $userAgent = $this->headers->get('User-Agent', '');
481
        return stripos($userAgent, 'Shockwave') !== false
482
            || stripos($userAgent, 'Flash') !== false;
483
    }
484
485
    private $_rawBody;
486
487
    /**
488
     * Returns the raw HTTP request body.
489
     * @return string the request body
490
     */
491 3
    public function getRawBody()
492
    {
493 3
        if ($this->_rawBody === null) {
494 3
            $this->_rawBody = file_get_contents('php://input');
495
        }
496
497 3
        return $this->_rawBody;
498
    }
499
500
    /**
501
     * Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
502
     * @param string $rawBody the request body
503
     */
504
    public function setRawBody($rawBody)
505
    {
506
        $this->_rawBody = $rawBody;
507
    }
508
509
    private $_bodyParams;
510
511
    /**
512
     * Returns the request parameters given in the request body.
513
     *
514
     * Request parameters are determined using the parsers configured in [[parsers]] property.
515
     * If no parsers are configured for the current [[contentType]] it uses the PHP function `mb_parse_str()`
516
     * to parse the [[rawBody|request body]].
517
     * @return array the request parameters given in the request body.
518
     * @throws \yii\base\InvalidConfigException if a registered parser does not implement the [[RequestParserInterface]].
519
     * @see getMethod()
520
     * @see getBodyParam()
521
     * @see setBodyParams()
522
     */
523 7
    public function getBodyParams()
524
    {
525 7
        if ($this->_bodyParams === null) {
526 4
            if (isset($_POST[$this->methodParam])) {
527 1
                $this->_bodyParams = $_POST;
528 1
                unset($this->_bodyParams[$this->methodParam]);
529 1
                return $this->_bodyParams;
530
            }
531
532 3
            $rawContentType = $this->getContentType();
533 3
            if (($pos = strpos($rawContentType, ';')) !== false) {
534
                // e.g. text/html; charset=UTF-8
535
                $contentType = substr($rawContentType, 0, $pos);
536
            } else {
537 3
                $contentType = $rawContentType;
538
            }
539
540 3
            if (isset($this->parsers[$contentType])) {
541
                $parser = Yii::createObject($this->parsers[$contentType]);
542
                if (!($parser instanceof RequestParserInterface)) {
543
                    throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
544
                }
545
                $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
546 3
            } elseif (isset($this->parsers['*'])) {
547
                $parser = Yii::createObject($this->parsers['*']);
548
                if (!($parser instanceof RequestParserInterface)) {
549
                    throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.');
550
                }
551
                $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
552 3
            } elseif ($this->getMethod() === 'POST') {
553
                // PHP has already parsed the body so we have all params in $_POST
554
                $this->_bodyParams = $_POST;
555
            } else {
556 3
                $this->_bodyParams = [];
557 3
                mb_parse_str($this->getRawBody(), $this->_bodyParams);
558
            }
559
        }
560
561 7
        return $this->_bodyParams;
562
    }
563
564
    /**
565
     * Sets the request body parameters.
566
     * @param array $values the request body parameters (name-value pairs)
567
     * @see getBodyParam()
568
     * @see getBodyParams()
569
     */
570 6
    public function setBodyParams($values)
571
    {
572 6
        $this->_bodyParams = $values;
573 6
    }
574
575
    /**
576
     * Returns the named request body parameter value.
577
     * If the parameter does not exist, the second parameter passed to this method will be returned.
578
     * @param string $name the parameter name
579
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
580
     * @return mixed the parameter value
581
     * @see getBodyParams()
582
     * @see setBodyParams()
583
     */
584 7
    public function getBodyParam($name, $defaultValue = null)
585
    {
586 7
        $params = $this->getBodyParams();
587
588 7
        if (is_object($params)) {
589
            // unable to use `ArrayHelper::getValue()` due to different dots in key logic and lack of exception handling
590
            try {
591 1
                return $params->{$name};
592 1
            } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) { ...return $defaultValue; } does not seem to be reachable.

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

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

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

    return false;
}

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

Loading history...
593 1
                return $defaultValue;
594
            }
595
        }
596
597 7
        return isset($params[$name]) ? $params[$name] : $defaultValue;
598
    }
599
600
    /**
601
     * Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters.
602
     *
603
     * @param string $name the parameter name
604
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
605
     * @return array|mixed
606
     */
607
    public function post($name = null, $defaultValue = null)
608
    {
609
        if ($name === null) {
610
            return $this->getBodyParams();
611
        }
612
613
        return $this->getBodyParam($name, $defaultValue);
614
    }
615
616
    private $_queryParams;
617
618
    /**
619
     * Returns the request parameters given in the [[queryString]].
620
     *
621
     * This method will return the contents of `$_GET` if params where not explicitly set.
622
     * @return array the request GET parameter values.
623
     * @see setQueryParams()
624
     */
625 36
    public function getQueryParams()
626
    {
627 36
        if ($this->_queryParams === null) {
628 29
            return $_GET;
629
        }
630
631 9
        return $this->_queryParams;
632
    }
633
634
    /**
635
     * Sets the request [[queryString]] parameters.
636
     * @param array $values the request query parameters (name-value pairs)
637
     * @see getQueryParam()
638
     * @see getQueryParams()
639
     */
640 9
    public function setQueryParams($values)
641
    {
642 9
        $this->_queryParams = $values;
643 9
    }
644
645
    /**
646
     * Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.
647
     *
648
     * @param string $name the parameter name
649
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
650
     * @return array|mixed
651
     */
652 24
    public function get($name = null, $defaultValue = null)
653
    {
654 24
        if ($name === null) {
655
            return $this->getQueryParams();
656
        }
657
658 24
        return $this->getQueryParam($name, $defaultValue);
659
    }
660
661
    /**
662
     * Returns the named GET parameter value.
663
     * If the GET parameter does not exist, the second parameter passed to this method will be returned.
664
     * @param string $name the GET parameter name.
665
     * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
666
     * @return mixed the GET parameter value
667
     * @see getBodyParam()
668
     */
669 27
    public function getQueryParam($name, $defaultValue = null)
670
    {
671 27
        $params = $this->getQueryParams();
672
673 27
        return isset($params[$name]) ? $params[$name] : $defaultValue;
674
    }
675
676
    private $_hostInfo;
677
    private $_hostName;
678
679
    /**
680
     * Returns the schema and host part of the current request URL.
681
     *
682
     * The returned URL does not have an ending slash.
683
     *
684
     * By default this value is based on the user request information. This method will
685
     * return the value of `$_SERVER['HTTP_HOST']` if it is available or `$_SERVER['SERVER_NAME']` if not.
686
     * You may want to check out the [PHP documentation](http://php.net/manual/en/reserved.variables.server.php)
687
     * for more information on these variables.
688
     *
689
     * You may explicitly specify it by setting the [[setHostInfo()|hostInfo]] property.
690
     *
691
     * > Warning: Dependent on the server configuration this information may not be
692
     * > reliable and [may be faked by the user sending the HTTP request](https://www.acunetix.com/vulnerabilities/web/host-header-attack).
693
     * > If the webserver is configured to serve the same site independent of the value of
694
     * > the `Host` header, this value is not reliable. In such situations you should either
695
     * > fix your webserver configuration or explicitly set the value by setting the [[setHostInfo()|hostInfo]] property.
696
     * > If you don't have access to the server configuration, you can setup [[\yii\filters\HostControl]] filter at
697
     * > application level in order to protect against such kind of attack.
698
     *
699
     * @property string|null schema and hostname part (with port number if needed) of the request URL
700
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
701
     * See [[getHostInfo()]] for security related notes on this property.
702
     * @return string|null schema and hostname part (with port number if needed) of the request URL
703
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
704
     * @see setHostInfo()
705
     */
706 30
    public function getHostInfo()
707
    {
708 30
        if ($this->_hostInfo === null) {
709 26
            $secure = $this->getIsSecureConnection();
710 26
            $http = $secure ? 'https' : 'http';
711
712 26
            if ($this->headers->has('X-Forwarded-Host')) {
713 2
                $this->_hostInfo = $http . '://' . trim(explode(',', $this->headers->get('X-Forwarded-Host'))[0]);
714 24
            } elseif ($this->headers->has('Host')) {
715 9
                $this->_hostInfo = $http . '://' . $this->headers->get('Host');
716 15
            } elseif (isset($_SERVER['SERVER_NAME'])) {
717 1
                $this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME'];
718 1
                $port = $secure ? $this->getSecurePort() : $this->getPort();
719 1
                if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
720
                    $this->_hostInfo .= ':' . $port;
721
                }
722
            }
723
        }
724
725 30
        return $this->_hostInfo;
726
    }
727
728
    /**
729
     * Sets the schema and host part of the application URL.
730
     * This setter is provided in case the schema and hostname cannot be determined
731
     * on certain Web servers.
732
     * @param string|null $value the schema and host part of the application URL. The trailing slashes will be removed.
733
     * @see getHostInfo() for security related notes on this property.
734
     */
735 58
    public function setHostInfo($value)
736
    {
737 58
        $this->_hostName = null;
738 58
        $this->_hostInfo = $value === null ? null : rtrim($value, '/');
739 58
    }
740
741
    /**
742
     * Returns the host part of the current request URL.
743
     * Value is calculated from current [[getHostInfo()|hostInfo]] property.
744
     *
745
     * > Warning: The content of this value may not be reliable, dependent on the server
746
     * > configuration. Please refer to [[getHostInfo()]] for more information.
747
     *
748
     * @return string|null hostname part of the request URL (e.g. `www.yiiframework.com`)
749
     * @see getHostInfo()
750
     * @since 2.0.10
751
     */
752 17
    public function getHostName()
753
    {
754 17
        if ($this->_hostName === null) {
755 17
            $this->_hostName = parse_url($this->getHostInfo(), PHP_URL_HOST);
756
        }
757
758 17
        return $this->_hostName;
759
    }
760
761
    private $_baseUrl;
762
763
    /**
764
     * Returns the relative URL for the application.
765
     * This is similar to [[scriptUrl]] except that it does not include the script file name,
766
     * and the ending slashes are removed.
767
     * @return string the relative URL for the application
768
     * @see setScriptUrl()
769
     */
770 318
    public function getBaseUrl()
771
    {
772 318
        if ($this->_baseUrl === null) {
773 317
            $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/');
774
        }
775
776 318
        return $this->_baseUrl;
777
    }
778
779
    /**
780
     * Sets the relative URL for the application.
781
     * By default the URL is determined based on the entry script URL.
782
     * This setter is provided in case you want to change this behavior.
783
     * @param string $value the relative URL for the application
784
     */
785 1
    public function setBaseUrl($value)
786
    {
787 1
        $this->_baseUrl = $value;
788 1
    }
789
790
    private $_scriptUrl;
791
792
    /**
793
     * Returns the relative URL of the entry script.
794
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
795
     * @return string the relative URL of the entry script.
796
     * @throws InvalidConfigException if unable to determine the entry script URL
797
     */
798 319
    public function getScriptUrl()
799
    {
800 319
        if ($this->_scriptUrl === null) {
801 1
            $scriptFile = $this->getScriptFile();
802
            $scriptName = basename($scriptFile);
803
            if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
804
                $this->_scriptUrl = $_SERVER['SCRIPT_NAME'];
805
            } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $scriptName) {
806
                $this->_scriptUrl = $_SERVER['PHP_SELF'];
807
            } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
808
                $this->_scriptUrl = $_SERVER['ORIG_SCRIPT_NAME'];
809
            } elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
810
                $this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
811
            } elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) {
812
                $this->_scriptUrl = str_replace([$_SERVER['DOCUMENT_ROOT'], '\\'], ['', '/'], $scriptFile);
813
            } else {
814
                throw new InvalidConfigException('Unable to determine the entry script URL.');
815
            }
816
        }
817
818 318
        return $this->_scriptUrl;
819
    }
820
821
    /**
822
     * Sets the relative URL for the application entry script.
823
     * This setter is provided in case the entry script URL cannot be determined
824
     * on certain Web servers.
825
     * @param string $value the relative URL for the application entry script.
826
     */
827 329
    public function setScriptUrl($value)
828
    {
829 329
        $this->_scriptUrl = $value === null ? null : '/' . trim($value, '/');
830 329
    }
831
832
    private $_scriptFile;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
833
834
    /**
835
     * Returns the entry script file path.
836
     * The default implementation will simply return `$_SERVER['SCRIPT_FILENAME']`.
837
     * @return string the entry script file path
838
     * @throws InvalidConfigException
839
     */
840 320
    public function getScriptFile()
841
    {
842 320
        if (isset($this->_scriptFile)) {
843 296
            return $this->_scriptFile;
844
        }
845
846 24
        if (isset($_SERVER['SCRIPT_FILENAME'])) {
847 22
            return $_SERVER['SCRIPT_FILENAME'];
848
        }
849
850 2
        throw new InvalidConfigException('Unable to determine the entry script file path.');
851
    }
852
853
    /**
854
     * Sets the entry script file path.
855
     * The entry script file path normally can be obtained from `$_SERVER['SCRIPT_FILENAME']`.
856
     * If your server configuration does not return the correct value, you may configure
857
     * this property to make it right.
858
     * @param string $value the entry script file path.
859
     */
860 296
    public function setScriptFile($value)
861
    {
862 296
        $this->_scriptFile = $value;
863 296
    }
864
865
    private $_pathInfo;
866
867
    /**
868
     * Returns the path info of the currently requested URL.
869
     * A path info refers to the part that is after the entry script and before the question mark (query string).
870
     * The starting and ending slashes are both removed.
871
     * @return string part of the request URL that is after the entry script and before the question mark.
872
     * Note, the returned path info is already URL-decoded.
873
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
874
     */
875 19
    public function getPathInfo()
876
    {
877 19
        if ($this->_pathInfo === null) {
878
            $this->_pathInfo = $this->resolvePathInfo();
879
        }
880
881 19
        return $this->_pathInfo;
882
    }
883
884
    /**
885
     * Sets the path info of the current request.
886
     * This method is mainly provided for testing purpose.
887
     * @param string $value the path info of the current request
888
     */
889 20
    public function setPathInfo($value)
890
    {
891 20
        $this->_pathInfo = $value === null ? null : ltrim($value, '/');
892 20
    }
893
894
    /**
895
     * Resolves the path info part of the currently requested URL.
896
     * A path info refers to the part that is after the entry script and before the question mark (query string).
897
     * The starting slashes are both removed (ending slashes will be kept).
898
     * @return string part of the request URL that is after the entry script and before the question mark.
899
     * Note, the returned path info is decoded.
900
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
901
     */
902
    protected function resolvePathInfo()
903
    {
904
        $pathInfo = $this->getUrl();
905
906
        if (($pos = strpos($pathInfo, '?')) !== false) {
907
            $pathInfo = substr($pathInfo, 0, $pos);
908
        }
909
910
        $pathInfo = urldecode($pathInfo);
911
912
        // try to encode in UTF8 if not so
913
        // http://w3.org/International/questions/qa-forms-utf-8.html
914
        if (!preg_match('%^(?:
915
            [\x09\x0A\x0D\x20-\x7E]              # ASCII
916
            | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
917
            | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
918
            | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
919
            | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
920
            | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
921
            | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
922
            | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
923
            )*$%xs', $pathInfo)
924
        ) {
925
            $pathInfo = $this->utf8Encode($pathInfo);
926
        }
927
928
        $scriptUrl = $this->getScriptUrl();
929
        $baseUrl = $this->getBaseUrl();
930
        if (strpos($pathInfo, $scriptUrl) === 0) {
931
            $pathInfo = substr($pathInfo, strlen($scriptUrl));
932
        } elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) {
933
            $pathInfo = substr($pathInfo, strlen($baseUrl));
934
        } elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0) {
935
            $pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
936
        } else {
937
            throw new InvalidConfigException('Unable to determine the path info of the current request.');
938
        }
939
940
        if (strncmp($pathInfo, '/', 1) === 0) {
941
            $pathInfo = substr($pathInfo, 1);
942
        }
943
944
        return (string) $pathInfo;
945
    }
946
947
    /**
948
     * Encodes an ISO-8859-1 string to UTF-8
949
     * @param string $s
950
     * @return string the UTF-8 translation of `s`.
951
     * @see https://github.com/symfony/polyfill-php72/blob/master/Php72.php#L24
952
     */
953
    private function utf8Encode($s)
954
    {
955
        $s .= $s;
956
        $len = \strlen($s);
957
        for ($i = $len >> 1, $j = 0; $i < $len; ++$i, ++$j) {
958
            switch (true) {
959
                case $s[$i] < "\x80": $s[$j] = $s[$i]; break;
960
                case $s[$i] < "\xC0": $s[$j] = "\xC2"; $s[++$j] = $s[$i]; break;
961
                default: $s[$j] = "\xC3"; $s[++$j] = \chr(\ord($s[$i]) - 64); break;
962
            }
963
        }
964
        return substr($s, 0, $j);
965
    }
966
967
    /**
968
     * Returns the currently requested absolute URL.
969
     * This is a shortcut to the concatenation of [[hostInfo]] and [[url]].
970
     * @return string the currently requested absolute URL.
971
     */
972
    public function getAbsoluteUrl()
973
    {
974
        return $this->getHostInfo() . $this->getUrl();
975
    }
976
977
    private $_url;
978
979
    /**
980
     * Returns the currently requested relative URL.
981
     * This refers to the portion of the URL that is after the [[hostInfo]] part.
982
     * It includes the [[queryString]] part if any.
983
     * @return string the currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.
984
     * @throws InvalidConfigException if the URL cannot be determined due to unusual server configuration
985
     */
986 11
    public function getUrl()
987
    {
988 11
        if ($this->_url === null) {
989 3
            $this->_url = $this->resolveRequestUri();
990
        }
991
992 11
        return $this->_url;
993
    }
994
995
    /**
996
     * Sets the currently requested relative URL.
997
     * The URI must refer to the portion that is after [[hostInfo]].
998
     * Note that the URI should be URL-encoded.
999
     * @param string $value the request URI to be set
1000
     */
1001 24
    public function setUrl($value)
1002
    {
1003 24
        $this->_url = $value;
1004 24
    }
1005
1006
    /**
1007
     * Resolves the request URI portion for the currently requested URL.
1008
     * This refers to the portion that is after the [[hostInfo]] part. It includes the [[queryString]] part if any.
1009
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
1010
     * @return string|bool the request URI portion for the currently requested URL.
1011
     * Note that the URI returned may be URL-encoded depending on the client.
1012
     * @throws InvalidConfigException if the request URI cannot be determined due to unusual server configuration
1013
     */
1014 3
    protected function resolveRequestUri()
1015
    {
1016 3
        if ($this->headers->has('X-Rewrite-Url')) { // IIS
1017
            $requestUri = $this->headers->get('X-Rewrite-Url');
1018 3
        } elseif (isset($_SERVER['REQUEST_URI'])) {
1019 3
            $requestUri = $_SERVER['REQUEST_URI'];
1020 3
            if ($requestUri !== '' && $requestUri[0] !== '/') {
1021 3
                $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
1022
            }
1023
        } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 CGI
1024
            $requestUri = $_SERVER['ORIG_PATH_INFO'];
1025
            if (!empty($_SERVER['QUERY_STRING'])) {
1026
                $requestUri .= '?' . $_SERVER['QUERY_STRING'];
1027
            }
1028
        } else {
1029
            throw new InvalidConfigException('Unable to determine the request URI.');
1030
        }
1031
1032 3
        return $requestUri;
1033
    }
1034
1035
    /**
1036
     * Returns part of the request URL that is after the question mark.
1037
     * @return string part of the request URL that is after the question mark
1038
     */
1039
    public function getQueryString()
1040
    {
1041
        return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
1042
    }
1043
1044
    /**
1045
     * Return if the request is sent via secure channel (https).
1046
     * @return bool if the request is sent via secure channel (https)
1047
     */
1048 43
    public function getIsSecureConnection()
1049
    {
1050 43
        if (isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)) {
1051 2
            return true;
1052
        }
1053 41
        foreach ($this->secureProtocolHeaders as $header => $values) {
1054 41
            if (($headerValue = $this->headers->get($header, null)) !== null) {
1055 2
                foreach ($values as $value) {
1056 2
                    if (strcasecmp($headerValue, $value) === 0) {
1057 41
                        return true;
1058
                    }
1059
                }
1060
            }
1061
        }
1062
1063 39
        return false;
1064
    }
1065
1066
    /**
1067
     * Returns the server name.
1068
     * @return string server name, null if not available
1069
     */
1070 1
    public function getServerName()
1071
    {
1072 1
        return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
1073
    }
1074
1075
    /**
1076
     * Returns the server port number.
1077
     * @return int|null server port number, null if not available
1078
     */
1079 2
    public function getServerPort()
1080
    {
1081 2
        return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null;
1082
    }
1083
1084
    /**
1085
     * Returns the URL referrer.
1086
     * @return string|null URL referrer, null if not available
1087
     */
1088
    public function getReferrer()
1089
    {
1090
        return $this->headers->get('Referer');
1091
    }
1092
1093
    /**
1094
     * Returns the URL origin of a CORS request.
1095
     *
1096
     * The return value is taken from the `Origin` [[getHeaders()|header]] sent by the browser.
1097
     *
1098
     * Note that the origin request header indicates where a fetch originates from.
1099
     * It doesn't include any path information, but only the server name.
1100
     * It is sent with a CORS requests, as well as with POST requests.
1101
     * It is similar to the referer header, but, unlike this header, it doesn't disclose the whole path.
1102
     * Please refer to <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin> for more information.
1103
     *
1104
     * @return string|null URL origin of a CORS request, `null` if not available.
1105
     * @see getHeaders()
1106
     * @since 2.0.13
1107
     */
1108 1
    public function getOrigin()
1109
    {
1110 1
        return $this->getHeaders()->get('origin');
1111
    }
1112
1113
    /**
1114
     * Returns the user agent.
1115
     * @return string|null user agent, null if not available
1116
     */
1117
    public function getUserAgent()
1118
    {
1119
        return $this->headers->get('User-Agent');
1120
    }
1121
1122
    /**
1123
     * Returns the user IP address.
1124
     * The IP is determined using headers and / or `$_SERVER` variables.
1125
     * @return string|null user IP address, null if not available
1126
     */
1127 55
    public function getUserIP()
1128
    {
1129 55
        foreach ($this->ipHeaders as $ipHeader) {
1130 55
            if ($this->headers->has($ipHeader)) {
1131 55
                return trim(explode(',', $this->headers->get($ipHeader))[0]);
1132
            }
1133
        }
1134
1135 54
        return $this->getRemoteIP();
1136
    }
1137
1138
    /**
1139
     * Returns the user host name.
1140
     * The HOST is determined using headers and / or `$_SERVER` variables.
1141
     * @return string|null user host name, null if not available
1142
     */
1143
    public function getUserHost()
1144
    {
1145
        foreach ($this->ipHeaders as $ipHeader) {
1146
            if ($this->headers->has($ipHeader)) {
1147
                return gethostbyaddr(trim(explode(',', $this->headers->get($ipHeader))[0]));
1148
            }
1149
        }
1150
1151
        return $this->getRemoteHost();
1152
    }
1153
1154
    /**
1155
     * Returns the IP on the other end of this connection.
1156
     * This is always the next hop, any headers are ignored.
1157
     * @return string|null remote IP address, `null` if not available.
1158
     * @since 2.0.13
1159
     */
1160 76
    public function getRemoteIP()
1161
    {
1162 76
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
1163
    }
1164
1165
    /**
1166
     * Returns the host name of the other end of this connection.
1167
     * This is always the next hop, any headers are ignored.
1168
     * @return string|null remote host name, `null` if not available
1169
     * @see getUserHost()
1170
     * @see getRemoteIP()
1171
     * @since 2.0.13
1172
     */
1173
    public function getRemoteHost()
1174
    {
1175
        return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
1176
    }
1177
1178
    /**
1179
     * @return string|null the username sent via HTTP authentication, `null` if the username is not given
1180
     * @see getAuthCredentials() to get both username and password in one call
1181
     */
1182 9
    public function getAuthUser()
1183
    {
1184 9
        return $this->getAuthCredentials()[0];
1185
    }
1186
1187
    /**
1188
     * @return string|null the password sent via HTTP authentication, `null` if the password is not given
1189
     * @see getAuthCredentials() to get both username and password in one call
1190
     */
1191 9
    public function getAuthPassword()
1192
    {
1193 9
        return $this->getAuthCredentials()[1];
1194
    }
1195
1196
    /**
1197
     * @return array that contains exactly two elements:
1198
     * - 0: the username sent via HTTP authentication, `null` if the username is not given
1199
     * - 1: the password sent via HTTP authentication, `null` if the password is not given
1200
     * @see getAuthUser() to get only username
1201
     * @see getAuthPassword() to get only password
1202
     * @since 2.0.13
1203
     */
1204 34
    public function getAuthCredentials()
1205
    {
1206 34
        $username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
1207 34
        $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
1208 34
        if ($username !== null || $password !== null) {
1209 16
            return [$username, $password];
1210
        }
1211
1212
        /*
1213
         * Apache with php-cgi does not pass HTTP Basic authentication to PHP by default.
1214
         * To make it work, add the following line to to your .htaccess file:
1215
         *
1216
         * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
1217
         */
1218 18
        $auth_token = $this->getHeaders()->get('HTTP_AUTHORIZATION') ?: $this->getHeaders()->get('REDIRECT_HTTP_AUTHORIZATION');
1219 18
        if ($auth_token !== null && strncasecmp($auth_token, 'basic', 5) === 0) {
1220
            $parts = array_map(function ($value) {
1221 18
                return strlen($value) === 0 ? null : $value;
1222 18
            }, explode(':', base64_decode(mb_substr($auth_token, 6)), 2));
1223
1224 18
            if (count($parts) < 2) {
1225 2
                return [$parts[0], null];
1226
            }
1227
1228 16
            return $parts;
1229
        }
1230
1231
        return [null, null];
1232
    }
1233
1234
    private $_port;
1235
1236
    /**
1237
     * Returns the port to use for insecure requests.
1238
     * Defaults to 80, or the port specified by the server if the current
1239
     * request is insecure.
1240
     * @return int port number for insecure requests.
1241
     * @see setPort()
1242
     */
1243 1
    public function getPort()
1244
    {
1245 1
        if ($this->_port === null) {
1246 1
            $serverPort = $this->getServerPort();
1247 1
            $this->_port = !$this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 80;
1248
        }
1249
1250 1
        return $this->_port;
1251
    }
1252
1253
    /**
1254
     * Sets the port to use for insecure requests.
1255
     * This setter is provided in case a custom port is necessary for certain
1256
     * server configurations.
1257
     * @param int $value port number.
1258
     */
1259
    public function setPort($value)
1260
    {
1261
        if ($value != $this->_port) {
1262
            $this->_port = (int) $value;
1263
            $this->_hostInfo = null;
1264
        }
1265
    }
1266
1267
    private $_securePort;
1268
1269
    /**
1270
     * Returns the port to use for secure requests.
1271
     * Defaults to 443, or the port specified by the server if the current
1272
     * request is secure.
1273
     * @return int port number for secure requests.
1274
     * @see setSecurePort()
1275
     */
1276
    public function getSecurePort()
1277
    {
1278
        if ($this->_securePort === null) {
1279
            $serverPort = $this->getServerPort();
1280
            $this->_securePort = $this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 443;
1281
        }
1282
1283
        return $this->_securePort;
1284
    }
1285
1286
    /**
1287
     * Sets the port to use for secure requests.
1288
     * This setter is provided in case a custom port is necessary for certain
1289
     * server configurations.
1290
     * @param int $value port number.
1291
     */
1292
    public function setSecurePort($value)
1293
    {
1294
        if ($value != $this->_securePort) {
1295
            $this->_securePort = (int) $value;
1296
            $this->_hostInfo = null;
1297
        }
1298
    }
1299
1300
    private $_contentTypes;
1301
1302
    /**
1303
     * Returns the content types acceptable by the end user.
1304
     *
1305
     * This is determined by the `Accept` HTTP header. For example,
1306
     *
1307
     * ```php
1308
     * $_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1309
     * $types = $request->getAcceptableContentTypes();
1310
     * print_r($types);
1311
     * // displays:
1312
     * // [
1313
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1314
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1315
     * //           'text/plain' => ['q' => 0.5],
1316
     * // ]
1317
     * ```
1318
     *
1319
     * @return array the content types ordered by the quality score. Types with the highest scores
1320
     * will be returned first. The array keys are the content types, while the array values
1321
     * are the corresponding quality score and other parameters as given in the header.
1322
     */
1323 3
    public function getAcceptableContentTypes()
1324
    {
1325 3
        if ($this->_contentTypes === null) {
1326 3
            if ($this->headers->get('Accept') !== null) {
1327 2
                $this->_contentTypes = $this->parseAcceptHeader($this->headers->get('Accept'));
0 ignored issues
show
Bug introduced by
It seems like $this->headers->get('Accept') targeting yii\web\HeaderCollection::get() can also be of type array; however, yii\web\Request::parseAcceptHeader() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
1328
            } else {
1329 2
                $this->_contentTypes = [];
1330
            }
1331
        }
1332
1333 3
        return $this->_contentTypes;
1334
    }
1335
1336
    /**
1337
     * Sets the acceptable content types.
1338
     * Please refer to [[getAcceptableContentTypes()]] on the format of the parameter.
1339
     * @param array $value the content types that are acceptable by the end user. They should
1340
     * be ordered by the preference level.
1341
     * @see getAcceptableContentTypes()
1342
     * @see parseAcceptHeader()
1343
     */
1344
    public function setAcceptableContentTypes($value)
1345
    {
1346
        $this->_contentTypes = $value;
1347
    }
1348
1349
    /**
1350
     * Returns request content-type
1351
     * The Content-Type header field indicates the MIME type of the data
1352
     * contained in [[getRawBody()]] or, in the case of the HEAD method, the
1353
     * media type that would have been sent had the request been a GET.
1354
     * For the MIME-types the user expects in response, see [[acceptableContentTypes]].
1355
     * @return string request content-type. Null is returned if this information is not available.
1356
     * @link https://tools.ietf.org/html/rfc2616#section-14.17
1357
     * HTTP 1.1 header field definitions
1358
     */
1359 3
    public function getContentType()
1360
    {
1361 3
        if (isset($_SERVER['CONTENT_TYPE'])) {
1362
            return $_SERVER['CONTENT_TYPE'];
1363
        }
1364
1365
        //fix bug https://bugs.php.net/bug.php?id=66606
1366 3
        return $this->headers->get('Content-Type');
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->headers->get('Content-Type'); of type string|array adds the type array to the return on line 1366 which is incompatible with the return type documented by yii\web\Request::getContentType of type string.
Loading history...
1367
    }
1368
1369
    private $_languages;
1370
1371
    /**
1372
     * Returns the languages acceptable by the end user.
1373
     * This is determined by the `Accept-Language` HTTP header.
1374
     * @return array the languages ordered by the preference level. The first element
1375
     * represents the most preferred language.
1376
     */
1377 2
    public function getAcceptableLanguages()
1378
    {
1379 2
        if ($this->_languages === null) {
1380 1
            if ($this->headers->has('Accept-Language')) {
1381
                $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') targeting yii\web\HeaderCollection::get() can also be of type array; however, yii\web\Request::parseAcceptHeader() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
1382
            } else {
1383 1
                $this->_languages = [];
1384
            }
1385
        }
1386
1387 2
        return $this->_languages;
1388
    }
1389
1390
    /**
1391
     * @param array $value the languages that are acceptable by the end user. They should
1392
     * be ordered by the preference level.
1393
     */
1394 1
    public function setAcceptableLanguages($value)
1395
    {
1396 1
        $this->_languages = $value;
1397 1
    }
1398
1399
    /**
1400
     * Parses the given `Accept` (or `Accept-Language`) header.
1401
     *
1402
     * This method will return the acceptable values with their quality scores and the corresponding parameters
1403
     * as specified in the given `Accept` header. The array keys of the return value are the acceptable values,
1404
     * while the array values consisting of the corresponding quality scores and parameters. The acceptable
1405
     * values with the highest quality scores will be returned first. For example,
1406
     *
1407
     * ```php
1408
     * $header = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1409
     * $accepts = $request->parseAcceptHeader($header);
1410
     * print_r($accepts);
1411
     * // displays:
1412
     * // [
1413
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1414
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1415
     * //           'text/plain' => ['q' => 0.5],
1416
     * // ]
1417
     * ```
1418
     *
1419
     * @param string $header the header to be parsed
1420
     * @return array the acceptable values ordered by their quality score. The values with the highest scores
1421
     * will be returned first.
1422
     */
1423 3
    public function parseAcceptHeader($header)
1424
    {
1425 3
        $accepts = [];
1426 3
        foreach (explode(',', $header) as $i => $part) {
1427 3
            $params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY);
1428 3
            if (empty($params)) {
1429 1
                continue;
1430
            }
1431
            $values = [
1432 3
                'q' => [$i, array_shift($params), 1],
1433
            ];
1434 3
            foreach ($params as $param) {
1435 2
                if (strpos($param, '=') !== false) {
1436 2
                    list($key, $value) = explode('=', $param, 2);
1437 2
                    if ($key === 'q') {
1438 2
                        $values['q'][2] = (float) $value;
1439
                    } else {
1440 2
                        $values[$key] = $value;
1441
                    }
1442
                } else {
1443 2
                    $values[] = $param;
1444
                }
1445
            }
1446 3
            $accepts[] = $values;
1447
        }
1448
1449 3
        usort($accepts, function ($a, $b) {
1450 3
            $a = $a['q']; // index, name, q
1451 3
            $b = $b['q'];
1452 3
            if ($a[2] > $b[2]) {
1453 2
                return -1;
1454
            }
1455
1456 2
            if ($a[2] < $b[2]) {
1457 1
                return 1;
1458
            }
1459
1460 2
            if ($a[1] === $b[1]) {
1461
                return $a[0] > $b[0] ? 1 : -1;
1462
            }
1463
1464 2
            if ($a[1] === '*/*') {
1465
                return 1;
1466
            }
1467
1468 2
            if ($b[1] === '*/*') {
1469
                return -1;
1470
            }
1471
1472 2
            $wa = $a[1][strlen($a[1]) - 1] === '*';
1473 2
            $wb = $b[1][strlen($b[1]) - 1] === '*';
1474 2
            if ($wa xor $wb) {
1475
                return $wa ? 1 : -1;
1476
            }
1477
1478 2
            return $a[0] > $b[0] ? 1 : -1;
1479 3
        });
1480
1481 3
        $result = [];
1482 3
        foreach ($accepts as $accept) {
1483 3
            $name = $accept['q'][1];
1484 3
            $accept['q'] = $accept['q'][2];
1485 3
            $result[$name] = $accept;
1486
        }
1487
1488 3
        return $result;
1489
    }
1490
1491
    /**
1492
     * Returns the user-preferred language that should be used by this application.
1493
     * The language resolution is based on the user preferred languages and the languages
1494
     * supported by the application. The method will try to find the best match.
1495
     * @param array $languages a list of the languages supported by the application. If this is empty, the current
1496
     * application language will be returned without further processing.
1497
     * @return string the language that the application should use.
1498
     */
1499 1
    public function getPreferredLanguage(array $languages = [])
1500
    {
1501 1
        if (empty($languages)) {
1502 1
            return Yii::$app->language;
1503
        }
1504 1
        foreach ($this->getAcceptableLanguages() as $acceptableLanguage) {
1505 1
            $acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
1506 1
            foreach ($languages as $language) {
1507 1
                $normalizedLanguage = str_replace('_', '-', strtolower($language));
1508
1509
                if (
1510 1
                    $normalizedLanguage === $acceptableLanguage // en-us==en-us
1511 1
                    || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us
1512 1
                    || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en
1513
                ) {
1514 1
                    return $language;
1515
                }
1516
            }
1517
        }
1518
1519 1
        return reset($languages);
1520
    }
1521
1522
    /**
1523
     * Gets the Etags.
1524
     *
1525
     * @return array The entity tags
1526
     */
1527
    public function getETags()
1528
    {
1529
        if ($this->headers->has('If-None-Match')) {
1530
            return preg_split('/[\s,]+/', str_replace('-gzip', '', $this->headers->get('If-None-Match')), -1, PREG_SPLIT_NO_EMPTY);
1531
        }
1532
1533
        return [];
1534
    }
1535
1536
    /**
1537
     * Returns the cookie collection.
1538
     *
1539
     * Through the returned cookie collection, you may access a cookie using the following syntax:
1540
     *
1541
     * ```php
1542
     * $cookie = $request->cookies['name']
1543
     * if ($cookie !== null) {
1544
     *     $value = $cookie->value;
1545
     * }
1546
     *
1547
     * // alternatively
1548
     * $value = $request->cookies->getValue('name');
1549
     * ```
1550
     *
1551
     * @return CookieCollection the cookie collection.
1552
     */
1553 68
    public function getCookies()
1554
    {
1555 68
        if ($this->_cookies === null) {
1556 68
            $this->_cookies = new CookieCollection($this->loadCookies(), [
1557 67
                'readOnly' => true,
1558
            ]);
1559
        }
1560
1561 67
        return $this->_cookies;
1562
    }
1563
1564
    /**
1565
     * Converts `$_COOKIE` into an array of [[Cookie]].
1566
     * @return array the cookies obtained from request
1567
     * @throws InvalidConfigException if [[cookieValidationKey]] is not set when [[enableCookieValidation]] is true
1568
     */
1569 68
    protected function loadCookies()
1570
    {
1571 68
        $cookies = [];
1572 68
        if ($this->enableCookieValidation) {
1573 67
            if ($this->cookieValidationKey == '') {
1574 1
                throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
1575
            }
1576 66
            foreach ($_COOKIE as $name => $value) {
1577
                if (!is_string($value)) {
1578
                    continue;
1579
                }
1580
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
1581
                if ($data === false) {
1582
                    continue;
1583
                }
1584
                $data = @unserialize($data);
1585
                if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
1586
                    $cookies[$name] = Yii::createObject([
1587 66
                        'class' => 'yii\web\Cookie',
1588
                        'name' => $name,
1589
                        'value' => $data[1],
1590
                        'expire' => null,
1591
                    ]);
1592
                }
1593
            }
1594
        } else {
1595 1
            foreach ($_COOKIE as $name => $value) {
1596 1
                $cookies[$name] = Yii::createObject([
1597 1
                    'class' => 'yii\web\Cookie',
1598 1
                    'name' => $name,
1599 1
                    'value' => $value,
1600
                    'expire' => null,
1601
                ]);
1602
            }
1603
        }
1604
1605 67
        return $cookies;
1606
    }
1607
1608
    private $_csrfToken;
1609
1610
    /**
1611
     * Returns the token used to perform CSRF validation.
1612
     *
1613
     * This token is generated in a way to prevent [BREACH attacks](http://breachattack.com/). It may be passed
1614
     * along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.
1615
     * @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time
1616
     * this method is called, a new CSRF token will be generated and persisted (in session or cookie).
1617
     * @return string the token used to perform CSRF validation.
1618
     */
1619 74
    public function getCsrfToken($regenerate = false)
1620
    {
1621 74
        if ($this->_csrfToken === null || $regenerate) {
1622 74
            $token = $this->loadCsrfToken();
1623 73
            if ($regenerate || empty($token)) {
1624 70
                $token = $this->generateCsrfToken();
1625
            }
1626 73
            $this->_csrfToken = Yii::$app->security->maskToken($token);
1627
        }
1628
1629 73
        return $this->_csrfToken;
1630
    }
1631
1632
    /**
1633
     * Loads the CSRF token from cookie or session.
1634
     * @return string the CSRF token loaded from cookie or session. Null is returned if the cookie or session
1635
     * does not have CSRF token.
1636
     */
1637 74
    protected function loadCsrfToken()
1638
    {
1639 74
        if ($this->enableCsrfCookie) {
1640 70
            return $this->getCookies()->getValue($this->csrfParam);
1641
        }
1642
1643 4
        return Yii::$app->getSession()->get($this->csrfParam);
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
1644
    }
1645
1646
    /**
1647
     * Generates an unmasked random token used to perform CSRF validation.
1648
     * @return string the random token for CSRF validation.
1649
     */
1650 70
    protected function generateCsrfToken()
1651
    {
1652 70
        $token = Yii::$app->getSecurity()->generateRandomString();
1653 70
        if ($this->enableCsrfCookie) {
1654 69
            $cookie = $this->createCsrfCookie($token);
1655 69
            Yii::$app->getResponse()->getCookies()->add($cookie);
1656
        } else {
1657 1
            Yii::$app->getSession()->set($this->csrfParam, $token);
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
1658
        }
1659
1660 70
        return $token;
1661
    }
1662
1663
    /**
1664
     * @return string the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent.
1665
     */
1666 3
    public function getCsrfTokenFromHeader()
1667
    {
1668 3
        return $this->headers->get(static::CSRF_HEADER);
1669
    }
1670
1671
    /**
1672
     * Creates a cookie with a randomly generated CSRF token.
1673
     * Initial values specified in [[csrfCookie]] will be applied to the generated cookie.
1674
     * @param string $token the CSRF token
1675
     * @return Cookie the generated cookie
1676
     * @see enableCsrfValidation
1677
     */
1678 69
    protected function createCsrfCookie($token)
1679
    {
1680 69
        $options = $this->csrfCookie;
1681 69
        return Yii::createObject(array_merge($options, [
1682 69
            'class' => 'yii\web\Cookie',
1683 69
            'name' => $this->csrfParam,
1684 69
            'value' => $token,
1685
        ]));
1686
    }
1687
1688
    /**
1689
     * Performs the CSRF validation.
1690
     *
1691
     * This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session.
1692
     * This method is mainly called in [[Controller::beforeAction()]].
1693
     *
1694
     * Note that the method will NOT perform CSRF validation if [[enableCsrfValidation]] is false or the HTTP method
1695
     * is among GET, HEAD or OPTIONS.
1696
     *
1697
     * @param string $clientSuppliedToken the user-provided CSRF token to be validated. If null, the token will be retrieved from
1698
     * the [[csrfParam]] POST field or HTTP header.
1699
     * This parameter is available since version 2.0.4.
1700
     * @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.
1701
     */
1702 7
    public function validateCsrfToken($clientSuppliedToken = null)
1703
    {
1704 7
        $method = $this->getMethod();
1705
        // only validate CSRF token on non-"safe" methods https://tools.ietf.org/html/rfc2616#section-9.1.1
1706 7
        if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
1707 6
            return true;
1708
        }
1709
1710 4
        $trueToken = $this->getCsrfToken();
1711
1712 4
        if ($clientSuppliedToken !== null) {
1713 2
            return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken);
1714
        }
1715
1716 3
        return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
1717 3
            || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
0 ignored issues
show
Bug introduced by
It seems like $this->getCsrfTokenFromHeader() targeting yii\web\Request::getCsrfTokenFromHeader() can also be of type array; however, yii\web\Request::validateCsrfTokenInternal() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
1718
    }
1719
1720
    /**
1721
     * Validates CSRF token.
1722
     *
1723
     * @param string $clientSuppliedToken The masked client-supplied token.
1724
     * @param string $trueToken The masked true token.
1725
     * @return bool
1726
     */
1727 4
    private function validateCsrfTokenInternal($clientSuppliedToken, $trueToken)
1728
    {
1729 4
        if (!is_string($clientSuppliedToken)) {
1730 3
            return false;
1731
        }
1732
1733 4
        $security = Yii::$app->security;
1734
1735 4
        return $security->compareString($security->unmaskToken($clientSuppliedToken), $security->unmaskToken($trueToken));
1736
    }
1737
}
1738