<?php 
/*
  本地缓存功能, 支持多数组缓存.
  保持入库时为原始数据, var_export函数会自动转义.
*/
defined('IN_SYSTEM') === false && exit('PHPnew Blog.');
class cache {
	public static $dir = './Data/cache_data/';
    public static $save_data = array();
    public static $save_tag = 0;
    public static $file_lock = 0;
    public static $month = 0;
	public static $mess = 'read/write read($tag=null,$filename=\'\',$times=3600) 保持入库时为原始数据';
    public static $headerstr = '<?php defined(\'IN_SYSTEM\') === false && exit(\'PHPnew Blog.\'); ?>';
	public static function read($tag=null,$filename='',$times=3600){
	    $cachefile = self::$dir.$filename;
        self::$save_tag = $tag;
		if(empty($tag) === true || empty($filename) === true || $tag === 'time' || is_file($cachefile) === false || self::$file_lock !== 0){
			return false;
		}
        $tag = md5(trim($tag)); // 防止非法key
        if(empty(self::$save_data[$filename]) === true){
            if(self::$month === 0){
                $data = fun_get_contents($cachefile);
                if($data){
                    $data = strtr($data, array(self::$headerstr=>''));
                    if($data)
                     self::$save_data[$filename] = unserialize($data);
                }
            }else{
                self::$save_data[$filename] = include_once($cachefile);
            }
        }
        
		if($times && ( GET_TIME - self::$save_data[$filename]['time'][$tag]) >= $times){
			return false;
		}
		
		if(empty(self::$save_data[$filename][$tag])=== true){
			return false;
		}
        
        self::$file_lock = 0;
		return self::$save_data[$filename][$tag];
	}
	
	public static function write($tag=null,$filename='',$data_array = array()){
		$cachefile = self::$dir.$filename;
		if(empty($tag) === true || empty($filename) === true || $tag === 'time' || empty($data_array)===true || self::$file_lock !== 0){
			return false;
		}
        
        if(is_array(self::$save_data[$filename]) === false)
                self::$save_data[$filename] = array();
		$tag = md5(trim($tag));
		self::$save_data[$filename]['time'][$tag] = GET_TIME;
		self::$save_data[$filename][$tag] = $data_array;
        
        self::$file_lock = 1;
        
        if(self::$month === 0){
            $write = self::$headerstr.serialize(self::$save_data[$filename]);
        }else{
            $write = sprintf("<?php \n defined('IN_SYSTEM') === false && exit('PHPnew Blog.'); \n return %s ;\n?>",var_export(self::$save_data[$filename],true));
        }
        $write_size = fun_put_contents($cachefile,$write,LOCK_EX);
        if($write_size){
            self::$file_lock = 0;
           	return $data_array;
        }
	    return false;
	}
    
    public static function dele($filename){
        if(is_file(self::$dir.$filename) === true){
            $bool = unlink(self::$dir.$filename);
            return $bool + 0;
        }
        return 0;
    }
}