Request.php 72 KB

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