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