<?php
@set_time_limit(1000);
if(phpversion() < '5.3.0') set_magic_quotes_runtime(0);
include '../source/base.php';
define('INSTALL_MODULE',true);
if(!defined('PS_PATH')) define('PS_PATH', XT_PATH.'..'.DIRECTORY_SEPARATOR);
defined('IN_XTCMS') or exit('No permission resources.');
if(file_exists(CACHE_PATH.'install.lock')) exit('您已经安装过XTLove,如果需要重新安装，请删除 ./cache/install.lock 文件！');
base::load_sys_class('param','','','0');
base::load_sys_func('global');
$steps = include PS_PATH.'install/step.inc.php';
$step = isset($_REQUEST['step']) ? trim($_REQUEST['step']) : 1;
$pos = strpos(get_url(),'install/install.php');
$siteurl = substr(get_url(),0,$pos);
if(strrpos(strtolower(PHP_OS),"win") === FALSE) {
	define('ISUNIX', TRUE);
} else {
	define('ISUNIX', FALSE);
}

$mode = 0777;

switch($step)
{
    case '1': //安装许可协议
		param::set_cookie('reg_sso_succ','');
		$license = file_get_contents(PS_PATH."install/license.txt");
		include PS_PATH."install/step/step".$step.".tpl.php";

		break;

	case '2':  //环境检测
        $PHP_GD  = '';
		if(extension_loaded('gd')) {
			if(function_exists('imagepng')) $PHP_GD .= 'png';
			if(function_exists('imagejpeg')) $PHP_GD .= ' jpg';
			if(function_exists('imagegif')) $PHP_GD .= ' gif';
		}
		$PHP_JSON = '0';
		if(extension_loaded('json')) {
			if(function_exists('json_decode') && function_exists('json_encode')) $PHP_JSON = '1';
		}
        $PHP_DNS = preg_match("/^[0-9.]{7,15}$/", @gethostbyname('www.newsteng.com')) ? 1 : 0;
		//是否满足XTCMS安装需求
		$is_right = (phpversion() >= '5.2.0' && extension_loaded('mysql') && $PHP_JSON && $PHP_GD) ? 1 : 0;

		//检查权限
		$files = file(PS_PATH."install/chmod.txt");
		foreach($files as $_k => $file) {
			$file = str_replace('*','',$file);
			$file = trim($file);
			if(is_dir(PS_PATH.$file)) {
				$is_dir = '1';
				$cname = '目录';
			} else {
				$is_dir = '0';
				$cname = '文件';
			}

			if($is_dir =='0' && is_writable(PS_PATH.$file)) {
					$is_writable = 1;
			} elseif($is_dir =='1' && dir_writeable(PS_PATH.$file)){
					$is_writable = 1;
			} else {
					$is_writable = 0;
					$no_writablefile = 1;
			}
			$filesmod[$_k]['file'] = $file;
			$filesmod[$_k]['is_dir'] = $is_dir;
			$filesmod[$_k]['cname'] = $cname;
			$filesmod[$_k]['is_writable'] = $is_writable;
		}
		if(dir_writeable(PS_PATH)) {
			$is_writable = 1;
		} else {
			$is_writable = 0;
		}
		$filesmod[$_k+1]['file'] = '网站根目录';
		$filesmod[$_k+1]['is_dir'] = '1';
		$filesmod[$_k+1]['cname'] = '目录';
		$filesmod[$_k+1]['is_writable'] = $is_writable;
		include PS_PATH."install/step/step".$step.".tpl.php";
		break;

	case '3': //配置帐号 （MYSQL帐号、管理员帐号、）
		$database = base::load_config('database');
		extract($database['default']);
		include PS_PATH."install/step/step".$step.".tpl.php";
		break;

	case '4': //安装详细过程
		extract($_POST);
		include PS_PATH."install/step/step".$step.".tpl.php";
		break;

	case '5': //完成安装
		$pos = strpos(get_url(),'install/install.php');
		$url = substr(get_url(),0,$pos);
		//设置cms报错信息
		set_config(array('errorlog'=>'1'),'system');
		file_put_contents(CACHE_PATH.'install.lock','');
		include PS_PATH."install/step/step".$step.".tpl.php";
		break;

	case 'install': //执行SQL
		extract($_POST);
		$PHP_SELF = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : $_SERVER['ORIG_PATH_INFO']);
		$rootpath = str_replace('\\','/',dirname($PHP_SELF));
		$rootpath = substr($rootpath,0,-7);
		$rootpath = strlen($rootpath)>1 ? $rootpath : "/";

		if ($module == 'xtcms') {
			//安装xtcms
			$cookie_pre = random(5, 'abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ').'_';
			$auth_key = random(20, '1294567890abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ');
			$xtcms_auth_key = random(32, '1294567890abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ');
			$sys_config = array('cookie_pre'=>$cookie_pre,
						'auth_key'=>$auth_key,
						'web_path'=>$rootpath,
						'errorlog'=>'0',
						'app_path'=>$siteurl,
						'js_path'=>$siteurl.'statics/js/',
						'css_path'=>$siteurl.'statics/css/',
						'img_path'=>$siteurl.'statics/images/',
						);
			$db_config = array('hostname'=>$dbhost,
						'username'=>$dbuser,
						'password'=>$dbpw,
						'database'=>$dbname,
						'tablepre'=>$tablepre,
						'pconnect'=>0,
						'charset'=>$dbcharset,
						);
			set_config($sys_config,'system');   //写入配置信息
			set_config($db_config,'database'); //写入数据库配置信息

			$lnk = mysql_connect($dbhost, $dbuser, $dbpw) or die ('Not connected : ' . mysql_error());
			$version = mysql_get_server_info();
			if($version > '4.1' && $dbcharset) {
				mysql_query("SET NAMES '$dbcharset'");
			}
			if($version > '5.0') {
				mysql_query("SET sql_mode=''");
			}
			mysql_select_db($dbname);
			$dbfile =  'xtcms_db.sql';
			if(file_exists(PS_PATH."install/main/".$dbfile)) {
				$sql = file_get_contents(PS_PATH."install/main/".$dbfile);
				_sql_execute($sql);
			}
			echo '数据库主文件安装完成<img src="images/correct.png" /><br>';
			//创建管理员信息
			if(CHARSET=='UTF-8') $username = iconv('UTF-8','GBK',$username);
			$password_arr = password($password);
			$password = $password_arr['password'];
			$encrypt = $password_arr['encrypt'];

			_sql_execute("INSERT INTO ".$tablepre."admin (`id`,`username`,`password`,`encrypt`,`issuper`,`lastlogin`,`ip`) VALUES ('1','$username','$password','$encrypt','1','','')");
			echo '管理员信息写入完成 <img src="images/correct.png" /><br>';
		}
		break;

	//数据库测试
	case 'dbtest':
		extract($_GET);
		if(!@mysql_connect($dbhost, $dbuser, $dbpw)) {
			exit('2');
		}
		$server_info = mysql_get_server_info();
		if($server_info < '4.0') exit('6');
		if(!mysql_select_db($dbname)) {
			if(!@mysql_query("CREATE DATABASE `$dbname`")) exit('3');
			mysql_select_db($dbname);
		}
		$tables = array();
		$query = mysql_query("SHOW TABLES FROM `$dbname`");
		while($r = mysql_fetch_row($query)) {
			$tables[] = $r[0];
		}
		if($tables && in_array($tablepre.'applications', $tables)) {
			exit('0');
		}
		else {
			exit('1');
		}
		break;
}
function format_textarea($string)
{
	return nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($string)));
}

function _sql_execute($sql,$r_tablepre = '',$s_tablepre = 'xt_')
{
    $sqls = _sql_split($sql,$r_tablepre,$s_tablepre);
	if(is_array($sqls))
    {
		foreach($sqls as $sql)
		{
			if(trim($sql) != '')
			{
				mysql_query($sql);
			}
		}
	}
	else
	{
		mysql_query($sqls);
	}
	return true;
}

function _sql_split($sql,$r_tablepre = '',$s_tablepre='xt_')
{
	global $dbcharset,$tablepre;
	$r_tablepre = $r_tablepre ? $r_tablepre : $tablepre;
	if(mysql_get_server_info > '4.1' && $dbcharset) {
		$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=".$dbcharset,$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 dir_writeable($dir) {
	$writeable = 0;
	if(is_dir($dir)) {
        if($fp = @fopen("$dir/chkdir.test", 'w')) {
            @fclose($fp);
            @unlink("$dir/chkdir.test");
            $writeable = 1;
        } else {
            $writeable = 0;
        }
	}
	return $writeable;
}

function set_config($config,$cfgfile) {
	if(!$config || !$cfgfile) return false;
	$configfile = PS_PATH.'configs'.DIRECTORY_SEPARATOR.$cfgfile.'.php';
	if(!is_writable($configfile)) showmessage('Please chmod '.$configfile.' to 0777 !');
	$pattern = $replacement = array();
	foreach($config as $k=>$v) {
			$v = trim($v);
			$configs[$k] = $v;
			$pattern[$k] = "/'".$k."'\s*=>\s*([']?)[^']*([']?)(\s*),/is";
        	$replacement[$k] = "'".$k."' => \${1}".$v."\${2}\${3},";
	}
	$str = file_get_contents($configfile);
	$str = preg_replace($pattern, $replacement, $str);
	return file_put_contents($configfile, $str, LOCK_EX);
}


function remote_file_exists($url_file){
	$headers = get_headers($url_file);
	if (!preg_match("/200/", $headers[0])){
		return false;
	}
	return true;
}
function password($password, $encrypt='') {
	$pwd = array();
	$pwd['encrypt'] =  $encrypt ? $encrypt : random(6, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
	$pwd['password'] = md5(md5(trim($password)).$pwd['encrypt']);
	return $encrypt ? $pwd['password'] : $pwd;
}
?>