<?php

// +----------------------------------------------------------------------
// | JiZhiCMS { 极致CMS，给您极致的建站体验 }  
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2099 http://www.jizhicms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 留恋风 <2581047041@qq.com>
// +----------------------------------------------------------------------
// | Date：2022/02/10
// +----------------------------------------------------------------------

namespace A\exts;

use FrPHP\lib\Controller;
class PluginsController extends Controller {
	
	private $tables = array();
	private $handler;
	private $config = array(
	  'host' => 'localhost',
	  'port' => 3306,
	  'user' => 'root',
	  'password' => 'root',
	  'database' => 'test',
	  'charset' => 'utf-8',
	  'target' => ''
	 );
	private $limit = 300;//每个备份文件存储的sql条数
	//自动执行
	public function _init(){
		/**
			继承系统默认配置
		
		**/
		
		//检查当前账户是否合乎操作
		if(!isset($_SESSION['admin']) || $_SESSION['admin']['id']==0){
			Redirect(U('Login/index'));
			
		}
 
	    if($_SESSION['admin']['isadmin']!=1){
			if(strpos($_SESSION['admin']['paction'],','.APP_CONTROLLER.',')!==false){
			   
			}else{
				$action = APP_CONTROLLER.'/'.APP_ACTION;
				if(strpos($_SESSION['admin']['paction'],','.$action.',')===false){
				   $ac = M('Ruler')->find(array('fc'=>$action));
				   if($this->frparam('ajax')){
					   
					   JsonReturn(['code'=>1,'msg'=>'您没有【'.$ac['name'].'】的权限！','url'=>U('Index/index')]);
				   }
				   Error('您没有【'.$ac['name'].'】的权限！',U('Index/index'));
				}
			}
		   
		  	
		}
	  	
	    $webconf = webConf();
	    $this->webconf = $webconf;
	    $customconf = get_custom();
	    $this->customconf = $customconf;
		
		//插件模板页目录
		
		$this->tpl = '@'.dirname(__FILE__).'/tpl/';
		
		/**
			在下面添加自定义操作
		**/
		
		
	}
	
	//执行SQL语句在此处处理,或者移动文件也可以在此处理
	public  function install(){
		
        M('sysconfig')->update(['field' => 'web_version'], ['data' => '1.9.x']);
		//更新配置
		setCache('webconfig',null);
		setCache('customconfig',null);

		$this->JZ_mysql();
		return true;
		
	}
	
	//mysql版本
	private function JZ_mysql(){
		set_time_limit(0);
		ignore_user_abort(true);
        //备份数据库
        $this->JZ_backup();

		//处理数据库
		 if(!M('sysconfig')->find(['field'=>'classtypemaxlevel'])){
            M('sysconfig')->add(['field'=>'classtypemaxlevel','title'=>'栏目全局递归','tip'=>'默认开启，栏目超过20个，请关闭此选项，有一定程度提升访问速度！','type'=>6,'data'=>0,'typeid'=>2,'config'=>'开启=1,关闭=0','orders'=>1,'sys'=>1]);
        }
		$sql = '';
        $fields = $this->getTableFields('recycle');
        if(!in_array('title',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."recycle ADD title varchar(255) default NULL COMMENT '标记'; ";
        }
        $fields = $this->getTableFields('tags');
        if(!in_array('tids',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."tags ADD tids varchar(500) default NULL COMMENT '相关栏目'; ";
        }
        if($sql){
            M()->runSql($sql);
        }
		

		$sql = '';
        if(!M('fields')->find(['molds'=>'message','field'=>'title'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('title', 'message', '标题', NULL, 1, ',4,', '255', NULL, 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'message','field'=>'user'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('user', 'message', '用户昵称', NULL, 1, ',4,', '255', NULL, 2, 0, 1, 0, 1, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'message','field'=>'tid'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('tid', 'message', '相关栏目', NULL, 13, ',4,', '11', '2,classname', 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'message','field'=>'tel'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('tel', 'message', '联系电话', NULL, 1, ',4,', '20', NULL, 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'message','field'=>'ip'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('ip', 'message', '留言IP', NULL, 1, ',4,', '50', NULL, 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'message','field'=>'body'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('body', 'message', '留言内容', NULL, 3, ',4,', NULL, NULL, 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'message','field'=>'isshow'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('isshow', 'message', '是否审核', NULL, 7, ',4,', '1', '未审核=0,已审核=1', 2, 0, 1, 1, 1, 1, NULL, '0', 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'message','field'=>'addtime'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('addtime', 'message', '提交时间', NULL, 11, ',4,', '11', NULL, 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        //处理会员模块
        if(!M('fields')->find(['molds'=>'member','field'=>'username'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('username', 'member', '用户昵称', NULL, 1, ',0,', '255', NULL, 2, 1, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'openid'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('openid', 'member', '微信OPENID', NULL, 1, ',0,', '255', NULL, 2, 0, 1, 1, 0, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'sex'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('sex', 'member', '性别', NULL, 12, ',0,', '2', '男=1,女=2,未知=0', 2, 0, 1, 1, 1, 1, NULL, '0', 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'gid'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('gid', 'member', '会员分组', NULL, 13, ',0,', '11', '6,name', 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'litpic'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('litpic', 'member', '会员头像', NULL, 5, ',0,', '255', NULL, 2, 0, 1, 1, 0, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'tel'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('tel', 'member', '电话号码', NULL, 1, ',0,', '12', NULL, 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'jifen'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('jifen', 'member', '积分', NULL, 14, ',0,', '10,2', NULL, 2, 0, 1, 1, 0, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'money'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('money', 'member', '金币', NULL, 14, ',0,', '10,2', NULL, 2, 0, 1, 1, 0, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'email'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('email', 'member', '邮箱', NULL, 1, ',0,', '255', NULL, 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'province'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('province', 'member', '省份', NULL, 1, ',0,', '50', NULL, 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'city'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('city', 'member', '城市', NULL, 1, ',0,', '50', NULL, 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'address'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('address', 'member', '详细地址', NULL, 1, ',0,', '255', NULL, 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'regtime'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('regtime', 'member', '注册时间', NULL, 11, ',0,', '11', NULL, 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'logintime'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('logintime', 'member', '最近登录', NULL, 11, ',0,', '11', NULL, 2, 0, 1, 1, 1, 1, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'signature'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('signature', 'member', '个性签名', NULL, 1, ',0,', '255', NULL, 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'birthday'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('birthday', 'member', '生日', NULL, 1, ',0,', '50', NULL, 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'pid'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('pid', 'member', '推荐人', NULL, 13, ',0,', '11', '3,username', 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);";
        }
        if(!M('fields')->find(['molds'=>'member','field'=>'isshow'])){
            $sql.="INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('isshow', 'member', '状态', '封禁后不能登录', 7, ',0,', '2', '正常=1,封禁=0', 2, 0, 1, 1, 1, 1, NULL, '1', 1, 0, 0, NULL, 1);";
        }
        if($sql){
            M()->runSql($sql);
        }
		
		//检查表是否存在
		$tables = $this->getTableData();
		if(!in_array(DB_PREFIX.'ctype',$tables)){
			$sql = "CREATE TABLE `".DB_PREFIX."ctype` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) DEFAULT NULL COMMENT '配置栏名称',
`action` varchar(255) DEFAULT NULL COMMENT '配置标识，用于权限控制',
`sys` tinyint(1) DEFAULT 0 COMMENT '系统配置，1是0否',
`isopen` tinyint(1) DEFAULT 1 COMMENT '是否启用，1启用0关闭',
PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;";
			M()->runSql($sql);
		}
		//检查字段是否存在
        $fields = $this->getTableFields('ctype');
        if(!in_array('sys',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."ctype ADD sys tinyint(1) DEFAULT 0;";
            M()->runSql($sql);
            M('ctype')->update(['sys'=>0],['sys'=>1]);
        }
        if(!in_array('isopen',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."ctype ADD isopen tinyint(1) DEFAULT 1;";
            M()->runSql($sql);
        }
        
        //更新会员字段前台显示问题
        $fields = ['openid','gid','jifen','money','regtime','logintime','pid'];
        foreach ($fields as $v){
            M('fields')->update(['molds'=>'member','field'=>$v],['ishome'=>0]);
        }
        //更新权限问题
        $rulers = ['Sys/base'=>'Sys/ctype/type/base','Sys/jifenset'=>'Sys/ctype/type/jifenset','Sys/high-level'=>'Sys/ctype/type/high-level','Sys/email-order'=>'Sys/ctype/type/email-order','Sys/searchconfig'=>'Sys/ctype/type/searchconfig','Sys/wechatbind'=>'Sys/ctype/type/wechatbind','Sys/payconfig'=>'Sys/ctype/type/payconfig'];
        foreach ($rulers as $k=>$v){
            M('ruler')->update(['fc'=>$k],['fc'=>$v,'isdesktop'=>1]);
        }
        $grouplist = M('level_group')->findAll();
        $r1 = ['Sys/base','Sys/jifenset','Sys/high-level','Sys/email-order','Sys/searchconfig','Sys/wechatbind','Sys/payconfig'];
        $r2 = ['Sys/ctype/type/base','Sys/ctype/type/jifenset','Sys/ctype/type/high-level','Sys/ctype/type/email-order','Sys/ctype/type/searchconfig','Sys/ctype/type/wechatbind','Sys/ctype/type/payconfig'];
        foreach ($grouplist as $v){
            $paction = str_replace($r1,$r2,$v['paction']);
            M('level_group')->update(['id'=>$v['id']],['paction'=>$paction]);
        }
        //增加权限
        if(!M('ruler')->find(['fc'=>'Sys/systype'])){
            $sql="INSERT INTO `".DB_PREFIX."ruler` (`name`,`fc`,`pid`,`isdesktop`,`sys`) VALUES ('配置栏目','Sys/systype','39',1,'1');
INSERT INTO `".DB_PREFIX."ruler` (`name`,`fc`,`pid`,`isdesktop`,`sys`) VALUES ('设置配置状态','Sys/systypestatus','39',0,'1');
INSERT INTO `".DB_PREFIX."ruler` (`name`,`fc`,`pid`,`isdesktop`,`sys`) VALUES ('修改配置分组','Sys/editctype','39',0,'1');
INSERT INTO `".DB_PREFIX."ruler` (`name`,`fc`,`pid`,`isdesktop`,`sys`) VALUES ('新增配置分组','Sys/addctype','39',0,'1');
INSERT INTO `".DB_PREFIX."ruler` (`name`,`fc`,`pid`,`isdesktop`,`sys`) VALUES ('全局配置','Sys/ctype','39',0,'1');
INSERT INTO `".DB_PREFIX."ruler` (`name`,`fc`,`pid`,`isdesktop`,`sys`) VALUES ('修改配置字段','Sys/setfield','39',0,'1');";
            M()->runSql($sql);
        }
		
		//检查字段是否存在
        $fields = $this->getTableFields('recycle');
        if(!in_array('title',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."recycle ADD title varchar(255) DEFAULT NULL;";
            M()->runSql($sql);
        }
        //更新系统配置分类
        M('sysconfig')->update(['type'=>9],['type'=>8]);

		if(!M('fields')->find(['molds'=>'message','field'=>'reply'])){
            M()->runSql("INSERT INTO `".DB_PREFIX."fields` (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('reply', 'message', '回复留言', NULL, 3, ',4,', NULL, NULL, 2, 0, 1, 1, 0, 0, NULL, NULL, 1, 0, 0, NULL, 1);");
        }
        if(!M('sysconfig')->find(['field'=>'hidetitleonliy'])){
            M('sysconfig')->add(['field'=>'hidetitleonliy','title'=>'字段重复检测','tip'=>'将【模块标识-检测字段】填写进去，用|进行分割，将会进行标题重复检测。如：article-title|product-title','type'=>2,'data'=>'article-title|product-title','typeid'=>2,'orders'=>0,'sys'=>1]);
        }
        M('sysconfig')->update(['field'=>'isajax'],['type'=>6,'data'=>0,'typeid'=>2,'config'=>'开启=1,关闭=0']);
        M('sysconfig')->update(['field'=>'invite_award_open'],['type'=>6,'data'=>0,'typeid'=>7,'config'=>'开启=1,关闭=0']);
        M('sysconfig')->update(['field'=>'invite_type'],['type'=>6,'typeid'=>7,'config'=>'积分=jifen,金币=money']);
        M('sysconfig')->update(['field'=>'invite_award'],['type'=>2,'typeid'=>7]);

		$sql = '';
        if(!M('sysconfig')->find(['field'=>'onlyuserupload'])){
            $sql .= "INSERT INTO ".DB_PREFIX."sysconfig (`field`,`title`,`tip`,`type`,`data`,`typeid`,`config`,`orders`,`sys`) VALUES ('onlyuserupload','会员上传限制','开启后，仅会员才可以上传！受会员上传大小限制！','6','1','2','开启=1,关闭=0','1','1');";
        }
        if(!M('fields')->find(['field'=>'uploadsize','molds'=>'member'])){
            $sql .= "INSERT INTO ".DB_PREFIX."fields (`field`,`molds`,`fieldname`,`tips`,`fieldtype`,`tids`,`fieldlong`,`body`,`orders`,`ismust`,`isshow`,`isadmin`,`issearch`,`islist`,`format`,`vdata`,`isajax`,`listorders`,`isext`,`width`,`ishome`) VALUES ('uploadsize', 'member', '上传限制', '单位M，上传总文件大小限制，超过此大小不允许上传', 4, ',0,', '11', NULL, 2, 0, 0, 1, 0, 0, NULL, '0', 1, 0, 0, NULL, 0);";
            $sql .= "alter table ".DB_PREFIX."member add `uploadsize` int(11) not null default 50 comment '用户上传限制';";
        }
        if($sql){
            M()->runSql($sql);
        }
		$sql = '';
        if(!M('sysconfig')->find(['field'=>'cachefilenum'])){
            $sql .= "INSERT INTO `".DB_PREFIX."sysconfig` (`field`,`title`,`tip`,`type`,`data`,`typeid`,`config`,`orders`,`sys`) VALUES ('cachefilenum','缓存文件数','0表示不限制，最大不超过500','2','100','2',null,0,'1');";
        }
        //修改字符集
        $sql.="set names utf8mb4;";
        $tables = $this->getTableData();
        foreach ($tables as $v){
            $sql.="ALTER TABLE ".$v." DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
            $sql.="ALTER TABLE ".$v." CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
        }
        
        if($sql){
            M()->runSql($sql);
        }

		if(!M('ruler')->find(['fc'=>'Fields/getSelect'])){
            $sql="INSERT INTO `".DB_PREFIX."ruler` (`name`,`fc`,`pid`,`isdesktop`,`sys`) VALUES ('绑定模块数据获取','Fields/getSelect','26',0,'0');";
            M()->runSql($sql);
        }

		$sql = '';
        $fields = $this->getTableFields('message');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."message ADD molds varchar(50) default 'message'; ";
        }
        $fields = $this->getTableFields('orders');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."orders ADD molds varchar(50) default 'orders'; ";
        }
        $fields = $this->getTableFields('page');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."page ADD molds varchar(50) default 'page'; ";
        }
        $fields = $this->getTableFields('attr');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."attr ADD molds varchar(50) default 'attr'; ";
        }
        $fields = $this->getTableFields('comment');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."comment ADD molds varchar(50) default 'comment'; ";
        }
        $fields = $this->getTableFields('member');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."member ADD molds varchar(50) default 'member'; ";
        }
        $fields = $this->getTableFields('member_group');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."member_group ADD molds varchar(50) default 'member_group'; ";
        }
        if(!in_array('isshow',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."member_group ADD isshow tinyint(1) default '1'; ";
        }
        $fields = $this->getTableFields('level_group');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."level_group ADD molds varchar(50) default 'level_group'; ";
        }
        if(!in_array('isshow',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."level_group ADD isshow tinyint(1) default '1'; ";
        }
        $fields = $this->getTableFields('level');
        if(!in_array('molds',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."level ADD molds varchar(50) default 'level'; ";
        }
        if(!in_array('isshow',$fields)){
            $sql.= "ALTER TABLE ".DB_PREFIX."level ADD isshow tinyint(1) default '1'; ";
        }
        if($sql){
            M()->runSql($sql);
        }
		$sql="ALTER TABLE ".DB_PREFIX."plugins MODIFY COLUMN version decimal(10,1) not null default 0";
        M()->runSql($sql);

		// $allconfig = M('sysconfig')->findAll();
        // $newconfig = [];
        // foreach($allconfig as $vs){
        //     $newconfig[$vs['typeid']][] = $vs;
        // }
        // $where = [];
        // $values = [];
        // foreach ($newconfig as $vv){
        //     $sort = 100;
        //     foreach ($vv as $vs){
        //         $where[] = ['id'=>$vs['id']];
        //         $values[] = ['orders'=>$sort];
        //         $sort = $sort-1;
        //     }
        // }
        // if(count($where)){
        //     M('sysconfig')->updateMuti($where,$values);
        // }
		 
        if(!M('ruler')->find(['name'=>'编辑器上传','fc'=>'Uploads','pid'=>0,'isdesktop'=>0,'sys'=>1])){
            $id = M('ruler')->add(['name'=>'编辑器上传','fc'=>'Uploads','pid'=>0,'isdesktop'=>0,'sys'=>1]);
            M('ruler')->add(['name'=>'上传功能','fc'=>'Uploads/index','pid'=>$id,'isdesktop'=>0,'sys'=>1]);
        }
        if(!M('ruler')->find(['name'=>'获取子栏目','fc'=>'Classtype/getchildren'])){
           M('ruler')->add(['name'=>'获取子栏目','fc'=>'Classtype/getchildren','pid'=>41,'isdesktop'=>0,'sys'=>1]);
        }

		if(!M('sysconfig')->find(['field'=>'islocal'])){
			$sql = "INSERT INTO `".DB_PREFIX."sysconfig` (`field`,`title`,`tip`,`type`,`data`,`typeid`,`config`,`orders`,`sys`) VALUES ('islocal','是否开启图片本地化','图片本地化可以将内容的外网图片保存到服务器','6','1','2','开启=1,关闭=0','1','1')";
			M()->runSql($sql);
		}
		if(!M('sysconfig')->find(['field'=>'openredis'])){
			$sql = "INSERT INTO `".DB_PREFIX."sysconfig` (`field`,`title`,`tip`,`type`,`data`,`typeid`,`config`,`orders`,`sys`) VALUES ('openredis','是否开启Redis','开启Redis后可以使用token登录前台账户，但必须服务器安装了Redis，在config里面需要配置redis信息','6','0','2','开启=1,关闭=0','1','1')";
			M()->runSql($sql);
		}

        //检查字段是否存在
        $fields = $this->getTableFields('member');
        if(!in_array('hassendtime',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."member ADD hassendtime int(11) default 0;";
            M()->runSql($sql);
        }
		//检查字段是否存在
        $fields = $this->getTableFields('article');
        if(!in_array('updatetime',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."article ADD updatetime int(11) default '0';";
            M()->runSql($sql);
        }
        $fields = $this->getTableFields('product');
        if(!in_array('updatetime',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."product ADD updatetime int(11) default '0';";
            M()->runSql($sql);
        }
        $fields = $this->getTableFields('message');
        if(!in_array('updatetime',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."message ADD updatetime int(11) default '0';";
            M()->runSql($sql);
        }
        $fields = $this->getTableFields('links');
        if(!in_array('updatetime',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."links ADD updatetime int(11) default '0';";
            M()->runSql($sql);
        }
        $fields = $this->getTableFields('tags');
        if(!in_array('updatetime',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."tags ADD updatetime int(11) default '0';";
            M()->runSql($sql);
        }
        $fields = $this->getTableFields('classtype');
        if(!in_array('addtime',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."classtype ADD addtime int(11) default '0';";
            M()->runSql($sql);
        }
        if(!in_array('updatetime',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."classtype ADD updatetime int(11) default '0';";
            M()->runSql($sql);
        }

		if(!isset($this->webconf['schedule_table'])){
			$insert = [
				'field'=>'schedule_table',
				'title'=>'定时发布表',
				'tip'=>'带有addtime发布时间字段的表才可以使用定时发布功能,用|分隔',
				'type'=>'3',
				'data'=>'article|product',
				'typeid'=>'2',
				'config'=>'',
				'orders'=>'1',
				'sys'=>'1',
			];
			M('sysconfig')->add($insert);
		}
        if(!isset($this->webconf['upload_file_name'])){
			$insert = [
				'field'=>'upload_file_name',
				'title'=>'上传文件重命名',
				'tip'=>'上传文件后是否重命名，默认开启重命名，关闭后上传文件名不会变',
				'type'=>'6',
				'data'=>'1',
				'typeid'=>'2',
				'config'=>'开启=1,关闭=0',
				'orders'=>'1',
				'sys'=>'1',
			];
			M('sysconfig')->add($insert);
		}

		//检查字段是否存在
         $fields = $this->getTableFields('fields');
         if(!in_array('ldfield',$fields)){
             $sql = "ALTER TABLE ".DB_PREFIX."fields ADD ldfield varchar(255) default null;";
             M()->runSql($sql);
         }
        if(!in_array('linkfield',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."fields ADD linkfield varchar(255) default null;";
            M()->runSql($sql);
        }
        if(!in_array('remote',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."fields ADD remote tinyint(1) default '1';";
            M()->runSql($sql);
        }
        $fields = $this->getTableFields('message');
        if(!in_array('reply',$fields)){
            $sql = "ALTER TABLE ".DB_PREFIX."message ADD reply text default null;";
            M()->runSql($sql);
        }
        // 添加权限
        if(!M('ruler')->find(['fc'=>'Fields/getliandong'])){
            M('ruler')->add(['fc'=>'Fields/getliandong','name'=>'获取联动数据','isdesktop'=>0,'pid'=>26,'sys'=>1]);
        }

		//检查是否存在自定义模型
		$custommodels = M('molds')->findAll("id>10 or biaoshi='tags'");
		foreach($custommodels as $v){
             //检查字段是否存在
			$fields = $this->getTableFields($v['biaoshi']);
			if(!in_array('istop',$fields)){
				$sql = "ALTER TABLE ".DB_PREFIX.$v['biaoshi']." ADD istop tinyint(1) default 0;";
				M()->runSql($sql);
				//绑定字段
				$w['field'] = 'istop';
				$w['molds'] = $v['biaoshi'];
				$w['fieldname'] = JZLANG('是否置顶');
				$w['tips'] = JZLANG('置顶显示');
				$w['fieldtype'] = 7;
				$w['fieldlong'] = 1;
				$w['format'] = NULL;
				$w['body'] = JZLANG('是=1,否=0');
				$w['ismust'] = 0;
				$w['isshow'] = 1;
				$w['isadmin'] = 1;
				$w['issearch'] = 1;
				$w['islist'] = 1;
				$w['vdata'] = 0;
				M('fields')->add($w);
			}
			if(!in_array('ishot',$fields)){
				$sql = "ALTER TABLE ".DB_PREFIX.$v['biaoshi']." ADD ishot tinyint(1) default 0;";
				M()->runSql($sql);
				//绑定字段
				$w['field'] = 'ishot';
				$w['molds'] = $v['biaoshi'];
				$w['fieldname'] = JZLANG('是否热门');
				$w['tips'] = JZLANG('热门显示');
				$w['fieldtype'] = 7;
				$w['fieldlong'] = 1;
				$w['format'] = NULL;
				$w['body'] = JZLANG('是=1,否=0');
				$w['ismust'] = 0;
				$w['isshow'] = 1;
				$w['isadmin'] = 1;
				$w['issearch'] = 1;
				$w['islist'] = 1;
				$w['vdata'] = 0;
				M('fields')->add($w);
			}
			if(!in_array('istuijian',$fields)){
				$sql = "ALTER TABLE ".DB_PREFIX.$v['biaoshi']." ADD istuijian tinyint(1) default 0;";
				M()->runSql($sql);
				//绑定字段
				$w['field'] = 'istuijian';
				$w['molds'] = $v['biaoshi'];
				$w['fieldname'] = JZLANG('是否推荐');
				$w['tips'] = JZLANG('推荐显示');
				$w['fieldtype'] = 7;
				$w['fieldlong'] = 1;
				$w['format'] = NULL;
				$w['body'] = JZLANG('是=1,否=0');
				$w['ismust'] = 0;
				$w['isshow'] = 1;
				$w['isadmin'] = 1;
				$w['issearch'] = 1;
				$w['islist'] = 1;
				$w['vdata'] = 0;
				M('fields')->add($w);
			}
        }




		//文件重命名
		$isok = rename(APP_PATH.APP_HOME.'/c',APP_PATH.APP_HOME.'/c'.date("YmdHis"));
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.APP_HOME.'/c]文件夹重命名失败！'));
		}
		$isok = mkdir(APP_PATH.APP_HOME.'/c',0777);
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.APP_HOME.'/c]文件夹创建失败！'));
		}
		$dir = APP_PATH.APP_HOME.'/exts/jzupdate/file/admin/c';
        $to = APP_PATH.APP_HOME.'/c';
        $this->removeFile($dir,$to);

		$isok = rename(APP_PATH.APP_HOME.'/t/tpl',APP_PATH.APP_HOME.'/t/tpl'.date("YmdHis"));
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.APP_HOME.'/t/tpl]文件夹重命名失败！'));
		}
		$isok = mkdir(APP_PATH.APP_HOME.'/t/tpl',0777);
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.APP_HOME.'/t/tpl]文件夹创建失败！'));
		}
		$dir = APP_PATH.APP_HOME.'/exts/jzupdate/file/admin/tpl';
        $to = APP_PATH.APP_HOME.'/t/tpl';
        $this->recurse_copy($dir,$to);

		$dir = APP_PATH.APP_HOME.'/exts/jzupdate/file/conf';
        $to = APP_PATH.'Conf';
        $this->removeFile($dir,$to);

		$isok = rename(APP_PATH.'FrPHP',APP_PATH.'FrPHP'.date("YmdHis"));
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.'FrPHP]文件夹重命名失败！'));
		}
		$isok = mkdir(APP_PATH.'FrPHP',0777);
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.'FrPHP]文件夹创建失败！'));
		}
		
		$dir = APP_PATH.APP_HOME.'/exts/jzupdate/file/frphp';
        $to = APP_PATH.'FrPHP';
        $this->recurse_copy($dir,$to);

		$isok = rename(APP_PATH.'Home/c',APP_PATH.'Home/c'.date("YmdHis"));
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.'Home/c]文件夹重命名失败！'));
		}
		$isok = mkdir(APP_PATH.'Home/c',0777);
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.'Home/c]文件夹创建失败！'));
		}
		$dir = APP_PATH.APP_HOME.'/exts/jzupdate/file/home/c';
        $to = APP_PATH.'Home/c';
        $this->removeFile($dir,$to);
		
		$isok = rename(APP_PATH.'static/common',APP_PATH.'static/common'.date("YmdHis"));
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.'static/common]文件夹重命名失败！'));
		}
		$isok = mkdir(APP_PATH.'static/common',0777);
		if(!$isok){
			JsonReturn(array('code'=>1,'msg'=>'['.APP_PATH.'/static/common]文件夹创建失败！'));
		}

		$dir = APP_PATH.APP_HOME.'/exts/jzupdate/file/static/common';
        $to = APP_PATH.'static/common';
        $this->recurse_copy($dir,$to);



    
        
        
	}
	
	//批量转移文件
	private function removeFile($from,$to){
		//移动后台插件控制器
		$sourcefile = $from;
		$target = $to;
		if(is_dir($sourcefile) && is_dir($target)){
			if (false != ($handle = opendir ( $sourcefile ))) {
				
				while ( false !== ($file = readdir ( $handle )) ) {
					//去掉"“.”、“..”以及带“.xxx”后缀的文件
					if ($file != "." && $file != ".." && !is_dir($sourcefile.'/'.$file) ) {
						$fs = $sourcefile.'/'.$file;
						$ft = $target.'/'.$file;
						 //备份源文件以防更新覆盖
						copy($ft,  $sourcefile.'/back/'.$file);
						$r = $this->file2dir($fs,$ft);
						if(!$r){
							JsonReturn(array('code'=>1,'msg'=>'文件转移失败！sourcefile:'.$fs.' targetfile:'.$ft));
						}
					}
				}
				//关闭句柄
				closedir ( $handle );
			}
		
		}
				
	}
	
	// 原目录，复制到的目录
	function recurse_copy($src,$dst) {  
	 
		$dir = opendir($src);
		@mkdir($dst);
		while(false !== ( $file = readdir($dir)) ) {
			if (( $file != '.' ) && ( $file != '..' )) {
				if ( is_dir($src . '/' . $file) ) {
					$this->recurse_copy($src . '/' . $file,$dst . '/' . $file);
				}
				else {
					copy($src . '/' . $file,$dst . '/' . $file);
				}
			}
		}
		closedir($dir);
	}
	//复制文件并转移
	function file2dir($sourcefile, $filename){
		 if( !file_exists($sourcefile)){
			 return false;
		 }
		 //$filename = basename($sourcefile);
		
		 return copy($sourcefile,  $filename);
	}
	
	//返回表字段
	private function getTableFields($table){
		if(defined('DB_TYPE') && DB_TYPE=='sqlite'){
			$sql = "pragma table_info(".DB_PREFIX.$table.")";
			
			$list = M()->findSql($sql);
			$fields = [];
			foreach($list as $v){
				$fields[]=$v['name'];
				
			}
		}else{
			$sql = 'SHOW COLUMNS FROM '.DB_PREFIX.$table;
			$list = M()->findSql($sql);
			$isgo = true;
			$fields = [];
			foreach($list as $v){
				$fields[]=$v['Field'];
				
			}
		}
		
		
		
		return $fields;
		
	}
	//返回数据库表
	private function getTableData(){
		if(defined('DB_TYPE') && DB_TYPE=='sqlite'){
			$sql = "select name from sqlite_master where type='table' order by name";
		}else{
			$sql = "SHOW TABLES";
		}
		
		
		$tables = M()->findSql($sql);
		$ttable = array();
		foreach($tables as $value){
			foreach($value as $vv){
				$ttable[] = $vv;
			}
			
		}
		return $ttable;
	}
	
	//备份数据库
	private function JZ_backup(){
		$pconfig = array(
			'host' =>DB_HOST,
			'port' =>DB_PORT,
			'user' =>DB_USER,
			'password' =>DB_PASS,
			'database' =>DB_NAME
		);
		$this->config = array_merge($this->config, $pconfig);
		$this->handler = new \PDO("mysql:host=".$this->config['host'].";port={$this->config['port']};dbname={$this->config['database']}", $this->config['user'], $this->config['password']);
		$this->handler->query("set names utf8");
		
		$this->backup();
	}
	
	//卸载程序,对新增字段、表等进行删除SQL操作，或者其他操作
	public function uninstall(){
		//下面是删除test表的SQL操作
		
		return true;
	}
	
	//安装页面介绍,操作说明
	public function desc(){
		$this->display($this->tpl.'plugins-description.html');
	}
	
	//配置文件,插件相关账号密码等操作
	public  function setconf($plugins){
		//将插件赋值到模板中
		$this->plugins = $plugins;
		$this->config = json_decode($plugins['config'],1);
		
		$this->display($this->tpl.'plugins-body.html');
	}
	
	//获取插件内提交的数据处理
	public function setconfigdata($data){
		//ids
		
		$config = $data;

		M('plugins')->update(['id'=>$data['id']],['config'=>json_encode($config,JSON_UNESCAPED_UNICODE)]);
		setCache('hook',null);//清空hook缓存
		JsonReturn(['code'=>0,'msg'=>'设置成功！']);
	}
	
	 /**
	  * 备份
	  * @param array $tables
	  * @return bool
	  */
	 private function backup($tables = array())
	 {
	  //存储表定义语句的数组
	  $ddl = array();
	  //存储数据的数组
	  $data = array();
	  $this->setTables($tables);
	  if (!empty($this->tables))
	  {
	   foreach ($this->tables as $table)
	   {
		$ddl[] = $this->getDDL($table);
		$data[] = $this->getData($table);
	   }
	   //开始写入
	   $this->writeToFile($this->tables, $ddl, $data);
	  }
	  else
	  {
	   $this->error = '数据库中没有表!';
	   return false;
	  }
	 }
	 /**
	  * 设置要备份的表
	  * @param array $tables
	  */
	 private function setTables($tables = array())
	 {
	  if (!empty($tables) && is_array($tables))
	  {
	   //备份指定表
	   $this->tables = $tables;
	  }
	  else
	  {
	   //备份全部表
	   $this->tables = $this->getTables();
	  }
	 }
	 /**
	  * 查询
	  * @param string $sql
	  * @return mixed
	  */
	 private function query($sql = '')
	 {
	  $stmt = $this->handler->query($sql);
	  $stmt->setFetchMode(\PDO::FETCH_NUM);
	  $list = $stmt->fetchAll();
	  return $list;
	 }
	 /**
	  * 获取全部表
	  * @return array
	  */
	 private function getTables()
	 {
	  $sql = 'SHOW TABLES';
	  $list = $this->query($sql);
	  $tables = array();
	  foreach ($list as $value)
	  {
	   $tables[] = $value[0];
	  }
	  return $tables;
	 }
	 /**
	  * 获取表定义语句
	  * @param string $table
	  * @return mixed
	  */
	 private function getDDL($table = '')
	 {
	  $sql = "SHOW CREATE TABLE `{$table}`";
	  $ddl = $this->query($sql)[0][1] . ';';
	  return $ddl;
	 }
	 /**
	  * 获取表数据
	  * @param string $table
	  * @return mixed
	  */
	 private function getData($table = '')
	 {
	  $sql = "SHOW COLUMNS FROM `{$table}`";
	  $list = $this->query($sql);
	  //字段
	  $columns = '';
	  //需要返回的SQL
	  $query = [];
	  foreach ($list as $value)
	  {
	   $columns .= "`{$value[0]}`,";
	  }
	  $columns = substr($columns, 0, -1);
	  $data = $this->query("SELECT * FROM `{$table}`");
	  foreach ($data as $value)
	  {
	   $dataSql = '';
	   foreach ($value as $v)
	   {
		if($v==='' || $v===null){
		  $dataSql .= " NULL,";
		}else{
		  $dataSql .= "'{$v}',";
		}
		
	   }
	   $dataSql = substr($dataSql, 0, -1);
	   $query[]= "INSERT INTO `{$table}` ({$columns}) VALUES ({$dataSql});\r\n";
	  }
	  return $query;
	 }
	 /**
	  * 写入文件
	  * @param array $tables
	  * @param array $ddl
	  * @param array $data
	  */
	 private function writeToFile($tables = array(), $ddl = array(), $data = array())
    {
        $public_str = "/*\r\nMySQL Database Backup Tools\r\n";
        $public_str .= "Server:{$this->config['host']}:{$this->config['port']}\r\n";
        $public_str .= "Database:{$this->config['database']}\r\n";
        $public_str .= "Data:" . date('Y-m-d H:i:s', time()) . "\r\n*/\r\n";
        $i = 0;
        //echo '备份数据库-'.$this->config['database'].'<br />';
        $countsql = 0;//记录sql数
        $filenum = 0;//文件序号
        $backfile = $this->config['target']==''? str_replace('_','',$this->config['database']).'_'.date('Y_m_d_H_i_s').'_'.rand(100000,999999): $this->config['target'].date('YmdHis');//文件名
        $str = $public_str."SET FOREIGN_KEY_CHECKS=0;\r\n";
        foreach ($tables as $table)
        {
            //echo '备份表：'.$table.'<br>';
            $str .= "-- ----------------------------\r\n";
            $str .= "-- Table structure for {$table}\r\n";
            $str .= "-- ----------------------------\r\n";
            $str .= "DROP TABLE IF EXISTS `{$table}`;\r\n";
            $str .= $ddl[$i] . "\r\n";
            
            $i++;
            //echo '备份成功！<br/>';
            
        }
        
        $filenum = 1;
        $i = 0;
        foreach($tables as $table){
            //echo '备份表数据：'.$table.' <br>';
            $str .= "-- ----------------------------\r\n";
            $str .= "-- Records of {$table}\r\n";
            $str .= "-- ----------------------------\r\n";
            //$str .= $data[$i] . "\r\n";
            foreach ($data[$i] as $v){
                $str .= $v;
            }
            $i++;
            
            
        }
        $str = '<?php die();?>'.$str;
        $isok = file_put_contents('backup/'.$backfile.'.php', $str);
        //echo '备份成功！<br/>  备份成功!花费时间' . (microtime(true) - $this->begin) . 'ms';
        if(!$isok){
			JsonReturn(['code'=>1,'msg'=>'[ backup/'.$backfile.'.php ] 写入文件失败！']);
		}
 
    }
    
	
	
}




