Core.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  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.
  14. *
  15. * @category Zend
  16. * @package Zend_Cache
  17. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * @package Zend_Cache
  23. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  24. * @license http://framework.zend.com/license/new-bsd New BSD License
  25. */
  26. class Zend_Cache_Core
  27. {
  28. /**
  29. * Backend Object
  30. *
  31. * @var object $_backend
  32. */
  33. protected $_backend = null;
  34. /**
  35. * Available options
  36. *
  37. * ====> (boolean) write_control :
  38. * - Enable / disable write control (the cache is read just after writing to detect corrupt entries)
  39. * - Enable write control will lightly slow the cache writing but not the cache reading
  40. * Write control can detect some corrupt cache files but maybe it's not a perfect control
  41. *
  42. * ====> (boolean) caching :
  43. * - Enable / disable caching
  44. * (can be very useful for the debug of cached scripts)
  45. *
  46. * =====> (string) cache_id_prefix :
  47. * - prefix for cache ids (namespace)
  48. *
  49. * ====> (boolean) automatic_serialization :
  50. * - Enable / disable automatic serialization
  51. * - It can be used to save directly datas which aren't strings (but it's slower)
  52. *
  53. * ====> (int) automatic_cleaning_factor :
  54. * - Disable / Tune the automatic cleaning process
  55. * - The automatic cleaning process destroy too old (for the given life time)
  56. * cache files when a new cache file is written :
  57. * 0 => no automatic cache cleaning
  58. * 1 => systematic cache cleaning
  59. * x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
  60. *
  61. * ====> (int) lifetime :
  62. * - Cache lifetime (in seconds)
  63. * - If null, the cache is valid forever.
  64. *
  65. * ====> (boolean) logging :
  66. * - If set to true, logging is activated (but the system is slower)
  67. *
  68. * ====> (boolean) ignore_user_abort
  69. * - If set to true, the core will set the ignore_user_abort PHP flag inside the
  70. * save() method to avoid cache corruptions in some cases (default false)
  71. *
  72. * @var array $_options available options
  73. */
  74. protected $_options = array(
  75. 'write_control' => true,
  76. 'caching' => true,
  77. 'cache_id_prefix' => null,
  78. 'automatic_serialization' => false,
  79. 'automatic_cleaning_factor' => 10,
  80. 'lifetime' => 3600,
  81. 'logging' => false,
  82. 'logger' => null,
  83. 'ignore_user_abort' => false
  84. );
  85. /**
  86. * Array of options which have to be transfered to backend
  87. *
  88. * @var array $_directivesList
  89. */
  90. protected static $_directivesList = array('lifetime', 'logging', 'logger');
  91. /**
  92. * Not used for the core, just a sort a hint to get a common setOption() method (for the core and for frontends)
  93. *
  94. * @var array $_specificOptions
  95. */
  96. protected $_specificOptions = array();
  97. /**
  98. * Last used cache id
  99. *
  100. * @var string $_lastId
  101. */
  102. private $_lastId = null;
  103. /**
  104. * True if the backend implements Zend_Cache_Backend_ExtendedInterface
  105. *
  106. * @var boolean $_extendedBackend
  107. */
  108. protected $_extendedBackend = false;
  109. /**
  110. * Array of capabilities of the backend (only if it implements Zend_Cache_Backend_ExtendedInterface)
  111. *
  112. * @var array
  113. */
  114. protected $_backendCapabilities = array();
  115. /**
  116. * Constructor
  117. *
  118. * @param array $options Associative array of options
  119. * @throws Zend_Cache_Exception
  120. * @return void
  121. */
  122. public function __construct(array $options = array())
  123. {
  124. while (list($name, $value) = each($options)) {
  125. $this->setOption($name, $value);
  126. }
  127. $this->_loggerSanity();
  128. }
  129. /**
  130. * Set the backend
  131. *
  132. * @param object $backendObject
  133. * @throws Zend_Cache_Exception
  134. * @return void
  135. */
  136. public function setBackend(Zend_Cache_Backend $backendObject)
  137. {
  138. $this->_backend= $backendObject;
  139. // some options (listed in $_directivesList) have to be given
  140. // to the backend too (even if they are not "backend specific")
  141. $directives = array();
  142. foreach (Zend_Cache_Core::$_directivesList as $directive) {
  143. $directives[$directive] = $this->_options[$directive];
  144. }
  145. $this->_backend->setDirectives($directives);
  146. if (in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_backend))) {
  147. $this->_extendedBackend = true;
  148. $this->_backendCapabilities = $this->_backend->getCapabilities();
  149. }
  150. }
  151. /**
  152. * Returns the backend
  153. *
  154. * @return object backend object
  155. */
  156. public function getBackend()
  157. {
  158. return $this->_backend;
  159. }
  160. /**
  161. * Public frontend to set an option
  162. *
  163. * There is an additional validation (relatively to the protected _setOption method)
  164. *
  165. * @param string $name Name of the option
  166. * @param mixed $value Value of the option
  167. * @throws Zend_Cache_Exception
  168. * @return void
  169. */
  170. public function setOption($name, $value)
  171. {
  172. if (!is_string($name)) {
  173. Zend_Cache::throwException("Incorrect option name : $name");
  174. }
  175. $name = strtolower($name);
  176. if (array_key_exists($name, $this->_options)) {
  177. // This is a Core option
  178. $this->_setOption($name, $value);
  179. return;
  180. }
  181. if (array_key_exists($name, $this->_specificOptions)) {
  182. // This a specic option of this frontend
  183. $this->_specificOptions[$name] = $value;
  184. return;
  185. }
  186. }
  187. /**
  188. * Public frontend to get an option value
  189. *
  190. * @param string $name Name of the option
  191. * @throws Zend_Cache_Exception
  192. * @return mixed option value
  193. */
  194. public function getOption($name)
  195. {
  196. if (is_string($name)) {
  197. $name = strtolower($name);
  198. if (array_key_exists($name, $this->_options)) {
  199. // This is a Core option
  200. return $this->_options[$name];
  201. }
  202. if (array_key_exists($name, $this->_specificOptions)) {
  203. // This a specic option of this frontend
  204. return $this->_specificOptions[$name];
  205. }
  206. }
  207. Zend_Cache::throwException("Incorrect option name : $name");
  208. }
  209. /**
  210. * Set an option
  211. *
  212. * @param string $name Name of the option
  213. * @param mixed $value Value of the option
  214. * @throws Zend_Cache_Exception
  215. * @return void
  216. */
  217. private function _setOption($name, $value)
  218. {
  219. if (!is_string($name) || !array_key_exists($name, $this->_options)) {
  220. Zend_Cache::throwException("Incorrect option name : $name");
  221. }
  222. $this->_options[$name] = $value;
  223. }
  224. /**
  225. * Force a new lifetime
  226. *
  227. * The new value is set for the core/frontend but for the backend too (directive)
  228. *
  229. * @param int $newLifetime New lifetime (in seconds)
  230. * @return void
  231. */
  232. public function setLifetime($newLifetime)
  233. {
  234. $this->_options['lifetime'] = $newLifetime;
  235. $this->_backend->setDirectives(array(
  236. 'lifetime' => $newLifetime
  237. ));
  238. }
  239. /**
  240. * Test if a cache is available for the given id and (if yes) return it (false else)
  241. *
  242. * @param string $id Cache id
  243. * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
  244. * @param boolean $doNotUnserialize Do not serialize (even if automatic_serialization is true) => for internal use
  245. * @return mixed|false Cached datas
  246. */
  247. public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false)
  248. {
  249. if (!$this->_options['caching']) {
  250. return false;
  251. }
  252. $id = $this->_id($id); // cache id may need prefix
  253. $this->_lastId = $id;
  254. self::_validateIdOrTag($id);
  255. $data = $this->_backend->load($id, $doNotTestCacheValidity);
  256. if ($data===false) {
  257. // no cache available
  258. return false;
  259. }
  260. if ((!$doNotUnserialize) && $this->_options['automatic_serialization']) {
  261. // we need to unserialize before sending the result
  262. return unserialize($data);
  263. }
  264. return $data;
  265. }
  266. /**
  267. * Test if a cache is available for the given id
  268. *
  269. * @param string $id Cache id
  270. * @return boolean True is a cache is available, false else
  271. */
  272. public function test($id)
  273. {
  274. if (!$this->_options['caching']) {
  275. return false;
  276. }
  277. $id = $this->_id($id); // cache id may need prefix
  278. self::_validateIdOrTag($id);
  279. $this->_lastId = $id;
  280. return $this->_backend->test($id);
  281. }
  282. /**
  283. * Save some data in a cache
  284. *
  285. * @param mixed $data Data to put in cache (can be another type than string if automatic_serialization is on)
  286. * @param string $id Cache id (if not set, the last cache id will be used)
  287. * @param array $tags Cache tags
  288. * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
  289. * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
  290. * @throws Zend_Cache_Exception
  291. * @return boolean True if no problem
  292. */
  293. public function save($data, $id = null, $tags = array(), $specificLifetime = false, $priority = 8)
  294. {
  295. if (!$this->_options['caching']) {
  296. return true;
  297. }
  298. if ($id === null) {
  299. $id = $this->_lastId;
  300. } else {
  301. $id = $this->_id($id);
  302. }
  303. self::_validateIdOrTag($id);
  304. self::_validateTagsArray($tags);
  305. if ($this->_options['automatic_serialization']) {
  306. // we need to serialize datas before storing them
  307. $data = serialize($data);
  308. } else {
  309. if (!is_string($data)) {
  310. Zend_Cache::throwException("Datas must be string or set automatic_serialization = true");
  311. }
  312. }
  313. // automatic cleaning
  314. if ($this->_options['automatic_cleaning_factor'] > 0) {
  315. $rand = rand(1, $this->_options['automatic_cleaning_factor']);
  316. if ($rand==1) {
  317. if ($this->_extendedBackend) {
  318. // New way
  319. if ($this->_backendCapabilities['automatic_cleaning']) {
  320. $this->clean(Zend_Cache::CLEANING_MODE_OLD);
  321. } else {
  322. $this->_log('Zend_Cache_Core::save() / automatic cleaning is not available/necessary with this backend');
  323. }
  324. } else {
  325. // Deprecated way (will be removed in next major version)
  326. if (method_exists($this->_backend, 'isAutomaticCleaningAvailable') && ($this->_backend->isAutomaticCleaningAvailable())) {
  327. $this->clean(Zend_Cache::CLEANING_MODE_OLD);
  328. } else {
  329. $this->_log('Zend_Cache_Core::save() / automatic cleaning is not available/necessary with this backend');
  330. }
  331. }
  332. }
  333. }
  334. if ($this->_options['ignore_user_abort']) {
  335. $abort = ignore_user_abort(true);
  336. }
  337. if (($this->_extendedBackend) && ($this->_backendCapabilities['priority'])) {
  338. $result = $this->_backend->save($data, $id, $tags, $specificLifetime, $priority);
  339. } else {
  340. $result = $this->_backend->save($data, $id, $tags, $specificLifetime);
  341. }
  342. if ($this->_options['ignore_user_abort']) {
  343. ignore_user_abort($abort);
  344. }
  345. if (!$result) {
  346. // maybe the cache is corrupted, so we remove it !
  347. if ($this->_options['logging']) {
  348. $this->_log("Zend_Cache_Core::save() : impossible to save cache (id=$id)");
  349. }
  350. $this->remove($id);
  351. return false;
  352. }
  353. if ($this->_options['write_control']) {
  354. $data2 = $this->_backend->load($id, true);
  355. if ($data!=$data2) {
  356. $this->_log('Zend_Cache_Core::save() / write_control : written and read data do not match');
  357. $this->_backend->remove($id);
  358. return false;
  359. }
  360. }
  361. return true;
  362. }
  363. /**
  364. * Remove a cache
  365. *
  366. * @param string $id Cache id to remove
  367. * @return boolean True if ok
  368. */
  369. public function remove($id)
  370. {
  371. if (!$this->_options['caching']) {
  372. return true;
  373. }
  374. $id = $this->_id($id); // cache id may need prefix
  375. self::_validateIdOrTag($id);
  376. return $this->_backend->remove($id);
  377. }
  378. /**
  379. * Clean cache entries
  380. *
  381. * Available modes are :
  382. * 'all' (default) => remove all cache entries ($tags is not used)
  383. * 'old' => remove too old cache entries ($tags is not used)
  384. * 'matchingTag' => remove cache entries matching all given tags
  385. * ($tags can be an array of strings or a single string)
  386. * 'notMatchingTag' => remove cache entries not matching one of the given tags
  387. * ($tags can be an array of strings or a single string)
  388. * 'matchingAnyTag' => remove cache entries matching any given tags
  389. * ($tags can be an array of strings or a single string)
  390. *
  391. * @param string $mode
  392. * @param array|string $tags
  393. * @throws Zend_Cache_Exception
  394. * @return boolean True if ok
  395. */
  396. public function clean($mode = 'all', $tags = array())
  397. {
  398. if (!$this->_options['caching']) {
  399. return true;
  400. }
  401. if (!in_array($mode, array(Zend_Cache::CLEANING_MODE_ALL,
  402. Zend_Cache::CLEANING_MODE_OLD,
  403. Zend_Cache::CLEANING_MODE_MATCHING_TAG,
  404. Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG,
  405. Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG))) {
  406. Zend_Cache::throwException('Invalid cleaning mode');
  407. }
  408. self::_validateTagsArray($tags);
  409. return $this->_backend->clean($mode, $tags);
  410. }
  411. /**
  412. * Return an array of stored cache ids which match given tags
  413. *
  414. * In case of multiple tags, a logical AND is made between tags
  415. *
  416. * @param array $tags array of tags
  417. * @return array array of matching cache ids (string)
  418. */
  419. public function getIdsMatchingTags($tags = array())
  420. {
  421. if (!$this->_extendedBackend) {
  422. Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
  423. }
  424. if (!($this->_backendCapabilities['tags'])) {
  425. Zend_Cache::throwException('tags are not supported by the current backend');
  426. }
  427. return $this->_backend->getIdsMatchingTags($tags);
  428. }
  429. /**
  430. * Return an array of stored cache ids which don't match given tags
  431. *
  432. * In case of multiple tags, a logical OR is made between tags
  433. *
  434. * @param array $tags array of tags
  435. * @return array array of not matching cache ids (string)
  436. */
  437. public function getIdsNotMatchingTags($tags = array())
  438. {
  439. if (!$this->_extendedBackend) {
  440. Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
  441. }
  442. if (!($this->_backendCapabilities['tags'])) {
  443. Zend_Cache::throwException('tags are not supported by the current backend');
  444. }
  445. return $this->_backend->getIdsNotMatchingTags($tags);
  446. }
  447. /**
  448. * Return an array of stored cache ids
  449. *
  450. * @return array array of stored cache ids (string)
  451. */
  452. public function getIds()
  453. {
  454. if (!$this->_extendedBackend) {
  455. Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
  456. }
  457. $array = $this->_backend->getIds();
  458. if ((!isset($this->_options['cache_id_prefix'])) || ($this->_options['cache_id_prefix'] == '')) return $array;
  459. // we need to remove cache_id_prefix from ids (see #ZF-6178)
  460. $res = array();
  461. while (list(,$id) = each($array)) {
  462. if (strpos($id, $this->_options['cache_id_prefix']) === 0) {
  463. $res[] = preg_replace("~^{$this->_options['cache_id_prefix']}~", '', $id);
  464. } else {
  465. $res[] = $id;
  466. }
  467. }
  468. return $res;
  469. }
  470. /**
  471. * Return an array of stored tags
  472. *
  473. * @return array array of stored tags (string)
  474. */
  475. public function getTags()
  476. {
  477. if (!$this->_extendedBackend) {
  478. Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
  479. }
  480. if (!($this->_backendCapabilities['tags'])) {
  481. Zend_Cache::throwException('tags are not supported by the current backend');
  482. }
  483. return $this->_backend->getTags();
  484. }
  485. /**
  486. * Return the filling percentage of the backend storage
  487. *
  488. * @return int integer between 0 and 100
  489. */
  490. public function getFillingPercentage()
  491. {
  492. if (!$this->_extendedBackend) {
  493. Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
  494. }
  495. return $this->_backend->getFillingPercentage();
  496. }
  497. /**
  498. * Return an array of metadatas for the given cache id
  499. *
  500. * The array will include these keys :
  501. * - expire : the expire timestamp
  502. * - tags : a string array of tags
  503. * - mtime : timestamp of last modification time
  504. *
  505. * @param string $id cache id
  506. * @return array array of metadatas (false if the cache id is not found)
  507. */
  508. public function getMetadatas($id)
  509. {
  510. if (!$this->_extendedBackend) {
  511. Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
  512. }
  513. $id = $this->_id($id); // cache id may need prefix
  514. return $this->_backend->getMetadatas($id);
  515. }
  516. /**
  517. * Give (if possible) an extra lifetime to the given cache id
  518. *
  519. * @param string $id cache id
  520. * @param int $extraLifetime
  521. * @return boolean true if ok
  522. */
  523. public function touch($id, $extraLifetime)
  524. {
  525. if (!$this->_extendedBackend) {
  526. Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
  527. }
  528. $id = $this->_id($id); // cache id may need prefix
  529. return $this->_backend->touch($id, $extraLifetime);
  530. }
  531. /**
  532. * Validate a cache id or a tag (security, reliable filenames, reserved prefixes...)
  533. *
  534. * Throw an exception if a problem is found
  535. *
  536. * @param string $string Cache id or tag
  537. * @throws Zend_Cache_Exception
  538. * @return void
  539. */
  540. protected static function _validateIdOrTag($string)
  541. {
  542. if (!is_string($string)) {
  543. Zend_Cache::throwException('Invalid id or tag : must be a string');
  544. }
  545. if (substr($string, 0, 9) == 'internal-') {
  546. Zend_Cache::throwException('"internal-*" ids or tags are reserved');
  547. }
  548. if (!preg_match('~^[\w]+$~D', $string)) {
  549. Zend_Cache::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]");
  550. }
  551. }
  552. /**
  553. * Validate a tags array (security, reliable filenames, reserved prefixes...)
  554. *
  555. * Throw an exception if a problem is found
  556. *
  557. * @param array $tags Array of tags
  558. * @throws Zend_Cache_Exception
  559. * @return void
  560. */
  561. protected static function _validateTagsArray($tags)
  562. {
  563. if (!is_array($tags)) {
  564. Zend_Cache::throwException('Invalid tags array : must be an array');
  565. }
  566. foreach($tags as $tag) {
  567. self::_validateIdOrTag($tag);
  568. }
  569. reset($tags);
  570. }
  571. /**
  572. * Make sure if we enable logging that the Zend_Log class
  573. * is available.
  574. * Create a default log object if none is set.
  575. *
  576. * @throws Zend_Cache_Exception
  577. * @return void
  578. */
  579. protected function _loggerSanity()
  580. {
  581. if (!isset($this->_options['logging']) || !$this->_options['logging']) {
  582. return;
  583. }
  584. if (isset($this->_options['logger']) && $this->_options['logger'] instanceof Zend_Log) {
  585. return;
  586. }
  587. // Create a default logger to the standard output stream
  588. require_once 'Zend/Log/Writer/Stream.php';
  589. $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
  590. $this->_options['logger'] = $logger;
  591. }
  592. /**
  593. * Log a message at the WARN (4) priority.
  594. *
  595. * @param string $message
  596. * @throws Zend_Cache_Exception
  597. * @return void
  598. */
  599. protected function _log($message, $priority = 4)
  600. {
  601. if (!$this->_options['logging']) {
  602. return;
  603. }
  604. if (!(isset($this->_options['logger']) || $this->_options['logger'] instanceof Zend_Log)) {
  605. Zend_Cache::throwException('Logging is enabled but logger is not set');
  606. }
  607. $logger = $this->_options['logger'];
  608. $logger->log($message, $priority);
  609. }
  610. /**
  611. * Make and return a cache id
  612. *
  613. * Checks 'cache_id_prefix' and returns new id with prefix or simply the id if null
  614. *
  615. * @param string $id Cache id
  616. * @return string Cache id (with or without prefix)
  617. */
  618. protected function _id($id)
  619. {
  620. if (($id !== null) && isset($this->_options['cache_id_prefix'])) {
  621. return $this->_options['cache_id_prefix'] . $id; // return with prefix
  622. }
  623. return $id; // no prefix, just return the $id passed
  624. }
  625. }