<?php

class cache {

    const RETRY_NUM = 100;

    private $cachefile;

    private $cacheexpire;

    private $content_val;

    public function __construct() {
        
    }

	public function set($cache_name, $expire=0) {
        $this->cachefile = GEN_ROOT . '/data/caches/' . $cache_name . '.cache.php';
        $this->cacheexpire = $expire;
    }

    public function isvalid() {
        @clearstatcache();
        if (!@file_exists($this->cachefile)) return false;
        if (!($mtime = @filemtime($this->cachefile))) return false;
        $nowtime = mktime();
        if(0 !== $this->cacheexpire) {
            if (($mtime + $this->cacheexpire) < $nowtime) {
                return false;
            }else{
                return true;
            }
        } else {
            return true;
        }
    }

    private function array_convert_string($array, $prefix='$result') {
        if(is_array($array)) {
            foreach($array as $key=>$val) {
                if(!is_array($val)) {
                    $this->content_val .= $prefix . '["' . $key . '"] = "' . $val . '";' . GEN_LINE_BREAK;
                } else {
                    $this->array_convert_string($val, $prefix.'["' . $key . '"]');
                }
            }
        }
    }

    public function make_cache($contents) {
        $content_val = '<?php' . GEN_LINE_BREAK;
     
        $this->array_convert_string($contents);
        $content_val .= $this->content_val;
        $content_val .= '?>';

        for ($i = 0; $i < self::RETRY_NUM; $i++) {

            $ft = @fopen($this->cachefile, "wb");

            if ($ft != false) break;

            if ($i == (self::RETRY_NUM-1)) return false;

        }
        @flock($ft,LOCK_UN);

        @flock($ft,LOCK_EX|LOCK_NB);

        for ($i = 0; $i < self::RETRY_NUM; $i++) {

            $tmp = @fwrite($ft,$content_val);
            if ($tmp != false) break;
            if ($i == (self::RETRY_NUM-1)) return false;
        }
        @flock($ft,LOCK_UN);
        @fclose($ft);
        @chmod($this->cachefile,0777);
        return true;
    }

    public function get_result() {
        if(!file_exists($this->cachefile)) {
            return false;
        }
        include_once $this->cachefile;
        return isset($result) ? $result : false;
    }

    public function clear_expired() {
        if(false === $this->isvalid()) {
            @unlink($this->cachefile);
        }
    }

    public function destroy() {
        @unlink($this->cachefile);
    }
}
?>
