7 * This source file is subject to the new BSD license that is bundled
8 * with this package in the file LICENSE.txt.
9 * It is also available through the world-wide-web at this URL:
10 * http://framework.zend.com/license/new-bsd
11 * If you did not receive a copy of the license and are unable to
12 * obtain it through the world-wide-web, please send an email
13 * to license@zend.com so we can send you a copy immediately.
17 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
18 * @license http://framework.zend.com/license/new-bsd New BSD License
19 * @version $Id: Core.php 24989 2012-06-21 07:24:13Z mabe $
25 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
26 * @license http://framework.zend.com/license/new-bsd New BSD License
33 const BACKEND_NOT_SUPPORTS_TAG
= 'tags are not supported by the current backend';
34 const BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
= 'Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available';
39 * @var Zend_Cache_Backend_Interface $_backend
41 protected $_backend = null;
46 * ====> (boolean) write_control :
47 * - Enable / disable write control (the cache is read just after writing to detect corrupt entries)
48 * - Enable write control will lightly slow the cache writing but not the cache reading
49 * Write control can detect some corrupt cache files but maybe it's not a perfect control
51 * ====> (boolean) caching :
52 * - Enable / disable caching
53 * (can be very useful for the debug of cached scripts)
55 * =====> (string) cache_id_prefix :
56 * - prefix for cache ids (namespace)
58 * ====> (boolean) automatic_serialization :
59 * - Enable / disable automatic serialization
60 * - It can be used to save directly datas which aren't strings (but it's slower)
62 * ====> (int) automatic_cleaning_factor :
63 * - Disable / Tune the automatic cleaning process
64 * - The automatic cleaning process destroy too old (for the given life time)
65 * cache files when a new cache file is written :
66 * 0 => no automatic cache cleaning
67 * 1 => systematic cache cleaning
68 * x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
70 * ====> (int) lifetime :
71 * - Cache lifetime (in seconds)
72 * - If null, the cache is valid forever.
74 * ====> (boolean) logging :
75 * - If set to true, logging is activated (but the system is slower)
77 * ====> (boolean) ignore_user_abort
78 * - If set to true, the core will set the ignore_user_abort PHP flag inside the
79 * save() method to avoid cache corruptions in some cases (default false)
81 * @var array $_options available options
83 protected $_options = array(
84 'write_control' => true,
86 'cache_id_prefix' => null,
87 'automatic_serialization' => false,
88 'automatic_cleaning_factor' => 10,
92 'ignore_user_abort' => false
96 * Array of options which have to be transfered to backend
98 * @var array $_directivesList
100 protected static $_directivesList = array('lifetime', 'logging', 'logger');
103 * Not used for the core, just a sort a hint to get a common setOption() method (for the core and for frontends)
105 * @var array $_specificOptions
107 protected $_specificOptions = array();
112 * @var string $_lastId
114 private $_lastId = null;
117 * True if the backend implements Zend_Cache_Backend_ExtendedInterface
119 * @var boolean $_extendedBackend
121 protected $_extendedBackend = false;
124 * Array of capabilities of the backend (only if it implements Zend_Cache_Backend_ExtendedInterface)
128 protected $_backendCapabilities = array();
133 * @param array|Zend_Config $options Associative array of options or Zend_Config instance
134 * @throws Zend_Cache_Exception
137 public function __construct($options = array())
139 if ($options instanceof Zend_Config
) {
140 $options = $options->toArray();
142 if (!is_array($options)) {
143 Zend_Cache
::throwException("Options passed were not an array"
144 . " or Zend_Config instance.");
146 while (list($name, $value) = each($options)) {
147 $this->setOption($name, $value);
149 $this->_loggerSanity();
153 * Set options using an instance of type Zend_Config
155 * @param Zend_Config $config
156 * @return Zend_Cache_Core
158 public function setConfig(Zend_Config
$config)
160 $options = $config->toArray();
161 while (list($name, $value) = each($options)) {
162 $this->setOption($name, $value);
170 * @param Zend_Cache_Backend $backendObject
171 * @throws Zend_Cache_Exception
174 public function setBackend(Zend_Cache_Backend
$backendObject)
176 $this->_backend
= $backendObject;
177 // some options (listed in $_directivesList) have to be given
178 // to the backend too (even if they are not "backend specific")
179 $directives = array();
180 foreach (Zend_Cache_Core
::$_directivesList as $directive) {
181 $directives[$directive] = $this->_options
[$directive];
183 $this->_backend
->setDirectives($directives);
184 if (in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_backend
))) {
185 $this->_extendedBackend
= true;
186 $this->_backendCapabilities
= $this->_backend
->getCapabilities();
192 * Returns the backend
194 * @return Zend_Cache_Backend backend object
196 public function getBackend()
198 return $this->_backend
;
202 * Public frontend to set an option
204 * There is an additional validation (relatively to the protected _setOption method)
206 * @param string $name Name of the option
207 * @param mixed $value Value of the option
208 * @throws Zend_Cache_Exception
211 public function setOption($name, $value)
213 if (!is_string($name)) {
214 Zend_Cache
::throwException("Incorrect option name!");
216 $name = strtolower($name);
217 if (array_key_exists($name, $this->_options
)) {
218 // This is a Core option
219 $this->_setOption($name, $value);
222 if (array_key_exists($name, $this->_specificOptions
)) {
223 // This a specic option of this frontend
224 $this->_specificOptions
[$name] = $value;
230 * Public frontend to get an option value
232 * @param string $name Name of the option
233 * @throws Zend_Cache_Exception
234 * @return mixed option value
236 public function getOption($name)
238 $name = strtolower($name);
240 if (array_key_exists($name, $this->_options
)) {
241 // This is a Core option
242 return $this->_options
[$name];
245 if (array_key_exists($name, $this->_specificOptions
)) {
246 // This a specic option of this frontend
247 return $this->_specificOptions
[$name];
250 Zend_Cache
::throwException("Incorrect option name : $name");
256 * @param string $name Name of the option
257 * @param mixed $value Value of the option
258 * @throws Zend_Cache_Exception
261 private function _setOption($name, $value)
263 if (!is_string($name) || !array_key_exists($name, $this->_options)) {
264 Zend_Cache::throwException("Incorrect option name
: $name");
266 if ($name == 'lifetime' && empty($value)) {
269 $this->_options
[$name] = $value;
273 * Force a new lifetime
275 * The new value is set for the core/frontend but for the backend too (directive)
277 * @param int $newLifetime New lifetime (in seconds)
280 public function setLifetime($newLifetime)
282 $this->_options
['lifetime'] = $newLifetime;
283 $this->_backend
->setDirectives(array(
284 'lifetime' => $newLifetime
289 * Test if a cache is available for the given id and (if yes) return it (false else)
291 * @param string $id Cache id
292 * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
293 * @param boolean $doNotUnserialize Do not serialize (even if automatic_serialization is true) => for internal use
294 * @return mixed|false Cached datas
296 public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false)
298 if (!$this->_options
['caching']) {
301 $id = $this->_id($id); // cache id may need prefix
302 $this->_lastId
= $id;
303 self
::_validateIdOrTag($id);
305 $this->_log("Zend_Cache_Core: load item '{$id}'", 7);
306 $data = $this->_backend
->load($id, $doNotTestCacheValidity);
308 // no cache available
311 if ((!$doNotUnserialize) && $this->_options
['automatic_serialization']) {
312 // we need to unserialize before sending the result
313 return unserialize($data);
319 * Test if a cache is available for the given id
321 * @param string $id Cache id
322 * @return int|false Last modified time of cache entry if it is available, false otherwise
324 public function test($id)
326 if (!$this->_options
['caching']) {
329 $id = $this->_id($id); // cache id may need prefix
330 self
::_validateIdOrTag($id);
331 $this->_lastId
= $id;
333 $this->_log("Zend_Cache_Core: test item '{$id}'", 7);
334 return $this->_backend
->test($id);
338 * Save some data in a cache
340 * @param mixed $data Data to put in cache (can be another type than string if automatic_serialization is on)
341 * @param string $id Cache id (if not set, the last cache id will be used)
342 * @param array $tags Cache tags
343 * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
344 * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
345 * @throws Zend_Cache_Exception
346 * @return boolean True if no problem
348 public function save($data, $id = null, $tags = array(), $specificLifetime = false, $priority = 8)
350 if (!$this->_options
['caching']) {
354 $id = $this->_lastId
;
356 $id = $this->_id($id);
358 self
::_validateIdOrTag($id);
359 self
::_validateTagsArray($tags);
360 if ($this->_options
['automatic_serialization']) {
361 // we need to serialize datas before storing them
362 $data = serialize($data);
364 if (!is_string($data)) {
365 Zend_Cache
::throwException("Datas must be string or set automatic_serialization = true");
369 // automatic cleaning
370 if ($this->_options
['automatic_cleaning_factor'] > 0) {
371 $rand = rand(1, $this->_options
['automatic_cleaning_factor']);
373 // new way || deprecated way
374 if ($this->_extendedBackend
|| method_exists($this->_backend
, 'isAutomaticCleaningAvailable')) {
375 $this->_log("Zend_Cache_Core::save(): automatic cleaning running", 7);
376 $this->clean(Zend_Cache
::CLEANING_MODE_OLD
);
378 $this->_log("Zend_Cache_Core::save(): automatic cleaning is not available/necessary with current backend", 4);
383 $this->_log("Zend_Cache_Core: save item '{$id}'", 7);
384 if ($this->_options
['ignore_user_abort']) {
385 $abort = ignore_user_abort(true);
387 if (($this->_extendedBackend
) && ($this->_backendCapabilities
['priority'])) {
388 $result = $this->_backend
->save($data, $id, $tags, $specificLifetime, $priority);
390 $result = $this->_backend
->save($data, $id, $tags, $specificLifetime);
392 if ($this->_options
['ignore_user_abort']) {
393 ignore_user_abort($abort);
397 // maybe the cache is corrupted, so we remove it !
398 $this->_log("Zend_Cache_Core::save(): failed to save item '{$id}' -> removing it", 4);
399 $this->_backend
->remove($id);
403 if ($this->_options
['write_control']) {
404 $data2 = $this->_backend
->load($id, true);
406 $this->_log("Zend_Cache_Core::save(): write control of item '{$id}' failed -> removing it", 4);
407 $this->_backend
->remove($id);
418 * @param string $id Cache id to remove
419 * @return boolean True if ok
421 public function remove($id)
423 if (!$this->_options
['caching']) {
426 $id = $this->_id($id); // cache id may need prefix
427 self
::_validateIdOrTag($id);
429 $this->_log("Zend_Cache_Core: remove item '{$id}'", 7);
430 return $this->_backend
->remove($id);
434 * Clean cache entries
436 * Available modes are :
437 * 'all' (default) => remove all cache entries ($tags is not used)
438 * 'old' => remove too old cache entries ($tags is not used)
439 * 'matchingTag' => remove cache entries matching all given tags
440 * ($tags can be an array of strings or a single string)
441 * 'notMatchingTag' => remove cache entries not matching one of the given tags
442 * ($tags can be an array of strings or a single string)
443 * 'matchingAnyTag' => remove cache entries matching any given tags
444 * ($tags can be an array of strings or a single string)
446 * @param string $mode
447 * @param array|string $tags
448 * @throws Zend_Cache_Exception
449 * @return boolean True if ok
451 public function clean($mode = 'all', $tags = array())
453 if (!$this->_options
['caching']) {
456 if (!in_array($mode, array(Zend_Cache
::CLEANING_MODE_ALL
,
457 Zend_Cache
::CLEANING_MODE_OLD
,
458 Zend_Cache
::CLEANING_MODE_MATCHING_TAG
,
459 Zend_Cache
::CLEANING_MODE_NOT_MATCHING_TAG
,
460 Zend_Cache
::CLEANING_MODE_MATCHING_ANY_TAG
))) {
461 Zend_Cache
::throwException('Invalid cleaning mode');
463 self
::_validateTagsArray($tags);
465 return $this->_backend
->clean($mode, $tags);
469 * Return an array of stored cache ids which match given tags
471 * In case of multiple tags, a logical AND is made between tags
473 * @param array $tags array of tags
474 * @return array array of matching cache ids (string)
476 public function getIdsMatchingTags($tags = array())
478 if (!$this->_extendedBackend
) {
479 Zend_Cache
::throwException(self
::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
);
481 if (!($this->_backendCapabilities
['tags'])) {
482 Zend_Cache
::throwException(self
::BACKEND_NOT_SUPPORTS_TAG
);
485 $ids = $this->_backend
->getIdsMatchingTags($tags);
487 // we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
488 if (isset($this->_options
['cache_id_prefix']) && $this->_options
['cache_id_prefix'] !== '') {
489 $prefix = & $this->_options
['cache_id_prefix'];
490 $prefixLen = strlen($prefix);
491 foreach ($ids as &$id) {
492 if (strpos($id, $prefix) === 0) {
493 $id = substr($id, $prefixLen);
502 * Return an array of stored cache ids which don't match given tags
504 * In case of multiple tags, a logical OR is made between tags
506 * @param array $tags array of tags
507 * @return array array of not matching cache ids (string)
509 public function getIdsNotMatchingTags($tags = array())
511 if (!$this->_extendedBackend
) {
512 Zend_Cache
::throwException(self
::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
);
514 if (!($this->_backendCapabilities
['tags'])) {
515 Zend_Cache
::throwException(self
::BACKEND_NOT_SUPPORTS_TAG
);
518 $ids = $this->_backend
->getIdsNotMatchingTags($tags);
520 // we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
521 if (isset($this->_options
['cache_id_prefix']) && $this->_options
['cache_id_prefix'] !== '') {
522 $prefix = & $this->_options
['cache_id_prefix'];
523 $prefixLen = strlen($prefix);
524 foreach ($ids as &$id) {
525 if (strpos($id, $prefix) === 0) {
526 $id = substr($id, $prefixLen);
535 * Return an array of stored cache ids which match any given tags
537 * In case of multiple tags, a logical OR is made between tags
539 * @param array $tags array of tags
540 * @return array array of matching any cache ids (string)
542 public function getIdsMatchingAnyTags($tags = array())
544 if (!$this->_extendedBackend
) {
545 Zend_Cache
::throwException(self
::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
);
547 if (!($this->_backendCapabilities
['tags'])) {
548 Zend_Cache
::throwException(self
::BACKEND_NOT_SUPPORTS_TAG
);
551 $ids = $this->_backend
->getIdsMatchingAnyTags($tags);
553 // we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
554 if (isset($this->_options
['cache_id_prefix']) && $this->_options
['cache_id_prefix'] !== '') {
555 $prefix = & $this->_options
['cache_id_prefix'];
556 $prefixLen = strlen($prefix);
557 foreach ($ids as &$id) {
558 if (strpos($id, $prefix) === 0) {
559 $id = substr($id, $prefixLen);
568 * Return an array of stored cache ids
570 * @return array array of stored cache ids (string)
572 public function getIds()
574 if (!$this->_extendedBackend
) {
575 Zend_Cache
::throwException(self
::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
);
578 $ids = $this->_backend
->getIds();
580 // we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
581 if (isset($this->_options
['cache_id_prefix']) && $this->_options
['cache_id_prefix'] !== '') {
582 $prefix = & $this->_options
['cache_id_prefix'];
583 $prefixLen = strlen($prefix);
584 foreach ($ids as &$id) {
585 if (strpos($id, $prefix) === 0) {
586 $id = substr($id, $prefixLen);
595 * Return an array of stored tags
597 * @return array array of stored tags (string)
599 public function getTags()
601 if (!$this->_extendedBackend
) {
602 Zend_Cache
::throwException(self
::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
);
604 if (!($this->_backendCapabilities
['tags'])) {
605 Zend_Cache
::throwException(self
::BACKEND_NOT_SUPPORTS_TAG
);
607 return $this->_backend
->getTags();
611 * Return the filling percentage of the backend storage
613 * @return int integer between 0 and 100
615 public function getFillingPercentage()
617 if (!$this->_extendedBackend
) {
618 Zend_Cache
::throwException(self
::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
);
620 return $this->_backend
->getFillingPercentage();
624 * Return an array of metadatas for the given cache id
626 * The array will include these keys :
627 * - expire : the expire timestamp
628 * - tags : a string array of tags
629 * - mtime : timestamp of last modification time
631 * @param string $id cache id
632 * @return array array of metadatas (false if the cache id is not found)
634 public function getMetadatas($id)
636 if (!$this->_extendedBackend
) {
637 Zend_Cache
::throwException(self
::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
);
639 $id = $this->_id($id); // cache id may need prefix
640 return $this->_backend
->getMetadatas($id);
644 * Give (if possible) an extra lifetime to the given cache id
646 * @param string $id cache id
647 * @param int $extraLifetime
648 * @return boolean true if ok
650 public function touch($id, $extraLifetime)
652 if (!$this->_extendedBackend
) {
653 Zend_Cache
::throwException(self
::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF
);
655 $id = $this->_id($id); // cache id may need prefix
657 $this->_log("Zend_Cache_Core: touch item '{$id}'", 7);
658 return $this->_backend
->touch($id, $extraLifetime);
662 * Validate a cache id or a tag (security, reliable filenames, reserved prefixes...)
664 * Throw an exception if a problem is found
666 * @param string $string Cache id or tag
667 * @throws Zend_Cache_Exception
670 protected static function _validateIdOrTag($string)
672 if (!is_string($string)) {
673 Zend_Cache
::throwException('Invalid id or tag : must be a string');
675 if (substr($string, 0, 9) == 'internal-') {
676 Zend_Cache
::throwException('"internal-*" ids or tags are reserved');
678 if (!preg_match('~^[a-zA-Z0-9_]+$~D', $string)) {
679 Zend_Cache
::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]");
684 * Validate a tags array (security, reliable filenames, reserved prefixes...)
686 * Throw an exception if a problem is found
688 * @param array $tags Array of tags
689 * @throws Zend_Cache_Exception
692 protected static function _validateTagsArray($tags)
694 if (!is_array($tags)) {
695 Zend_Cache
::throwException('Invalid tags array : must be an array');
697 foreach($tags as $tag) {
698 self
::_validateIdOrTag($tag);
704 * Make sure if we enable logging that the Zend_Log class
706 * Create a default log object if none is set.
708 * @throws Zend_Cache_Exception
711 protected function _loggerSanity()
713 if (!isset($this->_options
['logging']) || !$this->_options
['logging']) {
717 if (isset($this->_options
['logger']) && $this->_options
['logger'] instanceof Zend_Log
) {
721 // Create a default logger to the standard output stream
722 require_once 'Zend/Log.php';
723 require_once 'Zend/Log/Writer/Stream.php';
724 require_once 'Zend/Log/Filter/Priority.php';
725 $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
726 $logger->addFilter(new Zend_Log_Filter_Priority(Zend_Log
::WARN
, '<='));
727 $this->_options
['logger'] = $logger;
731 * Log a message at the WARN (4) priority.
733 * @param string $message
734 * @throws Zend_Cache_Exception
737 protected function _log($message, $priority = 4)
739 if (!$this->_options
['logging']) {
742 if (!(isset($this->_options
['logger']) || $this->_options
['logger'] instanceof Zend_Log
)) {
743 Zend_Cache
::throwException('Logging is enabled but logger is not set');
745 $logger = $this->_options
['logger'];
746 $logger->log($message, $priority);
750 * Make and return a cache id
752 * Checks 'cache_id_prefix' and returns new id with prefix or simply the id if null
754 * @param string $id Cache id
755 * @return string Cache id (with or without prefix)
757 protected function _id($id)
759 if (($id !== null) && isset($this->_options
['cache_id_prefix'])) {
760 return $this->_options
['cache_id_prefix'] . $id; // return with prefix
762 return $id; // no prefix, just return the $id passed