Request.php 71 KB

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