Request.php 66 KB

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