Request.php 71 KB

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