Completed
Push — 2.1 ( 83fa82...a136f4 )
by
unknown
12:35
created

Request::setBaseUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\StreamInterface;
12
use Psr\Http\Message\UploadedFileInterface;
13
use Psr\Http\Message\UriInterface;
14
use Yii;
15
use yii\base\InvalidConfigException;
16
use yii\di\Instance;
17
use yii\helpers\ArrayHelper;
18
use yii\helpers\Html;
19
use yii\http\Cookie;
20
use yii\http\CookieCollection;
21
use yii\http\FileStream;
22
use yii\http\MemoryStream;
23
use yii\http\MessageTrait;
24
use yii\http\UploadedFile;
25
use yii\http\Uri;
26
use yii\validators\IpValidator;
27
28
/**
29
 * The web Request class represents an HTTP request.
30
 *
31
 * It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.
32
 * Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST
33
 * parameters sent via other HTTP methods like PUT or DELETE.
34
 *
35
 * Request is configured as an application component in [[\yii\web\Application]] by default.
36
 * You can access that instance via `Yii::$app->request`.
37
 *
38
 * For more details and usage information on Request, see the [guide article on requests](guide:runtime-requests).
39
 *
40
 * @property string $absoluteUrl The currently requested absolute URL. This property is read-only.
41
 * @property array $acceptableContentTypes The content types ordered by the quality score. Types with the
42
 * highest scores will be returned first. The array keys are the content types, while the array values are the
43
 * corresponding quality score and other parameters as given in the header.
44
 * @property array $acceptableLanguages The languages ordered by the preference level. The first element
45
 * represents the most preferred language.
46
 * @property string|null $authPassword The password sent via HTTP authentication, null if the password is not
47
 * given. This property is read-only.
48
 * @property string|null $authUser The username sent via HTTP authentication, null if the username is not
49
 * given. This property is read-only.
50
 * @property string $baseUrl The relative URL for the application.
51
 * @property array $bodyParams The request parameters given in the request body.
52
 * @property string $contentType Request content-type. Null is returned if this information is not available.
53
 * This property is read-only.
54
 * @property CookieCollection $cookies The cookie collection. This property is read-only.
55
 * @property string $csrfToken The token used to perform CSRF validation. This property is read-only.
56
 * @property string $csrfTokenFromHeader The CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned
57
 * if no such header is sent. This property is read-only.
58
 * @property array $eTags The entity tags. This property is read-only.
59
 * @property string|null $hostInfo Schema and hostname part (with port number if needed) of the request URL
60
 * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. See
61
 * [[getHostInfo()]] for security related notes on this property.
62
 * @property string|null $hostName Hostname part of the request URL (e.g. `www.yiiframework.com`). This
63
 * property is read-only.
64
 * @property bool $isAjax Whether this is an AJAX (XMLHttpRequest) request. This property is read-only.
65
 * @property bool $isDelete Whether this is a DELETE request. This property is read-only.
66
 * @property bool $isFlash Whether this is an Adobe Flash or Adobe Flex request. This property is read-only.
67
 * @property bool $isGet Whether this is a GET request. This property is read-only.
68
 * @property bool $isHead Whether this is a HEAD request. This property is read-only.
69
 * @property bool $isOptions Whether this is a OPTIONS request. This property is read-only.
70
 * @property bool $isPatch Whether this is a PATCH request. This property is read-only.
71
 * @property bool $isPjax Whether this is a PJAX request. This property is read-only.
72
 * @property bool $isPost Whether this is a POST request. This property is read-only.
73
 * @property bool $isPut Whether this is a PUT request. This property is read-only.
74
 * @property bool $isSecureConnection If the request is sent via secure channel (https). This property is
75
 * read-only.
76
 * @property string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is
77
 * turned into upper case.
78
 * @property UriInterface $uri the URI instance.
79
 * @property mixed $requestTarget the message's request target.
80
 * @property string $pathInfo Part of the request URL that is after the entry script and before the question
81
 * mark. Note, the returned path info is already URL-decoded.
82
 * @property int $port Port number for insecure requests.
83
 * @property array $queryParams The request GET parameter values.
84
 * @property string $queryString Part of the request URL that is after the question mark. This property is
85
 * read-only.
86
 * @property string $rawBody The request body.
87
 * @property string|null $referrer URL referrer, null if not available. This property is read-only.
88
 * @property string|null $origin URL origin, null if not available. This property is read-only.
89
 * @property string $scriptFile The entry script file path.
90
 * @property string $scriptUrl The relative URL of the entry script.
91
 * @property int $securePort Port number for secure requests.
92
 * @property string $serverName Server name, null if not available. This property is read-only.
93
 * @property int|null $serverPort Server port number, null if not available. This property is read-only.
94
 * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded
95
 * depending on the client.
96
 * @property array $uploadedFiles Uploaded files for this request. See [[getUploadedFiles()]] for details.
97
 * @property string|null $userAgent User agent, null if not available. This property is read-only.
98
 * @property string|null $userHost User host name, null if not available. This property is read-only.
99
 * @property string|null $userIP User IP address, null if not available. This property is read-only.
100
 *
101
 * @author Qiang Xue <[email protected]>
102
 * @since 2.0
103
 * @SuppressWarnings(PHPMD.SuperGlobals)
104
 */
105
class Request extends \yii\base\Request implements RequestInterface
106
{
107
    use MessageTrait;
108
109
    /**
110
     * The name of the HTTP header for sending CSRF token.
111
     */
112
    const CSRF_HEADER = 'X-CSRF-Token';
113
    /**
114
     * The length of the CSRF token mask.
115
     * @deprecated 2.0.12 The mask length is now equal to the token length.
116
     */
117
    const CSRF_MASK_LENGTH = 8;
118
119
    /**
120
     * @var bool whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true.
121
     * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated
122
     * from the same application. If not, a 400 HTTP exception will be raised.
123
     *
124
     * Note, this feature requires that the user client accepts cookie. Also, to use this feature,
125
     * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfParam]].
126
     * You may use [[\yii\helpers\Html::beginForm()]] to generate his hidden input.
127
     *
128
     * In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and
129
     * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered.
130
     * You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]].
131
     *
132
     * @see Controller::enableCsrfValidation
133
     * @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
134
     */
135
    public $enableCsrfValidation = true;
136
    /**
137
     * @var string the name of the token used to prevent CSRF. Defaults to '_csrf'.
138
     * This property is used only when [[enableCsrfValidation]] is true.
139
     */
140
    public $csrfParam = '_csrf';
141
    /**
142
     * @var array the configuration for creating the CSRF [[Cookie|cookie]]. This property is used only when
143
     * both [[enableCsrfValidation]] and [[enableCsrfCookie]] are true.
144
     */
145
    public $csrfCookie = ['httpOnly' => true];
146
    /**
147
     * @var bool whether to use cookie to persist CSRF token. If false, CSRF token will be stored
148
     * in session under the name of [[csrfParam]]. Note that while storing CSRF tokens in session increases
149
     * security, it requires starting a session for every page, which will degrade your site performance.
150
     */
151
    public $enableCsrfCookie = true;
152
    /**
153
     * @var bool whether cookies should be validated to ensure they are not tampered. Defaults to true.
154
     */
155
    public $enableCookieValidation = true;
156
    /**
157
     * @var string a secret key used for cookie validation. This property must be set if [[enableCookieValidation]] is true.
158
     */
159
    public $cookieValidationKey;
160
    /**
161
     * @var string the name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE
162
     * request tunneled through POST. Defaults to '_method'.
163
     * @see getMethod()
164
     * @see getBodyParams()
165
     */
166
    public $methodParam = '_method';
167
    /**
168
     * @var array the parsers for converting the raw HTTP request body into [[bodyParams]].
169
     * The array keys are the request `Content-Types`, and the array values are the
170
     * corresponding configurations for [[Yii::createObject|creating the parser objects]].
171
     * A parser must implement the [[RequestParserInterface]].
172
     *
173
     * To enable parsing for JSON requests you can use the [[JsonParser]] class like in the following example:
174
     *
175
     * ```
176
     * [
177
     *     'application/json' => \yii\web\JsonParser::class,
178
     * ]
179
     * ```
180
     *
181
     * To register a parser for parsing all request types you can use `'*'` as the array key.
182
     * This one will be used as a fallback in case no other types match.
183
     *
184
     * @see getBodyParams()
185
     */
186
    public $parsers = [];
187
    /**
188
     * @var string name of the class to be used for uploaded file instantiation.
189
     * This class should implement [[UploadedFileInterface]].
190
     * @since 2.1.0
191
     */
192
    public $uploadedFileClass = UploadedFile::class;
193
    /**
194
     * @var array the configuration for trusted security related headers.
195
     *
196
     * An array key is an IPv4 or IPv6 IP address in CIDR notation for matching a client.
197
     *
198
     * An array value is a list of headers to trust. These will be matched against
199
     * [[secureHeaders]] to determine which headers are allowed to be sent by a specified host.
200
     * The case of the header names must be the same as specified in [[secureHeaders]].
201
     *
202
     * For example, to trust all headers listed in [[secureHeaders]] for IP addresses
203
     * in range `192.168.0.0-192.168.0.254` write the following:
204
     *
205
     * ```php
206
     * [
207
     *     '192.168.0.0/24',
208
     * ]
209
     * ```
210
     *
211
     * To trust just the `X-Forwarded-For` header from `10.0.0.1`, use:
212
     *
213
     * ```
214
     * [
215
     *     '10.0.0.1' => ['X-Forwarded-For']
216
     * ]
217
     * ```
218
     *
219
     * Default is to trust all headers except those listed in [[secureHeaders]] from all hosts.
220
     * Matches are tried in order and searching is stopped when IP matches.
221
     *
222
     * > Info: Matching is performed using [[IpValidator]].
223
     *   See [[IpValidator::::setRanges()|IpValidator::setRanges()]]
224
     *   and [[IpValidator::networks]] for advanced matching.
225
     *
226
     * @see $secureHeaders
227
     * @since 2.0.13
228
     */
229
    public $trustedHosts = [];
230
    /**
231
     * @var array lists of headers that are, by default, subject to the trusted host configuration.
232
     * These headers will be filtered unless explicitly allowed in [[trustedHosts]].
233
     * The match of header names is case-insensitive.
234
     * @see https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
235
     * @see $trustedHosts
236
     * @since 2.0.13
237
     */
238
    public $secureHeaders = [
239
        'X-Forwarded-For',
240
        'X-Forwarded-Host',
241
        'X-Forwarded-Proto',
242
        'Front-End-Https',
243
        'X-Rewrite-Url',
244
    ];
245
    /**
246
     * @var string[] List of headers where proxies store the real client IP.
247
     * It's not advisable to put insecure headers here.
248
     * The match of header names is case-insensitive.
249
     * @see $trustedHosts
250
     * @see $secureHeaders
251
     * @since 2.0.13
252
     */
253
    public $ipHeaders = [
254
        'X-Forwarded-For',
255
    ];
256
    /**
257
     * @var array list of headers to check for determining whether the connection is made via HTTPS.
258
     * The array keys are header names and the array value is a list of header values that indicate a secure connection.
259
     * The match of header names and values is case-insensitive.
260
     * It's not advisable to put insecure headers here.
261
     * @see $trustedHosts
262
     * @see $secureHeaders
263
     * @since 2.0.13
264
     */
265
    public $secureProtocolHeaders = [
266
        'X-Forwarded-Proto' => ['https'],
267
        'Front-End-Https' => ['on'],
268
    ];
269
270
    /**
271
     * @var CookieCollection Collection of request cookies.
272
     */
273
    private $_cookies;
274
    /**
275
     * @var string the HTTP method of the request.
276
     */
277
    private $_method;
278
    /**
279
     * @var UriInterface the URI instance associated with request.
280
     */
281
    private $_uri;
282
    /**
283
     * @var mixed the message's request target.
284
     */
285
    private $_requestTarget;
286
    /**
287
     * @var array uploaded files.
288
     * @since 2.1.0
289
     */
290
    private $_uploadedFiles;
291
292
293
    /**
294
     * Resolves the current request into a route and the associated parameters.
295
     * @return array the first element is the route, and the second is the associated parameters.
296
     * @throws NotFoundHttpException if the request cannot be resolved.
297
     */
298 1
    public function resolve()
299
    {
300 1
        $result = Yii::$app->getUrlManager()->parseRequest($this);
301 1
        if ($result !== false) {
302 1
            [$route, $params] = $result;
0 ignored issues
show
Bug introduced by
The variable $route does not exist. Did you forget to declare it?

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

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

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

Loading history...
303 1
            if ($this->_queryParams === null) {
304 1
                $_GET = $params + $_GET; // preserve numeric keys
305
            } else {
306 1
                $this->_queryParams = $params + $this->_queryParams;
307
            }
308
309 1
            return [$route, $this->getQueryParams()];
310
        }
311
312
        throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
313
    }
314
315
    /**
316
     * Filters headers according to the [[trustedHosts]].
317
     * @param array $rawHeaders
318
     * @return array filtered headers
319
     * @since 2.0.13
320
     */
321 113
    protected function filterHeaders($rawHeaders)
322
    {
323
        // do not trust any of the [[secureHeaders]] by default
324 113
        $trustedHeaders = [];
325
326
        // check if the client is a trusted host
327 113
        if (!empty($this->trustedHosts)) {
328 19
            $validator = $this->getIpValidator();
329 19
            $ip = $this->getRemoteIP();
330 19
            foreach ($this->trustedHosts as $cidr => $headers) {
331 19
                if (!is_array($headers)) {
332 19
                    $cidr = $headers;
333 19
                    $headers = $this->secureHeaders;
334
                }
335 19
                $validator->setRanges($cidr);
336 19
                if ($validator->validate($ip)) {
337 3
                    $trustedHeaders = $headers;
338 19
                    break;
339
                }
340
            }
341
        }
342
343 113
        $rawHeaders = array_change_key_case($rawHeaders, CASE_LOWER);
344
345
        // filter all secure headers unless they are trusted
346 113
        foreach ($this->secureHeaders as $secureHeader) {
347 113
            if (!in_array($secureHeader, $trustedHeaders)) {
348 113
                unset($rawHeaders[strtolower($secureHeader)]);
349
            }
350
        }
351
352 113
        return $rawHeaders;
353
    }
354
355
    /**
356
     * Creates instance of [[IpValidator]].
357
     * You can override this method to adjust validator or implement different matching strategy.
358
     *
359
     * @return IpValidator
360
     * @since 2.0.13
361
     */
362 19
    protected function getIpValidator()
363
    {
364 19
        return new IpValidator();
365
    }
366
367
    /**
368
     * Returns default message's headers, which should be present once [[headerCollection]] is instantiated.
369
     * @return string[][] an associative array of the message's headers.
370
     */
371 113
    protected function defaultHeaders()
372
    {
373 113
        if (function_exists('getallheaders')) {
374
            $headers = getallheaders();
375 113
        } elseif (function_exists('http_get_request_headers')) {
376
            $headers = http_get_request_headers();
377
        } else {
378 113
            $headers = [];
379 113
            foreach ($_SERVER as $name => $value) {
380 110
                if (strncmp($name, 'HTTP_', 5) === 0) {
381 30
                    $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
382 110
                    $headers[$name] = $value;
383
                }
384
            }
385
        }
386
387 113
        return $this->filterHeaders($headers);
388
    }
389
390
    /**
391
     * {@inheritdoc}
392
     * @since 2.1.0
393
     */
394
    public function getRequestTarget()
395
    {
396
        if ($this->_requestTarget === null) {
397
            $this->_requestTarget = $this->getUri()->__toString();
398
        }
399
        return $this->_requestTarget;
400
    }
401
402
    /**
403
     * Specifies the message's request target
404
     * @param mixed $requestTarget the message's request target.
405
     * @since 2.1.0
406
     */
407
    public function setRequestTarget($requestTarget)
408
    {
409
        $this->_requestTarget = $requestTarget;
410
    }
411
412
    /**
413
     * {@inheritdoc}
414
     * @since 2.1.0
415
     */
416
    public function withRequestTarget($requestTarget)
417
    {
418
        if ($this->getRequestTarget() === $requestTarget) {
419
            return $this;
420
        }
421
422
        $newInstance = clone $this;
423
        $newInstance->setRequestTarget($requestTarget);
424
        return $newInstance;
425
    }
426
427
    /**
428
     * {@inheritdoc}
429
     */
430 28
    public function getMethod()
431
    {
432 28
        if ($this->_method === null) {
433 19
            if (isset($_POST[$this->methodParam])) {
434 1
                $this->_method = $_POST[$this->methodParam];
435 18
            } elseif ($this->hasHeader('x-http-method-override')) {
436 1
                $this->_method = $this->getHeaderLine('x-http-method-override');
437 17
            } elseif (isset($_SERVER['REQUEST_METHOD'])) {
438 2
                $this->_method = $_SERVER['REQUEST_METHOD'];
439
            } else {
440 16
                $this->_method = 'GET';
441
            }
442
        }
443 28
        return $this->_method;
444
    }
445
446
    /**
447
     * Specifies request HTTP method.
448
     * @param string $method case-sensitive HTTP method.
449
     * @since 2.1.0
450
     */
451 11
    public function setMethod($method)
452
    {
453 11
        $this->_method =  $method;
454 11
    }
455
456
    /**
457
     * {@inheritdoc}
458
     * @since 2.1.0
459
     */
460 1
    public function withMethod($method)
461
    {
462 1
        if ($this->getMethod() === $method) {
463
            return $this;
464
        }
465
466 1
        $newInstance = clone $this;
467 1
        $newInstance->setMethod($method);
468 1
        return $newInstance;
469
    }
470
471
    /**
472
     * {@inheritdoc}
473
     * @since 2.1.0
474
     */
475
    public function getUri()
476
    {
477
        if (!$this->_uri instanceof UriInterface) {
478
            if ($this->_uri === null) {
479
                $uri = new Uri(['string' => $this->getAbsoluteUrl()]);
480
            } elseif ($this->_uri instanceof \Closure) {
481
                $uri = call_user_func($this->_uri, $this);
482
            } else {
483
                $uri = $this->_uri;
484
            }
485
486
            $this->_uri = Instance::ensure($uri, UriInterface::class);
487
        }
488
        return $this->_uri;
489
    }
490
491
    /**
492
     * Specifies the URI instance.
493
     * @param UriInterface|\Closure|array $uri URI instance or its DI compatible configuration.
494
     * @since 2.1.0
495
     */
496
    public function setUri($uri)
497
    {
498
        $this->_uri = $uri;
0 ignored issues
show
Documentation Bug introduced by
It seems like $uri can also be of type object<Closure> or array. However, the property $_uri is declared as type object<Psr\Http\Message\UriInterface>. Maybe add an additional type check?

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

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

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

class Id
{
    public $id;

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

}

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

$account_id = false;

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

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
499
    }
500
501
    /**
502
     * {@inheritdoc}
503
     * @since 2.1.0
504
     */
505
    public function withUri(UriInterface $uri, $preserveHost = false)
506
    {
507
        if ($this->getUri() === $uri) {
508
            return $this;
509
        }
510
511
        $newInstance = clone $this;
512
513
        $newInstance->setUri($uri);
514
        if (!$preserveHost) {
515
            return $newInstance->withHeader('host', $uri->getHost());
516
        }
517
        return $newInstance;
518
    }
519
520
    /**
521
     * Returns whether this is a GET request.
522
     * @return bool whether this is a GET request.
523
     */
524 2
    public function getIsGet()
525
    {
526 2
        return $this->getMethod() === 'GET';
527
    }
528
529
    /**
530
     * Returns whether this is an OPTIONS request.
531
     * @return bool whether this is a OPTIONS request.
532
     */
533
    public function getIsOptions()
534
    {
535
        return $this->getMethod() === 'OPTIONS';
536
    }
537
538
    /**
539
     * Returns whether this is a HEAD request.
540
     * @return bool whether this is a HEAD request.
541
     */
542 9
    public function getIsHead()
543
    {
544 9
        return $this->getMethod() === 'HEAD';
545
    }
546
547
    /**
548
     * Returns whether this is a POST request.
549
     * @return bool whether this is a POST request.
550
     */
551
    public function getIsPost()
552
    {
553
        return $this->getMethod() === 'POST';
554
    }
555
556
    /**
557
     * Returns whether this is a DELETE request.
558
     * @return bool whether this is a DELETE request.
559
     */
560
    public function getIsDelete()
561
    {
562
        return $this->getMethod() === 'DELETE';
563
    }
564
565
    /**
566
     * Returns whether this is a PUT request.
567
     * @return bool whether this is a PUT request.
568
     */
569
    public function getIsPut()
570
    {
571
        return $this->getMethod() === 'PUT';
572
    }
573
574
    /**
575
     * Returns whether this is a PATCH request.
576
     * @return bool whether this is a PATCH request.
577
     */
578
    public function getIsPatch()
579
    {
580
        return $this->getMethod() === 'PATCH';
581
    }
582
583
    /**
584
     * Returns whether this is an AJAX (XMLHttpRequest) request.
585
     *
586
     * Note that jQuery doesn't set the header in case of cross domain
587
     * requests: https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header
588
     *
589
     * @return bool whether this is an AJAX (XMLHttpRequest) request.
590
     */
591 14
    public function getIsAjax()
592
    {
593 14
        return $this->getHeaderLine('x-requested-with') === 'XMLHttpRequest';
594
    }
595
596
    /**
597
     * Returns whether this is a PJAX request
598
     * @return bool whether this is a PJAX request
599
     */
600 3
    public function getIsPjax()
601
    {
602 3
        return $this->getIsAjax() && $this->hasHeader('x-pjax');
603
    }
604
605
    /**
606
     * Returns whether this is an Adobe Flash or Flex request.
607
     * @return bool whether this is an Adobe Flash or Adobe Flex request.
608
     */
609
    public function getIsFlash()
610
    {
611
        $userAgent = $this->getUserAgent();
612
        if ($userAgent === null) {
613
            return false;
614
        }
615
        return (stripos($userAgent, 'Shockwave') !== false || stripos($userAgent, 'Flash') !== false);
616
    }
617
618
    /**
619
     * Returns default message body to be used in case it is not explicitly set.
620
     * @return StreamInterface default body instance.
621
     */
622
    protected function defaultBody()
623
    {
624
        return new FileStream([
625
            'filename' => 'php://input',
626
            'mode' => 'r',
627
        ]);
628
    }
629
630
    /**
631
     * Returns the raw HTTP request body.
632
     * @return string the request body
633
     */
634
    public function getRawBody()
635
    {
636
        return $this->getBody()->__toString();
637
    }
638
639
    /**
640
     * Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
641
     * @param string $rawBody the request body
642
     */
643 6
    public function setRawBody($rawBody)
644
    {
645 6
        $body = new MemoryStream();
646 6
        $body->write($rawBody);
647 6
        $this->setBody($body);
648 6
    }
649
650
    private $_bodyParams;
651
652
    /**
653
     * Returns the request parameters given in the request body.
654
     *
655
     * Request parameters are determined using the parsers configured in [[parsers]] property.
656
     * If no parsers are configured for the current [[contentType]] it uses the PHP function `mb_parse_str()`
657
     * to parse the [[rawBody|request body]].
658
     * @return array the request parameters given in the request body.
659
     * @throws InvalidConfigException if a registered parser does not implement the [[RequestParserInterface]].
660
     * @throws UnsupportedMediaTypeHttpException if unable to parse raw body.
661
     * @see getMethod()
662
     * @see getBodyParam()
663
     * @see setBodyParams()
664
     */
665 11
    public function getBodyParams()
666
    {
667 11
        if ($this->_bodyParams === null) {
668 8
            if (isset($_POST[$this->methodParam])) {
669
                $this->_bodyParams = $_POST;
670
                unset($this->_bodyParams[$this->methodParam]);
671
                return $this->_bodyParams;
672
            }
673
674 8
            $contentType = $this->getContentType();
675 8
            if (($pos = strpos($contentType, ';')) !== false) {
676
                // e.g. text/html; charset=UTF-8
677 2
                $contentType = trim(substr($contentType, 0, $pos));
678
            }
679
680 8
            if (isset($this->parsers[$contentType])) {
681 2
                $parser = Yii::createObject($this->parsers[$contentType]);
682 2
                if (!($parser instanceof RequestParserInterface)) {
683
                    throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
684
                }
685 2
                $this->_bodyParams = $parser->parse($this);
686 6
            } elseif (isset($this->parsers['*'])) {
687
                $parser = Yii::createObject($this->parsers['*']);
688
                if (!($parser instanceof RequestParserInterface)) {
689
                    throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.');
690
                }
691
                $this->_bodyParams = $parser->parse($this);
692 6
            } elseif ($this->getMethod() === 'POST') {
693 6
                if ($contentType !== 'application/x-www-form-urlencoded' && $contentType !== 'multipart/form-data') {
694 1
                    throw new UnsupportedMediaTypeHttpException();
695
                }
696
                // PHP has already parsed the body so we have all params in $_POST
697 6
                $this->_bodyParams = $_POST;
698
            } else {
699 1
                if ($contentType !== 'application/x-www-form-urlencoded') {
700 1
                    throw new UnsupportedMediaTypeHttpException();
701
                }
702 1
                $this->_bodyParams = [];
703 1
                mb_parse_str($this->getBody()->__toString(), $this->_bodyParams);
704
            }
705
        }
706
707 11
        return $this->_bodyParams;
708
    }
709
710
    /**
711
     * Sets the request body parameters.
712
     * @param array $values the request body parameters (name-value pairs)
713
     * @see getBodyParam()
714
     * @see getBodyParams()
715
     */
716 3
    public function setBodyParams($values)
717
    {
718 3
        $this->_bodyParams = $values;
719 3
    }
720
721
    /**
722
     * Returns the named request body parameter value.
723
     * If the parameter does not exist, the second parameter passed to this method will be returned.
724
     * @param string $name the parameter name
725
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
726
     * @return mixed the parameter value
727
     * @see getBodyParams()
728
     * @see setBodyParams()
729
     */
730 4
    public function getBodyParam($name, $defaultValue = null)
731
    {
732 4
        $params = $this->getBodyParams();
733
734 4
        return isset($params[$name]) ? $params[$name] : $defaultValue;
735
    }
736
737
    /**
738
     * Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters.
739
     *
740
     * @param string $name the parameter name
741
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
742
     * @return array|mixed
743
     */
744
    public function post($name = null, $defaultValue = null)
745
    {
746
        if ($name === null) {
747
            return $this->getBodyParams();
748
        }
749
750
        return $this->getBodyParam($name, $defaultValue);
751
    }
752
753
    private $_queryParams;
754
755
    /**
756
     * Returns the request parameters given in the [[queryString]].
757
     *
758
     * This method will return the contents of `$_GET` if params where not explicitly set.
759
     * @return array the request GET parameter values.
760
     * @see setQueryParams()
761
     */
762 29
    public function getQueryParams()
763
    {
764 29
        if ($this->_queryParams === null) {
765 23
            return $_GET;
766
        }
767
768 8
        return $this->_queryParams;
769
    }
770
771
    /**
772
     * Sets the request [[queryString]] parameters.
773
     * @param array $values the request query parameters (name-value pairs)
774
     * @see getQueryParam()
775
     * @see getQueryParams()
776
     */
777 8
    public function setQueryParams($values)
778
    {
779 8
        $this->_queryParams = $values;
780 8
    }
781
782
    /**
783
     * Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.
784
     *
785
     * @param string $name the parameter name
786
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
787
     * @return array|mixed
788
     */
789 15
    public function get($name = null, $defaultValue = null)
790
    {
791 15
        if ($name === null) {
792
            return $this->getQueryParams();
793
        }
794
795 15
        return $this->getQueryParam($name, $defaultValue);
796
    }
797
798
    /**
799
     * Returns the named GET parameter value.
800
     * If the GET parameter does not exist, the second parameter passed to this method will be returned.
801
     * @param string $name the GET parameter name.
802
     * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
803
     * @return mixed the GET parameter value
804
     * @see getBodyParam()
805
     */
806 20
    public function getQueryParam($name, $defaultValue = null)
807
    {
808 20
        $params = $this->getQueryParams();
809
810 20
        return isset($params[$name]) ? $params[$name] : $defaultValue;
811
    }
812
813
    private $_hostInfo;
814
    private $_hostName;
815
816
    /**
817
     * Returns the schema and host part of the current request URL.
818
     *
819
     * The returned URL does not have an ending slash.
820
     *
821
     * By default this value is based on the user request information. This method will
822
     * return the value of `$_SERVER['HTTP_HOST']` if it is available or `$_SERVER['SERVER_NAME']` if not.
823
     * You may want to check out the [PHP documentation](http://php.net/manual/en/reserved.variables.server.php)
824
     * for more information on these variables.
825
     *
826
     * You may explicitly specify it by setting the [[setHostInfo()|hostInfo]] property.
827
     *
828
     * > Warning: Dependent on the server configuration this information may not be
829
     * > reliable and [may be faked by the user sending the HTTP request](https://www.acunetix.com/vulnerabilities/web/host-header-attack).
830
     * > If the webserver is configured to serve the same site independent of the value of
831
     * > the `Host` header, this value is not reliable. In such situations you should either
832
     * > fix your webserver configuration or explicitly set the value by setting the [[setHostInfo()|hostInfo]] property.
833
     * > If you don't have access to the server configuration, you can setup [[\yii\filters\HostControl]] filter at
834
     * > application level in order to protect against such kind of attack.
835
     *
836
     * @property string|null schema and hostname part (with port number if needed) of the request URL
837
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
838
     * See [[getHostInfo()]] for security related notes on this property.
839
     * @return string|null schema and hostname part (with port number if needed) of the request URL
840
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
841
     * @see setHostInfo()
842
     */
843 24
    public function getHostInfo()
844
    {
845 24
        if ($this->_hostInfo === null) {
846 20
            $secure = $this->getIsSecureConnection();
847 20
            $http = $secure ? 'https' : 'http';
848 20
            if ($this->hasHeader('Host')) {
849 7
                $this->_hostInfo = $http . '://' . $this->getHeaderLine('Host');
850 13
            } elseif (isset($_SERVER['SERVER_NAME'])) {
851
                $this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME'];
852
                $port = $secure ? $this->getSecurePort() : $this->getPort();
853
                if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
854
                    $this->_hostInfo .= ':' . $port;
855
                }
856
            }
857
        }
858
859 24
        return $this->_hostInfo;
860
    }
861
862
    /**
863
     * Sets the schema and host part of the application URL.
864
     * This setter is provided in case the schema and hostname cannot be determined
865
     * on certain Web servers.
866
     * @param string|null $value the schema and host part of the application URL. The trailing slashes will be removed.
867
     * @see getHostInfo() for security related notes on this property.
868
     */
869 57
    public function setHostInfo($value)
870
    {
871 57
        $this->_hostName = null;
872 57
        $this->_hostInfo = $value === null ? null : rtrim($value, '/');
873 57
    }
874
875
    /**
876
     * Returns the host part of the current request URL.
877
     * Value is calculated from current [[getHostInfo()|hostInfo]] property.
878
     *
879
     * > Warning: The content of this value may not be reliable, dependent on the server
880
     * > configuration. Please refer to [[getHostInfo()]] for more information.
881
     *
882
     * @return string|null hostname part of the request URL (e.g. `www.yiiframework.com`)
883
     * @see getHostInfo()
884
     * @since 2.0.10
885
     */
886 11
    public function getHostName()
887
    {
888 11
        if ($this->_hostName === null) {
889 11
            $this->_hostName = parse_url($this->getHostInfo(), PHP_URL_HOST);
890
        }
891
892 11
        return $this->_hostName;
893
    }
894
895
    private $_baseUrl;
896
897
    /**
898
     * Returns the relative URL for the application.
899
     * This is similar to [[scriptUrl]] except that it does not include the script file name,
900
     * and the ending slashes are removed.
901
     * @return string the relative URL for the application
902
     * @see setScriptUrl()
903
     */
904 257
    public function getBaseUrl()
905
    {
906 257
        if ($this->_baseUrl === null) {
907 256
            $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/');
908
        }
909
910 257
        return $this->_baseUrl;
911
    }
912
913
    /**
914
     * Sets the relative URL for the application.
915
     * By default the URL is determined based on the entry script URL.
916
     * This setter is provided in case you want to change this behavior.
917
     * @param string $value the relative URL for the application
918
     */
919 1
    public function setBaseUrl($value)
920
    {
921 1
        $this->_baseUrl = $value;
922 1
    }
923
924
    private $_scriptUrl;
925
926
    /**
927
     * Returns the relative URL of the entry script.
928
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
929
     * @return string the relative URL of the entry script.
930
     * @throws InvalidConfigException if unable to determine the entry script URL
931
     */
932 258
    public function getScriptUrl()
933
    {
934 258
        if ($this->_scriptUrl === null) {
935 2
            $scriptFile = $this->getScriptFile();
936 1
            $scriptName = basename($scriptFile);
937 1
            if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
938 1
                $this->_scriptUrl = $_SERVER['SCRIPT_NAME'];
939
            } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $scriptName) {
940
                $this->_scriptUrl = $_SERVER['PHP_SELF'];
941
            } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
942
                $this->_scriptUrl = $_SERVER['ORIG_SCRIPT_NAME'];
943
            } elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
944
                $this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
945
            } elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) {
946
                $this->_scriptUrl = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $scriptFile));
947
            } else {
948
                throw new InvalidConfigException('Unable to determine the entry script URL.');
949
            }
950
        }
951
952 257
        return $this->_scriptUrl;
953
    }
954
955
    /**
956
     * Sets the relative URL for the application entry script.
957
     * This setter is provided in case the entry script URL cannot be determined
958
     * on certain Web servers.
959
     * @param string $value the relative URL for the application entry script.
960
     */
961 268
    public function setScriptUrl($value)
962
    {
963 268
        $this->_scriptUrl = $value === null ? null : '/' . trim($value, '/');
964 268
    }
965
966
    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...
967
968
    /**
969
     * Returns the entry script file path.
970
     * The default implementation will simply return `$_SERVER['SCRIPT_FILENAME']`.
971
     * @return string the entry script file path
972
     * @throws InvalidConfigException
973
     */
974 259
    public function getScriptFile()
975
    {
976 259
        if (isset($this->_scriptFile)) {
977 237
            return $this->_scriptFile;
978
        }
979
980 23
        if (isset($_SERVER['SCRIPT_FILENAME'])) {
981 21
            return $_SERVER['SCRIPT_FILENAME'];
982
        }
983
984 2
        throw new InvalidConfigException('Unable to determine the entry script file path.');
985
    }
986
987
    /**
988
     * Sets the entry script file path.
989
     * The entry script file path normally can be obtained from `$_SERVER['SCRIPT_FILENAME']`.
990
     * If your server configuration does not return the correct value, you may configure
991
     * this property to make it right.
992
     * @param string $value the entry script file path.
993
     */
994 237
    public function setScriptFile($value)
995
    {
996 237
        $this->_scriptFile = $value;
997 237
    }
998
999
    private $_pathInfo;
1000
1001
    /**
1002
     * Returns the path info of the currently requested URL.
1003
     * A path info refers to the part that is after the entry script and before the question mark (query string).
1004
     * The starting and ending slashes are both removed.
1005
     * @return string part of the request URL that is after the entry script and before the question mark.
1006
     * Note, the returned path info is already URL-decoded.
1007
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
1008
     */
1009 18
    public function getPathInfo()
1010
    {
1011 18
        if ($this->_pathInfo === null) {
1012
            $this->_pathInfo = $this->resolvePathInfo();
1013
        }
1014
1015 18
        return $this->_pathInfo;
1016
    }
1017
1018
    /**
1019
     * Sets the path info of the current request.
1020
     * This method is mainly provided for testing purpose.
1021
     * @param string $value the path info of the current request
1022
     */
1023 19
    public function setPathInfo($value)
1024
    {
1025 19
        $this->_pathInfo = $value === null ? null : ltrim($value, '/');
1026 19
    }
1027
1028
    /**
1029
     * Resolves the path info part of the currently requested URL.
1030
     * A path info refers to the part that is after the entry script and before the question mark (query string).
1031
     * The starting slashes are both removed (ending slashes will be kept).
1032
     * @return string part of the request URL that is after the entry script and before the question mark.
1033
     * Note, the returned path info is decoded.
1034
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
1035
     */
1036
    protected function resolvePathInfo()
1037
    {
1038
        $pathInfo = $this->getUrl();
1039
1040
        if (($pos = strpos($pathInfo, '?')) !== false) {
1041
            $pathInfo = substr($pathInfo, 0, $pos);
1042
        }
1043
1044
        $pathInfo = urldecode($pathInfo);
1045
1046
        // try to encode in UTF8 if not so
1047
        // http://w3.org/International/questions/qa-forms-utf-8.html
1048
        if (!preg_match('%^(?:
1049
            [\x09\x0A\x0D\x20-\x7E]              # ASCII
1050
            | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
1051
            | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
1052
            | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
1053
            | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
1054
            | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
1055
            | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
1056
            | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
1057
            )*$%xs', $pathInfo)
1058
        ) {
1059
            $pathInfo = utf8_encode($pathInfo);
1060
        }
1061
1062
        $scriptUrl = $this->getScriptUrl();
1063
        $baseUrl = $this->getBaseUrl();
1064
        if (strpos($pathInfo, $scriptUrl) === 0) {
1065
            $pathInfo = substr($pathInfo, strlen($scriptUrl));
1066
        } elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) {
1067
            $pathInfo = substr($pathInfo, strlen($baseUrl));
1068
        } elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0) {
1069
            $pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
1070
        } else {
1071
            throw new InvalidConfigException('Unable to determine the path info of the current request.');
1072
        }
1073
1074
        if (substr($pathInfo, 0, 1) === '/') {
1075
            $pathInfo = substr($pathInfo, 1);
1076
        }
1077
1078
        return (string) $pathInfo;
1079
    }
1080
1081
    /**
1082
     * Returns the currently requested absolute URL.
1083
     * This is a shortcut to the concatenation of [[hostInfo]] and [[url]].
1084
     * @return string the currently requested absolute URL.
1085
     */
1086
    public function getAbsoluteUrl()
1087
    {
1088
        return $this->getHostInfo() . $this->getUrl();
1089
    }
1090
1091
    private $_url;
1092
1093
    /**
1094
     * Returns the currently requested relative URL.
1095
     * This refers to the portion of the URL that is after the [[hostInfo]] part.
1096
     * It includes the [[queryString]] part if any.
1097
     * @return string the currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.
1098
     * @throws InvalidConfigException if the URL cannot be determined due to unusual server configuration
1099
     */
1100 11
    public function getUrl()
1101
    {
1102 11
        if ($this->_url === null) {
1103 3
            $this->_url = $this->resolveRequestUri();
1104
        }
1105
1106 11
        return $this->_url;
1107
    }
1108
1109
    /**
1110
     * Sets the currently requested relative URL.
1111
     * The URI must refer to the portion that is after [[hostInfo]].
1112
     * Note that the URI should be URL-encoded.
1113
     * @param string $value the request URI to be set
1114
     */
1115 24
    public function setUrl($value)
1116
    {
1117 24
        $this->_url = $value;
1118 24
    }
1119
1120
    /**
1121
     * Resolves the request URI portion for the currently requested URL.
1122
     * This refers to the portion that is after the [[hostInfo]] part. It includes the [[queryString]] part if any.
1123
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
1124
     * @return string|bool the request URI portion for the currently requested URL.
1125
     * Note that the URI returned may be URL-encoded depending on the client.
1126
     * @throws InvalidConfigException if the request URI cannot be determined due to unusual server configuration
1127
     */
1128 3
    protected function resolveRequestUri()
1129
    {
1130 3
        if ($this->hasHeader('x-rewrite-url')) { // IIS
1131
            $requestUri = $this->getHeaderLine('x-rewrite-url');
1132 3
        } elseif (isset($_SERVER['REQUEST_URI'])) {
1133 3
            $requestUri = $_SERVER['REQUEST_URI'];
1134 3
            if ($requestUri !== '' && $requestUri[0] !== '/') {
1135 3
                $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
1136
            }
1137
        } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 CGI
1138
            $requestUri = $_SERVER['ORIG_PATH_INFO'];
1139
            if (!empty($_SERVER['QUERY_STRING'])) {
1140
                $requestUri .= '?' . $_SERVER['QUERY_STRING'];
1141
            }
1142
        } else {
1143
            throw new InvalidConfigException('Unable to determine the request URI.');
1144
        }
1145
1146 3
        return $requestUri;
1147
    }
1148
1149
    /**
1150
     * Returns part of the request URL that is after the question mark.
1151
     * @return string part of the request URL that is after the question mark
1152
     */
1153
    public function getQueryString()
1154
    {
1155
        return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
1156
    }
1157
1158
    /**
1159
     * Return if the request is sent via secure channel (https).
1160
     * @return bool if the request is sent via secure channel (https)
1161
     */
1162 37
    public function getIsSecureConnection()
1163
    {
1164 37
        if (isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)) {
1165 2
            return true;
1166
        }
1167 35
        foreach ($this->secureProtocolHeaders as $header => $values) {
1168 35
            if ($this->hasHeader($header)) {
1169 2
                foreach ($values as $value) {
1170 2
                    if (strcasecmp($this->getHeaderLine($header), $value) === 0) {
1171 35
                        return true;
1172
                    }
1173
                }
1174
            }
1175
        }
1176
1177 33
        return false;
1178
    }
1179
1180
    /**
1181
     * Returns the server name.
1182
     * @return string server name, null if not available
1183
     */
1184 1
    public function getServerName()
1185
    {
1186 1
        return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
1187
    }
1188
1189
    /**
1190
     * Returns the server port number.
1191
     * @return int|null server port number, null if not available
1192
     */
1193 1
    public function getServerPort()
1194
    {
1195 1
        return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null;
1196
    }
1197
1198
    /**
1199
     * Returns the URL referrer.
1200
     * @return string|null URL referrer, null if not available
1201
     */
1202
    public function getReferrer()
1203
    {
1204
        if (!$this->hasHeader('Referer')) {
1205
            return null;
1206
        }
1207
        return $this->getHeaderLine('Referer');
1208
    }
1209
1210
    /**
1211
     * Returns the URL origin of a CORS request.
1212
     *
1213
     * The return value is taken from the `Origin` [[getHeaders()|header]] sent by the browser.
1214
     *
1215
     * Note that the origin request header indicates where a fetch originates from.
1216
     * It doesn't include any path information, but only the server name.
1217
     * It is sent with a CORS requests, as well as with POST requests.
1218
     * It is similar to the referer header, but, unlike this header, it doesn't disclose the whole path.
1219
     * Please refer to <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin> for more information.
1220
     *
1221
     * @return string|null URL origin of a CORS request, `null` if not available.
1222
     * @see getHeaders()
1223
     * @since 2.0.13
1224
     */
1225 1
    public function getOrigin()
1226
    {
1227 1
        return $this->getHeaderLine('origin');
1228
    }
1229
1230
    /**
1231
     * Returns the user agent.
1232
     * @return string|null user agent, null if not available
1233
     */
1234
    public function getUserAgent()
1235
    {
1236
        if (!$this->hasHeader('User-Agent')) {
1237
            return null;
1238
        }
1239
        return $this->getHeaderLine('User-Agent');
1240
    }
1241
1242
    /**
1243
     * Returns the user IP address.
1244
     * The IP is determined using headers and / or `$_SERVER` variables.
1245
     * @return string|null user IP address, null if not available
1246
     */
1247 32
    public function getUserIP()
1248
    {
1249 32
        foreach ($this->ipHeaders as $ipHeader) {
1250 32
            if ($this->hasHeader($ipHeader)) {
1251 32
                return trim(explode(',', $this->getHeaderLine($ipHeader))[0]);
1252
            }
1253
        }
1254
1255 31
        return $this->getRemoteIP();
1256
    }
1257
1258
    /**
1259
     * Returns the user host name.
1260
     * The HOST is determined using headers and / or `$_SERVER` variables.
1261
     * @return string|null user host name, null if not available
1262
     */
1263
    public function getUserHost()
1264
    {
1265
        foreach ($this->ipHeaders as $ipHeader) {
1266
            if ($this->hasHeader($ipHeader)) {
1267
                return gethostbyaddr(trim(explode(',', $this->getHeaderLine($ipHeader))[0]));
1268
            }
1269
        }
1270
1271
        return $this->getRemoteHost();
1272
    }
1273
1274
    /**
1275
     * Returns the IP on the other end of this connection.
1276
     * This is always the next hop, any headers are ignored.
1277
     * @return string|null remote IP address, `null` if not available.
1278
     * @since 2.0.13
1279
     */
1280 47
    public function getRemoteIP()
1281
    {
1282 47
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
1283
    }
1284
1285
    /**
1286
     * Returns the host name of the other end of this connection.
1287
     * This is always the next hop, any headers are ignored.
1288
     * @return string|null remote host name, `null` if not available
1289
     * @see getUserHost()
1290
     * @see getRemoteIP()
1291
     * @since 2.0.13
1292
     */
1293
    public function getRemoteHost()
1294
    {
1295
        return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
1296
    }
1297
1298
    /**
1299
     * @return string|null the username sent via HTTP authentication, null if the username is not given
1300
     */
1301 10
    public function getAuthUser()
1302
    {
1303 10
        return isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
1304
    }
1305
1306
    /**
1307
     * @return string|null the password sent via HTTP authentication, null if the password is not given
1308
     */
1309 10
    public function getAuthPassword()
1310
    {
1311 10
        return isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
1312
    }
1313
1314
    private $_port;
1315
1316
    /**
1317
     * Returns the port to use for insecure requests.
1318
     * Defaults to 80, or the port specified by the server if the current
1319
     * request is insecure.
1320
     * @return int port number for insecure requests.
1321
     * @see setPort()
1322
     */
1323
    public function getPort()
1324
    {
1325
        if ($this->_port === null) {
1326
            $this->_port = !$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : 80;
1327
        }
1328
1329
        return $this->_port;
1330
    }
1331
1332
    /**
1333
     * Sets the port to use for insecure requests.
1334
     * This setter is provided in case a custom port is necessary for certain
1335
     * server configurations.
1336
     * @param int $value port number.
1337
     */
1338
    public function setPort($value)
1339
    {
1340
        if ($value != $this->_port) {
1341
            $this->_port = (int) $value;
1342
            $this->_hostInfo = null;
1343
        }
1344
    }
1345
1346
    private $_securePort;
1347
1348
    /**
1349
     * Returns the port to use for secure requests.
1350
     * Defaults to 443, or the port specified by the server if the current
1351
     * request is secure.
1352
     * @return int port number for secure requests.
1353
     * @see setSecurePort()
1354
     */
1355
    public function getSecurePort()
1356
    {
1357
        if ($this->_securePort === null) {
1358
            $this->_securePort = $this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : 443;
1359
        }
1360
1361
        return $this->_securePort;
1362
    }
1363
1364
    /**
1365
     * Sets the port to use for secure requests.
1366
     * This setter is provided in case a custom port is necessary for certain
1367
     * server configurations.
1368
     * @param int $value port number.
1369
     */
1370
    public function setSecurePort($value)
1371
    {
1372
        if ($value != $this->_securePort) {
1373
            $this->_securePort = (int) $value;
1374
            $this->_hostInfo = null;
1375
        }
1376
    }
1377
1378
    private $_contentTypes;
1379
1380
    /**
1381
     * Returns the content types acceptable by the end user.
1382
     *
1383
     * This is determined by the `Accept` HTTP header. For example,
1384
     *
1385
     * ```php
1386
     * $_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1387
     * $types = $request->getAcceptableContentTypes();
1388
     * print_r($types);
1389
     * // displays:
1390
     * // [
1391
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1392
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1393
     * //           'text/plain' => ['q' => 0.5],
1394
     * // ]
1395
     * ```
1396
     *
1397
     * @return array the content types ordered by the quality score. Types with the highest scores
1398
     * will be returned first. The array keys are the content types, while the array values
1399
     * are the corresponding quality score and other parameters as given in the header.
1400
     */
1401 3
    public function getAcceptableContentTypes()
1402
    {
1403 3
        if ($this->_contentTypes === null) {
1404 2
            if ($this->hasHeader('Accept')) {
1405 2
                $this->_contentTypes = $this->parseAcceptHeader($this->getHeaderLine('Accept'));
1406
            } else {
1407 1
                $this->_contentTypes = [];
1408
            }
1409
        }
1410
1411 3
        return $this->_contentTypes;
1412
    }
1413
1414
    /**
1415
     * Sets the acceptable content types.
1416
     * Please refer to [[getAcceptableContentTypes()]] on the format of the parameter.
1417
     * @param array $value the content types that are acceptable by the end user. They should
1418
     * be ordered by the preference level.
1419
     * @see getAcceptableContentTypes()
1420
     * @see parseAcceptHeader()
1421
     */
1422 1
    public function setAcceptableContentTypes($value)
1423
    {
1424 1
        $this->_contentTypes = $value;
1425 1
    }
1426
1427
    /**
1428
     * Returns request content-type
1429
     * The Content-Type header field indicates the MIME type of the data
1430
     * contained in [[getBody()]] or, in the case of the HEAD method, the
1431
     * media type that would have been sent had the request been a GET.
1432
     * For the MIME-types the user expects in response, see [[acceptableContentTypes]].
1433
     * @return string request content-type. Empty string is returned if this information is not available.
1434
     * @link https://tools.ietf.org/html/rfc2616#section-14.17
1435
     * HTTP 1.1 header field definitions
1436
     */
1437 12
    public function getContentType()
1438
    {
1439 12
        return $this->getHeaderLine('Content-Type');
1440
    }
1441
1442
    private $_languages;
1443
1444
    /**
1445
     * Returns the languages acceptable by the end user.
1446
     * This is determined by the `Accept-Language` HTTP header.
1447
     * @return array the languages ordered by the preference level. The first element
1448
     * represents the most preferred language.
1449
     */
1450 1
    public function getAcceptableLanguages()
1451
    {
1452 1
        if ($this->_languages === null) {
1453
            if ($this->hasHeader('Accept-Language')) {
1454
                $this->_languages = array_keys($this->parseAcceptHeader($this->getHeaderLine('Accept-Language')));
1455
            } else {
1456
                $this->_languages = [];
1457
            }
1458
        }
1459
1460 1
        return $this->_languages;
1461
    }
1462
1463
    /**
1464
     * @param array $value the languages that are acceptable by the end user. They should
1465
     * be ordered by the preference level.
1466
     */
1467 1
    public function setAcceptableLanguages($value)
1468
    {
1469 1
        $this->_languages = $value;
1470 1
    }
1471
1472
    /**
1473
     * Parses the given `Accept` (or `Accept-Language`) header.
1474
     *
1475
     * This method will return the acceptable values with their quality scores and the corresponding parameters
1476
     * as specified in the given `Accept` header. The array keys of the return value are the acceptable values,
1477
     * while the array values consisting of the corresponding quality scores and parameters. The acceptable
1478
     * values with the highest quality scores will be returned first. For example,
1479
     *
1480
     * ```php
1481
     * $header = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1482
     * $accepts = $request->parseAcceptHeader($header);
1483
     * print_r($accepts);
1484
     * // displays:
1485
     * // [
1486
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1487
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1488
     * //           'text/plain' => ['q' => 0.5],
1489
     * // ]
1490
     * ```
1491
     *
1492
     * @param string $header the header to be parsed
1493
     * @return array the acceptable values ordered by their quality score. The values with the highest scores
1494
     * will be returned first.
1495
     */
1496 3
    public function parseAcceptHeader($header)
1497
    {
1498 3
        $accepts = [];
1499 3
        foreach (explode(',', $header) as $i => $part) {
1500 3
            $params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY);
1501 3
            if (empty($params)) {
1502 1
                continue;
1503
            }
1504
            $values = [
1505 3
                'q' => [$i, array_shift($params), 1],
1506
            ];
1507 3
            foreach ($params as $param) {
1508 2
                if (strpos($param, '=') !== false) {
1509 2
                    [$key, $value] = explode('=', $param, 2);
0 ignored issues
show
Bug introduced by
The variable $key does not exist. Did you forget to declare it?

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

Loading history...
Bug introduced by
The variable $value does not exist. Did you mean $values?

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

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

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

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

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

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

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

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

Loading history...
1514
                    }
1515
                } else {
1516 2
                    $values[] = $param;
1517
                }
1518
            }
1519 3
            $accepts[] = $values;
1520
        }
1521
1522 3
        usort($accepts, function ($a, $b) {
1523 3
            $a = $a['q']; // index, name, q
1524 3
            $b = $b['q'];
1525 3
            if ($a[2] > $b[2]) {
1526 2
                return -1;
1527
            }
1528
1529 2
            if ($a[2] < $b[2]) {
1530 1
                return 1;
1531
            }
1532
1533 2
            if ($a[1] === $b[1]) {
1534
                return $a[0] > $b[0] ? 1 : -1;
1535
            }
1536
1537 2
            if ($a[1] === '*/*') {
1538
                return 1;
1539
            }
1540
1541 2
            if ($b[1] === '*/*') {
1542
                return -1;
1543
            }
1544
1545 2
            $wa = $a[1][strlen($a[1]) - 1] === '*';
1546 2
            $wb = $b[1][strlen($b[1]) - 1] === '*';
1547 2
            if ($wa xor $wb) {
1548
                return $wa ? 1 : -1;
1549
            }
1550
1551 2
            return $a[0] > $b[0] ? 1 : -1;
1552 3
        });
1553
1554 3
        $result = [];
1555 3
        foreach ($accepts as $accept) {
1556 3
            $name = $accept['q'][1];
1557 3
            $accept['q'] = $accept['q'][2];
1558 3
            $result[$name] = $accept;
1559
        }
1560
1561 3
        return $result;
1562
    }
1563
1564
    /**
1565
     * Returns the user-preferred language that should be used by this application.
1566
     * The language resolution is based on the user preferred languages and the languages
1567
     * supported by the application. The method will try to find the best match.
1568
     * @param array $languages a list of the languages supported by the application. If this is empty, the current
1569
     * application language will be returned without further processing.
1570
     * @return string the language that the application should use.
1571
     */
1572 1
    public function getPreferredLanguage(array $languages = [])
1573
    {
1574 1
        if (empty($languages)) {
1575 1
            return Yii::$app->language;
1576
        }
1577 1
        foreach ($this->getAcceptableLanguages() as $acceptableLanguage) {
1578 1
            $acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
1579 1
            foreach ($languages as $language) {
1580 1
                $normalizedLanguage = str_replace('_', '-', strtolower($language));
1581
1582
                if (
1583 1
                    $normalizedLanguage === $acceptableLanguage // en-us==en-us
1584 1
                    || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us
1585 1
                    || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en
1586
                ) {
1587 1
                    return $language;
1588
                }
1589
            }
1590
        }
1591
1592 1
        return reset($languages);
1593
    }
1594
1595
    /**
1596
     * Gets the Etags.
1597
     *
1598
     * @return array The entity tags
1599
     */
1600
    public function getETags()
1601
    {
1602
        if ($this->hasHeader('if-none-match')) {
1603
            return preg_split('/[\s,]+/', str_replace('-gzip', '', $this->getHeaderLine('if-none-match')), -1, PREG_SPLIT_NO_EMPTY);
1604
        }
1605
1606
        return [];
1607
    }
1608
1609
    /**
1610
     * Returns the cookie collection.
1611
     *
1612
     * Through the returned cookie collection, you may access a cookie using the following syntax:
1613
     *
1614
     * ```php
1615
     * $cookie = $request->cookies['name']
1616
     * if ($cookie !== null) {
1617
     *     $value = $cookie->value;
1618
     * }
1619
     *
1620
     * // alternatively
1621
     * $value = $request->cookies->getValue('name');
1622
     * ```
1623
     *
1624
     * @return CookieCollection the cookie collection.
1625
     */
1626 33
    public function getCookies()
1627
    {
1628 33
        if ($this->_cookies === null) {
1629 33
            $this->_cookies = new CookieCollection($this->loadCookies(), [
1630 33
                'readOnly' => true,
1631
            ]);
1632
        }
1633
1634 33
        return $this->_cookies;
1635
    }
1636
1637
    /**
1638
     * Converts `$_COOKIE` into an array of [[Cookie]].
1639
     * @return array the cookies obtained from request
1640
     * @throws InvalidConfigException if [[cookieValidationKey]] is not set when [[enableCookieValidation]] is true
1641
     */
1642 33
    protected function loadCookies()
1643
    {
1644 33
        $cookies = [];
1645 33
        if ($this->enableCookieValidation) {
1646 32
            if ($this->cookieValidationKey == '') {
1647
                throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
1648
            }
1649 32
            foreach ($_COOKIE as $name => $value) {
1650
                if (!is_string($value)) {
1651
                    continue;
1652
                }
1653
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
1654
                if ($data === false) {
1655
                    continue;
1656
                }
1657
                $data = @unserialize($data);
1658
                if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
1659
                    $cookies[$name] = new Cookie([
1660 32
                        'name' => $name,
1661
                        'value' => $data[1],
1662
                        'expire' => null,
1663
                    ]);
1664
                }
1665
            }
1666
        } else {
1667 1
            foreach ($_COOKIE as $name => $value) {
1668
                $cookies[$name] = new Cookie([
1669
                    'name' => $name,
1670
                    'value' => $value,
1671
                    'expire' => null,
1672
                ]);
1673
            }
1674
        }
1675
1676 33
        return $cookies;
1677
    }
1678
1679
    /**
1680
     * Returns uploaded files for this request.
1681
     * Uploaded files are returned in format according to [PSR-7 Uploaded Files specs](http://www.php-fig.org/psr/psr-7/#16-uploaded-files).
1682
     * @return array uploaded files.
1683
     * @since 2.1.0
1684
     */
1685 11
    public function getUploadedFiles()
1686
    {
1687 11
        if ($this->_uploadedFiles === null) {
1688 5
            $this->getBodyParams(); // uploaded files are the part of the body and may be set while its parsing
1689 5
            if ($this->_uploadedFiles === null) {
1690 5
                $this->_uploadedFiles = $this->defaultUploadedFiles();
1691
            }
1692
        }
1693 11
        return $this->_uploadedFiles;
1694
    }
1695
1696
    /**
1697
     * Sets uploaded files for this request.
1698
     * Data structure for the uploaded files should follow [PSR-7 Uploaded Files specs](http://www.php-fig.org/psr/psr-7/#16-uploaded-files).
1699
     * @param array|null $uploadedFiles uploaded files.
1700
     * @since 2.1.0
1701
     */
1702 6
    public function setUploadedFiles($uploadedFiles)
1703
    {
1704 6
        $this->_uploadedFiles = $uploadedFiles;
0 ignored issues
show
Documentation Bug introduced by
It seems like $uploadedFiles can be null. However, the property $_uploadedFiles is declared as array. Maybe change the type of the property to array|null or add a type check?

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

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

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

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

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

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

Loading history...
1705 6
    }
1706
1707
    /**
1708
     * Initializes default uploaded files data structure parsing super-global $_FILES.
1709
     * @see http://www.php-fig.org/psr/psr-7/#16-uploaded-files
1710
     * @return array uploaded files.
1711
     * @since 2.1.0
1712
     */
1713 5
    protected function defaultUploadedFiles()
1714
    {
1715 5
        $files = [];
1716 5
        foreach ($_FILES as $class => $info) {
1717 3
            $files[$class] = [];
1718 3
            $this->populateUploadedFileRecursive($files[$class], $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
1719
        }
1720
1721 5
        return $files;
1722
    }
1723
1724
    /**
1725
     * Populates uploaded files array from $_FILE data structure recursively.
1726
     * @param array $files uploaded files array to be populated.
1727
     * @param mixed $names file names provided by PHP
1728
     * @param mixed $tempNames temporary file names provided by PHP
1729
     * @param mixed $types file types provided by PHP
1730
     * @param mixed $sizes file sizes provided by PHP
1731
     * @param mixed $errors uploading issues provided by PHP
1732
     * @since 2.1.0
1733
     */
1734 3
    private function populateUploadedFileRecursive(&$files, $names, $tempNames, $types, $sizes, $errors)
1735
    {
1736 3
        if (is_array($names)) {
1737 2
            foreach ($names as $i => $name) {
1738 2
                $files[$i] = [];
1739 2
                $this->populateUploadedFileRecursive($files[$i], $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
1740
            }
1741
        } else {
1742 3
            $files = Yii::createObject([
1743 3
                'class' => $this->uploadedFileClass,
1744 3
                'clientFilename' => $names,
1745 3
                'tempFilename' => $tempNames,
1746 3
                'clientMediaType' => $types,
1747 3
                'size' => $sizes,
1748 3
                'error' => $errors,
1749
            ]);
1750
        }
1751 3
    }
1752
1753
    /**
1754
     * Returns an uploaded file according to the given name.
1755
     * Name can be either a string HTML form input name, e.g. 'Item[file]' or array path, e.g. `['Item', 'file']`.
1756
     * Note: this method returns `null` in case given name matches multiple files.
1757
     * @param string|array $name HTML form input name or array path.
1758
     * @return UploadedFileInterface|null uploaded file instance, `null` - if not found.
1759
     * @since 2.1.0
1760
     */
1761 1
    public function getUploadedFileByName($name)
1762
    {
1763 1
        $uploadedFile = $this->findUploadedFiles($name);
1764 1
        if ($uploadedFile instanceof UploadedFileInterface) {
1765 1
            return $uploadedFile;
1766
        }
1767 1
        return null;
1768
    }
1769
1770
    /**
1771
     * Returns the list of uploaded file instances according to the given name.
1772
     * Name can be either a string HTML form input name, e.g. 'Item[file]' or array path, e.g. `['Item', 'file']`.
1773
     * Note: this method does NOT preserve uploaded files structure - it returns instances in single-level array (list),
1774
     * even if they are set by nested keys.
1775
     * @param string|array $name HTML form input name or array path.
1776
     * @return UploadedFileInterface[] list of uploaded file instances.
1777
     * @since 2.1.0
1778
     */
1779 1
    public function getUploadedFilesByName($name)
1780
    {
1781 1
        $uploadedFiles = $this->findUploadedFiles($name);
1782 1
        if ($uploadedFiles === null) {
1783
            return [];
1784
        }
1785 1
        if ($uploadedFiles instanceof UploadedFileInterface) {
1786 1
            return [$uploadedFiles];
1787
        }
1788 1
        return $this->reduceUploadedFiles($uploadedFiles);
1789
    }
1790
1791
    /**
1792
     * Finds the uploaded file or set of uploaded files inside [[$uploadedFiles]] according to given name.
1793
     * Name can be either a string HTML form input name, e.g. 'Item[file]' or array path, e.g. `['Item', 'file']`.
1794
     * @param string|array $name HTML form input name or array path.
1795
     * @return UploadedFileInterface|array|null
1796
     * @since 2.1.0
1797
     */
1798 2
    private function findUploadedFiles($name)
1799
    {
1800 2
        if (!is_array($name)) {
1801 2
            $name = preg_split('/\\]\\[|\\[|\\]/s', $name, -1, PREG_SPLIT_NO_EMPTY);
1802
        }
1803 2
        return ArrayHelper::getValue($this->getUploadedFiles(), $name);
1804
    }
1805
1806
    /**
1807
     * Reduces complex uploaded files structure to the single-level array (list).
1808
     * @param array $uploadedFiles raw set of the uploaded files.
1809
     * @return UploadedFileInterface[] list of uploaded files.
1810
     * @since 2.1.0
1811
     */
1812
    private function reduceUploadedFiles($uploadedFiles)
1813
    {
1814 1
        return array_reduce($uploadedFiles, function ($carry, $item) {
1815 1
            if ($item instanceof UploadedFileInterface) {
1816 1
                $carry[] = $item;
1817
            } else {
1818 1
                $carry = array_merge($carry, $this->reduceUploadedFiles($item));
1819
            }
1820 1
            return $carry;
1821 1
        }, []);
1822
    }
1823
1824
    private $_csrfToken;
1825
1826
    /**
1827
     * Returns the token used to perform CSRF validation.
1828
     *
1829
     * This token is generated in a way to prevent [BREACH attacks](http://breachattack.com/). It may be passed
1830
     * along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.
1831
     * @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time
1832
     * this method is called, a new CSRF token will be generated and persisted (in session or cookie).
1833
     * @return string the token used to perform CSRF validation.
1834
     */
1835 37
    public function getCsrfToken($regenerate = false)
1836
    {
1837 37
        if ($this->_csrfToken === null || $regenerate) {
1838 37
            if ($regenerate || ($token = $this->loadCsrfToken()) === null) {
1839 35
                $token = $this->generateCsrfToken();
1840
            }
1841 37
            $this->_csrfToken = Yii::$app->security->maskToken($token);
1842
        }
1843
1844 37
        return $this->_csrfToken;
1845
    }
1846
1847
    /**
1848
     * Loads the CSRF token from cookie or session.
1849
     * @return string the CSRF token loaded from cookie or session. Null is returned if the cookie or session
1850
     * does not have CSRF token.
1851
     */
1852 37
    protected function loadCsrfToken()
1853
    {
1854 37
        if ($this->enableCsrfCookie) {
1855 33
            return $this->getCookies()->getValue($this->csrfParam);
1856
        }
1857
1858 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...
1859
    }
1860
1861
    /**
1862
     * Generates an unmasked random token used to perform CSRF validation.
1863
     * @return string the random token for CSRF validation.
1864
     */
1865 35
    protected function generateCsrfToken()
1866
    {
1867 35
        $token = Yii::$app->getSecurity()->generateRandomString();
1868 35
        if ($this->enableCsrfCookie) {
1869 33
            $cookie = $this->createCsrfCookie($token);
1870 33
            Yii::$app->getResponse()->getCookies()->add($cookie);
1871
        } else {
1872 2
            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...
1873
        }
1874
1875 35
        return $token;
1876
    }
1877
1878
    /**
1879
     * @return string the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent.
1880
     */
1881 3
    public function getCsrfTokenFromHeader()
1882
    {
1883 3
        return $this->getHeaderLine(static::CSRF_HEADER);
1884
    }
1885
1886
    /**
1887
     * Creates a cookie with a randomly generated CSRF token.
1888
     * Initial values specified in [[csrfCookie]] will be applied to the generated cookie.
1889
     * @param string $token the CSRF token
1890
     * @return Cookie the generated cookie
1891
     * @see enableCsrfValidation
1892
     */
1893 33
    protected function createCsrfCookie($token)
1894
    {
1895 33
        $options = $this->csrfCookie;
1896 33
        $options['name'] = $this->csrfParam;
1897 33
        $options['value'] = $token;
1898 33
        return new Cookie($options);
1899
    }
1900
1901
    /**
1902
     * Performs the CSRF validation.
1903
     *
1904
     * This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session.
1905
     * This method is mainly called in [[Controller::beforeAction()]].
1906
     *
1907
     * Note that the method will NOT perform CSRF validation if [[enableCsrfValidation]] is false or the HTTP method
1908
     * is among GET, HEAD or OPTIONS.
1909
     *
1910
     * @param string $clientSuppliedToken the user-provided CSRF token to be validated. If null, the token will be retrieved from
1911
     * the [[csrfParam]] POST field or HTTP header.
1912
     * This parameter is available since version 2.0.4.
1913
     * @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.
1914
     */
1915 5
    public function validateCsrfToken($clientSuppliedToken = null)
1916
    {
1917 5
        $method = $this->getMethod();
1918
        // only validate CSRF token on non-"safe" methods https://tools.ietf.org/html/rfc2616#section-9.1.1
1919 5
        if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
1920 5
            return true;
1921
        }
1922
1923 3
        $trueToken = $this->getCsrfToken();
1924
1925 3
        if ($clientSuppliedToken !== null) {
1926 1
            return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken);
1927
        }
1928
1929 3
        return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
1930 3
            || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
1931
    }
1932
1933
    /**
1934
     * Validates CSRF token.
1935
     *
1936
     * @param string $clientSuppliedToken The masked client-supplied token.
1937
     * @param string $trueToken The masked true token.
1938
     * @return bool
1939
     */
1940 3
    private function validateCsrfTokenInternal($clientSuppliedToken, $trueToken)
1941
    {
1942 3
        if (!is_string($clientSuppliedToken)) {
1943 3
            return false;
1944
        }
1945
1946 3
        $security = Yii::$app->security;
1947
1948 3
        return $security->unmaskToken($clientSuppliedToken) === $security->unmaskToken($trueToken);
1949
    }
1950
1951
    /**
1952
     * {@inheritdoc}
1953
     */
1954 2
    public function __clone()
1955
    {
1956 2
        parent::__clone();
1957
1958 2
        $this->cloneHttpMessageInternals();
1959
1960 2
        if (is_object($this->_cookies)) {
1961
            $this->_cookies = clone $this->_cookies;
1962
        }
1963 2
    }
1964
}
1965