Completed
Push — 2.1 ( 5c7bdb...e70364 )
by
unknown
11:17 queued 21s
created

Request::setUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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