<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST, ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace admin\controller;
use \temmoku\admin;
use \temmoku\db;
use admin\public_class\cache;
class plugin extends admin
{
	public function index(){
		$plugin = db::select('*')->from(jab.'plugin')->query();
    	foreach($plugin as $row){
    		$arr[]=$row['dir'];
    	}
    	$_dir=APP_PATH.'plugin/';
    	if ( $handle  =  opendir ( $_dir )) {
			while (( $file  =  readdir ( $handle ))!== false) {
			 	if($file==='.' || $file==='..' || is_file($_dir.$file) || in_array($file,$arr)){
				    continue;
				}
				
				$r['plugin']=@include_once $_dir.$file.'/install.php';
				//+++要替换成下划线
				$r['path']=$file;
				$file=str_replace("_","+++",$file);
				$r['dir']=$file;
			    $install[]=$r ;
			}
			//关闭打开的目录
			closedir ( $handle );
		}
		$this->assign('Plugin', $plugin);
		$this->assign('install', $install);
		$this->display(tpl('plugin/index'));
	}
	
	
	public function install(){
		
		$_dir=APP_PATH.'plugin/';
		
		$data=include_once $_dir.$_GET['dir'].'/install.php';
		
		$Plugin = db::select('*')->from(jab.'plugin')->query();
	    foreach($Plugin as $row){
	    	$arr[]=$row['dir'];
	    }
    	
		if(in_array($_GET['dir'],$arr)){
			$this->err('已经安装过了,系统禁止再次安装');
		}
		//安装start 
		if($_POST['step']==='post'){
			hook_listen('plugin_install_begin');
			$test=db::select('*')->from(jab.'plugin')->where("`table` LIKE '$_POST[table]'")->row();
			if($test){
				$this->err('已经存在数据表前戳，请重新输入');
			}
			$sql_dir=$_dir.$_POST['dir'].'/data.sql';
			if(is_file($sql_dir)){
				$sql=fils_content($sql_dir);
				$sql=str_replace("temmoku_plugin_".$data['table'],jab.'plugin_'.$_POST['table'],$sql);
				$explode=sql_regular_replace($sql);
				foreach($explode AS $V){
					if(!trim($V)){
						continue;
					}
					if(!$_POST['Import']){//不倒入数据
						$is=stristr($V,'INSERT INTO');
						if($is){
							continue;
						}
					}
					db::query(trim($V));
				}
			}
			
			//将要安装的插件信息插入插件库 star
			$post_data=[
				'name'=>$_POST['name'],
				'table'=>$_POST['table'],
				'dir'=>$_POST['dir'],
				'state'=>1,
				'user_show'=>$data['user_show'],
				'is_del'=>$data['is_del'],
				'is_copy'=>$data['is_copy'],
				'initial_name'=>$data['initial_name'],
				'version'=>$data['version'],
				'update'=>$data['update']
			];
			$id = db::insert(jab.'plugin')->cols($post_data)->query();
			
			
			$path=$_dir.$_POST['dir'];
			
			//自动转移公共静态文件
			$public_dir=$path."/public/";
	    	if(is_dir($public_dir)){
				recurse_copy($public_dir,Temmoku_PATH."public/");
				delete_dir($public_dir);
			}
			
			//自动安装狗子
			$hook_dir=$path."/hook/";
			if(is_dir($hook_dir)){
				recurse_copy($hook_dir,APP_PATH."hook",'hook');
				delete_dir($hook_dir);
			}
			
			//将命名空间进行替换
		    recurse_replace('plugin\\\\'.$data['initial_name'],'plugin\\\\'.$_POST['dir'],$path);
			//移动模板目录
			move_tpl($path."/view/",$data['initial_name'],$_POST['dir']);
		    //卸载init.php文件
	    	@unlink(APP_PATH."plugin/".$_POST['dir']."/init.php");
		    cache::plugin_route();
			cache::hook();
			if(CACHING==true){
				define('CACHING_ALLCACHE',true);
				\temmoku\vendor\think\cache::rm('conf_file');
				\temmoku\vendor\think\cache::rm('_config');
			}
			hook_listen('plugin_install_end',['dir'=>$_POST['dir']]);
			$this->Success('安装成功','/admin/plugin/index');
		}
		//安装end
		$this->assign('data', $data);
		$this->display(tpl('plugin/install'));
	}
	
	/*是否在前台会员中心显示*/
	public function user_show(){
		$id=intval($_POST['id']);
		db::update(jab.'plugin')->cols(['user_show'=>$_POST['user_show']])->where('id='.$id)->query();
		cache::plugin_route();
		echo json_encode(['code'=>'0','text'=>'操作成功']);
	}
	/*改变开启关闭状态*/
	public function state(){
		$id=intval($_POST['id']);
		db::update(jab.'plugin')->cols(['state'=>$_POST['state']])->where('id='.$id)->query();
		cache::plugin_route();
		echo json_encode(['code'=>'0','text'=>'操作成功']);
	}
	
	public function edit(){
		$id=intval($_POST['id']);
		$data=db::select('*')->from(jab.'plugin')->where('id='.$id)->row();
		if($id){
			if('name'===$_POST['step']){
				db::update(jab.'plugin')->cols(['name'=>$_POST['value']])->where('id='.$id)->query();
			}
		}
		cache::plugin_route();
		echo json_encode(['code'=>'1','text'=>'操作成功','value'=>$_POST['value']]);
	}
	public function del(){
		if($_GET['id']){
			$data=db::select('*')->from(jab.'plugin')->where('id='.$_GET['id'])->row();
			if(!$data){
				$this->err('不存在的插件');
			}
			if($data['is_del']=='1'){
				$this->err('本插件不允许删除');
			}
			hook_listen('plugin_del_begin',['data'=>$data]);
			//获取所有表
			$table=db::query("SHOW TABLE STATUS");
			foreach($table as $row){
				//进行正则匹配。不能胡乱删除
				$regular='/'.jab.'plugin_'.$data['table'].'/';
				preg_match_all($regular, $row['Name'], $matches);
				if($matches){
					if($matches[0]){
						$sql="DROP TABLE ".$row['Name'];
						db::query($sql);
					}
				}
			}
			//删除插件的信息
			db::delete(jab.'plugin')->where('id='.$data['id'])->query();
			cache::plugin_route();
			hook_listen('plugin_del_end',['data'=>$data]);
			$this->success('插件卸载成功');
		}elseif($_GET['step']==='uninstall'){
			hook_listen('plugin_uninstall_begin');
			if(!$_GET['dir']){
				$this->err('缺少必要参数');
			}
			$data=db::select('*')->from(jab.'plugin')->where("dir LIKE '$_GET[dir]'")->row();
			if($_data){
				$this->err('已经安装的插件不允许使用本方法卸载');
			}
			$dir=APP_PATH_PLUG.$_GET['dir'];
			
			if(strripos(realpath($dir),APP_PATH_PLUG) ===false){
				$this->err('要删除的目录不正确');
			}
			
			if(!is_dir($dir)){
				$this->err('要删除的目录不存在');
			}
			if(IS_WIN=='0' && function_exists('fileperms') ){
				if(function_exists('chomd')){
					chomd($dir,'0777');
				}
				$fileperms= substr ( sprintf ( '%o' ,  fileperms ( $dir )), - 4 );
				if($fileperms < '0755'){
					$this->err('权限不足，无法删除,可以手动删除，或者把文件夹权限设置为>=0777');
				}
			}
			//删除插件模板
			del_tpl($_GET['dir']);
			//删除插件文件
			delete_dir($dir);
			if(CACHING==true){
				define('CACHING_ALLCACHE',true);
				\temmoku\vendor\think\cache::rm('conf_file');
				\temmoku\vendor\think\cache::rm('_config');
			}
			hook_listen('plugin_uninstall_end');
			$this->success('插件删除成功');
		}
		
	}
	public function copy(){
		$data=db::select('*')->from(jab.'plugin')->where('id='.$_GET['id'])->row();
		if(!$data){
			$this->err('不存在的数据');
		}
		if($_POST['step']==='post'){
			hook_listen('plugin_copy_begin');
			$_POST['dir']=strtolower($_POST['dir']);
			$_POST['table']=strtolower($_POST['table']);
			if($_POST['dir']==='new'){
				$this->err('不允许的目录，如果非要此目录，请进行二次开发');
			}
			if(!$_POST['dir']){
				$this->err('必须输入文件夹名称');
			}
			if(!$_POST['table']){
				$this->err('必须输入数据表前戳');
			}
			if(!$_POST['name']){
				$this->err('必须输入模块名称');
			}
			if(!preg_match ("/^[a-z]/i", $_POST['dir'])){
				 $this->err('文件夹名称必须是字母开头');
			}
			//新的位置
			$new_path=APP_PATH.'plugin/'.$_POST['dir'];
			if(is_dir($new_path)){
				$this->err('文件夹已经存在，请重新输入');
			}
			$test=db::select('*')->from(jab.'plugin')->where("`table` LIKE '$_POST[tabel]'")->row();
			if($test){
				$this->err('已经存在数据表前戳，请重新输入');
			}
			//老位置
			$old_path=APP_PATH.'plugin/'.$data['dir'];
			//复制文件
			recurse_copy($old_path,$new_path);
			//将要复制的模块信息插入模块库
			$post_data=[
					'name'=>$_POST['name'],
					'table'=>$_POST['table'],
					'dir'=>$_POST['dir'],
					'state'=>1,
					'user_show'=>$data['user_show'],
					'is_del'=>$data['is_del'],
					'is_copy'=>$data['is_copy'],
					'initial_name'=>$data['initial_name'],
					'version'=>$data['version'],
					'update'=>$data['update']
				];
			$insert_id = db::insert(jab.'plugin')->cols($post_data)->query();
			//获取所有表
			$table=db::query("SHOW TABLE STATUS");
			$data['table']=strtolower($data['table']);
			foreach($table as $row){
				$regular='/'.jab.'plugin_'.$data['table'].'/';
				preg_match_all($regular, $row['Name'], $matches);
				if($matches){
					if($matches[0]){
						$_search  =jab.'plugin_'.$data['table'];
						$_replace =jab.'plugin_'.$_POST['table'];
						$old_table=$row['Name'];
						$new_table = str_replace($_search,$_replace,$row['Name']);
						//不复制表内容，需要将创建的自定义模型剔除
						$Delete=[];
						if('-1'===$_POST['is_table_content']){
							//正则匹配老表的模型表,然后进行剔除
							$regular='/'.jab.'plugin_'.$data['table'].'content_[0-9]+/';
							preg_match_all($regular, $row['Name'], $_matches);
							foreach($_matches as $t){
								if(!empty($t)){
									$Delete=$t;
								}
							}
						}
						if(!in_array($old_table,$Delete)){
							$sql="CREATE TABLE $new_table LIKE $old_table ";
							db::query($sql);
						}
						//复制表的内容
						if('1'===$_POST['is_table_content']){
							$sql1="INSERT INTO $new_table SELECT * FROM $old_table ";
							db::query($sql1);
						}
					}
				}
			}
			//将命名空间进行替换
		    recurse_replace('plugin\\\\'.$data['dir'],'plugin\\\\'.$_POST['dir'],$new_path);
			//复制模板
			copy_tpl($data['dir'],$_POST['dir']);
		    //卸载init.php文件
	    	@unlink(APP_PATH."plugin/".$_POST['dir']."/init.php");
		    cache::plugin_route();
			hook_listen('plugin_copy_end');
			$this->Success('插件复制成功','/admin/plugin/index');
		}
		$this->assign('id', $data['id']);
		$this->assign('data', $data);
		$this->display(tpl('plugin/copy'));
	}
	
}
?>