PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/web/Request.php

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