Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1422 lines
52KB

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