<?php

/**
* Fast Cache Class
*
* Synopsis :
*
* <?php
* require_once('fastCache.php');
* $id = '123';
* $options = array(
*    'cacheDir' => '/tmp/',
*    'lifeTime' => 3600
* );
* $fastCache = new fastCache($options);
* if ($data = $fastCache->get($id)) {
*     // Cache hit !
*     // Content is in $data
*     // (...)
* } else {
*     // Cache miss !
*     // Put in $data datas to put in cache
*     // (...)
*     $fastCache->save($id, $data);
* }
* ?>
*
* @author Fabien MARTY <fab@php.net>
*/

class fastCache
{

    // --- Private properties ---
    
    /**
    * Directory where to put the cache files
    * (make sure to add a trailing slash)
    *
    * @var string $_cacheDir
    */
    var $_cacheDir = '/tmp/';
    
    /**
    * Enable / disable caching
    *
    * (can be very usefull for the debug of cached scripts)
    *
    * @var boolean $_caching
    */
    var $_caching = true;
    
    /**
    * Cache lifetime (in seconds)
    *
    * @var int $_lifeTime
    */
    var $_lifeTime = 3600;
    
    /**
    * Enable / disable fileLocking
    *
    * (can avoid cache corruption under bad circumstances)  
    *
    * @var boolean $_fileLocking
    */
    var $_fileLocking = true;
    
    /**
    * Timestamp of the last valid cache
    *
    * @var int $_refreshTime
    */
    var $_refreshTime;
    
    /**
    * File name (with path)
    *
    * @var string $_file
    */
    var $_file;
    
    // --- Public methods ---
    
    /**
    * Constructor
    *
    * $options is an assoc. Availables options are :
    * $options = array(
    *     'cacheDir' => directory where to put the cache files (string),
    *     'caching' => enable / disable caching (boolean),
    *     'lifeTime' => cache lifetime in seconds (int),
    *     'fileLocking' => enable / disable fileLocking (boolean)
    * );
    *
    * @param array $options options
    * @access public
    */
    function fastCache($options = NULL)
    {
        if (isset($options['cacheDir'])) $this->_cacheDir = $options['cacheDir'];
        if (isset($options['caching'])) $this->_caching = $options['caching'];
        if (isset($options['lifeTime'])) $this->_lifeTime = $options['lifeTime'];
        if (isset($options['fileLocking'])) $this->_fileLocking = $options['fileLocking'];
        $this->_refreshTime = time() - $this->_lifeTime;
    }
    
    /**
    * Test if a cache is available and (if yes) return it
    *
    * @param string $id cache id
    * @param string $group name of the cache group
    * @return string data of the cache (or false if no cache available)
    * @access public
    */
    function get($id, $group = 'default')
    {
        if ($this->_caching) {
            $this->_setFileName($id, $group);
            if (@filemtime($this->_file) > $this->_refreshTime) {
                return $this->_read();
            }
        }
        return false;
    }
    
    /**
    * Save some data in a cache file
    *
    * @param string $id cache id
    * @param string $data data to put in cache
    * @param string $group name of the cache group
    * @return boolean true if no problem
    * @access public
    */
    function save($id, $data, $group = 'default') 
    {
        if ($this->_caching) {
            $this->_setFileName($id, $group);
            return $this->_write($data);
        }
        return false;
    }
    
    /**
    * Remove a cache file
    *
    * @param string $id cache id
    * @param string $group name of the cache group
    * @return boolean true if no problem
    * @access public
    */
    function remove($id, $group)
    {
        $this->_setFileName($id, $group);
        if (!unlink($this->_file)) {
      		fastCache::_raiseError('fastCache : Unable to remove cache !', -3);   
            return false;
        }
        return true;
    }
    
    /**
    * Clean the cache
    *
    * if no group is specified all cache files will be destroyed
    * else only cache files of the specified group will be destroyed
    *
    * @param string $group name of the cache group
    * @return boolean true if no problem
    * @access public
    */
    function clean($group = false)     
    {
        $motif = ($group) ? "cache_$group_" : 'cache_';
        if (!($dh = opendir($this->_cacheDir))) {
    		fastCache::_raiseError('fastCache : Unable to open cache directory !', -4);   
            return false;
        }
        while ($file = readdir($dh)) {
            if (($file != '.') && ($file != '..')) {
                $file = $this->_cacheDir . $file;
                if (is_file($file)) {
                    if (strpos($file, $motif, 0)) {
                        if (!unlink($file)) {
                            fastCache::_raiseError('fastCache : Unable to remove cache !', -3);   
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
    
    // --- Private methods ---
    
    /**
    * Make a file name (with path)
    *
    * @param string $id cache id
    * @param string $group name of the group
    * @access private
    */
    function _setFileName($id, $group)
    {
        $this->_file = ($this->_cacheDir.'cache_'.$group.'_'.md5($id));
    }
    
    /**
    * Read the cache file and return the content
    *
    * @return string content of the cache file
    * @access private
    */
    function _read()
    {
        $fp = @fopen($this->_file, "r");
        if ($this->_fileLocking) flock($fp, LOCK_SH);
        if ($fp) {
			$data = '';
			while (($tmp = fread($fp, 4096))) {
				$data .= $tmp;
			}
            if ($this->_fileLocking) flock($fp, LOCK_UN);
			fclose($fp);
			return $data;
		}
   		fastCache::_raiseError('fastCache : Unable to read cache !', -2);   
        return false;
    }
    
    /**
    * Write the given data in the cache file
    *
    * @param string $data data to put in cache
    * @return boolean true if ok
    * @access private
    */
    function _write($data)
    {
        $fp = @fopen($this->_file, "w");
		if ($fp) {
            if ($this->_fileLocking) flock($fp, LOCK_EX);
			fwrite($fp, $data, strlen($data));
			if ($this->_fileLocking) flock($fp, LOCK_UN);
            fclose($fp);
            return true;
		}
		fastCache::_raiseError('fastCache : Unable to write cache !', -1);
        return false;
    }
    
    /**
    * Trigger a PEAR error
    *
    * To improve performances, the PEAR.php file is included dynamically.
    * The file is so included only when an error is triggered. So, in most
    * cases, the file isn't included and perfs are much better. 
    *
    * @param string $msg error message
    * @param int $code error code
    * @access private
    */
    function _raiseError($msg, $code)
    {
        include_once('PEAR.php');
        PEAR::raiseError($msg, $code, PEAR_ERROR_DIE);
    }
    
} 

?>