Request.php 71 KB

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