<?php
//公共类
class commonMod
{

    public $model; //数据库模型对象
    public $tpl; //模板对象
    public $config; //全局配置
    static $global; //静态变量，用来实现单例模式
    public function __construct()
    {
        session_start(); //开启session
        //参数配置
        if (!isset(self::$global['config'])) {
            global $config;
            self::$global['config'] = $config;
        }
        $this->config = self::$global['config']; //配置

        //数据库模型初始化
        if (!isset(self::$global['model'])) {
            self::$global['model'] = new cpModel($this->config); //实例化数据库模型类
        }
        $this->model = self::$global['model']; //数据库模型对象
        //模板初始化
        if (!isset(self::$global['tpl'])) {
            self::$global['tpl'] = new cpTemplate($this->config); //实例化模板类
        }
        $this->tpl = self::$global['tpl']; //模板类对象

        $this->checkLogin(); //检查是否登录

        $this->autoauth(); //检查是否拥有权限与开关

        $config['PLUGIN_PATH'] = './../plugins/';
        Plugin::init('Admin', $config);

    }


    //模板变量解析
    protected function assign($name, $value)
    {
        return $this->tpl->assign($name, $value);
    }

    //模板输出
    protected function display($tpl = '')
    {
        $this->assign("model", $this->model);
        $this->assign('sys', $this->config);
        return $this->tpl->display($tpl);

    }

    //直接跳转
    protected function redirect($url)
    {
        header('location:' . $url, false, 301);
        exit;
    }

    //操作成功之后跳转,默认三秒钟跳转
    protected function success($msg, $url = null, $waitSecond = 3)
    {
        if ($url == null)
            $url = __URL__;
        $this->assign('message', $this->getlang($msg));
        $this->assign('url', $url);
        $this->assign('waitSecond', $waitSecond);
        $this->display('success');
        exit;
    }

    //内容操作成功之后跳转,默认三秒钟跳转
    protected function content_success($msg,$aid,$cid,$list='index',$add='add',$edit='edit',$waitSecond = 5)
    {
        
        $this->assign('message', $this->getlang($msg));
        $this->assign('aid', $aid);
        $this->assign('cid', $cid);
        $this->assign('list', $list);
        $this->assign('add', $add);
        $this->assign('edit', $edit);
        $this->assign('waitSecond', $waitSecond);
        $this->display('content_success');
        exit;
    }

    //栏目操作成功之后跳转,默认三秒钟跳转
    protected function class_success($msg,$cid,$list='index',$add='add',$edit='edit',$waitSecond = 5)
    {
        
        $this->assign('message', $this->getlang($msg));
        $this->assign('cid', $cid);
        $this->assign('list', $list);
        $this->assign('add', $add);
        $this->assign('edit', $edit);
        $this->assign('waitSecond', $waitSecond);
        $this->display('class_success');
        exit;
    }

    //出错之后跳转，后退到前一页
    protected function error($msg)
    {
        header("Content-type: text/html; charset=utf-8");
        $msg = "alert('".$this->getlang($msg)."');";
        echo "<script>$msg history.go(-1);</script>";
        exit;
    }

    //出错之后返回json数据
    protected function jserror($msg)
    {
        echo json_encode(array("msg" => $this->getlang($msg), "result" => '0'));
        exit;
    }

    //成功之后返回json
    protected function jssuccess($msg)
    {
        echo json_encode(array("msg" => $this->getlang($msg), "result" => '1'));
        exit;
    }

    //检查是否登录,如果还没有登录，且当前操作不是登录或者验证码生成操作，则跳到登录页面
    protected function checkLogin()
    {
        $login_spot = $this->config;
        if (empty($_SESSION[$login_spot['spot'] . 'admin_spot']) || empty($_SESSION[$login_spot['spot'] .
            'admin_uid']) || empty($_SESSION[$login_spot['spot'] . 'admin_user']) || empty($_SESSION[$login_spot['spot'] .
            'admin_gid'])) {
            //如果当前操作是登录或者验证码生成，则放行
            if ($_GET['_module'] == 'login' && in_array($_GET['_action'], array(
                'index',
                'login',
                'verify'))) {
                return false;
            }
            
            if ($_GET['_module'] == 'upload') {
                return false;
            }
            $module=substr($_GET['_module'],0,3);
            if($module=='dl_'){
                return false; //如果模块名的前三个字符为dl_那么取消对此模块的登录验证
            }
            
            //跳转到登录页面
            $this->redirect(__APP__ . '/login');
        }
        return true;
    }

    //分页 $url:基准网址，$totalRows: $listRows列表每页显示行数$rollPage 分页栏每页显示的页数
    protected function page($url, $totalRows, $listRows =20, $rollPage = 5)
    {
        $page = new page();
        return $page->show($url, $totalRows, $listRows, $rollPage);
    }



    //获取前台配置
    public function getconfig($name=null)
    {
        require (__ROOTDIR__ . '/inc/config.php'); 

        if(empty($name)){
        return $config;
        }else{
        return $config[$name];
        }
    }

    //权限自动判断
    public function autoauth()
    {
        $module=in($_GET['_module']);

        //跳过
        $module_s=array(
        "common",
        "empty",
        "extend",
        "index",
        "label",
        "login",
        "menu",
        "plus",
        "updb",
        "upload",
        "channel",
        );

        if(!in_array($module,$module_s)){

        $modelif=explode('_',$module);

        $modlist=$this->model->table('model')->select();
        foreach ($modlist as $key) {
            $mod_mark[]=$key['mark'];
        }

        if(!in_array($modelif[0],$mod_mark)){


            //插件权限判断
            $pluslist=$this->model->table('extend')->select();
            foreach ($pluslist as $key) {
            $plus_name[]=$key['PLUS_NAME'];
            }
            if(in_array($module,$plus_name)){
            //插件权限判断
            if(!$this->plussetting($module,'OPEN')){
            $this->error('该插件已关闭！');
            exit;
            }
            $condition['module']=$module;
            $info = $this->model->table('resource')->where($condition)->find();
            if(!$this->auth_if($info['id'])){
            $this->error('您无权进行操作!');
            }
            }else{
            //模块权限判断
            if(!$this->modulesetting($module,'OPEN')){
            $this->error('该模块已关闭！');
            exit;
            }

            $condition['module']=$module;
            $info = $this->model->table('resource')->where($condition)->find();
            if(!$this->auth_if($info['id'])){
            $this->error('您无权进行操作!');
            }

        }


        }else{
            //模型权限判断
            if(!$this->modelsetting($modelif[0],'OPEN')){
            $this->error('该模块已关闭！');
            exit;
        }

        }

        }

    }

    //普通权限手动验证
    public function auth($id)
    {
        if (l_auth::auth_operate($this->model, $id)) {
        } else {
            $this->error('您无权进行操作！');
            exit;
        }
    }
    //栏目权限手动验证
    public function auth_class($cid)
    {
        if (l_auth::auth_class($this->model, 10, $cid)) {
        } else {
            $this->error('您无权进行操作！');
            exit;
        }
    }
    //栏目权限验证判断
    public function auth_class_if($cid)
    {
        if (l_auth::auth_class($this->model, 10, $cid)) {
            return true;
        } else {
            return false;
        }
    }
    
    //普通权限验证判断
    public function auth_if($id)
    {
        if (l_auth::auth_operate($this->model,$id)) {
            return true;
        } else {
            return false;
        }
    }

    //内容栏目权限添加
    protected function auth_class_add($cid,$name)
    {
        $auth_data = array();
        $auth_data['pid'] = '10';
        $auth_data['cid'] = $cid;
        $auth_data['name'] = $name;
        $group_id = $this->model->table('resource')->data($auth_data)->insert(); //添加权限栏目

        $config=$this->config;
        if ($_SESSION[$config['spot'] . 'admin_uid'] == 1) {
            $group_info = $this->model->table('admin_group')->where('id=1')->find(); //查询权限列表
            $group_data = array();
            $group_data['power_value'] = $group_info['power_value'] . ',' . $group_id;
            $this->model->table('admin_group')->data($group_data)->where('id=1')->update(); //增加超级管理组权限
        } else {
            $group_condition['id'] = $_SESSION[$config['spot'] . 'admin_uid'];
            $group_info = $this->model->table('admin_group')->where($group_condition)->find(); //查询权限列表
            $group_data = array();
            $group_data['power_value'] = $group_info['power_value'] . ',' . $group_id;
            $this->model->table('admin_group')->data($group_data)->where($group_condition)->update(); //增加当前管理组权限

            $admin_group_info = $this->model->table('admin_group')->where('id=1')->find(); //查询权限列表
            $admin_group_data = array();
            $admin_group_data['power_value'] = $admin_group_info['power_value'] . ',' . $group_id;
            $this->model->table('admin_group')->data($admin_group_data)->where('id=1')->update(); //增加超级管理组权限
        }
    }
    
    //内容栏目权限修改
    protected function auth_class_edit($cid,$name)
    {
        $auth_data = array();
        $auth_data['name']=$name;
        $auth_condition = array();
        $auth_condition['cid'] = $cid;        
        $this->model->table('resource')->data($auth_data)->where($auth_condition)->update(); //修改权限栏目信息
    }
	
	//获取当前语言
    public function getlang($lang)
    {
		$getlang= Lang::getPack(__LANG__);
		if(empty($getlang[$lang])){
			return $lang;
			}else{
			return $getlang[$lang];	
			}		 
    }

    //获取语言
    public function lang()
    {
        $lang=$this->config['LANG_OPEN'];
        if($lang==1){
            return __LANG__.'/';
        }
    }

    //获取语言ID
    public function getlangid()
    {
        $condition['lang']=__LANG__;
        $info = $this->model->table('lang')->where($condition)->find();
        return $info['id']; 
    }

    
	
	//插件操作hook
    public function plus_hook($module,$action,$data=NULL)
    {
        Plugin::hook('hook_'.$module.'_'.$action,'',$data); //插件执行
    }
	
	//插件模板操作hook
    public function plus_hook_tpl($module,$action,$data=NULL)
    {
        Plugin::hook('hook_tpl_'.$module.'_'.$action,'',$data); //模板内插件执行
    }

    //模块参数读取和设置
    public function modulesetting($module,$name = '', $value = null)
    {

        $file=dirname(__file__).'/'.$module;
        $setting = empty($setting) ? require ($file. '/setting.php') : $setting;
        if (empty($name))
        {
            $condition['FILE_NAME']=$setting['FILE_NAME'];
            return $this->model->table('module')->where($condition)->find(); //返回所有配置
        } else
        {
            if (is_null($value))
            {
                $condition['FILE_NAME']=$setting['FILE_NAME'];
                $info=$this->model->table('module')->where($condition)->find();
                return isset($info[$name]) ? $info[$name] : false; //返回指定配置值
            } else
            {
                $condition['FILE_NAME']=$setting['FILE_NAME'];
                $data[$name] = $value;
                $this->model->table('module')->data($data)->where($condition)->update();
                return true; //写入配置
            }
        }
    }
	
	//模型参数读取和设置
    public function modelsetting($module,$name = '', $value = null)
    {
        $file=dirname(__file__).'/'.$module;
        $setting = empty($setting) ? require ($file. '/modsetting.php') : $setting;

        if (empty($name))
        {
            $condition['mark']=$setting['FILE_NAME'];
            return $this->model->table('model')->where($condition)->find(); //返回所有配置
        } else
        {
            if (is_null($value))
            {
                $condition['mark']=$setting['FILE_NAME'];
                $info=$this->model->table('model')->where($condition)->find();
                return isset($info[$name]) ? $info[$name] : false; //返回指定配置值
            } else
            {
                $condition['mark']=$setting['FILE_NAME'];
                $data[$name] = $value;
                $this->model->table('model')->data($data)->where($condition)->update();
                return true; //写入配置
            }
        }
    }

    //插件参数读取和设置
    public function plussetting($module,$name = '', $value = null)
    {
        $file=__ROOTDIR__.'/plugins/'.$module;
        $setting = empty($setting) ? require ($file. '/setting.php') : $setting;

        if (empty($name))
        {
            $condition['PLUS_NAME']=$setting['PLUS_NAME'];
            return $this->model->table('extend')->where($condition)->find(); //返回所有配置
        } else
        {
            if (is_null($value))
            {
                $condition['PLUS_NAME']=$setting['PLUS_NAME'];
                $info=$this->model->table('extend')->where($condition)->find();
                return isset($info[$name]) ? $info[$name] : false; //返回指定配置值
            } else
            {
                $condition['PLUS_NAME']=$setting['PLUS_NAME'];
                $data[$name] = $value;
                $this->model->table('extend')->data($data)->where($condition)->update();
                return true; //写入配置
            }
        }
    }

    //参数读取和设置
    public function plus_setting($name = '', $value = null)
    {
        $module=$_GET['_module'];
        return $this->plussetting($module,$name,$value);
    }
    //配置读取
    public function plus_configout()
    {       
        return unserialize($this->plus_setting('config'));

    }
    //配置保存
    public function plus_configin($data)
    {
        if(!empty($data)){
          $config=serialize($data); 
          return $this->plus_setting('config', $config);
        }

    }

    //执行数据库操作
    protected function _runSql($sql_array = "")
    {
        if (is_string($sql_array))
        {
            $this->model->query($sql_array);
            return true;
        }
        if (is_array($sql_array))
        {
            foreach ($sql_array as $sql)
            {
                $this->model->query($sql);
            }
            return true;
        }
        return false;
    }

}
?>