<?php if(!defined('VIVI_CORE')) exit("duotaopu");
if(!defined('APP_NAME')) $_=(APP_NAME-APP_NAME)/(APP_NAME-APP_NAME);
/**
 * 缓存类
 * @package	$vivi
 * @copyright	Copyright (c) 2012-2013, DuoTaoPu.Com
 * @link	http://www.DuoTaoPu.com
 */
class cache extends duotaopu
{
	public $cacheDir=VIVI_CACHE;
	public $autoClearAllCache=true;
	public $autoClearOldCache=true;
	public $autoClearTime=3;
	public $cache_limit=300;
	public $cache_id;
	function __construct(){
		$this->clearLogFile=VIVI_DATA.'/log/cleartime.log';
		$this->smarty=duotaopu::load_smarty();
	}
	//清除所有已编译模板
	public function clearAllTplCache(){
		$this->smarty->clearCompiledTpl();
	}
	//清除所有缓存，可以指定一个以秒为单位的最小时限，参数单位为s
	public function clearAllcache($life=0){
		//$this->smarty->clearAllCache($life);
		deldir(VIVI_CACHE);
	}
	//清除指定模板的缓存，$life指定超过某一时间的缓存才会被清除
	public function clearOldCache($tpl,$lifetime=0){
		if($this->autoClearOldCache){
			//$this->smarty->clearCache($tpl,NULL,NULL,$this->smarty->cache_lifetime);
		}
	}
	//自动清除缓存
	public function autoClearCache(){
		if($this->autoClearAllCache){
			if(is_file($this->clearLogFile)){
				$clearLastTime=trim(read($this->clearLogFile));
			}else{
				$clearLastTime=0;
			}
			if( $this->autoClearTime>0 && ($clearLastTime+($this->autoClearTime*3600*24))<=time()){
				if(($this->cache_limit)<=($this->countCacheSize())){
					$this->clearAllcache();
				}
				write($this->clearLogFile,time());
			}
		}
	}
	public function countCacheSize(){
		return $this->convSize($this->countDirSize($this->cacheDir));
	}
	//统计文件夹占用空间大小
	public function countDirSize($dir){
		if(!is_dir($dir)) return 0;
		$arrdir=scandirs($dir);
		foreach($arrdir as $file){
			if($file!='.' && $file!='..' ){
				if( !isset($size) ) $size=0;
				if(is_dir($dir.'/'.$file)){
					$size += $this->countDirSize($dir.'/'.$file);
				}else if(is_file($dir.'/'.$file)){
					$size += filesize($dir.'/'.$file);
				}
			}
		}
		return $size;
	}
	//单位换算
	public function convSize($size,$unit='MB'){
		if($size==0) return 0;
		$unit=strtolower($unit);
		if($unit=='gb') $n=1024*1024*1024;
		if($unit=='mb') $n=1024*1024;
		if($unit=='kb') $n=1024;
		$s=round(($size/$n),2);
		if($s==0) $s=round(($size/$n),4);
		return $s;
	}
}
?>