Request.php 55 KB

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