<?php
if(!defined('MOD'))  die("access die");
$acion = $_GET['acion'] ? $_GET['acion'] : 'modify';
$file = R_P . '/config/options.php';
if($admin_info['groupid'] != 1 ) qbase::purviewCheckDie();
if ($_POST['action'] == 'updateoptions'){
	$_oldset = $_SET;
	$_SET = $_POST['options'];
	foreach($_SET as $key=>$val){
		$_SET[$key] = replace_special($val);
	}
	$failed = array();
	if(($_SET['cache'] == 'apc' && !function_exists('apc_fetch')) || ($_SET['cache'] == 'memache' && !class_exists('Memcache'))){
		unset($_SET['cache']);
		$failed[] = "<p>缓存方式更改失败，服务器不支持该方式</p>";
	}
	$str = qbase::readfromfile($file);	
	while (list($key, $val) = each($_SET)){
		$str = renews_option(trim($key), trim($val), $str);
		qdb::query("replace into ".TABLEPRE."config (g, k, v) values ('option', '{$key}', '{$val}')");
	}
	qbase::writetofile($file, $str);
	if((intval($_SET['homepage_html']) == 0 || $_oldset['homepage_index'] != $_SET['homepage_index']) && is_file(R_P . '/index' . $_oldset['homepage_index'])){
		@unlink(R_P . '/index' . $_oldset['homepage_index']);
		clearstatcache();
	}
	qbase::get_object('event', 'option', array('type'=>'option'));
	$wait = 2;
	if(empty($failed)){
		qbase::showmsg("网站基本配置完毕", "default", "system.php?sys=option&action=modify");
	}else{
		qbase::showmsg(implode('', $failed), "default", "system.php?sys=option&action=modify");
	}
}elseif ($_GET['action'] == 'modify'){
	TemplateSelect();
	$timeoff = GetTimeOff();
	$_SET['weburl'] = 'http://' . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? '' : ':' . $_SERVER['SERVER_PORT']);
	$_SET['abspath'] = substr(dirname(__FILE__), 0, strlen(dirname(__FILE__))-20) ;
	$_SET['webpath'] = substr($_SERVER['SCRIPT_NAME'], 0, -16);
	include qbase::template($path . 'options');
}elseif($_GET['action'] == 'test'){
	$subject = "系统邮件测试";
	$msg = "";
	$mailto = trim(urldecode($_GET['m']));
	$username = 'test';
	$template = R_P . "/config/mail/test.html";
	$param = array(
		'host'=>trim(urldecode($_GET['h'])),
		'port'=>intval($_GET['p']),
		'user'=>trim(urldecode($_GET['u'])),
		'pass'=>trim(urldecode($_GET['pa']))
	);
	$_SET['smtpserver'] = $param['host'];
	$_SET['smtpserverport'] = $param['port'];
	$_SET['smtpuser'] = $param['user'];
	$_SET['smtppass'] = $param['pass'];
	$result = qbase::get_object('sendmail', $username, $mailto)->send($subject, $msg, $template, true);
	if($result === true){
		$status = '<p>邮件发送成功, 测试通过</p>';
		ob_clean();
	}else{
		$msg = ob_get_contents();
		ob_clean();
		$status = '<p>邮件发送失败, 原因如下</p><p>' . $msg . '</p>';
	}
	echo qbase::xmlPrint($status);
}

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);
}
?>