text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Output.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Cache_Core
 */
require_once 'Zend/Cache/Core.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Frontend_Output extends Zend_Cache_Core
{

    private $_idStack = array();

    /**
     * Constructor
     *
     * @param  array $options Associative array of options
     * @return void
     */
    public function __construct(array $options = array())
    {
        parent::__construct($options);
        $this->_idStack = array();
    }

    /**
     * Start the cache
     *
     * @param  string  $id                     Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @param  boolean $echoData               If set to true, datas are sent to the browser if the cache is hit (simpy returned else)
     * @return mixed True if the cache is hit (false else) with $echoData=true (default) ; string else (datas)
     */
    public function start($id, $doNotTestCacheValidity = false, $echoData = true)
    {
        $data = $this->load($id, $doNotTestCacheValidity);
        if ($data !== false) {
            if ( $echoData ) {
                echo($data);
                return true;
            } else {
                return $data;
            }
        }
        ob_start();
        ob_implicit_flush(false);
        $this->_idStack[] = $id;
        return false;
    }

    /**
     * Stop the cache
     *
     * @param  array   $tags             Tags array
     * @param  int     $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @param  string  $forcedDatas      If not null, force written datas with this
     * @param  boolean $echoData         If set to true, datas are sent to the browser
     * @param  int     $priority         integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
     * @return void
     */
    public function end($tags = array(), $specificLifetime = false, $forcedDatas = null, $echoData = true, $priority = 8)
    {
        if ($forcedDatas === null) {
            $data = ob_get_clean();
        } else {
            $data =& $forcedDatas;
        }
        $id = array_pop($this->_idStack);
        if ($id === null) {
            Zend_Cache::throwException('use of end() without a start()');
        }
        $this->save($data, $id, $tags, $specificLifetime, $priority);
        if ($echoData) {
            echo($data);
        }
    }

}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Page.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Cache_Core
 */
require_once 'Zend/Cache/Core.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Frontend_Page extends Zend_Cache_Core
{
    /**
     * This frontend specific options
     *
     * ====> (boolean) http_conditional :
     * - if true, http conditional mode is on
     * WARNING : http_conditional OPTION IS NOT IMPLEMENTED FOR THE MOMENT (TODO)
     *
     * ====> (boolean) debug_header :
     * - if true, a debug text is added before each cached pages
     *
     * ====> (boolean) content_type_memorization :
     * - deprecated => use memorize_headers instead
     * - if the Content-Type header is sent after the cache was started, the
     *   corresponding value can be memorized and replayed when the cache is hit
     *   (if false (default), the frontend doesn't take care of Content-Type header)
     *
     * ====> (array) memorize_headers :
     * - an array of strings corresponding to some HTTP headers name. Listed headers
     *   will be stored with cache datas and "replayed" when the cache is hit
     *
     * ====> (array) default_options :
     * - an associative array of default options :
     *     - (boolean) cache : cache is on by default if true
     *     - (boolean) cacheWithXXXVariables  (XXXX = 'Get', 'Post', 'Session', 'Files' or 'Cookie') :
     *       if true,  cache is still on even if there are some variables in this superglobal array
     *       if false, cache is off if there are some variables in this superglobal array
     *     - (boolean) makeIdWithXXXVariables (XXXX = 'Get', 'Post', 'Session', 'Files' or 'Cookie') :
     *       if true, we have to use the content of this superglobal array to make a cache id
     *       if false, the cache id won't be dependent of the content of this superglobal array
     *     - (int) specific_lifetime : cache specific lifetime
     *                                (false => global lifetime is used, null => infinite lifetime,
     *                                 integer => this lifetime is used), this "lifetime" is probably only
     *                                usefull when used with "regexps" array
     *     - (array) tags : array of tags (strings)
     *     - (int) priority : integer between 0 (very low priority) and 10 (maximum priority) used by
     *                        some particular backends
     *
     * ====> (array) regexps :
     * - an associative array to set options only for some REQUEST_URI
     * - keys are (pcre) regexps
     * - values are associative array with specific options to set if the regexp matchs on $_SERVER['REQUEST_URI']
     *   (see default_options for the list of available options)
     * - if several regexps match the $_SERVER['REQUEST_URI'], only the last one will be used
     *
     * @var array options
     */
    protected $_specificOptions = array(
        'http_conditional' => false,
        'debug_header' => false,
        'content_type_memorization' => false,
        'memorize_headers' => array(),
        'default_options' => array(
            'cache_with_get_variables' => false,
            'cache_with_post_variables' => false,
            'cache_with_session_variables' => false,
            'cache_with_files_variables' => false,
            'cache_with_cookie_variables' => false,
            'make_id_with_get_variables' => true,
            'make_id_with_post_variables' => true,
            'make_id_with_session_variables' => true,
            'make_id_with_files_variables' => true,
            'make_id_with_cookie_variables' => true,
            'cache' => true,
            'specific_lifetime' => false,
            'tags' => array(),
            'priority' => null
        ),
        'regexps' => array()
    );

    /**
     * Internal array to store some options
     *
     * @var array associative array of options
     */
    protected $_activeOptions = array();

    /**
     * If true, the page won't be cached
     *
     * @var boolean
     */
    protected $_cancel = false;

    /**
     * Constructor
     *
     * @param  array   $options                Associative array of options
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct(array $options = array())
    {
        while (list($name, $value) = each($options)) {
            $name = strtolower($name);
            switch ($name) {
                case 'regexps':
                    $this->_setRegexps($value);
                    break;
                case 'default_options':
                    $this->_setDefaultOptions($value);
                    break;
                case 'content_type_memorization':
                    $this->_setContentTypeMemorization($value);
                    break;
                default:
                    $this->setOption($name, $value);
            }
        }
        if (isset($this->_specificOptions['http_conditional'])) {
            if ($this->_specificOptions['http_conditional']) {
                Zend_Cache::throwException('http_conditional is not implemented for the moment !');
            }
        }
        $this->setOption('automatic_serialization', true);
    }

    /**
     * Specific setter for the 'default_options' option (with some additional tests)
     *
     * @param  array $options Associative array
     * @throws Zend_Cache_Exception
     * @return void
     */
    protected function _setDefaultOptions($options)
    {
        if (!is_array($options)) {
            Zend_Cache::throwException('default_options must be an array !');
        }
        foreach ($options as $key=>$value) {
            if (!is_string($key)) {
                Zend_Cache::throwException("invalid option [$key] !");
            }
            $key = strtolower($key);
            if (isset($this->_specificOptions['default_options'][$key])) {
                $this->_specificOptions['default_options'][$key] = $value;
            }
        }
    }

    /**
     * Set the deprecated contentTypeMemorization option
     *
     * @param boolean $value value
     * @return void
     * @deprecated
     */
    protected function _setContentTypeMemorization($value)
    {
        $found = null;
        foreach ($this->_specificOptions['memorize_headers'] as $key => $value) {
            if (strtolower($value) == 'content-type') {
                $found = $key;
            }
        }
        if ($value) {
            if (!$found) {
                $this->_specificOptions['memorize_headers'][] = 'Content-Type';
            }
        } else {
            if ($found) {
                unset($this->_specificOptions['memorize_headers'][$found]);
            }
        }
    }

    /**
     * Specific setter for the 'regexps' option (with some additional tests)
     *
     * @param  array $options Associative array
     * @throws Zend_Cache_Exception
     * @return void
     */
    protected function _setRegexps($regexps)
    {
        if (!is_array($regexps)) {
            Zend_Cache::throwException('regexps option must be an array !');
        }
        foreach ($regexps as $regexp=>$conf) {
            if (!is_array($conf)) {
                Zend_Cache::throwException('regexps option must be an array of arrays !');
            }
            $validKeys = array_keys($this->_specificOptions['default_options']);
            foreach ($conf as $key=>$value) {
                if (!is_string($key)) {
                    Zend_Cache::throwException("unknown option [$key] !");
                }
                $key = strtolower($key);
                if (!in_array($key, $validKeys)) {
                    unset($regexps[$regexp][$key]);
                }
            }
        }
        $this->setOption('regexps', $regexps);
    }

    /**
     * Start the cache
     *
     * @param  string  $id       (optional) A cache id (if you set a value here, maybe you have to use Output frontend instead)
     * @param  boolean $doNotDie For unit testing only !
     * @return boolean True if the cache is hit (false else)
     */
    public function start($id = false, $doNotDie = false)
    {
        $this->_cancel = false;
        $lastMatchingRegexp = null;
        if (isset($_SERVER['REQUEST_URI'])) {
            foreach ($this->_specificOptions['regexps'] as $regexp => $conf) {
                if (preg_match("`$regexp`", $_SERVER['REQUEST_URI'])) {
                    $lastMatchingRegexp = $regexp;
                }
            }
        }
        $this->_activeOptions = $this->_specificOptions['default_options'];
        if ($lastMatchingRegexp !== null) {
            $conf = $this->_specificOptions['regexps'][$lastMatchingRegexp];
            foreach ($conf as $key=>$value) {
                $this->_activeOptions[$key] = $value;
            }
        }
        if (!($this->_activeOptions['cache'])) {
            return false;
        }
        if (!$id) {
            $id = $this->_makeId();
            if (!$id) {
                return false;
            }
        }
        $array = $this->load($id);
        if ($array !== false) {
            $data = $array['data'];
            $headers = $array['headers'];
            if (!headers_sent()) {
                foreach ($headers as $key=>$headerCouple) {
                    $name = $headerCouple[0];
                    $value = $headerCouple[1];
                    header("$name: $value");
                }
            }
            if ($this->_specificOptions['debug_header']) {
                echo 'DEBUG HEADER : This is a cached page !';
            }
            echo $data;
            if ($doNotDie) {
                return true;
            }
            die();
        }
        ob_start(array($this, '_flush'));
        ob_implicit_flush(false);
        return false;
    }

    /**
     * Cancel the current caching process
     */
    public function cancel()
    {
        $this->_cancel = true;
    }

    /**
     * callback for output buffering
     * (shouldn't really be called manually)
     *
     * @param  string $data Buffered output
     * @return string Data to send to browser
     */
    public function _flush($data)
    {
        if ($this->_cancel) {
            return $data;
        }
        $contentType = null;
        $storedHeaders = array();
        $headersList = headers_list();
        foreach($this->_specificOptions['memorize_headers'] as $key=>$headerName) {
            foreach ($headersList as $headerSent) {
                $tmp = explode(':', $headerSent);
                $headerSentName = trim(array_shift($tmp));
                if (strtolower($headerName) == strtolower($headerSentName)) {
                    $headerSentValue = trim(implode(':', $tmp));
                    $storedHeaders[] = array($headerSentName, $headerSentValue);
                }
            }
        }
        $array = array(
            'data' => $data,
            'headers' => $storedHeaders
        );
        $this->save($array, null, $this->_activeOptions['tags'], $this->_activeOptions['specific_lifetime'], $this->_activeOptions['priority']);
        return $data;
    }

    /**
     * Make an id depending on REQUEST_URI and superglobal arrays (depending on options)
     *
     * @return mixed|false a cache id (string), false if the cache should have not to be used
     */
    protected function _makeId()
    {
        $tmp = $_SERVER['REQUEST_URI'];
        $array = explode('?', $tmp, 2);
          $tmp = $array[0];
        foreach (array('Get', 'Post', 'Session', 'Files', 'Cookie') as $arrayName) {
            $tmp2 = $this->_makePartialId($arrayName, $this->_activeOptions['cache_with_' . strtolower($arrayName) . '_variables'], $this->_activeOptions['make_id_with_' . strtolower($arrayName) . '_variables']);
            if ($tmp2===false) {
                return false;
            }
            $tmp = $tmp . $tmp2;
        }
        return md5($tmp);
    }

    /**
     * Make a partial id depending on options
     *
     * @param  string $arrayName Superglobal array name
     * @param  bool   $bool1     If true, cache is still on even if there are some variables in the superglobal array
     * @param  bool   $bool2     If true, we have to use the content of the superglobal array to make a partial id
     * @return mixed|false Partial id (string) or false if the cache should have not to be used
     */
    protected function _makePartialId($arrayName, $bool1, $bool2)
    {
        switch ($arrayName) {
        case 'Get':
            $var = $_GET;
            break;
        case 'Post':
            $var = $_POST;
            break;
        case 'Session':
            if (isset($_SESSION)) {
                $var = $_SESSION;
            } else {
                $var = null;
            }
            break;
        case 'Cookie':
            if (isset($_COOKIE)) {
                $var = $_COOKIE;
            } else {
                $var = null;
            }
            break;
        case 'Files':
            $var = $_FILES;
            break;
        default:
            return false;
        }
        if ($bool1) {
            if ($bool2) {
                return serialize($var);
            }
            return '';
        }
        if (count($var) > 0) {
            return false;
        }
        return '';
    }

}

repo_name: michael-romer/zf-boilerplate

repo_language: PHP

mime_type: text/html


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: File.php 24218 2011-07-10 01:22:58Z ramon $
 */

/**
 * @see Zend_Cache_Core
 */
require_once 'Zend/Cache/Core.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Frontend_File extends Zend_Cache_Core
{

    /**
     * Consts for master_files_mode
     */
    const MODE_AND = 'AND';
    const MODE_OR  = 'OR';

    /**
     * Available options
     *
     * ====> (string) master_file :
     * - a complete path of the master file
     * - deprecated (see master_files)
     *
     * ====> (array) master_files :
     * - an array of complete path of master files
     * - this option has to be set !
     *
     * ====> (string) master_files_mode :
     * - Zend_Cache_Frontend_File::MODE_AND or Zend_Cache_Frontend_File::MODE_OR
     * - if MODE_AND, then all master files have to be touched to get a cache invalidation
     * - if MODE_OR (default), then a single touched master file is enough to get a cache invalidation
     *
     * ====> (boolean) ignore_missing_master_files
     * - if set to true, missing master files are ignored silently
     * - if set to false (default), an exception is thrown if there is a missing master file
     * @var array available options
     */
    protected $_specificOptions = array(
        'master_file' => null,
        'master_files' => null,
        'master_files_mode' => 'OR',
        'ignore_missing_master_files' => false
    );

    /**
     * Master file mtimes
     *
     * Array of int
     *
     * @var array
     */
    private $_masterFile_mtimes = null;

    /**
     * Constructor
     *
     * @param  array $options Associative array of options
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct(array $options = array())
    {
        while (list($name, $value) = each($options)) {
            $this->setOption($name, $value);
        }
        if (!isset($this->_specificOptions['master_files'])) {
            Zend_Cache::throwException('master_files option must be set');
        }
    }

    /**
     * Change the master_files option
     *
     * @param array $masterFiles the complete paths and name of the master files
     */
    public function setMasterFiles(array $masterFiles)
    {
        $this->_specificOptions['master_file']  = null; // to keep a compatibility
        $this->_specificOptions['master_files'] = null;
        $this->_masterFile_mtimes = array();

        clearstatcache();
        $i = 0;
        foreach ($masterFiles as $masterFile) {
            if (file_exists($masterFile)) {
                $mtime = filemtime($masterFile);
            } else {
                $mtime = false;
            }

            if (!$this->_specificOptions['ignore_missing_master_files'] && !$mtime) {
                Zend_Cache::throwException('Unable to read master_file : ' . $masterFile);
            }

            $this->_masterFile_mtimes[$i] = $mtime;
            $this->_specificOptions['master_files'][$i] = $masterFile;
            if ($i === 0) { // to keep a compatibility
                $this->_specificOptions['master_file'] = $masterFile;
            }

            $i++;
        }
    }

    /**
     * Change the master_file option
     *
     * To keep the compatibility
     *
     * @deprecated
     * @param string $masterFile the complete path and name of the master file
     */
    public function setMasterFile($masterFile)
    {
          $this->setMasterFiles(array($masterFile));
    }

    /**
     * Public frontend to set an option
     *
     * Just a wrapper to get a specific behaviour for master_file
     *
     * @param  string $name  Name of the option
     * @param  mixed  $value Value of the option
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function setOption($name, $value)
    {
        if ($name == 'master_file') {
            $this->setMasterFile($value);
        } else if ($name == 'master_files') {
            $this->setMasterFiles($value);
        } else {
            parent::setOption($name, $value);
        }
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * @param  string  $id                     Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @param  boolean $doNotUnserialize       Do not serialize (even if automatic_serialization is true) => for internal use
     * @return mixed|false Cached datas
     */
    public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false)
    {
        if (!$doNotTestCacheValidity) {
            if ($this->test($id)) {
                return parent::load($id, true, $doNotUnserialize);
            }
            return false;
        }
        return parent::load($id, true, $doNotUnserialize);
    }

    /**
     * Test if a cache is available for the given id
     *
     * @param  string $id Cache id
     * @return int|false Last modified time of cache entry if it is available, false otherwise
     */
    public function test($id)
    {
        $lastModified = parent::test($id);
        if ($lastModified) {
            if ($this->_specificOptions['master_files_mode'] == self::MODE_AND) {
                // MODE_AND
                foreach($this->_masterFile_mtimes as $masterFileMTime) {
                    if ($masterFileMTime) {
                        if ($lastModified > $masterFileMTime) {
                            return $lastModified;
                        }
                    }
                }
            } else {
                // MODE_OR
                $res = true;
                foreach($this->_masterFile_mtimes as $masterFileMTime) {
                    if ($masterFileMTime) {
                        if ($lastModified <= $masterFileMTime) {
                            return false;
                        }
                    }
                }
                return $lastModified;
            }
        }
        return false;
    }

}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Function.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Cache_Core
 */
require_once 'Zend/Cache/Core.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Frontend_Function extends Zend_Cache_Core
{
    /**
     * This frontend specific options
     *
     * ====> (boolean) cache_by_default :
     * - if true, function calls will be cached by default
     *
     * ====> (array) cached_functions :
     * - an array of function names which will be cached (even if cache_by_default = false)
     *
     * ====> (array) non_cached_functions :
     * - an array of function names which won't be cached (even if cache_by_default = true)
     *
     * @var array options
     */
    protected $_specificOptions = array(
        'cache_by_default' => true,
        'cached_functions' => array(),
        'non_cached_functions' => array()
    );

    /**
     * Constructor
     *
     * @param  array $options Associative array of options
     * @return void
     */
    public function __construct(array $options = array())
    {
        while (list($name, $value) = each($options)) {
            $this->setOption($name, $value);
        }
        $this->setOption('automatic_serialization', true);
    }

    /**
     * Main method : call the specified function or get the result from cache
     *
     * @param  callback $callback         A valid callback
     * @param  array    $parameters       Function parameters
     * @param  array    $tags             Cache tags
     * @param  int      $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @param  int      $priority         integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
     * @return mixed Result
     */
    public function call($callback, array $parameters = array(), $tags = array(), $specificLifetime = false, $priority = 8)
    {
        if (!is_callable($callback, true, $name)) {
            Zend_Cache::throwException('Invalid callback');
        }

        $cacheBool1 = $this->_specificOptions['cache_by_default'];
        $cacheBool2 = in_array($name, $this->_specificOptions['cached_functions']);
        $cacheBool3 = in_array($name, $this->_specificOptions['non_cached_functions']);
        $cache = (($cacheBool1 || $cacheBool2) && (!$cacheBool3));
        if (!$cache) {
            // Caching of this callback is disabled
            return call_user_func_array($callback, $parameters);
        }

        $id = $this->_makeId($callback, $parameters);
        if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1])) {
            // A cache is available
            $output = $rs[0];
            $return = $rs[1];
        } else {
            // A cache is not available (or not valid for this frontend)
            ob_start();
            ob_implicit_flush(false);
            $return = call_user_func_array($callback, $parameters);
            $output = ob_get_clean();
            $data = array($output, $return);
            $this->save($data, $id, $tags, $specificLifetime, $priority);
        }

        echo $output;
        return $return;
    }

    /**
     * ZF-9970
     *
     * @deprecated
     */
    private function _makeId($callback, array $args)
    {
        return $this->makeId($callback, $args);
    }

    /**
     * Make a cache id from the function name and parameters
     *
     * @param  callback $callback A valid callback
     * @param  array    $args     Function parameters
     * @throws Zend_Cache_Exception
     * @return string Cache id
     */
    public function makeId($callback, array $args = array())
    {
        if (!is_callable($callback, true, $name)) {
            Zend_Cache::throwException('Invalid callback');
        }

        // functions, methods and classnames are case-insensitive
        $name = strtolower($name);

        // generate a unique id for object callbacks
        if (is_object($callback)) { // Closures & __invoke
            $object = $callback;
        } elseif (isset($callback[0])) { // array($object, 'method')
            $object = $callback[0];
        }
        if (isset($object)) {
            try {
                $tmp = @serialize($callback);
            } catch (Exception $e) {
                Zend_Cache::throwException($e->getMessage());
            }
            if (!$tmp) {
                $lastErr = error_get_last();
                Zend_Cache::throwException("Can't serialize callback object to generate id: {$lastErr['message']}");
            }
            $name.= '__' . $tmp;
        }

        // generate a unique id for arguments
        $argsStr = '';
        if ($args) {
            try {
                $argsStr = @serialize(array_values($args));
            } catch (Exception $e) {
                Zend_Cache::throwException($e->getMessage());
            }
            if (!$argsStr) {
                $lastErr = error_get_last();
                throw Zend_Cache::throwException("Can't serialize arguments to generate id: {$lastErr['message']}");
            }
        }

        return md5($name . $argsStr);
    }

}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Capture.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Cache_Core
 */
require_once 'Zend/Cache/Core.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Frontend_Capture extends Zend_Cache_Core
{
    /**
     * Page identifiers
     * @var array
     */
    protected $_idStack = array();

    /**
     * Tags
     * @var array
     */
    protected $_tags = array();

    protected $_extension = null;

    /**
     * Start the cache
     *
     * @param  string  $id Cache id
     * @return mixed True if the cache is hit (false else) with $echoData=true (default) ; string else (datas)
     */
    public function start($id, array $tags, $extension = null)
    {
        $this->_tags = $tags;
        $this->_extension = $extension;
        ob_start(array($this, '_flush'));
        ob_implicit_flush(false);
        $this->_idStack[] = $id;
        return false;
    }

    /**
     * callback for output buffering
     * (shouldn't really be called manually)
     *
     * @param  string $data Buffered output
     * @return string Data to send to browser
     */
    public function _flush($data)
    {
        $id = array_pop($this->_idStack);
        if ($id === null) {
            Zend_Cache::throwException('use of _flush() without a start()');
        }
        if ($this->_extension) {
            $this->save(serialize(array($data, $this->_extension)), $id, $this->_tags);
        } else {
            $this->save($data, $id, $this->_tags);
        }
        return $data;
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Class.php 24032 2011-05-10 21:08:20Z mabe $
 */

/**
 * @see Zend_Cache_Core
 */
require_once 'Zend/Cache/Core.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Frontend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Frontend_Class extends Zend_Cache_Core
{
    /**
     * Available options
     *
     * ====> (mixed) cached_entity :
     * - if set to a class name, we will cache an abstract class and will use only static calls
     * - if set to an object, we will cache this object methods
     *
     * ====> (boolean) cache_by_default :
     * - if true, method calls will be cached by default
     *
     * ====> (array) cached_methods :
     * - an array of method names which will be cached (even if cache_by_default = false)
     *
     * ====> (array) non_cached_methods :
     * - an array of method names which won't be cached (even if cache_by_default = true)
     *
     * @var array available options
     */
    protected $_specificOptions = array(
        'cached_entity' => null,
        'cache_by_default' => true,
        'cached_methods' => array(),
        'non_cached_methods' => array()
    );

    /**
     * Tags array
     *
     * @var array
     */
    private $_tags = array();

    /**
     * SpecificLifetime value
     *
     * false => no specific life time
     *
     * @var int
     */
    private $_specificLifetime = false;

    /**
     * The cached object or the name of the cached abstract class
     *
     * @var mixed
     */
    private $_cachedEntity = null;

     /**
      * The class name of the cached object or cached abstract class
      *
      * Used to differentiate between different classes with the same method calls.
      *
      * @var string
      */
    private $_cachedEntityLabel = '';

    /**
     * Priority (used by some particular backends)
     *
     * @var int
     */
    private $_priority = 8;

    /**
     * Constructor
     *
     * @param  array $options Associative array of options
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct(array $options = array())
    {
        while (list($name, $value) = each($options)) {
            $this->setOption($name, $value);
        }
        if ($this->_specificOptions['cached_entity'] === null) {
            Zend_Cache::throwException('cached_entity must be set !');
        }
        $this->setCachedEntity($this->_specificOptions['cached_entity']);
        $this->setOption('automatic_serialization', true);
    }

    /**
     * Set a specific life time
     *
     * @param  int $specificLifetime
     * @return void
     */
    public function setSpecificLifetime($specificLifetime = false)
    {
        $this->_specificLifetime = $specificLifetime;
    }

    /**
     * Set the priority (used by some particular backends)
     *
     * @param int $priority integer between 0 (very low priority) and 10 (maximum priority)
     */
    public function setPriority($priority)
    {
        $this->_priority = $priority;
    }

    /**
     * Public frontend to set an option
     *
     * Just a wrapper to get a specific behaviour for cached_entity
     *
     * @param  string $name  Name of the option
     * @param  mixed  $value Value of the option
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function setOption($name, $value)
    {
        if ($name == 'cached_entity') {
            $this->setCachedEntity($value);
        } else {
            parent::setOption($name, $value);
        }
    }

    /**
     * Specific method to set the cachedEntity
     *
     * if set to a class name, we will cache an abstract class and will use only static calls
     * if set to an object, we will cache this object methods
     *
     * @param mixed $cachedEntity
     */
    public function setCachedEntity($cachedEntity)
    {
        if (!is_string($cachedEntity) && !is_object($cachedEntity)) {
            Zend_Cache::throwException('cached_entity must be an object or a class name');
        }
        $this->_cachedEntity = $cachedEntity;
        $this->_specificOptions['cached_entity'] = $cachedEntity;
        if (is_string($this->_cachedEntity)){
            $this->_cachedEntityLabel = $this->_cachedEntity;
        } else {
            $ro = new ReflectionObject($this->_cachedEntity);
            $this->_cachedEntityLabel = $ro->getName();
        }
    }

    /**
     * Set the cache array
     *
     * @param  array $tags
     * @return void
     */
    public function setTagsArray($tags = array())
    {
        $this->_tags = $tags;
    }

    /**
     * Main method : call the specified method or get the result from cache
     *
     * @param  string $name       Method name
     * @param  array  $parameters Method parameters
     * @return mixed Result
     */
    public function __call($name, $parameters)
    {
        $callback = array($this->_cachedEntity, $name);

        if (!is_callable($callback, false)) {
            Zend_Cache::throwException('Invalid callback');
        }

        $cacheBool1 = $this->_specificOptions['cache_by_default'];
        $cacheBool2 = in_array($name, $this->_specificOptions['cached_methods']);
        $cacheBool3 = in_array($name, $this->_specificOptions['non_cached_methods']);
        $cache = (($cacheBool1 || $cacheBool2) && (!$cacheBool3));
        if (!$cache) {
            // We do not have not cache
            return call_user_func_array($callback, $parameters);
        }

        $id = $this->_makeId($name, $parameters);
        if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1]) ) {
            // A cache is available
            $output = $rs[0];
            $return = $rs[1];
        } else {
            // A cache is not available (or not valid for this frontend)
            ob_start();
            ob_implicit_flush(false);

            try {
                $return = call_user_func_array($callback, $parameters);
                $output = ob_get_clean();
                $data = array($output, $return);
                $this->save($data, $id, $this->_tags, $this->_specificLifetime, $this->_priority);
            } catch (Exception $e) {
                ob_end_clean();
                throw $e;
            }
        }

        echo $output;
        return $return;
    }

    /**
     * ZF-9970
     *
     * @deprecated
     */
    private function _makeId($name, $args)
    {
        return $this->makeId($name, $args);
    }

    /**
     * Make a cache id from the method name and parameters
     *
     * @param  string $name Method name
     * @param  array  $args Method parameters
     * @return string Cache id
     */
    public function makeId($name, array $args = array())
    {
        return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($args));
    }

}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Apc.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Cache_Backend_Interface
 */
require_once 'Zend/Cache/Backend/ExtendedInterface.php';

/**
 * @see Zend_Cache_Backend
 */
require_once 'Zend/Cache/Backend.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Backend_Apc extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
    /**
     * Log message
     */
    const TAGS_UNSUPPORTED_BY_CLEAN_OF_APC_BACKEND = 'Zend_Cache_Backend_Apc::clean() : tags are unsupported by the Apc backend';
    const TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND =  'Zend_Cache_Backend_Apc::save() : tags are unsupported by the Apc backend';

    /**
     * Constructor
     *
     * @param  array $options associative array of options
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct(array $options = array())
    {
        if (!extension_loaded('apc')) {
            Zend_Cache::throwException('The apc extension must be loaded for using this backend !');
        }
        parent::__construct($options);
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * WARNING $doNotTestCacheValidity=true is unsupported by the Apc backend
     *
     * @param  string  $id                     cache id
     * @param  boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
     * @return string cached datas (or false)
     */
    public function load($id, $doNotTestCacheValidity = false)
    {
        $tmp = apc_fetch($id);
        if (is_array($tmp)) {
            return $tmp[0];
        }
        return false;
    }

    /**
     * Test if a cache is available or not (for the given id)
     *
     * @param  string $id cache id
     * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
     */
    public function test($id)
    {
        $tmp = apc_fetch($id);
        if (is_array($tmp)) {
            return $tmp[1];
        }
        return false;
    }

    /**
     * Save some string datas into a cache record
     *
     * Note : $data is always "string" (serialization is done by the
     * core not by the backend)
     *
     * @param string $data datas to cache
     * @param string $id cache id
     * @param array $tags array of strings, the cache record will be tagged by each string entry
     * @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @return boolean true if no problem
     */
    public function save($data, $id, $tags = array(), $specificLifetime = false)
    {
        $lifetime = $this->getLifetime($specificLifetime);
        $result = apc_store($id, array($data, time(), $lifetime), $lifetime);
        if (count($tags) > 0) {
            $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
        }
        return $result;
    }

    /**
     * Remove a cache record
     *
     * @param  string $id cache id
     * @return boolean true if no problem
     */
    public function remove($id)
    {
        return apc_delete($id);
    }

    /**
     * Clean some cache records
     *
     * Available modes are :
     * 'all' (default)  => remove all cache entries ($tags is not used)
     * 'old'            => unsupported
     * 'matchingTag'    => unsupported
     * 'notMatchingTag' => unsupported
     * 'matchingAnyTag' => unsupported
     *
     * @param  string $mode clean mode
     * @param  array  $tags array of tags
     * @throws Zend_Cache_Exception
     * @return boolean true if no problem
     */
    public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
    {
        switch ($mode) {
            case Zend_Cache::CLEANING_MODE_ALL:
                return apc_clear_cache('user');
                break;
            case Zend_Cache::CLEANING_MODE_OLD:
                $this->_log("Zend_Cache_Backend_Apc::clean() : CLEANING_MODE_OLD is unsupported by the Apc backend");
                break;
            case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
            case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
            case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
                $this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_APC_BACKEND);
                break;
            default:
                Zend_Cache::throwException('Invalid mode for clean() method');
                break;
        }
    }

    /**
     * Return true if the automatic cleaning is available for the backend
     *
     * DEPRECATED : use getCapabilities() instead
     *
     * @deprecated
     * @return boolean
     */
    public function isAutomaticCleaningAvailable()
    {
        return false;
    }

    /**
     * Return the filling percentage of the backend storage
     *
     * @throws Zend_Cache_Exception
     * @return int integer between 0 and 100
     */
    public function getFillingPercentage()
    {
        $mem = apc_sma_info(true);
        $memSize    = $mem['num_seg'] * $mem['seg_size'];
        $memAvailable= $mem['avail_mem'];
        $memUsed = $memSize - $memAvailable;
        if ($memSize == 0) {
            Zend_Cache::throwException('can\'t get apc memory size');
        }
        if ($memUsed > $memSize) {
            return 100;
        }
        return ((int) (100. * ($memUsed / $memSize)));
    }

    /**
     * Return an array of stored tags
     *
     * @return array array of stored tags (string)
     */
    public function getTags()
    {
        $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
        return array();
    }

    /**
     * Return an array of stored cache ids which match given tags
     *
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param array $tags array of tags
     * @return array array of matching cache ids (string)
     */
    public function getIdsMatchingTags($tags = array())
    {
        $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
        return array();
    }

    /**
     * Return an array of stored cache ids which don't match given tags
     *
     * In case of multiple tags, a logical OR is made between tags
     *
     * @param array $tags array of tags
     * @return array array of not matching cache ids (string)
     */
    public function getIdsNotMatchingTags($tags = array())
    {
        $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
        return array();
    }

    /**
     * Return an array of stored cache ids which match any given tags
     *
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param array $tags array of tags
     * @return array array of any matching cache ids (string)
     */
    public function getIdsMatchingAnyTags($tags = array())
    {
        $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
        return array();
    }

    /**
     * Return an array of stored cache ids
     *
     * @return array array of stored cache ids (string)
     */
    public function getIds()
    {
        $res = array();
        $array = apc_cache_info('user', false);
        $records = $array['cache_list'];
        foreach ($records as $record) {
            $res[] = $record['info'];
        }
        return $res;
    }

    /**
     * Return an array of metadatas for the given cache id
     *
     * The array must include these keys :
     * - expire : the expire timestamp
     * - tags : a string array of tags
     * - mtime : timestamp of last modification time
     *
     * @param string $id cache id
     * @return array array of metadatas (false if the cache id is not found)
     */
    public function getMetadatas($id)
    {
        $tmp = apc_fetch($id);
        if (is_array($tmp)) {
            $data = $tmp[0];
            $mtime = $tmp[1];
            if (!isset($tmp[2])) {
                // because this record is only with 1.7 release
                // if old cache records are still there...
                return false;
            }
            $lifetime = $tmp[2];
            return array(
                'expire' => $mtime + $lifetime,
                'tags' => array(),
                'mtime' => $mtime
            );
        }
        return false;
    }

    /**
     * Give (if possible) an extra lifetime to the given cache id
     *
     * @param string $id cache id
     * @param int $extraLifetime
     * @return boolean true if ok
     */
    public function touch($id, $extraLifetime)
    {
        $tmp = apc_fetch($id);
        if (is_array($tmp)) {
            $data = $tmp[0];
            $mtime = $tmp[1];
            if (!isset($tmp[2])) {
                // because this record is only with 1.7 release
                // if old cache records are still there...
                return false;
            }
            $lifetime = $tmp[2];
            $newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
            if ($newLifetime <=0) {
                return false;
            }
            apc_store($id, array($data, time(), $newLifetime), $newLifetime);
            return true;
        }
        return false;
    }

    /**
     * Return an associative array of capabilities (booleans) of the backend
     *
     * The array must include these keys :
     * - automatic_cleaning (is automating cleaning necessary)
     * - tags (are tags supported)
     * - expired_read (is it possible to read expired cache records
     *                 (for doNotTestCacheValidity option for example))
     * - priority does the backend deal with priority when saving
     * - infinite_lifetime (is infinite lifetime can work with this backend)
     * - get_list (is it possible to get the list of cache ids and the complete list of tags)
     *
     * @return array associative of with capabilities
     */
    public function getCapabilities()
    {
        return array(
            'automatic_cleaning' => false,
            'tags' => false,
            'expired_read' => false,
            'priority' => false,
            'infinite_lifetime' => false,
            'get_list' => true
        );
    }

}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Test.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Cache_Backend_Interface
 */
require_once 'Zend/Cache/Backend/ExtendedInterface.php';

/**
 * @see Zend_Cache_Backend
 */
require_once 'Zend/Cache/Backend.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Backend_Test extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
    /**
     * Available options
     *
     * @var array available options
     */
    protected $_options = array();

    /**
     * Frontend or Core directives
     *
     * @var array directives
     */
    protected $_directives = array();

    /**
     * Array to log actions
     *
     * @var array $_log
     */
    private $_log = array();

    /**
     * Current index for log array
     *
     * @var int $_index
     */
    private $_index = 0;

    /**
     * Constructor
     *
     * @param  array $options associative array of options
     * @return void
     */
    public function __construct($options = array())
    {
        $this->_addLog('construct', array($options));
    }

    /**
     * Set the frontend directives
     *
     * @param  array $directives assoc of directives
     * @return void
     */
    public function setDirectives($directives)
    {
        $this->_addLog('setDirectives', array($directives));
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * For this test backend only, if $id == 'false', then the method will return false
     * if $id == 'serialized', the method will return a serialized array
     * ('foo' else)
     *
     * @param  string  $id                     Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @return string Cached datas (or false)
     */
    public function load($id, $doNotTestCacheValidity = false)
    {
        $this->_addLog('get', array($id, $doNotTestCacheValidity));

        if ( $id == 'false'
          || $id == 'd8523b3ee441006261eeffa5c3d3a0a7'
          || $id == 'e83249ea22178277d5befc2c5e2e9ace'
          || $id == '40f649b94977c0a6e76902e2a0b43587'
          || $id == '88161989b73a4cbfd0b701c446115a99'
          || $id == '205fc79cba24f0f0018eb92c7c8b3ba4'
          || $id == '170720e35f38150b811f68a937fb042d')
        {
            return false;
        }
        if ($id=='serialized') {
            return serialize(array('foo'));
        }
        if ($id=='serialized2') {
            return serialize(array('headers' => array(), 'data' => 'foo'));
        }
        if ( $id == '71769f39054f75894288e397df04e445' || $id == '615d222619fb20b527168340cebd0578'
          || $id == '8a02d218a5165c467e7a5747cc6bd4b6' || $id == '648aca1366211d17cbf48e65dc570bee'
          || $id == '4a923ef02d7f997ca14d56dfeae25ea7') {
            return serialize(array('foo', 'bar'));
        }
        return 'foo';
    }

    /**
     * Test if a cache is available or not (for the given id)
     *
     * For this test backend only, if $id == 'false', then the method will return false
     * (123456 else)
     *
     * @param  string $id Cache id
     * @return mixed|false false (a cache is not available) or "last modified" timestamp (int) of the available cache record
     */
    public function test($id)
    {
        $this->_addLog('test', array($id));
        if ($id=='false') {
            return false;
        }
        if (($id=='3c439c922209e2cb0b54d6deffccd75a')) {
            return false;
        }
        return 123456;
    }

    /**
     * Save some string datas into a cache record
     *
     * For this test backend only, if $id == 'false', then the method will return false
     * (true else)
     *
     * @param  string $data             Datas to cache
     * @param  string $id               Cache id
     * @param  array  $tags             Array of strings, the cache record will be tagged by each string entry
     * @param  int    $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @return boolean True if no problem
     */
    public function save($data, $id, $tags = array(), $specificLifetime = false)
    {
        $this->_addLog('save', array($data, $id, $tags));
        if (substr($id,-5)=='false') {
            return false;
        }
        return true;
    }

    /**
     * Remove a cache record
     *
     * For this test backend only, if $id == 'false', then the method will return false
     * (true else)
     *
     * @param  string $id Cache id
     * @return boolean True if no problem
     */
    public function remove($id)
    {
        $this->_addLog('remove', array($id));
        if (substr($id,-5)=='false') {
            return false;
        }
        return true;
    }

    /**
     * Clean some cache records
     *
     * For this test backend only, if $mode == 'false', then the method will return false
     * (true else)
     *
     * Available modes are :
     * Zend_Cache::CLEANING_MODE_ALL (default)    => remove all cache entries ($tags is not used)
     * Zend_Cache::CLEANING_MODE_OLD              => remove too old cache entries ($tags is not used)
     * Zend_Cache::CLEANING_MODE_MATCHING_TAG     => remove cache entries matching all given tags
     *                                               ($tags can be an array of strings or a single string)
     * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
     *                                               ($tags can be an array of strings or a single string)
     *
     * @param  string $mode Clean mode
     * @param  array  $tags Array of tags
     * @return boolean True if no problem
     */
    public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
    {
        $this->_addLog('clean', array($mode, $tags));
        if ($mode=='false') {
            return false;
        }
        return true;
    }

    /**
     * Get the last log
     *
     * @return string The last log
     */
    public function getLastLog()
    {
        return $this->_log[$this->_index - 1];
    }

    /**
     * Get the log index
     *
     * @return int Log index
     */
    public function getLogIndex()
    {
        return $this->_index;
    }

    /**
     * Get the complete log array
     *
     * @return array Complete log array
     */
    public function getAllLogs()
    {
        return $this->_log;
    }

    /**
     * Return true if the automatic cleaning is available for the backend
     *
     * @return boolean
     */
    public function isAutomaticCleaningAvailable()
    {
        return true;
    }

    /**
     * Return an array of stored cache ids
     *
     * @return array array of stored cache ids (string)
     */
    public function getIds()
    {
        return array(
            'prefix_id1', 'prefix_id2'
        );
    }

    /**
     * Return an array of stored tags
     *
     * @return array array of stored tags (string)
     */
    public function getTags()
    {
        return array(
            'tag1', 'tag2'
        );
    }

    /**
     * Return an array of stored cache ids which match given tags
     *
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param array $tags array of tags
     * @return array array of matching cache ids (string)
     */
    public function getIdsMatchingTags($tags = array())
    {
        if ($tags == array('tag1', 'tag2')) {
            return array('prefix_id1', 'prefix_id2');
        }

        return array();
    }

    /**
     * Return an array of stored cache ids which don't match given tags
     *
     * In case of multiple tags, a logical OR is made between tags
     *
     * @param array $tags array of tags
     * @return array array of not matching cache ids (string)
     */
    public function getIdsNotMatchingTags($tags = array())
    {
        if ($tags == array('tag3', 'tag4')) {
            return array('prefix_id3', 'prefix_id4');
        }

        return array();
    }

    /**
     * Return an array of stored cache ids which match any given tags
     *
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param array $tags array of tags
     * @return array array of any matching cache ids (string)
     */
    public function getIdsMatchingAnyTags($tags = array())
    {
        if ($tags == array('tag5', 'tag6')) {
            return array('prefix_id5', 'prefix_id6');
        }

        return array();
    }

    /**
     * Return the filling percentage of the backend storage
     *
     * @return int integer between 0 and 100
     */
    public function getFillingPercentage()
    {
        return 50;
    }

    /**
     * Return an array of metadatas for the given cache id
     *
     * The array must include these keys :
     * - expire : the expire timestamp
     * - tags : a string array of tags
     * - mtime : timestamp of last modification time
     *
     * @param string $id cache id
     * @return array array of metadatas (false if the cache id is not found)
     */
    public function getMetadatas($id)
    {
        return false;
    }

    /**
     * Give (if possible) an extra lifetime to the given cache id
     *
     * @param string $id cache id
     * @param int $extraLifetime
     * @return boolean true if ok
     */
    public function touch($id, $extraLifetime)
    {
        return true;
    }

    /**
     * Return an associative array of capabilities (booleans) of the backend
     *
     * The array must include these keys :
     * - automatic_cleaning (is automating cleaning necessary)
     * - tags (are tags supported)
     * - expired_read (is it possible to read expired cache records
     *                 (for doNotTestCacheValidity option for example))
     * - priority does the backend deal with priority when saving
     * - infinite_lifetime (is infinite lifetime can work with this backend)
     * - get_list (is it possible to get the list of cache ids and the complete list of tags)
     *
     * @return array associative of with capabilities
     */
    public function getCapabilities()
    {
        return array(
            'automatic_cleaning' => true,
            'tags'               => true,
            'expired_read'       => false,
            'priority'           => true,
            'infinite_lifetime'  => true,
            'get_list'           => true
        );
    }

    /**
     * Add an event to the log array
     *
     * @param  string $methodName MethodName
     * @param  array  $args       Arguments
     * @return void
     */
    private function _addLog($methodName, $args)
    {
        $this->_log[$this->_index] = array(
            'methodName' => $methodName,
            'args' => $args
        );
        $this->_index = $this->_index + 1;
    }

}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Static.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Cache_Backend_Interface
 */
require_once 'Zend/Cache/Backend/Interface.php';

/**
 * @see Zend_Cache_Backend
 */
require_once 'Zend/Cache/Backend.php';

/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Backend_Static
    extends Zend_Cache_Backend
    implements Zend_Cache_Backend_Interface
{
    const INNER_CACHE_NAME = 'zend_cache_backend_static_tagcache';

    /**
     * Static backend options
     * @var array
     */
    protected $_options = array(
        'public_dir'            => null,
        'sub_dir'               => 'html',
        'file_extension'        => '.html',
        'index_filename'        => 'index',
        'file_locking'          => true,
        'cache_file_umask'      => 0600,
        'cache_directory_umask' => 0700,
        'debug_header'          => false,
        'tag_cache'             => null,
        'disable_caching'       => false
    );

    /**
     * Cache for handling tags
     * @var Zend_Cache_Core
     */
    protected $_tagCache = null;

    /**
     * Tagged items
     * @var array
     */
    protected $_tagged = null;

    /**
     * Interceptor child method to handle the case where an Inner
     * Cache object is being set since it's not supported by the
     * standard backend interface
     *
     * @param  string $name
     * @param  mixed $value
     * @return Zend_Cache_Backend_Static
     */
    public function setOption($name, $value)
    {
        if ($name == 'tag_cache') {
            $this->setInnerCache($value);
        } else {
            parent::setOption($name, $value);
        }
        return $this;
    }

    /**
     * Retrieve any option via interception of the parent's statically held
     * options including the local option for a tag cache.
     *
     * @param  string $name
     * @return mixed
     */
    public function getOption($name)
    {
        if ($name == 'tag_cache') {
            return $this->getInnerCache();
        } else {
            if (in_array($name, $this->_options)) {
                return $this->_options[$name];
            }
            if ($name == 'lifetime') {
                return parent::getLifetime();
            }
            return null;
        }
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * Note : return value is always "string" (unserialization is done by the core not by the backend)
     *
     * @param  string  $id                     Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @return string|false cached datas
     */
    public function load($id, $doNotTestCacheValidity = false)
    {
        if (($id = (string)$id) === '') {
            $id = $this->_detectId();
        } else {
            $id = $this->_decodeId($id);
        }
        if (!$this->_verifyPath($id)) {
            Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
        }
        if ($doNotTestCacheValidity) {
            $this->_log("Zend_Cache_Backend_Static::load() : \$doNotTestCacheValidity=true is unsupported by the Static backend");
        }

        $fileName = basename($id);
        if ($fileName === '') {
            $fileName = $this->_options['index_filename'];
        }
        $pathName = $this->_options['public_dir'] . dirname($id);
        $file     = rtrim($pathName, '/') . '/' . $fileName . $this->_options['file_extension'];
        if (file_exists($file)) {
            $content = file_get_contents($file);
            return $content;
        }

        return false;
    }

    /**
     * Test if a cache is available or not (for the given id)
     *
     * @param  string $id cache id
     * @return bool
     */
    public function test($id)
    {
        $id = $this->_decodeId($id);
        if (!$this->_verifyPath($id)) {
            Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
        }

        $fileName = basename($id);
        if ($fileName === '') {
            $fileName = $this->_options['index_filename'];
        }
        if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
            $this->_tagged = $tagged;
        } elseif (!$this->_tagged) {
            return false;
        }
        $pathName = $this->_options['public_dir'] . dirname($id);

        // Switch extension if needed
        if (isset($this->_tagged[$id])) {
            $extension = $this->_tagged[$id]['extension'];
        } else {
            $extension = $this->_options['file_extension'];
        }
        $file     = $pathName . '/' . $fileName . $extension;
        if (file_exists($file)) {
            return true;
        }
        return false;
    }

    /**
     * Save some string datas into a cache record
     *
     * Note : $data is always "string" (serialization is done by the
     * core not by the backend)
     *
     * @param  string $data            Datas to cache
     * @param  string $id              Cache id
     * @param  array $tags             Array of strings, the cache record will be tagged by each string entry
     * @param  int   $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @return boolean true if no problem
     */
    public function save($data, $id, $tags = array(), $specificLifetime = false)
    {
        if ($this->_options['disable_caching']) {
            return true;
        }
        $extension = null;
        if ($this->_isSerialized($data)) {
            $data = unserialize($data);
            $extension = '.' . ltrim($data[1], '.');
            $data = $data[0];
        }

        clearstatcache();
        if (($id = (string)$id) === '') {
            $id = $this->_detectId();
        } else {
            $id = $this->_decodeId($id);
        }

        $fileName = basename($id);
        if ($fileName === '') {
            $fileName = $this->_options['index_filename'];
        }

        $pathName = realpath($this->_options['public_dir']) . dirname($id);
        $this->_createDirectoriesFor($pathName);

        if ($id === null || strlen($id) == 0) {
            $dataUnserialized = unserialize($data);
            $data = $dataUnserialized['data'];
        }
        $ext = $this->_options['file_extension'];
        if ($extension) $ext = $extension;
        $file = rtrim($pathName, '/') . '/' . $fileName . $ext;
        if ($this->_options['file_locking']) {
            $result = file_put_contents($file, $data, LOCK_EX);
        } else {
            $result = file_put_contents($file, $data);
        }
        @chmod($file, $this->_octdec($this->_options['cache_file_umask']));

        if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
            $this->_tagged = $tagged;
        } elseif ($this->_tagged === null) {
            $this->_tagged = array();
        }
        if (!isset($this->_tagged[$id])) {
            $this->_tagged[$id] = array();
        }
        if (!isset($this->_tagged[$id]['tags'])) {
            $this->_tagged[$id]['tags'] = array();
        }
        $this->_tagged[$id]['tags'] = array_unique(array_merge($this->_tagged[$id]['tags'], $tags));
        $this->_tagged[$id]['extension'] = $ext;
        $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
        return (bool) $result;
    }

    /**
     * Recursively create the directories needed to write the static file
     */
    protected function _createDirectoriesFor($path)
    {
        if (!is_dir($path)) {
            $oldUmask = umask(0);
            if ( !@mkdir($path, $this->_octdec($this->_options['cache_directory_umask']), true)) {
                $lastErr = error_get_last();
                umask($oldUmask);
                Zend_Cache::throwException("Can't create directory: {$lastErr['message']}");
            }
            umask($oldUmask);
        }
    }

    /**
     * Detect serialization of data (cannot predict since this is the only way
     * to obey the interface yet pass in another parameter).
     *
     * In future, ZF 2.0, check if we can just avoid the interface restraints.
     *
     * This format is the only valid one possible for the class, so it's simple
     * to just run a regular expression for the starting serialized format.
     */
    protected function _isSerialized($data)
    {
        return preg_match("/a:2:\{i:0;s:\d+:\"/", $data);
    }

    /**
     * Remove a cache record
     *
     * @param  string $id Cache id
     * @return boolean True if no problem
     */
    public function remove($id)
    {
        if (!$this->_verifyPath($id)) {
            Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
        }
        $fileName = basename($id);
        if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
            $this->_tagged = $tagged;
        } elseif (!$this->_tagged) {
            return false;
        }
        if (isset($this->_tagged[$id])) {
            $extension = $this->_tagged[$id]['extension'];
        } else {
            $extension = $this->_options['file_extension'];
        }
        if ($fileName === '') {
            $fileName = $this->_options['index_filename'];
        }
        $pathName = $this->_options['public_dir'] . dirname($id);
        $file     = realpath($pathName) . '/' . $fileName . $extension;
        if (!file_exists($file)) {
            return false;
        }
        return unlink($file);
    }

    /**
     * Remove a cache record recursively for the given directory matching a
     * REQUEST_URI based relative path (deletes the actual file matching this
     * in addition to the matching directory)
     *
     * @param  string $id Cache id
     * @return boolean True if no problem
     */
    public function removeRecursively($id)
    {
        if (!$this->_verifyPath($id)) {
            Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
        }
        $fileName = basename($id);
        if ($fileName === '') {
            $fileName = $this->_options['index_filename'];
        }
        $pathName  = $this->_options['public_dir'] . dirname($id);
        $file      = $pathName . '/' . $fileName . $this->_options['file_extension'];
        $directory = $pathName . '/' . $fileName;
        if (file_exists($directory)) {
            if (!is_writable($directory)) {
                return false;
            }
            if (is_dir($directory)) {
                foreach (new DirectoryIterator($directory) as $file) {
                    if (true === $file->isFile()) {
                        if (false === unlink($file->getPathName())) {
                            return false;
                        }
                    }
                }
            }
            rmdir($directory);
        }
        if (file_exists($file)) {
            if (!is_writable($file)) {
                return false;
            }
            return unlink($file);
        }
        return true;
    }

    /**
     * Clean some cache records
     *
     * Available modes are :
     * Zend_Cache::CLEANING_MODE_ALL (default)    => remove all cache entries ($tags is not used)
     * Zend_Cache::CLEANING_MODE_OLD              => remove too old cache entries ($tags is not used)
     * Zend_Cache::CLEANING_MODE_MATCHING_TAG     => remove cache entries matching all given tags
     *                                               ($tags can be an array of strings or a single string)
     * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
     *                                               ($tags can be an array of strings or a single string)
     * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
     *                                               ($tags can be an array of strings or a single string)
     *
     * @param  string $mode Clean mode
     * @param  array  $tags Array of tags
     * @return boolean true if no problem
     */
    public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
    {
        $result = false;
        switch ($mode) {
            case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
            case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
                if (empty($tags)) {
                    throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
                }
                if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
                    $this->_tagged = $tagged;
                } elseif (!$this->_tagged) {
                    return true;
                }
                foreach ($tags as $tag) {
                    $urls = array_keys($this->_tagged);
                    foreach ($urls as $url) {
                        if (isset($this->_tagged[$url]['tags']) && in_array($tag, $this->_tagged[$url]['tags'])) {
                            $this->remove($url);
                            unset($this->_tagged[$url]);
                        }
                    }
                }
                $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
                $result = true;
                break;
            case Zend_Cache::CLEANING_MODE_ALL:
                if ($this->_tagged === null) {
                    $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
                    $this->_tagged = $tagged;
                }
                if ($this->_tagged === null || empty($this->_tagged)) {
                    return true;
                }
                $urls = array_keys($this->_tagged);
                foreach ($urls as $url) {
                    $this->remove($url);
                    unset($this->_tagged[$url]);
                }
                $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
                $result = true;
                break;
            case Zend_Cache::CLEANING_MODE_OLD:
                $this->_log("Zend_Cache_Backend_Static : Selected Cleaning Mode Currently Unsupported By This Backend");
                break;
            case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
                if (empty($tags)) {
                    throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
                }
                if ($this->_tagged === null) {
                    $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
                    $this->_tagged = $tagged;
                }
                if ($this->_tagged === null || empty($this->_tagged)) {
                    return true;
                }
                $urls = array_keys($this->_tagged);
                foreach ($urls as $url) {
                    $difference = array_diff($tags, $this->_tagged[$url]['tags']);
                    if (count($tags) == count($difference)) {
                        $this->remove($url);
                        unset($this->_tagged[$url]);
                    }
                }
                $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
                $result = true;
                break;
            default:
                Zend_Cache::throwException('Invalid mode for clean() method');
                break;
        }
        return $result;
    }

    /**
     * Set an Inner Cache, used here primarily to store Tags associated
     * with caches created by this backend. Note: If Tags are lost, the cache
     * should be completely cleaned as the mapping of tags to caches will
     * have been irrevocably lost.
     *
     * @param  Zend_Cache_Core
     * @return void
     */
    public function setInnerCache(Zend_Cache_Core $cache)
    {
        $this->_tagCache = $cache;
        $this->_options['tag_cache'] = $cache;
    }

    /**
     * Get the Inner Cache if set
     *
     * @return Zend_Cache_Core
     */
    public function getInnerCache()
    {
        if ($this->_tagCache === null) {
            Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()');
        }
        return $this->_tagCache;
    }

    /**
     * Verify path exists and is non-empty
     *
     * @param  string $path
     * @return bool
     */
    protected function _verifyPath($path)
    {
        $path = realpath($path);
        $base = realpath($this->_options['public_dir']);
        return strncmp($path, $base, strlen($base)) !== 0;
    }

    /**
     * Determine the page to save from the request
     *
     * @return string
     */
    protected function _detectId()
    {
        return $_SERVER['REQUEST_URI'];
    }

    /**
     * Validate a cache id or a tag (security, reliable filenames, reserved prefixes...)
     *
     * Throw an exception if a problem is found
     *
     * @param  string $string Cache id or tag
     * @throws Zend_Cache_Exception
     * @return void
     * @deprecated Not usable until perhaps ZF 2.0
     */
    protected static function _validateIdOrTag($string)
    {
        if (!is_string($string)) {
            Zend_Cache::throwException('Invalid id or tag : must be a string');
        }

        // Internal only checked in Frontend - not here!
        if (substr($string, 0, 9) == 'internal-') {
            return;
        }

        // Validation assumes no query string, fragments or scheme included - only the path
        if (!preg_match(
                '/^(?:\/(?:(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*\'()\[\]:@&=+$,;])*)?)+$/',
                $string
            )
        ) {
            Zend_Cache::throwException("Invalid id or tag '$string' : must be a valid URL path");
        }
    }

    /**
     * Detect an octal string and return its octal value for file permission ops
     * otherwise return the non-string (assumed octal or decimal int already)
     *
     * @param string $val The potential octal in need of conversion
     * @return int
     */
    protected function _octdec($val)
    {
        if (is_string($val) && decoct(octdec($val)) == $val) {
            return octdec($val);
        }
        return $val;
    }

    /**
     * Decode a request URI from the provided ID
     *
     * @param string $id
     * @return string
     */
    protected function _decodeId($id)
    {
        return pack('H*', $id);
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ZendPlatform.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Cache_Backend_Interface
 */
require_once 'Zend/Cache/Backend.php';

/**
 * @see Zend_Cache_Backend_Interface
 */
require_once 'Zend/Cache/Backend/Interface.php';

/**
 * Impementation of Zend Cache Backend using the Zend Platform (Output Content Caching)
 *
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Backend_ZendPlatform extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
    /**
     * internal ZP prefix
     */
    const TAGS_PREFIX = "internal_ZPtag:";

    /**
     * Constructor
     * Validate that the Zend Platform is loaded and licensed
     *
     * @param  array $options Associative array of options
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct(array $options = array())
    {
        if (!function_exists('accelerator_license_info')) {
            Zend_Cache::throwException('The Zend Platform extension must be loaded for using this backend !');
        }
        if (!function_exists('accelerator_get_configuration')) {
            $licenseInfo = accelerator_license_info();
            Zend_Cache::throwException('The Zend Platform extension is not loaded correctly: '.$licenseInfo['failure_reason']);
        }
        $accConf = accelerator_get_configuration();
        if (@!$accConf['output_cache_licensed']) {
            Zend_Cache::throwException('The Zend Platform extension does not have the proper license to use content caching features');
        }
        if (@!$accConf['output_cache_enabled']) {
            Zend_Cache::throwException('The Zend Platform content caching feature must be enabled for using this backend, set the \'zend_accelerator.output_cache_enabled\' directive to On !');
        }
        if (!is_writable($accConf['output_cache_dir'])) {
            Zend_Cache::throwException('The cache copies directory \''. ini_get('zend_accelerator.output_cache_dir') .'\' must be writable !');
        }
        parent:: __construct($options);
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * @param  string  $id                     Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @return string Cached data (or false)
     */
    public function load($id, $doNotTestCacheValidity = false)
    {
        // doNotTestCacheValidity implemented by giving zero lifetime to the cache
        if ($doNotTestCacheValidity) {
            $lifetime = 0;
        } else {
            $lifetime = $this->_directives['lifetime'];
        }
        $res = output_cache_get($id, $lifetime);
        if($res) {
            return $res[0];
        } else {
            return false;
        }
    }

    /**
     * Test if a cache is available or not (for the given id)
     *
     * @param  string $id Cache id
     * @return mixed|false false (a cache is not available) or "last modified" timestamp (int) of the available cache record
     */
    public function test($id)
    {
        $result = output_cache_get($id, $this->_directives['lifetime']);
        if ($result) {
            return $result[1];
        }
        return false;
    }

    /**
     * Save some string datas into a cache record
     *
     * Note : $data is always "string" (serialization is done by the
     * core not by the backend)
     *
     * @param  string $data             Data to cache
     * @param  string $id               Cache id
     * @param  array  $tags             Array of strings, the cache record will be tagged by each string entry
     * @param  int    $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @return boolean true if no problem
     */
    public function save($data, $id, $tags = array(), $specificLifetime = false)
    {
        if (!($specificLifetime === false)) {
            $this->_log("Zend_Cache_Backend_ZendPlatform::save() : non false specifc lifetime is unsuported for this backend");
        }

        $lifetime = $this->_directives['lifetime'];
        $result1  = output_cache_put($id, array($data, time()));
        $result2  = (count($tags) == 0);

        foreach ($tags as $tag) {
            $tagid = self::TAGS_PREFIX.$tag;
            $old_tags = output_cache_get($tagid, $lifetime);
            if ($old_tags === false) {
                $old_tags = array();
            }
            $old_tags[$id] = $id;
            output_cache_remove_key($tagid);
            $result2 = output_cache_put($tagid, $old_tags);
        }

        return $result1 && $result2;
    }

    /**
     * Remove a cache record
     *
     * @param  string $id Cache id
     * @return boolean True if no problem
     */
    public function remove($id)
    {
        return output_cache_remove_key($id);
    }

    /**
     * Clean some cache records
     *
     * Available modes are :
     * Zend_Cache::CLEANING_MODE_ALL (default)    => remove all cache entries ($tags is not used)
     * Zend_Cache::CLEANING_MODE_OLD              => remove too old cache entries ($tags is not used)
     *                                               This mode is not supported in this backend
     * Zend_Cache::CLEANING_MODE_MATCHING_TAG     => remove cache entries matching all given tags
     *                                               ($tags can be an array of strings or a single string)
     * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => unsupported
     * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
     *                                               ($tags can be an array of strings or a single string)
     *
     * @param  string $mode Clean mode
     * @param  array  $tags Array of tags
     * @throws Zend_Cache_Exception
     * @return boolean True if no problem
     */
    public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
    {
        switch ($mode) {
            case Zend_Cache::CLEANING_MODE_ALL:
            case Zend_Cache::CLEANING_MODE_OLD:
                $cache_dir = ini_get('zend_accelerator.output_cache_dir');
                if (!$cache_dir) {
                    return false;
                }
                $cache_dir .= '/.php_cache_api/';
                return $this->_clean($cache_dir, $mode);
                break;
            case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
                $idlist = null;
                foreach ($tags as $tag) {
                    $next_idlist = output_cache_get(self::TAGS_PREFIX.$tag, $this->_directives['lifetime']);
                    if ($idlist) {
                        $idlist = array_intersect_assoc($idlist, $next_idlist);
                    } else {
                        $idlist = $next_idlist;
                    }
                    if (count($idlist) == 0) {
                        // if ID list is already empty - we may skip checking other IDs
                        $idlist = null;
                        break;
                    }
                }
                if ($idlist) {
                    foreach ($idlist as $id) {
                        output_cache_remove_key($id);
                    }
                }
                return true;
                break;
            case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
                $this->_log("Zend_Cache_Backend_ZendPlatform::clean() : CLEANING_MODE_NOT_MATCHING_TAG is not supported by the Zend Platform backend");
                return false;
                break;
            case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
                $idlist = null;
                foreach ($tags as $tag) {
                    $next_idlist = output_cache_get(self::TAGS_PREFIX.$tag, $this->_directives['lifetime']);
                    if ($idlist) {
                        $idlist = array_merge_recursive($idlist, $next_idlist);
                    } else {
                        $idlist = $next_idlist;
                    }
                    if (count($idlist) == 0) {
                        // if ID list is already empty - we may skip checking other IDs
                        $idlist = null;
                        break;
                    }
                }
                if ($idlist) {
                    foreach ($idlist as $id) {
                        output_cache_remove_key($id);
                    }
                }
                return true;
                break;
            default:
                Zend_Cache::throwException('Invalid mode for clean() method');
                break;
        }
    }

    /**
     * Clean a directory and recursivly go over it's subdirectories
     *
     * Remove all the cached files that need to be cleaned (according to mode and files mtime)
     *
     * @param  string $dir  Path of directory ot clean
     * @param  string $mode The same parameter as in Zend_Cache_Backend_ZendPlatform::clean()
     * @return boolean True if ok
     */
    private function _clean($dir, $mode)
    {
        $d = @dir($dir);
        if (!$d) {
            return false;
        }
        $result = true;
        while (false !== ($file = $d->read())) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            $file = $d->path . $file;
            if (is_dir($file)) {
                $result = ($this->_clean($file .'/', $mode)) && ($result);
            } else {
                if ($mode == Zend_Cache::CLEANING_MODE_ALL) {
                    $result = ($this->_remove($file)) && ($result);
                } else if ($mode == Zend_Cache::CLEANING_MODE_OLD) {
                    // Files older than lifetime get deleted from cache
                    if ($this->_directives['lifetime'] !== null) {
                        if ((time() - @filemtime($file)) > $this->_directives['lifetime']) {
                            $result = ($this->_remove($file)) && ($result);
                        }
                    }
                }
            }
        }
        $d->close();
        return $result;
    }

    /**
     * Remove a file
     *
     * If we can't remove the file (because of locks or any problem), we will touch
     * the file to invalidate it
     *
     * @param  string $file Complete file path
     * @return boolean True if ok
     */
    private function _remove($file)
    {
        if (!@unlink($file)) {
            # If we can't remove the file (because of locks or any problem), we will touch
            # the file to invalidate it
            $this->_log("Zend_Cache_Backend_ZendPlatform::_remove() : we can't remove $file => we are going to try to invalidate it");
            if ($this->_directives['lifetime'] === null) {
                return false;
            }
            if (!file_exists($file)) {
                return false;
            }
            return @touch($file, time() - 2*abs($this->_directives['lifetime']));
        }
        return true;
    }

}