<?php
/**
 * @version $Id: install.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

function str_parcate($cate, &$str_parcate, $startID = 0)
{
	if (!$cate[$startID]['cup']) return;
	foreach ($cate as $key => $value)
	{
		if ($value['cup'] == $startID)
		{
			$str_parcate .= $value['cid'].',';
			str_parcate($cate, $str_parcate, $value['cid']);
		}
	}
}

function str_subcate($cate, &$str_subcate, $startID = 0)
{
	foreach ($cate as $key => $value)
	{
		if ($value['cup'] == $startID)
		{
			$str_subcate .= $value['cid'].',';
			str_subcate($cate, $str_subcate, $value['cid']);
		}
	}
}
function addS(&$array)
{
	if (is_array($array))
	{
		foreach ($array as $key => $value)
		{
			 addS($array[$key]);
		}
	}
	elseif (is_string($array))
	{
		$array = addslashes($array);
	}
}
function result($result = 1, $output = 1)
{
	if($result)
	{
		$text = ' ... <span class="blue">OK</span>';
		if(!$output)
		{
			return $text;
		}
		echo $text;
	}
	else
	{
		$text = ' ... <span class="red">Failed</span>';
		if(!$output)
		{
			return $text;
		}
		echo $text;
	}
}
function runquery($sql)
{
	global $db_charset, $db_prefix, $tablenum, $i_message;
	$sql = str_replace("\r", "\n", str_replace('`pb_', '`'.$db_prefix, $sql));
	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query)
	{
		$queries = explode("\n", trim($query));
		$sq = "";
		foreach($queries as $query)
		{
			$sq .= $query;
		}
		$ret[$num] = $sq;
		$num ++;
	}
	unset($sql);
	foreach($ret as $query)
	{
		$query = trim($query);
		if($query) {
			if(substr($query, 0, 12) == 'CREATE TABLE')
			{
				$name = preg_replace("/CREATE TABLE `([a-z0-9_]+)` .*/is", "\\1", $query);
				echo '<p>'.$i_message['create_table'].' '.$name.' ... <span class="blue">OK</span></p>';
				@mysql_query(createtable($query, $db_charset));
				$tablenum ++;
			}
			else
			{
				@mysql_query($query);
			}
		}
	}
}
function createtable($sql, $db_charset)
{
	$db_charset = (strpos($db_charset, '-') === FALSE) ? $db_charset : str_replace('-', '', $db_charset);
	$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=$db_charset" : " TYPE=$type");
}
function getip()
{
	if (isset ($_SERVER['HTTP_X_FORWARDED_FOR']))
	{
		$onlineip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	elseif (isset ($_SERVER['HTTP_CLIENT_IP']))
	{
		$onlineip = $_SERVER['HTTP_CLIENT_IP'];
	}
	else
	{
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	$onlineip = preg_match('/[\d\.]{7,15}/', addslashes($onlineip), $onlineipmatches);
	return $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
}
function pb_writable($var)
{
	$writeable = FALSE;
	$var = PBDIGG_ROOT.$var;
	if(!is_dir($var))
	{
		@mkdir($var, 0777);
	}
	if (is_dir($var))
	{
		$var .= '/temp.txt';
		if (($fp = @fopen($var, 'w')) && (fwrite($fp, 'pbdigg')))
		{
			fclose($fp);
			@unlink($var);
			$writeable = TRUE;
		}
	}
	return $writeable;
}
function PWriteFile($filename, $content, $mode = 'ab')
{
	if (strpos($filename, '..') !== FALSE)
	{
		return FALSE;
	}
	$path = dirname($filename);
	if (!is_dir($path))
	{
		if (!mkdir($path, 0777))
		{
			return FALSE;
		}
	}
	$fp = @ fopen($filename, $mode);
	if ($fp)
	{
		flock($fp, LOCK_EX);
		fwrite($fp, $content);
		fclose($fp);
		@ chmod($filename, 0777);
		return TRUE;
	}
	return FALSE;
}
function random($length, $isNum = FALSE)
{
	$random = '';
	$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	$num = '0123456789';
	if ($isNum)
	{
		$sequece = 'num';
	}
	else
	{
		$sequece = 'str';
	}
	$max = strlen($$sequece) - 1;
	for ($i = 0; $i < $length; $i++)
	{
		$random .= ${$sequece}{mt_rand(0, $max)};
	}
	return $random;
}

error_reporting(E_ERROR | E_WARNING | E_PARSE);
$_PBVERSION = '2.0.0';
define('PBDIGG_INSTALL', TRUE);
define('IN_PBDIGG', TRUE);
define('PBDIGG_ROOT', str_replace('\\', '/', substr(dirname(__FILE__), 0, -7)));
$timestamp = time();
$ip = getip();
$installfile = 'install.sql';
require_once('install_lang.php');
header('Content-Type: text/html; charset=gbk');
if (file_exists('install.lock'))
{
	exit($i_message['install_lock']);
}
if (!is_readable($installfile))
{
	exit($i_message['install_dbFile_error']);
}
$quit = false;
$msg = $alert = $link = $sql = $allownext = '';
$configfile = PBDIGG_ROOT.'data/sql.inc.php';
$managerfile = PBDIGG_ROOT.'data/manager.inc.php';
$PHP_SELF = addslashes(htmlspecialchars($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']));
set_magic_quotes_runtime(0);
if (!get_magic_quotes_gpc())
{
	addS($_POST);
	addS($_GET);
}
@extract($_POST);
@extract($_GET);
?>
<html>
<head>
<title><?php echo $i_message['install_title']; ?></title>
<meta http-equiv=Content-Type content="text/html; charset=gbk">
<link href="style.css" rel="stylesheet" type="text/css" />
<body>
<div id='content'>
<div id='pageheader'>
	<div id="logo"><img src="images/pbdigg.gif" width="260" height="80" border="0" alt="PBDIGG" /></div>
	<div id="version" class="rightheader">Version <?php echo $_PBVERSION; ?></div>
</div>
<div id='innercontent'>
	<h1>PBDigg <?php echo $_PBVERSION, ' ', $i_message['install_wizard']; ?></h1>
<?php
if (!$v)
{
?>
<div class="botBorder">
<p><span class='red'><?php echo $i_message['install_warning'];?></span></p>
</div>
<div class="botBorder">
<?php echo $i_message['install_intro'];?>
</div>
<form method="post" action="install.php?v=1">
<p class="center"><input type="submit" class="submit" value="<?php echo $i_message['install_start'];?>" /></p>
</form>
<?php
}
elseif ($v == '1')
{
?>
<h2><?php echo $i_message['install_license_title'];?></h2>
<p>
<textarea class="textarea" readonly="readonly" cols="50">
<?php echo $i_message['install_license'];?>
</textarea>
</p>
<form action="install.php?v=2" method="post">
<p><input type="checkbox" name="agree" value="1" onclick="if(this.checked==true){this.form.next.disabled=''}else{this.form.next.disabled='true'}" checked="checked" /><?php echo $i_message['install_agree'];?></p>
<p><input type="button" class="submit" name="prev" value="<?php echo $i_message['install_prev'];?>" onclick="history.go(-1)">&nbsp;
	<input type="submit" class="submit" name="next" value="<?php echo $i_message['install_next'];?>" /></p>
</form>
<?php
}
elseif ($v == '2')
{
if ($agree == 'no')
{
	echo '<script>alert('.$i_message['install_disagree_license'].');history.go(-1)</script>';
}
$dirarray = array (
	'admin/dbak',
	'attachments',
	'cache/pbdigg',
	'compile/admin',
	'compile/pbdigg',
	'data',
	'data/cache',
	'data/log',
	'data/session',
	'debug',
	'images/cate',
	'images/avatars',
	'install'
);
$writeable = array();
foreach ($dirarray as $key => $dir)
{	
	if (pb_writable($dir))
	{
		$writeable[$key] = $dir.result(1, 0);
	}
	else
	{
		$writeable[$key] = $dir.result(0, 0);
		$quit = TRUE;
	}
}
?>
<div class="botBorder">
<p><span class='red'><?php echo $i_message['install_dirmod'];?></span></p>
</div>
<div class="shade">
<div class="settingHead"><?php echo $i_message['install_env'];?></div>
<h5><?php echo $i_message['php_os'];?></h5>
<p><?php echo PHP_OS;result(1, 1);?></p>
<h5><?php echo $i_message['php_version'];?></h5>
<p>
<?php
echo PHP_VERSION;
if (PHP_VERSION < '4.0.6')
{
	result(0, 1);
	$quite = TRUE;
}
else
{
	result(1, 1);
}
?></p>
<h5><?php echo $i_message['file_upload'];?></h5>
<p>
<?php
if (@ini_get('file_uploads'))
{
	echo $i_message['support'],'/',@ini_get('upload_max_filesize');
}
else
{
	echo '<span class="red">'.$i_message['unsupport'].'</span>';
}
result(1, 1);
?></p>
<h5><?php echo $i_message['mysql'];?></h5>
<p>
<?php
if (function_exists('mysql_connect'))
{
	echo $i_message['support'];
	result(1, 1);
}
else
{
	echo '<span class="red">'.$i_message['mysql_unsupport'].'</span>';
	result(0, 1);
	$quite = TRUE;
}
?></p>
</div>
<div class="shade">
<div class="settingHead"><?php echo $i_message['dirmod'];?></div>
<?php
foreach ($writeable as $value)
{
	echo '<p>'.$value.'</p>';
}
?>
</div>
<p class="center">
	<form method="post" action='install.php?v=3'>
	<input type="button" class="submit" name="prev" value="<?php echo $i_message['install_prev'];?>" onclick="history.go(-1)">&nbsp;
	<input type="submit" class="submit" name="next" value="<?php echo $i_message['install_next'];?>" <?php if($quit) echo "disabled=\"disabled\"";?>>
	</form>
</p>
<?php
}
elseif ($v == '3')
{
?>
<h2><?php echo $i_message['install_setting'];?></h2>
<form method="post" action="install.php?v=4" id="install" onsubmit="return check();">
<div class="shade">
<div class="settingHead"><?php echo $i_message['dirmod'];?></div>

<h5><?php echo $i_message['install_mysql_host'];?></h5>
<p><?php echo $i_message['install_mysql_host_intro'];?></p>
<p><input type="text" name="db_host" value="localhost" size="40" class='input' /></p>

<h5><?php echo $i_message['install_mysql_username'];?></h5>
<p><input type="text" name="db_username" value="root" size="40" class='input' /></p>

<h5><?php echo $i_message['install_mysql_password'];?></h5>
<p><input type="password" name="db_password" value="" size="40" class='input' /></p>

<h5><?php echo $i_message['install_mysql_name'];?></h5>
<p><input type="text" name="db_name" value="" size="40" class='input' /></p>

<h5><?php echo $i_message['install_mysql_prefix'];?></h5>
<p><?php echo $i_message['install_mysql_prefix_intro'];?></p>
<p><input type="text" name="db_prefix" value="pb_" size="40" class='input' /></p>
</div>

<div class="shade">
<div class="settingHead"><?php echo $i_message['founder'];?></div>

<h5><?php echo $i_message['install_founder_name'];?></h5>
<p><input type="text" name="username" value="admin" size="40" class='input' /></p>

<h5><?php echo $i_message['install_founder_password'];?></h5>
<p><input type="text" name="password" value="" size="40" class='input' /></p>

<h5><?php echo $i_message['install_founder_rpassword'];?></h5>
<p><input type="text" name="rpassword" value="" size="40" class='input' /></p>

<h5><?php echo $i_message['install_founder_email'];?></h5>
<p><input type="text" name="email" value="admin@admin.com" size="40" class='input' /></p>
</div>
<div class="center">
	<input type="button" class="submit" name="prev" value="<?php echo $i_message['install_prev'];?>" onclick="history.go(-1)">&nbsp;
	<input type="submit" class="submit" name="next" value="<?php echo $i_message['install_next'];?>">
	</form>
</div>
<script type="text/javascript" language="javascript">
function check()
{
	var obj = document.getElementById('install');
	if (!obj.db_host.value)
	{
		alert('<?php echo $i_message['install_mysql_host_empty'];?>');
		obj.db_host.focus();
		return false;
	}
	else if (!obj.db_username.value)
	{
		alert('<?php echo $i_message['install_mysql_username_empty'];?>');
		obj.db_username.focus();
		return false;
	}
	else if (!obj.db_name.value)
	{
		alert('<?php echo $i_message['install_mysql_name_empty'];?>');
		obj.db_name.focus();
		return false;
	}
	else if (!obj.username.value)
	{
		alert('<?php echo $i_message['install_founder_name_empty'];?>');
		obj.username.focus();
		return false;
	}
	else if (obj.password.value.length < 6)
	{
		alert('<?php echo $i_message['install_founder_password_length'];?>');
		obj.password.focus();
		return false;
	}
	else if (obj.password.value != obj.rpassword.value)
	{
		alert('<?php echo $i_message['install_founder_rpassword_error'];?>');
		obj.rpassword.focus();
		return false;
	}
	else if (!obj.email.value)
	{
		alert('<?php echo $i_message['install_founder_email_empty'];?>');
		obj.email.focus();
		return false;
	}
	return true;
}
</script>
<?php
}
elseif ($v == '4')
{
	if(empty($db_host) || empty($db_username) || empty($db_name) || empty($db_prefix))
	{
		$msg .= '<p>'.$i_message['mysql_invalid_configure'].'<p>';
		$quit = TRUE;
	}
	elseif (!@mysql_connect($db_host, $db_username, $db_password))
	{
		$msg .= '<p>'.$i_message['database_errno_'.mysql_errno()].'</p>';
		$quit = TRUE;
	}
	if(strstr($db_prefix, '.'))
	{
		$msg .= '<p>'.$i_message['mysql_invalid_prefix'].'</p>';
		$quit = TRUE;
	}
	if (empty($username) || empty($password) || empty($rpassword) || empty($email))
	{
		$msg .= '<p>'.$i_message['founder_invalid_configure'].'</p>';
		$quit = TRUE;
	}
	elseif (strlen($password) < 6)
	{
		$msg .= '<p>'.$i_message['founder_invalid_password'].'</p>';
		$quit = TRUE;
	}
	elseif ($password != $rpassword)
	{
		$msg .= '<p>'.$i_message['founder_invalid_rpassword'].'</p>';
		$quit = TRUE;
	}
	elseif (!preg_match('/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,3}$/i', $email))
	{
		$msg .= '<p>'.$i_message['founder_invalid_email'].'</p>';
		$quit = TRUE;
	}
	else
	{
		$forbiddencharacter = array ("\\","&"," ","'","\"","/","*",",","<",">","\r","\t","\n","#","$","(",")","%","@","+","?",";","^");
		foreach ($forbiddencharacter as $value)
		{
			if (strpos($username, $value) !== FALSE)
			{
				$msg .= '<p>'.$i_message['forbidden_character'].'</p>';
				$quit = TRUE;
				break;
			}
		}
	}
	if ($quit)
	{
		$allownext = 'disabled="disabled"';
?>
<div class="error"><?php echo $i_message['error'];?></div>
<?php
	echo $msg;
	}
	else
	{
		$fp = @fopen($configfile, 'wb');
		$configfilecontent = <<<EOT
<?php

/** PBDigg SQL CONFIG FILE! **/

//数据库服务器，一般为localhost
\$db_host = '$db_host';

//数据库名称
\$db_name = '$db_name';

//数据库用户名
\$db_username = '$db_username';

//数据库密码
\$db_password = '$db_password';

//数据库持久连接 0=关闭, 1=打开
\$db_pconnect = '0';

//表前缀
\$db_prefix = '$db_prefix';

//数据库字符集, 可选 'gbk', 'big5', 'utf-8'
\$db_charset = 'gbk';

//数据库类型
\$_PBDEV['dbType'] = 'MySQL';

//是否将错误格式化写入日志文件 0=否, 1=是
\$_PBDEV['logDataFile'] = '0';

//是否将错误写入调试文件 0=否, 1=是
\$_PBDEV['logDebugFile'] = '1';

//是否启用debug模式，TRUE将显示完整错误信息，FALSE将显示提示性错误信息
\$_PBDEV['debug'] = TRUE;

?>
EOT;
		@chmod($configfile, 0777);
		fwrite($fp, trim($configfilecontent));
		@fclose($fp);

		$fp = @fopen($managerfile, 'wb');
		$md5password = md5($password);
		$managerfilecontent = <<<EOT
<?php
/** {$i_message['founder_intro']} **/
if (!defined('IN_PBDIGG'))
{
	exit('Access Denied!');
}
\$siteFounder = array(
		'username' => '$username',
		'password' => '$md5password'
);
?>
EOT;
		@chmod($managerfile, 0777);
		fwrite($fp, trim($managerfilecontent));
		@fclose($fp);
		$msg .= '<p>'.$i_message['configure_log_success'].'</p>';
?>
<div class="botBorder">
<p><?php echo $i_message['install_founder_name'], ' ', $username?></p>
<p><?php echo $i_message['install_founder_password'], ' ', $password;?></p>
</div>
<?php
}
?>
<div class="center">
	<form method="post" action="install.php?v=5&email=<?php echo rawurlencode($email)?>">
	<input type="button" class="submit" name="prev" value="<?php echo $i_message['install_prev'];?>" onclick="history.go(-1)">&nbsp;
	<input type="submit" class="submit" name="next" value="<?php echo $i_message['install_next'];?>" <?=$allownext?>>
	</form>
</div>
<?php
}
elseif ($v == '5')
{
	@require_once($configfile);
	if (!$db_host && !$db_name)
	{
		$msg .= '<p>'.$i_message['configure_read_failed'].'</p>';
		$quit = TRUE;
	}
	else
	{
		mysql_connect($db_host, $db_username, $db_password);
		$sqlv = mysql_get_server_info();
		if($sqlv < '4.0.2')
		{
			$msg .= '<p>'.$i_message['mysql_version_402'].'</p>';
			$quit = TRUE;
		}
		else
		{
			if($sqlv > '4.1')
			{
				$db_charset = (strpos($db_charset, '-') === FALSE) ? $db_charset : str_replace('-', '', $db_charset);
				mysql_query("CREATE DATABASE IF NOT EXISTS `$db_name` DEFAULT CHARACTER SET $db_charset");
			}
			else
			{
				mysql_query("CREATE DATABASE IF NOT EXISTS `$db_name`");
			}
			if (mysql_errno())
			{
				$errormsg = $i_message['database_errno_'.mysql_errno()];
				$msg .= '<p>'.($errormsg ? $errormsg : $i_message['database_errno']).'</p>';
				$quit = TRUE;
			}
			else
			{
				mysql_select_db($db_name);
			}
			$link = mysql_query("SELECT COUNT(*) FROM {$db_prefix}configs");
			if($link)
			{
				$msg .= '<p>'.$i_message['pbdigg_rebuild'].'</p>';
				$alert = ' onclick="return confirm(\''.$i_message['pbdigg_rebuild'].'\');"';
			}
			mysql_close();
		}
	}
	if ($quit)
	{
		$allownext = 'disabled="disabled"';
?>
<div class="error"><?php echo $i_message['error'];?></div>
<?php
	echo $msg;
}
else
{
?>
<div class="botBorder">
<p><?php echo $i_message['mysql_import_data'];?></p>
</div>
<?php
}
?>
<div class="center">
	<form method="post" action="install.php?v=6&email=<?php echo rawurlencode($email)?>">
	<input type="button" class="submit" name="prev" value="<?php echo $i_message['install_prev'];?>" onclick="history.go(-1)">&nbsp;
	<input type="submit" class="submit" name="next" value="<?php echo $i_message['install_next'];?>" <?php echo $allownext,$alert?>>
	</form>
</div>
<?php
}
elseif ($v == '6')
{
	@require_once($configfile);
	@require_once($managerfile);
	mysql_connect($db_host, $db_username, $db_password);
	if (mysql_get_server_info() > '5.0')
	{
		mysql_query("SET sql_mode = ''");
	}
	$db_charset = (strpos($db_charset, '-') === FALSE) ? $db_charset : str_replace('-', '', $db_charset);
	mysql_query("SET character_set_connection=$db_charset, character_set_results=$db_charset, character_set_client=binary");
	mysql_select_db($db_name);	
	$tablenum = 0;
	$fp = fopen($installfile, 'rb');
	$sql = fread($fp, filesize($installfile));
	fclose($fp);
?>
<div class="botBorder">
<h4><?php echo $i_message['import_processing'];?></h4>
<?php
	runquery($sql);
?>
</div>
<div class="botBorder">
<h4><?php echo $i_message['create_founder'];?></h4>
<?php
mysql_query("INSERT INTO {$db_prefix}members (username, password, email, adminid, groupid, publicemail, regip, regdate) VALUES ('".$siteFounder['username']."', '".$siteFounder['password']."', '$email', 1, 1, 1, '$ip', '$timestamp')");
mysql_query("INSERT INTO {$db_prefix}memberdata (uid, postnum, commentnum, tdigg, cdigg, diggnum, tbury, cbury, burynum, currency, lastip, currentip, lastvisit, lastpost, lastcomment, uploadnum, visitcount) VALUES (1, 0, 0, '', '', 0, '', '', 0, 0, '$ip', '$ip', '$timestamp', 0, 0, 0, 0)");
mysql_query("INSERT INTO {$db_prefix}memberexp (uid, qq, msn, site, location, birthday, signature, showsign, avatar, gender) VALUES (1, '', '', '', '', '0000-00-00', '', 1, '', 3)");
mysql_query("UPDATE {$db_prefix}configs SET text = 'http://".substr($_SERVER['HTTP_HOST'].dirname($PHP_SELF), 0, -8)."/' WHERE title = 'pb_siteurl'");
mysql_query("UPDATE {$db_prefix}configs SET text = '".random(10)."' WHERE title = 'pb_sitehash'");
mysql_query("UPDATE {$db_prefix}sitestat SET newmember = '".$siteFounder['username']."' WHERE id = 1");
mysql_close();
?>
<p><?php echo $i_message['create_founder_success'];?></p>
</div>
<div class="botBorder">
<h4><?php echo $i_message['create_cache'];?></h4>
<?php
	error_reporting(E_ALL);
require_once(PBDIGG_ROOT.'include/Cache.class.php');
require_once(PBDIGG_ROOT.'include/MySQL.class.php');
$DB = new MySQL($db_host, $db_username, $db_password, $db_name, $db_pconnect);
$Cache = new Cache();
$Cache->coreCache();
fopen('install.lock', 'w');
?>
<p><?php echo $i_message['create_cache_success'];?></p>
</div>
<div class="botBorder">
<h4><?php echo $i_message['install_success'];?></h4>
<?php echo $i_message['install_success_intro'];?>
</div>
<?php
}
?>
</div>
<div class='copyright'>PBDigg Version 2.0.0 &#169; copyright 2007 - 2008 PBDigg.com All Rights Reserved</div>
</div>
</body>
</html>