Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1444 linhas
53KB

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