<?php
!function_exists('writeover') && exit('Forbidden');
require_once(R_P.'require/pw_func.php');

function updatecache($array='') {
	if (empty($array) || !is_array($array)) {
		updatecache_i(1);
		if(R_P==D_P || !file_exists(D_P.'data/bbscache/config.php')||!file_exists(D_P.'data/bbscache/dbreg.php')){
			updatecache_c();
		}
		updatecache_p(1);
		updatecache_w();
		updatecache_sy();
		updatecache_g();
		updatecache_bk();
		updatecache_df();
		//updatecache_cy();updatecache_conf('o',true);
		updatecache_ol();
		updatecache_mddb(1);
		updatecache_ml();

		updatecache_f(1);
		updatecache_md(1);
		updatecache_l(1);
		updatecache_gr(1);

		updatecache_inv();
		updatecache_plan();
		updatecache_ftp();
		updatecache_field(1);
		updatecache_form();
		updatecache_help();
		cache_read();
		updatecache_hotforum();
		updateStampCache();
		updateBlockCache();
	} else {
		foreach ($array as $value) {
			$value();
		}
	}
}
function updatecache_f($return=0) {
	global $db;
	updatecache_fd();
	$db->update("UPDATE pw_forums SET ifsub='0' WHERE type<3");
	$db->update("UPDATE pw_forums SET ifsub='1' WHERE type>2");

	$query	= $db->query("SELECT f.fid,f.fup,f.ifsub,f.type,f.name,f.style,f.f_type,f.cms,f.ifhide,f.forumtype,fd.aid,fd.aids,fd.aidcache FROM pw_forums f LEFT JOIN pw_forumdata fd ON f.fid=fd.fid ORDER BY f.vieworder,f.fid");
	$catedb = $forumdb = $subdb1 = $subdb2 = $forum_cache = $fname= array();
	while ($forum = $db->fetch_array($query)) {
		$fname[$forum['fid']] = str_replace(array("\\","'",'<','>'),array("\\\\","\'",'&lt;','&gt;'), strip_tags($forum['name']));
		if ($forum['type'] == 'category') {
			$catedb[] = $forum;
		} elseif ($forum['type'] == 'forum') {
			$forumdb[$forum['fup']] || $forumdb[$forum['fup']] = array();
			$forumdb[$forum['fup']][] = $forum;
		} elseif ($forum['type'] == 'sub') {
			$subdb1[$forum['fup']] || $subdb1[$forum['fup']] = array();
			$subdb1[$forum['fup']][] = $forum;
		} else {
			$subdb2[$forum['fup']] || $subdb2[$forum['fup']] = array();
			$subdb2[$forum['fup']][] = $forum;
		}
	}
	$forumcache = '';
	foreach ($catedb as $cate) {
		if (!$cate) continue;
		$forum_cache[$cate['fid']] = $cate;

		if ($cate['cms']) {
			$cmscache .= "<option value=\"$cate[fid]\">>> {$fname[$cate[fid]]}</option>\r\n";
		} elseif ($cate['f_type']!='hidden') {
			$forumcache .= "<option value=\"$cate[fid]\">>> {$fname[$cate[fid]]}</option>\r\n";
		}
		if (!$forumdb[$cate['fid']]) continue;

		foreach ($forumdb[$cate['fid']] as $forum) {
			$forum_cache[$forum['fid']] = $forum;

			if ($forum['cms']) {
				$cmscache .= "<option value=\"$forum[fid]\"> &nbsp;|- {$fname[$forum[fid]]}</option>\r\n";
			} elseif ($forum['f_type']!='hidden') {
				$forumcache .= "<option value=\"$forum[fid]\"> &nbsp;|- {$fname[$forum[fid]]}</option>\r\n";
			}
			if (!$subdb1[$forum['fid']]) continue;

			foreach ($subdb1[$forum['fid']] as $sub1) {
				$forum_cache[$sub1['fid']] = $sub1;

				if ($sub1['cms']) {
					$cmscache .= "<option value=\"$sub1[fid]\"> &nbsp; &nbsp;|-  {$fname[$sub1[fid]]}</option>\r\n";
				} elseif ($sub1['f_type']!='hidden') {
					$forumcache .= "<option value=\"$sub1[fid]\"> &nbsp; &nbsp;|-  {$fname[$sub1[fid]]}</option>\r\n";
				}
				if (!$subdb2[$sub1['fid']]) continue;

				foreach ($subdb2[$sub1['fid']] as $sub2) {
					$forum_cache[$sub2['fid']] = $sub2;

					if ($sub2['cms']) {
						$cmscache .= "<option value=\"$sub2[fid]\">&nbsp;&nbsp; &nbsp; &nbsp;|-  {$fname[$sub2[fid]]}</option>\r\n";
					} elseif ($sub2['f_type']!='hidden') {
						$forumcache .= "<option value=\"$sub2[fid]\">&nbsp;&nbsp; &nbsp; &nbsp;|-  {$fname[$sub2[fid]]}</option>\r\n";
					}
				}
			}
		}
	}
	$forum_cache = "\$forum=".pw_var_export($forum_cache).";";
	$forumcache  = "\$forumcache='\r\n$forumcache';\r\n\$cmscache='\r\n$cmscache';";
	writeover(D_P."data/bbscache/forumcache.php","<?php\r\n".$forumcache."\r\n?>");
	writeover(D_P.'data/bbscache/forum_cache.php',"<?php\r\n".$forum_cache."\r\n?>");
	$cache = $forum_cache."\r\n".$forumcache;
	$db->pw_update(
		"SELECT * FROM pw_cache WHERE name='forum_cache'",
		"UPDATE pw_cache SET cache=".pwEscape($cache,false)." WHERE name='forum_cache'",
		"INSERT INTO pw_cache SET name='forum_cache',cache=".pwEscape($cache,false)
	);
	updateCatedbs();
	if (empty($return)) {
		cache_read();
	}
}
function updatecache_fd() {
	global $db;
	$db->update("UPDATE pw_forums SET childid='0'");
	$havechild = array();
	$fup_a = array(0 => '');
	$query = $db->query("SELECT fid,fup,type,forumadmin,fupadmin FROM pw_forums ORDER BY type");
	while ($rt = $db->fetch_array($query)) {
		if ($rt['fup'] > 0) {
			$havechild[$rt['fup']] = 1;
		}
		$fupadmin = $fup_a[$rt['fup']];
		if ($rt['fupadmin'] != $fupadmin) {
			$db->update("UPDATE pw_forums SET fupadmin=" . pwEscape($fupadmin) . " WHERE fid=" . pwEscape($rt['fid']));
		}
		if ($rt['forumadmin'] = trim($rt['forumadmin'],',')) {
			$fupadmin .= $fupadmin ? $rt['forumadmin'].',' : ','.$rt['forumadmin'].',';
		}
		$fup_a[$rt['fid']] = $fupadmin;
	}
	if ($havechild) {
		$havechilds = pwImplode(array_keys($havechild));
		$db->update("UPDATE pw_forums SET childid='1' WHERE fid IN($havechilds)");
	}
}

/**
* 更新公告緩沖,更新友情聯接緩沖
*/
function updatecache_i($return=0) {
	global $db,$db_windpost,$timestamp;
	//公告部分
	require_once(R_P.'require/bbscode.php');
	@include(D_P.'data/bbscache/forum_cache.php');
	$db->update("UPDATE pw_forumdata SET aid='0',aids='',aidcache='0'");
	$db->update("UPDATE pw_announce SET ifconvert='0' WHERE ifconvert!='0'");
	$num = 0;
	$sharelink = $notice_A = $notice_C = $C_cfid = $F_ffid = $F_fid = $cachedb = $cachetype = $newforum = array();
	$query = $db->query("SELECT aid,fid,author,startdate,enddate,url,subject,content FROM pw_announce WHERE ifopen='1' AND (enddate=0 OR enddate>=".pwEscape($timestamp).") ORDER BY vieworder,startdate DESC");
	while ($rt = $db->fetch_array($query)) {
		if ($rt['fid'] == -1) {
			if ($rt['startdate'] <= $timestamp) {
				$num++;
			} else {
				continue;
			}
			$notice_A[$rt['aid']] = array(
				'aid' => $rt['aid'],
				'author' => $rt['author'],
				'startdate' => $rt['startdate'],
				'enddate' => $rt['enddate'],
				'subject' => $rt['subject'],
				'url' => $rt['url']
			);
		} elseif (!$forum[$rt['fid']]['cms'] && $forum[$rt['fid']]['type']=='category') {
			if ($rt['startdate']<=$timestamp) {
				if ($C_cfid[$rt['fid']]) {
					continue;
				} elseif (!$rt['enddate']) {
					$C_cfid[$rt['fid']] = true;
				}
			}
			$rt['subject'] = substrs($rt['subject'],65);
			$notice_C[$rt['fid']][$rt['aid']] = array(
				'aid' => $rt['aid'],
				'fid' => $rt['fid'],
				'author' => $rt['author'],
				'startdate' => $rt['startdate'],
				'enddate' => $rt['enddate'],
				'subject' => $rt['subject'],
				'url' => $rt['url']
			);
		} elseif ($rt['fid']!=-2) {
			if ($rt['startdate']<=$timestamp) {
				if ($F_ffid[$rt['fid']]) {
					continue;
				} elseif (!$rt['enddate']) {
					$F_ffid[$rt['fid']] = true;
				}
			}
			if (!$F_fid[$rt['fid']]['aid'] && $rt['startdate']<=$timestamp && (!$rt['enddate'] || $rt['enddate']>=$timestamp)) {
				$F_fid[$rt['fid']]['aid'] = $rt['aid'];
				if ($rt['content']!=convert($rt['content'],$db_windpost,2)) {
					$db->update("UPDATE pw_announce SET ifconvert='1' WHERE aid=".pwEscape($rt['aid'],false));
				}
			} else {
				$F_fid[$rt['fid']]['aids'] .= ",$rt[aid]";
			}
		}
	}
	foreach ($forum as $key => $value) {
		$value['aids'] = '';
		$value['aid'] = $value['aidcache'] = 0;
		$update = false;
		if ((int)$F_fid[$key]['aid']>0) {
			$update = true;
			$value['aid'] = $F_fid[$key]['aid'];
		}
		if ($F_fid[$key]['aids']) {
			$update = true;
			$value['aids'] = substr($F_fid[$key]['aids'],1);
			$value['aidcache'] = $timestamp;
		}
		$update && $db->update("UPDATE pw_forumdata SET ".pwSqlSingle(array('aid'=>$value['aid'],'aids'=>$value['aids'],'aidcache'=>$value['aidcache']))."WHERE fid=".pwEscape($key));
		$newforum[$key] = $value;
	}
	//友情鏈接部分
	$sharelogo = $sharetext = '';
	$query = $db->query("SELECT threadorder,name,url,descrip,logo FROM pw_sharelinks WHERE ifcheck=1 ORDER BY threadorder");
	while ($rt = $db->fetch_array($query)) {
		if ($rt['threadorder']<0) {
			$sharelink[0][] = ($rt['logo'] ? "<div class=\"fl\"><a href=\"$rt[url]\"><img src=\"$rt[logo]\" width=\"88\" height=\"31\" /></a></div>" : '')."<div><a href=\"$rt[url]\" target=\"_blank\">$rt[name]</a><br />$rt[descrip]</div>";
		} elseif ($rt['logo']) {
			$sharelogo .= "<a href=\"$rt[url]\" target=\"_blank\"><img src=\"$rt[logo]\" alt=\"$rt[descrip]\" width=\"88\" height=\"31\"></a> ";
		} else {
			$sharetext .= "<a href=\"$rt[url]\" target=\"_blank\" title=\"$rt[descrip]\">[$rt[name]]</a> ";
		}
	}
	if ($sharelogo || $sharetext) {
		$brtags = $sharelogo && $sharetext ? '<br />' : '';
		$sharelink[1] = rtrim($sharelogo).$brtags.rtrim($sharetext);
	} else {
		$sharelink[1] = '';
	}
	//更新系統公告+友情鏈接
	$cachetype['index_cache'] = "\$notice_A=".pw_var_export($notice_A).";\r\n\$sharelink=".pw_var_export($sharelink).";";
	writeover(D_P.'data/bbscache/index_cache.php',"<?php\r\n{$cachetype[index_cache]}\r\n?>");
	//更新分類公告
	$cachetype['thread_announce'] = "\$notice_A=".pw_var_export($notice_A).";\r\n\$notice_C=".pw_var_export($notice_C).";";
	writeover(D_P.'data/bbscache/thread_announce.php',"<?php\r\n{$cachetype[thread_announce]}\r\n?>");
	//更新版規
	if ($newforum != $forum) {
		$cachetype['forum_cache'] = "\$forum=".pw_var_export($newforum).";";
		writeover(D_P.'data/bbscache/forum_cache.php',"<?php\r\n{$cachetype[forum_cache]}\r\n?>");
		@include(D_P.'data/bbscache/forumcache.php');
		$cachetype['forum_cache'] .= "\r\n\$forumcache='".str_replace(array("\\","'"),array("\\\\","\'"),$forumcache)."';\r\n\$cmscache='".str_replace(array("\\","'"),array("\\\\","\'"),$cmscache)."';";
		$sql_in = ",'forum_cache'";
	} else {
		$sql_in = '';
	}
	//更新緩存數據庫
	$query = $db->query("SELECT name FROM pw_cache WHERE name IN('index_cache','thread_announce'$sql_in)");
	while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
		$cachedb[] = $rt[0];
	}
	$db->free_result($query);
	foreach ($cachetype as $key => $value) {
		if (in_array($key,$cachedb)) {
			$db->update("UPDATE pw_cache SET cache=".pwEscape($value,false)."WHERE name=".pwEscape($key,false));
		} else {
			$db->update("INSERT INTO pw_cache SET ".pwSqlSingle(array('name'=>$key,'cache'=>$value)));
		}
	}
	if (empty($return)) {
		cache_read();
	}
}
/**
* 更新用戶組緩沖
*/
function updatecache_g($gid = array()) {
	global $db;
	$sql = '';
	if (!empty($gid) && is_array($gid)) {
		$sql .= ' AND gid IN(' . pwImplode($gid) . ')';
	} elseif (is_numeric($gid)) {
		$sql .= ' AND gid=' . pwEscape($gid);
	} else {
		$sql .= " AND (ifdefault='0' OR gid='1')";
	}
	$gdb	= array();
	$query	= $db->query("SELECT gid,gptype,grouptitle,groupimg,grouppost FROM pw_usergroups WHERE 1 $sql");
	while ($rt = $db->fetch_array($query)) {
		$rt['SYSTEM'] = $rt['_G'] = array();
		$gdb[$rt['gid']] = $rt;
	}
	if (empty($gdb)) {
		return;
	}
	$query	= $db->query("SELECT gid,rkey,type,rvalue FROM pw_permission WHERE uid='0' AND fid='0' AND gid IN(" . (pwImplode(array_keys($gdb))) .")");
	while ($rt = $db->fetch_array($query)) {
		$id = $rt['gid'];
		if (!isset($gdb[$id])) continue;
		if ($rt['type'] == 'basic') {
			$gdb[$id]['_G'][$rt['rkey']] = $rt['rvalue'];
		} elseif ($gdb[$id]['gptype'] == 'special' || $gdb[$id]['gptype']=='system' && $rt['type'] != 'special') {
			$gdb[$id]['SYSTEM'][$rt['rkey']] = $rt['rvalue'];
		}
	}
	foreach ($gdb as $key => $group) {
		updatecache_gp($group);
	}
}

function updatecache_gp($group) {
	$groupcache = '';
	foreach ($group as $key => $value) {
		if (is_array($value)) {
			$groupcache .= "\${$key}=".pw_var_export($value).";\r\n";
		} else {
			$groupcache .= "\$gp_$key=".pw_var_export($value).";\r\n";
		}
	}
	writeover(D_P."data/groupdb/group_$group[gid].php","<?php\r\n".$groupcache."?>");
}
function updatecache_gr($return=0) {
	global $db;
	$gpright = array();
	$query = $db->query("SELECT gid,rkey,rvalue FROM pw_permission WHERE uid='0' AND fid='0' AND rkey IN ('imgwidth','imgheight','fontsize')");
	while ($rt = $db->fetch_array($query)) {
		$gpright[$rt['gid']][$rt['rkey']] = $rt['rvalue'];
	}
	$gpright = "\$gp_right=".pw_var_export($gpright).";";
	writeover(D_P."data/bbscache/gp_right.php","<?php\r\n{$gpright}\r\n?>");
	$cache = $gpright;
	$db->pw_update(
		"SELECT * FROM pw_cache WHERE name='gp_right'",
		"UPDATE pw_cache SET cache=".pwEscape($cache,false)."WHERE name='gp_right'",
		"INSERT INTO pw_cache SET name='gp_right',cache=".pwEscape($cache,false)
	);
	if (empty($return)) {
		cache_read();
	}
}
/**
* 更新用戶等級緩沖
*/
function updatecache_l($return=0) {
	global $db;
	$query = $db->query("SELECT gid,gptype,grouptitle,groupimg,grouppost FROM pw_usergroups ORDER BY grouppost,gid");
	$defaultdb = "\$ltitle=\$lpic=\$lneed=array();\r\n/**\r\n* default\r\n*/\r\n";
	$sysdb = "\r\n/**\r\n* system\r\n*/\r\n";
	$vipdb = "\r\n/**\r\n* special\r\n*/\r\n";
	$memdb = "\r\n/**\r\n* member\r\n*/\r\n";
	while (@extract($db->fetch_array($query))) {
		$gid = (int)$gid;
		if ($gptype == 'member') {
			$memdb .= "\$ltitle[$gid]=".pw_var_export($grouptitle).";\t\t\$lpic[$gid]=".pw_var_export($groupimg). ";\t\t\$lneed[$gid]=".pw_var_export($grouppost).";\r\n";
		} elseif ($gptype == 'special') {
			$vipdb .= "\$ltitle[$gid]=".pw_var_export($grouptitle).";\t\t\$lpic[$gid]=".pw_var_export($groupimg). ";\r\n";
		} elseif ($gptype == 'system') {
			$sysdb .= "\$ltitle[$gid]=".pw_var_export($grouptitle).";\t\t\$lpic[$gid]=".pw_var_export($groupimg). ";\r\n";
		} elseif ($gptype == 'default') {
			$defaultdb .= "\$ltitle[$gid]=".pw_var_export($grouptitle).";\t\t\$lpic[$gid]=". pw_var_export($groupimg).";\r\n";
		}
	}
	writeover(D_P.'data/bbscache/level.php',"<?php\r\n".$defaultdb.$sysdb.$vipdb.$memdb."\r\n?>");
	$cache = $defaultdb.$sysdb.$vipdb.$memdb;
	$db->pw_update(
		"SELECT * FROM pw_cache WHERE name='level'",
		"UPDATE pw_cache SET cache=".pwEscape($cache,false)."WHERE name='level'",
		"INSERT INTO pw_cache SET name='level',cache=".pwEscape($cache,false)
	);
	if (empty($return)) {
		cache_read();
	}
}
/**
* 更新核心設置組緩沖
*/
function updatecache_c() {
	global $db,$db_bbsurl,$db_mode;
	$query = $db->query("SELECT db_name,db_value FROM pw_config");
	$configdb = $regdb = "<?php\r\n";
	while (@extract($db->fetch_array($query))) {
		$db_name = key_cv($db_name);
		if (in_array($db_name, array('db_hackdb','db_question','db_answer','db_questions','db_shortcutforum', 'rg_regcredit','db_windpost','db_windreply','db_windpic','db_creditlog','db_creditpay','db_styledb','db_sellset','db_enhideset','db_modepages','db_modes','db_modedomain','db_bbstitle','db_floorname','db_sitemsg','db_headnav','db_footnav'))) {
			if (!is_array($db_value = unserialize($db_value))) {
				$db_value = array();
			}
		}
		if (strpos($db_name,'db_') !== false) {
			$configdb .= "\$$db_name=".pw_var_export($db_value).";\r\n";
		} elseif (strpos($db_name,'rg_') !== false) {
			$regdb .= "\$$db_name=".pw_var_export($db_value).";\r\n";
		}
	}
	$creditdb = $advertdb = array();
	$query	  = $db->query("SELECT * FROM pw_modules WHERE type=6 AND state=1 ORDER BY vieworder");
	while($rt = $db->fetch_array($query)){
		$ad   = array();
		$code = $style = '';
		$conf = unserialize($rt['config']);
		if ($conf['style'] == 'code') {
			$code = $conf['htmlcode'];
		} elseif ($conf['style'] == 'txt') {
			if ($conf['color']) {
				$style .= "color:$conf[color];";
			}
			if ($conf['size']) {
				$style .= "font-size:$conf[size];";
			}
			if ($style) {
				$style = " style=\"$style\"";
			}
			if ($rt['ifhire'] == 1) {
				$conf['link'] = $db_bbsurl."/hack.php?H_name=advert&action=ajax&id=".$rt['id'];
				$code = "<a style=\"cursor:pointer\" onclick=\"sendmsg('hack.php?action=ajax&id=$rt[id]','H_name=advert');\"{$style}>$conf[title]</a>";
			} else {
				$code = "<a href=\"$conf[link]\" target=\"_blank\"{$style}>$conf[title]</a>";
			}
		} elseif ($conf['style'] == 'img') {
			if ($conf['width']) {
				$style .= " width=\"$conf[width]\"";
			}
			if ($conf['height']) {
				$style .= " height=\"$conf[height]\"";
			}
			if ($conf['descrip']) {
				$style .= " alt=\"$conf[descrip]\"";
			}
			if ($rt['ifhire'] == 1) {
				$conf['link'] = $db_bbsurl."/hack.php?H_name=advert&action=ajax&id=".$rt['id'];
				$code = "<a style=\"cursor:pointer\" onclick=\"sendmsg('hack.php?action=ajax&id=$rt[id]','H_name=advert')\";><img src=\"$conf[url]\"{$style}></a>";
			} else {
				$code = "<a href=\"$conf[link]\" target=\"_blank\"><img src=\"$conf[url]\"{$style}></a>";
			}
		} elseif ($conf['style'] == 'flash') {
			if ($conf['width']) {
				$style .= " width=\"$conf[width]\"";
			}
			if ($conf['height']) {
				$style .= " height=\"$conf[height]\"";
			}
			if ($rt['ifhire'] == 1) {
				$code = "<a style=\"cursor:pointer\" onclick=\"sendmsg('hack.php?action=ajax&id=$rt[id]','H_name=advert')\";><img src=\"$conf[link]\"{$style}></a>";
			} else {
				$code = "<embed{$style} src=\"$conf[link]\" type=\"application/x-shockwave-flash\"></embed>";
			}
		}
		if ($rt['varname'] == 'popup') {
			$conf['height']= (int) $conf['height'];
			$conf['width'] = (int) $conf['width'];
			$conf['close'] = (int) $conf['close'];
			$code = array($conf['title'],$code,$conf['height'],$conf['width'],$conf['close']);
		} elseif ($rt['varname'] == 'article') {
			$ad['lou']		= $conf['lou'];
			$ad['position'] = $conf['position'];
		}
		$ad['starttime'] = PwStrtoTime($conf['starttime']);
		$ad['endtime']	 = PwStrtoTime($conf['endtime']);
		$ad['fid']		 = $conf['fid'];
		$ad['descrip']	 = $conf['descrip'];
		$ad['link']	     = $conf['link'];
		$ad['code']		 = $code;
		if ($rt['ifhire']) {
			$ad['ifhire'] = $rt['ifhire'];
		}
		$advertdb[$rt['varname']][] = $ad;
	}
	$configdb .= "\$db_advertdb=".pw_var_export($advertdb).";\r\n";

	$query = $db->query("SELECT * FROM pw_credits");
	while ($rt = $db->fetch_array($query)) {
		$creditdb[$rt['cid']] = array($rt['name'],$rt['unit'],$rt['description']);
	}
	$configdb .= "\$_CREDITDB=".pw_var_export($creditdb).";\r\n?>";
	$regdb .= "?>";
	writeover(D_P.'data/bbscache/config.php',$configdb);
	writeover(D_P.'data/bbscache/dbreg.php',$regdb);
}

/**
* 更新風格緩沖
*/
function updatecache_sy($name='') {
	global $db,$db_picpath;
	$imgpath = '../../'.$db_picpath;
	$sqlwhere = "WHERE uid=0 ";
	if ($name) {
		$sqlwhere .= " AND name=".pwEscape($name);
	}
	$query = $db->query("SELECT * FROM pw_styles $sqlwhere");
	while (@extract($db->fetch_array($query))) {
		$stylecontent = "<?php
\$stylepath = ".pw_var_export($stylepath).";
\$tplpath = ".pw_var_export($tplpath).";
\$yeyestyle = ".pw_var_export($yeyestyle).";
\$bgcolor = ".pw_var_export($bgcolor).";
\$linkcolor = ".pw_var_export($linkcolor).";
\$tablecolor = ".pw_var_export($tablecolor).";
\$tdcolor = ".pw_var_export($tdcolor).";
\$tablewidth = ".pw_var_export($tablewidth).";
\$mtablewidth = ".pw_var_export($mtablewidth).";
\$headcolor	= ".pw_var_export($headcolor).";
\$headborder = ".pw_var_export($headborder).";
\$headfontone = ".pw_var_export($headfontone).";
\$headfonttwo = ".pw_var_export($headfonttwo).";
\$cbgcolor = ".pw_var_export($cbgcolor).";
\$cbgborder = ".pw_var_export($cbgborder).";
\$cbgfont = ".pw_var_export($cbgfont).";
\$forumcolorone	= ".pw_var_export($forumcolorone).";
\$forumcolortwo	= ".pw_var_export($forumcolortwo).";
\$extcss = ".pw_var_export($extcss).";
\?>";
		$style_css = explode('<!--css-->',readover(D_P."data/style/{$tplpath}_css.htm"));
		$style_css = addslashes(str_replace(array('<style type="text/css">','</style>'),'',$style_css[1]));
		eval("\$style_css = \"$style_css\";");
		writeover(D_P."data/bbscache/$tplpath.css",$style_css);
		writeover(D_P."data/style/$name.php",str_replace("\?>","?>",$stylecontent));
		$sqlStyles[] = $name;
	}
	if (empty($name)) {
		$fp = opendir(D_P."data/style/");
		while ($skinfile = readdir($fp)) {
			if (eregi("\.php$",$skinfile)) {
				$skinfile = str_replace(".php","",$skinfile);
				$styles[] = $skinfile;
			}
		}
		closedir($fp);
		foreach ($styles as $key => $value) {
			if (!in_array($value,$sqlStyles)) {
				include Pcv(D_P."data/style/$value.php");
				$style_css = explode('<!--css-->',readover(D_P."data/style/{$tplpath}_css.htm"));
				$style_css = addslashes(str_replace(array('<style type="text/css">','</style>'),'',$style_css[1]));
				eval("\$style_css = \"$style_css\";");
				writeover(D_P."data/bbscache/$tplpath.css",$style_css);
			}
		}
	}
}
/**
* 更新動作表情緩沖
*/
function updatecache_p($return=0) {
	global $db;
	$faces		= "\$faces=array(\r\n"; //表情組
	$face		= "\$face=array(\r\n"; //表情
	$jsface		= "var face=new Array();\n";
	$jsfaces	= "var faces=new Array();\n";
	$jsfacedb	= "var facedb=new Array();\n";

	$count = 0;
	@extract($db->get_one("SELECT db_value AS fc_shownum FROM pw_config WHERE db_name='fc_shownum'"));
	$rs = $db->query("SELECT * FROM pw_smiles WHERE type=0 ORDER BY vieworder");
	while (@extract(db_cv($db->fetch_array($rs)))) {
		if ($count == 0) {
			$jsdefault="var defaultface='$path';\nvar fc_shownum='$fc_shownum';\n\n";
			$count = 1;
		}
		$faces		.= "\t'$path'=>array(\r\n";
		$faces		.= "\t\t'name'=>'$name',\r\n";
		$faces		.=  "\t\t'child'=>array(";
		$jsfaces	.= "faces['$path'] = [";
		$jsfacedb	.= "facedb['$path'] = '$name';\n";
		$query = $db->query("SELECT * FROM pw_smiles WHERE type='$id' ORDER BY vieworder");
		while ($smile = db_cv($db->fetch_array($query))) {
			$face	.= "\t'$smile[id]'=>array('$path/$smile[path]','$smile[name]','$smile[descipt]'),\r\n";
			$faces	.= "'$smile[id]',";
			$jsface	.= "face[$smile[id]]=['$path/$smile[path]','$smile[name]'];\n";
			$jsfaces.= "$smile[id],";
		}
		$faces		.= "),\r\n";
		$faces		.= "\t),\r\n";
		$jsfaces	.= "];\n";
	}
	$faces	.= ");\r\n";
	$face	.= ");";
	writeover(D_P."data/bbscache/face.js",$jsdefault.$jsfacedb."\n".$jsface."\n".$jsfaces);
	writeover(D_P."data/bbscache/postcache.php","<?php\r\n".$faces.$face."\r\n?>");

	$cache = $faces.$face;
	$db->pw_update(
		"SELECT * FROM pw_cache WHERE name='postcache'",
		"UPDATE pw_cache SET cache=".pwEscape($cache,false)."WHERE name='postcache'",
		"INSERT INTO pw_cache SET name='postcache',cache=".pwEscape($cache,false)
	);
	if (empty($return)) {
		cache_read();
	}
}
/**
* 更新禁用詞語緩沖
*/
function updatecache_w() {
	global $db;
	$writeinfo = "<?php";
	$replace = $wordsfb = $alarm = $pwcode  = array();
	$query = $db->query("SELECT * FROM pw_wordfb");
	while (@extract($db->fetch_array($query))) {
		if ($word) {
			$word = preg_quote($word,'/');
			if ($type == 0) {
				$replace[$word] = $wordreplace;
			} elseif ($type==1) {
				$wordsfb[$word] = $wordreplace;
			} else {
				$alarm[$word] = $wordreplace;
			}
		}
	}
	$regxp = array('([^\(&]+?)','(\w+)','(\d+)');
	$query = $db->query("SELECT name,pattern,replacement,param FROM pw_windcode");
	while (@extract($db->fetch_array($query))) {
		list($o,$t,$s) = explode("\t",$pattern);
		$name = preg_quote($name,'/');
		if ($param == 2) {
			$pwcode['searcharray'][] = "/\[$name=$regxp[$o]\]$regxp[$t]\[\/$name\]/is";
		} elseif ($param == 3) {
			$pwcode['searcharray'][] = "/\[$name=$regxp[$o],$regxp[$t]\]$regxp[$s]\[\/$name\]/is";
		} else {
			$pwcode['searcharray'][] = "/\[$name\]$regxp[$o]\[\/$name\]/is";
		}
		$pwcode['replacearray'][] = preg_replace('/\{(\d+)\}/i','\\\\\\1',$replacement);
	}
	$writeinfo .= "\r\n\$replace=".pw_var_export($replace).";";
	$writeinfo .= "\r\n\$wordsfb=".pw_var_export($wordsfb).";";
	$writeinfo .= "\r\n\$alarm=".pw_var_export($alarm).";";
	$writeinfo .= "\r\n\$pwcode=".pw_var_export($pwcode).";";
	writeover(D_P."data/bbscache/wordsfb.php",$writeinfo."\r\n?>");
}
function updatecache_bk() {
	global $db;
	$query=$db->query("SELECT * FROM pw_hack WHERE hk_name LIKE 'bk_%'");
	$configdb="<?php\r\n";
	while (@extract($db->fetch_array($query))) {
		$hk_name = key_cv($hk_name);
		$configdb.="\$$hk_name=".pw_var_export($hk_value).";\r\n";
	}
	$configdb.="?>";
	writeover(D_P.'data/bbscache/bk_config.php',$configdb);
}
function updatecache_df() {
	global $db;
	$query = $db->query("SELECT * FROM pw_config WHERE db_name LIKE 'df_%'");
	$configdb = "<?php\r\n";
	$_cachedb = $_newdb = $_cmsdb = $_fiddb = $_forumlogodb = array();

	while (@extract($db->fetch_array($query))) {
		$db_name = key_cv($db_name);
		if ($db_name == 'df_cache') {
			$db_value = P_unserialize($db_value);
			if (is_array($db_value)) {
				foreach ($db_value as $key=>$value) {
					$_cachedb[$key] = array(trim($value[0]),trim($value[1]));
				}
			}
		} elseif ($db_name == 'df_NEW') {
			$db_value = P_unserialize($db_value);
			if (is_array($db_value)) {
				foreach ($db_value as $value) {
					$_newdb[] = $value;
				}
			}
		} elseif ($db_name=='df_CMS') {
			$db_value = P_unserialize($db_value);
			if (is_array($db_value)) {
				foreach ($db_value as $value) {
					$_cmsdb[] = $value;
				}
			}
		} elseif ($db_name=='df_FID') {
			$db_value = P_unserialize($db_value);
			if (is_array($db_value)) {
				foreach ($db_value as $value) {
					$_fiddb[] = $value;
				}
			}
		} elseif ($db_name=='df_forumlogo') {
			$db_value = P_unserialize($db_value);
			if (is_array($db_value)) {
				foreach($db_value as $key => $value){
					if ($value[0]) {
						$_forumlogodb[$key] = array($value[0],$value[1],$value[2],$value[3]);
					}
				}
			}
		} else {
			$configdb .= "\$$db_name=".pw_var_export($db_value).";\r\n";
		}
	}
	$configdb .= "\r\n\$df_cache=".pw_var_export($_cachedb).";\r\n";
	$configdb .= "\r\n\$df_NEW=".pw_var_export($_newdb).";\r\n";
	$configdb .= "\r\n\$df_CMS=".pw_var_export($_cmsdb).";\r\n";
	$configdb .= "\r\n\$df_FID=".pw_var_export($_fiddb).";\r\n";
	$configdb .= "\r\n\$df_forumlogo=".pw_var_export($_forumlogodb).";\r\n";
	$configdb .= "?>";
	writeover(D_P.'data/bbscache/c_config.php',$configdb);
}
/*
function updatecache_cy() {
	global $db;
	$query = $db->query("SELECT * FROM pw_hack WHERE hk_name LIKE 'cn\_%'");
	$colonydb = "<?php\r\n";
	while (@extract($db->fetch_array($query))) {
		$hk_name = key_cv($hk_name);
		$colonydb .= "\$$hk_name=".pw_var_export($hk_value).";\r\n";
	}
	$colonydb .= "\n?>";
	writeover(D_P.'data/bbscache/cn_config.php', $colonydb);
}
*/
function updatecache_inv() {
	global $db;
	$query = $db->query("SELECT * FROM pw_hack WHERE hk_name LIKE 'inv_%'");
	$invdb = "<?php\r\n";
	while (@extract($db->fetch_array($query))) {
		$hk_name = key_cv($hk_name);
		$invdb .="\$$hk_name=".pw_var_export($hk_value).";\r\n";
	}
	$invdb .="\n?>";
	writeover(D_P.'data/bbscache/inv_config.php', $invdb);
}
function updatecache_ol() {
	global $db;
	$onlinedb = "<?php\r\n";
	$query = $db->query("SELECT * FROM pw_config WHERE db_name LIKE 'ol_%'");
	while (@extract($db->fetch_array($query))) {
		$db_name   = key_cv($db_name);
		$onlinedb .= "\$$db_name=".pw_var_export($db_value).";\r\n";
	}
	$onlinedb .= "?>";
	writeover(D_P.'data/bbscache/ol_config.php',$onlinedb);
}
function updatecache_md($return=0) {
	global $db;
	$medaldb='';
	$query = $db->query("SELECT * FROM pw_hack WHERE hk_name LIKE 'md\_%'");
	while (@extract($db->fetch_array($query))) {
		$hk_name = key_cv($hk_name);
		$medaldb.="\$$hk_name=".pw_var_export($hk_value).";\r\n";
	}
	writeover(D_P.'data/bbscache/md_config.php',"<?php\r\n".$medaldb."\r\n?>");
	$cache = $medaldb;
	$db->pw_update(
		"SELECT * FROM pw_cache WHERE name='md_config'",
		"UPDATE pw_cache SET cache=".pwEscape($cache,false)."WHERE name='md_config'",
		"INSERT INTO pw_cache SET name='md_config',cache=".pwEscape($cache,false)
	);
	if (empty($return)) {
		cache_read();
	}
}
function updatecache_mddb($return=0) {
	global $db;
	$medaldb = array();
	$query = $db->query("SELECT * FROM pw_medalinfo ORDER BY id");
	while ($rt = $db->fetch_array($query)) {
		$medaldb[$rt['id']] = $rt;
	}
	$medaldb = "\$_MEDALDB=".pw_var_export($medaldb).";";
	writeover(D_P.'data/bbscache/medaldb.php',"<?php\r\n".$medaldb."\r\n?>");
	$cache = $medaldb;
	$db->pw_update(
		"SELECT * FROM pw_cache WHERE name='medaldb'",
		"UPDATE pw_cache SET cache=".pwEscape($cache,false)."WHERE name='medaldb'",
		"INSERT INTO pw_cache SET name='medaldb',cache=".pwEscape($cache,false)
	);
	if (empty($return)) {
		cache_read();
	}
}
function updatecache_plan() {
	global $db;
	$plandb = $plantime = array();
	$query = $db->query("SELECT id,month,week,day,hour,nexttime,filename FROM pw_plan WHERE ifopen='1' ORDER BY id");
	while ($rt = $db->fetch_array($query)) {
		$plantime[] = $rt['nexttime'];
		$plandb[$rt['id']] = $rt;
	}
	writeover(D_P.'data/bbscache/plandb.php',"<?php\r\n\$plandb=".pw_var_export($plandb).";\r\n?>");
	rsort($plantime);
	$plantime = array_pop($plantime);
	$db->update("UPDATE pw_bbsinfo SET plantime=".pwEscape($plantime,false)."WHERE id='1'");
}
function updatecache_conf($m,$hk = false,$filename = '') {
	global $db;
	if ($hk) {
		$sql = "SELECT hk_name AS name,vtype,hk_value AS value FROM pw_hack WHERE hk_name LIKE '{$m}\_%'";
	} else {
		$sql = "SELECT db_name AS name,vtype,db_value AS value FROM pw_config WHERE db_name LIKE '{$m}\_%'";
	}
	!$filename && $filename = $m.'_config.php';
	$confdb	= '';
	$query	= $db->query($sql);
	while (@extract($db->fetch_array($query))) {
		$name = key_cv($name);
		if ($vtype == 'array' && !is_array($value = unserialize($value))) {
			$value = array();
		}
		$confdb	.= "\$$name=" . pw_var_export($value) . ";\r\n";
	}
	writeover(D_P."data/bbscache/$filename","<?php\r\n".$confdb."?>");
}
function updatecache_ml() {
	global $db;
	$maildb	= '';
	$query	= $db->query("SELECT * FROM pw_config WHERE db_name LIKE 'ml\_%'");
	while (@extract($db->fetch_array($query))) {
		$db_name = key_cv($db_name);
		$maildb	.= "\$$db_name=".pw_var_export($db_value).";\r\n";
	}
	writeover(D_P.'data/bbscache/mail_config.php',"<?php\r\n".$maildb."?>");
}
function updatecache_ftp() {
	global $db;
	$ftpdb	= '';
	$query	= $db->query("SELECT * FROM pw_config WHERE db_name LIKE 'ftp\_%'");
	while (@extract($db->fetch_array($query))) {
		$db_name = key_cv($db_name);
		$ftpdb	.= "\$$db_name=".pw_var_export($db_value).";\r\n";
	}
	writeover(D_P.'data/bbscache/ftp_config.php',"<?php\r\n".$ftpdb."?>");
}
function updatecache_field($return=0) {
	global $db;
	$customfield = array();
	$query = $db->query("SELECT * FROM pw_customfield WHERE state='1' ORDER BY vieworder");
	while ($rt = $db->fetch_array($query)) {
		$customfield[] = $rt;
	}
	$cachedb = "\$customfield=".pw_var_export($customfield).";";
	writeover(D_P.'data/bbscache/customfield.php',"<?php\r\n".$cachedb."\r\n?>");
	$cache = $cachedb;
	$db->pw_update(
		"SELECT * FROM pw_cache WHERE name='customfield'",
		"UPDATE pw_cache SET cache=".pwEscape($cache,false)."WHERE name='customfield'",
		"INSERT INTO pw_cache SET name='customfield',cache=".pwEscape($cache,false)
	);
	if (empty($return)) {
		cache_read();
	}
}
function updatecache_form() {
	global $db;
	$rs = $db->query("SELECT id,name,value FROM pw_setform WHERE ifopen='1'");
	$setform = "<?php\n\$setformdb=array(\n";
	while ($rt = $db->fetch_array($rs)) {
		$rt['value'] = unserialize($rt['value']);
		$setformdb[$rt['id']] = $rt;
	}
	$setformdb = "\$setformdb=".pw_var_export($setformdb).";\r\n";
	writeover(D_P.'data/bbscache/setform.php',"<?php\r\n".$setformdb."?>");
}
function updatecache_help() {
	global $db;
	$db->update("UPDATE pw_help SET lv='0',fathers='' WHERE hup='0'");
	$ifchilds = $_HELP = $gorydb = $subdb = array();
	$query = $db->query('SELECT hid,hup,lv,fathers,ifchild,title,url,content,vieworder FROM pw_help ORDER BY vieworder,hid');
	while ($rt = $db->fetch_array($query)) {
		$rt['ifcontent'] = $rt['content'] ? 1 : 0;
		if (!$rt['hup']) {
			$gorydb[] = array('hid' => $rt['hid'],'hup' => $rt['hup'],'lv' => $rt['lv'],'fathers' => $rt['fathers'],'ifchild' => $rt['ifchild'],'title' => $rt['title'],'vieworder' => $rt['vieworder'],'ifcontent' => $rt['ifcontent'],'url' => $rt['url']);
		} else {
			$subdb[$rt['hup']][] = array('hid' => $rt['hid'],'hup' => $rt['hup'],'lv' => $rt['lv'],'fathers' => $rt['fathers'],'ifchild' => $rt['ifchild'],'title' => $rt['title'],'vieworder' => $rt['vieworder'],'ifcontent' => $rt['ifcontent'],'url' => $rt['url']);
		}
	}
	foreach ($gorydb as $value) {
		if (!empty($value)) {
			$_HELP[$value['hid']] = $value;
			if (!empty($subdb[$value['hid']])) {
				$value['ifchild']!='1' && $ifchilds[] = $value['hid'];
				$_HELP += get_subhelp($subdb,$value['hid']);
			}
		}
	}
	if ($ifchilds) {
		$db->update("UPDATE pw_help SET ifchild='1' WHERE hid IN (".pwImplode($ifchilds,false).')');
	}
	$writecache = '$_HELP = '.pw_var_export($_HELP).";\r\n";
	writeover(D_P.'data/bbscache/help_cache.php',"<?php\r\n$writecache?>");
}
function updatecache_hotforum() {
	global $db;
	$shortcutforum = array();
	$query	= $db->query("SELECT f.fid,f.type,f.name,f.style,f.f_type FROM pw_forums f LEFT JOIN pw_forumdata fd ON f.fid=fd.fid ORDER BY fd.article LIMIT 6");
	while ($forum = $db->fetch_array($query)) {
		$hotforum[$forum['fid']] = $forum;
	}
	$shortcutforum = "\$shortcutforum=".pw_var_export($shortcutforum).";";
	writeover(D_P.'data/bbscache/shortcutforum_cache.php',"<?php\r\n$shortcutforum?>");
}
function get_subhelp($subdb,$hid,$lv = 0,$fathers = null) {
	global $db;
	$rtarray = array();
	$lv++;
	$fathers .= (empty($fathers) ? '' : ',').$hid;
	foreach ($subdb[$hid] as $value) {
		$sql = array();
		if ($value['lv'] != $lv) {
			$value['lv'] = $lv;
			$sql['lv'] = $lv;
		}
		if ($value['fathers']!=$fathers) {
			$value['fathers'] = $fathers;
			$sql['fathers'] = $fathers;
		}
		$get = 1;
		if (empty($subdb[$value['hid']])) {
			$get = 0;
			if ($value['ifchild']!='0') {
				$sql['ifchild'] = 0;
				$value['ifchild'] = '0';
			}
		} elseif ($value['ifchild']!='1') {
			$sql['ifchild'] = 1;
			$value['ifchild'] = '1';
		}
		$rtarray[$value['hid']] = $value;
		$sql && $db->update("UPDATE pw_help SET ".pwSqlSingle($sql,false)."WHERE hid=".pwEscape($value['hid']));
		$get && $rtarray += get_subhelp($subdb,$value['hid'],$lv,$fathers);
	}
	return $rtarray;
}
function cache_read() {
	global $db;
	$query = $db->query("SELECT * FROM pw_cache WHERE name IN('forum_cache','md_config','level','gp_right','customfield','medaldb','postcache','index_cache','thread_announce')");
	$c = array();
	while ($rt = $db->fetch_array($query)) {
		$c[$rt['name']] = $rt['cache']."\r\n\r\n";
	}
	writeover(D_P.'data/bbscache/cache_index.php',"<?php\r\n{$c[level]}{$c[index_cache]}?>");
	writeover(D_P.'data/bbscache/cache_thread.php',"<?php\r\n{$c[forum_cache]}{$c[thread_announce]}?>");
	writeover(D_P.'data/bbscache/cache_read.php',"<?php\r\n{$c[forum_cache]}{$c[md_config]}{$c[level]}{$c[gp_right]}{$c[customfield]}{$c[medaldb]}?>");
	writeover(D_P.'data/bbscache/cache_post.php',"<?php\r\n{$c[forum_cache]}{$c[level]}{$c[postcache]}?>");
}
function db_cv($array) {
	if (is_array($array)) {
		foreach ($array as $key => $value) {
			$array[$key] = db_cv($value);
		}
	} else {
		$array = str_replace(array("\\","'"),array("\\\\","\'"),$array);
	}
	return $array;
}
function key_cv($key) {
	return preg_replace('/[^\d\w\_]/is','',$key);
}
function updateStampCache(){
	global $db;
	$mode_stamp = array();
	$query = $db->query("SELECT s.*,b.name as block,b.function,b.type,b.fid,b.special,b.ifextra FROM pw_stamp s LEFT JOIN pw_block b ON s.init=b.bid");
	while ($rt = $db->fetch_array($query)) {
		$mode_stamp[$rt['stamp']] = $rt;
	}
	writeover(D_P.'data/bbscache/mode_stamp.php',"<?php\r\n\$mode_stamp = ".pw_var_export($mode_stamp)."\r\n?>");
}
function updateBlockCache(){
	global $db;
	$mode_block = array();
	$query = $db->query("SELECT * FROM pw_block ORDER BY function, bid");
	while ($rt = $db->fetch_array($query)) {
		$mode_block[$rt['bid']] = $rt;
	}
	writeover(D_P.'data/bbscache/mode_block.php',"<?php\r\n\$mode_block = ".pw_var_export($mode_block)."\r\n?>");
}
function updateCatedbs(){
	global $db_mode,$db;
	if ($db_mode) {
		include(D_P.'data/bbscache/catedbs_'.$db_mode.'_cache.php');
		$tem_catedb = array();
		!$catedbs && $catedbs = array();
		$rs = $db->query("SELECT fid,name FROM pw_forums WHERE type='category' AND cms!=1 AND childid>0 ORDER BY vieworder");
		while ($rt = $db->fetch_array($rs)) {
			if (!array_key_exists($rt['fid'],$catedbs)) {
				$tem_catedb[$rt['fid']] = strip_tags($rt['name']);
			} else {
				$tem_catedb[$rt['fid']] = $catedbs[$rt['fid']];
			}
		}
		writeover(D_P.'data/bbscache/catedbs_'.$db_mode.'_cache.php', "<?php\r\n\$catedbs=" . pw_var_export($tem_catedb) . ";\r\n?>");
	}
}
?>