Request.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  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. /**
  11. * The web Request class represents an HTTP request
  12. *
  13. * It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.
  14. * Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST
  15. * parameters sent via other HTTP methods like PUT or DELETE.
  16. *
  17. * Request is configured as an application component in [[\yii\web\Application]] by default.
  18. * You can access that instance via `Yii::$app->request`.
  19. *
  20. * For more details and usage information on Request, see the [guide article on requests](guide:runtime-requests).
  21. *
  22. * @property string $absoluteUrl The currently requested absolute URL. This property is read-only.
  23. * @property array $acceptableContentTypes The content types ordered by the quality score. Types with the
  24. * highest scores will be returned first. The array keys are the content types, while the array values are the
  25. * corresponding quality score and other parameters as given in the header.
  26. * @property array $acceptableLanguages The languages ordered by the preference level. The first element
  27. * represents the most preferred language.
  28. * @property string|null $authPassword The password sent via HTTP authentication, null if the password is not
  29. * given. This property is read-only.
  30. * @property string|null $authUser The username sent via HTTP authentication, null if the username is not
  31. * given. This property is read-only.
  32. * @property string $baseUrl The relative URL for the application.
  33. * @property array $bodyParams The request parameters given in the request body.
  34. * @property string $contentType Request content-type. Null is returned if this information is not available.
  35. * This property is read-only.
  36. * @property CookieCollection $cookies The cookie collection. This property is read-only.
  37. * @property string $csrfToken The token used to perform CSRF validation. This property is read-only.
  38. * @property string $csrfTokenFromHeader The CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned
  39. * if no such header is sent. This property is read-only.
  40. * @property array $eTags The entity tags. This property is read-only.
  41. * @property HeaderCollection $headers The header collection. This property is read-only.
  42. * @property string|null $hostInfo Schema and hostname part (with port number if needed) of the request URL
  43. * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set. See
  44. * [[getHostInfo()]] for security related notes on this property.
  45. * @property string|null $hostName Hostname part of the request URL (e.g. `www.yiiframework.com`). This
  46. * property is read-only.
  47. * @property bool $isAjax Whether this is an AJAX (XMLHttpRequest) request. This property is read-only.
  48. * @property bool $isDelete Whether this is a DELETE request. This property is read-only.
  49. * @property bool $isFlash Whether this is an Adobe Flash or Adobe Flex request. This property is read-only.
  50. * @property bool $isGet Whether this is a GET request. This property is read-only.
  51. * @property bool $isHead Whether this is a HEAD request. This property is read-only.
  52. * @property bool $isOptions Whether this is a OPTIONS request. This property is read-only.
  53. * @property bool $isPatch Whether this is a PATCH request. This property is read-only.
  54. * @property bool $isPjax Whether this is a PJAX request. This property is read-only.
  55. * @property bool $isPost Whether this is a POST request. This property is read-only.
  56. * @property bool $isPut Whether this is a PUT request. This property is read-only.
  57. * @property bool $isSecureConnection If the request is sent via secure channel (https). This property is
  58. * read-only.
  59. * @property string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is
  60. * turned into upper case. This property is read-only.
  61. * @property string $pathInfo Part of the request URL that is after the entry script and before the question
  62. * mark. Note, the returned path info is already URL-decoded.
  63. * @property int $port Port number for insecure requests.
  64. * @property array $queryParams The request GET parameter values.
  65. * @property string $queryString Part of the request URL that is after the question mark. This property is
  66. * read-only.
  67. * @property string $rawBody The request body.
  68. * @property string|null $referrer URL referrer, null if not available. This property is read-only.
  69. * @property string $scriptFile The entry script file path.
  70. * @property string $scriptUrl The relative URL of the entry script.
  71. * @property int $securePort Port number for secure requests.
  72. * @property string $serverName Server name, null if not available. This property is read-only.
  73. * @property int|null $serverPort Server port number, null if not available. This property is read-only.
  74. * @property string $url The currently requested relative URL. Note that the URI returned may be URL-encoded
  75. * depending on the client.
  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. * @deprecated 2.0.12 The mask length is now equal to the token length.
  92. */
  93. const CSRF_MASK_LENGTH = 8;
  94. /**
  95. * @var bool whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true.
  96. * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated
  97. * from the same application. If not, a 400 HTTP exception will be raised.
  98. *
  99. * Note, this feature requires that the user client accepts cookie. Also, to use this feature,
  100. * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfParam]].
  101. * You may use [[\yii\helpers\Html::beginForm()]] to generate his hidden input.
  102. *
  103. * In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and
  104. * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered.
  105. * You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]].
  106. *
  107. * @see Controller::enableCsrfValidation
  108. * @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
  109. */
  110. public $enableCsrfValidation = true;
  111. /**
  112. * @var string the name of the token used to prevent CSRF. Defaults to '_csrf'.
  113. * This property is used only when [[enableCsrfValidation]] is true.
  114. */
  115. public $csrfParam = '_csrf';
  116. /**
  117. * @var array the configuration for creating the CSRF [[Cookie|cookie]]. This property is used only when
  118. * both [[enableCsrfValidation]] and [[enableCsrfCookie]] are true.
  119. */
  120. public $csrfCookie = ['httpOnly' => true];
  121. /**
  122. * @var bool whether to use cookie to persist CSRF token. If false, CSRF token will be stored
  123. * in session under the name of [[csrfParam]]. Note that while storing CSRF tokens in session increases
  124. * security, it requires starting a session for every page, which will degrade your site performance.
  125. */
  126. public $enableCsrfCookie = true;
  127. /**
  128. * @var bool whether cookies should be validated to ensure they are not tampered. Defaults to true.
  129. */
  130. public $enableCookieValidation = true;
  131. /**
  132. * @var string a secret key used for cookie validation. This property must be set if [[enableCookieValidation]] is true.
  133. */
  134. public $cookieValidationKey;
  135. /**
  136. * @var string the name of the POST parameter that is used to indicate if a request is a PUT, PATCH or DELETE
  137. * request tunneled through POST. Defaults to '_method'.
  138. * @see getMethod()
  139. * @see getBodyParams()
  140. */
  141. public $methodParam = '_method';
  142. /**
  143. * @var array the parsers for converting the raw HTTP request body into [[bodyParams]].
  144. * The array keys are the request `Content-Types`, and the array values are the
  145. * corresponding configurations for [[Yii::createObject|creating the parser objects]].
  146. * A parser must implement the [[RequestParserInterface]].
  147. *
  148. * To enable parsing for JSON requests you can use the [[JsonParser]] class like in the following example:
  149. *
  150. * ```
  151. * [
  152. * 'application/json' => 'yii\web\JsonParser',
  153. * ]
  154. * ```
  155. *
  156. * To register a parser for parsing all request types you can use `'*'` as the array key.
  157. * This one will be used as a fallback in case no other types match.
  158. *
  159. * @see getBodyParams()
  160. */
  161. public $parsers = [];
  162. /**
  163. * @var CookieCollection Collection of request cookies.
  164. */
  165. private $_cookies;
  166. /**
  167. * @var HeaderCollection Collection of request headers.
  168. */
  169. private $_headers;
  170. /**
  171. * Resolves the current request into a route and the associated parameters.
  172. * @return array the first element is the route, and the second is the associated parameters.
  173. * @throws NotFoundHttpException if the request cannot be resolved.
  174. */
  175. public function resolve()
  176. {
  177. $result = Yii::$app->getUrlManager()->parseRequest($this);
  178. if ($result !== false) {
  179. list ($route, $params) = $result;
  180. if ($this->_queryParams === null) {
  181. $_GET = $params + $_GET; // preserve numeric keys
  182. } else {
  183. $this->_queryParams = $params + $this->_queryParams;
  184. }
  185. return [$route, $this->getQueryParams()];
  186. }
  187. throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
  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. }
  426. return $this->getBodyParam($name, $defaultValue);
  427. }
  428. private $_queryParams;
  429. /**
  430. * Returns the request parameters given in the [[queryString]].
  431. *
  432. * This method will return the contents of `$_GET` if params where not explicitly set.
  433. * @return array the request GET parameter values.
  434. * @see setQueryParams()
  435. */
  436. public function getQueryParams()
  437. {
  438. if ($this->_queryParams === null) {
  439. return $_GET;
  440. }
  441. return $this->_queryParams;
  442. }
  443. /**
  444. * Sets the request [[queryString]] parameters.
  445. * @param array $values the request query parameters (name-value pairs)
  446. * @see getQueryParam()
  447. * @see getQueryParams()
  448. */
  449. public function setQueryParams($values)
  450. {
  451. $this->_queryParams = $values;
  452. }
  453. /**
  454. * Returns GET parameter with a given name. If name isn't specified, returns an array of all GET parameters.
  455. *
  456. * @param string $name the parameter name
  457. * @param mixed $defaultValue the default parameter value if the parameter does not exist.
  458. * @return array|mixed
  459. */
  460. public function get($name = null, $defaultValue = null)
  461. {
  462. if ($name === null) {
  463. return $this->getQueryParams();
  464. }
  465. return $this->getQueryParam($name, $defaultValue);
  466. }
  467. /**
  468. * Returns the named GET parameter value.
  469. * If the GET parameter does not exist, the second parameter passed to this method will be returned.
  470. * @param string $name the GET parameter name.
  471. * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
  472. * @return mixed the GET parameter value
  473. * @see getBodyParam()
  474. */
  475. public function getQueryParam($name, $defaultValue = null)
  476. {
  477. $params = $this->getQueryParams();
  478. return isset($params[$name]) ? $params[$name] : $defaultValue;
  479. }
  480. private $_hostInfo;
  481. private $_hostName;
  482. /**
  483. * Returns the schema and host part of the current request URL.
  484. *
  485. * The returned URL does not have an ending slash.
  486. *
  487. * By default this value is based on the user request information. This method will
  488. * return the value of `$_SERVER['HTTP_HOST']` if it is available or `$_SERVER['SERVER_NAME']` if not.
  489. * You may want to check out the [PHP documentation](http://php.net/manual/en/reserved.variables.server.php)
  490. * for more information on these variables.
  491. *
  492. * You may explicitly specify it by setting the [[setHostInfo()|hostInfo]] property.
  493. *
  494. * > Warning: Dependent on the server configuration this information may not be
  495. * > reliable and [may be faked by the user sending the HTTP request](https://www.acunetix.com/vulnerabilities/web/host-header-attack).
  496. * > If the webserver is configured to serve the same site independent of the value of
  497. * > the `Host` header, this value is not reliable. In such situations you should either
  498. * > fix your webserver configuration or explicitly set the value by setting the [[setHostInfo()|hostInfo]] property.
  499. * > If you don't have access to the server configuration, you can setup [[\yii\filters\HostControl]] filter at
  500. * > application level in order to protect against such kind of attack.
  501. *
  502. * @property string|null schema and hostname part (with port number if needed) of the request URL
  503. * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
  504. * See [[getHostInfo()]] for security related notes on this property.
  505. * @return string|null schema and hostname part (with port number if needed) of the request URL
  506. * (e.g. `http://www.yiiframework.com`), null if can't be obtained from `$_SERVER` and wasn't set.
  507. * @see setHostInfo()
  508. */
  509. public function getHostInfo()
  510. {
  511. if ($this->_hostInfo === null) {
  512. $secure = $this->getIsSecureConnection();
  513. $http = $secure ? 'https' : 'http';
  514. if (isset($_SERVER['HTTP_HOST'])) {
  515. $this->_hostInfo = $http . '://' . $_SERVER['HTTP_HOST'];
  516. } elseif (isset($_SERVER['SERVER_NAME'])) {
  517. $this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME'];
  518. $port = $secure ? $this->getSecurePort() : $this->getPort();
  519. if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
  520. $this->_hostInfo .= ':' . $port;
  521. }
  522. }
  523. }
  524. return $this->_hostInfo;
  525. }
  526. /**
  527. * Sets the schema and host part of the application URL.
  528. * This setter is provided in case the schema and hostname cannot be determined
  529. * on certain Web servers.
  530. * @param string|null $value the schema and host part of the application URL. The trailing slashes will be removed.
  531. * @see getHostInfo() for security related notes on this property.
  532. */
  533. public function setHostInfo($value)
  534. {
  535. $this->_hostName = null;
  536. $this->_hostInfo = $value === null ? null : rtrim($value, '/');
  537. }
  538. /**
  539. * Returns the host part of the current request URL.
  540. * Value is calculated from current [[getHostInfo()|hostInfo]] property.
  541. *
  542. * > Warning: The content of this value may not be reliable, dependent on the server
  543. * > configuration. Please refer to [[getHostInfo()]] for more information.
  544. *
  545. * @return string|null hostname part of the request URL (e.g. `www.yiiframework.com`)
  546. * @see getHostInfo()
  547. * @since 2.0.10
  548. */
  549. public function getHostName()
  550. {
  551. if ($this->_hostName === null) {
  552. $this->_hostName = parse_url($this->getHostInfo(), PHP_URL_HOST);
  553. }
  554. return $this->_hostName;
  555. }
  556. private $_baseUrl;
  557. /**
  558. * Returns the relative URL for the application.
  559. * This is similar to [[scriptUrl]] except that it does not include the script file name,
  560. * and the ending slashes are removed.
  561. * @return string the relative URL for the application
  562. * @see setScriptUrl()
  563. */
  564. public function getBaseUrl()
  565. {
  566. if ($this->_baseUrl === null) {
  567. $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/');
  568. }
  569. return $this->_baseUrl;
  570. }
  571. /**
  572. * Sets the relative URL for the application.
  573. * By default the URL is determined based on the entry script URL.
  574. * This setter is provided in case you want to change this behavior.
  575. * @param string $value the relative URL for the application
  576. */
  577. public function setBaseUrl($value)
  578. {
  579. $this->_baseUrl = $value;
  580. }
  581. private $_scriptUrl;
  582. /**
  583. * Returns the relative URL of the entry script.
  584. * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
  585. * @return string the relative URL of the entry script.
  586. * @throws InvalidConfigException if unable to determine the entry script URL
  587. */
  588. public function getScriptUrl()
  589. {
  590. if ($this->_scriptUrl === null) {
  591. $scriptFile = $this->getScriptFile();
  592. $scriptName = basename($scriptFile);
  593. if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
  594. $this->_scriptUrl = $_SERVER['SCRIPT_NAME'];
  595. } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $scriptName) {
  596. $this->_scriptUrl = $_SERVER['PHP_SELF'];
  597. } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
  598. $this->_scriptUrl = $_SERVER['ORIG_SCRIPT_NAME'];
  599. } elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
  600. $this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
  601. } elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) {
  602. $this->_scriptUrl = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $scriptFile));
  603. } else {
  604. throw new InvalidConfigException('Unable to determine the entry script URL.');
  605. }
  606. }
  607. return $this->_scriptUrl;
  608. }
  609. /**
  610. * Sets the relative URL for the application entry script.
  611. * This setter is provided in case the entry script URL cannot be determined
  612. * on certain Web servers.
  613. * @param string $value the relative URL for the application entry script.
  614. */
  615. public function setScriptUrl($value)
  616. {
  617. $this->_scriptUrl = $value === null ? null : '/' . trim($value, '/');
  618. }
  619. private $_scriptFile;
  620. /**
  621. * Returns the entry script file path.
  622. * The default implementation will simply return `$_SERVER['SCRIPT_FILENAME']`.
  623. * @return string the entry script file path
  624. * @throws InvalidConfigException
  625. */
  626. public function getScriptFile()
  627. {
  628. if (isset($this->_scriptFile)) {
  629. return $this->_scriptFile;
  630. }
  631. if (isset($_SERVER['SCRIPT_FILENAME'])) {
  632. return $_SERVER['SCRIPT_FILENAME'];
  633. }
  634. throw new InvalidConfigException('Unable to determine the entry script file path.');
  635. }
  636. /**
  637. * Sets the entry script file path.
  638. * The entry script file path normally can be obtained from `$_SERVER['SCRIPT_FILENAME']`.
  639. * If your server configuration does not return the correct value, you may configure
  640. * this property to make it right.
  641. * @param string $value the entry script file path.
  642. */
  643. public function setScriptFile($value)
  644. {
  645. $this->_scriptFile = $value;
  646. }
  647. private $_pathInfo;
  648. /**
  649. * Returns the path info of the currently requested URL.
  650. * A path info refers to the part that is after the entry script and before the question mark (query string).
  651. * The starting and ending slashes are both removed.
  652. * @return string part of the request URL that is after the entry script and before the question mark.
  653. * Note, the returned path info is already URL-decoded.
  654. * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
  655. */
  656. public function getPathInfo()
  657. {
  658. if ($this->_pathInfo === null) {
  659. $this->_pathInfo = $this->resolvePathInfo();
  660. }
  661. return $this->_pathInfo;
  662. }
  663. /**
  664. * Sets the path info of the current request.
  665. * This method is mainly provided for testing purpose.
  666. * @param string $value the path info of the current request
  667. */
  668. public function setPathInfo($value)
  669. {
  670. $this->_pathInfo = $value === null ? null : ltrim($value, '/');
  671. }
  672. /**
  673. * Resolves the path info part of the currently requested URL.
  674. * A path info refers to the part that is after the entry script and before the question mark (query string).
  675. * The starting slashes are both removed (ending slashes will be kept).
  676. * @return string part of the request URL that is after the entry script and before the question mark.
  677. * Note, the returned path info is decoded.
  678. * @throws InvalidConfigException if the path info cannot be determined due to unexpected server configuration
  679. */
  680. protected function resolvePathInfo()
  681. {
  682. $pathInfo = $this->getUrl();
  683. if (($pos = strpos($pathInfo, '?')) !== false) {
  684. $pathInfo = substr($pathInfo, 0, $pos);
  685. }
  686. $pathInfo = urldecode($pathInfo);
  687. // try to encode in UTF8 if not so
  688. // http://w3.org/International/questions/qa-forms-utf-8.html
  689. if (!preg_match('%^(?:
  690. [\x09\x0A\x0D\x20-\x7E] # ASCII
  691. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  692. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  693. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  694. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  695. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  696. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  697. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  698. )*$%xs', $pathInfo)
  699. ) {
  700. $pathInfo = utf8_encode($pathInfo);
  701. }
  702. $scriptUrl = $this->getScriptUrl();
  703. $baseUrl = $this->getBaseUrl();
  704. if (strpos($pathInfo, $scriptUrl) === 0) {
  705. $pathInfo = substr($pathInfo, strlen($scriptUrl));
  706. } elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) {
  707. $pathInfo = substr($pathInfo, strlen($baseUrl));
  708. } elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0) {
  709. $pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
  710. } else {
  711. throw new InvalidConfigException('Unable to determine the path info of the current request.');
  712. }
  713. if (substr($pathInfo, 0, 1) === '/') {
  714. $pathInfo = substr($pathInfo, 1);
  715. }
  716. return (string) $pathInfo;
  717. }
  718. /**
  719. * Returns the currently requested absolute URL.
  720. * This is a shortcut to the concatenation of [[hostInfo]] and [[url]].
  721. * @return string the currently requested absolute URL.
  722. */
  723. public function getAbsoluteUrl()
  724. {
  725. return $this->getHostInfo() . $this->getUrl();
  726. }
  727. private $_url;
  728. /**
  729. * Returns the currently requested relative URL.
  730. * This refers to the portion of the URL that is after the [[hostInfo]] part.
  731. * It includes the [[queryString]] part if any.
  732. * @return string the currently requested relative URL. Note that the URI returned may be URL-encoded depending on the client.
  733. * @throws InvalidConfigException if the URL cannot be determined due to unusual server configuration
  734. */
  735. public function getUrl()
  736. {
  737. if ($this->_url === null) {
  738. $this->_url = $this->resolveRequestUri();
  739. }
  740. return $this->_url;
  741. }
  742. /**
  743. * Sets the currently requested relative URL.
  744. * The URI must refer to the portion that is after [[hostInfo]].
  745. * Note that the URI should be URL-encoded.
  746. * @param string $value the request URI to be set
  747. */
  748. public function setUrl($value)
  749. {
  750. $this->_url = $value;
  751. }
  752. /**
  753. * Resolves the request URI portion for the currently requested URL.
  754. * This refers to the portion that is after the [[hostInfo]] part. It includes the [[queryString]] part if any.
  755. * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
  756. * @return string|bool the request URI portion for the currently requested URL.
  757. * Note that the URI returned may be URL-encoded depending on the client.
  758. * @throws InvalidConfigException if the request URI cannot be determined due to unusual server configuration
  759. */
  760. protected function resolveRequestUri()
  761. {
  762. if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { // IIS
  763. $requestUri = $_SERVER['HTTP_X_REWRITE_URL'];
  764. } elseif (isset($_SERVER['REQUEST_URI'])) {
  765. $requestUri = $_SERVER['REQUEST_URI'];
  766. if ($requestUri !== '' && $requestUri[0] !== '/') {
  767. $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
  768. }
  769. } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 CGI
  770. $requestUri = $_SERVER['ORIG_PATH_INFO'];
  771. if (!empty($_SERVER['QUERY_STRING'])) {
  772. $requestUri .= '?' . $_SERVER['QUERY_STRING'];
  773. }
  774. } else {
  775. throw new InvalidConfigException('Unable to determine the request URI.');
  776. }
  777. return $requestUri;
  778. }
  779. /**
  780. * Returns part of the request URL that is after the question mark.
  781. * @return string part of the request URL that is after the question mark
  782. */
  783. public function getQueryString()
  784. {
  785. return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
  786. }
  787. /**
  788. * Return if the request is sent via secure channel (https).
  789. * @return bool if the request is sent via secure channel (https)
  790. */
  791. public function getIsSecureConnection()
  792. {
  793. return isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)
  794. || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;
  795. }
  796. /**
  797. * Returns the server name.
  798. * @return string server name, null if not available
  799. */
  800. public function getServerName()
  801. {
  802. return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
  803. }
  804. /**
  805. * Returns the server port number.
  806. * @return int|null server port number, null if not available
  807. */
  808. public function getServerPort()
  809. {
  810. return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null;
  811. }
  812. /**
  813. * Returns the URL referrer.
  814. * @return string|null URL referrer, null if not available
  815. */
  816. public function getReferrer()
  817. {
  818. return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  819. }
  820. /**
  821. * Returns the user agent.
  822. * @return string|null user agent, null if not available
  823. */
  824. public function getUserAgent()
  825. {
  826. return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  827. }
  828. /**
  829. * Returns the user IP address.
  830. * @return string|null user IP address, null if not available
  831. */
  832. public function getUserIP()
  833. {
  834. return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
  835. }
  836. /**
  837. * Returns the user host name.
  838. * @return string|null user host name, null if not available
  839. */
  840. public function getUserHost()
  841. {
  842. return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
  843. }
  844. /**
  845. * @return string|null the username sent via HTTP authentication, null if the username is not given
  846. */
  847. public function getAuthUser()
  848. {
  849. return isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
  850. }
  851. /**
  852. * @return string|null the password sent via HTTP authentication, null if the password is not given
  853. */
  854. public function getAuthPassword()
  855. {
  856. return isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
  857. }
  858. private $_port;
  859. /**
  860. * Returns the port to use for insecure requests.
  861. * Defaults to 80, or the port specified by the server if the current
  862. * request is insecure.
  863. * @return int port number for insecure requests.
  864. * @see setPort()
  865. */
  866. public function getPort()
  867. {
  868. if ($this->_port === null) {
  869. $this->_port = !$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : 80;
  870. }
  871. return $this->_port;
  872. }
  873. /**
  874. * Sets the port to use for insecure requests.
  875. * This setter is provided in case a custom port is necessary for certain
  876. * server configurations.
  877. * @param int $value port number.
  878. */
  879. public function setPort($value)
  880. {
  881. if ($value != $this->_port) {
  882. $this->_port = (int) $value;
  883. $this->_hostInfo = null;
  884. }
  885. }
  886. private $_securePort;
  887. /**
  888. * Returns the port to use for secure requests.
  889. * Defaults to 443, or the port specified by the server if the current
  890. * request is secure.
  891. * @return int port number for secure requests.
  892. * @see setSecurePort()
  893. */
  894. public function getSecurePort()
  895. {
  896. if ($this->_securePort === null) {
  897. $this->_securePort = $this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : 443;
  898. }
  899. return $this->_securePort;
  900. }
  901. /**
  902. * Sets the port to use for secure requests.
  903. * This setter is provided in case a custom port is necessary for certain
  904. * server configurations.
  905. * @param int $value port number.
  906. */
  907. public function setSecurePort($value)
  908. {
  909. if ($value != $this->_securePort) {
  910. $this->_securePort = (int) $value;
  911. $this->_hostInfo = null;
  912. }
  913. }
  914. private $_contentTypes;
  915. /**
  916. * Returns the content types acceptable by the end user.
  917. * This is determined by the `Accept` HTTP header. For example,
  918. *
  919. * ```php
  920. * $_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
  921. * $types = $request->getAcceptableContentTypes();
  922. * print_r($types);
  923. * // displays:
  924. * // [
  925. * // 'application/json' => ['q' => 1, 'version' => '1.0'],
  926. * // 'application/xml' => ['q' => 1, 'version' => '2.0'],
  927. * // 'text/plain' => ['q' => 0.5],
  928. * // ]
  929. * ```
  930. *
  931. * @return array the content types ordered by the quality score. Types with the highest scores
  932. * will be returned first. The array keys are the content types, while the array values
  933. * are the corresponding quality score and other parameters as given in the header.
  934. */
  935. public function getAcceptableContentTypes()
  936. {
  937. if ($this->_contentTypes === null) {
  938. if (isset($_SERVER['HTTP_ACCEPT'])) {
  939. $this->_contentTypes = $this->parseAcceptHeader($_SERVER['HTTP_ACCEPT']);
  940. } else {
  941. $this->_contentTypes = [];
  942. }
  943. }
  944. return $this->_contentTypes;
  945. }
  946. /**
  947. * Sets the acceptable content types.
  948. * Please refer to [[getAcceptableContentTypes()]] on the format of the parameter.
  949. * @param array $value the content types that are acceptable by the end user. They should
  950. * be ordered by the preference level.
  951. * @see getAcceptableContentTypes()
  952. * @see parseAcceptHeader()
  953. */
  954. public function setAcceptableContentTypes($value)
  955. {
  956. $this->_contentTypes = $value;
  957. }
  958. /**
  959. * Returns request content-type
  960. * The Content-Type header field indicates the MIME type of the data
  961. * contained in [[getRawBody()]] or, in the case of the HEAD method, the
  962. * media type that would have been sent had the request been a GET.
  963. * For the MIME-types the user expects in response, see [[acceptableContentTypes]].
  964. * @return string request content-type. Null is returned if this information is not available.
  965. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
  966. * HTTP 1.1 header field definitions
  967. */
  968. public function getContentType()
  969. {
  970. if (isset($_SERVER['CONTENT_TYPE'])) {
  971. return $_SERVER['CONTENT_TYPE'];
  972. }
  973. if (isset($_SERVER['HTTP_CONTENT_TYPE'])) {
  974. //fix bug https://bugs.php.net/bug.php?id=66606
  975. return $_SERVER['HTTP_CONTENT_TYPE'];
  976. }
  977. return null;
  978. }
  979. private $_languages;
  980. /**
  981. * Returns the languages acceptable by the end user.
  982. * This is determined by the `Accept-Language` HTTP header.
  983. * @return array the languages ordered by the preference level. The first element
  984. * represents the most preferred language.
  985. */
  986. public function getAcceptableLanguages()
  987. {
  988. if ($this->_languages === null) {
  989. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  990. $this->_languages = array_keys($this->parseAcceptHeader($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  991. } else {
  992. $this->_languages = [];
  993. }
  994. }
  995. return $this->_languages;
  996. }
  997. /**
  998. * @param array $value the languages that are acceptable by the end user. They should
  999. * be ordered by the preference level.
  1000. */
  1001. public function setAcceptableLanguages($value)
  1002. {
  1003. $this->_languages = $value;
  1004. }
  1005. /**
  1006. * Parses the given `Accept` (or `Accept-Language`) header.
  1007. *
  1008. * This method will return the acceptable values with their quality scores and the corresponding parameters
  1009. * as specified in the given `Accept` header. The array keys of the return value are the acceptable values,
  1010. * while the array values consisting of the corresponding quality scores and parameters. The acceptable
  1011. * values with the highest quality scores will be returned first. For example,
  1012. *
  1013. * ```php
  1014. * $header = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
  1015. * $accepts = $request->parseAcceptHeader($header);
  1016. * print_r($accepts);
  1017. * // displays:
  1018. * // [
  1019. * // 'application/json' => ['q' => 1, 'version' => '1.0'],
  1020. * // 'application/xml' => ['q' => 1, 'version' => '2.0'],
  1021. * // 'text/plain' => ['q' => 0.5],
  1022. * // ]
  1023. * ```
  1024. *
  1025. * @param string $header the header to be parsed
  1026. * @return array the acceptable values ordered by their quality score. The values with the highest scores
  1027. * will be returned first.
  1028. */
  1029. public function parseAcceptHeader($header)
  1030. {
  1031. $accepts = [];
  1032. foreach (explode(',', $header) as $i => $part) {
  1033. $params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY);
  1034. if (empty($params)) {
  1035. continue;
  1036. }
  1037. $values = [
  1038. 'q' => [$i, array_shift($params), 1],
  1039. ];
  1040. foreach ($params as $param) {
  1041. if (strpos($param, '=') !== false) {
  1042. list ($key, $value) = explode('=', $param, 2);
  1043. if ($key === 'q') {
  1044. $values['q'][2] = (double) $value;
  1045. } else {
  1046. $values[$key] = $value;
  1047. }
  1048. } else {
  1049. $values[] = $param;
  1050. }
  1051. }
  1052. $accepts[] = $values;
  1053. }
  1054. usort($accepts, function ($a, $b) {
  1055. $a = $a['q']; // index, name, q
  1056. $b = $b['q'];
  1057. if ($a[2] > $b[2]) {
  1058. return -1;
  1059. }
  1060. if ($a[2] < $b[2]) {
  1061. return 1;
  1062. }
  1063. if ($a[1] === $b[1]) {
  1064. return $a[0] > $b[0] ? 1 : -1;
  1065. }
  1066. if ($a[1] === '*/*') {
  1067. return 1;
  1068. }
  1069. if ($b[1] === '*/*') {
  1070. return -1;
  1071. }
  1072. $wa = $a[1][strlen($a[1]) - 1] === '*';
  1073. $wb = $b[1][strlen($b[1]) - 1] === '*';
  1074. if ($wa xor $wb) {
  1075. return $wa ? 1 : -1;
  1076. }
  1077. return $a[0] > $b[0] ? 1 : -1;
  1078. });
  1079. $result = [];
  1080. foreach ($accepts as $accept) {
  1081. $name = $accept['q'][1];
  1082. $accept['q'] = $accept['q'][2];
  1083. $result[$name] = $accept;
  1084. }
  1085. return $result;
  1086. }
  1087. /**
  1088. * Returns the user-preferred language that should be used by this application.
  1089. * The language resolution is based on the user preferred languages and the languages
  1090. * supported by the application. The method will try to find the best match.
  1091. * @param array $languages a list of the languages supported by the application. If this is empty, the current
  1092. * application language will be returned without further processing.
  1093. * @return string the language that the application should use.
  1094. */
  1095. public function getPreferredLanguage(array $languages = [])
  1096. {
  1097. if (empty($languages)) {
  1098. return Yii::$app->language;
  1099. }
  1100. foreach ($this->getAcceptableLanguages() as $acceptableLanguage) {
  1101. $acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
  1102. foreach ($languages as $language) {
  1103. $normalizedLanguage = str_replace('_', '-', strtolower($language));
  1104. if ($normalizedLanguage === $acceptableLanguage || // en-us==en-us
  1105. strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 || // en==en-us
  1106. strpos($normalizedLanguage, $acceptableLanguage . '-') === 0) { // en-us==en
  1107. return $language;
  1108. }
  1109. }
  1110. }
  1111. return reset($languages);
  1112. }
  1113. /**
  1114. * Gets the Etags.
  1115. *
  1116. * @return array The entity tags
  1117. */
  1118. public function getETags()
  1119. {
  1120. if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
  1121. return preg_split('/[\s,]+/', str_replace('-gzip', '', $_SERVER['HTTP_IF_NONE_MATCH']), -1, PREG_SPLIT_NO_EMPTY);
  1122. }
  1123. return [];
  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. $this->_csrfToken = Yii::$app->security->maskToken($token);
  1207. }
  1208. return $this->_csrfToken;
  1209. }
  1210. /**
  1211. * Loads the CSRF token from cookie or session.
  1212. * @return string the CSRF token loaded from cookie or session. Null is returned if the cookie or session
  1213. * does not have CSRF token.
  1214. */
  1215. protected function loadCsrfToken()
  1216. {
  1217. if ($this->enableCsrfCookie) {
  1218. return $this->getCookies()->getValue($this->csrfParam);
  1219. }
  1220. return Yii::$app->getSession()->get($this->csrfParam);
  1221. }
  1222. /**
  1223. * Generates an unmasked random token used to perform CSRF validation.
  1224. * @return string the random token for CSRF validation.
  1225. */
  1226. protected function generateCsrfToken()
  1227. {
  1228. $token = Yii::$app->getSecurity()->generateRandomKey();
  1229. if ($this->enableCsrfCookie) {
  1230. $cookie = $this->createCsrfCookie($token);
  1231. Yii::$app->getResponse()->getCookies()->add($cookie);
  1232. } else {
  1233. Yii::$app->getSession()->set($this->csrfParam, $token);
  1234. }
  1235. return $token;
  1236. }
  1237. /**
  1238. * @return string the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent.
  1239. */
  1240. public function getCsrfTokenFromHeader()
  1241. {
  1242. return $this->headers->get(static::CSRF_HEADER);
  1243. }
  1244. /**
  1245. * Creates a cookie with a randomly generated CSRF token.
  1246. * Initial values specified in [[csrfCookie]] will be applied to the generated cookie.
  1247. * @param string $token the CSRF token
  1248. * @return Cookie the generated cookie
  1249. * @see enableCsrfValidation
  1250. */
  1251. protected function createCsrfCookie($token)
  1252. {
  1253. $options = $this->csrfCookie;
  1254. $options['name'] = $this->csrfParam;
  1255. $options['value'] = $token;
  1256. return new Cookie($options);
  1257. }
  1258. /**
  1259. * Performs the CSRF validation.
  1260. *
  1261. * This method will validate the user-provided CSRF token by comparing it with the one stored in cookie or session.
  1262. * This method is mainly called in [[Controller::beforeAction()]].
  1263. *
  1264. * Note that the method will NOT perform CSRF validation if [[enableCsrfValidation]] is false or the HTTP method
  1265. * is among GET, HEAD or OPTIONS.
  1266. *
  1267. * @param string $clientSuppliedToken the user-provided CSRF token to be validated. If null, the token will be retrieved from
  1268. * the [[csrfParam]] POST field or HTTP header.
  1269. * This parameter is available since version 2.0.4.
  1270. * @return bool whether CSRF token is valid. If [[enableCsrfValidation]] is false, this method will return true.
  1271. */
  1272. public function validateCsrfToken($clientSuppliedToken = null)
  1273. {
  1274. $method = $this->getMethod();
  1275. // only validate CSRF token on non-"safe" methods http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
  1276. if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
  1277. return true;
  1278. }
  1279. $trueToken = $this->getCsrfToken();
  1280. if ($clientSuppliedToken !== null) {
  1281. return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken);
  1282. }
  1283. return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
  1284. || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
  1285. }
  1286. /**
  1287. * Validates CSRF token
  1288. *
  1289. * @param string $clientSuppliedToken The masked client-supplied token.
  1290. * @param string $trueToken The masked true token.
  1291. * @return bool
  1292. */
  1293. private function validateCsrfTokenInternal($clientSuppliedToken, $trueToken)
  1294. {
  1295. if (!is_string($clientSuppliedToken)) {
  1296. return false;
  1297. }
  1298. $security = Yii::$app->security;
  1299. return $security->unmaskToken($clientSuppliedToken) === $security->unmaskToken($trueToken);
  1300. }
  1301. }