Request.php 64 KB

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