<?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 install\controller;
use temmoku\controller;
use temmoku\db;
use temmoku\lib\cookie;
use PDO;
use PDOException;
class Index extends Controller{
	public function index(){
		$lock=APP_PATH.'conf/install.lock';
		if(is_file($lock)){
			$this->err('已经安装过程序，如果需要重新安装，请删除'.$lock.'文件');
		}
		$_POST['step'] ? $_GET['step']=$_POST['step'] : $_GET['step'] ;
		
		if($_GET['step']==='1'){
			//初始化一些安装信息
			$modular="<?php return [
				'MODULE_ROTUE'=>['admin','install','user','plugin'],
				'Disable_modules'=>['conf','hook']
			]; ?>";
			write_file(APP_PATH."module_route.php",$modular);
			if (extension_loaded('mysqli')) {
			 	$mysql='<span style="color:green">已安装</span>';
			}else{
				$mysql='<span style="color:red">未安装</span>';
			}
			if(function_exists('gd_info')) {
			    $gd_info = @gd_info();
				$gd= $gd_info["GD Version"];
			}
			$this->assign('gd', $gd);
			$this->assign('Mysql_VERSION', $mysql);
			
			$app=Temmoku_PATH.'app';
			is_writable($app) ? $app_path_is_w='<span class="green">可写</span>' : $app_path_is_w='<span class="red">不可写</span>';
			is_readable($app) ? $app_path_is_r='<span class="green">可读</span>' : $app_path_is_r='<span class="red">不可读</span>';
			$this->assign('app_path_is_w', $app_path_is_w);
			$this->assign('app_path_is_r', $app_path_is_r);
			$attachment=Temmoku_PATH.'attachment';
			is_writable($attachment) ? $attachment_path_is_w='<span class="green">可写</span>' : $attachment_path_is_w='<span class="red">不可写</span>';
			is_readable($attachment) ? $attachment_path_is_r='<span class="green">可读</span>' : $attachment_path_is_r='<span class="red">不可读</span>';
			$this->assign('attachment_path_is_w', $attachment_path_is_w);
			$this->assign('attachment_path_is_r', $attachment_path_is_r);
			
			$this->assign('tmp_path_is_w', $tmp_path_is_w);
			$this->assign('tmp_path_is_r', $tmp_path_is_r);
			class_exists('pdo') ? $pdo= '开启' : $pdo='不支持';
			$this->assign('pdo', $pdo);
		}elseif($_GET['step']==='2'){
			$arr=array_merge(C('MODULE_ROTUE'),C('Disable_modules'));
			if ( $handle  =  opendir ( APP_PATH )) {
				while (( $file  =  readdir ( $handle ))!== false) {
					$r=[];
					//$file=mb_strtolower($file);
				 	if($file==='.' || $file==='..' || is_file(APP_PATH.$file) || in_array(mb_strtolower($file),$arr)){
					    continue;
					}
					$files=APP_PATH.$file.'/install.php';
					if(is_file($files)){
						$r['data']=include_once $files;
					}
					$r['dir']=$file;
				    $modular[]=$r ;
				}
				
				//关闭打开的目录
				closedir ( $handle );
			}
			$this->assign('modular', $modular);
			$_dir=APP_PATH.'plugin/';
	    	if ( $handle  =  opendir ( $_dir )) {
				while (( $file  =  readdir ( $handle ))!== false) {
					$r=[];
				 	if($file==='.' || $file==='..' || is_file($_dir.$file)){
					    continue;
					}
					$r['data']=@include_once $_dir.$file.'/install.php';
					$r['path']=$file;
					$r['dir']=$file;
				    $Plugin[]=$r ;
				}
				//关闭打开的目录
				closedir ( $handle );
			}
			$this->assign('Plugin', $Plugin);
		}elseif($_POST['step']==='3'){
			$_POST['modular'] ? $modular=implode('####',$_POST['modular']) :$modular='';
			$_POST['plugin'] ? $plugin=implode('####',$_POST['plugin']):$plugin='';
			$this->assign('modular',$modular);
			$this->assign('plugin',$plugin);
		}elseif($_POST['step']==='4'){
			//安装
		}
		
		$this->display(tpl('index'));
	}
	
	public function install(){
		$lock=APP_PATH.'conf/install.lock';
		if(is_file($lock)){
			$this->err('已经安装过程序，如果需要重新安装，请删除'.$lock.'文件');
		}
		
		if($_POST['action']=='star'){
			$dsn       = 'mysql:host='.$_POST['dbhost'].';port='.$_POST['dbport'];
	        try {
			   	$PDO= new PDO ( $dsn ,  $_POST['dbuser'] ,  $_POST['dbpassword'],array(
	                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
	            ));
			
				
	            $test_dbname='SHOW CREATE DATABASE `'.$_POST["dbname"].'`';
	            
		        if($PDO->query($test_dbname)==false){
		        	$sql = 'CREATE DATABASE `'.$_POST["dbname"].'`';
					$test=$PDO->query($sql); 
					if($PDO->query($test_dbname)==false){
						$arr=[
							'Result'=>'-1',
							'msg'=>'数据库创建失败'
						];
					}else{
						$arr=[
							'Result'=>'1',
							'msg'=>'数据库创建成功，等待写入主数据',
							'action'=>'main',
							'i'=>'0',
						];
					}
		        }else{
		        	$arr=[
							'Result'=>'1',
							'msg'=>'数据库存在，直接写入主数据',
							'action'=>'main',
							'i'=>'0'
						];
		        }
		        if($arr['Result']=='1'){
		        	
		        	$database_file=APP_PATH.'conf/database.php';
		        	$content="<?php \n";
					$content.="        	return	[\n";
					$content.="		        'dbhost'     => '".$_POST['dbhost']."',\n";
					$content.="		        'dbport'     => '".$_POST['dbport']."',\n";
					$content.="		        'dbuser'     => '".$_POST['dbuser']."',\n";
					$content.="		        'dbpassword' => '".$_POST['dbpassword']."',\n";
					$content.="		        'dbname'   => '".$_POST['dbname']."',\n";
					$content.="		        'charset'  => 'utf8',\n";
					$content.="		        'jab'  => '".$_POST['jab']."',\n";
					$content.="		    ]\n";
		        	$content.="?>";
		        	write_file($database_file,$content);
		        }
			} catch ( PDOException $e ) {
				$arr=[
						'Result'=>'-1',
						'msg'=>'数据库连接错误'
					];
			}
			echo json_encode($arr);
		}else{
			
			$dsn       = 'mysql:dbname='.$_POST["dbname"].';host='.$_POST["dbhost"].';port='.$_POST['dbport'];
			try {
			   	$PDO= new PDO ( $dsn,$_POST['dbuser'],$_POST['dbpassword'],array(
	                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
	            ));
			} catch ( PDOException $e ) {
				$arr=[
					'Result'=>'-1',
					'msg'=>'数据库连接错误'
				];
				echo json_encode($arr);
				exit;
			}
			
			if($_POST['action']=='main'){
				$sql_dir=APP_PATH.'install/conf/data.sql';
				if(is_file($sql_dir)){
					$sql=fils_content($sql_dir);
				}
				$sql=str_replace("temmoku_",$_POST['jab'],$sql);
				$explode = sql_regular_replace($sql);
				$num=COUNT($explode);
				$i=0;
				foreach($explode AS $table){
					$i++;
					if($i>$_POST['i']){
						if(strstr  ( $table ,'CREATE'  ))  {
							preg_match('/CREATE TABLE(.*?)`([^ ]*)`/', $table, $matches);
							$test=$PDO->query($table);
							$arr=[
								'Result'=>'1',
								'msg'=>'创建数据表“'.$matches[2].'”成功',
								'action'=>'main',
								'i'=>$i,
							];
							echo json_encode($arr);
							break;
						}else{
							$test=$PDO->query($table);
							
						}
					}
					if($i==$num){
						if($_POST['modular']){
							$modular=explode('####',$_POST['modular']);
							$arr=[
								'Result'=>'1',
								'msg'=>'主数据库创建完成，等待创建模块“'.$modular[0].'”数据表',
								'action'=>'module',
								'i'=>0,
								'ii'=>0
							];
						}else if($_POST['plugin']){
							$plugin=explode('####',$_POST['plugin']);
							$arr=[
								'Result'=>'1',
								'msg'=>'主数据库创建完成.不存在模块，直接创建插件“'.$plugin[0].'”数据表',
								'action'=>'plugin',
								'i'=>0,
								'ii'=>0
							];
						}else{
							$arr=[
								'Result'=>'1',
								'action'=>'setting',
								'msg'=>'数据全部创建完成，开始生成必要缓存及文件',
							];
						}
						die(json_encode($arr));
					}
				}
			}elseif($_POST['action']=='module'){
				$modular=explode('####',$_POST['modular']);
				$modular_num=count($modular);
				foreach($modular AS $key=>$value){
					if($key==$_POST['i']){
						//获取数据库信息
						$sql_dir=APP_PATH.$value.'/data.sql';
						if(is_file($sql_dir)){//存在则
							$sql=fils_content($sql_dir);
							//获取模块初始值
							$modular_install_set=APP_PATH.$value.'/install.php';
							if(is_file($modular_install_set)){
								$modular_set=include_once $modular_install_set;
							}
							//替换数据表
							$sql=str_replace("temmoku_".$modular_set['table'],$_POST['jab'].strtolower($value)."_",$sql);
							$explode = sql_regular_replace($sql);
							$sql_num=COUNT($explode);
							$ii=0;
							foreach($explode AS $table){
								$ii++;
								if($ii>$_POST['ii']){
									if(strstr  ( $table ,'CREATE'  ))  {
										preg_match('/CREATE TABLE(.*?)`([^ ]*)`/', $table, $matches);
										$test=$PDO->query($table);
										$arr=[
											'Result'=>'1',
											'msg'=>'创建数据表“'.$matches[2].'”成功',
											'action'=>'module',
											'i'=>$key,
											'ii'=>$ii
										];
										echo json_encode($arr);
										exit;
									}else{
										$test=$PDO->query($table);
									}
								}
								if($ii==$sql_num){
									//将要安装的模块信息插入模块库 star
									$post_data=[
										'name'=>$modular_set['name'],
										'table'=>strtolower($value)."_",
										'dir'=>$value,
										'state'=>1,
										'initial_name'=>$modular_set['initial_name'],
										'version'=>$modular_set['version'],
										'update'=>$modular_set['update']
									];
									db::insert($_POST['jab'].'modular')->cols($post_data)->query();
									if($modular_set['initial_name'] != $value){
										$function_flie=APP_PATH.$value.'/function.php';
										if(is_file($function_flie)){
											$fils_content=fils_content($function_flie);
											$fils_content=preg_replace( '/\\\\/' , "\\\\\\"  , $fils_content );
											$fils_content=preg_replace('/function[\s]'.$modular_set['initial_name'].'_/','function '.$value."_",$fils_content);
											write_file($function_flie,$fils_content);
										}
										//将命名空间进行替换
						       			recurse_replace($modular_set['initial_name'],$value,APP_PATH.$value);
						       		}
									
									move_tpl(APP_PATH.$value.'/view',$modular_set['initial_name'],$value);
						       		$m_jab=$_POST['jab'].strtolower($value);
									if($key+1==$modular_num){//开始执行插件安装
										if($_POST['plugin']){
											$plugin=explode('####',$_POST['plugin']);
											$arr=[
												'Result'=>'1',
												'msg'=>'模块数据表全部创建完成，等待创建插件“'.$plugin[0].'”数据表',
												'action'=>'plugin',
												'i'=>0,
												'ii'=>0
											];
										}else{
											$arr=[
												'Result'=>'1',
												'action'=>'setting',
												'msg'=>'数据全部创建完成，开始生成必要缓存及文件',
											];
										}
									}else{
										$arr=[
											'Result'=>'1',
											'msg'=>'模块“'.$modular[$key].'”数据表创建完成，等待创建“'.$modular[$key+1].'”模块数据表',
											'action'=>'module',
											'i'=>$key+1,
											'ii'=>0
										];
									}
									echo json_encode($arr);
									exit;
								}
							}
						}
					}
				}
			}elseif($_POST['action']=='plugin'){
				
				$plugin=explode('####',$_POST['plugin']);
				$plugin_num=count($plugin);
				foreach($plugin AS $key=>$value){
					if($key==$_POST['i']){
						//获取模块初始值
						$plugin_install_set=APP_PATH.'plugin/'.$value.'/install.php';
						if(is_file($plugin_install_set)){
							$plugin_set=include_once $plugin_install_set;
						}
						//获取数据库信息
						$sql_dir=APP_PATH.'plugin/'.$value.'/data.sql';
						if(is_file($sql_dir)){//存在则
							$sql=fils_content($sql_dir);
							//替换数据表
							$sql=str_replace("temmoku_plugin_".$plugin_set['table'],$_POST['jab'].'plugin_'.strtolower($value)."_",$sql);
							$explode = sql_regular_replace($sql);
							$sql_num=COUNT($explode);
							$ii=0;
							foreach($explode AS $table){
								$ii++;
								if($ii>$_POST['ii']){
									if(strstr  ( $table ,'CREATE'  ))  {
										preg_match('/CREATE TABLE(.*?)`([^ ]*)`/', $table, $matches);
										$test=$PDO->query($table);
										$arr=[
											'Result'=>'1',
											'msg'=>'创建数据表“'.$matches[2].'”成功',
											'action'=>'plugin',
											'i'=>$key,
											'ii'=>$ii
										];
										echo json_encode($arr);
										exit;
									}else{
										$test=$PDO->query($table);
									}
								}
								if($ii==$sql_num){
									//将要安装的插件信息插入插件库 star
									$post_data=[
											    'name'=>$plugin_set['name'],
											   	'table'=>$plugin_set["table"],
											    'dir'=>$value,
											    'state'=>1,
											    'user_show'=>$plugin_set['user_show'],
											    'is_del'=>$plugin_set['is_del'],
											    'is_copy'=>$plugin_set['is_copy'],
											    'initial_name'=>$plugin_set['initial_name'],
											    'version'=>$plugin_set['version'],
											    'update'=>$plugin_set['update']
									];
									db::insert(jab.'plugin')->cols($post_data)->query();
									
									if($value != $plugin_set['initial_name']){
										//将命名空间进行替换
										recurse_replace('plugin\\\\'.$plugin_set['initial_name'],'plugin\\\\'.$value,APP_PATH_PLUG.$value);
									}
									move_tpl(APP_PATH_PLUG.$value.'/view',$plugin_set['initial_name'],$value);
									
									if($key+1==$plugin_num){//开始执行插件安装
										$arr=[
											'Result'=>'1',
											'action'=>'setting',
											'msg'=>'数据全部创建完成，开始生成必要缓存及文件',
										];
										
									}else{
										$arr=[
											'Result'=>'1',
											'msg'=>'插件“'.$plugin[$key].'”数据表创建完成，等待创建插件“'.$plugin[$key+1].'”数据表',
											'action'=>'plugin',
											'i'=>$key+1,
											'ii'=>0
										];
									}
									echo json_encode($arr);
									exit;
								}
							}
						}else{
							//将要安装的插件信息插入插件库 star
							$post_data=[
								'name'=>$plugin_set['name'],
								'table'=>$plugin_set["table"],
								'dir'=>$value,
								'state'=>1,
								'user_show'=>$plugin_set['user_show'],
								'is_del'=>$plugin_set['is_del'],
								'is_copy'=>$plugin_set['is_copy'],
								'initial_name'=>$plugin_set['initial_name'],
							  	'version'=>$plugin_set['version'],
							   'update'=>$plugin_set['update']
							];
							db::insert(jab.'plugin')->cols($post_data)->query();
							if($key+1==$plugin_num){//开始执行插件安装
								$arr=[
									'Result'=>'1',
									'action'=>'setting',
									'msg'=>'数据全部创建完成，开始生成必要缓存及文件',
								];
							}else{
								$arr=[
									'Result'=>'1',
									'msg'=>'插件“'.$plugin[$key].'”数据表创建完成，等待创建插件“'.$plugin[$key+1].'”数据表',
									'action'=>'plugin',
									'i'=>$key+1,
									'ii'=>0
								];
							}
							echo json_encode($arr);
							exit;
						}
					}
				}
			}elseif($_POST['action']=='setting'){
				$setting=[
					'webname'=>$_POST['webname'],
					'weburl'=>$_POST['weburl'],
					'index'=>$_POST['index']
				];
				$parse_url=parse_url ( $_POST['weburl']);
				$parse_url['host'] ? $setting['weburl']=$parse_url['host'] : $setting['weburl']=$parse_url['path'];
				$setting['weburl']=trim(trim($setting['weburl'],'/'));
				$setting['md5']=_rand(32,3);
				foreach($setting AS $key=>$name){
					$one=db::select('*')->from(jab."setting")->where("s_key LIKE '$key' ")->row();
					if($one){
						db::update(jab."setting")->cols(array('s_name'))->where("s_key LIKE '$key'")->bindValue('s_name', "$name")->query();
					}else{
						db::insert(jab."setting")->cols(array('s_key'=>"$key",'s_name'=>"$name"))->query();
					}
				}
				$rand=_rand(4);
				db::insert(jab."user")->cols(['username'=>$_POST['username'],'password'=>md5(md5($_POST['password']).$rand),'groupid'=>'3','rand'=>$rand])->query();
				

		    	//登入后台
		    	$data = (new \admin\model\index)->Login($_POST['username'],$_POST['password']);
		    	$ORDINARY_ADMIN=encode($data['UserDB']['uid'].' '.$data['UserDB']['password'],C('ONLINEIP'));
				//写入浏览器缓存
				cookie::set('ORDINARY_ADMIN',$ORDINARY_ADMIN);
				$lock=APP_PATH.'conf/install.lock';
				write_file($lock,"");
				c('md5',$setting['md5']);
				//先更新核心缓存
		    	\admin\public_class\cache::all();
		    	//更新模块缓存
		    	$modular=db::select('*')->from(jab.'modular')->query();
		    	if($modular){
		    		foreach($modular AS $key=>$row){
			    		$modular_file= APP_PATH.$row['dir']."/public_class/cache.php";
			    		if(is_file($modular_file)){
			    			//加载此文件。
			    			include_once $modular_file;
			    			//执行相关操作
			    			$controller=$row['dir']."\public_class\cache";
			    			$controller::run($row);
			    		}
			    	}
		    	}
		    	//更新插件缓存
		    	$plugin=db::select('*')->from(jab.'plugin')->query();
		    	if($plugin){
		    		foreach($plugin AS $key=>$row){
			    		$file= APP_PATH.'plugin/'.$row['dir']."/public_class/cache.php";
			    		if(is_file($file)){
			    			//加载此文件。
			    			include_once $file;
			    			//执行相关操作
			    			$controller='plugin\\'.$row['dir']."\public_class\cache";
			    			$controller::run($row);
			    		}
			    	}
		    	}
				$arr=[
						'Result'=>'ok',
						'msg'=>'所有功能安装完毕',
					];
				exit(json_encode($arr));
			}
		}
	}
	
	
	
	private function regular(&$sql){
		$sql=preg_replace  ('/#(.+)/' , '', $sql );
		$sql=preg_replace  ('/--(.+)/' , '', $sql );
		$sql=preg_replace  ('/\/\*(.+)/' , '', $sql );
		$sql=str_replace("--",'',$sql);
		$explode=explode("\n",$sql);
		foreach($explode AS $V){
			if(!trim($V)){
				continue;
			}
			$_explode[]=trim($V);
		}
		if($_explode){
			$_explode=implode("\n",$_explode); 
			$explode=explode(";\n",$_explode);
		}
		
		return $explode;
	}
	
	
	public function test_sql(){
		
		$dsn       = 'mysql:host='.$_POST['dbhost'].';port='.$_POST['dbport'];
        try {
		    new  PDO ( $dsn ,  $_POST['dbuser'] ,  $_POST['dbpassword'],array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
            ));
		} catch ( PDOException $e ) {
			echo '0';
		}
	}
}
