Request.php 72 KB

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