<?php
/**
 * @version $Id: cache.class.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

class Cache
{
	/**
	 * 缓存文件列表
	 */
	var $cacheList = '';
	/**
	 * 缓存文件生存期
	 */
	var $lifeTime = 0;
	/**
	 * 缓存内容
	 */
	var $cacheContent = '';
	/**
	 * 缓存文件名
	 */
	var $cacheFileName = '';
	
	/**
	 * 构造函数
	 */
	function __construct()
	{}
	function Cache()
	{
		$this->__construct();
	}
    /**
     * 设置缓存生存期
     */
    function setLifeTime($lifeTime)
    {
    	$this->lifeTime = (int)$lifeTime;
    }
    /**
     * 设置缓存文件
     */
    function setCacheFileName($cacheFileName)
    {
    	$this->cacheFileName = $cacheFileName;
    }
    /**
     * 设置缓存文件列表
     */
    function setCacheList($cacheList)
    {
    	$this->cacheList .= $cacheList.',';
    }
    /**
     * 返回缓存内容
     */
    function getCacheContent()
    {
    	return $this->cacheContent;
    }
	/**
	 * 系统设置
	 * 
	 * @version 2.0
	 */
	function config()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT title, text FROM {$db_prefix}configs WHERE title LIKE 'pb_%'");
		$content = '';
		while ($result = $DB->db_fetch_array())
		{
			$content .= '$'.$result['title']."='".addcslashes($result['text'], '\'\\')."';\r\n";
		}
		$DB->db_free();
		$this->writeCache('config', $content);
	}
	
	/**
	 * 系统统计信息
	 * 
	 * @version 2.0
	 */
	function sitestat()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT newmember, membernum, catenum, artnum, comnum FROM {$db_prefix}sitestat WHERE id = 1");
		$content = "return \$_sitestat = array(\r\n";
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\t'newmember' => '" . addcslashes($result['newmember'], '\'\\') . "',\r\n";
			$content .= "\t'membernum' => '" . $result['membernum'] . "',\r\n";
			$content .= "\t'catenum' => '" . $result['catenum'] . "',\r\n";
			$content .= "\t'artnum' => '" . $result['artnum'] . "',\r\n";
			$content .= "\t'comnum' => '" . $result['comnum'] . "'\r\n";
		}
		$content .= ");";
		$DB->db_free();
		$this->writeCache('sitestat', $content);
	}
	
	/**
	 * 注册信息
	 * 
	 * @version 2.0
	 */
	function reg()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT title, text FROM {$db_prefix}configs WHERE title LIKE 'reg_%'");
		$content = '';
		while ($result = $DB->db_fetch_array())
		{
			$content .= '$'.$result['title']."='".addcslashes($result['text'], '\'\\')."';\r\n";
		}
		$DB->db_free();
		$this->writeCache('reg', $content);
	}
	/**
	 * 分类缓存
	 * 
	 * @version 1.0
	 */
	function categories()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT cid, cup, name, displayorder, status FROM {$db_prefix}categories ORDER BY displayorder");
		$content = "\$categories = array(\r\n";
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\t'" . $result['cid'] . "' => array(\r\n";
			$content .= "\t\t'cid' => '" . $result['cid'] . "',\r\n";
			$content .= "\t\t'cup' => '" . $result['cup'] . "',\r\n";
			$content .= "\t\t'name' => '" . addcslashes($result['name'], '\'\\') . "',\r\n";
			$content .= "\t\t'displayorder' => '" . $result['displayorder'] . "',\r\n";
			$content .= "\t\t'status' => '" . $result['status'] . "'),\r\n";
		}
		$content .= ");";
		$DB->db_free();
		$this->writeCache('categories', $content);
	}
	/**
	 * 分类单独缓存
	 * 
	 * @version 1.0
	 */
	function singlecate($cid = '')
	{
		global $DB, $db_prefix;
		require(PBDIGG_ROOT.'data/cache/cache_categories.php');
		$sql = $cid ? ' WHERE cid IN ('.$cid.')' : '';
		$DB->db_query("SELECT cid, icon, keywords, description, tnum, cnum FROM {$db_prefix}categories".$sql);
		while ($result = $DB->db_fetch_array())
		{
			$content = "\$singlecate = array(";
			$content .= "'icon' => '" . addcslashes($result['icon'], '\'\\') . "',";
			$content .= "'keywords' => '" . addcslashes($result['keywords'], '\'\\') . "',";
			$content .= "'description' => '" . addcslashes($result['description'], '\'\\') . "',";
			$parcids = $subcids = '';
			str_parcate($categories, $parcids, $result['cid']);
			str_subcate($categories,  $subcids, $result['cid']);
			$content .= "'parcids' => '" . $parcids . "',";
			$content .= "'subcids' => '" . $subcids . "',";
			$content .= "'tnum' => '" . $result['tnum'] . "',";
			$content .= "'cnum' => '" . $result['cnum'] . "'";
			$content .= ");";
			$this->writeCache('singlecate_'.$result['cid'], $content);
		}
		$DB->db_free();
	}
	/**
	 * 会员组信息
	 * 
	 * @version 1.0
	 */
	function grouplevel()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT groupid, gtype, grouptitle FROM {$db_prefix}usergroups ORDER BY groupid");
		$content = "\$grouplevel = array(\r\n";
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\t'" . $result['groupid'] . "' => array(\r\n";
			$content .= "\t\t'groupid' => '" . $result['groupid'] . "',\r\n";
			$content .= "\t\t'gtype' => '" . $result['gtype'] . "',\r\n";
			$content .= "\t\t'grouptitle' => '" . addcslashes($result['grouptitle'], '\\\'') . "'\r\n";
			$content .= "\t),\r\n";
		}
		$content .= ");";
		$this->writeCache('grouplevel', $content);
	}
	/**
	 * 用户组缓存
	 * 
	 * @version 2.0
	 */
	function userGroupCache()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT * FROM {$db_prefix}usergroups ORDER BY groupid");
		$content = '';
		while ($result = $DB->db_fetch_array())
		{
			foreach ($result as $key => $value)
			{
				$content .= '$'.$key." = '".$value."';\r\n";
			}
			$this->writeCache('usergroup_'.$result['groupid'], $content);
			$content = '';
		}
	}
	/**
	 * 管理组缓存
	 * 
	 * @version 2.0
	 */
	function adminGroupCache()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT * FROM {$db_prefix}admingroups ORDER BY adminid");
		$content = '';
		while ($result = $DB->db_fetch_array())
		{
			foreach ($result as $key => $value)
			{
				$content .= '$'.$key." = '".$value."';\r\n";
			}
			$this->writeCache('admingroup_'.$result['adminid'], $content);
			$content = '';
		}
	}
	/**
	 * 标签
	 * 
	 * @version 2.0
	 */
	function tags()
	{
		global $DB, $db_prefix, $pb_trantags, $pb_tagcolor;

		$DB->db_query("SELECT tagid, tagname, usenum FROM {$db_prefix}tags WHERE ifopen = 1 ORDER BY usenum DESC LIMIT 0, $pb_trantags");
		$content = "return \$_tags = array(\r\n";
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\t'" . $result['tagid'] . "' => array(\r\n";
			$content .= "\t\t'tagid' => '" . $result['tagid'] . "',\r\n";
			$content .= "\t\t'tagname' => '" . addcslashes($result['tagname'], '\\\'') . "',\r\n";
			$content .= "\t\t'encodetagname' => '" . addcslashes(rawurlencode($result['tagname']), '\\\'') . "',\r\n";
			$content .= "\t\t'usenum' => '" . $result['usenum'] . "',\r\n";
			if ($pb_tagcolor)
			{
				$content .= "\t\t'color' => '" . addcslashes(getTagStyle(), '\\\'') . "',\r\n";
			}
			$content .= "\t),\r\n";
		}
		$content .= ");";
		$DB->db_free();
		$this->writeCache('tags', $content);
	}
	/**
	 * 系统标签
	 */
	function systags()
	{
		global $DB, $db_prefix, $pb_tagcolor;
		$DB->db_query("SELECT tagid, tagname, usenum FROM {$db_prefix}tags WHERE ifsys = 1 AND ifopen = 1 ORDER BY usenum DESC");
		$content = "return \$systags = array(\r\n";
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\t'" . $result['tagid'] . "' => array(\r\n";
			$content .= "\t\t'tagid' => '" . $result['tagid'] . "',\r\n";
			$content .= "\t\t'tagname' => '" . addcslashes($result['tagname'], '\\\'') . "',\r\n";
			$content .= "\t\t'encodetagname' => '" . addcslashes(rawurlencode($result['tagname']), '\\\'') . "',\r\n";
			$content .= "\t\t'usenum' => '" . $result['usenum'] . "',\r\n";
			if ($pb_tagcolor)
			{
				$content .= "\t\t'color' => '" . addcslashes(getTagStyle(), '\\\'') . "',\r\n";
			}
			$content .= "\t),\r\n";
		}
		$content .= ");";
		$DB->db_free();
		$this->writeCache('systags', $content);
	}
	/**
	 * 插件缓存
	 * 
	 * @version 2.0
	 */
	function plugins()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT pid, pname, pmark FROM {$db_prefix}plugins WHERE status = 1 AND foreground = 1");
		$content = "\$plugins = array(\r\n";
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\t'" . $result['pid'] . "' => array(\r\n";
			$content .= "\t\t'pid' => '" . $result['pid'] . "',\r\n";
			$content .= "\t\t'pname' => '" . addcslashes($result['pname'], '\\\'') . "',\r\n";
			$content .= "\t\t'pmark' => '" . addcslashes($result['pmark'], '\\\'') . "',\r\n";
			$content .= "\t),\r\n";
		}
		$content .= ");";
		$DB->db_free();
		$this->writeCache('plugins', $content);
	}
	/**
	 * 插件导航缓存
	 */
	function pluginsmenu()
	{
		global $DB, $db_prefix, $cp_message;
		$DB->db_query("SELECT pname, pmark FROM {$db_prefix}plugins");
		$content = "\$m_plugin = array (\r\n\t'mName' => '".$cp_message['plugin']."',\r\n\t'mItems' => array (\r\n";
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\t\t'".$result['pname']."' => '".$result['pmark']."',\r\n";
		}
		$content .= "\t)\r\n);";
		$DB->db_free();
		$this->writeCache('pluginsmenu', $content);
	}
	/**
	 * 友情链接
	 * 
	 * @version 2.0
	 */
	function flink()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT * FROM {$db_prefix}links WHERE ifshow = 1 ORDER BY displayorder");
		$ck = TRUE;
		$pright = chr(80).chr(66).chr(68).chr(105).chr(103).chr(103);
		$purl = chr(104).chr(116).chr(116).chr(112).chr(58).chr(47).chr(47).chr(119).chr(119).chr(119).chr(46).chr(112).chr(98).chr(100).chr(105).chr(103).chr(103).chr(46).chr(110).chr(101).chr(116);
		$content = "\$links = array(\r\n";
		while ($result = $DB->db_fetch_array())
		{
			if ($ck && (strpos($result['siteurl'], $purl) !== FALSE))
			{
				$ck = FALSE;
			}
			$content .= "\t'" . $result['lid'] . "' => array(\r\n";
			$content .= "\t\t'lid' => '" . $result['lid'] . "',\r\n";
			$content .= "\t\t'sitename' => '" . addcslashes($result['sitename'], '\'\\') . "',\r\n";
			$content .= "\t\t'siteurl' => '" . addcslashes($result['siteurl'], '\'\\') . "',\r\n";
			$content .= "\t\t'description' => '" . addcslashes($result['description'], '\'\\') . "',\r\n";
			$content .= "\t\t'ifshow' => '" . $result['ifshow'] . "',\r\n";
			$content .= "\t\t'displayorder' => '" . $result['displayorder'] . "',\r\n";
			$content .= "\t\t'logo' => '" . addcslashes($result['logo'], '\'\\') . "'),\r\n";
		}
		if ($ck)
		{
			$content .= "\t'1' => array(\r\n";
			$content .= "\t\t'lid' => '1',\r\n";
			$content .= "\t\t'sitename' => '$pright',\r\n";
			$content .= "\t\t'siteurl' => '$purl',\r\n";
			$content .= "\t\t'description' => '$pright',\r\n";
			$content .= "\t\t'ifshow' => '1',\r\n";
			$content .= "\t\t'displayorder' => '9999',\r\n";
			$content .= "\t\t'logo' => ''),\r\n";
		}
		$content .= ");";
		$this->writeCache('links', $content);
	}
 	/** 缓存模板
	 * 
	 * @version 1.0
	 */
	function tplvar()
	{
		global $DB, $db_prefix, $timestamp;
		$DB->db_query("SELECT tplmark, tplcontent FROM {$db_prefix}tplvar");
		$content = '';
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\$tpl_".$result['tplmark']." = '".addcslashes($result['tplcontent'], '\\\'')."';\r\n";
		}
		$this->writeCache('tplvar', $content);
	}
	/**
	 * 置顶主题
	 */
	function toparticle()
	{
		global $DB, $db_prefix, $pb_rewrite, $func_message;
		$DB->db_query("SELECT t.tid, t.subject, t.postdate, ti.titlecolor, ti.titlestyle FROM {$db_prefix}threads t LEFT JOIN {$db_prefix}tinfo ti USING (tid) WHERE t.topped = 1 AND t.ifcheck = 1 ORDER BY t.postdate DESC");
		if ($DB->db_num())
		{
			$tpl_topped = '';
			@include(PBDIGG_ROOT.'data/cache/cache_tplvar.php');
			$content = "\$toparticle = '";
			while ($result = $DB->db_fetch_array())
			{
				$style = '';
				if ($result['titlecolor'])
				{
					$style = 'color:#'.$result['titlecolor'].';';
				}
				if ($result['titlestyle'])
				{
					/*b/em/u*/
					($result['titlestyle']{0}) && $style .= 'font-weight:bold;';
					($result['titlestyle']{1}) && $style .= 'font-style:italic;';
					($result['titlestyle']{2}) && $style .= 'text-decoration:underline;';
				}
				$style && $result['subject'] = '<span style="'.$style.'">'.$result['subject'].'</span>';
				$tpl_replace = array(addcslashes($result['subject'], '\'\\'),
									'show.php?tid='.$result['tid'],
									$func_message['toparticle'],
									gdate($result['postdate'], 'Y-m-d H:i'));
				$content .= str_replace(array('{!--subject--}','{!--turl--}','{!--topped--}','{!--postdate--}'), $tpl_replace, $tpl_topped);
			}
			$content .= "'";
		}
		else
		{
			$content = "\$toparticle = '';";
		}
		$this->writeCache('toparticle', $content);
	}
	/**
	 * 头条新闻
	 */
	function firstarticle()
	{
		global $DB, $db_prefix, $pb_rewrite, $func_message, $_PBENV;
		$result = $DB->db_fetch_one_array("SELECT t.tid, t.subject, t.topicimg, t.postdate, ti.sdesc, ti.titlecolor, ti.titlestyle FROM {$db_prefix}tinfo ti INNER JOIN {$db_prefix}threads t USING (tid) WHERE ti.iffirst = 1 AND t.ifcheck = 1 ORDER BY t.tid DESC LIMIT 1");
		if ($result)
		{
			$tpl_first = $style = '';
			@include(PBDIGG_ROOT.'data/cache/cache_tplvar.php');
			$content = "\$firstarticle = '";
			$restult['altsubject'] = $restult['subject'];
			if ($result['titlecolor'])
			{
				$style = 'color:#'.$result['titlecolor'].';';
			}
			if ($result['titlestyle'])
			{
				/*b/em/u*/
				($result['titlestyle']{0}) && $style .= 'font-weight:bold;';
				($result['titlestyle']{1}) && $style .= 'font-style:italic;';
				($result['titlestyle']{2}) && $style .= 'text-decoration:underline;';
			}
			$style && $result['subject'] = '<span style="'.$style.'">'.$result['subject'].'</span>';
			$result['topicimg'] && list($result['topicimg'],,) = explode('|', $result['topicimg']);
			$tpl_replace = array(addcslashes($result['altsubject'], '\'\\'),addcslashes($result['subject'], '\'\\'),'show.php?tid='.$result['tid'],$_PBENV['PB_URL'].'attachments/'.$result['topicimg'],gdate($result['postdate'], 'Y-m-d H:i'),$result['sdesc']);
			$content .= str_replace(array('{!--altsubject--}','{!--subject--}','{!--turl--}','{!--topicimg--}','{!--postdate--}','{!--summary--}'), $tpl_replace, $tpl_first);
			$content .= "'";
		}
		else
		{
			$content = "\$firstarticle = '';";
		}
		$this->writeCache('firstarticle', $content);
	}
	/**
	 * 推荐主题
	 */
	function commendarticle()
	{
		global $DB, $db_prefix, $pb_rewrite, $_PBENV, $func_message;
		$DB->db_query("SELECT t.tid, t.subject, ti.commendpic, ti.titlecolor, ti.titlestyle FROM {$db_prefix}tinfo ti LEFT JOIN {$db_prefix}threads t ON t.tid = ti.tid WHERE ti.commend = 1 AND ti.commendpic <> '' AND t.ifcheck = 1 ORDER BY t.postdate DESC");
		if ($DB->db_num())
		{
			$content = "\$commendarticle = '";
			$pics = 'fo.addVariable("pics","';
			$links = 'fo.addVariable("links","';
			$texts = 'fo.addVariable("texts","';
			while ($result = $DB->db_fetch_array())
			{
				$pics .= $_PBENV['PB_URL'].'attachments/commend/'.$result['commendpic'].'|';
				$links .= 'show.php?tid='.$result['tid'].'|';
				$texts .= addcslashes($result['subject'], '\\\'').'|';
			}
			$pics = substr($pics, 0, -1).'");';
			$links = substr($links, 0, -1).'");';
			$texts = substr($texts, 0, -1).'");';
			$content .= $pics.$links.$texts."'";
		}
		else
		{
			$content = "\$commendarticle = '';";
		}
		$this->writeCache('commendarticle', $content);
	}
	/**
	 * 网站公告
	 * 
	 * @version 1.0
	 */
	function announce()
	{
		global $DB, $db_prefix, $timestamp;
		$DB->db_query("SELECT aid, cid, author, subject, url, content, postdate, displayorder FROM {$db_prefix}announcements WHERE enddate = 0 OR enddate >= $timestamp ORDER BY displayorder");
		$content = "\$announcements = array(\r\n";
		while ($result = $DB->db_fetch_array())
		{
			$content .= "\t'" . $result['aid'] . "' => array(\r\n";
			$content .= "\t\t'aid' => '" . $result['aid'] . "',\r\n";
			$content .= "\t\t'cid' => '" . $result['cid'] . "',\r\n";
			$content .= "\t\t'author' => '" . addcslashes($result['author'], '\\\'') . "',\r\n";
			$content .= "\t\t'subject' => '" . addcslashes($result['subject'], '\\\'') . "',\r\n";
			if ($result["url"])
			{
				$content .= "\t\t'link' => '" . addcslashes($result['url'], '\\\'') . "',\r\n";
			}
			else
			{
				$content .= "\t\t'link' => 'announcement.php?aid=" . $result['aid'] . "#".$result['aid']."',\r\n";
			}
			$content .= "\t\t'url' => '<a href=\"".addcslashes($result['url'], '\\\'')."\" target=\"_blank\">" . addcslashes($result['url'], '\\\'') . "</a>',\r\n";
			$content .= "\t\t'content' => '" . addcslashes($result['content'], '\\\'') . "',\r\n";
			$content .= "\t\t'postdate' => '" . gdate($result['postdate'], 'Y-m-d H:i') . "',\r\n";
			$content .= "\t\t'displayorder' => '" . $result['displayorder'] . "'),\r\n";
		}
		$content .= ");";
		$this->writeCache('announcements', $content);
	}

	/**
	 * 创建调用模板
	 */
	function mktrantpl()
	{
		global $DB, $db_prefix;
		$DB->db_query("SELECT * FROM {$db_prefix}templates");
		$t = $c = $m = 'array(';
		$content = '$trantpl = array(';
		while ($rs = $DB->db_fetch_array())
		{
			$tmp = "array('tplmark'=>'".$rs['tplmark']."', 'trancid'=>'".$rs['trancid']."', 'trannum'=>'".$rs['trannum']."', 'tranattribute'=>'".$rs['tranattribute']."', 'cotentlimit'=>'".$rs['cotentlimit']."', 'titlelimit'=>'".$rs['titlelimit']."', 'iftopicimg'=>'".$rs['iftopicimg']."', 'ifcommend'=>'".$rs['ifcommend']."', 'ifcommendpic'=>'".$rs['ifcommendpic']."', 'timelimit'=>'".$rs['timelimit']."', 'timeformat'=>'".$rs['timeformat']."', 'trantype'=>'".$rs['trantype']."', 'displayorder'=>'".$rs['displayorder']."', 'ifself'=>'".$rs['ifself']."', 'tplcontent'=>'".addcslashes($rs['tplcontent'], '\\\'')."'),";
			${$rs['trantype']} .= $tmp;
		}
		$t .= '),';
		$c .= '),';
		$m .= '),';
		$content .= $t.$c.$m.");";
		$DB->db_free();
		$this->writeCache('trantpl', $content);
	}
	/**
	 * 创建调用内容
	 * 
	 * @param String $tplmark 模板标识
	 * @param Int $type 模板类型(0:文章，1：评论，2：会员)
	 */
	function mktran($tplmark = '', $type = '')
	{
		global $DB, $db_prefix, $func_message, $timestamp, $_PBENV, $pb_rewrite, $categories;
		$trantpl = '';
		if ($tplmark)
		{
			$rs = $DB->db_fetch_one_array("SELECT * FROM {$db_prefix}templates WHERE tplmark = '$tplmark'");
			if ($rs)
			{
				$trantpl[$type][] = array('tplmark'=>$rs['tplmark'], 'trancid'=>$rs['trancid'], 'trannum'=>$rs['trannum'], 'tranattribute'=>$rs['tranattribute'], 'cotentlimit'=>$rs['cotentlimit'], 'titlelimit'=>$rs['titlelimit'], 'iftopicimg'=>$rs['iftopicimg'], 'ifcommend'=>$rs['ifcommend'], 'ifcommendpic'=>$rs['ifcommendpic'], 'timelimit'=>$rs['timelimit'], 'timeformat'=>$rs['timeformat'], 'trantype'=>$rs['trantype'], 'displayorder'=>$rs['displayorder'], 'ifself'=>$rs['ifself'],'tplcontent'=>$rs['tplcontent']);
			}
			else
			{
				return $func_message['tran_tpl_needed'];
			}
		}
		elseif (!@include_once (PBDIGG_ROOT.'data/cache/cache_trantpl.php'))
		{
			return $func_message['tran_tpl_needed'];
		}
		$t = $c = $m = 'array(';
		$content_replacement = array('[emote]', '[/emote]', '[strike]', '[/strike]', '[br]', '[pre]', '[/pre]', '[acronym]', '[/acronym]', '[address]', '[/address]', '[ul]', '[ol]', '[li]', '[/ul]', '[/ol]', '[/li]', '[div]','[/div]','[p]','[/p]','[span]','[/span]','[tr]','[/tr]','[/td]','[/table]','[code]','[/code]','[b]','[/b]','[i]','[/i]','[u]','[/u]','[img]','[/img]','[/font]','[/size]','[/color]','[/align]','[/url]','[/quote]','[/media]','[/flash]','[/email]');
		$content_preg_replacement = '#\[(font|table|td|size|color|align|url|quote|media|flash|email)(.*?)\]#is';
		$commentubb_replacement = array('[code]','[/code]','[b]','[/b]','[i]','[/i]','[u]','[/u]','[img]','[/img]','[/font]','[/size]','[/color]','[/url]','[/quote]','[/media]','[/flash]','[/email]','[emote]','[/emote]');
		$thread_replacement = array('{!--altsubject--}','{!--subject--}','{!--turl--}','{!--summary--}','{!--topicimg--}','{!--digg--}','{!--bury--}','{!--comments--}','{!--views--}','{!--postdate--}','{!--author--}','{!--avatar--}','{!--uurl--}','{!--commendpic--}');
		$comment_replacement = array('{!--altsubject--}','{!--subject--}','{!--turl--}','{!--summary--}','{!--postdate--}','{!--author--}','{!--avatar--}','{!--uurl--}','{!--digg--}','{!--bury--}');
		$member_replacement = array('{!--username--}','{!--avatar--}','{!--uurl--}','{!--postnum--}','{!--commentnum--}','{!--diggnum--}','{!--burynum--}','{!--regdate--}');
		if ($trantpl[0])
		{
			foreach ($trantpl[0] as $v)
			{
				$t .= '\''.$v['tplmark'].'\',';
				$sql = $limit = $orderby = '';
				if ($v['trancid'])
				{
					if ($v['ifself'])
					{
						$tmpcid = '';
						str_subcate($categories, $tmpcid, $v['trancid']);
						$v['trancid'] = $tmpcid.$v['trancid'];
					}
					$sql .= ' AND t.cid IN ('.$v['trancid'].')';
				}
				if ($v['iftopicimg'])
				{
					$sql .= ' AND t.topicimg <> \'\'';
				}
				if ($v['ifcommend'])
				{
					$sql .= ' AND ti.commend = \'1\'';
				}
				if ($v['ifcommendpic'])
				{
					$sql .= ' AND ti.commendpic <> \'\'';
				}
				if ($v['timelimit'])
				{
					$sql .= ' AND t.postdate > '.($timestamp - $v['timelimit']);
				}
				$limit = ' LIMIT 0, '.$v['trannum'];
				$orderby = ' ORDER BY t.'.$v['tranattribute'].($v['displayorder'] ? ' DESC' : ' ASC');
				$sql = $sql ? 'WHERE'.substr($sql, 4) : '';
				$s = "SELECT t.tid, t.author, t.uid, t.subject, t.content, t.topicimg, t.postdate, t.digg, t.bury, t.views, t.comments, ti.commendpic, ti.titlecolor, ti.titlestyle, mx.avatar 
						FROM {$db_prefix}threads t 
						LEFT JOIN {$db_prefix}tinfo ti 
						ON t.tid = ti.tid 
						LEFT JOIN {$db_prefix}memberexp mx 
						ON t.uid = mx.uid ".$sql.$orderby.$limit;
				$content = 'return $'.$v['tplmark'].' = \'';
				$DB->db_query($s);
				while ($rs = $DB->db_fetch_array())
				{
					$rs['altsubject'] = $rs['subject'];
					if ($v['titlelimit'])
					{
						$rs['subject'] = PBSubstr($rs['subject'], $v['titlelimit']);
					}
					$style = '';
					if ($rs['titlecolor'])
					{
						$style = 'color:#'.$rs['titlecolor'].';';
					}
					if ($rs['titlestyle'])
					{
						/*b/em/u*/
						($rs['titlestyle']{0}) && $style .= 'font-weight:bold;';
						($rs['titlestyle']{1}) && $style .= 'font-style:italic;';
						($rs['titlestyle']{2}) && $style .= 'text-decoration:underline;';
					}
					$style && $rs['subject'] = '<span style="'.$style.'">'.$rs['subject'].'</span>';
					$rs['content'] = preg_replace($content_preg_replacement, '', str_replace($content_replacement, '', $rs['content']));
					if ($v['cotentlimit'])
					{
						$rs['content'] = PBSubstr($rs['content'], $v['cotentlimit']);
					}
					$rs['altsubject'] = addcslashes($rs['altsubject'], '\\\'');
					$rs['subject'] = addcslashes($rs['subject'], '\\\'');
					$rs['content'] = addcslashes($rs['content'], '\\\'');
					if ($rs['commendpic'])
					{
						$rs['commendpic'] = $_PBENV['PB_URL'].'attachments/commend/'.$rs['commendpic'];
					}
					if (!$rs['avatar'])
					{
						$rs['avatar'] = $_PBENV['PB_URL'].'images/avatars/portrait/default.png';
					}
					elseif (substr($rs['avatar'], 0, 7) != 'http://')
					{
						$rs['avatar'] = $_PBENV['PB_URL'].'images/avatars/'.$rs['avatar'];
					}
					if ($v['timeformat'] ==  '-1')
					{
						$rs['postdate'] = formatPostTime($rs['postdate']);
					}
					else
					{
						$rs['postdate'] = gdate($rs['postdate'], $v['timeformat']);
					}
					if ($rs['topicimg'])
					{
						list($rs['topicimg'],,) = explode('|', $rs['topicimg']);
						$rs['topicimg'] = $_PBENV['PB_URL'].'attachments/'.$rs['topicimg'];
					}
					else
					{
						$rs['topicimg'] = $_PBENV['PB_URL'].'images/noimg.gif';
					}
					if (!$rs['author'])
					{
						$rs['author'] = $func_message['net_friend'];
					}
					$rs['turl'] = 'show.php?tid='.$rs['tid'];
					$rs['uurl'] = 'user.php?uid='.$rs['uid'];
					$content .= str_replace($thread_replacement, array($rs['altsubject'],$rs['subject'],$rs['turl'],$rs['content'],$rs['topicimg'],$rs['digg'],$rs['bury'],$rs['comments'],$rs['views'],$rs['postdate'],$rs['author'],$rs['avatar'],$rs['uurl'],$rs['commendpic']), $v['tplcontent']);
				}
				$content .= '\';';
				$DB->db_free();
				$this->writeCache($v['tplmark'], $content);
			}
		}
		$t .= '),';
		if ($trantpl[1])
		{
			foreach ($trantpl[1] as $v)
			{
				$c .= '\''.$v['tplmark'].'\',';
				$sql = $limit = $orderby = '';
				if ($v['trancid'])
				{
					if ($v['ifself'])
					{
						$tmpcid = '';
						str_subcate($categories, $tmpcid, $v['trancid']);
						$v['trancid'] = $tmpcid.$v['trancid'];
					}
					$sql .= ' AND c.cid IN ('.$v['trancid'].')';
				}
				if ($v['timelimit'])
				{
					$sql .= ' AND c.postdate > '.($timestamp - $v['timelimit']);
				}
				$limit = ' LIMIT 0, '.$v['trannum'];
				$orderby = ' ORDER BY c.'.$v['tranattribute'].($v['displayorder'] ? ' DESC' : ' ASC');
				$sql = $sql ? 'WHERE'.substr($sql, 4) : '';
				$s = "SELECT t.tid, t.subject, c.author, c.uid, c.content, c.postdate, c.digg, c.bury, ti.titlecolor, ti.titlestyle, mx.avatar 
						FROM {$db_prefix}comments c 
						INNER JOIN {$db_prefix}threads t 
						ON c.tid = t.tid 
						LEFT JOIN {$db_prefix}tinfo ti 
						ON t.tid = ti.tid 
						LEFT JOIN {$db_prefix}memberexp mx 
						ON c.uid = mx.uid ".$sql.$orderby.$limit;
				$content = 'return $'.$v['tplmark'].' = \'';
				$DB->db_query($s);
				while ($rs = $DB->db_fetch_array())
				{
					$rs['altsubject'] = $rs['subject'];
					if ($v['titlelimit'])
					{
						$rs['subject'] = PBSubstr($rs['subject'], $v['titlelimit']);
					}
					$style = '';
					if ($rs['titlecolor'])
					{
						$style = 'color:#'.$rs['titlecolor'].';';
					}
					if ($rs['titlestyle'])
					{
						/*b/em/u*/
						($rs['titlestyle']{0}) && $style .= 'font-weight:bold;';
						($rs['titlestyle']{1}) && $style .= 'font-style:italic;';
						($rs['titlestyle']{2}) && $style .= 'text-decoration:underline;';
					}
					$style && $rs['subject'] = '<span style="'.$style.'">'.$rs['subject'].'</span>';
					$rs['altsubject'] = addcslashes($rs['altsubject'], '\\\'');
					$rs['subject'] = addcslashes($rs['subject'], '\\\'');
					$rs['content'] = preg_replace($content_preg_replacement, '', str_replace($commentubb_replacement, '', $rs['content']));
					if ($v['cotentlimit'])
					{
						$rs['content'] = PBSubstr($rs['content'], $v['cotentlimit']);
					}
					$rs['content'] = addcslashes($rs['content'], '\\\'');
					if (!$rs['avatar'])
					{
						$rs['avatar'] = $_PBENV['PB_URL'].'images/avatars/portrait/default.png';
					}
					elseif (substr($rs['avatar'], 0, 7) != 'http://')
					{
						$rs['avatar'] = $_PBENV['PB_URL'].'images/avatars/'.$rs['avatar'];
					}
					if ($v['timeformat'] ==  '-1')
					{
						$rs['postdate'] = formatPostTime($rs['postdate']);
					}
					else
					{
						$rs['postdate'] = gdate($rs['postdate'], $v['timeformat']);
					}
					if (!$rs['author'])
					{
						$rs['author'] = $func_message['net_friend'];
					}
					$rs['turl'] = 'show.php?tid='.$rs['tid'];
					$rs['uurl'] = 'user.php?uid='.$rs['uid'];
					$content .= str_replace($comment_replacement, array($rs['altsubject'],$rs['subject'],$rs['turl'],$rs['content'],$rs['postdate'],$rs['author'],$rs['avatar'],$rs['uurl'],$rs['digg'],$rs['bury']), $v['tplcontent']);
				}
				$content .= '\';';
				$DB->db_free();
				$this->writeCache($v['tplmark'], $content);
			}
		}
		$c .= '),';
		if ($trantpl[2])
		{
			foreach ($trantpl[2] as $v)
			{
				$m .= '\''.$v['tplmark'].'\',';
				$sql = $limit = $orderby = '';
				if ($v['tranattribute'] == 'newmember')
				{
					$sql .= 'ORDER BY m.regdate DESC';
				}
				else
				{
					$sql .= 'WHERE m.groupid = -1 ORDER BY md.currency DESC';
				}
				$limit = ' LIMIT 0, '.$v['trannum'];
				$s = "SELECT m.uid, m.username, m.regdate, mx.avatar, md.postnum, md.commentnum, md.diggnum, md.burynum 
						FROM {$db_prefix}members m 
						LEFT JOIN {$db_prefix}memberdata md 
						ON m.uid = md.uid 
						LEFT JOIN {$db_prefix}memberexp mx 
						ON m.uid = mx.uid ".$sql.$limit;
				$content = 'return $'.$v['tplmark'].' = \'';
				$DB->db_query($s);
				while ($rs = $DB->db_fetch_array())
				{
					if (!$rs['avatar'])
					{
						$rs['avatar'] = $_PBENV['PB_URL'].'images/avatars/portrait/default.png';
					}
					elseif (substr($rs['avatar'], 0, 7) != 'http://')
					{
						$rs['avatar'] = $_PBENV['PB_URL'].'images/avatars/'.$rs['avatar'];
					}
					if ($v['timeformat'] ==  '-1')
					{
						$rs['regdate'] = formatPostTime($rs['regdate']);
					}
					else
					{
						$rs['regdate'] = gdate($rs['regdate'], $v['timeformat']);
					}
					$content .= str_replace($member_replacement, array($rs['username'],$rs['avatar'],'user.php?uid='.$rs['uid'],$rs['postnum'],$rs['commentnum'],$rs['diggnum'],$rs['burynum'],$rs['regdate']), $v['tplcontent']);
				}
				$content .= '\';';
				$DB->db_free();
				$this->writeCache($v['tplmark'], $content);
			}
		}
		$m .= '),';
		if (!$tplmark)
		{
			$this->writeCache('tranlist', '$tranlist = array('.$t.$c.$m.');');
		}
	}
	
	/**
	 * 核心缓存
	 */
	function coreCache()
	{
		$this->config();
		$this->reg();
		$this->categories();
		$this->singlecate();
		$this->mktrantpl();
		$this->sitestat();
		$this->grouplevel();
		$this->userGroupCache();
		$this->adminGroupCache();
		$this->flink();
		$this->announce();
		$this->tplvar();
		$this->toparticle();
		$this->commendarticle();
		$this->mktrantpl();
		$this->mktran();
	}
	/**
	 * 加载调用内容
	 * 
	 * @param String $cacheName 缓存文件名
	 * @param Int $cacheName 缓存类型
	 * @param Boolean $checkTime 是否检查缓存时间
	 * @param Int $force 是否必须加载
	 * @version 1.0
	 */
	function _loadTran($cacheName, $type, $checkTime = TRUE, $force = 0)
	{
		global $timestamp, $func_message;
		$cacheFile = PBDIGG_ROOT.'data/cache/cache_'.$cacheName.'.php';
		if (file_exists($cacheFile))
		{
			clearstatcache();
			if ($checkTime && ($timestamp - filemtime($cacheFile)) > $this->lifeTime)
			{
				$this->mktran($cacheName, $type);
			}
			$this->cacheContent = include_once($cacheFile);
		}
		elseif ($force)
		{
			$this->mktran($cacheName, $type);
			$this->cacheContent = include_once($cacheFile);
		}
		else
		{
			$this->cacheContent = sprintf($func_message['tran_cache_needed'], $cacheName);
		}
	}

	/**
	 * 加载缓存
	 * 
	 * @param String $cacheName 缓存文件名
	 * @param Boolean $checkTime 是否检查缓存时间
	 * @param int $force 是否必须加载
	 * @version 1.0
	 */
	function loadCache($cacheName, $checkTime = TRUE, $force = 0)
	{
		$cacheFile = PBDIGG_ROOT.'data/cache/cache_'.$cacheName.'.php';
		if (file_exists($cacheFile))
		{
			clearstatcache();
			if ($checkTime && (time() - filemtime($cacheFile)) > $this->lifeTime)
			{
				$this->$cacheName();
			}
			$this->cacheContent = include_once($cacheFile);
		}
		elseif ($force)
		{
			$this->$cacheName();
			$this->cacheContent = include_once($cacheFile);
		}
		else
		{
			$this->cacheContent = '';
		}
	}
	/**
	 * 缓存文件属性
	 * 
	 * @return boolean 是否可写
	 */
	function cacheMod($mod = 0777)
	{
		if (strpos($this->cacheFileName, '..') !== FALSE) return FALSE;
		$file = PBDIGG_ROOT.'data/cache/cache_'.$this->cacheFileName.'.php';
		if (is_writable($file) || chmod($file, $mod))
		{
			return TRUE;
		}
		return FALSE;
	}
	/**
	 * 更新缓存
	 * 
	 * @version 1.0
	 */
	function refreshCache()
	{
		if ($this->cacheList)
		{
			$funcName = array_filter(explode(',', $this->cacheList));
			foreach ($funcName as $value)
			{
				$this->$value();
			}
			return TRUE;
		}
		return FALSE;
	}

	/**
	 * 缓存写入函数
	 * 
	 * @version 2.0
	 */
	function writeCache($fileName, $content)
	{
		$cacheFile = PBDIGG_ROOT . 'data/cache/cache_' . $fileName . '.php';
		$cacheContent = "<?php\r\n\r\n/** PBDigg Cache File, DO NOT Modify! **/\r\n\r\n";
		$cacheContent .= $content;
		$cacheContent .= "\r\n?>";
		return PWriteFile($cacheFile, $cacheContent, 'wb');
	}
}
?>
