Core.php 23 KB

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