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.

1388 linhas
51KB

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