Api.php 15 KB

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