<?php
ob_start();
error_reporting(E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);
@set_magic_quotes_runtime(0);
if(PHP_VERSION < '4.1.0') {
	$_GET = &$HTTP_GET_VARS;
	$_POST = &$HTTP_POST_VARS;
	$_COOKIE = &$HTTP_COOKIE_VARS;
	$_SERVER = &$HTTP_SERVER_VARS;
	$_ENV = &$HTTP_ENV_VARS;
	$_FILES = &$HTTP_POST_FILES;
}
define('R_P', dirname(__FILE__));
define('C_P', R_P . '/cache');
define('T_P', R_P . '/templates/');
include(R_P . '/config/options.php');
include(R_P . '/config/config.php');
define('W_P', $_SET['weburl'].$_SET['webpath']);
define('AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
define('JSONP', (isset($_GET['jsonp']) && intval($_GET['jsonp'])) ? true : false);
define('TABLEPRE', $_SET['tablepre']);
define('QMECMS_CONNECT', 'mysql');
header("Content-Type: text/html; charset={$_SET['def_charset']}");
$magic_quote = get_magic_quotes_gpc();
require_once(R_P . '/include/class.db.php');
require_once(R_P . '/include/inc.functions.php');

$_GET = qbase::saddslashes($_GET);
$_POST = qbase::saddslashes($_POST);
$_FILES = qbase::saddslashes($_FILES);
$_COOKIE = qbase::saddslashes($_COOKIE);


$_SET['weburl'] = 'http://' . $_SERVER['HTTP_HOST'] . ($_SERVER['SERVER_PORT'] == 80 ? '' : ':' . $_SERVER['SERVER_PORT']);
$_SET['webpath'] = substr($_SERVER['SCRIPT_NAME'], 0, -11);

$theurl = 'install.php';
$configfile = R_P .'/config/config.php';
$optionfile = R_P .'/config/options.php';
$lockfile = R_P.'/config/install.lock';
$sqlfile = R_P . '/config/sql.php';

$step = empty($_GET['step'])?0:intval($_GET['step']);
$action = empty($_GET['action'])?'':trim($_GET['action']);
$nowarr = array('','','','','','','');

if(false === qbase::writeable($configfile)) show_msg("文件 $configfile 读写权限设置错误，请设置为可写，再执行安装程序");
if(false === qbase::writeable($optionfile)) show_msg("文件 $optionfile 读写权限设置错误，请设置为可写，再执行安装程序");

if(is_file($lockfile)) {
	show_msg('警告!您已经安装过QmeCMS<br>
		为了保证数据安全，请立即手动删除 install.php 文件<br>
		如果您想重新安装QmeCMS，请删除 config/install.lock 文件，再运行安装文件');
}

if(!function_exists('mysql_connect')){
	show_msg('警告!当前服务器环境不支持mysql，不能安装QmeCMS');
}

if(empty($step)) {

	show_header();
	$param[root] = qbase::writeable(R_P);
	$param[config] = qbase::writeable(R_P . '/config/config.php');
	$param[options] = qbase::writeable(R_P . '/config/options.php');
	$param[config_dir] = qbase::writeable(R_P . '/config/');
	$param[attachment] = qbase::writeable(R_P . '/attachment/');
	if($param[attachment]) $param[attachment] = checkfdperm(R_P . '/attachment/' ,0);
	$param[cache] = qbase::writeable(R_P . '/cache/');
	if($param[cache]) $param[cache] = checkfdperm(R_P . '/cache/' ,0);
	$param[template] = qbase::writeable(R_P . '/templates/');
	if($param[template]) $param[template] = checkfdperm(R_P . '/templates/' ,0);
	$param[admin_template] = qbase::writeable(R_P . '/admin/templates/');
	if($param[admin_template]) $param[template] = checkfdperm(R_P . '/admin/templates/' ,0);
	$status = true;
	foreach($param as $key=>$val){
		if($val){
			$param[$key] = "<font color='green'><strong>√</strong></font>";
		}else{
			$param[$key] = "<font color='red'><strong>×</strong></font>";
			$status = false;
		}
	}
	//安装阅读
	print<<<END
	<table class="showtable" width="100%">
	<tr><td>
	<strong>欢迎您使用QmeCMS</strong><br>
	在您执行安装文件进行安装之前，先要设置相关的目录属性，以便数据文件可以被程序正确读/写/删/创建子目录。<br>
	使用 FTP 软件登录您的服务器，将服务器上以下目录、以及该目录下面的所有文件的属性设置为777，win主机请设置internet来宾帐户可读写属性<br>
	</td></tr>
	</table>

	<table width="100%">
	</td></tr>
	<tr><td>
	<table class="datatable">
	<tr style="font-weight:bold;"><td>名称</td><td>所需权限属性</td><td>说明</td><td>检测结果</td></tr>
	<tr><td><strong>./</strong></td><td>读/写/创建子目录</td><td>创建频道</td><td align='center'>$param[root]</td></tr>
	<tr><td><strong>./config/config.php</strong></td><td>读/写</td><td>数据库配置文件</td><td align='center'>$param[config]</td></tr>
	<tr><td><strong>./config/options.php</strong></td><td>读/写</td><td>系统配置文件</td><td align='center'>$param[options]</td></tr>
	<tr><td><strong>./config/</strong></td><td>读/写</td><td>系统其它的配置</td><td align='center'>$param[config_dir]</td></tr>
	<tr><td><strong>./attachment/</strong> (包括本目录、子目录和文件)</td><td>读/写/删</td><td>附件目录</td><td align='center'>$param[attachment]</td></tr>
	<tr><td><strong>./cache/</strong> (包括本目录、子目录和文件)</td><td>读/写/删</td><td>站点缓存数据目录</td><td align='center'>$param[cache]</td></tr>
	<tr><td><strong>./templates/</strong> (包括本目录、子目录和文件)</td><td>读/写/删</td><td>前台模板目录</td><td align='center'>$param[template]</td></tr>
	<tr><td><strong>./admin/templates/</strong> (包括本目录、子目录和文件)</td><td>读/写/删</td><td>后台模板目录</td><td align='center'>$param[admin_template]</td></tr>
	</table>
	</td></tr>
	</table>
		<table class=button>
	<tr><td>
END;

	if($status == true){
		echo "<input type=\"button\" id=\"sqlsubmit\" name=\"sqlsubmit\"   value=\"没有问题，下一步，继续\" onclick=\"window.location.href='install.php?step=1';\">";
	}else{
		echo "<p>有目录权限未通过检测，请设置好后刷新本页重试</p>";
	}

	echo "</td></tr></table>";

} elseif($step == 1) {

	show_header();
	print<<<END
	<form id="theform" method="post" action="{$theurl}?step=2">

	<table class="showtable">
	<tr><td><strong>设置QmeCMS数据库信息</strong></td></tr>
	<tr><td id="msg1">这里设置QmeCMS的数据库信息</td></tr>
	</table>
	<table class=datatable>
	<tr>
	<td width="25%">数据库服务器本地地址:</td>
	<td><input type="text" name="db[servername]" size="20" value="{$_SET['servername']}"></td>
	<td width="35%">一般为localhost</td>
	</tr>
	<tr>
	<td>数据库用户名:</td>
	<td><input type="text" name="db[dbusername]" size="20" value="{$_SET['dbusername']}"></td>
	<td>&nbsp;</td>
	</tr>
	<tr>
	<td>数据库密码:</td>
	<td><input type="password" name="db[dbpassword]" size="20" value="{$_SET['dbpassword']}"></td>
	<td>&nbsp;</td>
	</tr>
	<tr>
	<td>数据库名:</td>
	<td><input type="text" name="db[dbname]" size="20" value="{$_SET['dbname']}"></td>
	<td>系统不会自动创建数据库，请先创建好</td>
	</tr>
	<tr>
	<td>表名前缀:</td>
	<td><input type="text" name="db[tablepre]" size="20" value="{$_SET['tablepre']}"></td>
	<td>不能为空，默认为qmecms_</td>
	</tr>
	</table>

	<table class=button>
	<tr><td><input type="submit" id="sqlsubmit" name="sqlsubmit" value="设置完毕,检测我的数据库配置"></td></tr>
	</table>
	</form>
END;
	show_footer();

} elseif ($step == 2) {

	//检测数据库账号，密码
	$dbset = $_POST['db'];
	if(!@mysql_connect($dbset['servername'], $dbset['dbusername'], $dbset['dbpassword'])) {
		show_msg('数据库连接信息填写错误，请确认');
	}
	if(!@mysql_select_db($dbset['dbname'])) {
		//试图创建datbase
		if(!@mysql_query("create database {$dbset['dbname']} ")){
			show_msg('设定的QmeCMS数据库无效，请先手工操作后，再执行安装程序');
		}
	} 
	//写配置文件

	foreach($dbset as $key=>$val){
		$_SET[$key] = $val;
	}

	$str = qbase::readfromfile($configfile);	
	foreach($dbset as $key=>$val){
		$str = renews_option(trim($key), trim($val), $str);
	}
	qbase::writetofile($configfile, $str);

	//获取最新的sql文
	$newsql = qbase::readfromfile($sqlfile);

	if($_SET['tablepre'] != 'qmecms_') $newsql = str_replace('qmecms_', $_SET['tablepre'], $newsql);//替换表名前缀

	//获取要创建的表
	$tables = $sqls = array();
	if($newsql) {
		preg_match_all("/(CREATE TABLE ([a-z0-9\_\-`]+).+?\s*)(TYPE|ENGINE)+\=/ies", $newsql, $mathes);
		$sqls = $mathes[1];
		$tables = $mathes[2];
	}

	if(empty($tables)) {
		show_msg("安装SQL语句获取失败，请确认SQL文件 $sqlfile 是否存在");
	}
	$_SET['dbcharset'] = str_replace("-", "", $_SET['def_charset']);

	$myisamtype = qdb::version()>'4.1' ? " ENGINE=MYISAM".(empty($_SET['dbcharset'])?'':" DEFAULT CHARSET=$_SET[dbcharset]" ):" TYPE=MYISAM";
	$installok = true;
	foreach ($tables as $key => $tablename) {
		$tablename = str_replace('`','', $tablename);
		qdb::query("DROP TABLE IF EXISTS `$tablename`");
		if(!$query = qdb::query($sqls[$key].$myisamtype)) {
			$installok = false;
			break;
		}
	}
	
	if(!$installok) {
		show_msg("<font color=\"blue\">数据表 ($tablename) 自动安装失败</font><br />反馈: ".mysql_error()."<br /><br />请参照 $sqlfile 文件中的SQL文，自己手工安装数据库后，再继续进行安装操作<br /><br /><a href=\"?step=$step\">重试</a>");
	} else {
		$_SET['passport_key'] = qbase::random(6);
		$sql = array();
		/*插入初始数据*/
		$sql[] = "replace INTO `{$_SET['tablepre']}channel` 
			(`id`, `channelid`, `channelname`, `channeltitle`, `channelitem`, `channeldir`, `channelselect`, `system`, `show`, `link`, `url`, `is_html`, `is_html_content`, `is_auto`, `close_index`, `istext`, `html_type`, `html_pre`, `html_size`, `CidCacheTime`, `ShowCacheTime`, `allow_upload`, `upload_size`, `upload_type`, `coment_pass`, `pic_width`, `pic_height`, `pic_cut`, `water`, `water_position`, `water_word`, `water_size`, `water_color`, `target`, `skin`, `description`, `displayorder`, `html_date_path`, `show_related`, `show_special`, `show_money`, `show_vote`, `upload_date_path`, `domain`) 
			VALUES 
			(1, 1, '文章', '文章', '篇', 'article', 1, 1, 1, 0, '', 0, 1, 1, 0, 1, '.html', 'qmecms_', 0, 0, 0, 1, 10240, 'rar|zip|exe|gif|jpg|bmp|png|swf|php', 1, 160, 120, 1, 1, 4, '', 20, '#F60F5C', '_self', 'default', '用户服务', 1, 8, 1, 1, 1, 0, 2, ''),
			(2, 2, '下载', '软件', '个', 'download', 2, 1, 1, 0, '', 0, 1, 1, 0, 1, '.html', 'qmecms_', 0, 0, 0, 1, 50000, 'rar|zip|exe|gif|jpg|bmp|png|swf|doc|pdf|txt', 0, 160, 120, 0, 1, 4, '', 12, '', '_self', 'default', '免费版，破解版，绿色版软件下载', 2, 8, 0, 1, 1, 0, 1, ''),
			(3, 3, '图集', '图集', '个', 'picture', 3, 1, 1, 0, '', 0, 1, 0, 0, 0, '.html', 'qmecms_', 0, 0, 0, 1, 5000000, 'rar|zip|exe|gif|jpg|bmp|png|swf', 0, 140, 160, 1, 0, 4, '', 12, '', '_self', 'default', '美女图库', 3, 3, 0, 1, 1, 0, 1, ''),
			(4, 4, '影视', '影视', '部', 'movie', 4, 1, 1, 0, '', 0, 1, 0, 0, 1, '.html', 'qmecms_', 0, 0, 0, 1, 1024, 'gif|jpg|bmp|png|swf|flv|mp4|rm|mp3|wav|mid|midi|ra|avi|mpg|mpeg|asf|asx|wma|mov', 0, 100, 140, 1, 1, 4, '', 20, '#F60F5C', '_self', 'default', '影视', 4, 6, 0, 1, 1, 0, 2, '')
		";
		$sql[] = "replace INTO `{$_SET['tablepre']}comment_filter` 
			(`fid`, `keyword`, `type`, `act`) 
			VALUES 
			(2, '一夜情', 0, 1),
			(3, '[0-9]{5,11}', 1, 0),
			(8, '鲜花', 0, 0),
			(9, '丰胸', 0, 1),
			(10, '翘臀', 0, 1),
			(11, '无码', 0, 1),
			(12, 'A片', 0, 1),
			(13, '做爱', 0, 1),
			(15, '激情', 0, 1),
			(16, '[http:\\/\\/|https:\\/\\/|ftp:\\/\\/]', 1, 0)
		";

		$sql[] = "replace INTO `{$_SET['tablepre']}config` (`g`, `k`, `v`) VALUES
		('option', 'title', 'QmeCMS'),
		('option', 'webpath', '{$_SET['webpath']}'),
		('option', 'abspath', '{$_SET['abspath']}'),
		('option', 'keyword', '网站内容管理系统'),
		('option', 'mail_verify', '1'),
		('option', 'user_verify', '1'),
		('option', 'enablemember', '1'),
		('option', 'skin', 'default'),
		('option', 'cookie_expire', ''),
		('option', 'cookie_domain', ''),
		('option', 'cookie_path', '/'),
		('option', 'from_replace', '台湾|温家宝|法轮功'),
		('option', 'to_replace', ''),
		('option', 'rewrite', '0'),
		('option', 'passport_key', '{$_SET['passport_key']}'),
		('option', 'smtpserver', 'smtp.163.com'),
		('option', 'smtpserverport', '25'),
		('option', 'smtpuser', 'username@163.com'),
		('option', 'smtppass', 'password'),
		('option', 'timezone', '+8'),
		('option', 'weburl', '{$_SET['weburl']}'),
		('option', 'enablecontribute', '1'),
		('option', 'reg_ip', '60'),
		('option', 'comment_cache', '0'),
		('option', 'debug', '1'),
		('option', 'cache', 'file'),
		('author', 'author', '天下无敌\n京华烟云'),
		('author', 'from', '人名日报\n明报\n环球新闻\nCATV\n新京报'),
		('option', 'log', '0'),
		('option', 'comment_guest', '1'),
		('option', 'beian', ''),
		('option', 'homepage_html', '0'),
		('option', 'comment_code', '1'),
		('option', 'trackback', '0'),
		('option', 'login_code', '0'),
		('option', 'reg_code', '1'),
		('option', 'modify_views', '0'),
		('option', 'comment_random_verify', '0'),
		('option', 'doc_link', '0'),
		('option', 'doc_link_show', '0'),
		('option', 'forbidden_upload', 'php|php3|asp|jsp|aspx'),
		('author', 'filter', '头条\n推荐\n图片\n幻灯\n滚动\n特荐'),
		('option', 'admin_verify_code', '111111'),
		('option', 'uc', '0'),
		('option', 'ip_banned', '1'),
		('option', 'homepage_index', '.html'),
		('option', 'admin_path', 'admin'),
		('option', 'auto_filename', '0'),
		('option', 'google_filename', '0'),
		('option', 'comment_self_see', '1')";

		$sql[] = "replace INTO `{$_SET['tablepre']}cron` (`id`, `title`, `name`, `status`, `filter`, `exptime`, `createdate`, `lasttime`) VALUES (1, '定时发送邮件', 'sendmail.php', 1, 'a:4:{s:1:\"m\";s:3:\"*/2\";s:1:\"h\";s:1:\"*\";s:1:\"d\";s:1:\"*\";s:1:\"w\";s:1:\"*\";}', 0, 1273245903, 1285903449),(2, '定时更新浏览数缓存', 'view_update.php', 1, 'a:4:{s:1:\"m\";i:1;s:1:\"h\";s:1:\"*\";s:1:\"d\";s:1:\"*\";s:1:\"w\";s:1:\"*\";}', 0, 1273585813, 1285902102),(3, '定时更新JS文件管理中的JS', 'js_update.php', 1, 'a:4:{s:1:\"m\";i:1;s:1:\"h\";s:3:\"*/4\";s:1:\"d\";s:1:\"*\";s:1:\"w\";s:1:\"*\";}', 0, 1276214352, 1285776082)";
		$sql[] = "replace INTO `{$_SET['tablepre']}module` (`id`, `pid`, `name`, `table_name`, `admin_php`, `user_list_php`, `user_list_last_php`, `user_content_php`, `is_showpage`, `is_lock`, `is_morechannel`, `is_hidden`) VALUES (1, 0, '文章模型', 'article', 'article', 'list', 'list_child', 'show', 1, 0, 1, 0),(2, 0, '下载模型', 'download', 'download', 'list', 'list_child', 'show', 0, 0, 1, 0),(3, 0, '图集模型', 'pic', 'pic', 'list', 'list_child', 'show', 1, 0, 1, 0),(4, 0, '影视模型', 'movie', 'movie', 'list', 'list_child', 'show', 0, 0, 1, 0),(5, 0, '普通专题', 'special', 'special', 'list', '', '', 0, 0, 0, 0)";
		$sql[] = "replace INTO `{$_SET['tablepre']}pic_setting` (`id`, `channelid`, `w`, `h`, `type`, `name`) VALUES (3, 3, 256, 160, 1, '_256'),(1, 3, 64, 40, 1, '_s'),(2, 3, 128, 80, 1, '_128'),(4, 3, 800, 500, 0, '_800')";
		$sql[] = "replace INTO `{$_SET['tablepre']}setting` (`channelid`, `type`, `val`) VALUES (2, 'systems', '2000|2000|1\r\nxp|XP|1\r\n2003|2003|1\r\nvista|Vista|1\r\nnt|NT|1\r\nme|Me|1\r\nwin9x|Win9x\r\nwin7|Win7\r\ndos|DOS\r\nos2|OS2\r\nlinux|Linux'),(2, 'softtype', '0|国外软件\r\n1|国内软件|1\r\n2|汉化软件\r\n3|软件补丁'),(2, 'use_type', '0|收费版\r\n1|共享版\r\n2|免费版|1'),(2, 'language', 'gbk|简体中文|1\r\nbig5|繁体中文\r\nen|英文版\r\nlanguage|多国语言'),(2, 'plugin', 'green|绿色版本|1\r\nno|没有插件\r\nselect|插件可选\r\nforce|强制安装'),(1, 'subject_pre', '1|图文\r\n2|组图\r\n3|注意\r\n4|推荐'),(4, 'play_area', '大陆|大陆\r\n港台|港台\r\n美国|美国\r\n韩国|韩国\r\n日本|日本\r\n英国|英国\r\n法国|法国\r\n其它|其它'),(4, 'subject_pre', '1|大片\r\n2|高清\r\n3|惊艳\r\n4|热剧'),(3, 'subject_pre', '1|美图\r\n2|高清')";
		$sql[] = "replace INTO `{$_SET['tablepre']}ad` (`id`,`name`,`description`,`width`,`num`) values ('1','home_bananer','网站顶部的通栏bananer广告','960','0')";
		$sql[] = "replace INTO `{$_SET['tablepre']}ad_mapping` (`pid`,`id`,`subject`,`type`,`dateline`,`closetime`,`status`,`word`,`src`,`link`,`width`,`height`,`code`,`filter_val`,`filter_type`,`channelid`,`ordering`,`modifytime`) values ('1','1','通栏宣传','img','1286287134','1288843200','1','','http://www.qmecms.com/attachment/money/4K54D9T30I692.jpg','http://www.qmecms.com','960','90','','user.php','1','0','0','1286434831')"; 
		$sql[] = "replace INTO `{$_SET['tablepre']}announcement` (`id`,`channelid`,`title`,`content`,`addtime`) values ('1','0','QmeCMS网站内容管理系统1.0版发布','<h3>QmeCMS介绍</h3>\r\n<ul>\r\n    <li>简单介绍：是一个免费的网站内容管理系统，做网站既快又专业</li>\r\n    <li>功能强大：基于文章，下载，图集，影视模块自由组合，全站可选的生成静态文件</li>\r\n    <li>使用版权：非商业用途完全免费</li>\r\n    <li>商业模式：对技术支持服务进行收费、对网站建设提供个性化定制服务</li>\r\n    <li>系统特点：无技术门槛，简单，易用，美观，实用</li>\r\n</ul>','1286436607')";
		$sql[] = "replace INTO `{$_SET['tablepre']}portal` (`pid`,`p_title`,`p_type`,`p_html`,`p_dateline`,`p_uid`,`p_status`) values ('1','网站首页幻灯片','0','','1286702034','1','1')";
		$sql[] = "replace INTO `{$_SET['tablepre']}portal_mapping` (`id`,`pid`,`uid`,`subject`,`url`,`thumb`,`ordering`,`description`,`subject_color`,`target`,`extdata`) values ('1','1','0','电视剧《雪豹》','http://www.qmecms.com/movie/tv/2010/xuebao-2417.html','http://www.qmecms.com/attachment/support/2010/10/1N3Z073Ei19X.jpg','1','','#FF6600','_blank','')";
		$sql[] = "replace INTO `{$_SET['tablepre']}site` (`id`,`name`,`url`,`description`,`logo`,`pwd`,`status`,`views`,`dateline`,`ordering`) values ('1','QmeCMS内容管理系统','http://www.qmecms.com','QmeCMS - 我们每天都在进步','http://www.qmecms.com/images/logo_qmecms.gif','','1','9','0','1')";
		$sql[] = "replace INTO `{$_SET['tablepre']}votesubject` (`voteid`,`subject`,`type`,`inputer`,`addtime`,`totime`,`passed`,`checkip`) values ('1','你是如何知道QmeCMS的','0','admin','1286708414','1317398400','1','1')";
		$sql[] = "replace INTO `{$_SET['tablepre']}voteoption` (`optionid`,`voteid`,`voteoption`,`number`) values ('1','1','从搜索引擎过来的','0'),('2','1','在论坛上看到的','1'),('3','1','朋友给介绍推荐的','2'),('4','1','无意间闯进来了','0')";

		$sql[] = "INSERT INTO `{$_SET['tablepre']}user_group` (`gid`, `gname`, `point`, `validity`, `type`, `purview`) VALUES
			(1, '待认证会员', 0, 0, 1, ''),
			(2, '普通会员', 10, 0, 1, 'a:5:{s:4:\"post\";i:1;s:5:\"reply\";i:1;s:10:\"upload_ext\";s:0:\"\";s:11:\"upload_size\";s:0:\"\";s:6:\"upload\";i:0;}'),
			(3, '金牌会员', 50, 0, 0, 'a:5:{s:4:\"post\";i:1;s:5:\"reply\";i:1;s:6:\"upload\";i:1;s:10:\"upload_ext\";s:11:\"jpg|png|gif\";s:11:\"upload_size\";s:3:\"300\";}'),
			(4, 'VIP会员', 200, 31536000, 0, 'a:5:{s:4:\"post\";i:1;s:5:\"reply\";i:1;s:6:\"upload\";i:1;s:10:\"upload_ext\";s:19:\"jpg|gif|png|zip|rar\";s:11:\"upload_size\";s:4:\"1024\";}')";

		foreach($sql as $qu){
			qdb::query($qu);
		}

		$_SET['cookie_domain'] = '';
		$_SET['auto_filename'] = '0';
		$_SET['google_filename'] = '0';
		$_SET['doc_link'] = '0';
		$_SET['doc_link_show'] = '0';
		$str = qbase::readfromfile($optionfile);	
		while (list($key, $val) = each($_SET)){
			$str = renews_option(trim($key), trim($val), $str);
		}
		qbase::writetofile($optionfile, $str);
	
		qbase::createdir(R_P . '/article/');
		qbase::createdir(R_P . '/download/');
		qbase::createdir(R_P . '/picture/');
		qbase::createdir(R_P . '/moive/');

		qbase::writetofile(R_P . '/config/friend_link.php', "<?php\n\$_SET['plugin_site_open'] = '1';\n\$_SET['plugin_site_logo'] = '1';\n?>");
		qbase::writetofile(R_P . '/config/guestbook.php', "<?php\n\$_SET['plugin_guestbook_open'] = '1';\n\$_SET['plugin_guestbook_verify'] = '1';\n?>");

		show_msg('数据表已经全部安装完成，进入下一步操作', ($step+1), 1);
	}

} elseif ($step == 3) {

	show_header();
	print<<<END
	<form id="theform" method="post" action="{$theurl}?step=4">

	<table class="showtable">
	<tr><td><strong>设置超级管理员的账号</strong></td></tr>
	<tr><td id="msg1">这里设置QmeCMS的管理员账号，请注意，QmeCMS的后台用户和前台注册用户是分开的</td></tr>
	</table>
	<table class=datatable>
	<tr>
	<td>管理员账号:</td>
	<td><input type="text" name="username" size="20" value=""></td>
	<td>&nbsp;</td>
	</tr>
	<tr>
	<td>管理员密码:</td>
	<td><input type="password" name="password" size="20" value=""></td>
	<td>&nbsp;</td>
	</tr>
	<tr>
	<td>在输入一遍密码:</td>
	<td><input type="password" name="re_password" size="20" value=""></td>
	<td>&nbsp;</td>
	</tr>
	</table>

	<table class=button>
	<tr><td><input type="submit" id="sqlsubmit" name="sqlsubmit" value="设置完毕"></td></tr>
	</table>
	</form>
END;
	show_footer();

} elseif ($step == 4) {

	$username = trim($_POST['username']);
	$password = trim(stripslashes($_POST['password']));
	$re_password = trim(stripslashes($_POST['re_password']));
	if($password != $re_password){
		show_msg("出错了，两次密码输入不一致，请重试", 3, 1);
	}
	$password = md5(md5($password));
	qdb::query("TRUNCATE TABLE {$_SET['tablepre']}admin");
	qdb::query("insert into {$_SET['tablepre']}admin (username, password, groupid ) values ('{$username}', '{$password}', 1)");
	qbase::writetofile($lockfile, "");
	@unlink("index.html");
	show_msg("恭喜你，QmeCMS安装完成！强烈建议您通过FTP删除此安装文件 install.php，点击进入<a href='admin/index.php'>管理后台</a>", 999);
}

//页面头部
function show_header() {
	global $nowarr, $step, $theurl, $_SET;

	$nowarr[$step] = ' class="current"';
	print<<<END
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=$_SET[def_charset]" />
	<title> QmeCMS 程序安装 </title>
	<style type="text/css">
	* {font-size:12px; font-family: Verdana, Arial, Helvetica, sans-serif; line-height: 1.5em; word-break: break-all; }
	body { text-align:center; margin: 0; padding: 0; background: #F5FBFF; }
	.bodydiv { margin: 10px auto 0; width:720px; text-align:left; border: solid #86B9D6; border-width: 5px 1px 1px; background: #FFF; }
	h1 { font-size: 18px; margin: 1px 0 0; line-height: 50px; height: 50px; background: #E8F7FC; color: #5086A5; padding-left: 10px; }
	#menu {width: 100%; margin: 10px auto; text-align: center; }
	#menu td { height: 30px; line-height: 30px; color: #999; border-bottom: 3px solid #EEE; }
	.current { font-weight: bold; color: #090 !important; border-bottom-color: #F90 !important; }
	.showtable { width:100%; border: solid; border-color:#86B9D6 #B2C9D3 #B2C9D3; border-width: 3px 1px 1px; margin: 10px auto; background: #F5FCFF; }
	.showtable td { padding: 3px; }
	.showtable strong { color: #5086A5; }
	.datatable { width: 100%; margin: 10px auto 25px; }
	.datatable td { padding: 5px 0; border-bottom: 1px solid #EEE; }
	input { border: 1px solid #B2C9D3; padding: 5px; background: #F5FCFF; }
	.button { margin: 10px auto 20px; width: 100%; }
	.button td { text-align: center; }
	.button input, .button button { border: solid; border-color:#F90; border-width: 1px 1px 3px; padding: 5px 10px; color: #090; background: #FFFAF0; cursor: pointer; }
	#footer { font-size: 10px; line-height: 40px; background: #E8F7FC; text-align: center; height: 38px; overflow: hidden; color: #5086A5; margin-top: 20px; }
	</style>
	<script type="text/javascript">
	function $(id) {
		return document.getElementById(id);
	}
	</script>
	</head>
	<body id="append_parent">
	<div class="bodydiv">
	<h1>QmeCMS程序安装</h1>
	<div style="width:90%;margin:0 auto;">
	<table id="menu">
	<tr>
	<td{$nowarr[0]}>1.安装开始</td>
	<td{$nowarr[1]}>2.设置数据库连接信息</td>
	<td{$nowarr[2]}>3.创建数据库结构</td>
	<td{$nowarr[3]}>4.设置超级管理员</td>
	<td{$nowarr[4]}>5.安装完成</td>
	</tr>
	</table>
END;
}

//页面顶部
function show_footer() {
	print<<<END
	</div>
	<div id="footer">&copy; QmeCMS. 2010-2020 www.qmecms.com</div>
	</div>
	<br>
	</body>
	</html>
END;
}


//显示
function show_msg($message, $next=0, $jump=0) {
	global $theurl;

	$nextstr = '';
	$backstr = '';

	ob_clean();
	if(empty($next)) {
		$backstr .= "<a href=\"javascript:history.go(-1);\">返回上一步</a>";
	} elseif ($next == 999) {
	} else {
		$url_forward = "$theurl?step=$next";
		if($jump) {
			$nextstr .= "<a href=\"$url_forward\">请稍等...</a><script>setTimeout(\"window.location.href ='$url_forward';\", 1000);</script>";
		} else {
			$nextstr .= "<a href=\"$url_forward\">继续下一步</a>";
			$backstr .= "<a href=\"javascript:history.go(-1);\">返回上一步</a>";
		}
	}

	show_header();
	print<<<END
	<table>
	<tr><td>$message</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>$backstr $nextstr</td></tr>
	</table>
END;
	show_footer();
	exit();
}

//检查权限
function checkfdperm($path, $isfile=0) {
	if($isfile) {
		$file = $path;
		$mod = 'a';
	} else {
		$file = $path.'./install_tmptest.data';
		$mod = 'w';
	}
	if(!@$fp = fopen($file, $mod)) {
		return false;
	}
	if(!$isfile) {
		//是否可以删除
		fwrite($fp, ' ');
		fclose($fp);
		if(!@unlink($file)) {
			return false;
		}
		//检测是否可以创建子目录
		if(is_dir($path.'./install_tmpdir')) {
			if(!@rmdir($path.'./install_tmpdir')) {
				return false;
			}
		}
		if(!@mkdir($path.'./install_tmpdir')) {
			return false;
		}
		//是否可以删除
		if(!@rmdir($path.'./install_tmpdir')) {
			return false;
		}
	} else {
		fclose($fp);
	}
	return true;
}

function renews_option($name, $value, $str)
{ 
	return preg_replace("/\\\$_SET\['" . $name . "'\]\s*\=\s*'.*?';/is", "\$_SET['" . $name . "'] = '" . htmlspecialchars($value) . "';", $str);
}
function replace_special($content){
	$content = preg_replace("/\\n|\\r\\n/", "|", $content);
	return preg_replace("/\'|\"|\$/", "", $content);
}

?>
