<?php
class db_cache
{
	var $cache_id,$time_limit,$cache_filename;
	function db_cache($time_limit = 0){
		$this->set_time_limit($time_limit);
		
	}

	function get_cache_filename($string){
		$this->set_cache_id($string);
		return SQL_CACHEDIR.$this->get_cache_id().'.cache';
	}

	function set_cache_id($value){
		$this->cache_id = md5($value);
	}

	function get_cache_id(){
		return $this->cache_id;
	}

	function set_time_limit($seconds){
		if($seconds > 0)
			$this->time_limit = $seconds;
		else
			$this->time_limit = DB_CACHE_EXPIRE;
	}

	function get_time_limit(){
		return $this->time_limit;
	}

	function save_cachefile($data){
		// safe result into file.
		$stream = serialize($data);
		$fp = fopen($this->cache_filename,"w");
		fwrite($fp, $stream);
		fclose($fp);
		return unserialize(implode('',file($this->cache_filename)));
	}

	function process($sql){
		$file = $this->get_cache_filename($sql);
		$this->cache_filename = $file;
		if (file_exists($file) && filemtime($file) > (time() - $this->get_time_limit() )) {
			// aus cache holen
			return false;
		}else{
		        if (file_exists($file)) @unlink($file);
			return true;
		}
	}
}
