<?php

/*
	[SupeSite/X-Space] (C)2001-2006 Comsenz Inc.
	安裝文件

	$RCSfile: install.php,v $
	$Revision: 1.34 $
	$Date: 2006/10/31 05:23:34 $
*/

error_reporting(E_ERROR | E_WARNING | E_PARSE);
set_magic_quotes_runtime(0);

define('IN_SUPESITE', TRUE);
define(S_ROOT, '');

if(file_exists('./install.lock')) {
	exit('本安裝文件已經被鎖定，請不要重複安裝。為了安全起見，請立即刪除本文件！');
}

$_SGLOBAL = array(
	'supe_username' => 'admin',
	'timestamp' => time()
);

$_SCONFIG = array();

//SETTING
$title = '安裝SupeSite/X-Space';

empty($_SERVER['PHP_SELF'])?$PHP_SELF=$_SERVER['SCRIPT_NAME']:$PHP_SELF=$_SERVER['PHP_SELF'];

if(empty($_GET['step'])) {
	
	//環境檢查
	foreach(array('is_dir','mkdir') as $value) {
		if(!function_exists($value)) {
			exit("<p>對不起，你的PHP不支持目錄操作函數 $value ，請先聯繫主機商解決PHP配置問題</p>");
		}
	}
	
	$tmpdir = './install';
	if($d = dir($tmpdir)) {
		$d->close();
	} else {
		exit("<p>對不起，你的PHP不支持 dir(directory 類)，請先聯繫主機商解決PHP配置問題</p>");
	}
	
	$step = 0;
} else {
	$step = intval($_GET['step']);
}

$sqlfile = './install/supesite.sql';
if(!is_readable($sqlfile)) {
	exit('Please upload ./install and all its files completely.');
}

include('./config.php');

$class1 = $class2 = $class3 = $class4 = $class5 = '';
$errmsg = $disabled = '';

//POST
if(!empty($_POST['install_1_submit'])) {
	
	$ischeck = true;

	if(!@mysql_connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpw'])) {
		$ischeck = false;
		$errmsg = '您填寫的論壇數據庫用戶名、密碼信息不正確，請檢查！';
	} else {
		if(!@mysql_select_db($_POST['dbname'])) {
			$ischeck = false;
			$errmsg = '您填寫的論壇數據庫名不正確，請檢查！';
		}
	}
	if($ischeck && empty($_POST['bbsurl'])) {
		$ischeck = false;
		$errmsg = '您填寫的論壇訪問URL地址不能為空，請檢查！';
	}
	
	if($ischeck) {
		if(!empty($_POST['stablepre']) && $_POST['stablepre'] != $_POST['tablepre']) {
			$ischeck = true;
		} else {
			$ischeck = false;
			$errmsg = '您填寫的表名前綴不能為空，或者與論壇表名前綴相同，請檢查！';
		}
	}

	if($ischeck) {

		$file = './config.php';
		$fp = fopen($file, 'r');
		$configfile = fread($fp, filesize($file));
		fclose($fp);

		foreach (array('dbhost', 'dbuser', 'dbpw', 'dbname', 'adminemail', 'tablepre', 'stablepre', 'bbsver', 'siteurl', 'bbsurl', 'bbsattachurl', 'dbcharset', 'cookiedomain') as $value) {
			$configfile = preg_replace("/[$]".$value."\s*\=\s*[\"'].*?[\"']/is", "\$".$value." = '".$_POST[$value]."'", $configfile);
		}

		$fp = fopen($file, 'w');
		fwrite($fp, trim($configfile));
		fclose($fp);

		$step = 2;
	} else {
		$step = 1;
	}
} elseif(!empty($_POST['install_4_submit'])) {

	//連接數據庫
	require_once './config.php';
	require_once './class/db_mysql.class.php';
	require_once './function/cache.func.php';
	require_once './function/main.func.php';
	require_once './function/common.func.php';
	require_once './data/system/config.cache.php';
	
	define('S_URL', $siteurl);

	$_SCONFIG['stablepre'] = $stablepre;
	$_SCONFIG['dtablepre'] = $tablepre;

	$_SGLOBAL['db'] = $db = new dbstuff;
	$_SGLOBAL['timestamp'] = time();

	if(empty($dbcharset) && in_array(strtolower($charset), array('gbk', 'big5', 'utf-8'))) {
		$dbcharset = str_replace('-', '', $charset);
	}
	if(!empty($dbcharset)) $db->charset = $dbcharset;
	$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
	
	$db->select_db($dbname);
	if($db->error()) {
		$disabled = ' disabled="true"';
		$errmsg = '無法選擇數據庫('.$dbname.')，請確認該數據庫是否存在';
		$ischeck = false;
	}
	

	$newvalue = array();
	if(empty($_POST['show'])) $_POST['show']['index'] = 1;
	$usetypearr = array();
	foreach(array('index', 'news', 'blog', 'image', 'goods', 'file', 'link', 'bbs') as $value) {
		$system = 1;
		$default = 0;
		if($value == $_POST['default']) {
			$default = 1;
		}
		if($value == 'index') {
			$tpl = 'index';
			$url = S_URL;
		} else {
			$tpl = $value.'_index';
			$url = geturl('action/'.$value);
		}
		$newvalue[$value] = array(
				'action' => $value,
				'name' => $_SSCONFIG['channel'][$value]['name'],
				'tpl' => $tpl,
				'url' => $url,
				'default' => $default,
				'system' => $system,
				'show' => empty($_POST['show'][$value])?0:1
		);
		if(!empty($_POST['show'][$value]) && $value != 'index' && $value != 'bbs') {
			$usetypearr[] = $value;
		}
	}
	if(empty($usetypearr)) {
		$usetype = 'news,blog';
	} else {
		$usetype = implode(',', $usetypearr);
	}
	
	$newvaluestr = addslashes(serialize(sstripslashes($newvalue)));

	$_SGLOBAL['db']->query('UPDATE '.tname('settings').' SET `value`=\''.$newvaluestr.'\' WHERE variable=\'channel\'');
	$_SGLOBAL['db']->query('UPDATE '.tname('settings').' SET `value`=\''.$usetype.'\' WHERE variable=\'usetype\'');
	updatesettingcache();
	$step = 5;
}

if(empty($step)) {
	include('install/step.php');
} elseif ($step == 1) {
	
	if(!file_exists('./config.php')) {
		$disabled = ' disabled="true"';
		$errmsg = '系統配置文件config.php不存在，請將該文件上傳到服務器';
	} elseif(!is_writeable('./config.php')) {
		$disabled = ' disabled="true"';
		$errmsg = '系統配置文件config.php不能被寫入，請檢查該文件屬性';
	}

	$class1 = ' class="current"';

	$_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '/install.php'));
	$siteurl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

	include('install/step_1.php');
} elseif ($step == 2) {
	$class2 = ' class="current"';
	
	$dirarr = array(
		'./attachments',
		'./cache/robot',
		'./cache/tpl',
		'./channel',
		'./data',
		'./data/robot',
		'./data/temp',
		'./data/system',
		'./data/xpi',
		'./data/xpi/chrome/content/blogmark',
		'./data/xpi/chrome/locale/en/blogmark',
		'./html',
		'./log',
		'./templates/default',
		'./user'
	);
	$writearr = array();
	$pass = true;
	foreach ($dirarr as $key => $dir) {
		if(dir_writeable($dir)) {
			$writearr[$key] = '';
		} else {
			$writearr[$key] = ' class="wrong"';
			$pass = false;
		}
	}
	if(!$pass) {
		$disabled = ' disabled="true"';
		$errmsg = '部分目錄不能被寫入，請檢查相應目錄屬性設置';
	}
	
	include('install/step_2.php');
} elseif ($step == 3) {
	
	$ischeck = true;

	$fp = fopen($sqlfile, 'rb');
	$sql = fread($fp, 2048000);
	fclose($fp);
	
	//連接數據庫
	require_once './config.php';
	require_once './class/db_mysql.class.php';
	require_once './function/cache.func.php';
	require_once './function/main.func.php';
	require_once './function/common.func.php';

	$_SCONFIG['stablepre'] = $stablepre;
	$_SCONFIG['dtablepre'] = $tablepre;

	$_SGLOBAL['db'] = $db = new dbstuff;
	$_SGLOBAL['timestamp'] = time();

	if(empty($dbcharset) && in_array(strtolower($charset), array('gbk', 'big5', 'utf-8'))) {
		$dbcharset = str_replace('-', '', $charset);
	}
	if(!empty($dbcharset)) $db->charset = $dbcharset;
	$db->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
	
	$db->select_db($dbname);
	if($db->error()) {
		$disabled = ' disabled="true"';
		$errmsg = '無法選擇數據庫('.$dbname.')，請確認該數據庫是否存在';
		$ischeck = false;
	}
	
	if($ischeck) {
		$class3 = ' class="current"';
		
		include('install/header.php');
		echo '<h2>安裝數據庫</h2>';
		echo '<ul class="checkinfo">';

		runquery($sql);
		
		echo '</ul>';
		
		//更新論壇配置
		$db->query("UPDATE {$tablepre}settings SET `value`='1' WHERE `variable`='supe_status'");
		$db->query("UPDATE {$tablepre}settings SET `value`='$stablepre' WHERE `variable`='supe_tablepre'");
		$db->query("UPDATE {$tablepre}settings SET `value`='$siteurl' WHERE `variable`='supe_siteurl'");
		
		//更新緩存
		updatecache();

		echo '<p class="btns"><input type="button" value="上一步" class="btn" onclick="window.location.href=\''.$PHP_SELF.'?step=2\';" /><input type="button" value="下一步" name="installsubmit" class="btnsubmit" onclick="window.location.href=\''.$PHP_SELF.'?step=4\';" /></p>';
		include('install/footer.php');
	}
} elseif ($step == 4) {
	
	$class4 = ' class="current"';

	include('install/step_4.php');
} elseif ($step == 5) {
	
	$class5 = ' class="current"';
	
	@$fp = fopen('./install.lock', 'w');
	@fwrite($fp, "Access Denied");
	@fclose($fp);
	
	include('install/step_5.php');
}

function dir_writeable($dir) {
	if(!is_dir($dir)) {
		@mkdir($dir, 0777);
	}
	if(is_dir($dir)) {
		if($fp = @fopen("$dir/test.test", 'w')) {
			@fclose($fp);
			@unlink("$dir/test.test");
			$writeable = 1;
		} else {
			$writeable = 0;
		}
	}
	return $writeable;
}

//更新緩存
function updatecache() {
	global $db, $tablepre, $stablepre, $dbcharset, $siteurl, $_SGLOBAL, $_SCONFIG;
	
	//設置緩存
	updatesettingcache();
	//用戶組緩存
	updategroupcache();
	//廣告緩存
	updateadcache();
	//頁面特效
	updateeffectcache();
	//crons列表
	updatecronscache();
	//計劃任務
	updatecroncache();
	//分類
	updatecategorycache();
	//緩存論壇設置
	updatebbssetting();
	//緩存論壇風格設置
	updatebbsstyle();
	//緩存論壇語言屏蔽
	updatebbscensor();
	//緩存論壇bbcode/smiles
	updatebbsbbcode();
}

function runquery($sql) {
	global $db, $tablepre, $stablepre, $dbcharset;
	global $siteurl;
	
	//表名前綴
	$sql = str_replace("\r", "\n", str_replace(' supe_', ' '.$stablepre, $sql));
	$sql = str_replace("\r", "\n", str_replace(' `supe_', ' `'.$stablepre, $sql));
	$sql = str_replace("\r", "\n", str_replace(' cdb_', ' '.$tablepre, $sql));
	$sql = str_replace("\r", "\n", str_replace(' `cdb_', ' `'.$tablepre, $sql));

	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			@$ret[$num] .= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
		}
		$num++;
	}
	unset($sql);

	foreach($ret as $query) {
		$query = trim($query);
		if(strpos($query, '$')) {
			$query = preg_replace("/\\$([a-zA-Z0-9_]+)/ie", "$\\1", $query);
		}
		if($query) {
			if(substr($query, 0, 12) == 'CREATE TABLE') {
				$name = preg_replace("/CREATE TABLE ([a-z0-9_]+) .*/is", "\\1", $query);
				echo '<li>建立數據表 '.$name.' ...</li>';
				$db->query(createtable($query, $dbcharset));
			} else {
				$db->query($query, 'SILENT');
			}
		}
	}
}

function createtable($sql, $dbcharset) {
	$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
	$type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
	return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).
		(mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$dbcharset" : " TYPE=$type");
}

?>