Completed
Push — 2.1 ( 37580d...257604 )
by
unknown
12:15
created

Request::getMethod()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 10
cp 0.8
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
nc 5
nop 0
crap 5.2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\StreamInterface;
12
use Psr\Http\Message\UriInterface;
13
use Yii;
14
use yii\base\InvalidConfigException;
15
use yii\di\Instance;
16
use yii\http\Cookie;
17
use yii\http\CookieCollection;
18
use yii\http\FileStream;
19
use yii\http\MessageTrait;
20
use yii\http\Uri;
21
22
/**
23
 * The web Request class represents an HTTP request
24
 *
25
 * It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.
26
 * Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST
27
 * parameters sent via other HTTP methods like PUT or DELETE.
28
 *
29
 * Request is configured as an application component in [[\yii\web\Application]] by default.
30
 * You can access that instance via `Yii::$app->request`.
31
 *
32
 * For more details and usage information on Request, see the [guide article on requests](guide:runtime-requests).
33
 *
34
 * @property string $absoluteUrl The currently requested absolute URL. This property is read-only.
35
 * @property array $acceptableContentTypes The content types ordered by the quality score. Types with the
36
 * highest scores will be returned first. The array keys are the content types, while the array values are the
37
 * corresponding quality score and other parameters as given in the header.
38
 * @property array $acceptableLanguages The languages ordered by the preference level. The first element
39
 * represents the most preferred language.
40
 * @property string|null $authPassword The password sent via HTTP authentication, null if the password is not
41
 * given. This property is read-only.
42
 * @property string|null $authUser The username sent via HTTP authentication, null if the username is not
43
 * given. This property is read-only.
44
 * @property string $baseUrl The relative URL for the application.
45
 * @property array $bodyParams The request parameters given in the request body.
46
 * @property string $contentType Request content-type. Null is returned if this information is not available.
47
 * This property is read-only.
48
 * @property CookieCollection $cookies The cookie collection. This property is read-only.
49
 * @property string $csrfToken The token used to perform CSRF validation. This property is read-only.
50
 * @property string $csrfTokenFromHeader The CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned
51
 * if no such header is sent. This property is read-only.
52
 * @property array $eTags The entity tags. This property is read-only.
53
 * @property string|null $hostInfo Schema and hostname part (with port number if needed) of the request URL
54
 * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. See
55
 * [[getHostInfo()]] for security related notes on this property.
56
 * @property string|null $hostName Hostname part of the request URL (e.g. `www.yiiframework.com`). This
57
 * property is read-only.
58
 * @property bool $isAjax Whether this is an AJAX (XMLHttpRequest) request. This property is read-only.
59
 * @property bool $isDelete Whether this is a DELETE request. This property is read-only.
60
 * @property bool $isFlash Whether this is an Adobe Flash or Adobe Flex request. This property is read-only.
61
 * @property bool $isGet Whether this is a GET request. This property is read-only.
62
 * @property bool $isHead Whether this is a HEAD request. This property is read-only.
63
 * @property bool $isOptions Whether this is a OPTIONS request. This property is read-only.
64
 * @property bool $isPatch Whether this is a PATCH request. This property is read-only.
65
 * @property bool $isPjax Whether this is a PJAX request. This property is read-only.
66
 * @property bool $isPost Whether this is a POST request. This property is read-only.
67
 * @property bool $isPut Whether this is a PUT request. This property is read-only.
68
 * @property bool $isSecureConnection If the request is sent via secure channel (https). This property is
69
 * read-only.
70
 * @property string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is
71
 * turned into upper case.
72
 * @property UriInterface $uri the URI instance.
73
 * @property mixed $requestTarget the message's request target.
74
 * @property string $pathInfo Part of the request URL that is after the entry script and before the question
75
 * mark. Note, the returned path info is already URL-decoded.
76
 * @property int $port Port number for insecure requests.
77
 * @property array $queryParams The request GET parameter values.
78
 * @property string $queryString Part of the request URL that is after the question mark. This property is
79
 * read-only.
80
 * @property string $rawBody The request body.
81
 * @property string|null $referrer URL referrer, null if not available. This property is read-only.
82
 * @property string|null $origin URL origin, null if not available. This property is read-only.
83
 * @property string $scriptFile The entry script file path.
84
 * @property string $scriptUrl The relative URL of the entry script.
85
 * @property int $securePort Port number for secure requests.
86
 * @property string $serverName Server name, null if not available. This property is read-only.
87
 * @property int|null $serverPort Server port number, null if not available. This property is read-only.
88
 * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded
89
 * depending on the client.
90
 * @property string|null $userAgent User agent, null if not available. This property is read-only.
91
 * @property string|null $userHost User host name, null if not available. This property is read-only.
92
 * @property string|null $userIP User IP address, null if not available. This property is read-only.
93
 *
94
 * @author Qiang Xue <[email protected]>
95
 * @since 2.0
96
 */
97
class Request extends \yii\base\Request implements RequestInterface
98
{
99
    use MessageTrait;
100
101
    /**
102
     * The name of the HTTP header for sending CSRF token.
103
     */
104
    const CSRF_HEADER = 'X-CSRF-Token';
105
    /**
106
     * The length of the CSRF token mask.
107
     * @deprecated 2.0.12 The mask length is now equal to the token length.
108
     */
109
    const CSRF_MASK_LENGTH = 8;
110
111
    /**
112
     * @var bool whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true.
113
     * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated
114
     * from the same application. If not, a 400 HTTP exception will be raised.
115
     *
116
     * Note, this feature requires that the user client accepts cookie. Also, to use this feature,
117
     * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfParam]].
118
     * You may use [[\yii\helpers\Html::beginForm()]] to generate his hidden input.
119
     *
120
     * In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and
121
     * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered.
122
     * You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]].
123
     *
124
     * @see Controller::enableCsrfValidation
125
     * @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
126
     */
127
    public $enableCsrfValidation = true;
128
    /**
129
     * @var string the name of the token used to prevent CSRF. Defaults to '_csrf'.
130
     * This property is used only when [[enableCsrfValidation]] is true.
131
     */
132
    public $csrfParam = '_csrf';
133
    /**
134
     * @var array the configuration for creating the CSRF [[Cookie|cookie]]. This property is used only when
135
     * both [[enableCsrfValidation]] and [[enableCsrfCookie]] are true.
136
     */
137
    public $csrfCookie = ['httpOnly' => true];
138
    /**
139
     * @var bool whether to use cookie to persist CSRF token. If false, CSRF token will be stored
140
     * in session under the name of [[csrfParam]]. Note that while storing CSRF tokens in session increases
141
     * security, it requires starting a session for every page, which will degrade your site performance.
142
     */
143
    public $enableCsrfCookie = true;
144
    /**
145
     * @var bool whether cookies should be validated to ensure they are not tampered. Defaults to true.
146
     */
147
    public $enableCookieValidation = true;
148
    /**
149
     * @var string a secret key used for cookie validation. This property must be set if [[enableCookieValidation]] is true.
150
     */
151
    public $cookieValidationKey;
152
    /**
153
     * @var string the name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE
154
     * request tunneled through POST. Defaults to '_method'.
155
     * @see getMethod()
156
     * @see getBodyParams()
157
     */
158
    public $methodParam = '_method';
159
    /**
160
     * @var array the parsers for converting the raw HTTP request body into [[bodyParams]].
161
     * The array keys are the request `Content-Types`, and the array values are the
162
     * corresponding configurations for [[Yii::createObject|creating the parser objects]].
163
     * A parser must implement the [[RequestParserInterface]].
164
     *
165
     * To enable parsing for JSON requests you can use the [[JsonParser]] class like in the following example:
166
     *
167
     * ```
168
     * [
169
     *     'application/json' => \yii\web\JsonParser::class,
170
     * ]
171
     * ```
172
     *
173
     * To register a parser for parsing all request types you can use `'*'` as the array key.
174
     * This one will be used as a fallback in case no other types match.
175
     *
176
     * @see getBodyParams()
177
     */
178
    public $parsers = [];
179
180
    /**
181
     * @var CookieCollection Collection of request cookies.
182
     */
183
    private $_cookies;
184
    /**
185
     * @var string the HTTP method of the request.
186
     */
187
    private $_method;
188
    /**
189
     * @var UriInterface the URI instance associated with request.
190
     */
191
    private $_uri;
192
    /**
193
     * @var mixed the message's request target.
194
     */
195
    private $_requestTarget;
196
197
198
    /**
199
     * Resolves the current request into a route and the associated parameters.
200
     * @return array the first element is the route, and the second is the associated parameters.
201
     * @throws NotFoundHttpException if the request cannot be resolved.
202
     */
203 1
    public function resolve()
204
    {
205 1
        $result = Yii::$app->getUrlManager()->parseRequest($this);
206 1
        if ($result !== false) {
207 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...
208 1
            if ($this->_queryParams === null) {
209 1
                $_GET = $params + $_GET; // preserve numeric keys
210
            } else {
211 1
                $this->_queryParams = $params + $this->_queryParams;
212
            }
213 1
            return [$route, $this->getQueryParams()];
214
        }
215
216
        throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
217
    }
218
219
    /**
220
     * Returns default message's headers, which should be present once [[headerCollection]] is instantiated.
221
     * @return string[][] an associative array of the message's headers.
222
     */
223 35
    protected function defaultHeaders()
224
    {
225 35
        if (function_exists('getallheaders')) {
226
            $headers = getallheaders();
227 35
        } elseif (function_exists('http_get_request_headers')) {
228
            $headers = http_get_request_headers();
229
        } else {
230 35
            $headers = [];
231 35
            foreach ($_SERVER as $name => $value) {
232 35
                if (strncmp($name, 'HTTP_', 5) === 0) {
233 1
                    $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
234 35
                    $headers[$name] = $value;
235
                }
236
            }
237
        }
238
239 35
        foreach ($headers as $name => $value) {
240 1
            $headers[strtolower($name)] = (array)$value;
241
        }
242
243 35
        return $headers;
244
    }
245
246
    /**
247
     * {@inheritdoc}
248
     * @since 2.1.0
249
     */
250
    public function getRequestTarget()
251
    {
252
        if ($this->_requestTarget === null) {
253
            $this->_requestTarget = $this->getUri()->__toString();
254
        }
255
        return $this->_requestTarget;
256
    }
257
258
    /**
259
     * Specifies the message's request target
260
     * @param mixed $requestTarget the message's request target.
261
     * @since 2.1.0
262
     */
263
    public function setRequestTarget($requestTarget)
264
    {
265
        $this->_requestTarget = $requestTarget;
266
    }
267
268
    /**
269
     * {@inheritdoc}
270
     * @since 2.1.0
271
     */
272
    public function withRequestTarget($requestTarget)
273
    {
274
        if ($this->getRequestTarget() === $requestTarget) {
275
            return $this;
276
        }
277
278
        $newInstance = clone $this;
279
        $newInstance->setRequestTarget($requestTarget);
280
        return $newInstance;
281
    }
282
283
    /**
284
     * {@inheritdoc}
285
     */
286 20
    public function getMethod()
287
    {
288 20
        if ($this->_method === null) {
289 16
            if (isset($_POST[$this->methodParam])) {
290 1
                $this->_method = $_POST[$this->methodParam];
291 15
            } elseif ($this->hasHeader('x-http-method-override')) {
292
                $this->_method = $this->getHeaderLine('x-http-method-override');
293 15
            } elseif (isset($_SERVER['REQUEST_METHOD'])) {
294
                $this->_method = $_SERVER['REQUEST_METHOD'];
295
            } else {
296 15
                $this->_method = 'GET';
297
            }
298
        }
299 20
        return $this->_method;
300
    }
301
302
    /**
303
     * Specifies request HTTP method.
304
     * @param string $method case-sensitive HTTP method.
305
     * @since 2.1.0
306
     */
307 6
    public function setMethod($method)
308
    {
309 6
        $this->_method =  $method;
310 6
    }
311
312
    /**
313
     * {@inheritdoc}
314
     * @since 2.1.0
315
     */
316
    public function withMethod($method)
317
    {
318
        if ($this->getMethod() === $method) {
319
            return $this;
320
        }
321
322
        $newInstance = clone $this;
323
        $newInstance->setMethod($method);
324
        return $newInstance;
325
    }
326
327
    /**
328
     * {@inheritdoc}
329
     * @since 2.1.0
330
     */
331
    public function getUri()
332
    {
333
        if (!$this->_uri instanceof UriInterface) {
334
            if ($this->_uri === null) {
335
                $uri = new Uri(['string' => $this->getAbsoluteUrl()]);
336
            } elseif ($this->_uri instanceof \Closure) {
337
                $uri = call_user_func($this->_uri, $this);
338
            } else {
339
                $uri = $this->_uri;
340
            }
341
342
            $this->_uri = Instance::ensure($uri, UriInterface::class);
343
        }
344
        return $this->_uri;
345
    }
346
347
    /**
348
     * Specifies the URI instance.
349
     * @param UriInterface|\Closure|array $uri URI instance or its DI compatible configuration.
350
     * @since 2.1.0
351
     */
352
    public function setUri($uri)
353
    {
354
        $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...
355
    }
356
357
    /**
358
     * {@inheritdoc}
359
     * @since 2.1.0
360
     */
361
    public function withUri(UriInterface $uri, $preserveHost = false)
362
    {
363
        if ($this->getUri() === $uri) {
364
            return $this;
365
        }
366
367
        $newInstance = clone $this;
368
369
        $newInstance->setUri($uri);
370
        if (!$preserveHost) {
371
            return $newInstance->withHeader('host', $uri->getHost());
372
        }
373
        return $newInstance;
374
    }
375
376
    /**
377
     * Returns whether this is a GET request.
378
     * @return bool whether this is a GET request.
379
     */
380 1
    public function getIsGet()
381
    {
382 1
        return $this->getMethod() === 'GET';
383
    }
384
385
    /**
386
     * Returns whether this is an OPTIONS request.
387
     * @return bool whether this is a OPTIONS request.
388
     */
389
    public function getIsOptions()
390
    {
391
        return $this->getMethod() === 'OPTIONS';
392
    }
393
394
    /**
395
     * Returns whether this is a HEAD request.
396
     * @return bool whether this is a HEAD request.
397
     */
398 9
    public function getIsHead()
399
    {
400 9
        return $this->getMethod() === 'HEAD';
401
    }
402
403
    /**
404
     * Returns whether this is a POST request.
405
     * @return bool whether this is a POST request.
406
     */
407
    public function getIsPost()
408
    {
409
        return $this->getMethod() === 'POST';
410
    }
411
412
    /**
413
     * Returns whether this is a DELETE request.
414
     * @return bool whether this is a DELETE request.
415
     */
416
    public function getIsDelete()
417
    {
418
        return $this->getMethod() === 'DELETE';
419
    }
420
421
    /**
422
     * Returns whether this is a PUT request.
423
     * @return bool whether this is a PUT request.
424
     */
425
    public function getIsPut()
426
    {
427
        return $this->getMethod() === 'PUT';
428
    }
429
430
    /**
431
     * Returns whether this is a PATCH request.
432
     * @return bool whether this is a PATCH request.
433
     */
434
    public function getIsPatch()
435
    {
436
        return $this->getMethod() === 'PATCH';
437
    }
438
439
    /**
440
     * Returns whether this is an AJAX (XMLHttpRequest) request.
441
     *
442
     * Note that jQuery doesn't set the header in case of cross domain
443
     * requests: https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header
444
     *
445
     * @return bool whether this is an AJAX (XMLHttpRequest) request.
446
     */
447 8
    public function getIsAjax()
448
    {
449 8
        return $this->getHeaderLine('x-requested-with') === 'XMLHttpRequest';
450
    }
451
452
    /**
453
     * Returns whether this is a PJAX request
454
     * @return bool whether this is a PJAX request
455
     */
456
    public function getIsPjax()
457
    {
458
        return $this->getIsAjax() && $this->hasHeader('x-pjax');
459
    }
460
461
    /**
462
     * Returns whether this is an Adobe Flash or Flex request.
463
     * @return bool whether this is an Adobe Flash or Adobe Flex request.
464
     */
465
    public function getIsFlash()
466
    {
467
        $userAgent = $this->getUserAgent();
468
        if ($userAgent === null) {
469
            return false;
470
        }
471
        return (stripos($userAgent, 'Shockwave') !== false || stripos($userAgent, 'Flash') !== false);
472
    }
473
474
    /**
475
     * Returns default message body to be used in case it is not explicitly set.
476
     * @return StreamInterface default body instance.
477
     */
478 1
    protected function defaultBody()
479
    {
480 1
        return new FileStream([
481 1
            'filename' => 'php://input',
482
            'mode' => 'r',
483
        ]);
484
    }
485
486
    private $_rawBody;
487
488
    /**
489
     * Returns the raw HTTP request body.
490
     * @return string the request body
491
     */
492 1
    public function getRawBody()
493
    {
494 1
        if ($this->_rawBody === null) {
495 1
            $this->_rawBody = $this->getBody()->__toString();
496
        }
497
498 1
        return $this->_rawBody;
499
    }
500
501
    /**
502
     * Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests.
503
     * @param string $rawBody the request body
504
     */
505
    public function setRawBody($rawBody)
506
    {
507
        $this->_rawBody = $rawBody;
508
    }
509
510
    private $_bodyParams;
511
512
    /**
513
     * Returns the request parameters given in the request body.
514
     *
515
     * Request parameters are determined using the parsers configured in [[parsers]] property.
516
     * If no parsers are configured for the current [[contentType]] it uses the PHP function `mb_parse_str()`
517
     * to parse the [[rawBody|request body]].
518
     * @return array the request parameters given in the request body.
519
     * @throws \yii\base\InvalidConfigException if a registered parser does not implement the [[RequestParserInterface]].
520
     * @see getMethod()
521
     * @see getBodyParam()
522
     * @see setBodyParams()
523
     */
524 4
    public function getBodyParams()
525
    {
526 4
        if ($this->_bodyParams === null) {
527 2
            if (isset($_POST[$this->methodParam])) {
528
                $this->_bodyParams = $_POST;
529
                unset($this->_bodyParams[$this->methodParam]);
530
                return $this->_bodyParams;
531
            }
532
533 2
            $rawContentType = $this->getContentType();
534 2
            if (($pos = strpos($rawContentType, ';')) !== false) {
535
                // e.g. text/html; charset=UTF-8
536
                $contentType = substr($rawContentType, 0, $pos);
537
            } else {
538 2
                $contentType = $rawContentType;
539
            }
540
541 2
            if (isset($this->parsers[$contentType])) {
542
                $parser = Yii::createObject($this->parsers[$contentType]);
543
                if (!($parser instanceof RequestParserInterface)) {
544
                    throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
545
                }
546
                $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
547 2
            } elseif (isset($this->parsers['*'])) {
548
                $parser = Yii::createObject($this->parsers['*']);
549
                if (!($parser instanceof RequestParserInterface)) {
550
                    throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.');
551
                }
552
                $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
553 2
            } elseif ($this->getMethod() === 'POST') {
554
                // PHP has already parsed the body so we have all params in $_POST
555 1
                $this->_bodyParams = $_POST;
556
            } else {
557 1
                $this->_bodyParams = [];
558 1
                mb_parse_str($this->getRawBody(), $this->_bodyParams);
559
            }
560
        }
561
562 4
        return $this->_bodyParams;
563
    }
564
565
    /**
566
     * Sets the request body parameters.
567
     * @param array $values the request body parameters (name-value pairs)
568
     * @see getBodyParam()
569
     * @see getBodyParams()
570
     */
571 3
    public function setBodyParams($values)
572
    {
573 3
        $this->_bodyParams = $values;
574 3
    }
575
576
    /**
577
     * Returns the named request body parameter value.
578
     * If the parameter does not exist, the second parameter passed to this method will be returned.
579
     * @param string $name the parameter name
580
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
581
     * @return mixed the parameter value
582
     * @see getBodyParams()
583
     * @see setBodyParams()
584
     */
585 4
    public function getBodyParam($name, $defaultValue = null)
586
    {
587 4
        $params = $this->getBodyParams();
588
589 4
        return isset($params[$name]) ? $params[$name] : $defaultValue;
590
    }
591
592
    /**
593
     * Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters.
594
     *
595
     * @param string $name the parameter name
596
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
597
     * @return array|mixed
598
     */
599
    public function post($name = null, $defaultValue = null)
600
    {
601
        if ($name === null) {
602
            return $this->getBodyParams();
603
        }
604
605
        return $this->getBodyParam($name, $defaultValue);
606
    }
607
608
    private $_queryParams;
609
610
    /**
611
     * Returns the request parameters given in the [[queryString]].
612
     *
613
     * This method will return the contents of `$_GET` if params where not explicitly set.
614
     * @return array the request GET parameter values.
615
     * @see setQueryParams()
616
     */
617 29
    public function getQueryParams()
618
    {
619 29
        if ($this->_queryParams === null) {
620 23
            return $_GET;
621
        }
622
623 8
        return $this->_queryParams;
624
    }
625
626
    /**
627
     * Sets the request [[queryString]] parameters.
628
     * @param array $values the request query parameters (name-value pairs)
629
     * @see getQueryParam()
630
     * @see getQueryParams()
631
     */
632 8
    public function setQueryParams($values)
633
    {
634 8
        $this->_queryParams = $values;
635 8
    }
636
637
    /**
638
     * Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.
639
     *
640
     * @param string $name the parameter name
641
     * @param mixed $defaultValue the default parameter value if the parameter does not exist.
642
     * @return array|mixed
643
     */
644 15
    public function get($name = null, $defaultValue = null)
645
    {
646 15
        if ($name === null) {
647
            return $this->getQueryParams();
648
        }
649
650 15
        return $this->getQueryParam($name, $defaultValue);
651
    }
652
653
    /**
654
     * Returns the named GET parameter value.
655
     * If the GET parameter does not exist, the second parameter passed to this method will be returned.
656
     * @param string $name the GET parameter name.
657
     * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
658
     * @return mixed the GET parameter value
659
     * @see getBodyParam()
660
     */
661 20
    public function getQueryParam($name, $defaultValue = null)
662
    {
663 20
        $params = $this->getQueryParams();
664
665 20
        return isset($params[$name]) ? $params[$name] : $defaultValue;
666
    }
667
668
    private $_hostInfo;
669
    private $_hostName;
670
671
    /**
672
     * Returns the schema and host part of the current request URL.
673
     *
674
     * The returned URL does not have an ending slash.
675
     *
676
     * By default this value is based on the user request information. This method will
677
     * return the value of `$_SERVER['HTTP_HOST']` if it is available or `$_SERVER['SERVER_NAME']` if not.
678
     * You may want to check out the [PHP documentation](http://php.net/manual/en/reserved.variables.server.php)
679
     * for more information on these variables.
680
     *
681
     * You may explicitly specify it by setting the [[setHostInfo()|hostInfo]] property.
682
     *
683
     * > Warning: Dependent on the server configuration this information may not be
684
     * > reliable and [may be faked by the user sending the HTTP request](https://www.acunetix.com/vulnerabilities/web/host-header-attack).
685
     * > If the webserver is configured to serve the same site independent of the value of
686
     * > the `Host` header, this value is not reliable. In such situations you should either
687
     * > fix your webserver configuration or explicitly set the value by setting the [[setHostInfo()|hostInfo]] property.
688
     * > If you don't have access to the server configuration, you can setup [[\yii\filters\HostControl]] filter at
689
     * > application level in order to protect against such kind of attack.
690
     *
691
     * @property string|null schema and hostname part (with port number if needed) of the request URL
692
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
693
     * See [[getHostInfo()]] for security related notes on this property.
694
     * @return string|null schema and hostname part (with port number if needed) of the request URL
695
     * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
696
     * @see setHostInfo()
697
     */
698 17
    public function getHostInfo()
699
    {
700 17
        if ($this->_hostInfo === null) {
701 13
            $secure = $this->getIsSecureConnection();
702 13
            $http = $secure ? 'https' : 'http';
703 13
            if ($this->hasHeader('Host')) {
704
                $this->_hostInfo = $http . '://' . $this->getHeaderLine('Host');
705 13
            } elseif (isset($_SERVER['SERVER_NAME'])) {
706
                $this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME'];
707
                $port = $secure ? $this->getSecurePort() : $this->getPort();
708
                if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
709
                    $this->_hostInfo .= ':' . $port;
710
                }
711
            }
712
        }
713
714 17
        return $this->_hostInfo;
715
    }
716
717
    /**
718
     * Sets the schema and host part of the application URL.
719
     * This setter is provided in case the schema and hostname cannot be determined
720
     * on certain Web servers.
721
     * @param string|null $value the schema and host part of the application URL. The trailing slashes will be removed.
722
     * @see getHostInfo() for security related notes on this property.
723
     */
724 54
    public function setHostInfo($value)
725
    {
726 54
        $this->_hostName = null;
727 54
        $this->_hostInfo = $value === null ? null : rtrim($value, '/');
728 54
    }
729
730
    /**
731
     * Returns the host part of the current request URL.
732
     * Value is calculated from current [[getHostInfo()|hostInfo]] property.
733
     *
734
     * > Warning: The content of this value may not be reliable, dependent on the server
735
     * > configuration. Please refer to [[getHostInfo()]] for more information.
736
     *
737
     * @return string|null hostname part of the request URL (e.g. `www.yiiframework.com`)
738
     * @see getHostInfo()
739
     * @since 2.0.10
740
     */
741 4
    public function getHostName()
742
    {
743 4
        if ($this->_hostName === null) {
744 4
            $this->_hostName = parse_url($this->getHostInfo(), PHP_URL_HOST);
745
        }
746
747 4
        return $this->_hostName;
748
    }
749
750
    private $_baseUrl;
751
752
    /**
753
     * Returns the relative URL for the application.
754
     * This is similar to [[scriptUrl]] except that it does not include the script file name,
755
     * and the ending slashes are removed.
756
     * @return string the relative URL for the application
757
     * @see setScriptUrl()
758
     */
759 238
    public function getBaseUrl()
760
    {
761 238
        if ($this->_baseUrl === null) {
762 237
            $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/');
763
        }
764
765 238
        return $this->_baseUrl;
766
    }
767
768
    /**
769
     * Sets the relative URL for the application.
770
     * By default the URL is determined based on the entry script URL.
771
     * This setter is provided in case you want to change this behavior.
772
     * @param string $value the relative URL for the application
773
     */
774 1
    public function setBaseUrl($value)
775
    {
776 1
        $this->_baseUrl = $value;
777 1
    }
778
779
    private $_scriptUrl;
780
781
    /**
782
     * Returns the relative URL of the entry script.
783
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
784
     * @return string the relative URL of the entry script.
785
     * @throws InvalidConfigException if unable to determine the entry script URL
786
     */
787 239
    public function getScriptUrl()
788
    {
789 239
        if ($this->_scriptUrl === null) {
790 2
            $scriptFile = $this->getScriptFile();
791 1
            $scriptName = basename($scriptFile);
792 1
            if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
793 1
                $this->_scriptUrl = $_SERVER['SCRIPT_NAME'];
794
            } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $scriptName) {
795
                $this->_scriptUrl = $_SERVER['PHP_SELF'];
796
            } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
797
                $this->_scriptUrl = $_SERVER['ORIG_SCRIPT_NAME'];
798
            } elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
799
                $this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
800
            } elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) {
801
                $this->_scriptUrl = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $scriptFile));
802
            } else {
803
                throw new InvalidConfigException('Unable to determine the entry script URL.');
804
            }
805
        }
806
807 238
        return $this->_scriptUrl;
808
    }
809
810
    /**
811
     * Sets the relative URL for the application entry script.
812
     * This setter is provided in case the entry script URL cannot be determined
813
     * on certain Web servers.
814
     * @param string $value the relative URL for the application entry script.
815
     */
816 249
    public function setScriptUrl($value)
817
    {
818 249
        $this->_scriptUrl = $value === null ? null : '/' . trim($value, '/');
819 249
    }
820
821
    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...
822
823
    /**
824
     * Returns the entry script file path.
825
     * The default implementation will simply return `$_SERVER['SCRIPT_FILENAME']`.
826
     * @return string the entry script file path
827
     * @throws InvalidConfigException
828
     */
829 240
    public function getScriptFile()
830
    {
831 240
        if (isset($this->_scriptFile)) {
832 218
            return $this->_scriptFile;
833
        }
834
835 23
        if (isset($_SERVER['SCRIPT_FILENAME'])) {
836 21
            return $_SERVER['SCRIPT_FILENAME'];
837
        }
838
839 2
        throw new InvalidConfigException('Unable to determine the entry script file path.');
840
    }
841
842
    /**
843
     * Sets the entry script file path.
844
     * The entry script file path normally can be obtained from `$_SERVER['SCRIPT_FILENAME']`.
845
     * If your server configuration does not return the correct value, you may configure
846
     * this property to make it right.
847
     * @param string $value the entry script file path.
848
     */
849 218
    public function setScriptFile($value)
850
    {
851 218
        $this->_scriptFile = $value;
852 218
    }
853
854
    private $_pathInfo;
855
856
    /**
857
     * Returns the path info of the currently requested URL.
858
     * A path info refers to the part that is after the entry script and before the question mark (query string).
859
     * The starting and ending slashes are both removed.
860
     * @return string part of the request URL that is after the entry script and before the question mark.
861
     * Note, the returned path info is already URL-decoded.
862
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
863
     */
864 18
    public function getPathInfo()
865
    {
866 18
        if ($this->_pathInfo === null) {
867
            $this->_pathInfo = $this->resolvePathInfo();
868
        }
869
870 18
        return $this->_pathInfo;
871
    }
872
873
    /**
874
     * Sets the path info of the current request.
875
     * This method is mainly provided for testing purpose.
876
     * @param string $value the path info of the current request
877
     */
878 19
    public function setPathInfo($value)
879
    {
880 19
        $this->_pathInfo = $value === null ? null : ltrim($value, '/');
881 19
    }
882
883
    /**
884
     * Resolves the path info part of the currently requested URL.
885
     * A path info refers to the part that is after the entry script and before the question mark (query string).
886
     * The starting slashes are both removed (ending slashes will be kept).
887
     * @return string part of the request URL that is after the entry script and before the question mark.
888
     * Note, the returned path info is decoded.
889
     * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
890
     */
891
    protected function resolvePathInfo()
892
    {
893
        $pathInfo = $this->getUrl();
894
895
        if (($pos = strpos($pathInfo, '?')) !== false) {
896
            $pathInfo = substr($pathInfo, 0, $pos);
897
        }
898
899
        $pathInfo = urldecode($pathInfo);
900
901
        // try to encode in UTF8 if not so
902
        // http://w3.org/International/questions/qa-forms-utf-8.html
903
        if (!preg_match('%^(?:
904
            [\x09\x0A\x0D\x20-\x7E]              # ASCII
905
            | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
906
            | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
907
            | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
908
            | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
909
            | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
910
            | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
911
            | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
912
            )*$%xs', $pathInfo)
913
        ) {
914
            $pathInfo = utf8_encode($pathInfo);
915
        }
916
917
        $scriptUrl = $this->getScriptUrl();
918
        $baseUrl = $this->getBaseUrl();
919
        if (strpos($pathInfo, $scriptUrl) === 0) {
920
            $pathInfo = substr($pathInfo, strlen($scriptUrl));
921
        } elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) {
922
            $pathInfo = substr($pathInfo, strlen($baseUrl));
923
        } elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0) {
924
            $pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
925
        } else {
926
            throw new InvalidConfigException('Unable to determine the path info of the current request.');
927
        }
928
929
        if (substr($pathInfo, 0, 1) === '/') {
930
            $pathInfo = substr($pathInfo, 1);
931
        }
932
933
        return (string) $pathInfo;
934
    }
935
936
    /**
937
     * Returns the currently requested absolute URL.
938
     * This is a shortcut to the concatenation of [[hostInfo]] and [[url]].
939
     * @return string the currently requested absolute URL.
940
     */
941
    public function getAbsoluteUrl()
942
    {
943
        return $this->getHostInfo() . $this->getUrl();
944
    }
945
946
    private $_url;
947
948
    /**
949
     * Returns the currently requested relative URL.
950
     * This refers to the portion of the URL that is after the [[hostInfo]] part.
951
     * It includes the [[queryString]] part if any.
952
     * @return string the currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.
953
     * @throws InvalidConfigException if the URL cannot be determined due to unusual server configuration
954
     */
955 11
    public function getUrl()
956
    {
957 11
        if ($this->_url === null) {
958 3
            $this->_url = $this->resolveRequestUri();
959
        }
960
961 11
        return $this->_url;
962
    }
963
964
    /**
965
     * Sets the currently requested relative URL.
966
     * The URI must refer to the portion that is after [[hostInfo]].
967
     * Note that the URI should be URL-encoded.
968
     * @param string $value the request URI to be set
969
     */
970 23
    public function setUrl($value)
971
    {
972 23
        $this->_url = $value;
973 23
    }
974
975
    /**
976
     * Resolves the request URI portion for the currently requested URL.
977
     * This refers to the portion that is after the [[hostInfo]] part. It includes the [[queryString]] part if any.
978
     * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
979
     * @return string|bool the request URI portion for the currently requested URL.
980
     * Note that the URI returned may be URL-encoded depending on the client.
981
     * @throws InvalidConfigException if the request URI cannot be determined due to unusual server configuration
982
     */
983 3
    protected function resolveRequestUri()
984
    {
985 3
        if ($this->hasHeader('x-rewrite-url')) { // IIS
986
            $requestUri = $this->getHeaderLine('x-rewrite-url');
987 3
        } elseif (isset($_SERVER['REQUEST_URI'])) {
988 3
            $requestUri = $_SERVER['REQUEST_URI'];
989 3
            if ($requestUri !== '' && $requestUri[0] !== '/') {
990 3
                $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
991
            }
992
        } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 CGI
993
            $requestUri = $_SERVER['ORIG_PATH_INFO'];
994
            if (!empty($_SERVER['QUERY_STRING'])) {
995
                $requestUri .= '?' . $_SERVER['QUERY_STRING'];
996
            }
997
        } else {
998
            throw new InvalidConfigException('Unable to determine the request URI.');
999
        }
1000
1001 3
        return $requestUri;
1002
    }
1003
1004
    /**
1005
     * Returns part of the request URL that is after the question mark.
1006
     * @return string part of the request URL that is after the question mark
1007
     */
1008
    public function getQueryString()
1009
    {
1010
        return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
1011
    }
1012
1013
    /**
1014
     * Return if the request is sent via secure channel (https).
1015
     * @return bool if the request is sent via secure channel (https)
1016
     */
1017 13
    public function getIsSecureConnection()
1018
    {
1019 13
        return isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)
1020 13
            || strcasecmp($this->getHeaderLine('x-forwarded-proto'), 'https') === 0;
1021
    }
1022
1023
    /**
1024
     * Returns the server name.
1025
     * @return string server name, null if not available
1026
     */
1027 1
    public function getServerName()
1028
    {
1029 1
        return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
1030
    }
1031
1032
    /**
1033
     * Returns the server port number.
1034
     * @return int|null server port number, null if not available
1035
     */
1036 1
    public function getServerPort()
1037
    {
1038 1
        return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null;
1039
    }
1040
1041
    /**
1042
     * Returns the URL referrer.
1043
     * @return string|null URL referrer, null if not available
1044
     */
1045
    public function getReferrer()
1046
    {
1047
        if (!$this->hasHeader('Referer')) {
1048
            return null;
1049
        }
1050
        return $this->getHeaderLine('Referer');
1051
    }
1052
1053
    /**
1054
     * Returns the URL origin of a CORS request.
1055
     *
1056
     * The return value is taken from the `Origin` [[getHeaders()|header]] sent by the browser.
1057
     *
1058
     * Note that the origin request header indicates where a fetch originates from.
1059
     * It doesn't include any path information, but only the server name.
1060
     * It is sent with a CORS requests, as well as with POST requests.
1061
     * It is similar to the referer header, but, unlike this header, it doesn't disclose the whole path.
1062
     * Please refer to <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin> for more information.
1063
     *
1064
     * @return string|null URL origin of a CORS request, `null` if not available.
1065
     * @see getHeaders()
1066
     * @since 2.0.13
1067
     */
1068
    public function getOrigin()
1069
    {
1070
        return $this->getHeaderLine('origin');
1071
    }
1072
1073
    /**
1074
     * Returns the user agent.
1075
     * @return string|null user agent, null if not available
1076
     */
1077
    public function getUserAgent()
1078
    {
1079
        if (!$this->hasHeader('User-Agent')) {
1080
            return null;
1081
        }
1082
        return $this->getHeaderLine('User-Agent');
1083
    }
1084
1085
    /**
1086
     * Returns the user IP address.
1087
     * @return string|null user IP address, null if not available
1088
     */
1089 27
    public function getUserIP()
1090
    {
1091 27
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
1092
    }
1093
1094
    /**
1095
     * Returns the user host name.
1096
     * @return string|null user host name, null if not available
1097
     */
1098
    public function getUserHost()
1099
    {
1100
        return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
1101
    }
1102
1103
    /**
1104
     * @return string|null the username sent via HTTP authentication, null if the username is not given
1105
     */
1106 10
    public function getAuthUser()
1107
    {
1108 10
        return isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
1109
    }
1110
1111
    /**
1112
     * @return string|null the password sent via HTTP authentication, null if the password is not given
1113
     */
1114 10
    public function getAuthPassword()
1115
    {
1116 10
        return isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
1117
    }
1118
1119
    private $_port;
1120
1121
    /**
1122
     * Returns the port to use for insecure requests.
1123
     * Defaults to 80, or the port specified by the server if the current
1124
     * request is insecure.
1125
     * @return int port number for insecure requests.
1126
     * @see setPort()
1127
     */
1128
    public function getPort()
1129
    {
1130
        if ($this->_port === null) {
1131
            $this->_port = !$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : 80;
1132
        }
1133
1134
        return $this->_port;
1135
    }
1136
1137
    /**
1138
     * Sets the port to use for insecure requests.
1139
     * This setter is provided in case a custom port is necessary for certain
1140
     * server configurations.
1141
     * @param int $value port number.
1142
     */
1143
    public function setPort($value)
1144
    {
1145
        if ($value != $this->_port) {
1146
            $this->_port = (int) $value;
1147
            $this->_hostInfo = null;
1148
        }
1149
    }
1150
1151
    private $_securePort;
1152
1153
    /**
1154
     * Returns the port to use for secure requests.
1155
     * Defaults to 443, or the port specified by the server if the current
1156
     * request is secure.
1157
     * @return int port number for secure requests.
1158
     * @see setSecurePort()
1159
     */
1160
    public function getSecurePort()
1161
    {
1162
        if ($this->_securePort === null) {
1163
            $this->_securePort = $this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : 443;
1164
        }
1165
1166
        return $this->_securePort;
1167
    }
1168
1169
    /**
1170
     * Sets the port to use for secure requests.
1171
     * This setter is provided in case a custom port is necessary for certain
1172
     * server configurations.
1173
     * @param int $value port number.
1174
     */
1175
    public function setSecurePort($value)
1176
    {
1177
        if ($value != $this->_securePort) {
1178
            $this->_securePort = (int) $value;
1179
            $this->_hostInfo = null;
1180
        }
1181
    }
1182
1183
    private $_contentTypes;
1184
1185
    /**
1186
     * Returns the content types acceptable by the end user.
1187
     * This is determined by the `Accept` HTTP header. For example,
1188
     *
1189
     * ```php
1190
     * $_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1191
     * $types = $request->getAcceptableContentTypes();
1192
     * print_r($types);
1193
     * // displays:
1194
     * // [
1195
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1196
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1197
     * //           'text/plain' => ['q' => 0.5],
1198
     * // ]
1199
     * ```
1200
     *
1201
     * @return array the content types ordered by the quality score. Types with the highest scores
1202
     * will be returned first. The array keys are the content types, while the array values
1203
     * are the corresponding quality score and other parameters as given in the header.
1204
     */
1205 2
    public function getAcceptableContentTypes()
1206
    {
1207 2
        if ($this->_contentTypes === null) {
1208 1
            if ($this->hasHeader('Accept')) {
1209
                $this->_contentTypes = $this->parseAcceptHeader($this->getHeaderLine('Accept'));
1210
            } else {
1211 1
                $this->_contentTypes = [];
1212
            }
1213
        }
1214
1215 2
        return $this->_contentTypes;
1216
    }
1217
1218
    /**
1219
     * Sets the acceptable content types.
1220
     * Please refer to [[getAcceptableContentTypes()]] on the format of the parameter.
1221
     * @param array $value the content types that are acceptable by the end user. They should
1222
     * be ordered by the preference level.
1223
     * @see getAcceptableContentTypes()
1224
     * @see parseAcceptHeader()
1225
     */
1226 1
    public function setAcceptableContentTypes($value)
1227
    {
1228 1
        $this->_contentTypes = $value;
1229 1
    }
1230
1231
    /**
1232
     * Returns request content-type
1233
     * The Content-Type header field indicates the MIME type of the data
1234
     * contained in [[getRawBody()]] or, in the case of the HEAD method, the
1235
     * media type that would have been sent had the request been a GET.
1236
     * For the MIME-types the user expects in response, see [[acceptableContentTypes]].
1237
     * @return string request content-type. Empty string is returned if this information is not available.
1238
     * @link https://tools.ietf.org/html/rfc2616#section-14.17
1239
     * HTTP 1.1 header field definitions
1240
     */
1241 2
    public function getContentType()
1242
    {
1243 2
        return $this->getHeaderLine('Content-Type');
1244
    }
1245
1246
    private $_languages;
1247
1248
    /**
1249
     * Returns the languages acceptable by the end user.
1250
     * This is determined by the `Accept-Language` HTTP header.
1251
     * @return array the languages ordered by the preference level. The first element
1252
     * represents the most preferred language.
1253
     */
1254 1
    public function getAcceptableLanguages()
1255
    {
1256 1
        if ($this->_languages === null) {
1257
            if ($this->hasHeader('Accept-Language')) {
1258
                $this->_languages = array_keys($this->parseAcceptHeader($this->getHeaderLine('Accept-Language')));
1259
            } else {
1260
                $this->_languages = [];
1261
            }
1262
        }
1263
1264 1
        return $this->_languages;
1265
    }
1266
1267
    /**
1268
     * @param array $value the languages that are acceptable by the end user. They should
1269
     * be ordered by the preference level.
1270
     */
1271 1
    public function setAcceptableLanguages($value)
1272
    {
1273 1
        $this->_languages = $value;
1274 1
    }
1275
1276
    /**
1277
     * Parses the given `Accept` (or `Accept-Language`) header.
1278
     *
1279
     * This method will return the acceptable values with their quality scores and the corresponding parameters
1280
     * as specified in the given `Accept` header. The array keys of the return value are the acceptable values,
1281
     * while the array values consisting of the corresponding quality scores and parameters. The acceptable
1282
     * values with the highest quality scores will be returned first. For example,
1283
     *
1284
     * ```php
1285
     * $header = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
1286
     * $accepts = $request->parseAcceptHeader($header);
1287
     * print_r($accepts);
1288
     * // displays:
1289
     * // [
1290
     * //     'application/json' => ['q' => 1, 'version' => '1.0'],
1291
     * //      'application/xml' => ['q' => 1, 'version' => '2.0'],
1292
     * //           'text/plain' => ['q' => 0.5],
1293
     * // ]
1294
     * ```
1295
     *
1296
     * @param string $header the header to be parsed
1297
     * @return array the acceptable values ordered by their quality score. The values with the highest scores
1298
     * will be returned first.
1299
     */
1300 1
    public function parseAcceptHeader($header)
1301
    {
1302 1
        $accepts = [];
1303 1
        foreach (explode(',', $header) as $i => $part) {
1304 1
            $params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY);
1305 1
            if (empty($params)) {
1306 1
                continue;
1307
            }
1308
            $values = [
1309 1
                'q' => [$i, array_shift($params), 1],
1310
            ];
1311 1
            foreach ($params as $param) {
1312 1
                if (strpos($param, '=') !== false) {
1313 1
                    [$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...
1314 1
                    if ($key === 'q') {
1315 1
                        $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...
1316
                    } else {
1317 1
                        $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...
1318
                    }
1319
                } else {
1320 1
                    $values[] = $param;
1321
                }
1322
            }
1323 1
            $accepts[] = $values;
1324
        }
1325
1326 1
        usort($accepts, function ($a, $b) {
1327 1
            $a = $a['q']; // index, name, q
1328 1
            $b = $b['q'];
1329 1
            if ($a[2] > $b[2]) {
1330 1
                return -1;
1331
            }
1332
1333 1
            if ($a[2] < $b[2]) {
1334 1
                return 1;
1335
            }
1336
1337 1
            if ($a[1] === $b[1]) {
1338
                return $a[0] > $b[0] ? 1 : -1;
1339
            }
1340
1341 1
            if ($a[1] === '*/*') {
1342
                return 1;
1343
            }
1344
1345 1
            if ($b[1] === '*/*') {
1346
                return -1;
1347
            }
1348
1349 1
            $wa = $a[1][strlen($a[1]) - 1] === '*';
1350 1
            $wb = $b[1][strlen($b[1]) - 1] === '*';
1351 1
            if ($wa xor $wb) {
1352
                return $wa ? 1 : -1;
1353
            }
1354
1355 1
            return $a[0] > $b[0] ? 1 : -1;
1356 1
        });
1357
1358 1
        $result = [];
1359 1
        foreach ($accepts as $accept) {
1360 1
            $name = $accept['q'][1];
1361 1
            $accept['q'] = $accept['q'][2];
1362 1
            $result[$name] = $accept;
1363
        }
1364
1365 1
        return $result;
1366
    }
1367
1368
    /**
1369
     * Returns the user-preferred language that should be used by this application.
1370
     * The language resolution is based on the user preferred languages and the languages
1371
     * supported by the application. The method will try to find the best match.
1372
     * @param array $languages a list of the languages supported by the application. If this is empty, the current
1373
     * application language will be returned without further processing.
1374
     * @return string the language that the application should use.
1375
     */
1376 1
    public function getPreferredLanguage(array $languages = [])
1377
    {
1378 1
        if (empty($languages)) {
1379 1
            return Yii::$app->language;
1380
        }
1381 1
        foreach ($this->getAcceptableLanguages() as $acceptableLanguage) {
1382 1
            $acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
1383 1
            foreach ($languages as $language) {
1384 1
                $normalizedLanguage = str_replace('_', '-', strtolower($language));
1385
1386
                if (
1387 1
                    $normalizedLanguage === $acceptableLanguage // en-us==en-us
1388 1
                    || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us
1389 1
                    || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en
1390
                ) {
1391 1
                    return $language;
1392
                }
1393
            }
1394
        }
1395
1396 1
        return reset($languages);
1397
    }
1398
1399
    /**
1400
     * Gets the Etags.
1401
     *
1402
     * @return array The entity tags
1403
     */
1404
    public function getETags()
1405
    {
1406
        if ($this->hasHeader('if-none-match')) {
1407
            return preg_split('/[\s,]+/', str_replace('-gzip', '', $this->getHeaderLine('if-none-match')), -1, PREG_SPLIT_NO_EMPTY);
1408
        }
1409
1410
        return [];
1411
    }
1412
1413
    /**
1414
     * Returns the cookie collection.
1415
     * Through the returned cookie collection, you may access a cookie using the following syntax:
1416
     *
1417
     * ```php
1418
     * $cookie = $request->cookies['name']
1419
     * if ($cookie !== null) {
1420
     *     $value = $cookie->value;
1421
     * }
1422
     *
1423
     * // alternatively
1424
     * $value = $request->cookies->getValue('name');
1425
     * ```
1426
     *
1427
     * @return CookieCollection the cookie collection.
1428
     */
1429 32
    public function getCookies()
1430
    {
1431 32
        if ($this->_cookies === null) {
1432 32
            $this->_cookies = new CookieCollection($this->loadCookies(), [
1433 32
                'readOnly' => true,
1434
            ]);
1435
        }
1436
1437 32
        return $this->_cookies;
1438
    }
1439
1440
    /**
1441
     * Converts `$_COOKIE` into an array of [[Cookie]].
1442
     * @return array the cookies obtained from request
1443
     * @throws InvalidConfigException if [[cookieValidationKey]] is not set when [[enableCookieValidation]] is true
1444
     */
1445 32
    protected function loadCookies()
1446
    {
1447 32
        $cookies = [];
1448 32
        if ($this->enableCookieValidation) {
1449 31
            if ($this->cookieValidationKey == '') {
1450
                throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
1451
            }
1452 31
            foreach ($_COOKIE as $name => $value) {
1453
                if (!is_string($value)) {
1454
                    continue;
1455
                }
1456
                $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
1457
                if ($data === false) {
1458
                    continue;
1459
                }
1460
                $data = @unserialize($data);
1461
                if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
1462
                    $cookies[$name] = new Cookie([
1463 31
                        'name' => $name,
1464
                        'value' => $data[1],
1465
                        'expire' => null,
1466
                    ]);
1467
                }
1468
            }
1469
        } else {
1470 1
            foreach ($_COOKIE as $name => $value) {
1471
                $cookies[$name] = new Cookie([
1472
                    'name' => $name,
1473
                    'value' => $value,
1474
                    'expire' => null,
1475
                ]);
1476
            }
1477
        }
1478
1479 32
        return $cookies;
1480
    }
1481
1482
    private $_csrfToken;
1483
1484
    /**
1485
     * Returns the token used to perform CSRF validation.
1486
     *
1487
     * This token is generated in a way to prevent [BREACH attacks](http://breachattack.com/). It may be passed
1488
     * along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.
1489
     * @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time
1490
     * this method is called, a new CSRF token will be generated and persisted (in session or cookie).
1491
     * @return string the token used to perform CSRF validation.
1492
     */
1493 35
    public function getCsrfToken($regenerate = false)
1494
    {
1495 35
        if ($this->_csrfToken === null || $regenerate) {
1496 35
            if ($regenerate || ($token = $this->loadCsrfToken()) === null) {
1497 34
                $token = $this->generateCsrfToken();
1498
            }
1499 35
            $this->_csrfToken = Yii::$app->security->maskToken($token);
1500
        }
1501
1502 35
        return $this->_csrfToken;
1503
    }
1504
1505
    /**
1506
     * Loads the CSRF token from cookie or session.
1507
     * @return string the CSRF token loaded from cookie or session. Null is returned if the cookie or session
1508
     * does not have CSRF token.
1509
     */
1510 35
    protected function loadCsrfToken()
1511
    {
1512 35
        if ($this->enableCsrfCookie) {
1513 32
            return $this->getCookies()->getValue($this->csrfParam);
1514
        }
1515 3
        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...
1516
    }
1517
1518
    /**
1519
     * Generates an unmasked random token used to perform CSRF validation.
1520
     * @return string the random token for CSRF validation.
1521
     */
1522 34
    protected function generateCsrfToken()
1523
    {
1524 34
        $token = Yii::$app->getSecurity()->generateRandomKey();
1525 34
        if ($this->enableCsrfCookie) {
1526 32
            $cookie = $this->createCsrfCookie($token);
1527 32
            Yii::$app->getResponse()->getCookies()->add($cookie);
1528
        } else {
1529 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...
1530
        }
1531 34
        return $token;
1532
    }
1533
1534
    /**
1535
     * @return string the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent.
1536
     */
1537 3
    public function getCsrfTokenFromHeader()
1538
    {
1539 3
        return $this->getHeaderLine(static::CSRF_HEADER);
1540
    }
1541
1542
    /**
1543
     * Creates a cookie with a randomly generated CSRF token.
1544
     * Initial values specified in [[csrfCookie]] will be applied to the generated cookie.
1545
     * @param string $token the CSRF token
1546
     * @return Cookie the generated cookie
1547
     * @see enableCsrfValidation
1548
     */
1549 32
    protected function createCsrfCookie($token)
1550
    {
1551 32
        $options = $this->csrfCookie;
1552 32
        $options['name'] = $this->csrfParam;
1553 32
        $options['value'] = $token;
1554 32
        return new Cookie($options);
1555
    }
1556
1557
    /**
1558
     * Performs the CSRF validation.
1559
     *
1560
     * This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session.
1561
     * This method is mainly called in [[Controller::beforeAction()]].
1562
     *
1563
     * Note that the method will NOT perform CSRF validation if [[enableCsrfValidation]] is false or the HTTP method
1564
     * is among GET, HEAD or OPTIONS.
1565
     *
1566
     * @param string $clientSuppliedToken the user-provided CSRF token to be validated. If null, the token will be retrieved from
1567
     * the [[csrfParam]] POST field or HTTP header.
1568
     * This parameter is available since version 2.0.4.
1569
     * @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.
1570
     */
1571 4
    public function validateCsrfToken($clientSuppliedToken = null)
1572
    {
1573 4
        $method = $this->getMethod();
1574
        // only validate CSRF token on non-"safe" methods https://tools.ietf.org/html/rfc2616#section-9.1.1
1575 4
        if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
1576 4
            return true;
1577
        }
1578
1579
1580 3
        $trueToken = $this->getCsrfToken();
1581
1582 3
        if ($clientSuppliedToken !== null) {
1583 1
            return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken);
1584
        }
1585
1586 3
        return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
1587 3
            || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
1588
    }
1589
1590
    /**
1591
     * Validates CSRF token
1592
     *
1593
     * @param string $clientSuppliedToken The masked client-supplied token.
1594
     * @param string $trueToken The masked true token.
1595
     * @return bool
1596
     */
1597 3
    private function validateCsrfTokenInternal($clientSuppliedToken, $trueToken)
1598
    {
1599 3
        if (!is_string($clientSuppliedToken)) {
1600 3
            return false;
1601
        }
1602
1603 3
        $security = Yii::$app->security;
1604
1605 3
        return $security->unmaskToken($clientSuppliedToken) === $security->unmaskToken($trueToken);
1606
    }
1607
1608
    /**
1609
     * {@inheritdoc}
1610
     */
1611 1
    public function __clone()
1612
    {
1613 1
        parent::__clone();
1614
1615 1
        $this->cloneHttpMessageInternals();
1616
1617 1
        if (is_object($this->_cookies)) {
1618
            $this->_cookies = clone $this->_cookies;
1619
        }
1620 1
    }
1621
}
1622