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

/vendor/yiisoft/yii2/web/Request.php

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