<?php
require '../core/config/const.php';
$rootdir=ROOT;
$rootdir=str_ireplace('\\','/',$rootdir);
$rootdir=str_ireplace('/install/inc','',$rootdir);
$rootdir=str_ireplace('/install','',$rootdir);
define('ROOTDIR',$rootdir);
if (file_exists('../data/install.lock')){
Header("HTTP/1.1 303 See Other"); 
Header("Location: inc/installed.php"); 
exit; 
}
@set_time_limit(1000);
if(phpversion() <= '5.3.0') set_magic_quotes_runtime(0);
if('5.3.0' > phpversion() ) exit('您的php版本过低，不能安装本软件，请升级到5.3.0或更高版本再安装，谢谢！');
date_default_timezone_set('PRC');
error_reporting(E_ALL & ~E_NOTICE);
header('Content-Type: text/html; charset=UTF-8');
define('YUNYECMS_ROOT',str_replace('\\','/',realpath(dirname(__FILE__).'/../')).'/');
$sqlFile = 'yunyecms.sql';
$configFile =  'db.php';
if(!file_exists(YUNYECMS_ROOT.'install/'.$sqlFile) || !file_exists(YUNYECMS_ROOT.'install/'.$configFile)){
	echo '缺少必要的安装文件!';exit;
}
$steps= array(
	'1'=>'安装须知',
	'2'=>'环境检测',
	'3'=>'参数设置',
	'4'=>'正在安装',
	'5'=>'安装完成',
);
$step = isset($_GET['step'])? $_GET['step'] : 1;
switch($step)
{
case '1':
    include_once ("./inc/step1.tpl");
    exit ();

case '2':
 		if(phpversion()<5){
			die('本系统需要PHP5+MYSQL >=4.1环境，当前PHP版本为：'.phpversion());
		}
        $phpv = @ phpversion();
        $os = PHP_OS;
		$os = php_uname();
		$tmp = function_exists('gd_info') ? gd_info() : array();
        $server = $_SERVER["SERVER_SOFTWARE"];
        $host = (empty ($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_HOST"] : $_SERVER["SERVER_ADDR"]);
        $name = $_SERVER["SERVER_NAME"];
        $max_execution_time = ini_get('max_execution_time');
        $allow_reference = (ini_get('allow_call_time_pass_reference') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
        $allow_url_fopen = (ini_get('allow_url_fopen') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
        $safe_mode = (ini_get('safe_mode') ? '<font color=red>[×]On</font>' : '<font color=green>[√]Off</font>');
		$err=0;
		if(empty($tmp['GD Version'])){
			$gd =  '<span class="lable label-danger "><i class="fa fa-remove font-red"></i>  关闭  </span>' ;
			$err++;
		}else{
			$gd =  '<span class="lable lable-success"><i class="fa fa-check  font-green"></i> 开启 </span> &nbsp;&nbsp; '.$tmp['GD Version'];
			
		}
		/*if(function_exists('mysql_connect')){
			$mysql = '<span class="lable lable-success"><i class="fa fa-check  font-green"></i> 开启 </span>';
		}else{
			$mysql = '<span class="lable label-danger "><i class="fa fa-remove font-red"></i>  关闭  </span>';
			$err++;
		}*/
		if(function_exists('mysqli_connect')){
			$mysqli = '<span class="lable lable-success"><i class="fa fa-check  font-green"></i> 开启 </span>';
		}else{
			$mysqli = '<span class="lable label-danger "><i class="fa fa-remove font-red"></i>  关闭  </span>';
			$err++;
		}
		if(ini_get('file_uploads')){
			$uploadSize = '<span class="lable lable-success"><i class="fa fa-check  font-green"></i> 开启 </span> &nbsp;&nbsp; 文件限制:'.ini_get('upload_max_filesize');
		}else{
			$uploadSize = '禁止上传';
		}
		if(function_exists('session_start')){
			$session = '<span class="lable lable-success"><i class="fa fa-check  font-green"></i> 开启 </span>' ;
		}else{
			$session = '<span class="lable label-danger "><i class="fa fa-remove font-red"></i>  关闭  </span>';
			$err++;
		}
         $folder = array ('core/config','uploads',"data","data/caches","data/admin");
        include_once ("./inc/step2.tpl");
        exit ();

case '3':
		if($_GET['testdbpwd']){
			$dbHost = $_POST['dbHost'];
			$dbName = trim($_POST['dbName']);
			$dbUser = trim($_POST['dbUser']);
			$dbPwd= trim($_POST['dbPwd']);
			$dbPort =!empty($_POST['dbPort'])?intval($_POST['dbPort']):3306;
			$conn = @mysqli_connect($dbHost, $dbUser, $dbPwd,'',$dbPort);
			if($conn){die("1"); }else{die("");}
		}
		$scriptName = !empty ($_SERVER["REQUEST_URI"]) ?  $scriptName = $_SERVER["REQUEST_URI"] :  $scriptName = $_SERVER["PHP_SELF"];
        $rootpath = @preg_replace("/\/(I|i)nstall\/index\.php(.*)$/", "", $scriptName);
		$domain = $_SERVER['HTTP_HOST'];
		$domain = $domain.$rootpath;
        include_once ("./inc/step3.tpl");
        exit ();
case '4':
	if(intval($_GET['install'])){
			$n = intval($_GET['n']);
			$arr=array();
			$dbHost = trim($_POST['dbHost']);
			$dbPort = trim($_POST['dbPort']);
			$dbName = trim($_POST['dbName']);
			//$dbHost = empty($dbPort) || $dbPort == 3306 ? $dbHost : $dbHost.':'.$dbPort;
			$dbUser = trim($_POST['dbUser']);
			$dbPwd= trim($_POST['dbPwd']);
			$dbPrefix = empty($_POST['dbPrefix']) ? 'yunyecms_' : trim($_POST['dbPrefix']);
			$username =  trim($_POST['username']);
			$password = trim($_POST['password']);
			$sitename = addslashes(trim($_POST['sitename']));
			$email = trim($_POST['email']);
			$seodesc = trim($_POST['seodescription']);
			$seokey = trim($_POST['seokeywords']);
			$conn = @ mysqli_connect($dbHost, $dbUser, $dbPwd,'',$dbPort);
			if(!$conn){
				$arr['msg'] = "连接数据库失败!";
				echo json_encode($arr);exit;
			}

			mysqli_query($conn,"SET NAMES 'utf8'");//,character_set_client=binary,sql_mode='';
			$version = mysqli_get_server_info($conn);
			if($version < 4.1){
				$arr['msg'] = '数据库版本太低!';
				echo json_encode($arr);exit;
			}

			if(empty($username)){
				$arr['msg'] = "用户名为空!";
				echo json_encode($arr);exit;
			}

			if(!mysqli_select_db($conn,$dbName)){
				if(!mysqli_query($conn,"CREATE DATABASE IF NOT EXISTS `".$dbName."`;")){
					$arr['msg'] = '数据库 '.$dbName.' 不存在，也没权限创建新的数据库！';
					echo json_encode($arr);exit;
				}else{
					$arr['n']=0;
					$arr['msg'] = "成功创建数据库:{$dbName}<br>";
					echo json_encode($arr);exit;
				}
			}
			//读取数据文件
			$sqldata = file_get_contents(YUNYECMS_ROOT.'install/'.$sqlFile);
		
			sql_execute($sqldata, $dbPrefix,$conn);
		
			$result = mysqli_query($conn,"SHOW TABLES");
			while($row = mysqli_fetch_array($result))
				{
			    $table = str_replace('yunyehui_',$dbPrefix,$row[0]);
                 mysqli_query($conn,"rename table $row[0] to $table");
				}		
		 	$strsql = "UPDATE `{$dbPrefix}lang` SET seotitle='$sitename',seokey='$seokey',seodesc='$seodesc',sitename='$sitename'  WHERE  title like '%中文%' ";	
			mysqli_query($conn,$strsql);
			//读取配置文件，并替换真实配置数据
			$strConfig = file_get_contents(YUNYECMS_ROOT.'install/'.$configFile);
			$strConfig = str_replace('#DB_HOST#', $dbHost, $strConfig);
			$strConfig = str_replace('#DB_NAME#', $dbName, $strConfig);
			$strConfig = str_replace('#DB_USER#', $dbUser, $strConfig);
			$strConfig = str_replace('#DB_PWD#', $dbPwd, $strConfig);
			$strConfig = str_replace('#DB_PORT#', $dbPort, $strConfig);
			$strConfig = str_replace('#DB_PREFIX#', $dbPrefix, $strConfig);
			@file_put_contents(YUNYECMS_ROOT.DIRECTORY_SEPARATOR.'core'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'db.php', $strConfig);
 			//插入管理员
			$time=time();
			$ip = getip();
			$sql="select * from `{$dbPrefix}user` where username='$username'";  
			$result=mysqli_query($conn,$sql);  
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);  
		    $query=get_insert_sql($username,$email,$password,1,$dbPrefix);
			if (!mysqli_num_rows($result))  
				{ 
				  $query=get_insert_sql($username,$email,$password,1,$dbPrefix);
				}  
			else  
				{ 
				  if(!empty($password)){
				   $rnd=make_rand(20);
				   $salt_new=make_rand(16);
				   $password=YUNYECMSadmPwd($password,$salt_new);				  
				   $query="update `{$dbPrefix}user`  set `password`='$password',`salt`='$salt_new',`rnd`='$rnd' where username='$username'";
				   }					
				}  		
            mysqli_query($conn,$query);
			$message  = '成功添加管理员 <br /> 成功写入配置文件 <br> 安装完成．';
			$arr=array('n'=>999999,'msg'=>$message);
			echo json_encode($arr); exit;
	   }
	 include_once ("./inc/step4.tpl");
	 exit();

case '5':
    //dir_delete(YUNYECMS_ROOT.'/data/admin/admlogin');
    //dir_delete(YUNYECMS_ROOT.'/data/admin/admsess');
    dir_delete(YUNYECMS_ROOT.'/data/caches/templates/default');
	$scriptName = !empty ($_SERVER["REQUEST_URI"]) ?  $scriptName = $_SERVER["REQUEST_URI"] :  $scriptName = $_SERVER["PHP_SELF"];
    $rootpath = @preg_replace("/\/(I|i)nstall\/index\.php(.*)/", "", $scriptName);
	$domain = $_SERVER['HTTP_HOST'];
	$domain = $domain.$rootpath;
	include_once ("./inc/step5.tpl");
	@touch('../data/install.lock');
    exit ();
}
function testwrite($d )
{
	$tfile = "_test.txt";
	$fp = @fopen( $d."/".$tfile, "w" );
	if ( !$fp )
	{
		return false;
	}
	fclose( $fp );
	$rs = @unlink( $d."/".$tfile );
	if ( $rs )
	{
		return true;
	}
	return false;
}

function dir_list($path, $exts = '', $list= array()) {
    $path = dir_path($path);
    $files = glob($path.'*');
    foreach($files as $v) {
        $fileext = fileext($v);
        if (!$exts || preg_match("/\.($exts)/i", $v)) {
            $list[] = $v;
            if (is_dir($v)) {
                $list = dir_list($v, $exts, $list);
            }
        }
    }
    return $list;
}
function fileext($filename) {
    return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}
function dir_path($path) {
    $path = str_replace('\\', '/', $path);
    if(substr($path, -1) != '/') $path = $path.'/';
    return $path;
}
function dir_delete($dir) {
    $dir = dir_path($dir);
    if (!is_dir($dir)) return FALSE;
    $list = glob($dir.'*');
    foreach((array)$list as $v) {
        is_dir($v) ? dir_delete($v) : @unlink($v);
    }
    return @rmdir($dir);
}


function dir_create($path, $mode = 0777) {
	if(is_dir($path)) return TRUE;
	$ftp_enable = 0;
	$path = dir_path($path);
	$temp = explode('/', $path);
	$cur_dir = '';
	$max = count($temp) - 1;
	for($i=0; $i<$max; $i++) {
		$cur_dir .= $temp[$i].'/';
		if (@is_dir($cur_dir)) continue;
		@mkdir($cur_dir, 0777,true);
		@chmod($cur_dir, 0777);
	}
	return is_dir($path);
}


function sql_execute($sql,$tablepre,$conn) {
    $sqls = sql_split($sql,$tablepre);
	if(is_array($sqls))
    {
		foreach($sqls as $sql)
		{
			if(trim($sql) != '')
			{
				mysqli_query($conn,$sql);
			}
		}
	}
	else
	{
		mysqli_query($conn,$sqls);
	}
	return true;
}

function  sql_split($sql,$tablepre) {
	if($tablepre != "yunyehui_") $sql = str_replace("yunyehui_", $tablepre, $sql);
	$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8",$sql);
	//if($r_tablepre != $s_tablepre) $sql = str_replace($s_tablepre, $r_tablepre, $sql);
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query)
	{
		$ret[$num] = '';
		$queries = explode("\n", trim($query));
		$queries = array_filter($queries);
		foreach($queries as $query)
		{
			$str1 = substr($query, 0, 1);
			if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
		}
		$num++;
	}
	return $ret;
}

function getip(){
		if (isset($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], "unknown"))
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], "unknown"))
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		else if (isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
			$ip = $_SERVER['REMOTE_ADDR'];
		else if (isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
			$ip = $_SERVER['REMOTE_ADDR'];
		else $ip = "";
		return ($ip);
}
function getipport(){
	$ipport=(int)$_SERVER['REMOTE_PORT'];
	return $ipport;
}

 function get_insert_sql($username,$email,$password,$roleid,$dbPrefix,$status=1) {
		 $username=ysafestr(trim($username));
		 $rnd=make_rand(20);
		 $salt=make_rand(16);
		 $email=ysafestr(trim($email));
		 $password=ysafestr(trim($password));
		 $password=YUNYECMSadmPwd($password,$salt);
		 $roleid=(int)trim($roleid);
		 $addip["ipaddr"]=getip();
		 $addip["ipport"]=getipport();
		 $addiparr=yunyecms_strencode(json_encode($addip)); 
		 $createtime=time();
		 $status=ysafestr(trim($status));
		 if(empty($status)){
			 $status=0;
			 }else{
		     $status=(int)trim($status);
				 }
				$strsql="insert into `{$dbPrefix}user` (`username`, `password`, `roleid`, `salt`, `rnd`, `email`,`createtime`,`addip`,`status`) values('$username','$password',$roleid,'$salt','$rnd','$email',$createtime,'$addiparr',$status)";
				return $strsql;
	 }

	function ysafestr($string) {
		$string=str_replace("%","",$string);
		$string = str_replace('%20','',$string);
		$string = str_replace('%27','',$string);
		$string = str_replace('%2527','',$string);
		$string=str_replace("\t","",$string);
		$string = str_replace('*','',$string);
		$string = str_replace("'",'',$string);
		$string = str_replace(';','',$string);
		//$string = str_replace("{",'',$string);
		//$string = str_replace('}','',$string);
		$string=str_replace("#","",$string);
		$string=str_replace("--","",$string);
		$string=str_replace("\"","",$string);
		$string=str_replace("/","",$string);
		$string = str_replace('\\','',$string);
		$string=htmlspecialchars($string);
		$string = str_replace("$", "&#36;", $string);
		$string = str_replace("\n", "<br/>", $string);	
		$string = str_replace('%','%&lrm;',$string);
		$string=addslashes($string);
		return $string;
	}

function YUNYECMSadmPwd($password,$salt){
	$pwd=md5($salt.'~*Y^U^N-Y&*E$^=(C^&M#&*S'.md5(SHA1($password.'l~#i#~u^').$salt.'x#i#a^o-f^e^i').$salt);
	return $pwd;
}

function yunyecms_strencode($string,$salt='~^y#u%n$y^e*c%m^s^~'){
	return base64_encode(substr(md5($salt),8,18).base64_encode($string).substr(sha1($salt),0,35));
}

function make_rand($length = 8 ){  
    $chars = 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', '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',  
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    $keys = array_rand($chars, $length);  
    $rerand = '';  
    for($i = 0; $i < $length; $i++)
    {  
        $rerand .= $chars[$keys[$i]];
    }  
    return $rerand;  
}  
	

?>