Request.php 40 KB

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