1 | <?php |
||
2 | /** |
||
3 | * @link https://www.yiiframework.com/ |
||
4 | * @copyright Copyright (c) 2008 Yii Software LLC |
||
5 | * @license https://www.yiiframework.com/license/ |
||
6 | */ |
||
7 | |||
8 | namespace yii\web; |
||
9 | |||
10 | use Yii; |
||
11 | use yii\base\InvalidConfigException; |
||
12 | use yii\validators\IpValidator; |
||
13 | |||
14 | /** |
||
15 | * The web Request class represents an HTTP request. |
||
16 | * |
||
17 | * It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers. |
||
18 | * Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST |
||
19 | * parameters sent via other HTTP methods like PUT or DELETE. |
||
20 | * |
||
21 | * Request is configured as an application component in [[\yii\web\Application]] by default. |
||
22 | * You can access that instance via `Yii::$app->request`. |
||
23 | * |
||
24 | * For more details and usage information on Request, see the [guide article on requests](guide:runtime-requests). |
||
25 | * |
||
26 | * @property-read string $absoluteUrl The currently requested absolute URL. |
||
27 | * @property array $acceptableContentTypes The content types ordered by the quality score. Types with the |
||
28 | * highest scores will be returned first. The array keys are the content types, while the array values are the |
||
29 | * corresponding quality score and other parameters as given in the header. |
||
30 | * @property array $acceptableLanguages The languages ordered by the preference level. The first element |
||
31 | * represents the most preferred language. |
||
32 | * @property-read array $authCredentials That contains exactly two elements: - 0: the username sent via HTTP |
||
33 | * authentication, `null` if the username is not given - 1: the password sent via HTTP authentication, `null` if |
||
34 | * the password is not given. |
||
35 | * @property-read string|null $authPassword The password sent via HTTP authentication, `null` if the password |
||
36 | * is not given. |
||
37 | * @property-read string|null $authUser The username sent via HTTP authentication, `null` if the username is |
||
38 | * not given. |
||
39 | * @property string $baseUrl The relative URL for the application. |
||
40 | * @property array|object $bodyParams The request parameters given in the request body. |
||
41 | * @property-read string $contentType Request content-type. Empty string is returned if this information is |
||
42 | * not available. |
||
43 | * @property-read CookieCollection $cookies The cookie collection. |
||
44 | * @property-read string $csrfToken The token used to perform CSRF validation. |
||
45 | * @property-read string|null $csrfTokenFromHeader The CSRF token sent via [[CSRF_HEADER]] by browser. Null is |
||
46 | * returned if no such header is sent. |
||
47 | * @property-read array $eTags The entity tags. |
||
48 | * @property-read HeaderCollection $headers The header collection. |
||
49 | * @property string|null $hostInfo Schema and hostname part (with port number if needed) of the request URL |
||
50 | * (e.g. `https://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. See |
||
51 | * [[getHostInfo()]] for security related notes on this property. |
||
52 | * @property-read string|null $hostName Hostname part of the request URL (e.g. `www.yiiframework.com`). |
||
53 | * @property-read bool $isAjax Whether this is an AJAX (XMLHttpRequest) request. |
||
54 | * @property-read bool $isDelete Whether this is a DELETE request. |
||
55 | * @property-read bool $isFlash Whether this is an Adobe Flash or Adobe Flex request. |
||
56 | * @property-read bool $isGet Whether this is a GET request. |
||
57 | * @property-read bool $isHead Whether this is a HEAD request. |
||
58 | * @property-read bool $isOptions Whether this is a OPTIONS request. |
||
59 | * @property-read bool $isPatch Whether this is a PATCH request. |
||
60 | * @property-read bool $isPjax Whether this is a PJAX request. |
||
61 | * @property-read bool $isPost Whether this is a POST request. |
||
62 | * @property-read bool $isPut Whether this is a PUT request. |
||
63 | * @property-read bool $isSecureConnection If the request is sent via secure channel (https). |
||
64 | * @property-read string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value |
||
65 | * returned is turned into upper case. |
||
66 | * @property-read string|null $origin URL origin of a CORS request, `null` if not available. |
||
67 | * @property string $pathInfo Part of the request URL that is after the entry script and before the question |
||
68 | * mark. Note, the returned path info is already URL-decoded. |
||
69 | * @property int $port Port number for insecure requests. |
||
70 | * @property array $queryParams The request GET parameter values. |
||
71 | * @property-read string $queryString Part of the request URL that is after the question mark. |
||
72 | * @property string $rawBody The request body. |
||
73 | * @property-read string|null $referrer URL referrer, null if not available. |
||
74 | * @property-read string|null $remoteHost Remote host name, `null` if not available. |
||
75 | * @property-read string|null $remoteIP Remote IP address, `null` if not available. |
||
76 | * @property string $scriptFile The entry script file path. |
||
77 | * @property string $scriptUrl The relative URL of the entry script. |
||
78 | * @property int $securePort Port number for secure requests. |
||
79 | * @property-read string|null $serverName Server name, null if not available. |
||
80 | * @property-read int|null $serverPort Server port number, null if not available. |
||
81 | * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded |
||
82 | * depending on the client. |
||
83 | * @property-read string|null $userAgent User agent, null if not available. |
||
84 | * @property-read string|null $userHost User host name, null if not available. |
||
85 | * @property-read string|null $userIP User IP address, null if not available. |
||
86 | * |
||
87 | * @author Qiang Xue <[email protected]> |
||
88 | * @since 2.0 |
||
89 | * @SuppressWarnings(PHPMD.SuperGlobals) |
||
90 | */ |
||
91 | class Request extends \yii\base\Request |
||
92 | { |
||
93 | /** |
||
94 | * The name of the HTTP header for sending CSRF token. |
||
95 | */ |
||
96 | const CSRF_HEADER = 'X-CSRF-Token'; |
||
97 | /** |
||
98 | * The length of the CSRF token mask. |
||
99 | * @deprecated since 2.0.12. The mask length is now equal to the token length. |
||
100 | */ |
||
101 | const CSRF_MASK_LENGTH = 8; |
||
102 | |||
103 | /** |
||
104 | * @var bool whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true. |
||
105 | * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated |
||
106 | * from the same application. If not, a 400 HTTP exception will be raised. |
||
107 | * |
||
108 | * Note, this feature requires that the user client accepts cookie. Also, to use this feature, |
||
109 | * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfParam]]. |
||
110 | * You may use [[\yii\helpers\Html::beginForm()]] to generate his hidden input. |
||
111 | * |
||
112 | * In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and |
||
113 | * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered. |
||
114 | * You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]]. |
||
115 | * |
||
116 | * @see Controller::enableCsrfValidation |
||
117 | * @see https://en.wikipedia.org/wiki/Cross-site_request_forgery |
||
118 | */ |
||
119 | public $enableCsrfValidation = true; |
||
120 | /** |
||
121 | * @var string the name of the token used to prevent CSRF. Defaults to '_csrf'. |
||
122 | * This property is used only when [[enableCsrfValidation]] is true. |
||
123 | */ |
||
124 | public $csrfParam = '_csrf'; |
||
125 | /** |
||
126 | * @var array the configuration for creating the CSRF [[Cookie|cookie]]. This property is used only when |
||
127 | * both [[enableCsrfValidation]] and [[enableCsrfCookie]] are true. |
||
128 | */ |
||
129 | public $csrfCookie = ['httpOnly' => true]; |
||
130 | /** |
||
131 | * @var bool whether to use cookie to persist CSRF token. If false, CSRF token will be stored |
||
132 | * in session under the name of [[csrfParam]]. Note that while storing CSRF tokens in session increases |
||
133 | * security, it requires starting a session for every page, which will degrade your site performance. |
||
134 | */ |
||
135 | public $enableCsrfCookie = true; |
||
136 | /** |
||
137 | * @var bool whether cookies should be validated to ensure they are not tampered. Defaults to true. |
||
138 | */ |
||
139 | public $enableCookieValidation = true; |
||
140 | /** |
||
141 | * @var string a secret key used for cookie validation. This property must be set if [[enableCookieValidation]] is true. |
||
142 | */ |
||
143 | public $cookieValidationKey; |
||
144 | /** |
||
145 | * @var string the name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE |
||
146 | * request tunneled through POST. Defaults to '_method'. |
||
147 | * @see getMethod() |
||
148 | * @see getBodyParams() |
||
149 | */ |
||
150 | public $methodParam = '_method'; |
||
151 | /** |
||
152 | * @var array the parsers for converting the raw HTTP request body into [[bodyParams]]. |
||
153 | * The array keys are the request `Content-Types`, and the array values are the |
||
154 | * corresponding configurations for [[Yii::createObject|creating the parser objects]]. |
||
155 | * A parser must implement the [[RequestParserInterface]]. |
||
156 | * |
||
157 | * To enable parsing for JSON requests you can use the [[JsonParser]] class like in the following example: |
||
158 | * |
||
159 | * ``` |
||
160 | * [ |
||
161 | * 'application/json' => 'yii\web\JsonParser', |
||
162 | * ] |
||
163 | * ``` |
||
164 | * |
||
165 | * To register a parser for parsing all request types you can use `'*'` as the array key. |
||
166 | * This one will be used as a fallback in case no other types match. |
||
167 | * |
||
168 | * @see getBodyParams() |
||
169 | */ |
||
170 | public $parsers = []; |
||
171 | /** |
||
172 | * @var array the configuration for trusted security related headers. |
||
173 | * |
||
174 | * An array key is an IPv4 or IPv6 IP address in CIDR notation for matching a client. |
||
175 | * |
||
176 | * An array value is a list of headers to trust. These will be matched against |
||
177 | * [[secureHeaders]] to determine which headers are allowed to be sent by a specified host. |
||
178 | * The case of the header names must be the same as specified in [[secureHeaders]]. |
||
179 | * |
||
180 | * For example, to trust all headers listed in [[secureHeaders]] for IP addresses |
||
181 | * in range `192.168.0.0-192.168.0.254` write the following: |
||
182 | * |
||
183 | * ```php |
||
184 | * [ |
||
185 | * '192.168.0.0/24', |
||
186 | * ] |
||
187 | * ``` |
||
188 | * |
||
189 | * To trust just the `X-Forwarded-For` header from `10.0.0.1`, use: |
||
190 | * |
||
191 | * ``` |
||
192 | * [ |
||
193 | * '10.0.0.1' => ['X-Forwarded-For'] |
||
194 | * ] |
||
195 | * ``` |
||
196 | * |
||
197 | * Default is to trust all headers except those listed in [[secureHeaders]] from all hosts. |
||
198 | * Matches are tried in order and searching is stopped when IP matches. |
||
199 | * |
||
200 | * > Info: Matching is performed using [[IpValidator]]. |
||
201 | * See [[IpValidator::::setRanges()|IpValidator::setRanges()]] |
||
202 | * and [[IpValidator::networks]] for advanced matching. |
||
203 | * |
||
204 | * @see secureHeaders |
||
205 | * @since 2.0.13 |
||
206 | */ |
||
207 | public $trustedHosts = []; |
||
208 | /** |
||
209 | * @var array lists of headers that are, by default, subject to the trusted host configuration. |
||
210 | * These headers will be filtered unless explicitly allowed in [[trustedHosts]]. |
||
211 | * If the list contains the `Forwarded` header, processing will be done according to RFC 7239. |
||
212 | * The match of header names is case-insensitive. |
||
213 | * @see https://en.wikipedia.org/wiki/List_of_HTTP_header_fields |
||
214 | * @see https://datatracker.ietf.org/doc/html/rfc7239 |
||
215 | * @see trustedHosts |
||
216 | * @since 2.0.13 |
||
217 | */ |
||
218 | public $secureHeaders = [ |
||
219 | // Common: |
||
220 | 'X-Forwarded-For', |
||
221 | 'X-Forwarded-Host', |
||
222 | 'X-Forwarded-Proto', |
||
223 | 'X-Forwarded-Port', |
||
224 | |||
225 | // Microsoft: |
||
226 | 'Front-End-Https', |
||
227 | 'X-Rewrite-Url', |
||
228 | |||
229 | // ngrok: |
||
230 | 'X-Original-Host', |
||
231 | ]; |
||
232 | /** |
||
233 | * @var string[] List of headers where proxies store the real client IP. |
||
234 | * It's not advisable to put insecure headers here. |
||
235 | * To use the `Forwarded` header according to RFC 7239, the header must be added to [[secureHeaders]] list. |
||
236 | * The match of header names is case-insensitive. |
||
237 | * @see trustedHosts |
||
238 | * @see secureHeaders |
||
239 | * @since 2.0.13 |
||
240 | */ |
||
241 | public $ipHeaders = [ |
||
242 | 'X-Forwarded-For', // Common |
||
243 | ]; |
||
244 | /** |
||
245 | * @var string[] List of headers where proxies store the real request port. |
||
246 | * It's not advisable to put insecure headers here. |
||
247 | * To use the `Forwarded Port`, the header must be added to [[secureHeaders]] list. |
||
248 | * The match of header names is case-insensitive. |
||
249 | * @see trustedHosts |
||
250 | * @see secureHeaders |
||
251 | * @since 2.0.46 |
||
252 | */ |
||
253 | public $portHeaders = [ |
||
254 | 'X-Forwarded-Port', // Common |
||
255 | ]; |
||
256 | /** |
||
257 | * @var array list of headers to check for determining whether the connection is made via HTTPS. |
||
258 | * The array keys are header names and the array value is a list of header values that indicate a secure connection. |
||
259 | * The match of header names and values is case-insensitive. |
||
260 | * It's not advisable to put insecure headers here. |
||
261 | * @see trustedHosts |
||
262 | * @see secureHeaders |
||
263 | * @since 2.0.13 |
||
264 | */ |
||
265 | public $secureProtocolHeaders = [ |
||
266 | 'X-Forwarded-Proto' => ['https'], // Common |
||
267 | 'Front-End-Https' => ['on'], // Microsoft |
||
268 | ]; |
||
269 | |||
270 | /** |
||
271 | * @var CookieCollection Collection of request cookies. |
||
272 | */ |
||
273 | private $_cookies; |
||
274 | /** |
||
275 | * @var HeaderCollection Collection of request headers. |
||
276 | */ |
||
277 | private $_headers; |
||
278 | |||
279 | |||
280 | /** |
||
281 | * Resolves the current request into a route and the associated parameters. |
||
282 | * @return array the first element is the route, and the second is the associated parameters. |
||
283 | * @throws NotFoundHttpException if the request cannot be resolved. |
||
284 | */ |
||
285 | 1 | public function resolve() |
|
286 | { |
||
287 | 1 | $result = Yii::$app->getUrlManager()->parseRequest($this); |
|
288 | 1 | if ($result !== false) { |
|
289 | 1 | list($route, $params) = $result; |
|
290 | 1 | if ($this->_queryParams === null) { |
|
291 | 1 | $_GET = $params + $_GET; // preserve numeric keys |
|
292 | } else { |
||
293 | 1 | $this->_queryParams = $params + $this->_queryParams; |
|
294 | } |
||
295 | |||
296 | 1 | return [$route, $this->getQueryParams()]; |
|
297 | } |
||
298 | |||
299 | throw new NotFoundHttpException(Yii::t('yii', 'Page not found.')); |
||
300 | } |
||
301 | |||
302 | /** |
||
303 | * Filters headers according to the [[trustedHosts]]. |
||
304 | * @param HeaderCollection $headerCollection |
||
305 | * @since 2.0.13 |
||
306 | */ |
||
307 | 265 | protected function filterHeaders(HeaderCollection $headerCollection) |
|
308 | { |
||
309 | 265 | $trustedHeaders = $this->getTrustedHeaders(); |
|
310 | |||
311 | // remove all secure headers unless they are trusted |
||
312 | 265 | foreach ($this->secureHeaders as $secureHeader) { |
|
313 | 265 | if (!in_array($secureHeader, $trustedHeaders)) { |
|
314 | 245 | $headerCollection->remove($secureHeader); |
|
315 | } |
||
316 | } |
||
317 | 265 | } |
|
318 | |||
319 | /** |
||
320 | * Trusted headers according to the [[trustedHosts]]. |
||
321 | * @return array |
||
322 | * @since 2.0.28 |
||
323 | */ |
||
324 | 265 | protected function getTrustedHeaders() |
|
325 | { |
||
326 | // do not trust any of the [[secureHeaders]] by default |
||
327 | 265 | $trustedHeaders = []; |
|
328 | |||
329 | // check if the client is a trusted host |
||
330 | 265 | if (!empty($this->trustedHosts)) { |
|
331 | 77 | $validator = $this->getIpValidator(); |
|
332 | 77 | $ip = $this->getRemoteIP(); |
|
333 | 77 | foreach ($this->trustedHosts as $cidr => $headers) { |
|
334 | 77 | if (!is_array($headers)) { |
|
335 | 75 | $cidr = $headers; |
|
336 | 75 | $headers = $this->secureHeaders; |
|
337 | } |
||
338 | 77 | $validator->setRanges($cidr); |
|
339 | 77 | if ($validator->validate($ip)) { |
|
340 | 40 | $trustedHeaders = $headers; |
|
341 | 40 | break; |
|
342 | } |
||
343 | } |
||
344 | } |
||
345 | 265 | return $trustedHeaders; |
|
346 | } |
||
347 | |||
348 | /** |
||
349 | * Creates instance of [[IpValidator]]. |
||
350 | * You can override this method to adjust validator or implement different matching strategy. |
||
351 | * |
||
352 | * @return IpValidator |
||
353 | * @since 2.0.13 |
||
354 | */ |
||
355 | 170 | protected function getIpValidator() |
|
356 | { |
||
357 | 170 | return new IpValidator(); |
|
358 | } |
||
359 | |||
360 | /** |
||
361 | * Returns the header collection. |
||
362 | * The header collection contains incoming HTTP headers. |
||
363 | * @return HeaderCollection the header collection |
||
364 | */ |
||
365 | 265 | public function getHeaders() |
|
366 | { |
||
367 | 265 | if ($this->_headers === null) { |
|
368 | 265 | $this->_headers = new HeaderCollection(); |
|
369 | 265 | if (function_exists('getallheaders')) { |
|
370 | $headers = getallheaders(); |
||
371 | foreach ($headers as $name => $value) { |
||
372 | $this->_headers->add($name, $value); |
||
373 | } |
||
374 | 265 | } elseif (function_exists('http_get_request_headers')) { |
|
375 | $headers = http_get_request_headers(); |
||
376 | foreach ($headers as $name => $value) { |
||
377 | $this->_headers->add($name, $value); |
||
378 | } |
||
379 | } else { |
||
380 | // ['prefix' => length] |
||
381 | 265 | $headerPrefixes = ['HTTP_' => 5, 'REDIRECT_HTTP_' => 14]; |
|
382 | |||
383 | 265 | foreach ($_SERVER as $name => $value) { |
|
384 | 261 | foreach ($headerPrefixes as $prefix => $length) { |
|
385 | 261 | if (strncmp($name, $prefix, $length) === 0) { |
|
386 | 115 | $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, $length))))); |
|
387 | 115 | $this->_headers->add($name, $value); |
|
388 | 115 | continue 2; |
|
389 | } |
||
390 | } |
||
391 | } |
||
392 | } |
||
393 | 265 | $this->filterHeaders($this->_headers); |
|
394 | } |
||
395 | |||
396 | 265 | return $this->_headers; |
|
397 | } |
||
398 | |||
399 | /** |
||
400 | * Returns the method of the current request (e.g. GET, POST, HEAD, PUT, PATCH, DELETE). |
||
401 | * @return string request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. |
||
402 | * The value returned is turned into upper case. |
||
403 | */ |
||
404 | 43 | public function getMethod() |
|
405 | { |
||
406 | if ( |
||
407 | 43 | isset($_POST[$this->methodParam]) |
|
408 | // Never allow to downgrade request from WRITE methods (POST, PATCH, DELETE, etc) |
||
409 | // to read methods (GET, HEAD, OPTIONS) for security reasons. |
||
410 | 43 | && !in_array(strtoupper($_POST[$this->methodParam]), ['GET', 'HEAD', 'OPTIONS'], true) |
|
411 | ) { |
||
412 | 6 | return strtoupper($_POST[$this->methodParam]); |
|
413 | } |
||
414 | |||
415 | 41 | if ($this->headers->has('X-Http-Method-Override')) { |
|
416 | 1 | return strtoupper($this->headers->get('X-Http-Method-Override')); |
|
417 | } |
||
418 | |||
419 | 40 | if (isset($_SERVER['REQUEST_METHOD'])) { |
|
420 | 10 | return strtoupper($_SERVER['REQUEST_METHOD']); |
|
421 | } |
||
422 | |||
423 | 31 | return 'GET'; |
|
424 | } |
||
425 | |||
426 | /** |
||
427 | * Returns whether this is a GET request. |
||
428 | * @return bool whether this is a GET request. |
||
429 | */ |
||
430 | 2 | public function getIsGet() |
|
431 | { |
||
432 | 2 | return $this->getMethod() === 'GET'; |
|
433 | } |
||
434 | |||
435 | /** |
||
436 | * Returns whether this is an OPTIONS request. |
||
437 | * @return bool whether this is a OPTIONS request. |
||
438 | */ |
||
439 | 3 | public function getIsOptions() |
|
440 | { |
||
441 | 3 | return $this->getMethod() === 'OPTIONS'; |
|
442 | } |
||
443 | |||
444 | /** |
||
445 | * Returns whether this is a HEAD request. |
||
446 | * @return bool whether this is a HEAD request. |
||
447 | */ |
||
448 | 15 | public function getIsHead() |
|
449 | { |
||
450 | 15 | return $this->getMethod() === 'HEAD'; |
|
451 | } |
||
452 | |||
453 | /** |
||
454 | * Returns whether this is a POST request. |
||
455 | * @return bool whether this is a POST request. |
||
456 | */ |
||
457 | public function getIsPost() |
||
458 | { |
||
459 | return $this->getMethod() === 'POST'; |
||
460 | } |
||
461 | |||
462 | /** |
||
463 | * Returns whether this is a DELETE request. |
||
464 | * @return bool whether this is a DELETE request. |
||
465 | */ |
||
466 | public function getIsDelete() |
||
467 | { |
||
468 | return $this->getMethod() === 'DELETE'; |
||
469 | } |
||
470 | |||
471 | /** |
||
472 | * Returns whether this is a PUT request. |
||
473 | * @return bool whether this is a PUT request. |
||
474 | */ |
||
475 | public function getIsPut() |
||
476 | { |
||
477 | return $this->getMethod() === 'PUT'; |
||
478 | } |
||
479 | |||
480 | /** |
||
481 | * Returns whether this is a PATCH request. |
||
482 | * @return bool whether this is a PATCH request. |
||
483 | */ |
||
484 | public function getIsPatch() |
||
485 | { |
||
486 | return $this->getMethod() === 'PATCH'; |
||
487 | } |
||
488 | |||
489 | /** |
||
490 | * Returns whether this is an AJAX (XMLHttpRequest) request. |
||
491 | * |
||
492 | * Note that in case of cross domain requests, browser doesn't set the X-Requested-With header by default: |
||
493 | * https://stackoverflow.com/questions/8163703/cross-domain-ajax-doesnt-send-x-requested-with-header |
||
494 | * |
||
495 | * In case you are using `fetch()`, pass header manually: |
||
496 | * |
||
497 | * ``` |
||
498 | * fetch(url, { |
||
499 | * method: 'GET', |
||
500 | * headers: {'X-Requested-With': 'XMLHttpRequest'} |
||
501 | * }) |
||
502 | * ``` |
||
503 | * |
||
504 | * @return bool whether this is an AJAX (XMLHttpRequest) request. |
||
505 | */ |
||
506 | 16 | public function getIsAjax() |
|
507 | { |
||
508 | 16 | return $this->headers->get('X-Requested-With') === 'XMLHttpRequest'; |
|
509 | } |
||
510 | |||
511 | /** |
||
512 | * Returns whether this is a PJAX request. |
||
513 | * @return bool whether this is a PJAX request |
||
514 | */ |
||
515 | 3 | public function getIsPjax() |
|
516 | { |
||
517 | 3 | return $this->getIsAjax() && $this->headers->has('X-Pjax'); |
|
518 | } |
||
519 | |||
520 | /** |
||
521 | * Returns whether this is an Adobe Flash or Flex request. |
||
522 | * @return bool whether this is an Adobe Flash or Adobe Flex request. |
||
523 | */ |
||
524 | public function getIsFlash() |
||
525 | { |
||
526 | $userAgent = $this->headers->get('User-Agent', ''); |
||
527 | return stripos($userAgent, 'Shockwave') !== false |
||
528 | || stripos($userAgent, 'Flash') !== false; |
||
529 | } |
||
530 | |||
531 | private $_rawBody; |
||
532 | |||
533 | /** |
||
534 | * Returns the raw HTTP request body. |
||
535 | * @return string the request body |
||
536 | */ |
||
537 | 7 | public function getRawBody() |
|
538 | { |
||
539 | 7 | if ($this->_rawBody === null) { |
|
540 | 4 | $this->_rawBody = file_get_contents('php://input'); |
|
541 | } |
||
542 | |||
543 | 7 | return $this->_rawBody; |
|
544 | } |
||
545 | |||
546 | /** |
||
547 | * Sets the raw HTTP request body, this method is mainly used by test scripts to simulate raw HTTP requests. |
||
548 | * @param string $rawBody the request body |
||
549 | */ |
||
550 | 3 | public function setRawBody($rawBody) |
|
551 | { |
||
552 | 3 | $this->_rawBody = $rawBody; |
|
553 | 3 | } |
|
554 | |||
555 | private $_bodyParams; |
||
556 | |||
557 | /** |
||
558 | * Returns the request parameters given in the request body. |
||
559 | * |
||
560 | * Request parameters are determined using the parsers configured in [[parsers]] property. |
||
561 | * If no parsers are configured for the current [[contentType]] it uses the PHP function `mb_parse_str()` |
||
562 | * to parse the [[rawBody|request body]]. |
||
563 | * @return array|object the request parameters given in the request body. |
||
564 | * @throws \yii\base\InvalidConfigException if a registered parser does not implement the [[RequestParserInterface]]. |
||
565 | * @see getMethod() |
||
566 | * @see getBodyParam() |
||
567 | * @see setBodyParams() |
||
568 | */ |
||
569 | 16 | public function getBodyParams() |
|
570 | { |
||
571 | 16 | if ($this->_bodyParams === null) { |
|
572 | 8 | if (isset($_POST[$this->methodParam])) { |
|
573 | 1 | $this->_bodyParams = $_POST; |
|
574 | 1 | unset($this->_bodyParams[$this->methodParam]); |
|
575 | 1 | return $this->_bodyParams; |
|
576 | } |
||
577 | |||
578 | 7 | $rawContentType = $this->getContentType(); |
|
579 | 7 | if (($pos = strpos((string)$rawContentType, ';')) !== false) { |
|
580 | // e.g. text/html; charset=UTF-8 |
||
581 | $contentType = substr($rawContentType, 0, $pos); |
||
582 | } else { |
||
583 | 7 | $contentType = $rawContentType; |
|
584 | } |
||
585 | |||
586 | 7 | if (isset($this->parsers[$contentType])) { |
|
587 | 2 | $parser = Yii::createObject($this->parsers[$contentType]); |
|
588 | 2 | if (!($parser instanceof RequestParserInterface)) { |
|
589 | throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface."); |
||
590 | } |
||
591 | 2 | $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType); |
|
592 | 5 | } elseif (isset($this->parsers['*'])) { |
|
593 | $parser = Yii::createObject($this->parsers['*']); |
||
594 | if (!($parser instanceof RequestParserInterface)) { |
||
595 | throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.'); |
||
596 | } |
||
597 | $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType); |
||
598 | 5 | } elseif ($this->getMethod() === 'POST') { |
|
599 | // PHP has already parsed the body so we have all params in $_POST |
||
600 | $this->_bodyParams = $_POST; |
||
601 | } else { |
||
602 | 5 | $this->_bodyParams = []; |
|
603 | 5 | mb_parse_str($this->getRawBody(), $this->_bodyParams); |
|
604 | } |
||
605 | } |
||
606 | |||
607 | 16 | return $this->_bodyParams; |
|
608 | } |
||
609 | |||
610 | /** |
||
611 | * Sets the request body parameters. |
||
612 | * |
||
613 | * @param array|object $values the request body parameters (name-value pairs) |
||
614 | * @see getBodyParams() |
||
615 | */ |
||
616 | 11 | public function setBodyParams($values) |
|
617 | { |
||
618 | 11 | $this->_bodyParams = $values; |
|
619 | 11 | } |
|
620 | |||
621 | /** |
||
622 | * Returns the named request body parameter value. |
||
623 | * |
||
624 | * If the parameter does not exist, the second parameter passed to this method will be returned. |
||
625 | * |
||
626 | * @param string $name the parameter name |
||
627 | * @param mixed $defaultValue the default parameter value if the parameter does not exist. |
||
628 | * @return mixed the parameter value |
||
629 | * @see getBodyParams() |
||
630 | * @see setBodyParams() |
||
631 | */ |
||
632 | 7 | public function getBodyParam($name, $defaultValue = null) |
|
633 | { |
||
634 | 7 | $params = $this->getBodyParams(); |
|
635 | |||
636 | 7 | if (is_object($params)) { |
|
637 | // unable to use `ArrayHelper::getValue()` due to different dots in key logic and lack of exception handling |
||
638 | try { |
||
639 | 1 | return isset($params->{$name}) ? $params->{$name} : $defaultValue; |
|
640 | } catch (\Exception $e) { |
||
641 | return $defaultValue; |
||
642 | } |
||
643 | } |
||
644 | |||
645 | 7 | return isset($params[$name]) ? $params[$name] : $defaultValue; |
|
646 | } |
||
647 | |||
648 | /** |
||
649 | * Returns POST parameter with a given name. If name isn't specified, returns an array of all POST parameters. |
||
650 | * |
||
651 | * @param string $name the parameter name |
||
652 | * @param mixed $defaultValue the default parameter value if the parameter does not exist. |
||
653 | * @return array|mixed |
||
654 | */ |
||
655 | public function post($name = null, $defaultValue = null) |
||
656 | { |
||
657 | if ($name === null) { |
||
658 | return $this->getBodyParams(); |
||
659 | } |
||
660 | |||
661 | return $this->getBodyParam($name, $defaultValue); |
||
662 | } |
||
663 | |||
664 | private $_queryParams; |
||
665 | |||
666 | /** |
||
667 | * Returns the request parameters given in the [[queryString]]. |
||
668 | * |
||
669 | * This method will return the contents of `$_GET` if params where not explicitly set. |
||
670 | * @return array the request GET parameter values. |
||
671 | * @see setQueryParams() |
||
672 | */ |
||
673 | 65 | public function getQueryParams() |
|
674 | { |
||
675 | 65 | if ($this->_queryParams === null) { |
|
676 | 58 | return $_GET; |
|
677 | } |
||
678 | |||
679 | 9 | return $this->_queryParams; |
|
680 | } |
||
681 | |||
682 | /** |
||
683 | * Sets the request [[queryString]] parameters. |
||
684 | * @param array $values the request query parameters (name-value pairs) |
||
685 | * @see getQueryParam() |
||
686 | * @see getQueryParams() |
||
687 | */ |
||
688 | 9 | public function setQueryParams($values) |
|
689 | { |
||
690 | 9 | $this->_queryParams = $values; |
|
691 | 9 | } |
|
692 | |||
693 | /** |
||
694 | * Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters. |
||
695 | * |
||
696 | * @param string $name the parameter name |
||
697 | * @param mixed $defaultValue the default parameter value if the parameter does not exist. |
||
698 | * @return array|mixed |
||
699 | */ |
||
700 | 23 | public function get($name = null, $defaultValue = null) |
|
701 | { |
||
702 | 23 | if ($name === null) { |
|
703 | return $this->getQueryParams(); |
||
704 | } |
||
705 | |||
706 | 23 | return $this->getQueryParam($name, $defaultValue); |
|
707 | } |
||
708 | |||
709 | /** |
||
710 | * Returns the named GET parameter value. |
||
711 | * If the GET parameter does not exist, the second parameter passed to this method will be returned. |
||
712 | * @param string $name the GET parameter name. |
||
713 | * @param mixed $defaultValue the default parameter value if the GET parameter does not exist. |
||
714 | * @return mixed the GET parameter value |
||
715 | * @see getBodyParam() |
||
716 | */ |
||
717 | 26 | public function getQueryParam($name, $defaultValue = null) |
|
718 | { |
||
719 | 26 | $params = $this->getQueryParams(); |
|
720 | |||
721 | 26 | return isset($params[$name]) ? $params[$name] : $defaultValue; |
|
722 | } |
||
723 | |||
724 | private $_hostInfo; |
||
725 | private $_hostName; |
||
726 | |||
727 | /** |
||
728 | * Returns the schema and host part of the current request URL. |
||
729 | * |
||
730 | * The returned URL does not have an ending slash. |
||
731 | * |
||
732 | * By default this value is based on the user request information. This method will |
||
733 | * return the value of `$_SERVER['HTTP_HOST']` if it is available or `$_SERVER['SERVER_NAME']` if not. |
||
734 | * You may want to check out the [PHP documentation](https://www.php.net/manual/en/reserved.variables.server.php) |
||
735 | * for more information on these variables. |
||
736 | * |
||
737 | * You may explicitly specify it by setting the [[setHostInfo()|hostInfo]] property. |
||
738 | * |
||
739 | * > Warning: Dependent on the server configuration this information may not be |
||
740 | * > reliable and [may be faked by the user sending the HTTP request](https://www.acunetix.com/vulnerabilities/web/host-header-attack). |
||
741 | * > If the webserver is configured to serve the same site independent of the value of |
||
742 | * > the `Host` header, this value is not reliable. In such situations you should either |
||
743 | * > fix your webserver configuration or explicitly set the value by setting the [[setHostInfo()|hostInfo]] property. |
||
744 | * > If you don't have access to the server configuration, you can setup [[\yii\filters\HostControl]] filter at |
||
745 | * > application level in order to protect against such kind of attack. |
||
746 | * |
||
747 | * @property string|null schema and hostname part (with port number if needed) of the request URL |
||
748 | * (e.g. `https://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. |
||
749 | * See [[getHostInfo()]] for security related notes on this property. |
||
750 | * @return string|null schema and hostname part (with port number if needed) of the request URL |
||
751 | * (e.g. `https://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. |
||
752 | * @see setHostInfo() |
||
753 | */ |
||
754 | 49 | public function getHostInfo() |
|
755 | { |
||
756 | 49 | if ($this->_hostInfo === null) { |
|
757 | 45 | $secure = $this->getIsSecureConnection(); |
|
758 | 45 | $http = $secure ? 'https' : 'http'; |
|
759 | |||
760 | 45 | if ($this->getSecureForwardedHeaderTrustedPart('host') !== null) { |
|
761 | 8 | $this->_hostInfo = $http . '://' . $this->getSecureForwardedHeaderTrustedPart('host'); |
|
762 | 37 | } elseif ($this->headers->has('X-Forwarded-Host')) { |
|
763 | 3 | $this->_hostInfo = $http . '://' . trim(explode(',', $this->headers->get('X-Forwarded-Host'))[0]); |
|
764 | 34 | } elseif ($this->headers->has('X-Original-Host')) { |
|
765 | $this->_hostInfo = $http . '://' . trim(explode(',', $this->headers->get('X-Original-Host'))[0]); |
||
766 | 34 | } elseif ($this->headers->has('Host')) { |
|
767 | 11 | $this->_hostInfo = $http . '://' . $this->headers->get('Host'); |
|
768 | 23 | } elseif (isset($_SERVER['SERVER_NAME'])) { |
|
769 | 1 | $this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME']; |
|
770 | 1 | $port = $secure ? $this->getSecurePort() : $this->getPort(); |
|
771 | 1 | if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) { |
|
772 | $this->_hostInfo .= ':' . $port; |
||
773 | } |
||
774 | } |
||
775 | } |
||
776 | |||
777 | 49 | return $this->_hostInfo; |
|
778 | } |
||
779 | |||
780 | /** |
||
781 | * Sets the schema and host part of the application URL. |
||
782 | * This setter is provided in case the schema and hostname cannot be determined |
||
783 | * on certain Web servers. |
||
784 | * @param string|null $value the schema and host part of the application URL. The trailing slashes will be removed. |
||
785 | * @see getHostInfo() for security related notes on this property. |
||
786 | */ |
||
787 | 59 | public function setHostInfo($value) |
|
788 | { |
||
789 | 59 | $this->_hostName = null; |
|
790 | 59 | $this->_hostInfo = $value === null ? null : rtrim($value, '/'); |
|
791 | 59 | } |
|
792 | |||
793 | /** |
||
794 | * Returns the host part of the current request URL. |
||
795 | * Value is calculated from current [[getHostInfo()|hostInfo]] property. |
||
796 | * |
||
797 | * > Warning: The content of this value may not be reliable, dependent on the server |
||
798 | * > configuration. Please refer to [[getHostInfo()]] for more information. |
||
799 | * |
||
800 | * @return string|null hostname part of the request URL (e.g. `www.yiiframework.com`) |
||
801 | * @see getHostInfo() |
||
802 | * @since 2.0.10 |
||
803 | */ |
||
804 | 20 | public function getHostName() |
|
805 | { |
||
806 | 20 | if ($this->_hostName === null) { |
|
807 | 20 | $this->_hostName = parse_url((string)$this->getHostInfo(), PHP_URL_HOST); |
|
808 | } |
||
809 | |||
810 | 20 | return $this->_hostName; |
|
811 | } |
||
812 | |||
813 | private $_baseUrl; |
||
814 | |||
815 | /** |
||
816 | * Returns the relative URL for the application. |
||
817 | * This is similar to [[scriptUrl]] except that it does not include the script file name, |
||
818 | * and the ending slashes are removed. |
||
819 | * @return string the relative URL for the application |
||
820 | * @see setScriptUrl() |
||
821 | */ |
||
822 | 462 | public function getBaseUrl() |
|
823 | { |
||
824 | 462 | if ($this->_baseUrl === null) { |
|
825 | 460 | $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/'); |
|
826 | } |
||
827 | |||
828 | 462 | return $this->_baseUrl; |
|
829 | } |
||
830 | |||
831 | /** |
||
832 | * Sets the relative URL for the application. |
||
833 | * By default the URL is determined based on the entry script URL. |
||
834 | * This setter is provided in case you want to change this behavior. |
||
835 | * @param string $value the relative URL for the application |
||
836 | */ |
||
837 | 2 | public function setBaseUrl($value) |
|
838 | { |
||
839 | 2 | $this->_baseUrl = $value; |
|
840 | 2 | } |
|
841 | |||
842 | private $_scriptUrl; |
||
843 | |||
844 | /** |
||
845 | * Returns the relative URL of the entry script. |
||
846 | * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework. |
||
847 | * @return string the relative URL of the entry script. |
||
848 | * @throws InvalidConfigException if unable to determine the entry script URL |
||
849 | */ |
||
850 | 463 | public function getScriptUrl() |
|
851 | { |
||
852 | 463 | if ($this->_scriptUrl === null) { |
|
853 | 1 | $scriptFile = $this->getScriptFile(); |
|
854 | $scriptName = basename($scriptFile); |
||
855 | if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $scriptName) { |
||
856 | $this->_scriptUrl = $_SERVER['SCRIPT_NAME']; |
||
857 | } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $scriptName) { |
||
858 | $this->_scriptUrl = $_SERVER['PHP_SELF']; |
||
859 | } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) { |
||
860 | $this->_scriptUrl = $_SERVER['ORIG_SCRIPT_NAME']; |
||
861 | } elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) { |
||
862 | $this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName; |
||
863 | } elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) { |
||
864 | $this->_scriptUrl = str_replace([$_SERVER['DOCUMENT_ROOT'], '\\'], ['', '/'], $scriptFile); |
||
865 | } else { |
||
866 | throw new InvalidConfigException('Unable to determine the entry script URL.'); |
||
867 | } |
||
868 | } |
||
869 | |||
870 | 462 | return $this->_scriptUrl; |
|
871 | } |
||
872 | |||
873 | /** |
||
874 | * Sets the relative URL for the application entry script. |
||
875 | * This setter is provided in case the entry script URL cannot be determined |
||
876 | * on certain Web servers. |
||
877 | * @param string $value the relative URL for the application entry script. |
||
878 | */ |
||
879 | 473 | public function setScriptUrl($value) |
|
880 | { |
||
881 | 473 | $this->_scriptUrl = $value === null ? null : '/' . trim($value, '/'); |
|
882 | 473 | } |
|
883 | |||
884 | private $_scriptFile; |
||
885 | |||
886 | /** |
||
887 | * Returns the entry script file path. |
||
888 | * The default implementation will simply return `$_SERVER['SCRIPT_FILENAME']`. |
||
889 | * @return string the entry script file path |
||
890 | * @throws InvalidConfigException |
||
891 | */ |
||
892 | 464 | public function getScriptFile() |
|
893 | { |
||
894 | 464 | if (isset($this->_scriptFile)) { |
|
895 | 435 | return $this->_scriptFile; |
|
896 | } |
||
897 | |||
898 | 29 | if (isset($_SERVER['SCRIPT_FILENAME'])) { |
|
899 | 27 | return $_SERVER['SCRIPT_FILENAME']; |
|
900 | } |
||
901 | |||
902 | 2 | throw new InvalidConfigException('Unable to determine the entry script file path.'); |
|
903 | } |
||
904 | |||
905 | /** |
||
906 | * Sets the entry script file path. |
||
907 | * The entry script file path normally can be obtained from `$_SERVER['SCRIPT_FILENAME']`. |
||
908 | * If your server configuration does not return the correct value, you may configure |
||
909 | * this property to make it right. |
||
910 | * @param string $value the entry script file path. |
||
911 | */ |
||
912 | 435 | public function setScriptFile($value) |
|
913 | { |
||
914 | 435 | $this->_scriptFile = $value; |
|
915 | 435 | } |
|
916 | |||
917 | private $_pathInfo; |
||
918 | |||
919 | /** |
||
920 | * Returns the path info of the currently requested URL. |
||
921 | * A path info refers to the part that is after the entry script and before the question mark (query string). |
||
922 | * The starting and ending slashes are both removed. |
||
923 | * @return string part of the request URL that is after the entry script and before the question mark. |
||
924 | * Note, the returned path info is already URL-decoded. |
||
925 | * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration |
||
926 | */ |
||
927 | 19 | public function getPathInfo() |
|
928 | { |
||
929 | 19 | if ($this->_pathInfo === null) { |
|
930 | $this->_pathInfo = $this->resolvePathInfo(); |
||
931 | } |
||
932 | |||
933 | 19 | return $this->_pathInfo; |
|
934 | } |
||
935 | |||
936 | /** |
||
937 | * Sets the path info of the current request. |
||
938 | * This method is mainly provided for testing purpose. |
||
939 | * @param string $value the path info of the current request |
||
940 | */ |
||
941 | 20 | public function setPathInfo($value) |
|
942 | { |
||
943 | 20 | $this->_pathInfo = $value === null ? null : ltrim($value, '/'); |
|
944 | 20 | } |
|
945 | |||
946 | /** |
||
947 | * Resolves the path info part of the currently requested URL. |
||
948 | * A path info refers to the part that is after the entry script and before the question mark (query string). |
||
949 | * The starting slashes are both removed (ending slashes will be kept). |
||
950 | * @return string part of the request URL that is after the entry script and before the question mark. |
||
951 | * Note, the returned path info is decoded. |
||
952 | * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration |
||
953 | */ |
||
954 | protected function resolvePathInfo() |
||
955 | { |
||
956 | $pathInfo = $this->getUrl(); |
||
957 | |||
958 | if (($pos = strpos($pathInfo, '?')) !== false) { |
||
959 | $pathInfo = substr($pathInfo, 0, $pos); |
||
960 | } |
||
961 | |||
962 | $pathInfo = urldecode($pathInfo); |
||
963 | |||
964 | // try to encode in UTF8 if not so |
||
965 | // https://www.w3.org/International/questions/qa-forms-utf-8.en.html |
||
966 | if (!preg_match('%^(?: |
||
967 | [\x09\x0A\x0D\x20-\x7E] # ASCII |
||
968 | | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte |
||
969 | | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs |
||
970 | | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte |
||
971 | | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates |
||
972 | | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 |
||
973 | | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 |
||
974 | | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 |
||
975 | )*$%xs', $pathInfo) |
||
976 | ) { |
||
977 | $pathInfo = $this->utf8Encode($pathInfo); |
||
978 | } |
||
979 | |||
980 | $scriptUrl = $this->getScriptUrl(); |
||
981 | $baseUrl = $this->getBaseUrl(); |
||
982 | if (strpos($pathInfo, $scriptUrl) === 0) { |
||
983 | $pathInfo = substr($pathInfo, strlen($scriptUrl)); |
||
984 | } elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) { |
||
985 | $pathInfo = substr($pathInfo, strlen($baseUrl)); |
||
986 | } elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0) { |
||
987 | $pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl)); |
||
988 | } else { |
||
989 | throw new InvalidConfigException('Unable to determine the path info of the current request.'); |
||
990 | } |
||
991 | |||
992 | if (strncmp($pathInfo, '/', 1) === 0) { |
||
993 | $pathInfo = substr($pathInfo, 1); |
||
994 | } |
||
995 | |||
996 | return (string) $pathInfo; |
||
997 | } |
||
998 | |||
999 | /** |
||
1000 | * Encodes an ISO-8859-1 string to UTF-8 |
||
1001 | * @param string $s |
||
1002 | * @return string the UTF-8 translation of `s`. |
||
1003 | * @see https://github.com/symfony/polyfill-php72/blob/master/Php72.php#L24 |
||
1004 | */ |
||
1005 | private function utf8Encode($s) |
||
1006 | { |
||
1007 | $s .= $s; |
||
1008 | $len = \strlen($s); |
||
1009 | for ($i = $len >> 1, $j = 0; $i < $len; ++$i, ++$j) { |
||
1010 | switch (true) { |
||
1011 | case $s[$i] < "\x80": $s[$j] = $s[$i]; break; |
||
1012 | case $s[$i] < "\xC0": $s[$j] = "\xC2"; $s[++$j] = $s[$i]; break; |
||
1013 | default: $s[$j] = "\xC3"; $s[++$j] = \chr(\ord($s[$i]) - 64); break; |
||
1014 | } |
||
1015 | } |
||
1016 | return substr($s, 0, $j); |
||
1017 | } |
||
1018 | |||
1019 | /** |
||
1020 | * Returns the currently requested absolute URL. |
||
1021 | * This is a shortcut to the concatenation of [[hostInfo]] and [[url]]. |
||
1022 | * @return string the currently requested absolute URL. |
||
1023 | */ |
||
1024 | 1 | public function getAbsoluteUrl() |
|
1025 | { |
||
1026 | 1 | return $this->getHostInfo() . $this->getUrl(); |
|
1027 | } |
||
1028 | |||
1029 | private $_url; |
||
1030 | |||
1031 | /** |
||
1032 | * Returns the currently requested relative URL. |
||
1033 | * This refers to the portion of the URL that is after the [[hostInfo]] part. |
||
1034 | * It includes the [[queryString]] part if any. |
||
1035 | * @return string the currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client. |
||
1036 | * @throws InvalidConfigException if the URL cannot be determined due to unusual server configuration |
||
1037 | */ |
||
1038 | 11 | public function getUrl() |
|
1039 | { |
||
1040 | 11 | if ($this->_url === null) { |
|
1041 | 3 | $this->_url = $this->resolveRequestUri(); |
|
1042 | } |
||
1043 | |||
1044 | 11 | return $this->_url; |
|
1045 | } |
||
1046 | |||
1047 | /** |
||
1048 | * Sets the currently requested relative URL. |
||
1049 | * The URI must refer to the portion that is after [[hostInfo]]. |
||
1050 | * Note that the URI should be URL-encoded. |
||
1051 | * @param string $value the request URI to be set |
||
1052 | */ |
||
1053 | 25 | public function setUrl($value) |
|
1054 | { |
||
1055 | 25 | $this->_url = $value; |
|
1056 | 25 | } |
|
1057 | |||
1058 | /** |
||
1059 | * Resolves the request URI portion for the currently requested URL. |
||
1060 | * This refers to the portion that is after the [[hostInfo]] part. It includes the [[queryString]] part if any. |
||
1061 | * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework. |
||
1062 | * @return string|bool the request URI portion for the currently requested URL. |
||
1063 | * Note that the URI returned may be URL-encoded depending on the client. |
||
1064 | * @throws InvalidConfigException if the request URI cannot be determined due to unusual server configuration |
||
1065 | */ |
||
1066 | 3 | protected function resolveRequestUri() |
|
1067 | { |
||
1068 | 3 | if ($this->headers->has('X-Rewrite-Url')) { // IIS |
|
1069 | $requestUri = $this->headers->get('X-Rewrite-Url'); |
||
1070 | 3 | } elseif (isset($_SERVER['REQUEST_URI'])) { |
|
1071 | 3 | $requestUri = $_SERVER['REQUEST_URI']; |
|
1072 | 3 | if ($requestUri !== '' && $requestUri[0] !== '/') { |
|
1073 | 3 | $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri); |
|
1074 | } |
||
1075 | } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 CGI |
||
1076 | $requestUri = $_SERVER['ORIG_PATH_INFO']; |
||
1077 | if (!empty($_SERVER['QUERY_STRING'])) { |
||
1078 | $requestUri .= '?' . $_SERVER['QUERY_STRING']; |
||
1079 | } |
||
1080 | } else { |
||
1081 | throw new InvalidConfigException('Unable to determine the request URI.'); |
||
1082 | } |
||
1083 | |||
1084 | 3 | return $requestUri; |
|
1085 | } |
||
1086 | |||
1087 | /** |
||
1088 | * Returns part of the request URL that is after the question mark. |
||
1089 | * @return string part of the request URL that is after the question mark |
||
1090 | */ |
||
1091 | public function getQueryString() |
||
1092 | { |
||
1093 | return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; |
||
1094 | } |
||
1095 | |||
1096 | /** |
||
1097 | * Return if the request is sent via secure channel (https). |
||
1098 | * @return bool if the request is sent via secure channel (https) |
||
1099 | */ |
||
1100 | 73 | public function getIsSecureConnection() |
|
1101 | { |
||
1102 | 73 | if (isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)) { |
|
1103 | 2 | return true; |
|
1104 | } |
||
1105 | |||
1106 | 71 | if (($proto = $this->getSecureForwardedHeaderTrustedPart('proto')) !== null) { |
|
1107 | 9 | return strcasecmp($proto, 'https') === 0; |
|
1108 | } |
||
1109 | |||
1110 | 62 | foreach ($this->secureProtocolHeaders as $header => $values) { |
|
1111 | 62 | if (($headerValue = $this->headers->get($header, null)) !== null) { |
|
1112 | 5 | foreach ($values as $value) { |
|
1113 | 5 | if (strcasecmp($headerValue, $value) === 0) { |
|
1114 | 3 | return true; |
|
1115 | } |
||
1116 | } |
||
1117 | } |
||
1118 | } |
||
1119 | |||
1120 | 59 | return false; |
|
1121 | } |
||
1122 | |||
1123 | /** |
||
1124 | * Returns the server name. |
||
1125 | * @return string|null server name, null if not available |
||
1126 | */ |
||
1127 | 1 | public function getServerName() |
|
1128 | { |
||
1129 | 1 | return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null; |
|
1130 | } |
||
1131 | |||
1132 | /** |
||
1133 | * Returns the server port number. If a port is specified via a forwarding header (e.g. 'X-Forwarded-Port') |
||
1134 | * and the remote host is a "trusted host" the that port will be used (see [[portHeaders]]), |
||
1135 | * otherwise the default server port will be returned. |
||
1136 | * @return int|null server port number, null if not available |
||
1137 | * @see portHeaders |
||
1138 | */ |
||
1139 | 8 | public function getServerPort() |
|
1140 | { |
||
1141 | 8 | foreach ($this->portHeaders as $portHeader) { |
|
1142 | 8 | if ($this->headers->has($portHeader)) { |
|
1143 | 2 | $port = $this->headers->get($portHeader); |
|
1144 | 2 | if ($port !== null) { |
|
1145 | 2 | return $port; |
|
1146 | } |
||
1147 | } |
||
1148 | } |
||
1149 | |||
1150 | 6 | return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null; |
|
1151 | } |
||
1152 | |||
1153 | /** |
||
1154 | * Returns the URL referrer. |
||
1155 | * @return string|null URL referrer, null if not available |
||
1156 | */ |
||
1157 | public function getReferrer() |
||
1158 | { |
||
1159 | return $this->headers->get('Referer'); |
||
1160 | } |
||
1161 | |||
1162 | /** |
||
1163 | * Returns the URL origin of a CORS request. |
||
1164 | * |
||
1165 | * The return value is taken from the `Origin` [[getHeaders()|header]] sent by the browser. |
||
1166 | * |
||
1167 | * Note that the origin request header indicates where a fetch originates from. |
||
1168 | * It doesn't include any path information, but only the server name. |
||
1169 | * It is sent with a CORS requests, as well as with POST requests. |
||
1170 | * It is similar to the referer header, but, unlike this header, it doesn't disclose the whole path. |
||
1171 | * Please refer to <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin> for more information. |
||
1172 | * |
||
1173 | * @return string|null URL origin of a CORS request, `null` if not available. |
||
1174 | * @see getHeaders() |
||
1175 | * @since 2.0.13 |
||
1176 | */ |
||
1177 | 1 | public function getOrigin() |
|
1178 | { |
||
1179 | 1 | return $this->getHeaders()->get('origin'); |
|
1180 | } |
||
1181 | |||
1182 | /** |
||
1183 | * Returns the user agent. |
||
1184 | * @return string|null user agent, null if not available |
||
1185 | */ |
||
1186 | 1 | public function getUserAgent() |
|
1187 | { |
||
1188 | 1 | return $this->headers->get('User-Agent'); |
|
1189 | } |
||
1190 | |||
1191 | /** |
||
1192 | * Returns the user IP address from [[ipHeaders]]. |
||
1193 | * @return string|null user IP address, null if not available |
||
1194 | * @see ipHeaders |
||
1195 | * @since 2.0.28 |
||
1196 | */ |
||
1197 | 105 | protected function getUserIpFromIpHeaders() |
|
1198 | { |
||
1199 | 105 | $ip = $this->getSecureForwardedHeaderTrustedPart('for'); |
|
1200 | 105 | if ($ip !== null && preg_match( |
|
1201 | 105 | '/^\[?(?P<ip>(?:(?:(?:[0-9a-f]{1,4}:){1,6}(?:[0-9a-f]{1,4})?(?:(?::[0-9a-f]{1,4}){1,6}))|(?:\d{1,3}\.){3}\d{1,3}))\]?(?::(?P<port>\d+))?$/', |
|
1202 | $ip, |
||
1203 | $matches |
||
1204 | )) { |
||
1205 | 14 | $ip = $this->getUserIpFromIpHeader($matches['ip']); |
|
1206 | 14 | if ($ip !== null) { |
|
1207 | 14 | return $ip; |
|
1208 | } |
||
1209 | } |
||
1210 | |||
1211 | |||
1212 | 91 | foreach ($this->ipHeaders as $ipHeader) { |
|
1213 | 88 | if ($this->headers->has($ipHeader)) { |
|
1214 | 10 | $ip = $this->getUserIpFromIpHeader($this->headers->get($ipHeader)); |
|
1215 | 10 | if ($ip !== null) { |
|
1216 | 10 | return $ip; |
|
1217 | } |
||
1218 | } |
||
1219 | } |
||
1220 | 81 | return null; |
|
1221 | } |
||
1222 | |||
1223 | private $_ip = null; |
||
1224 | |||
1225 | /** |
||
1226 | * Returns the user IP address. |
||
1227 | * The IP is determined using headers and / or `$_SERVER` variables. |
||
1228 | * @return string|null user IP address, null if not available |
||
1229 | */ |
||
1230 | 105 | public function getUserIP() |
|
1231 | { |
||
1232 | 105 | if ($this->_ip === null) { |
|
1233 | 105 | $this->_ip = $this->getUserIpFromIpHeaders(); |
|
1234 | 105 | if ($this->_ip === null) { |
|
1235 | 81 | $this->_ip = $this->getRemoteIP(); |
|
1236 | } |
||
1237 | } |
||
1238 | |||
1239 | 105 | return $this->_ip; |
|
1240 | } |
||
1241 | |||
1242 | /** |
||
1243 | * Return user IP's from IP header. |
||
1244 | * |
||
1245 | * @param string $ips comma separated IP list |
||
1246 | * @return string|null IP as string. Null is returned if IP can not be determined from header. |
||
1247 | * @see getUserHost() |
||
1248 | * @see ipHeaders |
||
1249 | * @see getTrustedHeaders() |
||
1250 | * @since 2.0.28 |
||
1251 | */ |
||
1252 | 24 | protected function getUserIpFromIpHeader($ips) |
|
1253 | { |
||
1254 | 24 | $ips = trim($ips); |
|
1255 | 24 | if ($ips === '') { |
|
1256 | return null; |
||
1257 | } |
||
1258 | 24 | $ips = preg_split('/\s*,\s*/', $ips, -1, PREG_SPLIT_NO_EMPTY); |
|
1259 | 24 | krsort($ips); |
|
1260 | 24 | $validator = $this->getIpValidator(); |
|
1261 | 24 | $resultIp = null; |
|
1262 | 24 | foreach ($ips as $ip) { |
|
1263 | 24 | $validator->setRanges('any'); |
|
1264 | 24 | if (!$validator->validate($ip) /* checking IP format */) { |
|
1265 | 1 | break; |
|
1266 | } |
||
1267 | 24 | $resultIp = $ip; |
|
1268 | 24 | $isTrusted = false; |
|
1269 | 24 | foreach ($this->trustedHosts as $trustedCidr => $trustedCidrOrHeaders) { |
|
1270 | 24 | if (!is_array($trustedCidrOrHeaders)) { |
|
1271 | 24 | $trustedCidr = $trustedCidrOrHeaders; |
|
1272 | } |
||
1273 | 24 | $validator->setRanges($trustedCidr); |
|
1274 | 24 | if ($validator->validate($ip) /* checking trusted range */) { |
|
1275 | 7 | $isTrusted = true; |
|
1276 | 7 | break; |
|
1277 | } |
||
1278 | } |
||
1279 | 24 | if (!$isTrusted) { |
|
1280 | 20 | break; |
|
1281 | } |
||
1282 | } |
||
1283 | 24 | return $resultIp; |
|
1284 | } |
||
1285 | |||
1286 | /** |
||
1287 | * Returns the user host name. |
||
1288 | * The HOST is determined using headers and / or `$_SERVER` variables. |
||
1289 | * @return string|null user host name, null if not available |
||
1290 | */ |
||
1291 | public function getUserHost() |
||
1292 | { |
||
1293 | $userIp = $this->getUserIpFromIpHeaders(); |
||
1294 | if($userIp === null) { |
||
1295 | return $this->getRemoteHost(); |
||
1296 | } |
||
1297 | return gethostbyaddr($userIp); |
||
1298 | } |
||
1299 | |||
1300 | /** |
||
1301 | * Returns the IP on the other end of this connection. |
||
1302 | * This is always the next hop, any headers are ignored. |
||
1303 | * @return string|null remote IP address, `null` if not available. |
||
1304 | * @since 2.0.13 |
||
1305 | */ |
||
1306 | 142 | public function getRemoteIP() |
|
1307 | { |
||
1308 | 142 | return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null; |
|
1309 | } |
||
1310 | |||
1311 | /** |
||
1312 | * Returns the host name of the other end of this connection. |
||
1313 | * This is always the next hop, any headers are ignored. |
||
1314 | * @return string|null remote host name, `null` if not available |
||
1315 | * @see getUserHost() |
||
1316 | * @see getRemoteIP() |
||
1317 | * @since 2.0.13 |
||
1318 | */ |
||
1319 | public function getRemoteHost() |
||
1320 | { |
||
1321 | return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null; |
||
1322 | } |
||
1323 | |||
1324 | /** |
||
1325 | * @return string|null the username sent via HTTP authentication, `null` if the username is not given |
||
1326 | * @see getAuthCredentials() to get both username and password in one call |
||
1327 | */ |
||
1328 | 9 | public function getAuthUser() |
|
1329 | { |
||
1330 | 9 | return $this->getAuthCredentials()[0]; |
|
1331 | } |
||
1332 | |||
1333 | /** |
||
1334 | * @return string|null the password sent via HTTP authentication, `null` if the password is not given |
||
1335 | * @see getAuthCredentials() to get both username and password in one call |
||
1336 | */ |
||
1337 | 9 | public function getAuthPassword() |
|
1338 | { |
||
1339 | 9 | return $this->getAuthCredentials()[1]; |
|
1340 | } |
||
1341 | |||
1342 | /** |
||
1343 | * @return array that contains exactly two elements: |
||
1344 | * - 0: the username sent via HTTP authentication, `null` if the username is not given |
||
1345 | * - 1: the password sent via HTTP authentication, `null` if the password is not given |
||
1346 | * @see getAuthUser() to get only username |
||
1347 | * @see getAuthPassword() to get only password |
||
1348 | * @since 2.0.13 |
||
1349 | */ |
||
1350 | 39 | public function getAuthCredentials() |
|
1351 | { |
||
1352 | 39 | $username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null; |
|
1353 | 39 | $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null; |
|
1354 | 39 | if ($username !== null || $password !== null) { |
|
1355 | 21 | return [$username, $password]; |
|
1356 | } |
||
1357 | |||
1358 | /** |
||
1359 | * Apache with php-cgi does not pass HTTP Basic authentication to PHP by default. |
||
1360 | * To make it work, add one of the following lines to to your .htaccess file: |
||
1361 | * |
||
1362 | * SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0 |
||
1363 | * --OR-- |
||
1364 | * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] |
||
1365 | */ |
||
1366 | 18 | $auth_token = $this->getHeaders()->get('Authorization'); |
|
1367 | |||
1368 | 18 | if ($auth_token !== null && strncasecmp($auth_token, 'basic', 5) === 0) { |
|
1369 | $parts = array_map(function ($value) { |
||
1370 | 18 | return strlen($value) === 0 ? null : $value; |
|
1371 | 18 | }, explode(':', base64_decode(mb_substr($auth_token, 6)), 2)); |
|
1372 | |||
1373 | 18 | if (count($parts) < 2) { |
|
1374 | 2 | return [$parts[0], null]; |
|
1375 | } |
||
1376 | |||
1377 | 16 | return $parts; |
|
1378 | } |
||
1379 | |||
1380 | return [null, null]; |
||
1381 | } |
||
1382 | |||
1383 | private $_port; |
||
1384 | |||
1385 | /** |
||
1386 | * Returns the port to use for insecure requests. |
||
1387 | * Defaults to 80, or the port specified by the server if the current |
||
1388 | * request is insecure. |
||
1389 | * @return int port number for insecure requests. |
||
1390 | * @see setPort() |
||
1391 | */ |
||
1392 | 1 | public function getPort() |
|
1393 | { |
||
1394 | 1 | if ($this->_port === null) { |
|
1395 | 1 | $serverPort = $this->getServerPort(); |
|
1396 | 1 | $this->_port = !$this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 80; |
|
1397 | } |
||
1398 | |||
1399 | 1 | return $this->_port; |
|
1400 | } |
||
1401 | |||
1402 | /** |
||
1403 | * Sets the port to use for insecure requests. |
||
1404 | * This setter is provided in case a custom port is necessary for certain |
||
1405 | * server configurations. |
||
1406 | * @param int $value port number. |
||
1407 | */ |
||
1408 | public function setPort($value) |
||
1409 | { |
||
1410 | if ($value != $this->_port) { |
||
1411 | $this->_port = (int) $value; |
||
1412 | $this->_hostInfo = null; |
||
1413 | } |
||
1414 | } |
||
1415 | |||
1416 | private $_securePort; |
||
1417 | |||
1418 | /** |
||
1419 | * Returns the port to use for secure requests. |
||
1420 | * Defaults to 443, or the port specified by the server if the current |
||
1421 | * request is secure. |
||
1422 | * @return int port number for secure requests. |
||
1423 | * @see setSecurePort() |
||
1424 | */ |
||
1425 | public function getSecurePort() |
||
1426 | { |
||
1427 | if ($this->_securePort === null) { |
||
1428 | $serverPort = $this->getServerPort(); |
||
1429 | $this->_securePort = $this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 443; |
||
1430 | } |
||
1431 | |||
1432 | return $this->_securePort; |
||
1433 | } |
||
1434 | |||
1435 | /** |
||
1436 | * Sets the port to use for secure requests. |
||
1437 | * This setter is provided in case a custom port is necessary for certain |
||
1438 | * server configurations. |
||
1439 | * @param int $value port number. |
||
1440 | */ |
||
1441 | public function setSecurePort($value) |
||
1442 | { |
||
1443 | if ($value != $this->_securePort) { |
||
1444 | $this->_securePort = (int) $value; |
||
1445 | $this->_hostInfo = null; |
||
1446 | } |
||
1447 | } |
||
1448 | |||
1449 | private $_contentTypes; |
||
1450 | |||
1451 | /** |
||
1452 | * Returns the content types acceptable by the end user. |
||
1453 | * |
||
1454 | * This is determined by the `Accept` HTTP header. For example, |
||
1455 | * |
||
1456 | * ```php |
||
1457 | * $_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;'; |
||
1458 | * $types = $request->getAcceptableContentTypes(); |
||
1459 | * print_r($types); |
||
1460 | * // displays: |
||
1461 | * // [ |
||
1462 | * // 'application/json' => ['q' => 1, 'version' => '1.0'], |
||
1463 | * // 'application/xml' => ['q' => 1, 'version' => '2.0'], |
||
1464 | * // 'text/plain' => ['q' => 0.5], |
||
1465 | * // ] |
||
1466 | * ``` |
||
1467 | * |
||
1468 | * @return array the content types ordered by the quality score. Types with the highest scores |
||
1469 | * will be returned first. The array keys are the content types, while the array values |
||
1470 | * are the corresponding quality score and other parameters as given in the header. |
||
1471 | */ |
||
1472 | 5 | public function getAcceptableContentTypes() |
|
1473 | { |
||
1474 | 5 | if ($this->_contentTypes === null) { |
|
1475 | 4 | if ($this->headers->get('Accept') !== null) { |
|
1476 | 2 | $this->_contentTypes = $this->parseAcceptHeader($this->headers->get('Accept')); |
|
1477 | } else { |
||
1478 | 3 | $this->_contentTypes = []; |
|
1479 | } |
||
1480 | } |
||
1481 | |||
1482 | 5 | return $this->_contentTypes; |
|
1483 | } |
||
1484 | |||
1485 | /** |
||
1486 | * Sets the acceptable content types. |
||
1487 | * Please refer to [[getAcceptableContentTypes()]] on the format of the parameter. |
||
1488 | * @param array $value the content types that are acceptable by the end user. They should |
||
1489 | * be ordered by the preference level. |
||
1490 | * @see getAcceptableContentTypes() |
||
1491 | * @see parseAcceptHeader() |
||
1492 | */ |
||
1493 | 1 | public function setAcceptableContentTypes($value) |
|
1494 | { |
||
1495 | 1 | $this->_contentTypes = $value; |
|
1496 | 1 | } |
|
1497 | |||
1498 | /** |
||
1499 | * Returns request content-type |
||
1500 | * The Content-Type header field indicates the MIME type of the data |
||
1501 | * contained in [[getRawBody()]] or, in the case of the HEAD method, the |
||
1502 | * media type that would have been sent had the request been a GET. |
||
1503 | * For the MIME-types the user expects in response, see [[acceptableContentTypes]]. |
||
1504 | * @return string request content-type. Empty string is returned if this information is not available. |
||
1505 | * @link https://tools.ietf.org/html/rfc2616#section-14.17 |
||
1506 | * HTTP 1.1 header field definitions |
||
1507 | */ |
||
1508 | 7 | public function getContentType() |
|
1509 | { |
||
1510 | 7 | if (isset($_SERVER['CONTENT_TYPE'])) { |
|
1511 | 3 | return $_SERVER['CONTENT_TYPE']; |
|
1512 | } |
||
1513 | |||
1514 | //fix bug https://bugs.php.net/bug.php?id=66606 |
||
1515 | 4 | return $this->headers->get('Content-Type') ?: ''; |
|
1516 | } |
||
1517 | |||
1518 | private $_languages; |
||
1519 | |||
1520 | /** |
||
1521 | * Returns the languages acceptable by the end user. |
||
1522 | * This is determined by the `Accept-Language` HTTP header. |
||
1523 | * @return array the languages ordered by the preference level. The first element |
||
1524 | * represents the most preferred language. |
||
1525 | */ |
||
1526 | 2 | public function getAcceptableLanguages() |
|
1527 | { |
||
1528 | 2 | if ($this->_languages === null) { |
|
1529 | 1 | if ($this->headers->has('Accept-Language')) { |
|
1530 | $this->_languages = array_keys($this->parseAcceptHeader($this->headers->get('Accept-Language'))); |
||
1531 | } else { |
||
1532 | 1 | $this->_languages = []; |
|
1533 | } |
||
1534 | } |
||
1535 | |||
1536 | 2 | return $this->_languages; |
|
1537 | } |
||
1538 | |||
1539 | /** |
||
1540 | * @param array $value the languages that are acceptable by the end user. They should |
||
1541 | * be ordered by the preference level. |
||
1542 | */ |
||
1543 | 1 | public function setAcceptableLanguages($value) |
|
1544 | { |
||
1545 | 1 | $this->_languages = $value; |
|
1546 | 1 | } |
|
1547 | |||
1548 | /** |
||
1549 | * Parses the given `Accept` (or `Accept-Language`) header. |
||
1550 | * |
||
1551 | * This method will return the acceptable values with their quality scores and the corresponding parameters |
||
1552 | * as specified in the given `Accept` header. The array keys of the return value are the acceptable values, |
||
1553 | * while the array values consisting of the corresponding quality scores and parameters. The acceptable |
||
1554 | * values with the highest quality scores will be returned first. For example, |
||
1555 | * |
||
1556 | * ```php |
||
1557 | * $header = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;'; |
||
1558 | * $accepts = $request->parseAcceptHeader($header); |
||
1559 | * print_r($accepts); |
||
1560 | * // displays: |
||
1561 | * // [ |
||
1562 | * // 'application/json' => ['q' => 1, 'version' => '1.0'], |
||
1563 | * // 'application/xml' => ['q' => 1, 'version' => '2.0'], |
||
1564 | * // 'text/plain' => ['q' => 0.5], |
||
1565 | * // ] |
||
1566 | * ``` |
||
1567 | * |
||
1568 | * @param string $header the header to be parsed |
||
1569 | * @return array the acceptable values ordered by their quality score. The values with the highest scores |
||
1570 | * will be returned first. |
||
1571 | */ |
||
1572 | 3 | public function parseAcceptHeader($header) |
|
1573 | { |
||
1574 | 3 | $accepts = []; |
|
1575 | 3 | foreach (explode(',', $header) as $i => $part) { |
|
1576 | 3 | $params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY); |
|
1577 | 3 | if (empty($params)) { |
|
1578 | 1 | continue; |
|
1579 | } |
||
1580 | $values = [ |
||
1581 | 3 | 'q' => [$i, array_shift($params), 1], |
|
1582 | ]; |
||
1583 | 3 | foreach ($params as $param) { |
|
1584 | 2 | if (strpos($param, '=') !== false) { |
|
1585 | 2 | list($key, $value) = explode('=', $param, 2); |
|
1586 | 2 | if ($key === 'q') { |
|
1587 | 2 | $values['q'][2] = (float) $value; |
|
1588 | } else { |
||
1589 | 2 | $values[$key] = $value; |
|
1590 | } |
||
1591 | } else { |
||
1592 | 1 | $values[] = $param; |
|
1593 | } |
||
1594 | } |
||
1595 | 3 | $accepts[] = $values; |
|
1596 | } |
||
1597 | |||
1598 | usort($accepts, function ($a, $b) { |
||
1599 | 3 | $a = $a['q']; // index, name, q |
|
1600 | 3 | $b = $b['q']; |
|
1601 | 3 | if ($a[2] > $b[2]) { |
|
1602 | 2 | return -1; |
|
1603 | } |
||
1604 | |||
1605 | 2 | if ($a[2] < $b[2]) { |
|
1606 | 1 | return 1; |
|
1607 | } |
||
1608 | |||
1609 | 2 | if ($a[1] === $b[1]) { |
|
1610 | return $a[0] > $b[0] ? 1 : -1; |
||
1611 | } |
||
1612 | |||
1613 | 2 | if ($a[1] === '*/*') { |
|
1614 | return 1; |
||
1615 | } |
||
1616 | |||
1617 | 2 | if ($b[1] === '*/*') { |
|
1618 | return -1; |
||
1619 | } |
||
1620 | |||
1621 | 2 | $wa = $a[1][strlen($a[1]) - 1] === '*'; |
|
1622 | 2 | $wb = $b[1][strlen($b[1]) - 1] === '*'; |
|
1623 | 2 | if ($wa xor $wb) { |
|
1624 | return $wa ? 1 : -1; |
||
1625 | } |
||
1626 | |||
1627 | 2 | return $a[0] > $b[0] ? 1 : -1; |
|
1628 | 3 | }); |
|
1629 | |||
1630 | 3 | $result = []; |
|
1631 | 3 | foreach ($accepts as $accept) { |
|
1632 | 3 | $name = $accept['q'][1]; |
|
1633 | 3 | $accept['q'] = $accept['q'][2]; |
|
1634 | 3 | $result[$name] = $accept; |
|
1635 | } |
||
1636 | |||
1637 | 3 | return $result; |
|
1638 | } |
||
1639 | |||
1640 | /** |
||
1641 | * Returns the user-preferred language that should be used by this application. |
||
1642 | * The language resolution is based on the user preferred languages and the languages |
||
1643 | * supported by the application. The method will try to find the best match. |
||
1644 | * @param array $languages a list of the languages supported by the application. If this is empty, the current |
||
1645 | * application language will be returned without further processing. |
||
1646 | * @return string the language that the application should use. |
||
1647 | */ |
||
1648 | 1 | public function getPreferredLanguage(array $languages = []) |
|
1649 | { |
||
1650 | 1 | if (empty($languages)) { |
|
1651 | 1 | return Yii::$app->language; |
|
1652 | } |
||
1653 | 1 | foreach ($this->getAcceptableLanguages() as $acceptableLanguage) { |
|
1654 | 1 | $acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage)); |
|
1655 | 1 | foreach ($languages as $language) { |
|
1656 | 1 | $normalizedLanguage = str_replace('_', '-', strtolower($language)); |
|
1657 | |||
1658 | if ( |
||
1659 | 1 | $normalizedLanguage === $acceptableLanguage // en-us==en-us |
|
1660 | 1 | || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us |
|
1661 | 1 | || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en |
|
1662 | ) { |
||
1663 | 1 | return $language; |
|
1664 | } |
||
1665 | } |
||
1666 | } |
||
1667 | |||
1668 | 1 | return reset($languages); |
|
1669 | } |
||
1670 | |||
1671 | /** |
||
1672 | * Gets the Etags. |
||
1673 | * |
||
1674 | * @return array The entity tags |
||
1675 | */ |
||
1676 | public function getETags() |
||
1677 | { |
||
1678 | if ($this->headers->has('If-None-Match')) { |
||
1679 | return preg_split('/[\s,]+/', str_replace('-gzip', '', $this->headers->get('If-None-Match')), -1, PREG_SPLIT_NO_EMPTY); |
||
1680 | } |
||
1681 | |||
1682 | return []; |
||
1683 | } |
||
1684 | |||
1685 | /** |
||
1686 | * Returns the cookie collection. |
||
1687 | * |
||
1688 | * Through the returned cookie collection, you may access a cookie using the following syntax: |
||
1689 | * |
||
1690 | * ```php |
||
1691 | * $cookie = $request->cookies['name'] |
||
1692 | * if ($cookie !== null) { |
||
1693 | * $value = $cookie->value; |
||
1694 | * } |
||
1695 | * |
||
1696 | * // alternatively |
||
1697 | * $value = $request->cookies->getValue('name'); |
||
1698 | * ``` |
||
1699 | * |
||
1700 | * @return CookieCollection the cookie collection. |
||
1701 | */ |
||
1702 | 83 | public function getCookies() |
|
1703 | { |
||
1704 | 83 | if ($this->_cookies === null) { |
|
1705 | 83 | $this->_cookies = new CookieCollection($this->loadCookies(), [ |
|
1706 | 82 | 'readOnly' => true, |
|
1707 | ]); |
||
1708 | } |
||
1709 | |||
1710 | 82 | return $this->_cookies; |
|
1711 | } |
||
1712 | |||
1713 | /** |
||
1714 | * Converts `$_COOKIE` into an array of [[Cookie]]. |
||
1715 | * @return array the cookies obtained from request |
||
1716 | * @throws InvalidConfigException if [[cookieValidationKey]] is not set when [[enableCookieValidation]] is true |
||
1717 | */ |
||
1718 | 83 | protected function loadCookies() |
|
1719 | { |
||
1720 | 83 | $cookies = []; |
|
1721 | 83 | if ($this->enableCookieValidation) { |
|
1722 | 82 | if ($this->cookieValidationKey == '') { |
|
1723 | 1 | throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.'); |
|
1724 | } |
||
1725 | 81 | foreach ($_COOKIE as $name => $value) { |
|
1726 | if (!is_string($value)) { |
||
1727 | continue; |
||
1728 | } |
||
1729 | $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey); |
||
1730 | if ($data === false) { |
||
1731 | continue; |
||
1732 | } |
||
1733 | if (defined('PHP_VERSION_ID') && PHP_VERSION_ID >= 70000) { |
||
1734 | $data = @unserialize($data, ['allowed_classes' => false]); |
||
1735 | } else { |
||
1736 | $data = @unserialize($data); |
||
1737 | } |
||
1738 | if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) { |
||
1739 | $cookies[$name] = Yii::createObject([ |
||
1740 | 'class' => 'yii\web\Cookie', |
||
1741 | 'name' => $name, |
||
1742 | 'value' => $data[1], |
||
1743 | 'expire' => null, |
||
1744 | ]); |
||
1745 | } |
||
1746 | } |
||
1747 | } else { |
||
1748 | 1 | foreach ($_COOKIE as $name => $value) { |
|
1749 | 1 | $cookies[$name] = Yii::createObject([ |
|
1750 | 1 | 'class' => 'yii\web\Cookie', |
|
1751 | 1 | 'name' => $name, |
|
1752 | 1 | 'value' => $value, |
|
1753 | 'expire' => null, |
||
1754 | ]); |
||
1755 | } |
||
1756 | } |
||
1757 | |||
1758 | 82 | return $cookies; |
|
1759 | } |
||
1760 | |||
1761 | private $_csrfToken; |
||
1762 | |||
1763 | /** |
||
1764 | * Returns the token used to perform CSRF validation. |
||
1765 | * |
||
1766 | * This token is generated in a way to prevent [BREACH attacks](https://en.wikipedia.org/wiki/BREACH). It may be passed |
||
1767 | * along via a hidden field of an HTML form or an HTTP header value to support CSRF validation. |
||
1768 | * @param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time |
||
1769 | * this method is called, a new CSRF token will be generated and persisted (in session or cookie). |
||
1770 | * @return string the token used to perform CSRF validation. |
||
1771 | */ |
||
1772 | 89 | public function getCsrfToken($regenerate = false) |
|
1773 | { |
||
1774 | 89 | if ($this->_csrfToken === null || $regenerate) { |
|
1775 | 89 | $token = $this->loadCsrfToken(); |
|
1776 | 88 | if ($regenerate || empty($token)) { |
|
1777 | 85 | $token = $this->generateCsrfToken(); |
|
1778 | } |
||
1779 | 88 | $this->_csrfToken = Yii::$app->security->maskToken($token); |
|
1780 | } |
||
1781 | |||
1782 | 88 | return $this->_csrfToken; |
|
1783 | } |
||
1784 | |||
1785 | /** |
||
1786 | * Loads the CSRF token from cookie or session. |
||
1787 | * @return string|null the CSRF token loaded from cookie or session. Null is returned if the cookie or session |
||
1788 | * does not have CSRF token. |
||
1789 | */ |
||
1790 | 89 | protected function loadCsrfToken() |
|
1791 | { |
||
1792 | 89 | if ($this->enableCsrfCookie) { |
|
1793 | 85 | return $this->getCookies()->getValue($this->csrfParam); |
|
1794 | } |
||
1795 | |||
1796 | 4 | return Yii::$app->getSession()->get($this->csrfParam); |
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
1797 | } |
||
1798 | |||
1799 | /** |
||
1800 | * Generates an unmasked random token used to perform CSRF validation. |
||
1801 | * @return string the random token for CSRF validation. |
||
1802 | */ |
||
1803 | 85 | protected function generateCsrfToken() |
|
1804 | { |
||
1805 | 85 | $token = Yii::$app->getSecurity()->generateRandomString(); |
|
1806 | 85 | if ($this->enableCsrfCookie) { |
|
1807 | 84 | $cookie = $this->createCsrfCookie($token); |
|
1808 | 84 | Yii::$app->getResponse()->getCookies()->add($cookie); |
|
1809 | } else { |
||
1810 | 1 | Yii::$app->getSession()->set($this->csrfParam, $token); |
|
1811 | } |
||
1812 | |||
1813 | 85 | return $token; |
|
1814 | } |
||
1815 | |||
1816 | /** |
||
1817 | * @return string|null the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent. |
||
1818 | */ |
||
1819 | 3 | public function getCsrfTokenFromHeader() |
|
1820 | { |
||
1821 | 3 | return $this->headers->get(static::CSRF_HEADER); |
|
1822 | } |
||
1823 | |||
1824 | /** |
||
1825 | * Creates a cookie with a randomly generated CSRF token. |
||
1826 | * Initial values specified in [[csrfCookie]] will be applied to the generated cookie. |
||
1827 | * @param string $token the CSRF token |
||
1828 | * @return Cookie the generated cookie |
||
1829 | * @see enableCsrfValidation |
||
1830 | */ |
||
1831 | 84 | protected function createCsrfCookie($token) |
|
1832 | { |
||
1833 | 84 | $options = $this->csrfCookie; |
|
1834 | 84 | return Yii::createObject(array_merge($options, [ |
|
1835 | 84 | 'class' => 'yii\web\Cookie', |
|
1836 | 84 | 'name' => $this->csrfParam, |
|
1837 | 84 | 'value' => $token, |
|
1838 | ])); |
||
1839 | } |
||
1840 | |||
1841 | /** |
||
1842 | * Performs the CSRF validation. |
||
1843 | * |
||
1844 | * This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session. |
||
1845 | * This method is mainly called in [[Controller::beforeAction()]]. |
||
1846 | * |
||
1847 | * Note that the method will NOT perform CSRF validation if [[enableCsrfValidation]] is false or the HTTP method |
||
1848 | * is among GET, HEAD or OPTIONS. |
||
1849 | * |
||
1850 | * @param string|null $clientSuppliedToken the user-provided CSRF token to be validated. If null, the token will be retrieved from |
||
1851 | * the [[csrfParam]] POST field or HTTP header. |
||
1852 | * This parameter is available since version 2.0.4. |
||
1853 | * @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true. |
||
1854 | */ |
||
1855 | 8 | public function validateCsrfToken($clientSuppliedToken = null) |
|
1856 | { |
||
1857 | 8 | $method = $this->getMethod(); |
|
1858 | // only validate CSRF token on non-"safe" methods https://tools.ietf.org/html/rfc2616#section-9.1.1 |
||
1859 | 8 | if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) { |
|
1860 | 7 | return true; |
|
1861 | } |
||
1862 | |||
1863 | 4 | $trueToken = $this->getCsrfToken(); |
|
1864 | |||
1865 | 4 | if ($clientSuppliedToken !== null) { |
|
1866 | 2 | return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken); |
|
1867 | } |
||
1868 | |||
1869 | 3 | return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken) |
|
1870 | 3 | || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken); |
|
1871 | } |
||
1872 | |||
1873 | /** |
||
1874 | * Validates CSRF token. |
||
1875 | * |
||
1876 | * @param string $clientSuppliedToken The masked client-supplied token. |
||
1877 | * @param string $trueToken The masked true token. |
||
1878 | * @return bool |
||
1879 | */ |
||
1880 | 4 | private function validateCsrfTokenInternal($clientSuppliedToken, $trueToken) |
|
1881 | { |
||
1882 | 4 | if (!is_string($clientSuppliedToken)) { |
|
1883 | 3 | return false; |
|
1884 | } |
||
1885 | |||
1886 | 4 | $security = Yii::$app->security; |
|
1887 | |||
1888 | 4 | return $security->compareString($security->unmaskToken($clientSuppliedToken), $security->unmaskToken($trueToken)); |
|
1889 | } |
||
1890 | |||
1891 | /** |
||
1892 | * Gets first `Forwarded` header value for token |
||
1893 | * |
||
1894 | * @param string $token Header token |
||
1895 | * |
||
1896 | * @return string|null |
||
1897 | * |
||
1898 | * @since 2.0.31 |
||
1899 | */ |
||
1900 | 166 | protected function getSecureForwardedHeaderTrustedPart($token) |
|
1901 | { |
||
1902 | 166 | $token = strtolower($token); |
|
1903 | |||
1904 | 166 | if ($parts = $this->getSecureForwardedHeaderTrustedParts()) { |
|
1905 | 20 | $lastElement = array_pop($parts); |
|
1906 | 20 | if ($lastElement && isset($lastElement[$token])) { |
|
1907 | 20 | return $lastElement[$token]; |
|
1908 | } |
||
1909 | } |
||
1910 | 151 | return null; |
|
1911 | } |
||
1912 | |||
1913 | private $_secureForwardedHeaderTrustedParts; |
||
1914 | |||
1915 | /** |
||
1916 | * Gets only trusted `Forwarded` header parts |
||
1917 | * |
||
1918 | * @return array |
||
1919 | * |
||
1920 | * @since 2.0.31 |
||
1921 | */ |
||
1922 | 166 | protected function getSecureForwardedHeaderTrustedParts() |
|
1923 | { |
||
1924 | 166 | if ($this->_secureForwardedHeaderTrustedParts !== null) { |
|
1925 | 81 | return $this->_secureForwardedHeaderTrustedParts; |
|
1926 | } |
||
1927 | |||
1928 | 166 | $validator = $this->getIpValidator(); |
|
1929 | 166 | $trustedHosts = []; |
|
1930 | 166 | foreach ($this->trustedHosts as $trustedCidr => $trustedCidrOrHeaders) { |
|
1931 | 74 | if (!is_array($trustedCidrOrHeaders)) { |
|
1932 | 72 | $trustedCidr = $trustedCidrOrHeaders; |
|
1933 | } |
||
1934 | 74 | $trustedHosts[] = $trustedCidr; |
|
1935 | } |
||
1936 | 166 | $validator->setRanges($trustedHosts); |
|
1937 | |||
1938 | 166 | $this->_secureForwardedHeaderTrustedParts = array_filter( |
|
1939 | 166 | $this->getSecureForwardedHeaderParts(), |
|
1940 | function ($headerPart) use ($validator) { |
||
1941 | 20 | return isset($headerPart['for']) ? !$validator->validate($headerPart['for']) : true; |
|
1942 | 166 | } |
|
1943 | ); |
||
1944 | |||
1945 | 166 | return $this->_secureForwardedHeaderTrustedParts; |
|
1946 | } |
||
1947 | |||
1948 | private $_secureForwardedHeaderParts; |
||
1949 | |||
1950 | /** |
||
1951 | * Returns decoded forwarded header |
||
1952 | * |
||
1953 | * @return array |
||
1954 | * |
||
1955 | * @since 2.0.31 |
||
1956 | */ |
||
1957 | 166 | protected function getSecureForwardedHeaderParts() |
|
1958 | { |
||
1959 | 166 | if ($this->_secureForwardedHeaderParts !== null) { |
|
1960 | return $this->_secureForwardedHeaderParts; |
||
1961 | } |
||
1962 | 166 | if (count(preg_grep('/^forwarded$/i', $this->secureHeaders)) === 0) { |
|
1963 | 109 | return $this->_secureForwardedHeaderParts = []; |
|
1964 | } |
||
1965 | /* |
||
1966 | * First header is always correct, because proxy CAN add headers |
||
1967 | * after last one is found. |
||
1968 | * Keep in mind that it is NOT enforced, therefore we cannot be |
||
1969 | * sure, that this is really a first one. |
||
1970 | * |
||
1971 | * FPM keeps last header sent which is a bug. You need to merge |
||
1972 | * headers together on your web server before letting FPM handle it |
||
1973 | * @see https://bugs.php.net/bug.php?id=78844 |
||
1974 | */ |
||
1975 | 57 | $forwarded = $this->headers->get('Forwarded', ''); |
|
1976 | 57 | if ($forwarded === '') { |
|
1977 | 37 | return $this->_secureForwardedHeaderParts = []; |
|
1978 | } |
||
1979 | |||
1980 | 20 | preg_match_all('/(?:[^",]++|"[^"]++")+/', $forwarded, $forwardedElements); |
|
1981 | |||
1982 | 20 | foreach ($forwardedElements[0] as $forwardedPairs) { |
|
1983 | 20 | preg_match_all('/(?P<key>\w+)\s*=\s*(?:(?P<value>[^",;]*[^",;\s])|"(?P<value2>[^"]+)")/', $forwardedPairs, |
|
1984 | 20 | $matches, PREG_SET_ORDER); |
|
1985 | 20 | $this->_secureForwardedHeaderParts[] = array_reduce($matches, function ($carry, $item) { |
|
1986 | 20 | $value = $item['value']; |
|
1987 | 20 | if (isset($item['value2']) && $item['value2'] !== '') { |
|
1988 | 4 | $value = $item['value2']; |
|
1989 | } |
||
1990 | 20 | $carry[strtolower($item['key'])] = $value; |
|
1991 | 20 | return $carry; |
|
1992 | 20 | }, []); |
|
1993 | } |
||
1994 | 20 | return $this->_secureForwardedHeaderParts; |
|
1995 | } |
||
1996 | } |
||
1997 |