<?php
!function_exists('readover') && exit('Forbidden');
class ElementCache{
	var $scr;
	var $config;
	var $cache;
	var $update;
	var $file;
	/**
	 * 構造函數
	 *
	 * @param string $scr
	 * @return ElementCache
	 */
	function ElementCache($scr){
		global $db_mode;
		!$scr && Showmsg('elementcache_scr_empty');
		$configfile = Pcv(D_P.'data/bbscache/mode_'.$scr.'_'.$db_mode.'_config.php');
		@include($configfile);
		$this->scr		= $scr;
		$this->config	= ${$scr.'_config'};
		$this->file		= $this->getFileName();
		if ($this->file) {
			@include($this->file);
			$this->cache = $elementsinfo;
		}
	}
	/**
	 * 通過id獲取配置
	 *
	 * @param string $id
	 * @return array()
	 */
	function getConfigById($id){
		return $this->config[$id];
	}
	/**
	 * 設置某Id的配置
	 *
	 * @param string $id
	 * @return array()
	 */
	function setConfigById($id,$config){
		$this->config[$id] = $config;
	}
	/**
	 * 通過$cachetype獲取緩存文件名
	 *
	 * @param int $scr
	 * @return string
	 */
	function getFileName($scr=false,$mode=false){
		global $db_mode;
		//$mode 	= $db_mode ? $db_mode:'phpwind';
		$mode = $mode ? $mode : ($db_mode ? $db_mode : 'phpwind');
		$scr 	= $scr ? $scr : $this->scr;
		$filename = D_P.'data/bbscache/';
		switch ($scr) {
			case 'cate':
				global $cateid;
				if ($cateid) {
					$filename .= 'mode_'.$mode.'_cate_'.$cateid.'.php';
				} else {
					return false;
				}
				break;
			case 'thread':
				global $fid;
				if ($fid) {
					$filename .= 'mode_'.$mode.'_thread_'.$fid.'.php';
				} else {
					return false;
				}
				break;
			case 'read':
				global $fid;
				if ($fid) {
					$filename .= 'mode_'.$mode.'_read_'.$fid.'.php';
				} else {
					return false;
				}
				break;
			default:
				$filename .= 'mode_'.$mode.'_'.$scr.'.php';
				break;
		}
		if (!$filename) return false;
		return Pcv($filename);
	}

	/**
	 * 通過id 獲取緩存里的數據
	 *
	 * @param string $function
	 * @param int $id
	 * @return array
	 */
	function getContent($id){
		if (!array_key_exists($id,$this->cache)) {
			return null;
		}
		return $this->cache[$id];
	}
	/**
	 * 設置$id的值
	 *
	 * @param int $id
	 * @param array $result
	 */
	function setContent($id,$result){
		global $timestamp;
		$config = $this->getConfigById($id);
		$result['updatetime'] = $timestamp;
		$result['bid'] = $config['bid'];
		$this->cache[$id] = $result;
		$this->update = 1;
	}
	/**
	 * 更新緩存文件
	 *
	 */
	function updateFiles(){
		if ($this->update) {
			writeover($this->file,"<?php\r\n\$elementsinfo = ".pw_var_export($this->cache).";\r\n?>");
		}
	}
}
?>