<?php
/**
 * 
 * @file cache.php
 * @copyright (c) 2005 - 2011 eifr.com
 * @license http://www.gnu.org/copyleft/gpl.html gnu/gpl
 * eifr is free software
 */
require_once(EIFR_ROOT . 'libraries/file.php');
class CCacheHelper {
    var $cache_extension = '_cache.php';
    var $name;
    var $cache_file;

    function __construct($name = '') {
        $this -> name = "_cache_" . $name;
        $this -> cache_file = EIFR_ROOT . 'cache/' . $name . $this -> cache_extension;
        Log_v(__FILE__, __LINE__, 'cache file: ' . $this -> cache_file . ' name: ' . $this -> name);
    } 

    function deleteCache() {
        if (file_exists($this -> cache_file)) {
            unlink($this -> cache_file);
        } 
    } 

    function getCache() {
        @include($this -> cache_file);
        if (isset(${$this->name})) {
            return ${$this->name};
        } else {
            return false;
        } 
    } 

    function writeCache($value) {
        $pre = "<?php\n//Cache Created at: " . date('Y-m-d H:i:s') . "\n";
        if (!is_array($value)) {
            // $value = $value;
            $str = "\$$this->name = '$value';";
        } else {
            $str = "\$$this->name = " . $this -> arrayToString($value) . ';';
        } 
        $end = "\n?>";
        $cachedata = $pre . $str . $end;
        if ($fp = @fopen($this -> cache_file, 'wb')) {
            flock($fp, LOCK_EX);
            fwrite($fp, $cachedata);
            flock($fp, LOCK_UN);
            fclose($fp);
            return true;
        } else {
            exit("Can not write to cache files($this->cache_file), please check cache directory");
            return false;
        } 
    } 

    function arrayToString($array, $level = 0) {
        if (!is_array($array)) {
            return "'" . $array . "'";
        } 
        if (is_array($array) && function_exists('var_export')) {
            return var_export($array, true);
        } 

        $space = '';
        for($i = 0; $i <= $level; $i++) {
            $space .= "\t";
        } 
        $evaluate = "Array (\n";
        $comma = $space;
        if (is_array($array)) {
            foreach($array as $key => $val) {
                $key = is_string($key) ? '\'' . addcslashes($key, '\'\\') . '\'' : $key;
                $val = !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\'' . addcslashes($val, '\'\\') . '\'' : $val;
                if (is_array($val)) {
                    $evaluate .= "$comma$key => " . $this -> arrayToString($val, $level + 1);
                } else {
                    $evaluate .= "$comma$key => $val";
                } 
                $comma = ",\n$space";
            } 
        } 
        $evaluate .= "\n$space)";
        return $evaluate;
    } 
} 

/**
 * End of file cache.php
 */