1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747 |
- <?php
- namespace yii\web;
- use Yii;
- use yii\base\InvalidConfigException;
- use yii\validators\IpValidator;
- class Request extends \yii\base\Request
- {
-
- const CSRF_HEADER = 'X-CSRF-Token';
-
- const CSRF_MASK_LENGTH = 8;
-
- public $enableCsrfValidation = true;
-
- public $csrfParam = '_csrf';
-
- public $csrfCookie = ['httpOnly' => true];
-
- public $enableCsrfCookie = true;
-
- public $enableCookieValidation = true;
-
- public $cookieValidationKey;
-
- public $methodParam = '_method';
-
- public $parsers = [];
-
- public $trustedHosts = [];
-
- public $secureHeaders = [
-
- 'X-Forwarded-For',
- 'X-Forwarded-Host',
- 'X-Forwarded-Proto',
-
- 'Front-End-Https',
- 'X-Rewrite-Url',
- ];
-
- public $ipHeaders = [
- 'X-Forwarded-For',
- ];
-
- public $secureProtocolHeaders = [
- 'X-Forwarded-Proto' => ['https'],
- 'Front-End-Https' => ['on'],
- ];
-
- private $_cookies;
-
- private $_headers;
-
- public function resolve()
- {
- $result = Yii::$app->getUrlManager()->parseRequest($this);
- if ($result !== false) {
- list($route, $params) = $result;
- if ($this->_queryParams === null) {
- $_GET = $params + $_GET;
- } else {
- $this->_queryParams = $params + $this->_queryParams;
- }
- return [$route, $this->getQueryParams()];
- }
- throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
- }
-
- protected function filterHeaders(HeaderCollection $headerCollection)
- {
-
- $trustedHeaders = [];
-
- if (!empty($this->trustedHosts)) {
- $validator = $this->getIpValidator();
- $ip = $this->getRemoteIP();
- foreach ($this->trustedHosts as $cidr => $headers) {
- if (!is_array($headers)) {
- $cidr = $headers;
- $headers = $this->secureHeaders;
- }
- $validator->setRanges($cidr);
- if ($validator->validate($ip)) {
- $trustedHeaders = $headers;
- break;
- }
- }
- }
-
- foreach ($this->secureHeaders as $secureHeader) {
- if (!in_array($secureHeader, $trustedHeaders)) {
- $headerCollection->remove($secureHeader);
- }
- }
- }
-
- protected function getIpValidator()
- {
- return new IpValidator();
- }
-
- public function getHeaders()
- {
- if ($this->_headers === null) {
- $this->_headers = new HeaderCollection();
- if (function_exists('getallheaders')) {
- $headers = getallheaders();
- foreach ($headers as $name => $value) {
- $this->_headers->add($name, $value);
- }
- } elseif (function_exists('http_get_request_headers')) {
- $headers = http_get_request_headers();
- foreach ($headers as $name => $value) {
- $this->_headers->add($name, $value);
- }
- } else {
- foreach ($_SERVER as $name => $value) {
- if (strncmp($name, 'HTTP_', 5) === 0) {
- $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
- $this->_headers->add($name, $value);
- }
- }
- }
- $this->filterHeaders($this->_headers);
- }
- return $this->_headers;
- }
-
- public function getMethod()
- {
- if (
- isset($_POST[$this->methodParam])
-
-
- && !in_array(strtoupper($_POST[$this->methodParam]), ['GET', 'HEAD', 'OPTIONS'], true)
- ) {
- return strtoupper($_POST[$this->methodParam]);
- }
- if ($this->headers->has('X-Http-Method-Override')) {
- return strtoupper($this->headers->get('X-Http-Method-Override'));
- }
- if (isset($_SERVER['REQUEST_METHOD'])) {
- return strtoupper($_SERVER['REQUEST_METHOD']);
- }
- return 'GET';
- }
-
- public function getIsGet()
- {
- return $this->getMethod() === 'GET';
- }
-
- public function getIsOptions()
- {
- return $this->getMethod() === 'OPTIONS';
- }
-
- public function getIsHead()
- {
- return $this->getMethod() === 'HEAD';
- }
-
- public function getIsPost()
- {
- return $this->getMethod() === 'POST';
- }
-
- public function getIsDelete()
- {
- return $this->getMethod() === 'DELETE';
- }
-
- public function getIsPut()
- {
- return $this->getMethod() === 'PUT';
- }
-
- public function getIsPatch()
- {
- return $this->getMethod() === 'PATCH';
- }
-
- public function getIsAjax()
- {
- return $this->headers->get('X-Requested-With') === 'XMLHttpRequest';
- }
-
- public function getIsPjax()
- {
- return $this->getIsAjax() && $this->headers->has('X-Pjax');
- }
-
- public function getIsFlash()
- {
- $userAgent = $this->headers->get('User-Agent', '');
- return stripos($userAgent, 'Shockwave') !== false
- || stripos($userAgent, 'Flash') !== false;
- }
- private $_rawBody;
-
- public function getRawBody()
- {
- if ($this->_rawBody === null) {
- $this->_rawBody = file_get_contents('php://input');
- }
- return $this->_rawBody;
- }
-
- public function setRawBody($rawBody)
- {
- $this->_rawBody = $rawBody;
- }
- private $_bodyParams;
-
- public function getBodyParams()
- {
- if ($this->_bodyParams === null) {
- if (isset($_POST[$this->methodParam])) {
- $this->_bodyParams = $_POST;
- unset($this->_bodyParams[$this->methodParam]);
- return $this->_bodyParams;
- }
- $rawContentType = $this->getContentType();
- if (($pos = strpos($rawContentType, ';')) !== false) {
-
- $contentType = substr($rawContentType, 0, $pos);
- } else {
- $contentType = $rawContentType;
- }
- if (isset($this->parsers[$contentType])) {
- $parser = Yii::createObject($this->parsers[$contentType]);
- if (!($parser instanceof RequestParserInterface)) {
- throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
- }
- $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
- } elseif (isset($this->parsers['*'])) {
- $parser = Yii::createObject($this->parsers['*']);
- if (!($parser instanceof RequestParserInterface)) {
- throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.');
- }
- $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
- } elseif ($this->getMethod() === 'POST') {
-
- $this->_bodyParams = $_POST;
- } else {
- $this->_bodyParams = [];
- mb_parse_str($this->getRawBody(), $this->_bodyParams);
- }
- }
- return $this->_bodyParams;
- }
-
- public function setBodyParams($values)
- {
- $this->_bodyParams = $values;
- }
-
- public function getBodyParam($name, $defaultValue = null)
- {
- $params = $this->getBodyParams();
- if (is_object($params)) {
-
- try {
- return $params->{$name};
- } catch (\Exception $e) {
- return $defaultValue;
- }
- }
- return isset($params[$name]) ? $params[$name] : $defaultValue;
- }
-
- public function post($name = null, $defaultValue = null)
- {
- if ($name === null) {
- return $this->getBodyParams();
- }
- return $this->getBodyParam($name, $defaultValue);
- }
- private $_queryParams;
-
- public function getQueryParams()
- {
- if ($this->_queryParams === null) {
- return $_GET;
- }
- return $this->_queryParams;
- }
-
- public function setQueryParams($values)
- {
- $this->_queryParams = $values;
- }
-
- public function get($name = null, $defaultValue = null)
- {
- if ($name === null) {
- return $this->getQueryParams();
- }
- return $this->getQueryParam($name, $defaultValue);
- }
-
- public function getQueryParam($name, $defaultValue = null)
- {
- $params = $this->getQueryParams();
- return isset($params[$name]) ? $params[$name] : $defaultValue;
- }
- private $_hostInfo;
- private $_hostName;
-
- public function getHostInfo()
- {
- if ($this->_hostInfo === null) {
- $secure = $this->getIsSecureConnection();
- $http = $secure ? 'https' : 'http';
- if ($this->headers->has('X-Forwarded-Host')) {
- $this->_hostInfo = $http . '://' . trim(explode(',', $this->headers->get('X-Forwarded-Host'))[0]);
- } elseif ($this->headers->has('Host')) {
- $this->_hostInfo = $http . '://' . $this->headers->get('Host');
- } elseif (isset($_SERVER['SERVER_NAME'])) {
- $this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME'];
- $port = $secure ? $this->getSecurePort() : $this->getPort();
- if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
- $this->_hostInfo .= ':' . $port;
- }
- }
- }
- return $this->_hostInfo;
- }
-
- public function setHostInfo($value)
- {
- $this->_hostName = null;
- $this->_hostInfo = $value === null ? null : rtrim($value, '/');
- }
-
- public function getHostName()
- {
- if ($this->_hostName === null) {
- $this->_hostName = parse_url($this->getHostInfo(), PHP_URL_HOST);
- }
- return $this->_hostName;
- }
- private $_baseUrl;
-
- public function getBaseUrl()
- {
- if ($this->_baseUrl === null) {
- $this->_baseUrl = rtrim(dirname($this->getScriptUrl()), '\\/');
- }
- return $this->_baseUrl;
- }
-
- public function setBaseUrl($value)
- {
- $this->_baseUrl = $value;
- }
- private $_scriptUrl;
-
- public function getScriptUrl()
- {
- if ($this->_scriptUrl === null) {
- $scriptFile = $this->getScriptFile();
- $scriptName = basename($scriptFile);
- if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
- $this->_scriptUrl = $_SERVER['SCRIPT_NAME'];
- } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $scriptName) {
- $this->_scriptUrl = $_SERVER['PHP_SELF'];
- } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
- $this->_scriptUrl = $_SERVER['ORIG_SCRIPT_NAME'];
- } elseif (isset($_SERVER['PHP_SELF']) && ($pos = strpos($_SERVER['PHP_SELF'], '/' . $scriptName)) !== false) {
- $this->_scriptUrl = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
- } elseif (!empty($_SERVER['DOCUMENT_ROOT']) && strpos($scriptFile, $_SERVER['DOCUMENT_ROOT']) === 0) {
- $this->_scriptUrl = str_replace([$_SERVER['DOCUMENT_ROOT'], '\\'], ['', '/'], $scriptFile);
- } else {
- throw new InvalidConfigException('Unable to determine the entry script URL.');
- }
- }
- return $this->_scriptUrl;
- }
-
- public function setScriptUrl($value)
- {
- $this->_scriptUrl = $value === null ? null : '/' . trim($value, '/');
- }
- private $_scriptFile;
-
- public function getScriptFile()
- {
- if (isset($this->_scriptFile)) {
- return $this->_scriptFile;
- }
- if (isset($_SERVER['SCRIPT_FILENAME'])) {
- return $_SERVER['SCRIPT_FILENAME'];
- }
- throw new InvalidConfigException('Unable to determine the entry script file path.');
- }
-
- public function setScriptFile($value)
- {
- $this->_scriptFile = $value;
- }
- private $_pathInfo;
-
- public function getPathInfo()
- {
- if ($this->_pathInfo === null) {
- $this->_pathInfo = $this->resolvePathInfo();
- }
- return $this->_pathInfo;
- }
-
- public function setPathInfo($value)
- {
- $this->_pathInfo = $value === null ? null : ltrim($value, '/');
- }
-
- protected function resolvePathInfo()
- {
- $pathInfo = $this->getUrl();
- if (($pos = strpos($pathInfo, '?')) !== false) {
- $pathInfo = substr($pathInfo, 0, $pos);
- }
- $pathInfo = urldecode($pathInfo);
-
-
- if (!preg_match('%^(?:
- [\x09\x0A\x0D\x20-\x7E] # ASCII
- | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
- | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
- | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
- | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
- | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
- | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
- | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
- )*$%xs', $pathInfo)
- ) {
- $pathInfo = $this->utf8Encode($pathInfo);
- }
- $scriptUrl = $this->getScriptUrl();
- $baseUrl = $this->getBaseUrl();
- if (strpos($pathInfo, $scriptUrl) === 0) {
- $pathInfo = substr($pathInfo, strlen($scriptUrl));
- } elseif ($baseUrl === '' || strpos($pathInfo, $baseUrl) === 0) {
- $pathInfo = substr($pathInfo, strlen($baseUrl));
- } elseif (isset($_SERVER['PHP_SELF']) && strpos($_SERVER['PHP_SELF'], $scriptUrl) === 0) {
- $pathInfo = substr($_SERVER['PHP_SELF'], strlen($scriptUrl));
- } else {
- throw new InvalidConfigException('Unable to determine the path info of the current request.');
- }
- if (strncmp($pathInfo, '/', 1) === 0) {
- $pathInfo = substr($pathInfo, 1);
- }
- return (string) $pathInfo;
- }
-
- private function utf8Encode($s)
- {
- $s .= $s;
- $len = \strlen($s);
- for ($i = $len >> 1, $j = 0; $i < $len; ++$i, ++$j) {
- switch (true) {
- case $s[$i] < "\x80": $s[$j] = $s[$i]; break;
- case $s[$i] < "\xC0": $s[$j] = "\xC2"; $s[++$j] = $s[$i]; break;
- default: $s[$j] = "\xC3"; $s[++$j] = \chr(\ord($s[$i]) - 64); break;
- }
- }
- return substr($s, 0, $j);
- }
-
- public function getAbsoluteUrl()
- {
- return $this->getHostInfo() . $this->getUrl();
- }
- private $_url;
-
- public function getUrl()
- {
- if ($this->_url === null) {
- $this->_url = $this->resolveRequestUri();
- }
- return $this->_url;
- }
-
- public function setUrl($value)
- {
- $this->_url = $value;
- }
-
- protected function resolveRequestUri()
- {
- if ($this->headers->has('X-Rewrite-Url')) {
- $requestUri = $this->headers->get('X-Rewrite-Url');
- } elseif (isset($_SERVER['REQUEST_URI'])) {
- $requestUri = $_SERVER['REQUEST_URI'];
- if ($requestUri !== '' && $requestUri[0] !== '/') {
- $requestUri = preg_replace('/^(http|https):\/\/[^\/]+/i', '', $requestUri);
- }
- } elseif (isset($_SERVER['ORIG_PATH_INFO'])) {
- $requestUri = $_SERVER['ORIG_PATH_INFO'];
- if (!empty($_SERVER['QUERY_STRING'])) {
- $requestUri .= '?' . $_SERVER['QUERY_STRING'];
- }
- } else {
- throw new InvalidConfigException('Unable to determine the request URI.');
- }
- return $requestUri;
- }
-
- public function getQueryString()
- {
- return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
- }
-
- public function getIsSecureConnection()
- {
- if (isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') === 0 || $_SERVER['HTTPS'] == 1)) {
- return true;
- }
- foreach ($this->secureProtocolHeaders as $header => $values) {
- if (($headerValue = $this->headers->get($header, null)) !== null) {
- foreach ($values as $value) {
- if (strcasecmp($headerValue, $value) === 0) {
- return true;
- }
- }
- }
- }
- return false;
- }
-
- public function getServerName()
- {
- return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
- }
-
- public function getServerPort()
- {
- return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null;
- }
-
- public function getReferrer()
- {
- return $this->headers->get('Referer');
- }
-
- public function getOrigin()
- {
- return $this->getHeaders()->get('origin');
- }
-
- public function getUserAgent()
- {
- return $this->headers->get('User-Agent');
- }
-
- public function getUserIP()
- {
- foreach ($this->ipHeaders as $ipHeader) {
- if ($this->headers->has($ipHeader)) {
- return trim(explode(',', $this->headers->get($ipHeader))[0]);
- }
- }
- return $this->getRemoteIP();
- }
-
- public function getUserHost()
- {
- foreach ($this->ipHeaders as $ipHeader) {
- if ($this->headers->has($ipHeader)) {
- return gethostbyaddr(trim(explode(',', $this->headers->get($ipHeader))[0]));
- }
- }
- return $this->getRemoteHost();
- }
-
- public function getRemoteIP()
- {
- return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
- }
-
- public function getRemoteHost()
- {
- return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
- }
-
- public function getAuthUser()
- {
- return $this->getAuthCredentials()[0];
- }
-
- public function getAuthPassword()
- {
- return $this->getAuthCredentials()[1];
- }
-
- public function getAuthCredentials()
- {
- $username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
- $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
- if ($username !== null || $password !== null) {
- return [$username, $password];
- }
-
- $auth_token = $this->getHeaders()->get('HTTP_AUTHORIZATION') ?: $this->getHeaders()->get('REDIRECT_HTTP_AUTHORIZATION');
- if ($auth_token !== null && strncasecmp($auth_token, 'basic', 5) === 0) {
- $parts = array_map(function ($value) {
- return strlen($value) === 0 ? null : $value;
- }, explode(':', base64_decode(mb_substr($auth_token, 6)), 2));
- if (count($parts) < 2) {
- return [$parts[0], null];
- }
- return $parts;
- }
- return [null, null];
- }
- private $_port;
-
- public function getPort()
- {
- if ($this->_port === null) {
- $serverPort = $this->getServerPort();
- $this->_port = !$this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 80;
- }
- return $this->_port;
- }
-
- public function setPort($value)
- {
- if ($value != $this->_port) {
- $this->_port = (int) $value;
- $this->_hostInfo = null;
- }
- }
- private $_securePort;
-
- public function getSecurePort()
- {
- if ($this->_securePort === null) {
- $serverPort = $this->getServerPort();
- $this->_securePort = $this->getIsSecureConnection() && $serverPort !== null ? $serverPort : 443;
- }
- return $this->_securePort;
- }
-
- public function setSecurePort($value)
- {
- if ($value != $this->_securePort) {
- $this->_securePort = (int) $value;
- $this->_hostInfo = null;
- }
- }
- private $_contentTypes;
-
- public function getAcceptableContentTypes()
- {
- if ($this->_contentTypes === null) {
- if ($this->headers->get('Accept') !== null) {
- $this->_contentTypes = $this->parseAcceptHeader($this->headers->get('Accept'));
- } else {
- $this->_contentTypes = [];
- }
- }
- return $this->_contentTypes;
- }
-
- public function setAcceptableContentTypes($value)
- {
- $this->_contentTypes = $value;
- }
-
- public function getContentType()
- {
- if (isset($_SERVER['CONTENT_TYPE'])) {
- return $_SERVER['CONTENT_TYPE'];
- }
-
- return $this->headers->get('Content-Type');
- }
- private $_languages;
-
- public function getAcceptableLanguages()
- {
- if ($this->_languages === null) {
- if ($this->headers->has('Accept-Language')) {
- $this->_languages = array_keys($this->parseAcceptHeader($this->headers->get('Accept-Language')));
- } else {
- $this->_languages = [];
- }
- }
- return $this->_languages;
- }
-
- public function setAcceptableLanguages($value)
- {
- $this->_languages = $value;
- }
-
- public function parseAcceptHeader($header)
- {
- $accepts = [];
- foreach (explode(',', $header) as $i => $part) {
- $params = preg_split('/\s*;\s*/', trim($part), -1, PREG_SPLIT_NO_EMPTY);
- if (empty($params)) {
- continue;
- }
- $values = [
- 'q' => [$i, array_shift($params), 1],
- ];
- foreach ($params as $param) {
- if (strpos($param, '=') !== false) {
- list($key, $value) = explode('=', $param, 2);
- if ($key === 'q') {
- $values['q'][2] = (float) $value;
- } else {
- $values[$key] = $value;
- }
- } else {
- $values[] = $param;
- }
- }
- $accepts[] = $values;
- }
- usort($accepts, function ($a, $b) {
- $a = $a['q'];
- $b = $b['q'];
- if ($a[2] > $b[2]) {
- return -1;
- }
- if ($a[2] < $b[2]) {
- return 1;
- }
- if ($a[1] === $b[1]) {
- return $a[0] > $b[0] ? 1 : -1;
- }
- if ($a[1] === '*/*') {
- return 1;
- }
- if ($b[1] === '*/*') {
- return -1;
- }
- $wa = $a[1][strlen($a[1]) - 1] === '*';
- $wb = $b[1][strlen($b[1]) - 1] === '*';
- if ($wa xor $wb) {
- return $wa ? 1 : -1;
- }
- return $a[0] > $b[0] ? 1 : -1;
- });
- $result = [];
- foreach ($accepts as $accept) {
- $name = $accept['q'][1];
- $accept['q'] = $accept['q'][2];
- $result[$name] = $accept;
- }
- return $result;
- }
-
- public function getPreferredLanguage(array $languages = [])
- {
- if (empty($languages)) {
- return Yii::$app->language;
- }
- foreach ($this->getAcceptableLanguages() as $acceptableLanguage) {
- $acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
- foreach ($languages as $language) {
- $normalizedLanguage = str_replace('_', '-', strtolower($language));
- if (
- $normalizedLanguage === $acceptableLanguage
- || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0
- || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0
- ) {
- return $language;
- }
- }
- }
- return reset($languages);
- }
-
- public function getETags()
- {
- if ($this->headers->has('If-None-Match')) {
- return preg_split('/[\s,]+/', str_replace('-gzip', '', $this->headers->get('If-None-Match')), -1, PREG_SPLIT_NO_EMPTY);
- }
- return [];
- }
-
- public function getCookies()
- {
- if ($this->_cookies === null) {
- $this->_cookies = new CookieCollection($this->loadCookies(), [
- 'readOnly' => true,
- ]);
- }
- return $this->_cookies;
- }
-
- protected function loadCookies()
- {
- $cookies = [];
- if ($this->enableCookieValidation) {
- if ($this->cookieValidationKey == '') {
- throw new InvalidConfigException(get_class($this) . '::cookieValidationKey must be configured with a secret key.');
- }
- foreach ($_COOKIE as $name => $value) {
- if (!is_string($value)) {
- continue;
- }
- $data = Yii::$app->getSecurity()->validateData($value, $this->cookieValidationKey);
- if ($data === false) {
- continue;
- }
- if (defined('PHP_VERSION_ID') && PHP_VERSION_ID >= 70000) {
- $data = @unserialize($data, ['allowed_classes' => false]);
- } else {
- $data = @unserialize($data);
- }
- if (is_array($data) && isset($data[0], $data[1]) && $data[0] === $name) {
- $cookies[$name] = Yii::createObject([
- 'class' => 'yii\web\Cookie',
- 'name' => $name,
- 'value' => $data[1],
- 'expire' => null,
- ]);
- }
- }
- } else {
- foreach ($_COOKIE as $name => $value) {
- $cookies[$name] = Yii::createObject([
- 'class' => 'yii\web\Cookie',
- 'name' => $name,
- 'value' => $value,
- 'expire' => null,
- ]);
- }
- }
- return $cookies;
- }
- private $_csrfToken;
-
- public function getCsrfToken($regenerate = false)
- {
- if ($this->_csrfToken === null || $regenerate) {
- $token = $this->loadCsrfToken();
- if ($regenerate || empty($token)) {
- $token = $this->generateCsrfToken();
- }
- $this->_csrfToken = Yii::$app->security->maskToken($token);
- }
- return $this->_csrfToken;
- }
-
- protected function loadCsrfToken()
- {
- if ($this->enableCsrfCookie) {
- return $this->getCookies()->getValue($this->csrfParam);
- }
- return Yii::$app->getSession()->get($this->csrfParam);
- }
-
- protected function generateCsrfToken()
- {
- $token = Yii::$app->getSecurity()->generateRandomString();
- if ($this->enableCsrfCookie) {
- $cookie = $this->createCsrfCookie($token);
- Yii::$app->getResponse()->getCookies()->add($cookie);
- } else {
- Yii::$app->getSession()->set($this->csrfParam, $token);
- }
- return $token;
- }
-
- public function getCsrfTokenFromHeader()
- {
- return $this->headers->get(static::CSRF_HEADER);
- }
-
- protected function createCsrfCookie($token)
- {
- $options = $this->csrfCookie;
- return Yii::createObject(array_merge($options, [
- 'class' => 'yii\web\Cookie',
- 'name' => $this->csrfParam,
- 'value' => $token,
- ]));
- }
-
- public function validateCsrfToken($clientSuppliedToken = null)
- {
- $method = $this->getMethod();
-
- if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
- return true;
- }
- $trueToken = $this->getCsrfToken();
- if ($clientSuppliedToken !== null) {
- return $this->validateCsrfTokenInternal($clientSuppliedToken, $trueToken);
- }
- return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)
- || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);
- }
-
- private function validateCsrfTokenInternal($clientSuppliedToken, $trueToken)
- {
- if (!is_string($clientSuppliedToken)) {
- return false;
- }
- $security = Yii::$app->security;
- return $security->compareString($security->unmaskToken($clientSuppliedToken), $security->unmaskToken($trueToken));
- }
- }
|