<?
include("../include/config.inc.php");
include("../include/function.php");
include("../include/js.php");
include("../data/config.php");

//define('ROOT126CMS',preg_replace("#[\\\\\/]install#", '', dirname(__FILE__)));

function TestWrite($d)
{
    $tfile = '_dedet.txt';
    $d = preg_replace("#\/$#", '', $d);
    $fp = @fopen($d.'/'.$tfile,'w');
    if(!$fp) return false;
    else
    {
        fclose($fp);
        $rs = @unlink($d.'/'.$tfile);
        if($rs) return true;
        else return false;
    }
}
/**
 *  获得GD的版本
 *
 * @access    public
 * @return    int
 */
if ( ! function_exists('gdversion'))
{
    function gdversion()
    {
        //没启用php.ini函数的情况下如果有GD默认视作2.0以上版本
        if(!function_exists('phpinfo'))
        {
            if(function_exists('imagecreate'))
            {
                return '2.0';
            }
            else
            {
                return 0;
            }
        }
        else
        {
            ob_start();
            phpinfo(8);
            $module_info = ob_get_contents();
            ob_end_clean();
            if(preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i", $module_info,$matches))
            {
                $gdversion_h = $matches[1];
            }
            else
            {
                $gdversion_h = 0;
            }
            return $gdversion_h;
        }
    }
}

function bakindata($filename) {
	global $cfg_dbcharset;
	$sql=file($filename);
	$query='';
	$num=0;
	foreach($sql as $key => $value){
		$value=trim($value);
		if(!$value || $value[0]=='#') continue;
		if(eregi("\;$",$value)){
			$query.=$value;
			if(eregi("^CREATE",$query)){
				$extra = substr(strrchr($query,')'),1);
				$query = str_replace($extra,'',$query);
				if(mysql_get_server_info() > '4.1'){
					$extra = $cfg_dbcharset ? "ENGINE=MyISAM DEFAULT CHARSET=$cfg_dbcharset;" : "ENGINE=MyISAM;";
				}else{
					$extra = "TYPE=MyISAM;";
				}
				$query .= $extra;
			}elseif(eregi("^INSERT",$query)){
				$query='REPLACE '.substr($query,6);
			}
			mysql_query($query);
			$query='';
		} else{
			$query.=$value;
		}

	}
}


function check_db($dbhost, $dbuser, $dbpw, $dbname) {
	if(!function_exists('mysql_connect')) {
		exit("<script>alert('mysql_connect 函数未定义，\\n\\n 请查看服务器配置！');history.go(-1);</script>");
	}
	if(!@mysql_connect($dbhost, $dbuser, $dbpw)) {
		$errno = mysql_errno();
		$error = mysql_error();
		if($errno == 1045) {
			exit("<script>alert('1045 数据库密码错误，\\n\\n 请返回重新设置！');history.go(-1);</script>");
		} elseif($errno == 2003) {
			exit("<script>alert('database_errno_2003 不能连接数据库，\\n\\n 请返回重新设置！');history.go(-1);</script>");
		} else {
			exit("<script>alert('database_connect_error，\\n\\n 请返回重新设置！');history.go(-1);</script>");
		}
	} else {
		if($query = @mysql_query("SHOW TABLES FROM $dbname")) {
			/*while($row = mysql_fetch_row($query)) {
				if(preg_match("/^$tablepre/", $row[0])) {
					return false;
				}
			}*/
			return false;//数据库已存在
		}
	}
	return true;
}



$step = $_POST['step'];

//判断是否已安装过
if(file_exists('install.lock'))
{
    exit(" 程序已运行安装，如果你确定要重新安装，请先从FTP中删除文件: install/install.lock ");
}


if(empty($step))
{
    $step = 1;
}

/*------------------------
使用协议书
------------------------*/
if($step==1)
{
    include('./tpl/step-1.htm');
    exit();
}
/*------------------------
环境测试
------------------------*/
else if($step==2)
{
    $phpv = phpversion();
    $sp_os = PHP_OS;
    $sp_gd = gdversion();
	$current = round(@disk_free_space(".")/(1024*1024),2) . 'M';
	$max = @ini_get(upload_max_filesize);

	if( function_exists('mysql_connect') ){ $sp_mysql = '支持';$sp_mysql_style = 'w'; }else{ $sp_mysql = '不支持';$sp_mysql_style = 'nw';}
	if( function_exists('fsockopen') ){ $sp_fsockopen = '支持';$sp_fsockopen_style = 'w'; }else{ $sp_fsockopen = '不支持';$sp_fsockopen_style = 'nw';}
	if( function_exists('gethostbyname') ){ $sp_gethostbyname = '支持';$sp_gethostbyname_style = 'w'; }else{ $sp_gethostbyname = '不支持';$sp_gethostbyname_style = 'nw';}
	if( function_exists('file_get_contents') ){ $sp_fgc = '支持';$sp_fgc_style = 'w'; }else{ $sp_fgc = '不支持';$sp_fgc_style = 'nw';}
	if( function_exists('xml_parser_create') ){ $sp_xpc = '支持';$sp_xpc_style = 'w'; }else{ $sp_xpc = '不支持';$sp_xpc_style = 'nw';}
	
    $sp_testdirs = array(
        '/',
        '/cache/*',
        '/data/*',
        '/install',
        '/upload/*'
    );
    include('./tpl/step-2.htm');
    exit();
}
/*------------------------
设置参数
------------------------*/
else if($step==3)
{

    include('./tpl/step-3.htm');
    exit();
}

if($step==4)
{
    $dbinfo = $_POST['dbinfo'];
	
	
	$admininfo = $_POST['admininfo'];
	
	if( !$admininfo['pwd'] || ($admininfo['pwd'] != $admininfo['pwd2']) ){
		echo "<script>alert('两次输入密码不一至，\\n\\n 请返回重新设定！');history.go(-1);</script>";
	}
	
	//检测数据库是否已存在
	if ( !check_db($dbinfo['dbhost'], $dbinfo['dbuser'], $dbinfo['dbpwd'], $dbinfo['dbname']) ){//数据库已存在
	
		if( $dbinfo['forceinstall'] != 1 ){
			include('./tpl/step-3-2.htm');
			exit;
		}
	}
	
	
	$conn = mysql_connect($dbinfo['dbhost'],$dbinfo['dbuser'],$dbinfo['dbpwd']) or die("<script>alert('数据库服务器或登录密码无效，\\n\\n无法连接数据库，请重新设定！');history.go(-1);</script>");

    mysql_query("CREATE DATABASE IF NOT EXISTS `".$dbinfo['dbname']."`;",$conn);
    
    mysql_select_db($dbinfo['dbname']) or die("<script>alert('选择数据库失败，可能是你没权限，请预先创建一个数据库！');history.go(-1);</script>");
	
    mysql_query("SET NAMES 'gbk',character_set_client=binary,sql_mode='';",$conn);

    $fp = fopen(dirname(__FILE__)."/common.inc.php","r");
    $configStr1 = fread($fp,filesize(dirname(__FILE__)."/common.inc.php"));
    fclose($fp);
	
    //common.inc.php
    $configStr1 = str_replace("~dbhost~",$dbinfo['dbhost'],$configStr1);
    $configStr1 = str_replace("~dbname~",$dbinfo['dbname'],$configStr1);
    $configStr1 = str_replace("~dbuser~",$dbinfo['dbuser'],$configStr1);
    $configStr1 = str_replace("~dbpwd~",$dbinfo['dbpwd'],$configStr1);
    $configStr1 = str_replace("~dbcharset~",'gbk',$configStr1);

    @chmod(ROOT126CMS.'/data',0777);
    $fp = fopen(ROOT126CMS.'/data'."/common.inc.php","w") or die("<script>alert('写入配置失败，请检查../data目录是否可写入！');history.go(-1);</script>");
    fwrite($fp,$configStr1);
    fclose($fp);
	

	
	$dataFile = './data/126cms.sql';
	
	bakindata($dataFile);
	
	
	//管理员数据库增加网站创建者
	$admininfo['pwd']=md5($admininfo['pwd']);

	//写入数据库
	$query = "insert into `w6_admin`
            (`userid`,`pwd`,`email`,`gptype`)
            values
            ('".$admininfo['userid']."','".$admininfo['pwd']."','".$admininfo['email']."','1')";

	$result = mysql_query($query) or die(mysql_error());
  

	$showmsg = "成功导入";
	
	writetofile( './install.lock' , '' );
	
	include('./tpl/step-4.htm');
    exit();
}
