Request.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. class Request
  13. {
  14. /**
  15. * @var object 对象实例
  16. */
  17. protected static $instance;
  18. protected $method;
  19. /**
  20. * @var string 域名(含协议和端口)
  21. */
  22. protected $domain;
  23. /**
  24. * @var string URL地址
  25. */
  26. protected $url;
  27. /**
  28. * @var string 基础URL
  29. */
  30. protected $baseUrl;
  31. /**
  32. * @var string 当前执行的文件
  33. */
  34. protected $baseFile;
  35. /**
  36. * @var string 访问的ROOT地址
  37. */
  38. protected $root;
  39. /**
  40. * @var string pathinfo
  41. */
  42. protected $pathinfo;
  43. /**
  44. * @var string pathinfo(不含后缀)
  45. */
  46. protected $path;
  47. /**
  48. * @var array 当前路由信息
  49. */
  50. protected $routeInfo = [];
  51. /**
  52. * @var array 环境变量
  53. */
  54. protected $env;
  55. /**
  56. * @var array 当前调度信息
  57. */
  58. protected $dispatch = [];
  59. protected $module;
  60. protected $controller;
  61. protected $action;
  62. // 当前语言集
  63. protected $langset;
  64. /**
  65. * @var array 请求参数
  66. */
  67. protected $param = [];
  68. protected $get = [];
  69. protected $post = [];
  70. protected $request = [];
  71. protected $route = [];
  72. protected $put;
  73. protected $session = [];
  74. protected $file = [];
  75. protected $cookie = [];
  76. protected $server = [];
  77. protected $header = [];
  78. /**
  79. * @var array 资源类型
  80. */
  81. protected $mimeType = [
  82. 'xml' => 'application/xml,text/xml,application/x-xml',
  83. 'json' => 'application/json,text/x-json,application/jsonrequest,text/json',
  84. 'js' => 'text/javascript,application/javascript,application/x-javascript',
  85. 'css' => 'text/css',
  86. 'rss' => 'application/rss+xml',
  87. 'yaml' => 'application/x-yaml,text/yaml',
  88. 'atom' => 'application/atom+xml',
  89. 'pdf' => 'application/pdf',
  90. 'text' => 'text/plain',
  91. 'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
  92. 'csv' => 'text/csv',
  93. 'html' => 'text/html,application/xhtml+xml,*/*',
  94. ];
  95. protected $content;
  96. // 全局过滤规则
  97. protected $filter;
  98. // Hook扩展方法
  99. protected static $hook = [];
  100. // 绑定的属性
  101. protected $bind = [];
  102. // php://input
  103. protected $input;
  104. // 请求缓存
  105. protected $cache;
  106. // 缓存是否检查
  107. protected $isCheckCache;
  108. /**
  109. * 是否合并Param
  110. * @var bool
  111. */
  112. protected $mergeParam = false;
  113. /**
  114. * 构造函数
  115. * @access protected
  116. * @param array $options 参数
  117. */
  118. protected function __construct($options = [])
  119. {
  120. foreach ($options as $name => $item) {
  121. if (property_exists($this, $name)) {
  122. $this->$name = $item;
  123. }
  124. }
  125. if (is_null($this->filter)) {
  126. $this->filter = Config::get('default_filter');
  127. }
  128. // 保存 php://input
  129. $this->input = file_get_contents('php://input');
  130. }
  131. public function __call($method, $args)
  132. {
  133. if (array_key_exists($method, self::$hook)) {
  134. array_unshift($args, $this);
  135. return call_user_func_array(self::$hook[$method], $args);
  136. } else {
  137. throw new Exception('method not exists:' . __CLASS__ . '->' . $method);
  138. }
  139. }
  140. /**
  141. * Hook 方法注入
  142. * @access public
  143. * @param string|array $method 方法名
  144. * @param mixed $callback callable
  145. * @return void
  146. */
  147. public static function hook($method, $callback = null)
  148. {
  149. if (is_array($method)) {
  150. self::$hook = array_merge(self::$hook, $method);
  151. } else {
  152. self::$hook[$method] = $callback;
  153. }
  154. }
  155. /**
  156. * 初始化
  157. * @access public
  158. * @param array $options 参数
  159. * @return \think\Request
  160. */
  161. public static function instance($options = [])
  162. {
  163. if (is_null(self::$instance)) {
  164. self::$instance = new static($options);
  165. }
  166. return self::$instance;
  167. }
  168. /**
  169. * 销毁当前请求对象
  170. * @access public
  171. * @return void
  172. */
  173. public static function destroy()
  174. {
  175. if (!is_null(self::$instance)) {
  176. self::$instance = null;
  177. }
  178. }
  179. /**
  180. * 创建一个URL请求
  181. * @access public
  182. * @param string $uri URL地址
  183. * @param string $method 请求类型
  184. * @param array $params 请求参数
  185. * @param array $cookie
  186. * @param array $files
  187. * @param array $server
  188. * @param string $content
  189. * @return \think\Request
  190. */
  191. public static function create($uri, $method = 'GET', $params = [], $cookie = [], $files = [], $server = [], $content = null)
  192. {
  193. $server['PATH_INFO'] = '';
  194. $server['REQUEST_METHOD'] = strtoupper($method);
  195. $info = parse_url($uri);
  196. if (isset($info['host'])) {
  197. $server['SERVER_NAME'] = $info['host'];
  198. $server['HTTP_HOST'] = $info['host'];
  199. }
  200. if (isset($info['scheme'])) {
  201. if ('https' === $info['scheme']) {
  202. $server['HTTPS'] = 'on';
  203. $server['SERVER_PORT'] = 443;
  204. } else {
  205. unset($server['HTTPS']);
  206. $server['SERVER_PORT'] = 80;
  207. }
  208. }
  209. if (isset($info['port'])) {
  210. $server['SERVER_PORT'] = $info['port'];
  211. $server['HTTP_HOST'] = $server['HTTP_HOST'] . ':' . $info['port'];
  212. }
  213. if (isset($info['user'])) {
  214. $server['PHP_AUTH_USER'] = $info['user'];
  215. }
  216. if (isset($info['pass'])) {
  217. $server['PHP_AUTH_PW'] = $info['pass'];
  218. }
  219. if (!isset($info['path'])) {
  220. $info['path'] = '/';
  221. }
  222. $options = [];
  223. $options[strtolower($method)] = $params;
  224. $queryString = '';
  225. if (isset($info['query'])) {
  226. parse_str(html_entity_decode($info['query']), $query);
  227. if (!empty($params)) {
  228. $params = array_replace($query, $params);
  229. $queryString = http_build_query($params, '', '&');
  230. } else {
  231. $params = $query;
  232. $queryString = $info['query'];
  233. }
  234. } elseif (!empty($params)) {
  235. $queryString = http_build_query($params, '', '&');
  236. }
  237. if ($queryString) {
  238. parse_str($queryString, $get);
  239. $options['get'] = isset($options['get']) ? array_merge($get, $options['get']) : $get;
  240. }
  241. $server['REQUEST_URI'] = $info['path'] . ('' !== $queryString ? '?' . $queryString : '');
  242. $server['QUERY_STRING'] = $queryString;
  243. $options['cookie'] = $cookie;
  244. $options['param'] = $params;
  245. $options['file'] = $files;
  246. $options['server'] = $server;
  247. $options['url'] = $server['REQUEST_URI'];
  248. $options['baseUrl'] = $info['path'];
  249. $options['pathinfo'] = '/' == $info['path'] ? '/' : ltrim($info['path'], '/');
  250. $options['method'] = $server['REQUEST_METHOD'];
  251. $options['domain'] = isset($info['scheme']) ? $info['scheme'] . '://' . $server['HTTP_HOST'] : '';
  252. $options['content'] = $content;
  253. self::$instance = new self($options);
  254. return self::$instance;
  255. }
  256. /**
  257. * 设置或获取当前包含协议的域名
  258. * @access public
  259. * @param string $domain 域名
  260. * @return string
  261. */
  262. public function domain($domain = null)
  263. {
  264. if (!is_null($domain)) {
  265. $this->domain = $domain;
  266. return $this;
  267. } elseif (!$this->domain) {
  268. $this->domain = $this->scheme() . '://' . $this->host();
  269. }
  270. return $this->domain;
  271. }
  272. /**
  273. * 设置或获取当前完整URL 包括QUERY_STRING
  274. * @access public
  275. * @param string|true $url URL地址 true 带域名获取
  276. * @return string
  277. */
  278. public function url($url = null)
  279. {
  280. if (!is_null($url) && true !== $url) {
  281. $this->url = $url;
  282. return $this;
  283. } elseif (!$this->url) {
  284. if (IS_CLI) {
  285. $this->url = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
  286. } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
  287. $this->url = $_SERVER['HTTP_X_REWRITE_URL'];
  288. } elseif (isset($_SERVER['REQUEST_URI'])) {
  289. $this->url = $_SERVER['REQUEST_URI'];
  290. } elseif (isset($_SERVER['ORIG_PATH_INFO'])) {
  291. $this->url = $_SERVER['ORIG_PATH_INFO'] . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '');
  292. } else {
  293. $this->url = '';
  294. }
  295. }
  296. return true === $url ? $this->domain() . $this->url : $this->url;
  297. }
  298. /**
  299. * 设置或获取当前URL 不含QUERY_STRING
  300. * @access public
  301. * @param string $url URL地址
  302. * @return string
  303. */
  304. public function baseUrl($url = null)
  305. {
  306. if (!is_null($url) && true !== $url) {
  307. $this->baseUrl = $url;
  308. return $this;
  309. } elseif (!$this->baseUrl) {
  310. $str = $this->url();
  311. $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
  312. }
  313. return true === $url ? $this->domain() . $this->baseUrl : $this->baseUrl;
  314. }
  315. /**
  316. * 设置或获取当前执行的文件 SCRIPT_NAME
  317. * @access public
  318. * @param string $file 当前执行的文件
  319. * @return string
  320. */
  321. public function baseFile($file = null)
  322. {
  323. if (!is_null($file) && true !== $file) {
  324. $this->baseFile = $file;
  325. return $this;
  326. } elseif (!$this->baseFile) {
  327. $url = '';
  328. if (!IS_CLI) {
  329. $script_name = basename($_SERVER['SCRIPT_FILENAME']);
  330. if (basename($_SERVER['SCRIPT_NAME']) === $script_name) {
  331. $url = $_SERVER['SCRIPT_NAME'];
  332. } elseif (basename($_SERVER['PHP_SELF']) === $script_name) {
  333. $url = $_SERVER['PHP_SELF'];
  334. } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $script_name) {
  335. $url = $_SERVER['ORIG_SCRIPT_NAME'];
  336. } elseif (($pos = strpos($_SERVER['PHP_SELF'], '/' . $script_name)) !== false) {
  337. $url = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $script_name;
  338. } elseif (isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) === 0) {
  339. $url = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME']));
  340. }
  341. }
  342. $this->baseFile = $url;
  343. }
  344. return true === $file ? $this->domain() . $this->baseFile : $this->baseFile;
  345. }
  346. /**
  347. * 设置或获取URL访问根地址
  348. * @access public
  349. * @param string $url URL地址
  350. * @return string
  351. */
  352. public function root($url = null)
  353. {
  354. if (!is_null($url) && true !== $url) {
  355. $this->root = $url;
  356. return $this;
  357. } elseif (!$this->root) {
  358. $file = $this->baseFile();
  359. if ($file && 0 !== strpos($this->url(), $file)) {
  360. $file = str_replace('\\', '/', dirname($file));
  361. }
  362. $this->root = rtrim($file, '/');
  363. }
  364. return true === $url ? $this->domain() . $this->root : $this->root;
  365. }
  366. /**
  367. * 获取当前请求URL的pathinfo信息(含URL后缀)
  368. * @access public
  369. * @return string
  370. */
  371. public function pathinfo()
  372. {
  373. if (is_null($this->pathinfo)) {
  374. if (isset($_GET[Config::get('var_pathinfo')])) {
  375. // 判断URL里面是否有兼容模式参数
  376. $_SERVER['PATH_INFO'] = $_GET[Config::get('var_pathinfo')];
  377. unset($_GET[Config::get('var_pathinfo')]);
  378. } elseif (IS_CLI) {
  379. // CLI模式下 index.php module/controller/action/params/...
  380. $_SERVER['PATH_INFO'] = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
  381. }
  382. // 分析PATHINFO信息
  383. if (!isset($_SERVER['PATH_INFO'])) {
  384. foreach (Config::get('pathinfo_fetch') as $type) {
  385. if (!empty($_SERVER[$type])) {
  386. $_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type], $_SERVER['SCRIPT_NAME'])) ?
  387. substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME'])) : $_SERVER[$type];
  388. break;
  389. }
  390. }
  391. }
  392. $this->pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : ltrim($_SERVER['PATH_INFO'], '/');
  393. }
  394. return $this->pathinfo;
  395. }
  396. /**
  397. * 获取当前请求URL的pathinfo信息(不含URL后缀)
  398. * @access public
  399. * @return string
  400. */
  401. public function path()
  402. {
  403. if (is_null($this->path)) {
  404. $suffix = Config::get('url_html_suffix');
  405. $pathinfo = $this->pathinfo();
  406. if (false === $suffix) {
  407. // 禁止伪静态访问
  408. $this->path = $pathinfo;
  409. } elseif ($suffix) {
  410. // 去除正常的URL后缀
  411. $this->path = preg_replace('/\.(' . ltrim($suffix, '.') . ')$/i', '', $pathinfo);
  412. } else {
  413. // 允许任何后缀访问
  414. $this->path = preg_replace('/\.' . $this->ext() . '$/i', '', $pathinfo);
  415. }
  416. }
  417. return $this->path;
  418. }
  419. /**
  420. * 当前URL的访问后缀
  421. * @access public
  422. * @return string
  423. */
  424. public function ext()
  425. {
  426. return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
  427. }
  428. /**
  429. * 获取当前请求的时间
  430. * @access public
  431. * @param bool $float 是否使用浮点类型
  432. * @return integer|float
  433. */
  434. public function time($float = false)
  435. {
  436. return $float ? $_SERVER['REQUEST_TIME_FLOAT'] : $_SERVER['REQUEST_TIME'];
  437. }
  438. /**
  439. * 当前请求的资源类型
  440. * @access public
  441. * @return false|string
  442. */
  443. public function type()
  444. {
  445. $accept = $this->server('HTTP_ACCEPT');
  446. if (empty($accept)) {
  447. return false;
  448. }
  449. foreach ($this->mimeType as $key => $val) {
  450. $array = explode(',', $val);
  451. foreach ($array as $k => $v) {
  452. if (stristr($accept, $v)) {
  453. return $key;
  454. }
  455. }
  456. }
  457. return false;
  458. }
  459. /**
  460. * 设置资源类型
  461. * @access public
  462. * @param string|array $type 资源类型名
  463. * @param string $val 资源类型
  464. * @return void
  465. */
  466. public function mimeType($type, $val = '')
  467. {
  468. if (is_array($type)) {
  469. $this->mimeType = array_merge($this->mimeType, $type);
  470. } else {
  471. $this->mimeType[$type] = $val;
  472. }
  473. }
  474. /**
  475. * 当前的请求类型
  476. * @access public
  477. * @param bool $method true 获取原始请求类型
  478. * @return string
  479. */
  480. public function method($method = false)
  481. {
  482. if (true === $method) {
  483. // 获取原始请求类型
  484. return $this->server('REQUEST_METHOD') ?: 'GET';
  485. } elseif (!$this->method) {
  486. if (isset($_POST[Config::get('var_method')])) {
  487. $this->method = strtoupper($_POST[Config::get('var_method')]);
  488. $this->{$this->method}($_POST);
  489. } elseif (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
  490. $this->method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  491. } else {
  492. $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
  493. }
  494. }
  495. return $this->method;
  496. }
  497. /**
  498. * 是否为GET请求
  499. * @access public
  500. * @return bool
  501. */
  502. public function isGet()
  503. {
  504. return $this->method() == 'GET';
  505. }
  506. /**
  507. * 是否为POST请求
  508. * @access public
  509. * @return bool
  510. */
  511. public function isPost()
  512. {
  513. return $this->method() == 'POST';
  514. }
  515. /**
  516. * 是否为PUT请求
  517. * @access public
  518. * @return bool
  519. */
  520. public function isPut()
  521. {
  522. return $this->method() == 'PUT';
  523. }
  524. /**
  525. * 是否为DELTE请求
  526. * @access public
  527. * @return bool
  528. */
  529. public function isDelete()
  530. {
  531. return $this->method() == 'DELETE';
  532. }
  533. /**
  534. * 是否为HEAD请求
  535. * @access public
  536. * @return bool
  537. */
  538. public function isHead()
  539. {
  540. return $this->method() == 'HEAD';
  541. }
  542. /**
  543. * 是否为PATCH请求
  544. * @access public
  545. * @return bool
  546. */
  547. public function isPatch()
  548. {
  549. return $this->method() == 'PATCH';
  550. }
  551. /**
  552. * 是否为OPTIONS请求
  553. * @access public
  554. * @return bool
  555. */
  556. public function isOptions()
  557. {
  558. return $this->method() == 'OPTIONS';
  559. }
  560. /**
  561. * 是否为cli
  562. * @access public
  563. * @return bool
  564. */
  565. public function isCli()
  566. {
  567. return PHP_SAPI == 'cli';
  568. }
  569. /**
  570. * 是否为cgi
  571. * @access public
  572. * @return bool
  573. */
  574. public function isCgi()
  575. {
  576. return strpos(PHP_SAPI, 'cgi') === 0;
  577. }
  578. /**
  579. * 获取当前请求的参数
  580. * @access public
  581. * @param string|array $name 变量名
  582. * @param mixed $default 默认值
  583. * @param string|array $filter 过滤方法
  584. * @return mixed
  585. */
  586. public function param($name = '', $default = null, $filter = '')
  587. {
  588. if (empty($this->mergeParam)) {
  589. $method = $this->method(true);
  590. // 自动获取请求变量
  591. switch ($method) {
  592. case 'POST':
  593. $vars = $this->post(false);
  594. break;
  595. case 'PUT':
  596. case 'DELETE':
  597. case 'PATCH':
  598. $vars = $this->put(false);
  599. break;
  600. default:
  601. $vars = [];
  602. }
  603. // 当前请求参数和URL地址中的参数合并
  604. $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
  605. $this->mergeParam = true;
  606. }
  607. if (true === $name) {
  608. // 获取包含文件上传信息的数组
  609. $file = $this->file();
  610. $data = is_array($file) ? array_merge($this->param, $file) : $this->param;
  611. return $this->input($data, '', $default, $filter);
  612. }
  613. return $this->input($this->param, $name, $default, $filter);
  614. }
  615. /**
  616. * 设置获取路由参数
  617. * @access public
  618. * @param string|array $name 变量名
  619. * @param mixed $default 默认值
  620. * @param string|array $filter 过滤方法
  621. * @return mixed
  622. */
  623. public function route($name = '', $default = null, $filter = '')
  624. {
  625. if (is_array($name)) {
  626. $this->param = [];
  627. return $this->route = array_merge($this->route, $name);
  628. }
  629. return $this->input($this->route, $name, $default, $filter);
  630. }
  631. /**
  632. * 设置获取GET参数
  633. * @access public
  634. * @param string|array $name 变量名
  635. * @param mixed $default 默认值
  636. * @param string|array $filter 过滤方法
  637. * @return mixed
  638. */
  639. public function get($name = '', $default = null, $filter = '')
  640. {
  641. if (empty($this->get)) {
  642. $this->get = $_GET;
  643. }
  644. if (is_array($name)) {
  645. $this->param = [];
  646. return $this->get = array_merge($this->get, $name);
  647. }
  648. return $this->input($this->get, $name, $default, $filter);
  649. }
  650. /**
  651. * 设置获取POST参数
  652. * @access public
  653. * @param string $name 变量名
  654. * @param mixed $default 默认值
  655. * @param string|array $filter 过滤方法
  656. * @return mixed
  657. */
  658. public function post($name = '', $default = null, $filter = '')
  659. {
  660. if (empty($this->post)) {
  661. $content = $this->input;
  662. if (empty($_POST) && false !== strpos($this->contentType(), 'application/json')) {
  663. $this->post = (array) json_decode($content, true);
  664. } else {
  665. $this->post = $_POST;
  666. }
  667. }
  668. if (is_array($name)) {
  669. $this->param = [];
  670. return $this->post = array_merge($this->post, $name);
  671. }
  672. return $this->input($this->post, $name, $default, $filter);
  673. }
  674. /**
  675. * 设置获取PUT参数
  676. * @access public
  677. * @param string|array $name 变量名
  678. * @param mixed $default 默认值
  679. * @param string|array $filter 过滤方法
  680. * @return mixed
  681. */
  682. public function put($name = '', $default = null, $filter = '')
  683. {
  684. if (is_null($this->put)) {
  685. $content = $this->input;
  686. if (false !== strpos($this->contentType(), 'application/json')) {
  687. $this->put = (array) json_decode($content, true);
  688. } else {
  689. parse_str($content, $this->put);
  690. }
  691. }
  692. if (is_array($name)) {
  693. $this->param = [];
  694. return $this->put = is_null($this->put) ? $name : array_merge($this->put, $name);
  695. }
  696. return $this->input($this->put, $name, $default, $filter);
  697. }
  698. /**
  699. * 设置获取DELETE参数
  700. * @access public
  701. * @param string|array $name 变量名
  702. * @param mixed $default 默认值
  703. * @param string|array $filter 过滤方法
  704. * @return mixed
  705. */
  706. public function delete($name = '', $default = null, $filter = '')
  707. {
  708. return $this->put($name, $default, $filter);
  709. }
  710. /**
  711. * 设置获取PATCH参数
  712. * @access public
  713. * @param string|array $name 变量名
  714. * @param mixed $default 默认值
  715. * @param string|array $filter 过滤方法
  716. * @return mixed
  717. */
  718. public function patch($name = '', $default = null, $filter = '')
  719. {
  720. return $this->put($name, $default, $filter);
  721. }
  722. /**
  723. * 获取request变量
  724. * @param string $name 数据名称
  725. * @param string $default 默认值
  726. * @param string|array $filter 过滤方法
  727. * @return mixed
  728. */
  729. public function request($name = '', $default = null, $filter = '')
  730. {
  731. if (empty($this->request)) {
  732. $this->request = $_REQUEST;
  733. }
  734. if (is_array($name)) {
  735. $this->param = [];
  736. return $this->request = array_merge($this->request, $name);
  737. }
  738. return $this->input($this->request, $name, $default, $filter);
  739. }
  740. /**
  741. * 获取session数据
  742. * @access public
  743. * @param string|array $name 数据名称
  744. * @param string $default 默认值
  745. * @param string|array $filter 过滤方法
  746. * @return mixed
  747. */
  748. public function session($name = '', $default = null, $filter = '')
  749. {
  750. if (empty($this->session)) {
  751. $this->session = Session::get();
  752. }
  753. if (is_array($name)) {
  754. return $this->session = array_merge($this->session, $name);
  755. }
  756. return $this->input($this->session, $name, $default, $filter);
  757. }
  758. /**
  759. * 获取cookie参数
  760. * @access public
  761. * @param string|array $name 数据名称
  762. * @param string $default 默认值
  763. * @param string|array $filter 过滤方法
  764. * @return mixed
  765. */
  766. public function cookie($name = '', $default = null, $filter = '')
  767. {
  768. if (empty($this->cookie)) {
  769. $this->cookie = Cookie::get();
  770. }
  771. if (is_array($name)) {
  772. return $this->cookie = array_merge($this->cookie, $name);
  773. } elseif (!empty($name)) {
  774. $data = Cookie::has($name) ? Cookie::get($name) : $default;
  775. } else {
  776. $data = $this->cookie;
  777. }
  778. // 解析过滤器
  779. $filter = $this->getFilter($filter, $default);
  780. if (is_array($data)) {
  781. array_walk_recursive($data, [$this, 'filterValue'], $filter);
  782. reset($data);
  783. } else {
  784. $this->filterValue($data, $name, $filter);
  785. }
  786. return $data;
  787. }
  788. /**
  789. * 获取server参数
  790. * @access public
  791. * @param string|array $name 数据名称
  792. * @param string $default 默认值
  793. * @param string|array $filter 过滤方法
  794. * @return mixed
  795. */
  796. public function server($name = '', $default = null, $filter = '')
  797. {
  798. if (empty($this->server)) {
  799. $this->server = $_SERVER;
  800. }
  801. if (is_array($name)) {
  802. return $this->server = array_merge($this->server, $name);
  803. }
  804. return $this->input($this->server, false === $name ? false : strtoupper($name), $default, $filter);
  805. }
  806. /**
  807. * 获取上传的文件信息
  808. * @access public
  809. * @param string|array $name 名称
  810. * @return null|array|\think\File
  811. */
  812. public function file($name = '')
  813. {
  814. if (empty($this->file)) {
  815. $this->file = isset($_FILES) ? $_FILES : [];
  816. }
  817. if (is_array($name)) {
  818. return $this->file = array_merge($this->file, $name);
  819. }
  820. $files = $this->file;
  821. if (!empty($files)) {
  822. // 处理上传文件
  823. $array = [];
  824. foreach ($files as $key => $file) {
  825. if (is_array($file['name'])) {
  826. $item = [];
  827. $keys = array_keys($file);
  828. $count = count($file['name']);
  829. for ($i = 0; $i < $count; $i++) {
  830. if (empty($file['tmp_name'][$i]) || !is_file($file['tmp_name'][$i])) {
  831. continue;
  832. }
  833. $temp['key'] = $key;
  834. foreach ($keys as $_key) {
  835. $temp[$_key] = $file[$_key][$i];
  836. }
  837. $item[] = (new File($temp['tmp_name']))->setUploadInfo($temp);
  838. }
  839. $array[$key] = $item;
  840. } else {
  841. if ($file instanceof File) {
  842. $array[$key] = $file;
  843. } else {
  844. if (empty($file['tmp_name']) || !is_file($file['tmp_name'])) {
  845. continue;
  846. }
  847. $array[$key] = (new File($file['tmp_name']))->setUploadInfo($file);
  848. }
  849. }
  850. }
  851. if (strpos($name, '.')) {
  852. list($name, $sub) = explode('.', $name);
  853. }
  854. if ('' === $name) {
  855. // 获取全部文件
  856. return $array;
  857. } elseif (isset($sub) && isset($array[$name][$sub])) {
  858. return $array[$name][$sub];
  859. } elseif (isset($array[$name])) {
  860. return $array[$name];
  861. }
  862. }
  863. return;
  864. }
  865. /**
  866. * 获取环境变量
  867. * @param string|array $name 数据名称
  868. * @param string $default 默认值
  869. * @param string|array $filter 过滤方法
  870. * @return mixed
  871. */
  872. public function env($name = '', $default = null, $filter = '')
  873. {
  874. if (empty($this->env)) {
  875. $this->env = $_ENV;
  876. }
  877. if (is_array($name)) {
  878. return $this->env = array_merge($this->env, $name);
  879. }
  880. return $this->input($this->env, false === $name ? false : strtoupper($name), $default, $filter);
  881. }
  882. /**
  883. * 设置或者获取当前的Header
  884. * @access public
  885. * @param string|array $name header名称
  886. * @param string $default 默认值
  887. * @return string
  888. */
  889. public function header($name = '', $default = null)
  890. {
  891. if (empty($this->header)) {
  892. $header = [];
  893. if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
  894. $header = $result;
  895. } else {
  896. $server = $this->server ?: $_SERVER;
  897. foreach ($server as $key => $val) {
  898. if (0 === strpos($key, 'HTTP_')) {
  899. $key = str_replace('_', '-', strtolower(substr($key, 5)));
  900. $header[$key] = $val;
  901. }
  902. }
  903. if (isset($server['CONTENT_TYPE'])) {
  904. $header['content-type'] = $server['CONTENT_TYPE'];
  905. }
  906. if (isset($server['CONTENT_LENGTH'])) {
  907. $header['content-length'] = $server['CONTENT_LENGTH'];
  908. }
  909. }
  910. $this->header = array_change_key_case($header);
  911. }
  912. if (is_array($name)) {
  913. return $this->header = array_merge($this->header, $name);
  914. }
  915. if ('' === $name) {
  916. return $this->header;
  917. }
  918. $name = str_replace('_', '-', strtolower($name));
  919. return isset($this->header[$name]) ? $this->header[$name] : $default;
  920. }
  921. /**
  922. * 获取变量 支持过滤和默认值
  923. * @param array $data 数据源
  924. * @param string|false $name 字段名
  925. * @param mixed $default 默认值
  926. * @param string|array $filter 过滤函数
  927. * @return mixed
  928. */
  929. public function input($data = [], $name = '', $default = null, $filter = '')
  930. {
  931. if (false === $name) {
  932. // 获取原始数据
  933. return $data;
  934. }
  935. $name = (string) $name;
  936. if ('' != $name) {
  937. // 解析name
  938. if (strpos($name, '/')) {
  939. list($name, $type) = explode('/', $name);
  940. } else {
  941. $type = 's';
  942. }
  943. // 按.拆分成多维数组进行判断
  944. foreach (explode('.', $name) as $val) {
  945. if (isset($data[$val])) {
  946. $data = $data[$val];
  947. } else {
  948. // 无输入数据,返回默认值
  949. return $default;
  950. }
  951. }
  952. if (is_object($data)) {
  953. return $data;
  954. }
  955. }
  956. // 解析过滤器
  957. $filter = $this->getFilter($filter, $default);
  958. if (is_array($data)) {
  959. array_walk_recursive($data, [$this, 'filterValue'], $filter);
  960. reset($data);
  961. } else {
  962. $this->filterValue($data, $name, $filter);
  963. }
  964. if (isset($type) && $data !== $default) {
  965. // 强制类型转换
  966. $this->typeCast($data, $type);
  967. }
  968. return $data;
  969. }
  970. /**
  971. * 设置或获取当前的过滤规则
  972. * @param mixed $filter 过滤规则
  973. * @return mixed
  974. */
  975. public function filter($filter = null)
  976. {
  977. if (is_null($filter)) {
  978. return $this->filter;
  979. } else {
  980. $this->filter = $filter;
  981. }
  982. }
  983. protected function getFilter($filter, $default)
  984. {
  985. if (is_null($filter)) {
  986. $filter = [];
  987. } else {
  988. $filter = $filter ?: $this->filter;
  989. if (is_string($filter) && false === strpos($filter, '/')) {
  990. $filter = explode(',', $filter);
  991. } else {
  992. $filter = (array) $filter;
  993. }
  994. }
  995. $filter[] = $default;
  996. return $filter;
  997. }
  998. /**
  999. * 递归过滤给定的值
  1000. * @param mixed $value 键值
  1001. * @param mixed $key 键名
  1002. * @param array $filters 过滤方法+默认值
  1003. * @return mixed
  1004. */
  1005. private function filterValue(&$value, $key, $filters)
  1006. {
  1007. $default = array_pop($filters);
  1008. foreach ($filters as $filter) {
  1009. if (is_callable($filter)) {
  1010. // 调用函数或者方法过滤
  1011. $value = call_user_func($filter, $value);
  1012. } elseif (is_scalar($value)) {
  1013. if (false !== strpos($filter, '/')) {
  1014. // 正则过滤
  1015. if (!preg_match($filter, $value)) {
  1016. // 匹配不成功返回默认值
  1017. $value = $default;
  1018. break;
  1019. }
  1020. } elseif (!empty($filter)) {
  1021. // filter函数不存在时, 则使用filter_var进行过滤
  1022. // filter为非整形值时, 调用filter_id取得过滤id
  1023. $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
  1024. if (false === $value) {
  1025. $value = $default;
  1026. break;
  1027. }
  1028. }
  1029. }
  1030. }
  1031. return $this->filterExp($value);
  1032. }
  1033. /**
  1034. * 过滤表单中的表达式
  1035. * @param string $value
  1036. * @return void
  1037. */
  1038. public function filterExp(&$value)
  1039. {
  1040. // 过滤查询特殊字符
  1041. if (is_string($value) && preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT LIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOT EXISTS|NOTEXISTS|EXISTS|NOT NULL|NOTNULL|NULL|BETWEEN TIME|NOT BETWEEN TIME|NOTBETWEEN TIME|NOTIN|NOT IN|IN)$/i', $value)) {
  1042. $value .= ' ';
  1043. }
  1044. // TODO 其他安全过滤
  1045. }
  1046. /**
  1047. * 强制类型转换
  1048. * @param string $data
  1049. * @param string $type
  1050. * @return mixed
  1051. */
  1052. private function typeCast(&$data, $type)
  1053. {
  1054. switch (strtolower($type)) {
  1055. // 数组
  1056. case 'a':
  1057. $data = (array) $data;
  1058. break;
  1059. // 数字
  1060. case 'd':
  1061. $data = (int) $data;
  1062. break;
  1063. // 浮点
  1064. case 'f':
  1065. $data = (float) $data;
  1066. break;
  1067. // 布尔
  1068. case 'b':
  1069. $data = (boolean) $data;
  1070. break;
  1071. // 字符串
  1072. case 's':
  1073. default:
  1074. if (is_scalar($data)) {
  1075. $data = (string) $data;
  1076. } else {
  1077. throw new \InvalidArgumentException('variable type error:' . gettype($data));
  1078. }
  1079. }
  1080. }
  1081. /**
  1082. * 是否存在某个请求参数
  1083. * @access public
  1084. * @param string $name 变量名
  1085. * @param string $type 变量类型
  1086. * @param bool $checkEmpty 是否检测空值
  1087. * @return mixed
  1088. */
  1089. public function has($name, $type = 'param', $checkEmpty = false)
  1090. {
  1091. if (empty($this->$type)) {
  1092. $param = $this->$type();
  1093. } else {
  1094. $param = $this->$type;
  1095. }
  1096. // 按.拆分成多维数组进行判断
  1097. foreach (explode('.', $name) as $val) {
  1098. if (isset($param[$val])) {
  1099. $param = $param[$val];
  1100. } else {
  1101. return false;
  1102. }
  1103. }
  1104. return ($checkEmpty && '' === $param) ? false : true;
  1105. }
  1106. /**
  1107. * 获取指定的参数
  1108. * @access public
  1109. * @param string|array $name 变量名
  1110. * @param string $type 变量类型
  1111. * @return mixed
  1112. */
  1113. public function only($name, $type = 'param')
  1114. {
  1115. $param = $this->$type();
  1116. if (is_string($name)) {
  1117. $name = explode(',', $name);
  1118. }
  1119. $item = [];
  1120. foreach ($name as $key) {
  1121. if (isset($param[$key])) {
  1122. $item[$key] = $param[$key];
  1123. }
  1124. }
  1125. return $item;
  1126. }
  1127. /**
  1128. * 排除指定参数获取
  1129. * @access public
  1130. * @param string|array $name 变量名
  1131. * @param string $type 变量类型
  1132. * @return mixed
  1133. */
  1134. public function except($name, $type = 'param')
  1135. {
  1136. $param = $this->$type();
  1137. if (is_string($name)) {
  1138. $name = explode(',', $name);
  1139. }
  1140. foreach ($name as $key) {
  1141. if (isset($param[$key])) {
  1142. unset($param[$key]);
  1143. }
  1144. }
  1145. return $param;
  1146. }
  1147. /**
  1148. * 当前是否ssl
  1149. * @access public
  1150. * @return bool
  1151. */
  1152. public function isSsl()
  1153. {
  1154. $server = array_merge($_SERVER, $this->server);
  1155. if (isset($server['HTTPS']) && ('1' == $server['HTTPS'] || 'on' == strtolower($server['HTTPS']))) {
  1156. return true;
  1157. } elseif (isset($server['REQUEST_SCHEME']) && 'https' == $server['REQUEST_SCHEME']) {
  1158. return true;
  1159. } elseif (isset($server['SERVER_PORT']) && ('443' == $server['SERVER_PORT'])) {
  1160. return true;
  1161. } elseif (isset($server['HTTP_X_FORWARDED_PROTO']) && 'https' == $server['HTTP_X_FORWARDED_PROTO']) {
  1162. return true;
  1163. } elseif (Config::get('https_agent_name') && isset($server[Config::get('https_agent_name')])) {
  1164. return true;
  1165. }
  1166. return false;
  1167. }
  1168. /**
  1169. * 当前是否Ajax请求
  1170. * @access public
  1171. * @param bool $ajax true 获取原始ajax请求
  1172. * @return bool
  1173. */
  1174. public function isAjax($ajax = false)
  1175. {
  1176. $value = $this->server('HTTP_X_REQUESTED_WITH', '', 'strtolower');
  1177. $result = ('xmlhttprequest' == $value) ? true : false;
  1178. if (true === $ajax) {
  1179. return $result;
  1180. } else {
  1181. $result = $this->param(Config::get('var_ajax')) ? true : $result;
  1182. $this->mergeParam = false;
  1183. return $result;
  1184. }
  1185. }
  1186. /**
  1187. * 当前是否Pjax请求
  1188. * @access public
  1189. * @param bool $pjax true 获取原始pjax请求
  1190. * @return bool
  1191. */
  1192. public function isPjax($pjax = false)
  1193. {
  1194. $result = !is_null($this->server('HTTP_X_PJAX')) ? true : false;
  1195. if (true === $pjax) {
  1196. return $result;
  1197. } else {
  1198. $result = $this->param(Config::get('var_pjax')) ? true : $result;
  1199. $this->mergeParam = false;
  1200. return $result;
  1201. }
  1202. }
  1203. /**
  1204. * 获取客户端IP地址
  1205. * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
  1206. * @param boolean $adv 是否进行高级模式获取(有可能被伪装)
  1207. * @return mixed
  1208. */
  1209. public function ip($type = 0, $adv = true)
  1210. {
  1211. $type = $type ? 1 : 0;
  1212. static $ip = null;
  1213. if (null !== $ip) {
  1214. return $ip[$type];
  1215. }
  1216. $httpAgentIp = Config::get('http_agent_ip');
  1217. if ($httpAgentIp && isset($_SERVER[$httpAgentIp])) {
  1218. $ip = $_SERVER[$httpAgentIp];
  1219. } elseif ($adv) {
  1220. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1221. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1222. $pos = array_search('unknown', $arr);
  1223. if (false !== $pos) {
  1224. unset($arr[$pos]);
  1225. }
  1226. $ip = trim(current($arr));
  1227. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1228. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1229. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1230. $ip = $_SERVER['REMOTE_ADDR'];
  1231. }
  1232. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1233. $ip = $_SERVER['REMOTE_ADDR'];
  1234. }
  1235. // IP地址合法验证
  1236. $long = sprintf("%u", ip2long($ip));
  1237. $ip = $long ? [$ip, $long] : ['0.0.0.0', 0];
  1238. return $ip[$type];
  1239. }
  1240. /**
  1241. * 检测是否使用手机访问
  1242. * @access public
  1243. * @return bool
  1244. */
  1245. public function isMobile()
  1246. {
  1247. if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) {
  1248. return true;
  1249. } elseif (isset($_SERVER['HTTP_ACCEPT']) && strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML")) {
  1250. return true;
  1251. } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {
  1252. return true;
  1253. } elseif (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])) {
  1254. return true;
  1255. } else {
  1256. return false;
  1257. }
  1258. }
  1259. /**
  1260. * 当前URL地址中的scheme参数
  1261. * @access public
  1262. * @return string
  1263. */
  1264. public function scheme()
  1265. {
  1266. return $this->isSsl() ? 'https' : 'http';
  1267. }
  1268. /**
  1269. * 当前请求URL地址中的query参数
  1270. * @access public
  1271. * @return string
  1272. */
  1273. public function query()
  1274. {
  1275. return $this->server('QUERY_STRING');
  1276. }
  1277. /**
  1278. * 当前请求的host
  1279. * @access public
  1280. * @param bool $strict true 仅仅获取HOST
  1281. * @return string
  1282. */
  1283. public function host($strict = false)
  1284. {
  1285. if (isset($_SERVER['HTTP_X_REAL_HOST'])) {
  1286. $host = $_SERVER['HTTP_X_REAL_HOST'];
  1287. } else {
  1288. $host = $this->server('HTTP_HOST');
  1289. }
  1290. return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
  1291. }
  1292. /**
  1293. * 当前请求URL地址中的port参数
  1294. * @access public
  1295. * @return integer
  1296. */
  1297. public function port()
  1298. {
  1299. return $this->server('SERVER_PORT');
  1300. }
  1301. /**
  1302. * 当前请求 SERVER_PROTOCOL
  1303. * @access public
  1304. * @return integer
  1305. */
  1306. public function protocol()
  1307. {
  1308. return $this->server('SERVER_PROTOCOL');
  1309. }
  1310. /**
  1311. * 当前请求 REMOTE_PORT
  1312. * @access public
  1313. * @return integer
  1314. */
  1315. public function remotePort()
  1316. {
  1317. return $this->server('REMOTE_PORT');
  1318. }
  1319. /**
  1320. * 当前请求 HTTP_CONTENT_TYPE
  1321. * @access public
  1322. * @return string
  1323. */
  1324. public function contentType()
  1325. {
  1326. $contentType = $this->server('CONTENT_TYPE');
  1327. if ($contentType) {
  1328. if (strpos($contentType, ';')) {
  1329. list($type) = explode(';', $contentType);
  1330. } else {
  1331. $type = $contentType;
  1332. }
  1333. return trim($type);
  1334. }
  1335. return '';
  1336. }
  1337. /**
  1338. * 获取当前请求的路由信息
  1339. * @access public
  1340. * @param array $route 路由名称
  1341. * @return array
  1342. */
  1343. public function routeInfo($route = [])
  1344. {
  1345. if (!empty($route)) {
  1346. $this->routeInfo = $route;
  1347. } else {
  1348. return $this->routeInfo;
  1349. }
  1350. }
  1351. /**
  1352. * 设置或者获取当前请求的调度信息
  1353. * @access public
  1354. * @param array $dispatch 调度信息
  1355. * @return array
  1356. */
  1357. public function dispatch($dispatch = null)
  1358. {
  1359. if (!is_null($dispatch)) {
  1360. $this->dispatch = $dispatch;
  1361. }
  1362. return $this->dispatch;
  1363. }
  1364. /**
  1365. * 设置或者获取当前的模块名
  1366. * @access public
  1367. * @param string $module 模块名
  1368. * @return string|Request
  1369. */
  1370. public function module($module = null)
  1371. {
  1372. if (!is_null($module)) {
  1373. $this->module = $module;
  1374. return $this;
  1375. } else {
  1376. return $this->module ?: '';
  1377. }
  1378. }
  1379. /**
  1380. * 设置或者获取当前的控制器名
  1381. * @access public
  1382. * @param string $controller 控制器名
  1383. * @return string|Request
  1384. */
  1385. public function controller($controller = null)
  1386. {
  1387. if (!is_null($controller)) {
  1388. $this->controller = $controller;
  1389. return $this;
  1390. } else {
  1391. return $this->controller ?: '';
  1392. }
  1393. }
  1394. /**
  1395. * 设置或者获取当前的操作名
  1396. * @access public
  1397. * @param string $action 操作名
  1398. * @return string|Request
  1399. */
  1400. public function action($action = null)
  1401. {
  1402. if (!is_null($action) && !is_bool($action)) {
  1403. $this->action = $action;
  1404. return $this;
  1405. } else {
  1406. $name = $this->action ?: '';
  1407. return true === $action ? $name : strtolower($name);
  1408. }
  1409. }
  1410. /**
  1411. * 设置或者获取当前的语言
  1412. * @access public
  1413. * @param string $lang 语言名
  1414. * @return string|Request
  1415. */
  1416. public function langset($lang = null)
  1417. {
  1418. if (!is_null($lang)) {
  1419. $this->langset = $lang;
  1420. return $this;
  1421. } else {
  1422. return $this->langset ?: '';
  1423. }
  1424. }
  1425. /**
  1426. * 设置或者获取当前请求的content
  1427. * @access public
  1428. * @return string
  1429. */
  1430. public function getContent()
  1431. {
  1432. if (is_null($this->content)) {
  1433. $this->content = $this->input;
  1434. }
  1435. return $this->content;
  1436. }
  1437. /**
  1438. * 获取当前请求的php://input
  1439. * @access public
  1440. * @return string
  1441. */
  1442. public function getInput()
  1443. {
  1444. return $this->input;
  1445. }
  1446. /**
  1447. * 生成请求令牌
  1448. * @access public
  1449. * @param string $name 令牌名称
  1450. * @param mixed $type 令牌生成方法
  1451. * @return string
  1452. */
  1453. public function token($name = '__token__', $type = 'md5')
  1454. {
  1455. $type = is_callable($type) ? $type : 'md5';
  1456. $token = call_user_func($type, $_SERVER['REQUEST_TIME_FLOAT']);
  1457. if ($this->isAjax()) {
  1458. header($name . ': ' . $token);
  1459. }
  1460. Session::set($name, $token);
  1461. return $token;
  1462. }
  1463. /**
  1464. * 设置当前地址的请求缓存
  1465. * @access public
  1466. * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id
  1467. * @param mixed $expire 缓存有效期
  1468. * @param array $except 缓存排除
  1469. * @param string $tag 缓存标签
  1470. * @return void
  1471. */
  1472. public function cache($key, $expire = null, $except = [], $tag = null)
  1473. {
  1474. if (!is_array($except)) {
  1475. $tag = $except;
  1476. $except = [];
  1477. }
  1478. if (false !== $key && $this->isGet() && !$this->isCheckCache) {
  1479. // 标记请求缓存检查
  1480. $this->isCheckCache = true;
  1481. if (false === $expire) {
  1482. // 关闭当前缓存
  1483. return;
  1484. }
  1485. if ($key instanceof \Closure) {
  1486. $key = call_user_func_array($key, [$this]);
  1487. } elseif (true === $key) {
  1488. foreach ($except as $rule) {
  1489. if (0 === stripos($this->url(), $rule)) {
  1490. return;
  1491. }
  1492. }
  1493. // 自动缓存功能
  1494. $key = '__URL__';
  1495. } elseif (strpos($key, '|')) {
  1496. list($key, $fun) = explode('|', $key);
  1497. }
  1498. // 特殊规则替换
  1499. if (false !== strpos($key, '__')) {
  1500. $key = str_replace(['__MODULE__', '__CONTROLLER__', '__ACTION__', '__URL__', ''], [$this->module, $this->controller, $this->action, md5($this->url(true))], $key);
  1501. }
  1502. if (false !== strpos($key, ':')) {
  1503. $param = $this->param();
  1504. foreach ($param as $item => $val) {
  1505. if (is_string($val) && false !== strpos($key, ':' . $item)) {
  1506. $key = str_replace(':' . $item, $val, $key);
  1507. }
  1508. }
  1509. } elseif (strpos($key, ']')) {
  1510. if ('[' . $this->ext() . ']' == $key) {
  1511. // 缓存某个后缀的请求
  1512. $key = md5($this->url());
  1513. } else {
  1514. return;
  1515. }
  1516. }
  1517. if (isset($fun)) {
  1518. $key = $fun($key);
  1519. }
  1520. if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) {
  1521. // 读取缓存
  1522. $response = Response::create()->code(304);
  1523. throw new \think\exception\HttpResponseException($response);
  1524. } elseif (Cache::has($key)) {
  1525. list($content, $header) = Cache::get($key);
  1526. $response = Response::create($content)->header($header);
  1527. throw new \think\exception\HttpResponseException($response);
  1528. } else {
  1529. $this->cache = [$key, $expire, $tag];
  1530. }
  1531. }
  1532. }
  1533. /**
  1534. * 读取请求缓存设置
  1535. * @access public
  1536. * @return array
  1537. */
  1538. public function getCache()
  1539. {
  1540. return $this->cache;
  1541. }
  1542. /**
  1543. * 设置当前请求绑定的对象实例
  1544. * @access public
  1545. * @param string|array $name 绑定的对象标识
  1546. * @param mixed $obj 绑定的对象实例
  1547. * @return mixed
  1548. */
  1549. public function bind($name, $obj = null)
  1550. {
  1551. if (is_array($name)) {
  1552. $this->bind = array_merge($this->bind, $name);
  1553. } else {
  1554. $this->bind[$name] = $obj;
  1555. }
  1556. }
  1557. public function __set($name, $value)
  1558. {
  1559. $this->bind[$name] = $value;
  1560. }
  1561. public function __get($name)
  1562. {
  1563. return isset($this->bind[$name]) ? $this->bind[$name] : null;
  1564. }
  1565. public function __isset($name)
  1566. {
  1567. return isset($this->bind[$name]);
  1568. }
  1569. }