Request.php 71 KB

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