Request.php 63 KB

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