<?php
/**
 * Copyright (c) 2003-09  PHPWind.net. All rights reserved.
 *
 * @filename: install.php
 * @author: Noizy Sky_hold 0zz Fengyu Xiaolang Zhudong
 */
error_reporting(E_ERROR | E_PARSE);
@set_magic_quotes_runtime(0);
function_exists('date_default_timezone_set') && date_default_timezone_set('Etc/GMT+0');

$defined_vars = get_defined_vars();
foreach ($defined_vars as $_key => $_value) {
	if (!in_array($_key,array('GLOBALS','_POST','_GET','_COOKIE','_SERVER'))) {
		${$_key} = '';
		unset(${$_key});
	}
}

define('R_P',getdirname(__FILE__));
define('D_P',R_P);

$_POST = (array)$_POST; $_GET = (array)$_GET;
if (!get_magic_quotes_gpc()) {
	Add_S($_POST);
	Add_S($_GET);
}
foreach ($_POST as $_key => $_value) {
	!preg_match('/^\_/',$_key) && ${$_key} = $_POST[$_key];
}
foreach($_GET as $_key => $_value){
	!preg_match('/^\_/',$_key) && ${$_key} = $_GET[$_key];
}

$_WIND			= 'install';
$from_version	= '';
$wind_version	= '7.3.2';
$wind_repair	= '';
$wind_from		= '';//Customized version

!$_SERVER['PHP_SELF'] && $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$selfrpos = strrpos($_SERVER['PHP_SELF'],'/');
$basename = substr($_SERVER['PHP_SELF'],$selfrpos+1);
$bbsurl = 'http://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'],0,$selfrpos);
$crlf = GetCrlf();
$timestamp = time();

require_once(R_P.'lang/install_lang.php');
$stepmsg = $backmsg = $input = $log = $gojs = $gourl = '';
$systitle = $lang['title_install'];
$syslogo = 'install';
if ($step) {
	$stepmsg = $lang["step_$step"];
	$stepleft = $lang["step_{$step}_left"];
	$stepright = $lang["step_{$step}_right"];
}
ob_start();
require_once(R_P.'lang/header.htm');
$steptitle = $step;
file_exists(D_P.'data/install.lock') && Promptmsg('have_file');
$footer = false;
if (in_array($step,array(4,'union','resources','finish','app'))) {
	include_once(D_P.'data/sql_config.php');
	require_once Pcv(R_P."require/db_$database.php");
	$db = new DB($dbhost,$dbuser,$dbpw,$dbname,$pconnect);
	unset($dbhost,$dbuser,$dbpw,$dbname,$pconnect,$manager_pwd);
	//$manager,
}
$step>0 && $step<8 && @unlink(D_P."data/log$step.txt");

//is CE start
$ceversion = '1';
if ($ceversion=='1') {
	$db_windmagic = $writemsg = 0;
} else {
	$db_windmagic = $writemsg = 1;
}
$writemsg = 0;
//is CE end

if (!$step) {
	$footer = true;
	$lang['log_install'] = str_replace('{#basename}',$basename,$lang['log_install']);
	for ($i=1;$i<5;$i++) {
		@unlink(D_P."data/log$i.txt");
	}
} elseif ($step==1) {
	$wind_licence = str_replace(array('  ',"\n"),array('&nbsp; ','<br />'),readover('licence.txt'));
	writeover(D_P.'data/log1.txt',$lang['success_1']);
} elseif ($step==2) {
/**
 * 第二部
 * 1.目錄檢測可寫性和目錄是否存在
 */
	$w_check = array(
		'attachment/',
		'attachment/cn_img/',
		'attachment/photo/',
		'attachment/thumb/',
		'attachment/upload/',
		'attachment/mini/',
		'attachment/mutiupload/',
		'data/',
		'data/bbscache/',
		'data/groupdb/',
		'data/guestcache/',
		'data/tplcache/',
		'data/style/',
		'data/tmp/',
		'htm_data/'
	);
	$writelog = '';
	$fileexist = $writable = array();
	foreach ($w_check as $filename) {
		!N_writable(R_P.$filename) && $writable[] = $filename;
		!file_exists(R_P.$filename) && $fileexist[] = $filename;
		$writelog .= str_replace('{#filename}',$filename,$lang['success_2'])."\n";
	}
	if ($fileexist) {
		$filenames = implode('<br />',$fileexist);
		Promptmsg('error_unfinds');
	}
	if ($writable) {
		$filenames = implode('<br />',$writable);
		Promptmsg('error_777s');
	}
	$phplinfo = PHP_VERSION;
	$mysqlichecked = $mysqlchecked = '';
	if ($phplinfo>='5.1.0') {
		$mysqlichecked = 'CHECKED';
	} else {
		$mysqlchecked = 'CHECKED';
	}
	writeover(D_P.'data/log2.txt',trim($writelog,"\n"));
} elseif ($step==3) {
	/**
	 * 填寫數據庫信息，更新數據庫
	 */
	!$manager_email && Promptmsg('error_nothing');
	$mysqlimsg = '';
	$input = "<input type=\"hidden\" name=\"manager_email\" value=\"$manager_email\">";
	if (!file_exists(D_P.'data/sql_config.php') || $_POST['from']!='prompt') {
		if (!N_writable(D_P.'data/sql_config.php')) {
			$filename = 'data/sql_config.php';
			Promptmsg('error_777');
		}
		if (!$dbhost || !$dbuser || !$dbname || !$PW || !$manager || !$manager_pwd) {
			Promptmsg('error_nothing');
		}
		if ($manager_pwd!==$manager_ckpwd) {
			Promptmsg('error_ckpwd');
		}
		$manager_pwd = md5($manager_pwd);
		$charset = str_replace('-','',$lang['db_charset']);
		require R_P.'require/db_mysql.php';
		$db = new DB($dbhost,$dbuser,$dbpw,'',$pconnect);
		$mysqlinfo = mysql_get_server_info($db->sql);
		if ($database=='mysqli') {
			if ($mysqlinfo<'4.1.3') {
				$database = 'mysql'; $mysqlimsg = $lang['error_mysqli'];
			} else {
				ob_end_clean();
				if (Pwloaddl('mysqli')===false) {
					$database = 'mysql'; $mysqlimsg = $lang['error_mysqli'];
				}
				ob_start();
				require(R_P.'lang/header.htm');
				$steptitle = $step;
			}
		}

		$manager = array($manager); $manager_pwd = array($manager_pwd);
		$newconfig = array(
			'dbhost' => $dbhost,
			'dbuser' => $dbuser,
			'dbpw' => $dbpw,
			'dbname' => $dbname,
			'database' => $database,
			'PW' => $PW,
			'pconnect' => 0,
			'charset' => $charset,
			'manager' => $manager,
			'manager_pwd' => $manager_pwd,
			'db_hostweb' => 1,
			'attach_url' => array()
		);
		require_once(R_P.'require/updateset.php');
		write_config($newconfig); unset($newconfig);

		if ($mysqlinfo>'4.1') {
			mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname` DEFAULT CHARACTER SET $charset");
		} else {
			mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname`");
		}
		if (mysql_errno()) {
			Promptmsg('error_nodatabase');
		} elseif ($query = mysql_query("SELECT COUNT(*) FROM `$dbname`.{$PW}members")) {
			Promptmsg('have_install',3);
		}
		mysql_select_db($dbname);
	} else {
		include D_P.'data/sql_config.php';
		require Pcv(R_P."require/db_$database.php");
		$db = new DB($dbhost,$dbuser,$dbpw,$dbname,$pconnect);
	}

	$t		 = getdate($timestamp+8*3600);
	$tdtime  = (floor($timestamp/3600)-$t['hours'])*3600;
	$lang['db_bbsurl'] = $bbsurl;
	$lang['db_manager'] = $manager[0];
	$content = str_replace(array("\r","\n\n",";\n"),array('',"\n",";<wind>\n"),trim(readover(R_P.'lang/install_wind.sql')," \n"));

	$lang['db_sitemsg'] = preg_replace("/{#(.+?)}/eis",'$lang[\\1]',$lang['db_sitemsg']);
	$lang['db_floorname'] = preg_replace("/{#(.+?)}/eis",'$lang[\\1]',$lang['db_floorname']);
	$content = preg_replace("/{#(.+?)}/eis",'$lang[\\1]',$content).'<wind>';

	$content = explode("\n",$content);
	$writearray = array($lang['success_3']);
	@set_time_limit(200);
	$writearray = SQLCreate($content);

	$userstatus = 0;
	setstatus($userstatus,7);
	setstatus($userstatus,8);

	$db->update("INSERT INTO pw_members (username,password,email,groupid,memberid,regdate,userstatus) VALUES ('$manager[0]','$manager_pwd[0]','$manager_email','3','8','$timestamp','$userstatus')");
	$uid = $db->insert_id();
	$db->update("INSERT INTO pw_memberdata (uid,lastvisit,thisvisit) VALUES ('$uid','$timestamp','$timestamp')");
	$db->update("INSERT INTO pw_bbsinfo (id,newmember,totalmember,tdtcontrol) VALUES ('1','$manager[0]','1','$tdtime')");
	$db->update("INSERT INTO pw_administrators(uid,username,groupid,groups) VALUES('$uid','$manager[0]','3','')");
	$uninstalldb = (array)HackList();
	writeover(D_P.'data/log3.txt',implode("\n",$writearray)."\n$lang[success_3_2]");
} elseif ($step==4) {
	/**
	 * 安裝插件
	 */
	$syscachefile = D_P.'data/install_sys.sql';
	$sqlcache = readover($syscachefile);
	$createcache = '';
	$writearray = $db_hackdb = array();
	if (is_array($hackdb)) {
		$uninstalldb = (array)HackList();
		foreach ($hackdb as $value) {
			if ($uninstalldb[$value][0]) {
				$db_hackdb[$value] = $uninstalldb[$value];
				$createcache .= trim(readover(R_P."hack/$value/sql.txt")," \n")."\n";
			}
		}
		if ($createcache) {
			$createcache = explode("\n",str_replace(array("\r","\n\n",";\n"),array('',"\n",";<wind>\n"),$createcache.'<wind>'));
			if ($createcache) {
				$writearray = SQLCreate($createcache,1);
				$hacksqlcache = readover(D_P.'data/install_hack.sql');
				if ($hacksqlcache) {
					$sqlcache .= $hacksqlcache;
					writeover($syscachefile);
					@unlink(D_P.'data/install_hack.sql');
				}
				$db_hackdb = addslashes(serialize($db_hackdb));
			}
		}
		$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_hackdb','$db_hackdb')");
		$writearray[] = $lang['success_4'];
	}
	$sqlcache && SQLUpdate($sqlcache,$step);
	$writeinto = str_pad('<?die;?>',96)."\n";
	writeover(D_P.'data/bbscache/online.php',$writeinto);
	writeover(D_P.'data/bbscache/guest.php',$writeinto);
	writeover(D_P.'data/bbscache/olcache.php',"<?php\r\n\$userinbbs=1;\r\n\$guestinbbs=0;\r\n?>");
	$writearray = implode('<wind>',$writearray);
	for ($i=1;$i<4;$i++) {
		$log .= readover(D_P."data/log$i.txt")."\n";
	}
	$log = str_replace("\n",'<wind>',$log).$lang['success_4_2'];
} elseif ($step==5) {
	writeover(D_P.'data/log5.txt',"$lang[success_5]");
} elseif ($step=='resources') {
	/**
	 * 生成站點各種位置值，添加默認風格
	 */
	$sqlcache = readover(D_P.'data/install_sys.sql');
	$sqlcache && SQLUpdate($sqlcache,5);
	$steptitle = '!';
	mt_srand((double)microtime()*1000000);

	$rand = '0123%^&*45ICV%^&*B6789qazw~!@#$sxedcrikolpQWER%^&*TYUNM';
	$randlen = strlen($rand);
	for ($i=0;$i<10;$i++) {
		$db_hash .= $rand[mt_rand(0,$randlen)];
	}
	$db_siteid      = generatestr(32);
	$db_siteownerid = generatestr(32);
	$db_sitehash = '10'.SitStrCode(md5($db_siteid.$db_siteownerid),md5($db_siteownerid.$db_siteid));

	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_hash','$db_hash')");
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_windmagic','$db_windmagic')");
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_siteid','$db_siteid')");
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_siteownerid','$db_siteownerid')");
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_sitehash','$db_sitehash')");
	$db->update("REPLACE INTO pw_config(db_name,db_value) VALUES ('db_mode','$db_mode')");//7.3.2 模式選擇
	$db_modes = Array (
					'bbs'	=> array('m_name'	=> '論壇模式','ifopen'	=> 1,'title'	=> '論壇'),
					'area'	=> array('m_name'	=> '門戶模式','ifopen'	=> 1,'title'	=> '門戶'),
					'o'		=> array('m_name'	=> '圈子模式','ifopen'	=> 1,'title'	=> '圈子')
				);
	$db_modes = addslashes(serialize($db_modes));
	$db->update("REPLACE INTO pw_config SET db_name='db_modes',db_value= '$db_modes'");
	$db_modepages = Array ( 'area' => Array ( 'index' => Array ( 'name' => '首頁','template' => 'index' ), 'cate' => Array ( 'name' => '頻道頁','template' => 'cate' ), 'thread' => Array ( 'name' => '列表頁', 'template' => 'thread' ) ), 'o' => Array ( 'index' => Array ( 'name' => '首頁', 'template' => 'index' ), 'm_home' => Array ( 'name' => '動態', 'template' => 'm_home' ) ) );
	$db_modepages = addslashes(serialize($db_modepages));
	$db->update("REPLACE INTO pw_config SET db_name='db_modepages',db_value= '$db_modepages'");
	$db->update("REPLACE INTO pw_config SET db_name='db_ifpwcache',db_value= '567'");

	include_once(D_P.'data/style/wind.php');

	$db->update("REPLACE INTO pw_styles SET sid='1',name='wind',stylepath='$stylepath',tplpath='$tplpath',yeyestyle='$yeyestyle',bgcolor='$bgcolor',linkcolor='$linkcolor',tablecolor='$tablecolor',tdcolor='$tdcolor',tablewidth='$tablewidth',mtablewidth='$mtablewidth',headcolor='$headcolor',headborder='$headborder',headfontone='$headfontone',headfonttwo='$headfonttwo',cbgcolor='$cbgcolor',cbgborder='$cbgborder',cbgfont='$cbgfont',forumcolorone='$forumcolorone',forumcolortwo='$forumcolortwo'");

	require_once(R_P.'require/posthost.php');
	require_once(R_P.'admin/cache.php');
	updatecache_c();

	$log_resources = PostHost('http://u.phpwind.net/install/partner.php',"step=$step&url=$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]");
	if (strpos($log_resources,'<pw_log_resources>') === false) {
		$log_resources = $lang['log_resources'];
	}

	$stepright = $lang['success'];
} elseif ($step==6) {
	$sqlcache && SQLUpdate($sqlcache,$step);
	$host = $bbsurl;
	if ($host && strpos($host,'localhost') === false && strpos($host,'127.0') === false && strpos($host,'127.1') === false && strpos($host,'192.168') === false) {//獲取APP平台分類
		require_once(R_P.'require/posthost.php');

		$data = PostHost("http://app.phpwind.com/pw_app.php?", "action=getclass&", "POST");
		$backdata = substr($data,strpos($data,'$backdata=')+10);
		if (strpos($backdata,'Not Found') !== false) {
			Showmsg('The Interface is not exist');
		}
		if (strpos($backdata,'}') === false) {
			Showmsg($backdata);
		}
		$backdatadb = unserialize(stripslashes($backdata));
	} else {
		$backdatadb = $appinfo;
	}
} elseif ($step=='app') {
	/**
	 * 添加版塊/獲取APP帖子
	 */
	$sqlcache = readover(D_P.'data/install_sys.sql');
	$sqlcache && SQLUpdate($sqlcache,7);
	$steptitle = '!';

	$forum_pa = array('1'=>Char_cv(trim($_POST['forums1']),1),'3'=>$_POST['forums2'],'2'=>Char_cv(trim($_POST['forums3']),1),'4'=>$_POST['forums4']);

	!$_POST['forums1'] && Promptmsg('error_forums1');

	$writelog = '';
	$forum_sql = $forumsdb = array();
	$f = '';
	$n = 0;
	$nums = 0;
	foreach ($forum_pa as $fid => $value) {
		if ($value) {
			if (in_array($fid,array(1,2))) {
				$fup = 0; $childid = 1; $type = 'category'; $f_type = $allowvisit = '';
				$writelog .= str_replace('{#value}',$value,$lang['success_7'])."\n";
				$forum_sql[$fid] = "('$fid','$fup','$childid','$type','$value','3','$allowvisit','$f_type','0','1')";
			} else {
				$childid = 0; $f_type = $type = 'forum';
				$fup = $fid-2;
				$allowvisit = '';

				foreach ($value['name'] as $k =>$val) {
					if ($val) {
						$writelog .= str_replace('{#value}',$val,$lang['success_7'])."\n";
						$forum_sql2[] = "('$fup','$childid','$type','$val','3','$allowvisit','$f_type','0','1')";
						$n++;
						$f .= $f ? ','.$n : $n;
						$forumsdb[$val]['name'] = $val;
						$forumsdb[$val]['cid'] = $value['cid'][$k];
						$forumsdb[$val]['nums'] = $value['nums'][$k];
					}
				}
				foreach ($value['nums'] as $val) {
					$nums += $val;
				}
			}
		}
	}

	$nums > 250 && Promptmsg('app_limit');

	if (!empty($forum_sql)) {
		$db->update('REPLACE INTO pw_forums(fid,fup,childid,type,name,allowtype,allowvisit,f_type,cms,ifhide) VALUES '.implode(',',$forum_sql));
		$db->update("REPLACE INTO pw_forumdata(fid) VALUES ('".implode("'),('",array_keys($forum_sql))."')");
	}
	if (!empty($forum_sql2)) {
		$db->update('REPLACE INTO pw_forums(fup,childid,type,name,allowtype,allowvisit,f_type,cms,ifhide) VALUES '.implode(',',$forum_sql2));
		$fid = $db->insert_id()-1;
		foreach (explode(',',$f) as $v) {
			$fid++;
			$fids[] = "('$fid')";
		}
		$db->update('REPLACE INTO pw_forumdata(fid) VALUES '.implode(',',$fids));
	}

	/*自動注冊+帖子自動插入數據傳遞*/
	$host = $bbsurl;
	if ($host && strpos($host,'localhost') === false && strpos($host,'127.0') === false && strpos($host,'127.1') === false && strpos($host,'192.168') === false) {//本地不執行！

		include D_P.'data/bbscache/config.php';
		require_once(R_P.'require/posthost.php');

		$partner = md5($db_siteid.$db_siteownerid);
		$verify = md5($db_sitehash.$partner.'register');

		$query = $db->query("SELECT fid,name FROM pw_forums WHERE type IN ('forum','sub') ORDER BY fid");
		while ($rt = $db->fetch_array($query)) {
			$forumsdb[$rt['name']]['fid'] = $rt['fid'];
		}

		$app = serialize($forumsdb);
		$data = PostHost("http://app.phpwind.com/pw_app.php?","action=register&sitehash=$db_sitehash&siteid=$db_siteid&siteownerid=$db_siteownerid&manager=$manager[0]&app=$app&host=$host&verify=$verify&","POST");

		$backdata = substr($data,strpos($data,'$backdata=')+10);


		if (strpos($backdata,'Not Found') !== false) {
			Showmsg('The Interface is not exist');
		}
		if (strpos($backdata,'}') === false) {
			Showmsg($backdata);
		}
		$backdatadb = unserialize(stripslashes($backdata));
		$uid = $backdatadb['uid'];
		$username = $backdatadb['username'];
		$pwd = $backdatadb['password'];
		$state = $backdatadb['state'];

		/*自動注冊+帖子自動插入數據傳遞*/
		$lang['app_content1'] = preg_replace("/{#(.+?)}/eis",'$\\1',$lang['app_content1']);
		if ($uid && is_numeric($uid)) {
			$db->pw_update(
				"SELECT db_name FROM pw_config WHERE db_name='db_appuid'",
				"UPDATE pw_config SET db_value=".pwEscape($uid)."WHERE db_name='db_appuid'",
				"INSERT INTO pw_config SET db_name='db_appuid',db_value=".pwEscape($uid)
			);
		}
		if ($state && is_numeric($state)) {
			$db->pw_update(
				"SELECT db_name FROM pw_config WHERE db_name='db_appstate'",
				"UPDATE pw_config SET db_value=0 WHERE db_name='db_appstate'",
				"INSERT INTO pw_config SET db_name='db_appstate',db_value=0"
			);
		}

		//發送短消息
		require_once(R_P.'require/msg.php');
		$msg = array(
			'toUser'	=> $manager['0'],
			'subject'	=> $lang['app_subject'],
			'content'	=> $lang['app_content1']
		);
		pwSendMsg($msg);
		//發送短消息
	}

	writeover(D_P.'data/log7.txt',$writelog.$lang['success_7_2']);
	header("Location: $basename?step=finish");exit;

} elseif ($step=='finish') {

	if ($_GET['app'] == '1') {
		//發送短消息
		require_once(R_P.'require/msg.php');
		$msg = array(
			'toUser'	=> $manager['0'],
			'subject'	=> $lang['app_subject'],
			'content'	=> $lang['app_content2']
		);
		pwSendMsg($msg);
		//發送短消息
	}

	$sqlcache = readover(D_P.'data/install_sys.sql');
	$sqlcache && SQLUpdate($sqlcache,$step);
	$steptitle = '!';
	if (!is_writeable($basename)) {
		$lang['success_install'] .= "<br /><small><font color=\"red\">$lang[error_delinstall]</font></small>";
	}
	$lang['success_install'] = preg_replace("/{#(.+?)}/eis",'$\\1',$lang['success_install']);
	require(R_P.'lang/install.htm');
	require_once(R_P.'admin/cache.php');
	if ($writemsg) {
		require_once(R_P.'require/msg.php');
		$msg = array(
			'toUser'	=> $manager,
			'subject'	=> $lang['log_unionmsgt'],
			'content'	=> $lang['log_unionmsgc']
		);
		pwSendMsg($msg);
	}
	updatecache_cnc();
	updatecache();
	updatemedal_list();

	pwSetVersion('Install','Welcome to PHPWind Forums');

	writeover(D_P.'data/install.lock','LOCKED');
	for ($i=1;$i<8;$i++) {
		@unlink(D_P."data/log$i.txt");
	}
	@unlink(D_P.'data/install_sys.sql');
	@unlink($basename);
	footer();
}
require(R_P.'lang/install.htm');footer();
########################## FUNCTION ##########################
function updatecache_cnc() {
	global $db;
	$classdb = array();
	$query = $db->query('SELECT cid,cname FROM pw_cnclass ORDER BY cid');
	while ($rt = $db->fetch_array($query)) {
		$classdb[$rt['cid']] = $rt['cname'];
	}
	$classdb = serialize($classdb);
	$db->pw_update(
		"SELECT hk_name FROM pw_hack WHERE hk_name='o_classdb'",
		'UPDATE pw_hack SET ' . pwSqlSingle(array('hk_value' => $classdb, 'vtype' => 'array')) . " WHERE hk_name='o_classdb'",
		'INSERT INTO pw_hack SET ' . pwSqlSingle(array('hk_name' => 'o_classdb', 'vtype' => 'array', 'hk_value' => $classdb))
	);
	updatecache_conf('o',true);
}
function pw_var_export($input,$t = null) {
	$output = '';
	if (is_array($input)) {
		$output .= "array(\r\n";
		foreach ($input as $key => $value) {
			$output .= $t."\t".pw_var_export($key,$t."\t").' => '.pw_var_export($value,$t."\t");
			$output .= ",\r\n";
		}
		$output .= $t.')';
	} elseif (is_string($input)) {
		$output .= "'".str_replace(array("\\","'"),array("\\\\","\'"),$input)."'";
	} elseif (is_int($input) || is_double($input)) {
		$output .= "'".(string)$input."'";
	} elseif (is_bool($input)) {
		$output .= $input ? 'true' : 'false';
	} else {
		$output .= 'NULL';
	}
	return $output;
}
function substrs($content,$length,$add='Y'){
	if ($length && strlen($content)>$length) {
		global $db_charset;
		if ($db_charset!='utf-8') {
			$retstr = '';
			for ($i=0;$i<$length-2;$i++) {
				$retstr .= ord($content[$i]) > 127 ? $content[$i].$content[++$i] : $content[$i];
			}
			return $retstr.($add=='Y' ? ' ..' : '');
		}
		return utf8_trim(substr($content,0,$length)).($add=='Y' ? ' ..' : '');
	}
	return $content;
}
function utf8_trim($str) {
	$hex = '';
	$len = strlen($str)-1;
	for ($i=$len;$i>=0;$i-=1) {
		$ch = ord($str[$i]);
		$hex .= " $ch";
		if (($ch & 128)==0 || ($ch & 192)==192) {
			return substr($str,0,$i);
		}
	}
	return $str.$hex;
}
function PwStrtoTime($time){
	global $db_timedf;
	return function_exists('date_default_timezone_set') ? strtotime($time) - $db_timedf*3600 : strtotime($time);
}
function GetLang($lang,$EXT="php"){
	global $tplpath;
	if (file_exists(R_P."template/$tplpath/lang_$lang.$EXT")) {
		return R_P."template/$tplpath/lang_$lang.$EXT";
	} elseif (file_exists(R_P."template/wind/lang_$lang.$EXT")) {
		return R_P."template/wind/lang_$lang.$EXT";
	} else {
		exit("Can not find lang_$lang.$EXT file");
	}
}
function adminmsg(){}
function Showmsg(){}
function Char_cv($msg,$unhtml=null){
	$msg = str_replace(array("\t","\r","\n",'  '),array('','','','&nbsp; '),$msg);
	empty($unhtml) && $msg = str_replace(array('<','>'),array('&lt;','&gt;'),$msg);
	return $msg;
}
function HackList(){
	$hackdb = array();
	if ($fp = opendir(R_P.'hack')) {
		$infodb = array();
		while (($hackdir = readdir($fp))) {
			if (strpos($hackdir,'.')===false) {
				$hackopen = 0;
				$hackname = $hackdir;
				$filedata = readover(R_P."hack/$hackdir/info.xml");
				if (preg_match('/\<hackname\>(.+?)\<\/hackname\>\s+\<ifopen\>(.+?)\<\/ifopen\>/is',$filedata,$infodb)) {
					$infodb[1] && $hackname = Char_cv(str_replace(array("\n"),'',$infodb[1]));
					$hackopen = (int)$infodb[2];
				}
				$hackdb[$hackdir] = array($hackname,$hackdir,$hackopen);
			}
		}
		closedir($fp);
	}
	return $hackdb;
}
function SitStrCode($string,$key,$action='ENCODE'){
	$string	= $action == 'ENCODE' ? $string : base64_decode($string);
	$len	= strlen($key);
	$code	= '';
	for($i=0; $i<strlen($string); $i++){
		$k		= $i % $len;
		$code  .= $string[$i] ^ $key[$k];
	}
	$code = $action == 'DECODE' ? $code : str_replace('=','',base64_encode($code));
	return $code;
}
function generatestr($len) {
	mt_srand((double)microtime() * 1000000);
    $keychars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWYXZ";
	$maxlen = strlen($keychars)-1;
	$str = '';
	for ($i=0;$i<$len;$i++){
		$str .= $keychars[mt_rand(0,$maxlen)];
	}
	return substr(md5($str.microtime().$_SERVER['HTTP_HOST'].$_SERVER['HTTP_USER_AGENT'].$GLOBALS['db_hash']),0,$len);
}
function SQLUpdate($sqlcache,$step) {
	global $db;
	$sqlarray = explode(';<wind>',$sqlcache);
	$count = count($sqlarray);
	if ($count>0) {
		if ($count>50 && (int)$step>0) {
			$cutnum = ceil($count/$step)*($step-1);
			$cutnum<50 && $cutnum=0;
		} else {
			$cutnum = 0;
		}
		$num = 0; $cutcache = '';
		foreach ($sqlarray as $value) {
			if ($value) {
				$lowquery = strtolower(substr($value,0,5));
				if (in_array($lowquery,array('alter','inser','repla'))) {
					if ($cutnum) {
						$num++;
						if ($num>$cutnum) break;
					}
					$cutcache .= "$value;<wind>";
					$db->query($value);
				}
			}
		}
		if ($cutcache) {
			$writedata = str_replace($cutcache,'',$sqlcache);
			writeover(D_P.'data/install_sys.sql',$writedata);
		}
	} else {
		return false;
	}
	return true;
}
function SQLCreate($sqlarray,$hack = null) {
	global $db,$charset,$writearray,$lang;
	$query = $updatesql = '';
	$cachename = empty($hack) ? 'sys' : 'hack';
	foreach ($sqlarray as $value) {
		$value = trim($value," \t");
		if ($value && $value[0]!='#') {
			$query .= $value;
			if (substr($value,-7)==';<wind>') {
				$lowquery = strtolower(substr($query,0,5));
				$checkdrop = CheckDrop($value);
				if (in_array($lowquery,array('drop ','creat'))) {
					if ($cachename=='sys' || $checkdrop) {
						if ($lowquery=='creat') {
							$tablename = trim(substr($query,0,strpos($query,'(')));
							$tablename = substr($tablename,strrpos($tablename,' ')+1);
							$writearray[] = str_replace('{#tablename}',$tablename,$lang['success_3_1']);
							$search = trim(substr(strrchr($value,')'),1));
							$tabtype = substr(strchr($search,'='),1);
							$tabtype = substr($tabtype,0,strpos($tabtype,strpos($tabtype,' ') ? ' ' : ';'));
							if ($db->server_info() >= '4.1') {
								$replace = "ENGINE=$tabtype".($charset ? " DEFAULT CHARSET=$charset" : '').';';
							} else {
								$replace = "TYPE=$tabtype;";
							}
							$query = str_replace(array($search,'<wind>'),array($replace,''),$query);
						} else {
							$query = str_replace('<wind>','',$query);
						}
						$db->query($query);
					}
				} elseif ((in_array($lowquery,array('inser','repla')) && ($cachename=='sys' || $checkdrop)) || ($lowquery=='alter' && $cachename!='sys' && $checkdrop && strpos(strtolower($query),'drop')===false)) {
					$lowquery=='inser' && $query = 'REPLACE '.substr($query,6);
					$updatesql .= $query;
				}
				$query = '';
			}
		}
	}
	$updatesql && writeover(D_P."data/install_$cachename.sql",$updatesql);
	return $writearray;
}
function readover($filename,$method='rb'){
	strpos($filename,'..')!==false && exit('Forbidden');
	$filedata = '';
	if ($handle = @fopen($filename,$method)) {
		flock($handle,LOCK_SH);
		$filedata = @fread($handle,filesize($filename));
		fclose($handle);
	}
	return $filedata;
}
function writeover($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1){
	$check && strpos($filename,'..')!==false && exit('Forbidden');
	touch($filename);
	$handle=@fopen($filename,$method);
	if($iflock){
		flock($handle,LOCK_EX);
	}
	fwrite($handle,$data);
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
	$chmod && @chmod($filename,0777);
}
function Add_S(&$array){
	if (is_array($array)) {
		foreach ($array as $key => $value) {
			if (!is_array($value)) {
				$array[$key] = addslashes($value);
			} else {
				Add_S($array[$key]);
			}
		}
	}
}
function Promptmsg($msg,$tostep=null){
	@extract($GLOBALS, EXTR_SKIP);
	require(R_P.'lang/install_lang.php');
	$lang[$msg] && $msg = $lang[$msg];
	$msg = preg_replace("/{#(.+?)}/eis",'$\\1',$msg);
	$url = $backurl = 'javascript:history.go(-1);';
	$backmsg = !empty($tostep) ? $stepleft : '';
	if (!$backmsg) {
		$lang['last'] = $lang['back'];
		@unlink("log$step.txt");
	} else {
		$url = "document.getElementById('install').submit();";
	}
	require(R_P.'lang/promptmsg.htm');
	footer();
}
function footer(){
	global $footer;
	require_once(R_P.'lang/footer.htm');
	$output = trim(str_replace(array('<!--<!---->','<!---->',"\r",substr(R_P,0,-1)),'',ob_get_contents()),"\n");
	ob_end_clean();
	ob_start();
	echo $output;unset($output);exit;
}
function Pcv($filename,$ifcheck=1){
	$tmpname = strtolower($filename);
	if (strpos($tmpname,'http://')!==false || ($ifcheck && strpos($tmpname,'..')!==false)) {
		exit('Forbidden');
	}
	return $filename;
}
function CheckDrop($query){
	global $db;
	require_once(R_P.'admin/table.php');
	list($pwdb) = N_getTabledb();
	$next = true;
	foreach ($pwdb as $value) {
		if (strpos(strtolower($query),strtolower($value))!==false) {
			$next = false;
			break;
		}
	}
	return $next;
}
function getdirname($path=null){
	if (!empty($path)) {
		if (strpos($path,'\\')!==false) {
			return substr($path,0,strrpos($path,'\\')).'/';
		} elseif (strpos($path,'/')!==false) {
			return substr($path,0,strrpos($path,'/')).'/';
		}
	}
	return './';
}
function GetCrlf(){
	return GetPlatform()=='win' ? "\r\n" : "\n";
}
function GetPlatform(){
	if (strpos($_SERVER['HTTP_USER_AGENT'],'Win')!==false) {
		return 'win';
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'],'Mac')!==false) {
		return 'mac';
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'],'Linux')!==false) {
		return 'linux';
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'],'Unix')!==false) {
		return 'unix';
	} elseif (strpos($_SERVER['HTTP_USER_AGENT'],'OS/2')!==false) {
		return 'os2';
	} else {
		return '';
	}
}
function UserAgentMsg(){
	static $agent,$return;
	if ($agent===$_SERVER['HTTP_USER_AGENT']) {
		return $return;
	}
	$return = array();
	$agent = $_SERVER['HTTP_USER_AGENT'];
	if ($agent) {
		if (preg_match('/Opera(\/| )([0-9]\.[0-9]{1,2})/',$agent,$ver)) {
			$return = array('opera',$ver[2]);
		} elseif (preg_match('/MSIE ([0-9]\.[0-9]{1,2})/',$agent,$ver)) {
			$return = array('ie',$ver[1]);
		} elseif (preg_match('/OmniWeb\/([0-9]\.[0-9]{1,2})/',$agent,$ver)) {
			$return = array('omniweb',$ver[1]);
		} elseif (preg_match('/(Konqueror\/)(.*)(;)/',$agent,$ver)) {
			$return = array('konqueror',$ver[2]);
		} elseif (preg_match('/Firefox\/([0-9]\.[0-9]{1,2})/',$agent,$ver)) {
			$return = array('firefox',$ver[1]);
		} elseif (preg_match('/Chrome\/([0-9]\.[0-9]{1,2})/',$agent,$ver)) {
			$return = array('chrome',$ver[1]);
		} elseif (preg_match('/Safari\/([0-9]*)/',$agent,$ver)) {
			$return = array('safari',$ver[1]);
		} elseif (preg_match('/Mozilla\/([0-9]\.[0-9]{1,2})/',$agent,$ver1)) {
			if (preg_match('/Safari\/([0-9]*)/',$agent,$ver2)) {
				$return = array('safari',$ver1[1].'.'.$ver2[1]);
			} elseif (preg_match('/rv:1\.9(.*)Gecko/',$agent)) {
				$return = array('gecko','1.9');
			} else {
				$return = array('mozilla',$ver[1]);
			}
		} elseif (preg_match('/rv:1\.9(.*)Gecko/',$agent)) {
			$return = array('gecko','1.9');
		} else {
			$return = array('unknown',0);
		}
	}
	return $return;
}
function N_writable($pathfile) {
	//Copyright (c) 2003-09 PHPWind
	//fix windows acls bug
	$isDir = substr($pathfile,-1)=='/' ? true : false;
	if ($isDir) {
		if (is_dir($pathfile)) {
			mt_srand((double)microtime()*1000000);
			$pathfile = $pathfile.'pw_'.uniqid(mt_rand()).'.tmp';
		} elseif (@mkdir($pathfile)) {
			return N_writable($pathfile);
		} else {
			return false;
		}
	}
	@chmod($pathfile,0777);
	$fp = @fopen($pathfile,'ab');
	if ($fp===false) return false;
	fclose($fp);
	$isDir && @unlink($pathfile);
	return true;
}
function Pwloaddl($mod,$ckfunc='mysqli_get_client_info'){//20080714
	return extension_loaded($mod) && $ckfunc && function_exists($ckfunc) ? true : false;
}
function getLangInfo($T,$I,$L=array()) {
	static $lang;
	if (!isset($lang[$T])) {
		require GetLang($T);
	}
	if (isset($lang[$T][$I])) {
		eval('$I="'.addcslashes($lang[$T][$I],'"').'";');
	}
	return $I;
}
function pwEscape($var,$strip = true) {
	if (is_array($var)) {
		foreach ($var as $key => $value) {
			$var[$key] = pwEscape($value,$strip);
		}
		return $var;
	} elseif (is_numeric($var)) {
		return " '".$var."' ";
	} else {
		return " '".addslashes($strip ? stripslashes($var) : $var)."' ";
	}
}
function setstatus(&$status,$b,$setv = '1') {
	--$b;
	for ($i = strlen($setv)-1; $i >= 0 ; $i--) {
		if ($setv[$i]) {
			$status |= 1 << $b;
		} else {
			$status &= ~(1 << $b);
		}
		++$b;
	}
}
function pwSqlSingle($array,$strip=true) {
	//Copyright (c) 2003-09 PHPWind
	$array = pwEscape($array,$strip);
	$str = '';
	foreach ($array as $key => $val) {
		$str .= ($str ? ', ' : ' ').$key.'='.$val;
	}
	return $str;
}
function pwImplode($array,$strip=true) {
	return implode(',',pwEscape($array,$strip));
}
function pwSetVersion($do,$reason='') {//PHPWind history
	global $wind_version,$from_version,$wind_repair,$reason,$timestamp,$db;
	$wind_version = strtoupper($wind_version);
	$from_version = strtoupper($from_version);
	$PHPWind = $db->get_value("SELECT db_value FROM pw_config WHERE db_name='PHPWind'");
	$PHPWind = $PHPWind ? unserialize($PHPWind) : array();
	$PHPWind['version'] && $from_version = $PHPWind['version'];
	$reason || $reason = $from_version == $wind_version ? ($wind_repair ? 'Repair wind' : 'Re-do it again') : "";
	$PHPWind['history'][] = "$do\t$timestamp\t$from_version\t$wind_version,$wind_repair\t$reason";
	$PHPWind['version'] = $wind_version;
	$PHPWind['repair'] = $wind_repair;
	$db->update("REPLACE INTO pw_config (db_name, db_value, decrip) VALUES ('PHPWind',".pwEscape(serialize($PHPWind)).",'PHPWind')");
	//@unlink(D_P.'data/bbscache/version');
	return $PHPWind['version'];
}
function updatemedal_list(){
	global $db;
	$query = $db->query("SELECT uid FROM pw_medaluser GROUP BY uid");
	$medaldb = '<?php die;?>0';
	while ($rt = $db->fetch_array($query)) {
		$medaldb .= ','.$rt['uid'];
	}
	writeover(D_P.'data/bbscache/medals_list.php',$medaldb);
}
?>