Api.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Auth;
  4. use think\Config;
  5. use think\Db;
  6. use think\exception\HttpResponseException;
  7. use think\exception\ValidateException;
  8. use think\Hook;
  9. use think\Lang;
  10. use think\Loader;
  11. use think\Request;
  12. use think\Response;
  13. use think\Route;
  14. use think\Validate;
  15. /**
  16. * API控制器基类
  17. */
  18. class Api
  19. {
  20. /**
  21. * @var Request Request 实例
  22. */
  23. protected $request;
  24. /**
  25. * @var bool 验证失败是否抛出异常
  26. */
  27. protected $failException = false;
  28. /**
  29. * @var bool 是否批量验证
  30. */
  31. protected $batchValidate = false;
  32. /**
  33. * @var array 前置操作方法列表
  34. */
  35. protected $beforeActionList = [];
  36. /**
  37. * 无需登录的方法,同时也就不需要鉴权了
  38. * @var array
  39. */
  40. protected $noNeedLogin = [];
  41. /**
  42. * 无需鉴权的方法,但需要登录
  43. * @var array
  44. */
  45. protected $noNeedRight = [];
  46. /**
  47. * 权限Auth
  48. * @var Auth
  49. */
  50. protected $auth = null;
  51. /**
  52. * 默认响应输出类型,支持json/xml
  53. * @var string
  54. */
  55. protected $responseType = 'json';
  56. //分页
  57. protected $page;
  58. //每页展示数量
  59. protected $pagenum;
  60. /**
  61. * 构造方法
  62. * @access public
  63. * @param Request $request Request 对象
  64. */
  65. public function __construct(Request $request = null)
  66. {
  67. $this->request = is_null($request) ? Request::instance() : $request;
  68. $this->page = input('page', 1, 'intval');
  69. $this->pagenum = input('pagenum', 10, 'intval');
  70. // 控制器初始化
  71. $this->_initialize();
  72. // 前置操作方法
  73. if ($this->beforeActionList) {
  74. foreach ($this->beforeActionList as $method => $options) {
  75. is_numeric($method) ?
  76. $this->beforeAction($options) :
  77. $this->beforeAction($method, $options);
  78. }
  79. }
  80. }
  81. /**
  82. * 初始化操作
  83. * @access protected
  84. */
  85. protected function _initialize()
  86. {
  87. //跨域请求检测
  88. check_cors_request();
  89. // 检测IP是否允许
  90. check_ip_allowed();
  91. //移除HTML标签
  92. $this->request->filter('trim,strip_tags,htmlspecialchars');
  93. $this->auth = Auth::instance();
  94. $modulename = $this->request->module();
  95. $controllername = Loader::parseName($this->request->controller());
  96. $actionname = strtolower($this->request->action());
  97. // token
  98. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  99. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  100. // 设置当前请求的URI
  101. $this->auth->setRequestUri($path);
  102. // 检测是否需要验证登录
  103. if (!$this->auth->match($this->noNeedLogin)) {
  104. //初始化
  105. $this->auth->init($token);
  106. //检测是否登录
  107. if (!$this->auth->isLogin()) {
  108. $this->error(__('Please login first'), null, 401);
  109. }
  110. // 判断是否需要验证权限
  111. if (!$this->auth->match($this->noNeedRight)) {
  112. // 判断控制器和方法判断是否有对应权限
  113. if (!$this->auth->check($path)) {
  114. $this->error(__('You have no permission'), null, 403);
  115. }
  116. }
  117. } else {
  118. // 如果有传递token才验证是否登录状态
  119. if ($token) {
  120. $this->auth->init($token);
  121. }
  122. }
  123. $upload = \app\common\model\Config::upload();
  124. // 上传信息配置后
  125. Hook::listen("upload_config_init", $upload);
  126. Config::set('upload', array_merge(Config::get('upload'), $upload));
  127. // 加载当前控制器语言包
  128. $this->loadlang($controllername);
  129. //记录请求地址
  130. if ($controllername != 'notify') {
  131. $user_log = [
  132. 'user_id' => $this->auth->id ?: '',
  133. 'username' => $this->auth->mobile ?: '',
  134. 'url' => $modulename . '/' . $controllername . '/' . $actionname,
  135. 'content' => json_encode(request()->param('', null, 'trim,strip_tags,htmlspecialchars'), JSON_UNESCAPED_UNICODE),
  136. 'ip' => request()->ip(),
  137. 'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
  138. 'createtime' => time()
  139. ];
  140. Db::name('user_log')->insert($user_log);
  141. $session_content = json_decode($user_log['content'], true);
  142. if (isset($session_content['remark']) && $session_content['remark'] == '从外部启动跳转视频播放') {
  143. $session_result = explode(';', $session_content['result']);
  144. $session_video_id = $session_result[1];
  145. $session_video_id = mb_substr($session_video_id, 6);
  146. cache('session_video_id' . $this->auth->id, $session_video_id, 10);
  147. }
  148. }
  149. }
  150. /**
  151. * 加载语言文件
  152. * @param string $name
  153. */
  154. protected function loadlang($name)
  155. {
  156. $name = Loader::parseName($name);
  157. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  158. }
  159. /**
  160. * 操作成功返回的数据
  161. * @param string $msg 提示信息
  162. * @param mixed $data 要返回的数据
  163. * @param int $code 错误码,默认为1
  164. * @param string $type 输出类型
  165. * @param array $header 发送的 Header 信息
  166. */
  167. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  168. {
  169. $this->result($msg, $data, $code, $type, $header);
  170. }
  171. /**
  172. * 操作失败返回的数据
  173. * @param string $msg 提示信息
  174. * @param mixed $data 要返回的数据
  175. * @param int $code 错误码,默认为0
  176. * @param string $type 输出类型
  177. * @param array $header 发送的 Header 信息
  178. */
  179. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  180. {
  181. $this->result($msg, $data, $code, $type, $header);
  182. }
  183. /**
  184. * 返回封装后的 API 数据到客户端
  185. * @access protected
  186. * @param mixed $msg 提示信息
  187. * @param mixed $data 要返回的数据
  188. * @param int $code 错误码,默认为0
  189. * @param string $type 输出类型,支持json/xml/jsonp
  190. * @param array $header 发送的 Header 信息
  191. * @return void
  192. * @throws HttpResponseException
  193. */
  194. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  195. {
  196. $result = [
  197. 'code' => $code,
  198. 'msg' => $msg,
  199. 'time' => Request::instance()->server('REQUEST_TIME'),
  200. 'data' => $data,
  201. ];
  202. // 如果未设置类型则自动判断
  203. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  204. if (isset($header['statuscode'])) {
  205. $code = $header['statuscode'];
  206. unset($header['statuscode']);
  207. } else {
  208. //未设置状态码,根据code值判断
  209. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  210. }
  211. $response = Response::create($result, $type, $code)->header($header);
  212. throw new HttpResponseException($response);
  213. }
  214. /**
  215. * 前置操作
  216. * @access protected
  217. * @param string $method 前置操作方法名
  218. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  219. * @return void
  220. */
  221. protected function beforeAction($method, $options = [])
  222. {
  223. if (isset($options['only'])) {
  224. if (is_string($options['only'])) {
  225. $options['only'] = explode(',', $options['only']);
  226. }
  227. if (!in_array($this->request->action(), $options['only'])) {
  228. return;
  229. }
  230. } elseif (isset($options['except'])) {
  231. if (is_string($options['except'])) {
  232. $options['except'] = explode(',', $options['except']);
  233. }
  234. if (in_array($this->request->action(), $options['except'])) {
  235. return;
  236. }
  237. }
  238. call_user_func([$this, $method]);
  239. }
  240. /**
  241. * 设置验证失败后是否抛出异常
  242. * @access protected
  243. * @param bool $fail 是否抛出异常
  244. * @return $this
  245. */
  246. protected function validateFailException($fail = true)
  247. {
  248. $this->failException = $fail;
  249. return $this;
  250. }
  251. /**
  252. * 验证数据
  253. * @access protected
  254. * @param array $data 数据
  255. * @param string|array $validate 验证器名或者验证规则数组
  256. * @param array $message 提示信息
  257. * @param bool $batch 是否批量验证
  258. * @param mixed $callback 回调方法(闭包)
  259. * @return array|string|true
  260. * @throws ValidateException
  261. */
  262. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  263. {
  264. if (is_array($validate)) {
  265. $v = Loader::validate();
  266. $v->rule($validate);
  267. } else {
  268. // 支持场景
  269. if (strpos($validate, '.')) {
  270. list($validate, $scene) = explode('.', $validate);
  271. }
  272. $v = Loader::validate($validate);
  273. !empty($scene) && $v->scene($scene);
  274. }
  275. // 批量验证
  276. if ($batch || $this->batchValidate) {
  277. $v->batch(true);
  278. }
  279. // 设置错误信息
  280. if (is_array($message)) {
  281. $v->message($message);
  282. }
  283. // 使用回调验证
  284. if ($callback && is_callable($callback)) {
  285. call_user_func_array($callback, [$v, &$data]);
  286. }
  287. if (!$v->check($data)) {
  288. if ($this->failException) {
  289. throw new ValidateException($v->getError());
  290. }
  291. return $v->getError();
  292. }
  293. return true;
  294. }
  295. /**
  296. * 刷新Token
  297. */
  298. protected function token()
  299. {
  300. $token = $this->request->param('__token__');
  301. //验证Token
  302. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  303. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  304. }
  305. //刷新Token
  306. $this->request->token();
  307. }
  308. /*检查今日是否登录赠送过成长值*/
  309. protected function checklogingrowth($id = 0) {
  310. if ($id) {
  311. $user_info = Db::name('user')->find($id);
  312. //查询今日是否登录赠送过成长值
  313. $time = strtotime(date('Y-m-d', time()));
  314. $logingrowth = config('site.logingrowth') ? (int)config('site.logingrowth') : 0;//登录成长值
  315. if ($logingrowth) {
  316. $growth_log = Db::name('user_growth_log')->where(['user_id' => $user_info['id'], 'type' => 1])->order('id', 'desc')->find();
  317. if (!$growth_log || ($growth_log['after'] == $user_info['growthvalue'] && $growth_log['createtime'] < $time)) {
  318. Db::startTrans();
  319. $rs = create_growth_log($logingrowth, '登录', $id, 1);
  320. if ($rs != 1) {
  321. Db::rollback();
  322. } else {
  323. Db::commit();
  324. }
  325. /*$growth_data['user_id'] = $user_info['id'];
  326. $growth_data['growth'] = $logingrowth;
  327. $growth_data['before'] = $user_info['growthvalue'];
  328. $growth_data['after'] = $user_info['growthvalue'] + $logingrowth;
  329. $growth_data['memo'] = '登录';
  330. $growth_data['createtime'] = time();
  331. Db::startTrans();
  332. $rt = Db::name('user_growth_log')->insertGetId($growth_data);
  333. $rs = Db::name('user')->where(['id' => $user_info['id'], 'growthvalue' => $user_info['growthvalue']])->setField('growthvalue', $growth_data['after']);
  334. if ($rt && $rs) {
  335. Db::commit();
  336. } else {
  337. Db::rollback();
  338. }*/
  339. }
  340. }
  341. }
  342. }
  343. /*检查会员等级*/
  344. protected function checkviplevel($id = 0) {
  345. if ($id) {
  346. $user_info = Db::name('user')->find($id);
  347. //检查更新会员等级
  348. $growthvalue = $user_info['growthvalue'];
  349. $vip_info = Db::name('vip')->where(['growthvalue' => ['elt', $growthvalue]])->order('id', 'desc')->find();
  350. $user_data = [];
  351. if ($vip_info['id'] != $user_info['growthlevel']) {
  352. $user_data['growthlevel'] = $vip_info['id'];
  353. //当前会员信息
  354. $last_vip_info = Db::name('vip')->find($user_info['growthlevel']);
  355. $freenumber = $user_info['freenumber'] + $vip_info['free'] - $last_vip_info['free'];
  356. $user_data['freenumber'] = $freenumber > 0 ? $freenumber : 0;//免费次数
  357. }
  358. //检查体验会员
  359. if ($user_info['experiencetime'] < time()) {
  360. //体验会员到期
  361. if ($vip_info['id'] != $user_info['growthlevel']) { //成长值会员等级更新
  362. $user_data['maxlevel'] = $vip_info['id'];
  363. } elseif ($user_info['maxlevel'] != $user_info['growthlevel']) {
  364. $user_data['maxlevel'] = $user_info['growthlevel'];
  365. }
  366. } else {
  367. //体验会员没到期
  368. if ($vip_info['id'] > $user_info['maxlevel']) {
  369. $user_data['maxlevel'] = $vip_info['id'];
  370. }
  371. }
  372. if ($user_data) {
  373. Db::startTrans();
  374. $res = Db::name('user')->where(['id' => $user_info['id']])->setField($user_data);
  375. if (!$res) {
  376. Db::rollback();
  377. } else {
  378. Db::commit();
  379. }
  380. }
  381. }
  382. }
  383. //base16编码
  384. public function base16_encode($string = '')
  385. {
  386. $encode = '';
  387. $chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
  388. for ($i = 0; $i < strlen($string); $i++) {
  389. $encode .= $chars[(ord($string[$i]) & 0b11110000) >> 4] . $chars[ord($string[$i]) & 0b00001111];
  390. }
  391. return $encode;
  392. }
  393. }