Request.php 74 KB

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