www.gusucode.com > CIM PHP城市信息聚合(采集)系统 v0.0.5源码程序 > code/application/common/controller/Init.php
<?php /** * +------------------------------------------------------------ * | 控制器基类 (common/controller/Init.php) * +------------------------------------------------------------ * | @author: zhx (10630650@qq.com) * | @create_time: 2018-03-10 11:34:47 * +------------------------------------------------------------ * | @copyright: CIM城市信息聚合系统 http://cim.wandu.net * +------------------------------------------------------------ * | @last_modified_by: zhx * | @last_modified_time: 2018-03-10 11:34:47 * +------------------------------------------------------------ * | @todo: * +------------------------------------------------------------ */ namespace app\common\controller; use think\Controller; use think\facade\Env; header('X-Powered-By:CIM'); class Init extends Controller { public static $sys; public static $cfg; public static $user = ['group_id' => 0]; protected function initialize() { self::$sys = [ 'referer' => (input('server.HTTP_REFERER') ? input('server.HTTP_REFERER') : ''), 'module' => strtolower($this->request->module()), 'controller' => strtolower($this->request->controller()), 'action' => strtolower($this->request->action()), 'ip' => $this->request->ip(), 'datetime' => date('Y-m-d H:i:s', time()), 'is_mobile' => $this->request->isMobile(), 'method' => strtolower($this->request->method()), ]; $this->allow_source(); $this->assign('sys', self::$sys); $this->assign('cfg', self::$cfg = $this->load_setting('cfg')); if (self::$sys['controller'] != 'api') { if (self::$sys['is_mobile'] && !empty(self::$cfg['mobile_domain']) && strpos(self::$cfg['domain'], $_SERVER['HTTP_HOST'])) { $url = self::$cfg['mobile_domain']; //$url = rtrim(self::$cfg['app_domain'], '/') . (($_SERVER['REQUEST_URI'] == '/' || $_SERVER['REQUEST_URI'] == '/index.php') ? '' : ('/' . self::$sys['module'] . '/' . self::$sys['controller'] . '/' . (self::$sys['action'] == 'index' ? 'index' : 'view') . (input('?param.id') ? '/id/' . input('param.id') : '') . '?type=jump')); die(header('Location:' . $url)); } } if (isset(self::$cfg['close']) && self::$cfg['close'] == 1 && self::$sys['controller'] != 'admin') { if (self::$sys['module'] != 'admin') return $this->error(self::$cfg['close_tips']); } $this->check_token(); $this->role_check(); $this->assign('param', input('param.')); } /** * 允许跨域 */ function allow_source() { $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ''; $allow_origin = config('')['source']; if (in_array($origin, $allow_origin)) { header('Access-Control-Allow-Origin:' . $origin); } if (self::$sys['controller'] == 'admin' || self::$sys['module'] == 'admin' || in_array(self::$sys['module'] . self::$sys['controller'] . self::$sys['action'], ['userapisend_sms', 'userapiregister', 'indexapimanage', 'messageapimessage', 'userapicheck_name_exists', 'filesapiupload'])) { header("Access-Control-Allow-Credentials: true"); } header('content-type:application:json;charset=utf8'); header('Access-Control-Allow-Methods:POST'); header('Access-Control-Allow-Methods:GET'); header('Access-Control-Allow-Methods:REQUEST'); header('Access-Control-Allow-Headers:x-requested-with,content-type,token,key'); if (self::$sys['method'] == 'options') die(json_encode(['code' => 1, 'msg' => ''])); } /** * 检测权限 */ private function role_check() { $roles = ['user', 'admin']; foreach ($roles as $v) { if (!empty(session($v))) { if ($v == 'user') self::$user = session($v); $this->assign($v, session($v)); } } if (!in_array(self::$sys['controller'], $roles)) return; $_controller = self::$sys['controller']; if (empty(session($_controller))) { if ($_controller == 'admin') die(json_encode(['code' => 1000, 'msg' => '请登录......'])); $this->redirect($_controller . '/index/login'); } //检测角色权限 if (session($_controller . '.role_id')) { $role_power = array(); if (session($_controller . '.power')) $role_power = explode(',', session($_controller . '.power')); $action_key = self::$sys['module'] . '_' . $_controller . '_' . self::$sys['action']; if (!in_array($action_key, [ 'index_' . $_controller . '_index' ]) && !in_array($action_key, $role_power) ) return json(['code' => 1001, 'msg' => '您没有此项管理权限']); } $this->init_nav(); } /** * 获得所有模块的管理权限 * @return array */ public function get_nav_map() { $modules = get_dir(Env::get('app_path')); $_controller = self::$sys['controller']; $_map = []; foreach ($modules as $v) { if ($v == 'common' || !is_file(Env::get('app_path') . $v . '/config/app.php')) continue; $_cfg = include Env::get('app_path') . $v . '/config/app.php'; if (isset($_cfg['nav'][$_controller]) && !empty($_cfg['nav'][$_controller])) { $nav = []; foreach ($_cfg['nav'][$_controller] as $kk => $vv) { $nav[$v . '_' . $_controller . '_' . $kk] = (is_array($vv) ? $vv[0] : $vv); } $_map[$v] = ['name' => $_cfg['name'], 'controller' => $_controller, 'nav' => $nav]; } } return $_map; } public function _404() { return response($this->fetch(config('app.http_exception_template.404')), 404); } /** * 初始化导航 */ private function init_nav() { $_controller = self::$sys['controller']; if (!in_array($_controller, array('user', 'company', 'admin'))) return; $modules = get_dir(Env::get('app_path')); $nav = []; $_mounts = config('nav.mounts'); $nav = array_merge($nav, $_mounts); $modules = &$modules; foreach ($modules as $v) { if ($v == 'common' || !is_file(Env::get('app_path') . $v . '/config/app.php')) continue; $_cfg = include Env::get('app_path') . $v . '/config/app.php'; if (!isset($_cfg['nav'][$_controller])) continue; $_v = ['key' => $v, 'name' => $_cfg['name'], 'icon' => (isset($_cfg['icon']) ? $_cfg['icon'] : ''), 'url' => url('/' . $v . '/' . $_controller)]; if (config('nav.mode') == 1) $_v['subnav'] = $this->parse_subnav($v, $_cfg['nav'][$_controller]); if (isset($_cfg['nav']['mount'])) { if (isset($nav[$_cfg['nav']['mount']])) { $nav[$_cfg['nav']['mount']]['subnav'][$v] = $_v; } else { array_push($modules, $v); } continue; } $nav[$v] = $_v; } foreach ($_mounts as $k => $v) { if (empty($nav[$k]['subnav'])) unset($nav[$k]); } $this->assign('nav', $nav); $this->init_subnav(); return $nav; } /** * 解析子导航 */ private function parse_subnav($module, $arr) { if (isset($arr) && !empty($arr)) { foreach ($arr as $k => $v) { if (is_array($v)) { unset($arr[$k]); continue; } $arr[$k] = [ 'name' => $v, 'url' => url($module . '/' . self::$sys['controller'] . '/' . $k), ]; } return $arr; } } /** * 初始化子导航 */ private function init_subnav() { $_key = self::$sys['controller']; if (!is_file(Env::get('app_path') . self::$sys['module'] . '/config/app.php')) return; $_cfg = include Env::get('app_path') . self::$sys['module'] . '/config/app.php'; if (isset($_cfg['nav'][$_key]) && !empty($_cfg['nav'][$_key])) { $subnav = $_cfg['nav'][$_key]; foreach ($subnav as $k => $v) { $tmp = []; if (is_array($v)) { $tmp['name'] = $v[0]; $tmp['hide'] = 1; } else { $tmp['name'] = $v; $tmp['hide'] = 0; } $tmp['url'] = url(self::$sys['module'] . '/' . $_key . '/' . $k); $tmp['on'] = (self::$sys['action'] == $k ? 1 : 0); if ($tmp['on'] == 1) { $this->assign('current_nav', $tmp); } $subnav[$k] = $tmp; } $temp_subnav = (isset($subnav[self::$sys['action']]) && $subnav[self::$sys['action']]['hide'] == 1 ? $subnav[self::$sys['action']] : []); $this->assign('temp_subnav', $temp_subnav); if (!isset($this->_module['key'])) $this->_module['key'] = self::$sys['module']; if (self::$sys['module'] == $this->_module['key']) $this->assign('subnav', $subnav); return $subnav; } } /** * 初始化分页器 */ public function init_pager($count, $listRows = 20, $parameter = []) { $_page = new \app\common\controller\Page($count, $listRows, $parameter); // 实例化分页类 传入总记录数和每页显示的记录数 $_page->setConfig('header', '条记录'); $_page->setConfig('prev', '上一页'); $_page->setConfig('next', '下一页'); if (self::$sys['controller'] == 'admin') { $_page->setConfig('theme', '<li class="disabled"><span class="total">%TOTAL_ROW%%HEADER%/%TOTAL_PAGE%页</span></li>%FIRST%%UP_PAGE% %LINK_PAGE%%DOWN_PAGE%%END%'); } else { $_page->setConfig('theme', '%FIRST%%UP_PAGE% %LINK_PAGE%%DOWN_PAGE%%END%'); } //(对thinkphp自带分页的格式进行自定义) $pager = $_page->show(); // 分页显示输出 $this->assign('count', $count); $this->assign('pager', $pager); $this->assign('page', $_page); return array('firstRow' => $_page->firstRow, 'listRows' => $_page->listRows); } /** * 导入excel文件 * @param $path * @throws \PHPExcel_Exception * @throws \PHPExcel_Reader_Exception */ protected function load_excel($path) { if (!is_file($path)) return []; include(Env::get('extend_path') . 'PHPExcel.php'); $obj = new \PHPExcel(); $reader = new \PHPExcel_Reader_Excel2007(); if (!$reader->canRead($path)) { $reader = new \PHPExcel_Reader_Excel5(); if (!$reader->canRead($path)) { $this->error('未找到导入文件'); } } $obj = $reader->load($path); //读取excel文件中的第一个工作表 $current_sheet = $obj->getSheet(0); //取得最大列号 $all_column = $current_sheet->getHighestColumn(); //取得总行数 $all_row = $current_sheet->getHighestRow(); $all_value = array(); //从第二行开始输出,因为excel表中第一行为列名 for ($current_row = 2; $current_row <= $all_row; $current_row++) { //从第A列开始输出 for ($current_column = 'A'; $current_column <= $all_column; $current_column++) { $val = $current_sheet->getCell($current_column . $current_row)->getValue(); $all_value[$current_row][$current_column] = $val; } } return $all_value; } /** * 导出EXCEL文件 * @param $filename * @param $head_arr * @param $data * @throws \PHPExcel_Exception * @throws \PHPExcel_Reader_Exception */ protected function save_excel($filename, $head_arr, $data) { $filename .= '.xls'; include(Env::get('extend_path') . 'PHPExcel.php'); //创建PHPExcel对象,注意,不能少了\ $obj = new \PHPExcel(); $objProps = $obj->getProperties(); //设置表头 $key = ord("A"); foreach ($head_arr as $v) { $colum = chr($key); $obj->setActiveSheetIndex(0)->setCellValue($colum . '1', $v); $obj->setActiveSheetIndex(0)->setCellValue($colum . '1', $v); $key += 1; } $column = 2; $objActSheet = $obj->getActiveSheet(); foreach ($data as $key => $rows) { //行写入 $span = ord("A"); foreach ($rows as $keyName => $value) {// 列写入 $j = chr($span); $objActSheet->setCellValue($j . $column, $value); $span++; } $column++; } $filename = iconv("utf-8", "gb2312", $filename); //重命名表 //$obj->getActiveSheet()->setTitle('test'); //设置活动单指数到第一个表,所以Excel打开这是第一个表 $obj->setActiveSheetIndex(0); header('Content-Type: application/vnd.ms-excel'); header("Content-Disposition: attachment;filename=\"$filename\""); header('Cache-Control: max-age=0'); $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel5'); $objWriter->save('php://output'); //文件通过浏览器下载 exit; } /** * 筛选 * @param array $ops * @return array|void */ protected function init_filters($ops = []) { if (empty($ops)) return; $rs = []; $url = self::$sys['module'] . '/' . self::$sys['controller'] . '/' . self::$sys['action']; $params = input('param.'); foreach ($ops as $val) { list($key, $name, $param) = $val; $option = [ 'all' => [ 'url' => url($url, array_merge(input('param.'), [$key => '', 'page' => ''])), 'name' => '全部', 'on' => (!isset($params[$key]) || $params[$key] == '' ? 1 : 0) ] ]; foreach ($param as $k => $v) { //if (is_array($v)) $v = $v['name']; $option[$k] = [ 'url' => url($url, array_merge(input('param.'), [$key => $k, 'page' => ''])), 'name' => is_array($v) ? $v['name'] : $v, 'on' => (isset($params[$key]) && $params[$key] == $k ? 1 : 0) ]; if (is_array($v)) $option[$k] = array_merge($option[$k], $v); if ($option[$k]['on'] == 1) $rs['selected'][$key] = ['name' => $name, 'value' => is_array($v) ? $v['name'] : $v, 'url' => $option['all']['url']]; } $rs[$key] = ['name' => $name, 'value' => empty($rs['selected'][$key]['value']) ? $name : $rs['selected'][$key]['value'], 'option' => $option]; } return $rs; } /** * 排序 * @param array $ops * @return array|void */ protected function init_orders($ops = []) { if (empty($ops)) return; $params = input('param.'); $url = self::$sys['module'] . '/' . self::$sys['controller'] . '/' . self::$sys['action']; $option = [ 'default' => [ 'url' => url($url, array_merge($params, ['order' => ''])), 'name' => '默认排序', 'on' => (!isset($params['order']) || $params['order'] == '' ? 1 : 0) ] ]; foreach ($ops as $k => $v) { $option[$k] = [ 'url' => url($url, array_merge($params, ['order' => $k])), 'name' => $v, 'on' => (isset($params['order']) && $params['order'] == $k ? 1 : 0) ]; if ($option[$k]['on']) $value = $option[$k]['name']; } $option['select'] = ['name' => empty($value) ? $option['default']['name'] : $value]; return $option; } /** * 模块设置 */ public function setting($cache_id = '') { if (self::$sys['controller'] != 'admin') return; if (!$cache_id) $cache_id = self::$sys['module'] . '_setting'; if (request()->isPost()) { $data = input('post.'); if (isset($data['keywords']) && \is_array($data['keywords'])) $data['keywords'] = join(',', $data['keywords']); if (isset($data['onlyarea']) && \is_array($data['onlyarea'])) $data['onlyarea'] = join(',', $data['onlyarea']); if (!empty($data)) { $where = ['id' => $cache_id]; $data = ['value' => json_encode($data), 'update_time' => time()]; if (db('setting')->where($where)->count()) { db('setting')->where($where)->update($data); } else { $data['id'] = $cache_id; db('setting')->insert($data); } $this->load_setting($cache_id, 1); } return json(['code' => 1, 'msg' => '模块设置已更新']); } else { $data = $this->load_setting($cache_id); return json(['code' => 1, 'data' => [ $cache_id => $data ]]); } } /** * @param string $cache_id * 设置缓存数据 */ public function load_setting($cache_id = '', $refresh = 0) { if (!$cache_id) return ''; if ($refresh) cache($cache_id, null); $data = cache($cache_id); if (empty($data)) { $data = \think\Db::name('setting')->where('id', $cache_id)->find(); if (!empty($data)) { $data = json_decode($data['value'], 1); cache($cache_id, $data); } else { $data = ''; } } return $data; } /** * 空方法 * @param $name */ public function _empty($name) { if (in_array($name, ['add', 'edit'])) { return $this->form(input('param.id'), $name); } } function check_token() { $param = input('param.'); if (!empty($param['attr'])) { if (is_string($param['attr'])) $param['attr'] = json_decode($param['attr'], 1); if (!empty($param['attr']['token'])) { $token = $param['attr']['token']; if (!empty(cache($token))) { session('user', cache($token)); } else { die(json_encode(['code' => 1000, 'msg' => '请登录'])); } } } } }