<?php

/*
 * Copyright (C) xgcms.com
 */

// 调试模式: 1 打开，0 关闭
define('DEBUG', 0);

include './function.php';

// 站点根目录
define('POST_PATH', xn_realpath(substr(__FILE__, 0, -9).'../'));

// 框架的物理路径
$conf = include POST_PATH.'conf/conf.php';
if(empty($conf)) {
	message('<h3>读取配置文件失败，请检查配置文件是否存在并且有可读权限：'.POST_PATH.'conf/conf.php'.'</h3>');
}

// PHP 版本判断
if(version_compare(PHP_VERSION, '5.0.0') == -1) {
	message('<h3>非常抱歉，您的PHP版本太低 ('.PHP_VERSION.')，达不到最低安装要求 (5.0.0)</h3>');
}

if(!DEBUG && is_file($conf['upload_path'].'install.lock')) {
	message('已经安装过，如果需要重新安装，请删除 upload/install.lock 文件。');
}

$step = isset($_GET['step']) ? $_GET['step'] : '';

if(empty($step) || $step == 'checklicense') {
	include './step_1.php';
	exit;
} elseif($step == '2') {
	$env = $write = array();
	get_env($env, $write);
	include './step_3.php';
	exit;
} elseif($step == '4') {
	
	define('FRAMEWORK_PATH', POST_PATH.'core/xiunophp/');
	define('FRAMEWORK_TMP_PATH', $conf['tmp_path']);
	define('FRAMEWORK_LOG_PATH', $conf['log_path']);
	include FRAMEWORK_PATH.'core.php';
	core::init();
	core::ob_start();
	
	// 检测 mysql_connnect, mongodb, pdo 扩展情况
	$mysql_support = function_exists('mysql_connect');
	$mongodb_support = extension_loaded('Mongo');
	$pdo_support = extension_loaded('PDO');
	
	$type = core::gpc('type', 'G');
	empty($type) && $type = 'mysql';
	
	if(core::gpc('FORM_HASH', 'P')) {
		$host = core::gpc('host', 'P');
		$user = core::gpc('user', 'P');
		$pass = core::gpc('pass', 'P');
		$name = core::gpc('name', 'P');
		$tablepre = core::gpc('tablepre', 'P');
		$adminuser = core::gpc('adminuser', 'P');
		$adminpass = core::gpc('adminpass', 'P');
		$adminpass2 = core::gpc('adminpass2', 'P');
		$error = '';
		if($type == 'mysql') {
			$link = @mysql_connect($host, $user, $pass, TRUE);
			if(!$link) {
				$error = 'MySQL 账号密码可能有误：<span class="small">'.mysql_error().'</span>';
			} else {
				$r = mysql_select_db($name);
				if(mysql_errno() == 1049) {
					mysql_query("CREATE DATABASE $name");
					$r = mysql_select_db($name);
				}
				if(!$r) {
					$error = 'MySQL 账户权限可能受限：<span class="small">'.mysql_error().mysql_errno().'</span>';
				} else {
					$c = array(
						// 主 MySQL Server
						'master' => array (
								'host' => $host,
								'user' => $user,
								'password' => $pass,
								'name' => $name,
								'charset' => 'utf8',
								'tablepre' => $tablepre,
								'engine'=>'MyISAM',
						),
						// 从 MySQL Server
						'slaves' => array (
						)
					);
					//$conf['db']['type'] = 'mysql';
					//$conf['db']['master'] = $c['master'];
					//$conf['db']['slaves'] = $c['slaves'];
					$db = new db_mysql($c);
					
					$s = file_get_contents(POST_PATH.'install/post.sql');
					
					$s = str_replace("\r\n", "\n", $s);
					$s = preg_replace('#\n\#[^\n]*?\n#is', "\n", $s);	// 去掉注释行
					$sqlarr = explode(";\n", $s);
					
					foreach($sqlarr as $sql) {
						if(trim($sql)) {
							$sql = str_replace('xg_', $tablepre, $sql);
							try {
								$db->query($sql);
							} catch (Exception $e) {
								$error = $e->getMessage();
								break;
							}
						}
					}
					
					$db->truncate('framework_count');
					$db->truncate('framework_maxid');
					
				}
			}
		}
		
		if(!$error) {
			
			// 预设 count maxid
			$db->count('group', 16);
			$db->maxid('group-groupid', 15);
			$db->count('member', 2);
			$db->maxid('member-uid', 10);	// 内置10个账户，方便扩展
			$db->count('forum', 3);
			$db->maxid('forum-fid', 3);
			//$db->count('digestcate', 6);
			//$db->maxid('digestcate-cateid', 6);
			//$db->truncate('kv');
			$db->truncate('runtime');
			
			// db 写入配置文件
			$configfile = POST_PATH.'conf/conf.php';
			$replacearr = array('user'=>$user, 'host'=>$host, 'password'=>$pass, 'name'=>$name, 'tablepre'=>$tablepre);
			if($type == 'mysql') {
				file_line_replace($configfile, 18, 30, $replacearr);
			} elseif($type == 'pdo') {
				file_line_replace($configfile, 31, 43, $replacearr);
			} elseif($type == 'mongodb') {
				file_line_replace($configfile, 44, 54, $replacearr);
			}
			$typearr = array('type'=>$type);
			file_line_replace($configfile, 17, 18, $typearr);
			
			$url = misc::get_url_path();
			$public_key = md5(rand(1, 10000000).$_SERVER['ip']);
			$s = file_get_contents($configfile);
			$appurl = substr($url, 0, -8); // 带 /
			$s = preg_replace('#\'app_url\'\s*=\>\s*\'?.*?\'?,#is', "'app_url' => '$appurl',", $s);
			$s = preg_replace('#\'static_url\'\s*=\>\s*\'?.*?\'?,#is', "'static_url' => '$appurl',", $s);
			$s = preg_replace('#\'upload_url\'\s*=\>\s*\'?.*?\'?,#is', "'upload_url' => '{$appurl}upload/',", $s);
			$s = preg_replace('#\'click_server\'\s*=\>\s*\'?.*?\'?,#is', "'click_server' => '{$appurl}clickd/',", $s);
			$s = preg_replace('#\'public_key\'\s*=\>\s*\'?.*?\'?,#is', "'public_key' => '$public_key',", $s);
			$s = preg_replace('#\'installed\'\s*=\>\s*\'?.*?\'?,#is', "'installed' => 1,", $s);
			file_put_contents($configfile, $s);
			
			// 修改密码
			$muser = new member();
			$admin = $db->get("member-uid-1");
			$admin['username'] = $adminuser;
			$admin['securekey'] = rand(100000, 999999);
			$admin['password'] = $muser->md5_md5($adminpass, $admin['securekey']);
			$db->set("member-uid-1", $admin);
			
			$u = $db->get("member-uid-2");
			$u['groupid'] = 11;
			$u['securekey'] = $admin['securekey'];
			$u['password'] = $admin['password'];
			$db->set("member-uid-2", $u);
			
			// 生成 public_key 写入文件
			
			!is_dir($conf['upload_path'].'forum') && mkdir($conf['upload_path'].'forum', 0777);
			!is_dir($conf['upload_path'].'avatar') && mkdir($conf['upload_path'].'avatar', 0777);
			!is_dir($conf['upload_path'].'friendlink') && mkdir($conf['upload_path'].'friendlink', 0777);
			!is_dir($conf['upload_path'].'attach') && mkdir($conf['upload_path'].'attach', 0777);
			
			// 清理 cache
			clear_cache($conf['tmp_path'], 'tidcache_');
			clear_cache($conf['tmp_path'], 'tpl_');
			clear_cache($conf['tmp_path'], 'forum_');
			clear_cache($conf['tmp_path'], 'forumlist');
			clear_cache($conf['tmp_path'], 'miscarr_');
			clear_cache($conf['tmp_path'], 'group_');
			clear_cache($conf['tmp_path'], 'grouplist_');
			clear_cache($conf['tmp_path'], 'friendlink_');
			
			is_file($conf['tmp_path'].'new_post_tids.txt') && unlink($conf['tmp_path'].'new_post_tids.txt');
			is_file($conf['tmp_path'].'four_column_cache.js') && unlink($conf['tmp_path'].'four_column_cache.js');
			
			//copy('./digestcate.js', $conf['upload_path'].'digestcate.js');
			
			$clickserverfile = $conf['upload_path'].'click_server.data';
			$fp = fopen($clickserverfile, 'wb');
			fseek($fp, 4000000);
			fwrite($fp, pack("L*", 0x00), 4);
			fclose($fp);
		}
	}
	
	$master = $conf['db'][$type]['master'];
	include './step_4.php';	
	exit;
} elseif($step == '5') {
	// 设置 cookie
	/*
	$user = new user($bbs['conf']);
	$userdb = array('uid'=>1, 'username'=>'admin', 'password'=>'d14be7f4d15d16de92b7e34e18d0d0f7', 'groupid'=>'1');
	$user->set_login_cookie($userdb);
	*/
	header('Content-Type: text/html; charset=UTF-8');
	//include './header.inc.php';	
	echo '<h1>安装完成，点击<a href="../">【跳转到首页】</a>！</h1>';
	echo '<h3>安装完成，为了安全请删除 install 目录</h3><script>setTimeout(function() {window.location="../";}, 3000);</script>';
	//include './footer.inc.php';
	touch($conf['upload_path'].'install.lock');
	exit;
	

	
}elseif($step=='upgrade'){
	
	
	define('FRAMEWORK_PATH', POST_PATH.'xgframe/');
	define('FRAMEWORK_TMP_PATH', $conf['tmp_path']);
	define('FRAMEWORK_LOG_PATH', $conf['log_path']);
	include FRAMEWORK_PATH.'core.php';
	core::init();
	core::ob_start();
	
	// 检测 mysql_connnect, mongodb, pdo 扩展情况
	$mysql_support = function_exists('mysql_connect');
	$mongodb_support = extension_loaded('Mongo');
	$pdo_support = extension_loaded('PDO');
	
	$type = core::gpc('type', 'G');
	empty($type) && $type = 'mysql';

	if(core::gpc('FORM_HASH', 'P')) {
		$host = core::gpc('host', 'P');
		$user = core::gpc('user', 'P');
		$pass = core::gpc('pass', 'P');
		$name = core::gpc('name', 'P');
		$tablepre = core::gpc('tablepre', 'P');
		$adminuser = core::gpc('adminuser', 'P');
		$adminpass = core::gpc('adminpass', 'P');
		$adminpass2 = core::gpc('adminpass2', 'P');
		$error = '';
		if($type == 'mysql') {
			$link = @mysql_connect($host, $user, $pass, TRUE);
			if(!$link) {
				$error = 'MySQL 账号密码可能有误：<span class="small">'.mysql_error().'</span>';
			} else {
				$r = mysql_select_db($name);
				if(mysql_errno() == 1049) {
					mysql_query("CREATE DATABASE $name");
					$r = mysql_select_db($name);
				}
				if(!$r) {
					$error = 'MySQL 账户权限可能受限：<span class="small">'.mysql_error().mysql_errno().'</span>';
				} else {
					$c = array(
						// 主 MySQL Server
						'master' => array (
								'host' => $host,
								'user' => $user,
								'password' => $pass,
								'name' => $name,
								'charset' => 'utf8',
								'tablepre' => $tablepre,
								'engine'=>'MyISAM',
						),
						// 从 MySQL Server
						'slaves' => array (
						)
					);
					//$conf['db']['type'] = 'mysql';
					//$conf['db']['master'] = $c['master'];
					//$conf['db']['slaves'] = $c['slaves'];
					$db = new db_mysql($c);
					
					$s = file_get_contents(POST_PATH.'install/upgrade.sql');
					
					$s = str_replace("\r\n", "\n", $s);
					$s = preg_replace('#\n\#[^\n]*?\n#is', "\n", $s);	// 去掉注释行
					$sqlarr = explode(";\n", $s);
					foreach($sqlarr as $sql) {
						if(trim($sql)) {
							$sql = str_replace('xg_', $tablepre, $sql);
							try {
								$db->query($sql);
							} catch (Exception $e) {
								$error = $e->getMessage();
								break;
							}
						}
					}
					
					$db->truncate('framework_count');
					$db->truncate('framework_maxid');
					
				}
			}
		}
		
		if(!$error) {
			
			// 预设 count maxid
			$db->count('group', 16);
			$db->maxid('group-groupid', 15);
			$db->count('member', 2);
			$db->maxid('member-uid', 10);	// 内置10个账户，方便扩展
			$db->count('forum', 3);
			$db->maxid('forum-fid', 3);
			//$db->count('digestcate', 6);
			//$db->maxid('digestcate-cateid', 6);
			$db->truncate('kv');
			$db->truncate('runtime');
			
			// db 写入配置文件
			$configfile = POST_PATH.'conf/conf.php';
			$replacearr = array('user'=>$user, 'host'=>$host, 'password'=>$pass, 'name'=>$name, 'tablepre'=>$tablepre);
			if($type == 'mysql') {
				file_line_replace($configfile, 18, 30, $replacearr);
			} elseif($type == 'pdo') {
				file_line_replace($configfile, 31, 43, $replacearr);
			} elseif($type == 'mongodb') {
				file_line_replace($configfile, 44, 54, $replacearr);
			}
			$typearr = array('type'=>$type);
			file_line_replace($configfile, 17, 18, $typearr);
			
			$url = misc::get_url_path();
			$public_key = md5(rand(1, 10000000).$_SERVER['ip']);
			$s = file_get_contents($configfile);
			$appurl = substr($url, 0, -8); // 带 /
			$s = preg_replace('#\'app_url\'\s*=\>\s*\'?.*?\'?,#is', "'app_url' => '$appurl',", $s);
			$s = preg_replace('#\'static_url\'\s*=\>\s*\'?.*?\'?,#is', "'static_url' => '$appurl',", $s);
			$s = preg_replace('#\'upload_url\'\s*=\>\s*\'?.*?\'?,#is', "'upload_url' => '{$appurl}upload/',", $s);
			$s = preg_replace('#\'click_server\'\s*=\>\s*\'?.*?\'?,#is', "'click_server' => '{$appurl}clickd/',", $s);
			$s = preg_replace('#\'public_key\'\s*=\>\s*\'?.*?\'?,#is', "'public_key' => '$public_key',", $s);
			$s = preg_replace('#\'installed\'\s*=\>\s*\'?.*?\'?,#is', "'installed' => 1,", $s);
			file_put_contents($configfile, $s);
			
			// 修改密码
			$muser = new member();
			$admin = $db->get("member-uid-1");
			$admin['username'] = $adminuser;
			$admin['groupid'] = 1;
			$admin['securekey'] = rand(100000, 999999);
			$admin['password'] = $muser->md5_md5($adminpass, $admin['securekey']);
			$db->set("member-uid-1", $admin);
			
			$u = $db->get("member-uid-2");
			$u['groupid'] = 11;
			$u['securekey'] = $admin['securekey'];
			$u['password'] = $admin['password'];
			$db->set("member-uid-2", $u);
			
			// 生成 public_key 写入文件
			
			!is_dir($conf['upload_path'].'forum') && mkdir($conf['upload_path'].'forum', 0777);
			!is_dir($conf['upload_path'].'avatar') && mkdir($conf['upload_path'].'avatar', 0777);
			!is_dir($conf['upload_path'].'friendlink') && mkdir($conf['upload_path'].'friendlink', 0777);
			!is_dir($conf['upload_path'].'attach') && mkdir($conf['upload_path'].'attach', 0777);
			
			// 清理 cache
			clear_cache($conf['tmp_path'], 'tidcache_');
			clear_cache($conf['tmp_path'], 'tpl_');
			clear_cache($conf['tmp_path'], 'forum_');
			clear_cache($conf['tmp_path'], 'forumlist');
			clear_cache($conf['tmp_path'], 'miscarr_');
			clear_cache($conf['tmp_path'], 'group_');
			clear_cache($conf['tmp_path'], 'grouplist_');
			clear_cache($conf['tmp_path'], 'friendlink_');
			
			is_file($conf['tmp_path'].'new_post_tids.txt') && unlink($conf['tmp_path'].'new_post_tids.txt');
			is_file($conf['tmp_path'].'four_column_cache.js') && unlink($conf['tmp_path'].'four_column_cache.js');
			
			//copy('./digestcate.js', $conf['upload_path'].'digestcate.js');
			
			$clickserverfile = $conf['upload_path'].'click_server.data';
			$fp = fopen($clickserverfile, 'wb');
			fseek($fp, 4000000);
			fwrite($fp, pack("L*", 0x00), 4);
			fclose($fp);
		}
	}
	
	$master = $conf['db'][$type]['master'];
	include './step_0.php';	
	exit;	
}elseif($step=='upgrade2'){
	define('FRAMEWORK_PATH', POST_PATH.'xgframe/');
	define('FRAMEWORK_TMP_PATH', $conf['tmp_path']);
	define('FRAMEWORK_LOG_PATH', $conf['log_path']);
	include FRAMEWORK_PATH.'core.php';
	core::init();
	core::ob_start();
	$c =include POST_PATH.'conf/conf.php';
	$my=$c['db']['mysql'];
	$db = new db_mysql($my);
	$pre=$c['db']['mysql']['master']['tablepre'];
	$sql="update `{$pre}member` set `groupid`=11 where `uid`> 1";
	$db->query($sql);
	echo "会员组更新完成，即将进入下一步...";
	echo '<script>setTimeout(function() {window.location="?step=upgrade3";}, 3000);</script>';
}elseif($step=='upgrade3'){
	define('FRAMEWORK_PATH', POST_PATH.'xgframe/');
	define('FRAMEWORK_TMP_PATH', $conf['tmp_path']);
	define('FRAMEWORK_LOG_PATH', $conf['log_path']);
	include FRAMEWORK_PATH.'core.php';
	core::init();
	core::ob_start();
	$c =include POST_PATH.'conf/conf.php';
	$db = new db_mysql($c['db']['mysql']);
	$pre=$c['db']['mysql']['master']['tablepre'];
	$page=$_GET['page'];
	$page=$page>0?$page:1;
	$size=200;
	$start=($page-1)*$size;
	$npage=$page+1;
	$list=$db->index_fetch('post_content','pid',array(),array('pid'=>1),($page-1)*$size,$size);

	if(!empty($list)){
		foreach($list as $k=>$v){
			$key="post-pid-$v[pid]";
			$post=$db->get($key);
			$post['message']=html_out($v['message']);
			$db->set($key,$post);
		}
		$end=$start+$size;
		echo "正在更新帖子：$start-至-$end";
		echo '<script>setTimeout(function() {window.location="?step=upgrade3&page='.$npage.'";}, 3000);</script>';
		
	}else{
		$sql="DROP TABLE  `{$pre}post_content`";
		$db->query($sql);
		echo "帖子内容更新完成，即将进入首页..";
	    echo '<script>setTimeout(function() {window.location="../";}, 3000);</script>';
		
	}
	
}
