CC-2166: Packaging Improvements. Moved the Zend app into airtime_mvc. It is now installed to /var/www/airtime. Storage is now set to /srv/airtime/stor. Utils are now installed to /usr/lib/airtime/utils/. Added install/airtime-dircheck.php as a simple test to see if everything is install/uninstalled correctly.

This commit is contained in:
Paul Baranowski 2011-04-14 18:55:04 -04:00
parent 514777e8d2
commit b11cbd8159
4546 changed files with 138 additions and 51 deletions

View file

@ -0,0 +1,355 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Apc.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @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-2010 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
);
}
}

View file

@ -0,0 +1,250 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: BlackHole.php 17867 2009-08-28 09:42:11Z yoshida@zend.co.jp $
*/
/**
* @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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_BlackHole
extends Zend_Cache_Backend
implements Zend_Cache_Backend_ExtendedInterface
{
/**
* 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|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
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)
{
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)
{
return true;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return true;
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => remove too old cache entries ($tags is not used)
* 'matchingTag' => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* 'notMatchingTag' => remove cache entries not matching one of the given tags
* ($tags can be an array of strings or a single string)
* 'matchingAnyTag' => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode clean mode
* @param tags array $tags array of tags
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
return true;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return array();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
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())
{
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())
{
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())
{
return array();
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
* @throws Zend_Cache_Exception
*/
public function getFillingPercentage()
{
return 0;
}
/**
* 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 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' => true,
'tags' => true,
'expired_read' => true,
'priority' => true,
'infinite_lifetime' => true,
'get_list' => true,
);
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id cache id
*/
public function ___expire($id)
{
}
}

View file

@ -0,0 +1,126 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ExtendedInterface.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
require_once 'Zend/Cache/Backend/Interface.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Cache_Backend_ExtendedInterface extends Zend_Cache_Backend_Interface
{
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds();
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags();
/**
* 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());
/**
* 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());
/**
* 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());
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage();
/**
* 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);
/**
* 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 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();
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,99 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Interface.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Cache_Backend_Interface
{
/**
* Set the frontend directives
*
* @param array $directives assoc of directives
*/
public function setDirectives($directives);
/**
* 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);
/**
* 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);
/**
* 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);
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($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)
* 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());
}

View file

@ -0,0 +1,504 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Memcached.php 21535 2010-03-17 18:20:53Z mabe $
*/
/**
* @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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Memcached extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Default Values
*/
const DEFAULT_HOST = '127.0.0.1';
const DEFAULT_PORT = 11211;
const DEFAULT_PERSISTENT = true;
const DEFAULT_WEIGHT = 1;
const DEFAULT_TIMEOUT = 1;
const DEFAULT_RETRY_INTERVAL = 15;
const DEFAULT_STATUS = true;
const DEFAULT_FAILURE_CALLBACK = null;
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_MEMCACHED_BACKEND = 'Zend_Cache_Backend_Memcached::clean() : tags are unsupported by the Memcached backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND = 'Zend_Cache_Backend_Memcached::save() : tags are unsupported by the Memcached backend';
/**
* Available options
*
* =====> (array) servers :
* an array of memcached server ; each memcached server is described by an associative array :
* 'host' => (string) : the name of the memcached server
* 'port' => (int) : the port of the memcached server
* 'persistent' => (bool) : use or not persistent connections to this memcached server
* 'weight' => (int) : number of buckets to create for this server which in turn control its
* probability of it being selected. The probability is relative to the total
* weight of all servers.
* 'timeout' => (int) : value in seconds which will be used for connecting to the daemon. Think twice
* before changing the default value of 1 second - you can lose all the
* advantages of caching if your connection is too slow.
* 'retry_interval' => (int) : controls how often a failed server will be retried, the default value
* is 15 seconds. Setting this parameter to -1 disables automatic retry.
* 'status' => (bool) : controls if the server should be flagged as online.
* 'failure_callback' => (callback) : Allows the user to specify a callback function to run upon
* encountering an error. The callback is run before failover
* is attempted. The function takes two parameters, the hostname
* and port of the failed server.
*
* =====> (boolean) compression :
* true if you want to use on-the-fly compression
*
* =====> (boolean) compatibility :
* true if you use old memcache server or extension
*
* @var array available options
*/
protected $_options = array(
'servers' => array(array(
'host' => self::DEFAULT_HOST,
'port' => self::DEFAULT_PORT,
'persistent' => self::DEFAULT_PERSISTENT,
'weight' => self::DEFAULT_WEIGHT,
'timeout' => self::DEFAULT_TIMEOUT,
'retry_interval' => self::DEFAULT_RETRY_INTERVAL,
'status' => self::DEFAULT_STATUS,
'failure_callback' => self::DEFAULT_FAILURE_CALLBACK
)),
'compression' => false,
'compatibility' => false,
);
/**
* Memcache object
*
* @var mixed memcache object
*/
protected $_memcache = null;
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('memcache')) {
Zend_Cache::throwException('The memcache extension must be loaded for using this backend !');
}
parent::__construct($options);
if (isset($this->_options['servers'])) {
$value= $this->_options['servers'];
if (isset($value['host'])) {
// in this case, $value seems to be a simple associative array (one server only)
$value = array(0 => $value); // let's transform it into a classical array of associative arrays
}
$this->setOption('servers', $value);
}
$this->_memcache = new Memcache;
foreach ($this->_options['servers'] as $server) {
if (!array_key_exists('port', $server)) {
$server['port'] = self::DEFAULT_PORT;
}
if (!array_key_exists('persistent', $server)) {
$server['persistent'] = self::DEFAULT_PERSISTENT;
}
if (!array_key_exists('weight', $server)) {
$server['weight'] = self::DEFAULT_WEIGHT;
}
if (!array_key_exists('timeout', $server)) {
$server['timeout'] = self::DEFAULT_TIMEOUT;
}
if (!array_key_exists('retry_interval', $server)) {
$server['retry_interval'] = self::DEFAULT_RETRY_INTERVAL;
}
if (!array_key_exists('status', $server)) {
$server['status'] = self::DEFAULT_STATUS;
}
if (!array_key_exists('failure_callback', $server)) {
$server['failure_callback'] = self::DEFAULT_FAILURE_CALLBACK;
}
if ($this->_options['compatibility']) {
// No status for compatibility mode (#ZF-5887)
$this->_memcache->addServer($server['host'], $server['port'], $server['persistent'],
$server['weight'], $server['timeout'],
$server['retry_interval']);
} else {
$this->_memcache->addServer($server['host'], $server['port'], $server['persistent'],
$server['weight'], $server['timeout'],
$server['retry_interval'],
$server['status'], $server['failure_callback']);
}
}
}
/**
* 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|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = $this->_memcache->get($id);
if (is_array($tmp) && isset($tmp[0])) {
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 = $this->_memcache->get($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);
if ($this->_options['compression']) {
$flag = MEMCACHE_COMPRESSED;
} else {
$flag = 0;
}
// ZF-8856: using set because add needs a second request if item already exists
$result = @$this->_memcache->set($id, array($data, time(), $lifetime), $flag, $lifetime);
if (count($tags) > 0) {
$this->_log("Zend_Cache_Backend_Memcached::save() : tags are unsupported by the Memcached backend");
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
return $this->_memcache->delete($id, 0);
}
/**
* 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 $this->_memcache->flush();
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Memcached::clean() : CLEANING_MODE_OLD is unsupported by the Memcached 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_MEMCACHED_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
parent::setDirectives($directives);
$lifetime = $this->getLifetime(false);
if ($lifetime > 2592000) {
// #ZF-3490 : For the memcached backend, there is a lifetime limit of 30 days (2592000 seconds)
$this->_log('memcached backend has a limit of 30 days (2592000 seconds) for the lifetime');
}
if ($lifetime === null) {
// #ZF-4614 : we tranform null to zero to get the maximal lifetime
parent::setDirectives(array('lifetime' => 0));
}
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$this->_log("Zend_Cache_Backend_Memcached::save() : getting the list of cache ids is unsupported by the Memcache backend");
return array();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_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_MEMCACHED_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_MEMCACHED_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_MEMCACHED_BACKEND);
return array();
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$mems = $this->_memcache->getExtendedStats();
$memSize = null;
$memUsed = null;
foreach ($mems as $key => $mem) {
if ($mem === false) {
$this->_log('can\'t get stat from ' . $key);
continue;
}
$eachSize = $mem['limit_maxbytes'];
$eachUsed = $mem['bytes'];
if ($eachUsed > $eachSize) {
$eachUsed = $eachSize;
}
$memSize += $eachSize;
$memUsed += $eachUsed;
}
if ($memSize === null || $memUsed === null) {
Zend_Cache::throwException('Can\'t get filling percentage');
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* 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 = $this->_memcache->get($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)
{
if ($this->_options['compression']) {
$flag = MEMCACHE_COMPRESSED;
} else {
$flag = 0;
}
$tmp = $this->_memcache->get($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;
}
// #ZF-5702 : we try replace() first becase set() seems to be slower
if (!($result = $this->_memcache->replace($id, array($data, time(), $newLifetime), $flag, $newLifetime))) {
$result = $this->_memcache->set($id, array($data, time(), $newLifetime), $flag, $newLifetime);
}
return $result;
}
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' => false
);
}
}

View file

@ -0,0 +1,679 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Sqlite.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Sqlite extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Available options
*
* =====> (string) cache_db_complete_path :
* - the complete path (filename included) of the SQLITE database
*
* ====> (int) automatic_vacuum_factor :
* - Disable / Tune the automatic vacuum process
* - The automatic vacuum process defragment the database file (and make it smaller)
* when a clean() or delete() is called
* 0 => no automatic vacuum
* 1 => systematic vacuum (when delete() or clean() methods are called)
* x (integer) > 1 => automatic vacuum randomly 1 times on x clean() or delete()
*
* @var array Available options
*/
protected $_options = array(
'cache_db_complete_path' => null,
'automatic_vacuum_factor' => 10
);
/**
* DB ressource
*
* @var mixed $_db
*/
private $_db = null;
/**
* Boolean to store if the structure has benn checked or not
*
* @var boolean $_structureChecked
*/
private $_structureChecked = false;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
parent::__construct($options);
if ($this->_options['cache_db_complete_path'] === null) {
Zend_Cache::throwException('cache_db_complete_path option has to set');
}
if (!extension_loaded('sqlite')) {
Zend_Cache::throwException("Cannot use SQLite storage because the 'sqlite' extension is not loaded in the current PHP environment");
}
$this->_getConnection();
}
/**
* Destructor
*
* @return void
*/
public function __destruct()
{
@sqlite_close($this->_getConnection());
}
/**
* 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|false Cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$this->_checkAndBuildStructure();
$sql = "SELECT content FROM cache WHERE id='$id'";
if (!$doNotTestCacheValidity) {
$sql = $sql . " AND (expire=0 OR expire>" . time() . ')';
}
$result = $this->_query($sql);
$row = @sqlite_fetch_array($result);
if ($row) {
return $row['content'];
}
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)
{
$this->_checkAndBuildStructure();
$sql = "SELECT lastModified FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')';
$result = $this->_query($sql);
$row = @sqlite_fetch_array($result);
if ($row) {
return ((int) $row['lastModified']);
}
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)
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$this->_checkAndBuildStructure();
$lifetime = $this->getLifetime($specificLifetime);
$data = @sqlite_escape_string($data);
$mktime = time();
if ($lifetime === null) {
$expire = 0;
} else {
$expire = $mktime + $lifetime;
}
$this->_query("DELETE FROM cache WHERE id='$id'");
$sql = "INSERT INTO cache (id, content, lastModified, expire) VALUES ('$id', '$data', $mktime, $expire)";
$res = $this->_query($sql);
if (!$res) {
$this->_log("Zend_Cache_Backend_Sqlite::save() : impossible to store the cache id=$id");
return false;
}
$res = true;
foreach ($tags as $tag) {
$res = $this->_registerTag($id, $tag) && $res;
}
return $res;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
$this->_checkAndBuildStructure();
$res = $this->_query("SELECT COUNT(*) AS nbr FROM cache WHERE id='$id'");
$result1 = @sqlite_fetch_single($res);
$result2 = $this->_query("DELETE FROM cache WHERE id='$id'");
$result3 = $this->_query("DELETE FROM tag WHERE id='$id'");
$this->_automaticVacuum();
return ($result1 && $result2 && $result3);
}
/**
* 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())
{
$this->_checkAndBuildStructure();
$return = $this->_clean($mode, $tags);
$this->_automaticVacuum();
return $return;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$this->_checkAndBuildStructure();
$res = $this->_query("SELECT id FROM cache WHERE (expire=0 OR expire>" . time() . ")");
$result = array();
while ($id = @sqlite_fetch_single($res)) {
$result[] = $id;
}
return $result;
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_checkAndBuildStructure();
$res = $this->_query("SELECT DISTINCT(name) AS name FROM tag");
$result = array();
while ($id = @sqlite_fetch_single($res)) {
$result[] = $id;
}
return $result;
}
/**
* 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())
{
$first = true;
$ids = array();
foreach ($tags as $tag) {
$res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'");
if (!$res) {
return array();
}
$rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
$ids2 = array();
foreach ($rows as $row) {
$ids2[] = $row['id'];
}
if ($first) {
$ids = $ids2;
$first = false;
} else {
$ids = array_intersect($ids, $ids2);
}
}
$result = array();
foreach ($ids as $id) {
$result[] = $id;
}
return $result;
}
/**
* 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())
{
$res = $this->_query("SELECT id FROM cache");
$rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
$result = array();
foreach ($rows as $row) {
$id = $row['id'];
$matching = false;
foreach ($tags as $tag) {
$res = $this->_query("SELECT COUNT(*) AS nbr FROM tag WHERE name='$tag' AND id='$id'");
if (!$res) {
return array();
}
$nbr = (int) @sqlite_fetch_single($res);
if ($nbr > 0) {
$matching = true;
}
}
if (!$matching) {
$result[] = $id;
}
}
return $result;
}
/**
* 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())
{
$first = true;
$ids = array();
foreach ($tags as $tag) {
$res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'");
if (!$res) {
return array();
}
$rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
$ids2 = array();
foreach ($rows as $row) {
$ids2[] = $row['id'];
}
if ($first) {
$ids = $ids2;
$first = false;
} else {
$ids = array_merge($ids, $ids2);
}
}
$result = array();
foreach ($ids as $id) {
$result[] = $id;
}
return $result;
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$dir = dirname($this->_options['cache_db_complete_path']);
$free = disk_free_space($dir);
$total = disk_total_space($dir);
if ($total == 0) {
Zend_Cache::throwException('can\'t get disk_total_space');
} else {
if ($free >= $total) {
return 100;
}
return ((int) (100. * ($total - $free) / $total));
}
}
/**
* 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)
{
$tags = array();
$res = $this->_query("SELECT name FROM tag WHERE id='$id'");
if ($res) {
$rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
foreach ($rows as $row) {
$tags[] = $row['name'];
}
}
$this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)');
$res = $this->_query("SELECT lastModified,expire FROM cache WHERE id='$id'");
if (!$res) {
return false;
}
$row = @sqlite_fetch_array($res, SQLITE_ASSOC);
return array(
'tags' => $tags,
'mtime' => $row['lastModified'],
'expire' => $row['expire']
);
}
/**
* 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)
{
$sql = "SELECT expire FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')';
$res = $this->_query($sql);
if (!$res) {
return false;
}
$expire = @sqlite_fetch_single($res);
$newExpire = $expire + $extraLifetime;
$res = $this->_query("UPDATE cache SET lastModified=" . time() . ", expire=$newExpire WHERE id='$id'");
if ($res) {
return true;
} else {
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' => true,
'tags' => true,
'expired_read' => true,
'priority' => false,
'infinite_lifetime' => true,
'get_list' => true
);
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id Cache id
*/
public function ___expire($id)
{
$time = time() - 1;
$this->_query("UPDATE cache SET lastModified=$time, expire=$time WHERE id='$id'");
}
/**
* Return the connection resource
*
* If we are not connected, the connection is made
*
* @throws Zend_Cache_Exception
* @return resource Connection resource
*/
private function _getConnection()
{
if (is_resource($this->_db)) {
return $this->_db;
} else {
$this->_db = @sqlite_open($this->_options['cache_db_complete_path']);
if (!(is_resource($this->_db))) {
Zend_Cache::throwException("Impossible to open " . $this->_options['cache_db_complete_path'] . " cache DB file");
}
return $this->_db;
}
}
/**
* Execute an SQL query silently
*
* @param string $query SQL query
* @return mixed|false query results
*/
private function _query($query)
{
$db = $this->_getConnection();
if (is_resource($db)) {
$res = @sqlite_query($db, $query);
if ($res === false) {
return false;
} else {
return $res;
}
}
return false;
}
/**
* Deal with the automatic vacuum process
*
* @return void
*/
private function _automaticVacuum()
{
if ($this->_options['automatic_vacuum_factor'] > 0) {
$rand = rand(1, $this->_options['automatic_vacuum_factor']);
if ($rand == 1) {
$this->_query('VACUUM');
@sqlite_close($this->_getConnection());
}
}
}
/**
* Register a cache id with the given tag
*
* @param string $id Cache id
* @param string $tag Tag
* @return boolean True if no problem
*/
private function _registerTag($id, $tag) {
$res = $this->_query("DELETE FROM TAG WHERE name='$tag' AND id='$id'");
$res = $this->_query("INSERT INTO tag (name, id) VALUES ('$tag', '$id')");
if (!$res) {
$this->_log("Zend_Cache_Backend_Sqlite::_registerTag() : impossible to register tag=$tag on id=$id");
return false;
}
return true;
}
/**
* Build the database structure
*
* @return false
*/
private function _buildStructure()
{
$this->_query('DROP INDEX tag_id_index');
$this->_query('DROP INDEX tag_name_index');
$this->_query('DROP INDEX cache_id_expire_index');
$this->_query('DROP TABLE version');
$this->_query('DROP TABLE cache');
$this->_query('DROP TABLE tag');
$this->_query('CREATE TABLE version (num INTEGER PRIMARY KEY)');
$this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)');
$this->_query('CREATE TABLE tag (name TEXT, id TEXT)');
$this->_query('CREATE INDEX tag_id_index ON tag(id)');
$this->_query('CREATE INDEX tag_name_index ON tag(name)');
$this->_query('CREATE INDEX cache_id_expire_index ON cache(id, expire)');
$this->_query('INSERT INTO version (num) VALUES (1)');
}
/**
* Check if the database structure is ok (with the good version)
*
* @return boolean True if ok
*/
private function _checkStructureVersion()
{
$result = $this->_query("SELECT num FROM version");
if (!$result) return false;
$row = @sqlite_fetch_array($result);
if (!$row) {
return false;
}
if (((int) $row['num']) != 1) {
// old cache structure
$this->_log('Zend_Cache_Backend_Sqlite::_checkStructureVersion() : old cache structure version detected => the cache is going to be dropped');
return false;
}
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
*/
private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
$res1 = $this->_query('DELETE FROM cache');
$res2 = $this->_query('DELETE FROM tag');
return $res1 && $res2;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$mktime = time();
$res1 = $this->_query("DELETE FROM tag WHERE id IN (SELECT id FROM cache WHERE expire>0 AND expire<=$mktime)");
$res2 = $this->_query("DELETE FROM cache WHERE expire>0 AND expire<=$mktime");
return $res1 && $res2;
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$ids = $this->getIdsMatchingTags($tags);
$result = true;
foreach ($ids as $id) {
$result = $this->remove($id) && $result;
}
return $result;
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$ids = $this->getIdsNotMatchingTags($tags);
$result = true;
foreach ($ids as $id) {
$result = $this->remove($id) && $result;
}
return $result;
break;
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$ids = $this->getIdsMatchingAnyTags($tags);
$result = true;
foreach ($ids as $id) {
$result = $this->remove($id) && $result;
}
return $result;
break;
default:
break;
}
return false;
}
/**
* Check if the database structure is ok (with the good version), if no : build it
*
* @throws Zend_Cache_Exception
* @return boolean True if ok
*/
private function _checkAndBuildStructure()
{
if (!($this->_structureChecked)) {
if (!$this->_checkStructureVersion()) {
$this->_buildStructure();
if (!$this->_checkStructureVersion()) {
Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']);
}
}
$this->_structureChecked = true;
}
return true;
}
}

View file

@ -0,0 +1,558 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: BlackHole.php 17867 2009-08-28 09:42:11Z yoshida@zend.co.jp $
*/
/**
* @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-2010 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 (empty($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 (empty($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 (empty($fileName)) {
$fileName = $this->_options['index_filename'];
}
if (is_null($this->_tagged) && $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 (is_null($id) || strlen($id) == 0) {
$id = $this->_detectId();
} else {
$id = $this->_decodeId($id);
}
$fileName = basename($id);
if (empty($fileName)) {
$fileName = $this->_options['index_filename'];
}
$pathName = realpath($this->_options['public_dir']) . dirname($id);
$this->_createDirectoriesFor($pathName);
if (is_null($id) || 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 (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif (is_null($this->_tagged)) {
$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)
{
$parts = explode('/', $path);
$directory = '';
foreach ($parts as $part) {
$directory = rtrim($directory, '/') . '/' . $part;
if (!is_dir($directory)) {
mkdir($directory, $this->_octdec($this->_options['cache_directory_umask']));
}
}
}
/**
* 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 (is_null($this->_tagged) && $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 (empty($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 (empty($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;
}
foreach (new DirectoryIterator($directory) as $file) {
if (true === $file->isFile()) {
if (false === unlink($file->getPathName())) {
return false;
}
}
}
rmdir(dirname($path));
}
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 (is_null($this->_tagged) && $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 (is_null($this->_tagged)) {
$tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
$this->_tagged = $tagged;
}
if (is_null($this->_tagged) || 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 (is_null($this->_tagged)) {
$tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
$this->_tagged = $tagged;
}
if (is_null($this->_tagged) || 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 (is_null($this->_tagCache)) {
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 $val The potential octal in need of conversion
* @return int
*/
protected function _octdec($val)
{
if (decoct(octdec($val)) == $val && is_string($val)) {
return octdec($val);
}
return $val;
}
/**
* Decode a request URI from the provided ID
*/
protected function _decodeId($id)
{
return pack('H*', $id);;
}
}

View file

@ -0,0 +1,410 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Test.php 21292 2010-03-02 10:25:22Z mabe $
*/
/**
* @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-2010 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')
{
return false;
}
if ($id=='serialized') {
return serialize(array('foo'));
}
if ($id=='serialized2') {
return serialize(array('headers' => array(), 'data' => 'foo'));
}
if (($id=='71769f39054f75894288e397df04e445') or ($id=='615d222619fb20b527168340cebd0578')) {
return serialize(array('foo', 'bar'));
}
if (($id=='8a02d218a5165c467e7a5747cc6bd4b6') or ($id=='648aca1366211d17cbf48e65dc570bee')) {
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 ($id=='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 ($id=='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;
}
}

View file

@ -0,0 +1,506 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: TwoLevels.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @see Zend_Cache_Backend_ExtendedInterface
*/
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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Available options
*
* =====> (string) slow_backend :
* - Slow backend name
* - Must implement the Zend_Cache_Backend_ExtendedInterface
* - Should provide a big storage
*
* =====> (string) fast_backend :
* - Flow backend name
* - Must implement the Zend_Cache_Backend_ExtendedInterface
* - Must be much faster than slow_backend
*
* =====> (array) slow_backend_options :
* - Slow backend options (see corresponding backend)
*
* =====> (array) fast_backend_options :
* - Fast backend options (see corresponding backend)
*
* =====> (int) stats_update_factor :
* - Disable / Tune the computation of the fast backend filling percentage
* - When saving a record into cache :
* 1 => systematic computation of the fast backend filling percentage
* x (integer) > 1 => computation of the fast backend filling percentage randomly 1 times on x cache write
*
* =====> (boolean) slow_backend_custom_naming :
* =====> (boolean) fast_backend_custom_naming :
* =====> (boolean) slow_backend_autoload :
* =====> (boolean) fast_backend_autoload :
* - See Zend_Cache::factory() method
*
* =====> (boolean) auto_refresh_fast_cache
* - If true, auto refresh the fast cache when a cache record is hit
*
* @var array available options
*/
protected $_options = array(
'slow_backend' => 'File',
'fast_backend' => 'Apc',
'slow_backend_options' => array(),
'fast_backend_options' => array(),
'stats_update_factor' => 10,
'slow_backend_custom_naming' => false,
'fast_backend_custom_naming' => false,
'slow_backend_autoload' => false,
'fast_backend_autoload' => false,
'auto_refresh_fast_cache' => true
);
/**
* Slow Backend
*
* @var Zend_Cache_Backend
*/
protected $_slowBackend;
/**
* Fast Backend
*
* @var Zend_Cache_Backend
*/
protected $_fastBackend;
/**
* Cache for the fast backend filling percentage
*
* @var int
*/
protected $_fastBackendFillingPercentage = null;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
parent::__construct($options);
if ($this->_options['slow_backend'] === null) {
Zend_Cache::throwException('slow_backend option has to set');
}
if ($this->_options['fast_backend'] === null) {
Zend_Cache::throwException('fast_backend option has to set');
}
$this->_slowBackend = Zend_Cache::_makeBackend($this->_options['slow_backend'], $this->_options['slow_backend_options'], $this->_options['slow_backend_custom_naming'], $this->_options['slow_backend_autoload']);
$this->_fastBackend = Zend_Cache::_makeBackend($this->_options['fast_backend'], $this->_options['fast_backend_options'], $this->_options['fast_backend_custom_naming'], $this->_options['fast_backend_autoload']);
if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_slowBackend))) {
Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
}
if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) {
Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
}
$this->_slowBackend->setDirectives($this->_directives);
$this->_fastBackend->setDirectives($this->_directives);
}
/**
* 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)
{
$fastTest = $this->_fastBackend->test($id);
if ($fastTest) {
return $fastTest;
} else {
return $this->_slowBackend->test($id);
}
}
/**
* 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)
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false, $priority = 8)
{
$usage = $this->_getFastFillingPercentage('saving');
$boolFast = true;
$lifetime = $this->getLifetime($specificLifetime);
$preparedData = $this->_prepareData($data, $lifetime, $priority);
if (($priority > 0) && (10 * $priority >= $usage)) {
$fastLifetime = $this->_getFastLifetime($lifetime, $priority);
$boolFast = $this->_fastBackend->save($preparedData, $id, array(), $fastLifetime);
}
$boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
return ($boolFast && $boolSlow);
}
/**
* 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)
{
$res = $this->_fastBackend->load($id, $doNotTestCacheValidity);
if ($res === false) {
$res = $this->_slowBackend->load($id, $doNotTestCacheValidity);
if ($res === false) {
// there is no cache at all for this id
return false;
}
}
$array = unserialize($res);
// maybe, we have to refresh the fast cache ?
if ($this->_options['auto_refresh_fast_cache']) {
if ($array['priority'] == 10) {
// no need to refresh the fast cache with priority = 10
return $array['data'];
}
$newFastLifetime = $this->_getFastLifetime($array['lifetime'], $array['priority'], time() - $array['expire']);
// we have the time to refresh the fast cache
$usage = $this->_getFastFillingPercentage('loading');
if (($array['priority'] > 0) && (10 * $array['priority'] >= $usage)) {
// we can refresh the fast cache
$preparedData = $this->_prepareData($array['data'], $array['lifetime'], $array['priority']);
$this->_fastBackend->save($preparedData, $id, array(), $newFastLifetime);
}
}
return $array['data'];
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
$boolFast = $this->_fastBackend->remove($id);
$boolSlow = $this->_slowBackend->remove($id);
return $boolFast && $boolSlow;
}
/**
* 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
* @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:
$boolFast = $this->_fastBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
$boolSlow = $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
return $boolFast && $boolSlow;
break;
case Zend_Cache::CLEANING_MODE_OLD:
return $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_OLD);
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$ids = $this->_slowBackend->getIdsMatchingTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$ids = $this->_slowBackend->getIdsNotMatchingTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$ids = $this->_slowBackend->getIdsMatchingAnyTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return $this->_slowBackend->getIds();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return $this->_slowBackend->getTags();
}
/**
* 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())
{
return $this->_slowBackend->getIdsMatchingTags($tags);
}
/**
* 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())
{
return $this->_slowBackend->getIdsNotMatchingTags($tags);
}
/**
* 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())
{
return $this->_slowBackend->getIdsMatchingAnyTags($tags);
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
return $this->_slowBackend->getFillingPercentage();
}
/**
* 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 $this->_slowBackend->getMetadatas($id);
}
/**
* 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 $this->_slowBackend->touch($id, $extraLifetime);
}
/**
* 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()
{
$slowBackendCapabilities = $this->_slowBackend->getCapabilities();
return array(
'automatic_cleaning' => $slowBackendCapabilities['automatic_cleaning'],
'tags' => $slowBackendCapabilities['tags'],
'expired_read' => $slowBackendCapabilities['expired_read'],
'priority' => $slowBackendCapabilities['priority'],
'infinite_lifetime' => $slowBackendCapabilities['infinite_lifetime'],
'get_list' => $slowBackendCapabilities['get_list']
);
}
/**
* Prepare a serialized array to store datas and metadatas informations
*
* @param string $data data to store
* @param int $lifetime original lifetime
* @param int $priority priority
* @return string serialize array to store into cache
*/
private function _prepareData($data, $lifetime, $priority)
{
$lt = $lifetime;
if ($lt === null) {
$lt = 9999999999;
}
return serialize(array(
'data' => $data,
'lifetime' => $lifetime,
'expire' => time() + $lt,
'priority' => $priority
));
}
/**
* Compute and return the lifetime for the fast backend
*
* @param int $lifetime original lifetime
* @param int $priority priority
* @param int $maxLifetime maximum lifetime
* @return int lifetime for the fast backend
*/
private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
{
if ($lifetime === null) {
// if lifetime is null, we have an infinite lifetime
// we need to use arbitrary lifetimes
$fastLifetime = (int) (2592000 / (11 - $priority));
} else {
$fastLifetime = (int) ($lifetime / (11 - $priority));
}
if (($maxLifetime !== null) && ($maxLifetime >= 0)) {
if ($fastLifetime > $maxLifetime) {
return $maxLifetime;
}
}
return $fastLifetime;
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id cache id
*/
public function ___expire($id)
{
$this->_fastBackend->remove($id);
$this->_slowBackend->___expire($id);
}
private function _getFastFillingPercentage($mode)
{
if ($mode == 'saving') {
// mode saving
if ($this->_fastBackendFillingPercentage === null) {
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
} else {
$rand = rand(1, $this->_options['stats_update_factor']);
if ($rand == 1) {
// we force a refresh
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
}
}
} else {
// mode loading
// we compute the percentage only if it's not available in cache
if ($this->_fastBackendFillingPercentage === null) {
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
}
}
return $this->_fastBackendFillingPercentage;
}
}

View file

@ -0,0 +1,216 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Xcache.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Xcache extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_XCACHE_BACKEND = 'Zend_Cache_Backend_Xcache::clean() : tags are unsupported by the Xcache backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_XCACHE_BACKEND = 'Zend_Cache_Backend_Xcache::save() : tags are unsupported by the Xcache backend';
/**
* Available options
*
* =====> (string) user :
* xcache.admin.user (necessary for the clean() method)
*
* =====> (string) password :
* xcache.admin.pass (clear, not MD5) (necessary for the clean() method)
*
* @var array available options
*/
protected $_options = array(
'user' => null,
'password' => null
);
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('xcache')) {
Zend_Cache::throwException('The xcache 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 Xcache 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)
{
if ($doNotTestCacheValidity) {
$this->_log("Zend_Cache_Backend_Xcache::load() : \$doNotTestCacheValidity=true is unsupported by the Xcache backend");
}
$tmp = xcache_get($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)
{
if (xcache_isset($id)) {
$tmp = xcache_get($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 = xcache_set($id, array($data, time()), $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_XCACHE_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return xcache_unset($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:
// Necessary because xcache_clear_cache() need basic authentification
$backup = array();
if (isset($_SERVER['PHP_AUTH_USER'])) {
$backup['PHP_AUTH_USER'] = $_SERVER['PHP_AUTH_USER'];
}
if (isset($_SERVER['PHP_AUTH_PW'])) {
$backup['PHP_AUTH_PW'] = $_SERVER['PHP_AUTH_PW'];
}
if ($this->_options['user']) {
$_SERVER['PHP_AUTH_USER'] = $this->_options['user'];
}
if ($this->_options['password']) {
$_SERVER['PHP_AUTH_PW'] = $this->_options['password'];
}
xcache_clear_cache(XC_TYPE_VAR, 0);
if (isset($backup['PHP_AUTH_USER'])) {
$_SERVER['PHP_AUTH_USER'] = $backup['PHP_AUTH_USER'];
$_SERVER['PHP_AUTH_PW'] = $backup['PHP_AUTH_PW'];
}
return true;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Xcache::clean() : CLEANING_MODE_OLD is unsupported by the Xcache 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_XCACHE_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
}

View file

@ -0,0 +1,317 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ZendPlatform.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* @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-2010 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;
}
}

View file

@ -0,0 +1,207 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ZendServer.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/** @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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Cache_Backend_ZendServer extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* Available options
*
* =====> (string) namespace :
* Namespace to be used for chaching operations
*
* @var array available options
*/
protected $_options = array(
'namespace' => 'zendframework'
);
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
* @throws Zend_Cache_Exception
*/
abstract protected function _store($data, $id, $timeToLive);
/**
* Fetch data
*
* @param string $id Cache id
* @throws Zend_Cache_Exception
*/
abstract protected function _fetch($id);
/**
* Unset data
*
* @param string $id Cache id
*/
abstract protected function _unset($id);
/**
* Clear cache
*/
abstract protected function _clear();
/**
* 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 datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = $this->_fetch($id);
if ($tmp !== null) {
return $tmp;
}
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
* @throws Zend_Cache_Exception
*/
public function test($id)
{
$tmp = $this->_fetch('internal-metadatas---' . $id);
if ($tmp !== false) {
if (!is_array($tmp) || !isset($tmp['mtime'])) {
Zend_Cache::throwException('Cache metadata for \'' . $id . '\' id is corrupted' );
}
return $tmp['mtime'];
}
return false;
}
/**
* Compute & return the expire time
*
* @return int expire time (unix timestamp)
*/
private function _expireTime($lifetime)
{
if ($lifetime === null) {
return 9999999999;
}
return time() + $lifetime;
}
/**
* 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);
$metadatas = array(
'mtime' => time(),
'expire' => $this->_expireTime($lifetime),
);
if (count($tags) > 0) {
$this->_log('Zend_Cache_Backend_ZendServer::save() : tags are unsupported by the ZendServer backends');
}
return $this->_store($data, $id, $lifetime) &&
$this->_store($metadatas, 'internal-metadatas---' . $id, $lifetime);
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
$result1 = $this->_unset($id);
$result2 = $this->_unset('internal-metadatas---' . $id);
return $result1 && $result2;
}
/**
* 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:
$this->_clear();
return true;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_ZendServer::clean() : CLEANING_MODE_OLD is unsupported by the Zend Server backends.");
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->_clear();
$this->_log('Zend_Cache_Backend_ZendServer::clean() : tags are unsupported by the Zend Server backends.');
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
}

View file

@ -0,0 +1,100 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Disk.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/** @see Zend_Cache_Backend_Interface */
require_once 'Zend/Cache/Backend/Interface.php';
/** @see Zend_Cache_Backend_ZendServer */
require_once 'Zend/Cache/Backend/ZendServer.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_ZendServer_Disk extends Zend_Cache_Backend_ZendServer implements Zend_Cache_Backend_Interface
{
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
*/
public function __construct(array $options = array())
{
if (!function_exists('zend_disk_cache_store')) {
Zend_Cache::throwException('Zend_Cache_ZendServer_Disk backend has to be used within Zend Server environment.');
}
parent::__construct($options);
}
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
* @return boolean true if no problem
*/
protected function _store($data, $id, $timeToLive)
{
if (zend_disk_cache_store($this->_options['namespace'] . '::' . $id,
$data,
$timeToLive) === false) {
$this->_log('Store operation failed.');
return false;
}
return true;
}
/**
* Fetch data
*
* @param string $id Cache id
*/
protected function _fetch($id)
{
return zend_disk_cache_fetch($this->_options['namespace'] . '::' . $id);
}
/**
* Unset data
*
* @param string $id Cache id
* @return boolean true if no problem
*/
protected function _unset($id)
{
return zend_disk_cache_delete($this->_options['namespace'] . '::' . $id);
}
/**
* Clear cache
*/
protected function _clear()
{
zend_disk_cache_clear($this->_options['namespace']);
}
}

View file

@ -0,0 +1,100 @@
<?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-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ShMem.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/** @see Zend_Cache_Backend_Interface */
require_once 'Zend/Cache/Backend/Interface.php';
/** @see Zend_Cache_Backend_ZendServer */
require_once 'Zend/Cache/Backend/ZendServer.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_ZendServer_ShMem extends Zend_Cache_Backend_ZendServer implements Zend_Cache_Backend_Interface
{
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
*/
public function __construct(array $options = array())
{
if (!function_exists('zend_shm_cache_store')) {
Zend_Cache::throwException('Zend_Cache_ZendServer_ShMem backend has to be used within Zend Server environment.');
}
parent::__construct($options);
}
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
*
*/
protected function _store($data, $id, $timeToLive)
{
if (zend_shm_cache_store($this->_options['namespace'] . '::' . $id,
$data,
$timeToLive) === false) {
$this->_log('Store operation failed.');
return false;
}
return true;
}
/**
* Fetch data
*
* @param string $id Cache id
*/
protected function _fetch($id)
{
return zend_shm_cache_fetch($this->_options['namespace'] . '::' . $id);
}
/**
* Unset data
*
* @param string $id Cache id
* @return boolean true if no problem
*/
protected function _unset($id)
{
return zend_shm_cache_delete($this->_options['namespace'] . '::' . $id);
}
/**
* Clear cache
*/
protected function _clear()
{
zend_shm_cache_clear($this->_options['namespace']);
}
}