request = is_null($request) ? Request::instance() : $request; $this->page = input('page', 1, 'intval'); $this->pagenum = input('pagenum', 10, 'intval'); // 控制器初始化 $this->_initialize(); // 前置操作方法 if ($this->beforeActionList) { foreach ($this->beforeActionList as $method => $options) { is_numeric($method) ? $this->beforeAction($options) : $this->beforeAction($method, $options); } } } /** * 初始化操作 * @access protected */ protected function _initialize() { //跨域请求检测 check_cors_request(); // 检测IP是否允许 check_ip_allowed(); //移除HTML标签 $this->request->filter('trim,strip_tags,htmlspecialchars'); $this->auth = Auth::instance(); $modulename = $this->request->module(); $controllername = Loader::parseName($this->request->controller()); $actionname = strtolower($this->request->action()); // token $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token'))); $path = str_replace('.', '/', $controllername) . '/' . $actionname; // 设置当前请求的URI $this->auth->setRequestUri($path); // 检测是否需要验证登录 if (!$this->auth->match($this->noNeedLogin)) { //初始化 $this->auth->init($token); //检测是否登录 if (!$this->auth->isLogin()) { $this->error(__('Please login first'), null, 401); } // 判断是否需要验证权限 if (!$this->auth->match($this->noNeedRight)) { // 判断控制器和方法判断是否有对应权限 if (!$this->auth->check($path)) { $this->error(__('You have no permission'), null, 403); } } } else { // 如果有传递token才验证是否登录状态 if ($token) { $this->auth->init($token); } } $upload = \app\common\model\Config::upload(); // 上传信息配置后 Hook::listen("upload_config_init", $upload); Config::set('upload', array_merge(Config::get('upload'), $upload)); // 加载当前控制器语言包 $this->loadlang($controllername); //记录请求地址 if ($controllername != 'notify') { $user_log = [ 'user_id' => $this->auth->id ?: '', 'username' => $this->auth->mobile ?: '', 'url' => $modulename . '/' . $controllername . '/' . $actionname, 'param' => json_encode($this->request->request()), 'content' => json_encode(request()->param('', null, 'trim,strip_tags,htmlspecialchars'), JSON_UNESCAPED_UNICODE), 'ip' => request()->ip(), 'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255), 'createtime' => time() ]; Db::name('user_log')->insert($user_log); /*$session_content = json_decode($user_log['content'], true); if (isset($session_content['remark']) && $session_content['remark'] == '从外部启动跳转视频播放') { $session_result = explode(';', $session_content['result']); $session_video_id = $session_result[1]; $session_video_id = mb_substr($session_video_id, 6); $session_video_id_time = $session_video_id . '-3'; $data = Token::get($session_content['token']); $session_user_id = intval($data['user_id']); cache('session_video_id_time' . $session_user_id, $session_video_id_time, 10); }*/ } } /** * 加载语言文件 * @param string $name */ protected function loadlang($name) { $name = Loader::parseName($name); Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php'); } /** * 操作成功返回的数据 * @param string $msg 提示信息 * @param mixed $data 要返回的数据 * @param int $code 错误码,默认为1 * @param string $type 输出类型 * @param array $header 发送的 Header 信息 */ protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = []) { if($msg == 1){ $msg = 'success'; } if(empty($msg)){ $msg = '操作成功'; } $this->result($msg, $data, $code, $type, $header); } /** * 操作失败返回的数据 * @param string $msg 提示信息 * @param mixed $data 要返回的数据 * @param int $code 错误码,默认为0 * @param string $type 输出类型 * @param array $header 发送的 Header 信息 */ protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = []) { if(empty($msg)){ $msg = __('Invalid parameters'); } $this->result($msg, $data, $code, $type, $header); } /** * 返回封装后的 API 数据到客户端 * @access protected * @param mixed $msg 提示信息 * @param mixed $data 要返回的数据 * @param int $code 错误码,默认为0 * @param string $type 输出类型,支持json/xml/jsonp * @param array $header 发送的 Header 信息 * @return void * @throws HttpResponseException */ protected function result($msg, $data = null, $code = 0, $type = null, array $header = []) { $result = [ 'code' => $code, 'msg' => $msg, 'time' => Request::instance()->server('REQUEST_TIME'), 'data' => $data, ]; // 如果未设置类型则自动判断 $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType); if (isset($header['statuscode'])) { $code = $header['statuscode']; unset($header['statuscode']); } else { //未设置状态码,根据code值判断 $code = $code >= 1000 || $code < 200 ? 200 : $code; } $response = Response::create($result, $type, $code)->header($header); throw new HttpResponseException($response); } /** * 前置操作 * @access protected * @param string $method 前置操作方法名 * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]] * @return void */ protected function beforeAction($method, $options = []) { if (isset($options['only'])) { if (is_string($options['only'])) { $options['only'] = explode(',', $options['only']); } if (!in_array($this->request->action(), $options['only'])) { return; } } elseif (isset($options['except'])) { if (is_string($options['except'])) { $options['except'] = explode(',', $options['except']); } if (in_array($this->request->action(), $options['except'])) { return; } } call_user_func([$this, $method]); } /** * 设置验证失败后是否抛出异常 * @access protected * @param bool $fail 是否抛出异常 * @return $this */ protected function validateFailException($fail = true) { $this->failException = $fail; return $this; } /** * 验证数据 * @access protected * @param array $data 数据 * @param string|array $validate 验证器名或者验证规则数组 * @param array $message 提示信息 * @param bool $batch 是否批量验证 * @param mixed $callback 回调方法(闭包) * @return array|string|true * @throws ValidateException */ protected function validate($data, $validate, $message = [], $batch = false, $callback = null) { if (is_array($validate)) { $v = Loader::validate(); $v->rule($validate); } else { // 支持场景 if (strpos($validate, '.')) { list($validate, $scene) = explode('.', $validate); } $v = Loader::validate($validate); !empty($scene) && $v->scene($scene); } // 批量验证 if ($batch || $this->batchValidate) { $v->batch(true); } // 设置错误信息 if (is_array($message)) { $v->message($message); } // 使用回调验证 if ($callback && is_callable($callback)) { call_user_func_array($callback, [$v, &$data]); } if (!$v->check($data)) { if ($this->failException) { throw new ValidateException($v->getError()); } return $v->getError(); } return true; } /** * 刷新Token */ protected function token() { $token = $this->request->param('__token__'); //验证Token if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) { $this->error(__('Token verification error'), ['__token__' => $this->request->token()]); } //刷新Token $this->request->token(); } /*检查今日是否登录赠送过成长值*/ protected function checklogingrowth($id = 0) { if ($id) { $user_info = Db::name('user')->find($id); //查询今日是否登录赠送过成长值 $time = strtotime(date('Y-m-d', time())); $logingrowth = config('site.logingrowth') ? (int)config('site.logingrowth') : 0;//登录成长值 if ($logingrowth) { $growth_log = Db::name('user_growth_log')->where(['user_id' => $user_info['id'], 'type' => 1])->order('id', 'desc')->find(); if (!$growth_log || ($growth_log['after'] == $user_info['growthvalue'] && $growth_log['createtime'] < $time)) { Db::startTrans(); $rs = create_growth_log($logingrowth, '登录', $id, 1); if ($rs != 1) { Db::rollback(); } else { Db::commit(); } /*$growth_data['user_id'] = $user_info['id']; $growth_data['growth'] = $logingrowth; $growth_data['before'] = $user_info['growthvalue']; $growth_data['after'] = $user_info['growthvalue'] + $logingrowth; $growth_data['memo'] = '登录'; $growth_data['createtime'] = time(); Db::startTrans(); $rt = Db::name('user_growth_log')->insertGetId($growth_data); $rs = Db::name('user')->where(['id' => $user_info['id'], 'growthvalue' => $user_info['growthvalue']])->setField('growthvalue', $growth_data['after']); if ($rt && $rs) { Db::commit(); } else { Db::rollback(); }*/ } } } } /*检查会员等级*/ protected function checkviplevel($id = 0) { if ($id) { $user_info = Db::name('user')->find($id); //检查更新会员等级 $growthvalue = $user_info['growthvalue']; $vip_info = Db::name('vip')->where(['growthvalue' => ['elt', $growthvalue]])->order('id', 'desc')->find(); $user_data = []; if ($vip_info['id'] != $user_info['growthlevel']) { $user_data['growthlevel'] = $vip_info['id']; //当前会员信息 $last_vip_info = Db::name('vip')->find($user_info['growthlevel']); $freenumber = $user_info['freenumber'] + $vip_info['free'] - $last_vip_info['free']; $user_data['freenumber'] = $freenumber > 0 ? $freenumber : 0;//免费次数 } //检查体验会员 if ($user_info['experiencetime'] < time()) { //体验会员到期 if ($vip_info['id'] != $user_info['growthlevel']) { //成长值会员等级更新 $user_data['maxlevel'] = $vip_info['id']; } elseif ($user_info['maxlevel'] != $user_info['growthlevel']) { $user_data['maxlevel'] = $user_info['growthlevel']; } } else { //体验会员没到期 if ($vip_info['id'] > $user_info['maxlevel']) { $user_data['maxlevel'] = $vip_info['id']; } } if ($user_data) { Db::startTrans(); $res = Db::name('user')->where(['id' => $user_info['id']])->setField($user_data); if (!$res) { Db::rollback(); } else { Db::commit(); } } } } //base16编码 public function base16_encode($string = '') { $encode = ''; $chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']; for ($i = 0; $i < strlen($string); $i++) { $encode .= $chars[(ord($string[$i]) & 0b11110000) >> 4] . $chars[ord($string[$i]) & 0b00001111]; } return $encode; } }