AdminBaseController.php 9.1 KB
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use think\Db;

class AdminBaseController extends BaseController
{

    public function _initialize()
    {
        // 监听admin_init
        hook('admin_init');
        parent::_initialize();
        $session_admin_id = session('ADMIN_ID');
        if (!empty($session_admin_id)) {
            $user = Db::name('user')->where(['id' => $session_admin_id])->find();

            if (!$this->checkAccess($session_admin_id)) {
                $this->error("您没有访问权限!");
            }
            $this->assign("admin", $user);
        } else {
            if ($this->request->isPost()) {
                $this->error("您还没有登录!", url("admin/public/login"));
            } else {
                header("Location:" . url("admin/public/login"));
                exit();
            }
        }
        $siteInfo = cmf_get_site_info();
        $this->assign('site_info', $siteInfo);
    }

    public function _initializeView()
    {
        $cmfAdminThemePath    = config('cmf_admin_theme_path');
        $cmfAdminDefaultTheme = config('cmf_admin_default_theme');

        $themePath = "{$cmfAdminThemePath}{$cmfAdminDefaultTheme}";

        $root = cmf_get_root();

        //使cdn设置生效
        $cdnSettings = cmf_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$root}/{$themePath}",
                '__STATIC__'   => "{$root}/static",
                '__WEB_ROOT__' => $root
            ];
        } else {
            $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__'   => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        config('template.view_base', "$themePath/");
        config('view_replace_str', $viewReplaceStr);
    }

    /**
     * 初始化后台菜单
     */
    public function initMenu()
    {
    }

    /**
     *  检查后台用户访问权限
     * @param int $userId 后台用户id
     * @return boolean 检查通过返回true
     */
    private function checkAccess($userId)
    {
        // 如果用户id是1,则无需判断
        if ($userId == 1) {
            return true;
        }

        $module     = $this->request->module();
        $controller = $this->request->controller();
        $action     = $this->request->action();
        $rule       = $module . $controller . $action;

        $notRequire = ["adminIndexindex", "adminMainindex"];
        if (!in_array($rule, $notRequire)) {
            return cmf_auth_check($userId);
        } else {
            return true;
        }
    }

    /**
     * 关键字,日期查询
     * Author:xieJie
     * @param $param 所接收数据
     * @param $date 日期(如 h.create_time)
     * @param $keywords 关键词(如 h.title 或者 h.title|h.name)
     * @param $cate_id 分类(如 h.cate_id)
     * @return array
     */
    public function search($param,$date = '',$keywords = '',$cate_id='')
    {
        $map = [];
        $start_date = isset($param['start_time'])?strtotime($param['start_time']):'';
        $end_date = isset($param['end_time'])?strtotime($param['end_time']):'';
        if($start_date and $end_date){
            $map[$date] = ['between',[$start_date,$end_date]];
            $this->assign('start_time',$param['start_time']);
            $this->assign('end_time',$param['end_time']);
        }
        if($keyword = isset($param['keyword'])?$param['keyword']:''){
            $map[$keywords] = ['like',"%$keyword%"];
            $this->assign('keyword',$keyword);
        }
        if(isset($param['cate_id']) and !empty($param['cate_id'])){
            $map[$cate_id] = $param['cate_id'];
            $this->assign('cate_id',$param['cate_id']);
        }else{
            $this->assign('cate_id','');
        }
        return $map;
    }

    /**
     * 单个/批量删除
     * @param $model 要删除的模型
     * @return bool
     */
    public function del($model)
    {
        $param = $this->request->param();
        if(isset($param['id'])){
            /*单个删除*/
            $res = $model->where('id',$param['id'])->delete();
        }elseif(isset($param['ids'])){
            /*批量删除*/
            $res = $model->where('id','in',$param['ids'])->delete();
        }else{
            return false;
        }
        if($res){
            return true;
        }
        return false;
    }

    /**
     * 数据导出
     * @param array $title   标题行名称
     * @param array $data   导出数据
     * @param string $fileName 文件名
     * @param string $savePath 保存路径
     * @param $type   是否下载  false--保存   true--下载
     * @return string   返回文件全路径
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     * exportExcel(array('姓名','年龄'), array(array('a',21),array('b',23)), '档案', './', true);
     */
    public function exportExcel($title=array(), $data=array(), $fileName='', $savePath='./', $isDown=false){
        $obj = new \PHPExcel();
        //横向单元格标识
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

        $obj->getActiveSheet(0)->setTitle('sheet名称');   //设置sheet名称
        $_row = 1;   //设置纵向单元格标识
        if($title){
            $_cnt = count($title);
            $obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格
            $obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出:'.date('Y-m-d H:i:s'));  //设置合并后的单元格内容
            $_row++;
            $i = 0;
            foreach($title AS $v){   //设置列标题
                $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
                $i++;
            }
            $_row++;
        }

        //填写数据
        if($data){
            $i = 0;
            foreach($data AS $_v){
                $j = 0;
                foreach($_v AS $_cell){
                    $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
                    $j++;
                }
                $i++;
            }
        }

        //文件名处理
        if(!$fileName){
            $fileName = uniqid(time(),true);
        }

        $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');

        if($isDown){   //网页下载
            header('pragma:public');
            header("Content-Disposition:attachment;filename=$fileName.xls");
            $objWrite->save('php://output');exit;
        }

        $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
        $_savePath = $savePath.$_fileName.'.xlsx';
        $objWrite->save($_savePath);

        return $savePath.$fileName.'.xlsx';
    }

    /**
     * 统计查询
     * Author:xieJie
     * @param $param 所接收数据
     * @return array
     */
    public function search2($param)
    {
        $map['status'] = 1;
        if(isset($param['time']) and !empty($param['time'])){
            if($param['time'] == 7){
                $param['start_time'] = date('Y-m-d H:i',time() - 86400*7);
                $param['end_time'] = date('Y-m-d H:i',time());
                $this->assign('time',7);
            }elseif ($param['time'] == 30){
                $param['start_time'] = date('Y-m-d H:i',time() - 86400*30);
                $param['end_time'] = date('Y-m-d H:i',time());
                $this->assign('time',30);
            }else{
                return false;
            }
        }else{
            $this->assign('time','');
        }
        if(isset($param['start_time']) and !empty($param['start_time']) and isset($param['end_time']) and !empty($param['end_time'])){
            $start_date = isset($param['start_time'])?strtotime($param['start_time']):'';
            $end_date = isset($param['end_time'])?strtotime($param['end_time']):'';
            $map['create_time'] = ['between',[$start_date,$end_date]];
            $this->assign('start_time',$param['start_time']);
            $this->assign('end_time',$param['end_time']);
        }
        return $map;
    }

}