PageRenderTime 89ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/vendor/zend/Zend/Cache/Backend/Static.php

http://zoop.googlecode.com/
PHP | 558 lines | 436 code | 22 blank | 100 comment | 40 complexity | 25bca53df6807f260f72c154d5650011 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1
  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. * @subpackage Zend_Cache_Backend
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: BlackHole.php 17867 2009-08-28 09:42:11Z yoshida@zend.co.jp $
  21. */
  22. /**
  23. * @see Zend_Cache_Backend_Interface
  24. */
  25. require_once 'Zend/Cache/Backend/Interface.php';
  26. /**
  27. * @see Zend_Cache_Backend
  28. */
  29. require_once 'Zend/Cache/Backend.php';
  30. /**
  31. * @package Zend_Cache
  32. * @subpackage Zend_Cache_Backend
  33. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  34. * @license http://framework.zend.com/license/new-bsd New BSD License
  35. */
  36. class Zend_Cache_Backend_Static
  37. extends Zend_Cache_Backend
  38. implements Zend_Cache_Backend_Interface
  39. {
  40. const INNER_CACHE_NAME = 'zend_cache_backend_static_tagcache';
  41. /**
  42. * Static backend options
  43. * @var array
  44. */
  45. protected $_options = array(
  46. 'public_dir' => null,
  47. 'sub_dir' => 'html',
  48. 'file_extension' => '.html',
  49. 'index_filename' => 'index',
  50. 'file_locking' => true,
  51. 'cache_file_umask' => 0600,
  52. 'cache_directory_umask' => 0700,
  53. 'debug_header' => false,
  54. 'tag_cache' => null,
  55. 'disable_caching' => false
  56. );
  57. /**
  58. * Cache for handling tags
  59. * @var Zend_Cache_Core
  60. */
  61. protected $_tagCache = null;
  62. /**
  63. * Tagged items
  64. * @var array
  65. */
  66. protected $_tagged = null;
  67. /**
  68. * Interceptor child method to handle the case where an Inner
  69. * Cache object is being set since it's not supported by the
  70. * standard backend interface
  71. *
  72. * @param string $name
  73. * @param mixed $value
  74. * @return Zend_Cache_Backend_Static
  75. */
  76. public function setOption($name, $value)
  77. {
  78. if ($name == 'tag_cache') {
  79. $this->setInnerCache($value);
  80. } else {
  81. parent::setOption($name, $value);
  82. }
  83. return $this;
  84. }
  85. /**
  86. * Retrieve any option via interception of the parent's statically held
  87. * options including the local option for a tag cache.
  88. *
  89. * @param string $name
  90. * @return mixed
  91. */
  92. public function getOption($name)
  93. {
  94. if ($name == 'tag_cache') {
  95. return $this->getInnerCache();
  96. } else {
  97. if (in_array($name, $this->_options)) {
  98. return $this->_options[$name];
  99. }
  100. if ($name == 'lifetime') {
  101. return parent::getLifetime();
  102. }
  103. return null;
  104. }
  105. }
  106. /**
  107. * Test if a cache is available for the given id and (if yes) return it (false else)
  108. *
  109. * Note : return value is always "string" (unserialization is done by the core not by the backend)
  110. *
  111. * @param string $id Cache id
  112. * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
  113. * @return string|false cached datas
  114. */
  115. public function load($id, $doNotTestCacheValidity = false)
  116. {
  117. if (empty($id)) {
  118. $id = $this->_detectId();
  119. } else {
  120. $id = $this->_decodeId($id);
  121. }
  122. if (!$this->_verifyPath($id)) {
  123. Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
  124. }
  125. if ($doNotTestCacheValidity) {
  126. $this->_log("Zend_Cache_Backend_Static::load() : \$doNotTestCacheValidity=true is unsupported by the Static backend");
  127. }
  128. $fileName = basename($id);
  129. if (empty($fileName)) {
  130. $fileName = $this->_options['index_filename'];
  131. }
  132. $pathName = $this->_options['public_dir'] . dirname($id);
  133. $file = rtrim($pathName, '/') . '/' . $fileName . $this->_options['file_extension'];
  134. if (file_exists($file)) {
  135. $content = file_get_contents($file);
  136. return $content;
  137. }
  138. return false;
  139. }
  140. /**
  141. * Test if a cache is available or not (for the given id)
  142. *
  143. * @param string $id cache id
  144. * @return bool
  145. */
  146. public function test($id)
  147. {
  148. $id = $this->_decodeId($id);
  149. if (!$this->_verifyPath($id)) {
  150. Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
  151. }
  152. $fileName = basename($id);
  153. if (empty($fileName)) {
  154. $fileName = $this->_options['index_filename'];
  155. }
  156. if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
  157. $this->_tagged = $tagged;
  158. } elseif (!$this->_tagged) {
  159. return false;
  160. }
  161. $pathName = $this->_options['public_dir'] . dirname($id);
  162. // Switch extension if needed
  163. if (isset($this->_tagged[$id])) {
  164. $extension = $this->_tagged[$id]['extension'];
  165. } else {
  166. $extension = $this->_options['file_extension'];
  167. }
  168. $file = $pathName . '/' . $fileName . $extension;
  169. if (file_exists($file)) {
  170. return true;
  171. }
  172. return false;
  173. }
  174. /**
  175. * Save some string datas into a cache record
  176. *
  177. * Note : $data is always "string" (serialization is done by the
  178. * core not by the backend)
  179. *
  180. * @param string $data Datas to cache
  181. * @param string $id Cache id
  182. * @param array $tags Array of strings, the cache record will be tagged by each string entry
  183. * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
  184. * @return boolean true if no problem
  185. */
  186. public function save($data, $id, $tags = array(), $specificLifetime = false)
  187. {
  188. if ($this->_options['disable_caching']) {
  189. return true;
  190. }
  191. $extension = null;
  192. if ($this->_isSerialized($data)) {
  193. $data = unserialize($data);
  194. $extension = '.' . ltrim($data[1], '.');
  195. $data = $data[0];
  196. }
  197. clearstatcache();
  198. if (is_null($id) || strlen($id) == 0) {
  199. $id = $this->_detectId();
  200. } else {
  201. $id = $this->_decodeId($id);
  202. }
  203. $fileName = basename($id);
  204. if (empty($fileName)) {
  205. $fileName = $this->_options['index_filename'];
  206. }
  207. $pathName = realpath($this->_options['public_dir']) . dirname($id);
  208. $this->_createDirectoriesFor($pathName);
  209. if (is_null($id) || strlen($id) == 0) {
  210. $dataUnserialized = unserialize($data);
  211. $data = $dataUnserialized['data'];
  212. }
  213. $ext = $this->_options['file_extension'];
  214. if ($extension) $ext = $extension;
  215. $file = rtrim($pathName, '/') . '/' . $fileName . $ext;
  216. if ($this->_options['file_locking']) {
  217. $result = file_put_contents($file, $data, LOCK_EX);
  218. } else {
  219. $result = file_put_contents($file, $data);
  220. }
  221. @chmod($file, $this->_octdec($this->_options['cache_file_umask']));
  222. if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
  223. $this->_tagged = $tagged;
  224. } elseif (is_null($this->_tagged)) {
  225. $this->_tagged = array();
  226. }
  227. if (!isset($this->_tagged[$id])) {
  228. $this->_tagged[$id] = array();
  229. }
  230. if (!isset($this->_tagged[$id]['tags'])) {
  231. $this->_tagged[$id]['tags'] = array();
  232. }
  233. $this->_tagged[$id]['tags'] = array_unique(array_merge($this->_tagged[$id]['tags'], $tags));
  234. $this->_tagged[$id]['extension'] = $ext;
  235. $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
  236. return (bool) $result;
  237. }
  238. /**
  239. * Recursively create the directories needed to write the static file
  240. */
  241. protected function _createDirectoriesFor($path)
  242. {
  243. $parts = explode('/', $path);
  244. $directory = '';
  245. foreach ($parts as $part) {
  246. $directory = rtrim($directory, '/') . '/' . $part;
  247. if (!is_dir($directory)) {
  248. mkdir($directory, $this->_octdec($this->_options['cache_directory_umask']));
  249. }
  250. }
  251. }
  252. /**
  253. * Detect serialization of data (cannot predict since this is the only way
  254. * to obey the interface yet pass in another parameter).
  255. *
  256. * In future, ZF 2.0, check if we can just avoid the interface restraints.
  257. *
  258. * This format is the only valid one possible for the class, so it's simple
  259. * to just run a regular expression for the starting serialized format.
  260. */
  261. protected function _isSerialized($data)
  262. {
  263. return preg_match("/a:2:\{i:0;s:\d+:\"/", $data);
  264. }
  265. /**
  266. * Remove a cache record
  267. *
  268. * @param string $id Cache id
  269. * @return boolean True if no problem
  270. */
  271. public function remove($id)
  272. {
  273. if (!$this->_verifyPath($id)) {
  274. Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
  275. }
  276. $fileName = basename($id);
  277. if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
  278. $this->_tagged = $tagged;
  279. } elseif (!$this->_tagged) {
  280. return false;
  281. }
  282. if (isset($this->_tagged[$id])) {
  283. $extension = $this->_tagged[$id]['extension'];
  284. } else {
  285. $extension = $this->_options['file_extension'];
  286. }
  287. if (empty($fileName)) {
  288. $fileName = $this->_options['index_filename'];
  289. }
  290. $pathName = $this->_options['public_dir'] . dirname($id);
  291. $file = realpath($pathName) . '/' . $fileName . $extension;
  292. if (!file_exists($file)) {
  293. return false;
  294. }
  295. return unlink($file);
  296. }
  297. /**
  298. * Remove a cache record recursively for the given directory matching a
  299. * REQUEST_URI based relative path (deletes the actual file matching this
  300. * in addition to the matching directory)
  301. *
  302. * @param string $id Cache id
  303. * @return boolean True if no problem
  304. */
  305. public function removeRecursively($id)
  306. {
  307. if (!$this->_verifyPath($id)) {
  308. Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
  309. }
  310. $fileName = basename($id);
  311. if (empty($fileName)) {
  312. $fileName = $this->_options['index_filename'];
  313. }
  314. $pathName = $this->_options['public_dir'] . dirname($id);
  315. $file = $pathName . '/' . $fileName . $this->_options['file_extension'];
  316. $directory = $pathName . '/' . $fileName;
  317. if (file_exists($directory)) {
  318. if (!is_writable($directory)) {
  319. return false;
  320. }
  321. foreach (new DirectoryIterator($directory) as $file) {
  322. if (true === $file->isFile()) {
  323. if (false === unlink($file->getPathName())) {
  324. return false;
  325. }
  326. }
  327. }
  328. rmdir(dirname($path));
  329. }
  330. if (file_exists($file)) {
  331. if (!is_writable($file)) {
  332. return false;
  333. }
  334. return unlink($file);
  335. }
  336. return true;
  337. }
  338. /**
  339. * Clean some cache records
  340. *
  341. * Available modes are :
  342. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  343. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  344. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  345. * ($tags can be an array of strings or a single string)
  346. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  347. * ($tags can be an array of strings or a single string)
  348. * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
  349. * ($tags can be an array of strings or a single string)
  350. *
  351. * @param string $mode Clean mode
  352. * @param array $tags Array of tags
  353. * @return boolean true if no problem
  354. */
  355. public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  356. {
  357. $result = false;
  358. switch ($mode) {
  359. case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
  360. case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
  361. if (empty($tags)) {
  362. throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
  363. }
  364. if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
  365. $this->_tagged = $tagged;
  366. } elseif (!$this->_tagged) {
  367. return true;
  368. }
  369. foreach ($tags as $tag) {
  370. $urls = array_keys($this->_tagged);
  371. foreach ($urls as $url) {
  372. if (isset($this->_tagged[$url]['tags']) && in_array($tag, $this->_tagged[$url]['tags'])) {
  373. $this->remove($url);
  374. unset($this->_tagged[$url]);
  375. }
  376. }
  377. }
  378. $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
  379. $result = true;
  380. break;
  381. case Zend_Cache::CLEANING_MODE_ALL:
  382. if (is_null($this->_tagged)) {
  383. $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
  384. $this->_tagged = $tagged;
  385. }
  386. if (is_null($this->_tagged) || empty($this->_tagged)) {
  387. return true;
  388. }
  389. $urls = array_keys($this->_tagged);
  390. foreach ($urls as $url) {
  391. $this->remove($url);
  392. unset($this->_tagged[$url]);
  393. }
  394. $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
  395. $result = true;
  396. break;
  397. case Zend_Cache::CLEANING_MODE_OLD:
  398. $this->_log("Zend_Cache_Backend_Static : Selected Cleaning Mode Currently Unsupported By This Backend");
  399. break;
  400. case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
  401. if (empty($tags)) {
  402. throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
  403. }
  404. if (is_null($this->_tagged)) {
  405. $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
  406. $this->_tagged = $tagged;
  407. }
  408. if (is_null($this->_tagged) || empty($this->_tagged)) {
  409. return true;
  410. }
  411. $urls = array_keys($this->_tagged);
  412. foreach ($urls as $url) {
  413. $difference = array_diff($tags, $this->_tagged[$url]['tags']);
  414. if (count($tags) == count($difference)) {
  415. $this->remove($url);
  416. unset($this->_tagged[$url]);
  417. }
  418. }
  419. $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
  420. $result = true;
  421. break;
  422. default:
  423. Zend_Cache::throwException('Invalid mode for clean() method');
  424. break;
  425. }
  426. return $result;
  427. }
  428. /**
  429. * Set an Inner Cache, used here primarily to store Tags associated
  430. * with caches created by this backend. Note: If Tags are lost, the cache
  431. * should be completely cleaned as the mapping of tags to caches will
  432. * have been irrevocably lost.
  433. *
  434. * @param Zend_Cache_Core
  435. * @return void
  436. */
  437. public function setInnerCache(Zend_Cache_Core $cache)
  438. {
  439. $this->_tagCache = $cache;
  440. $this->_options['tag_cache'] = $cache;
  441. }
  442. /**
  443. * Get the Inner Cache if set
  444. *
  445. * @return Zend_Cache_Core
  446. */
  447. public function getInnerCache()
  448. {
  449. if (is_null($this->_tagCache)) {
  450. Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()');
  451. }
  452. return $this->_tagCache;
  453. }
  454. /**
  455. * Verify path exists and is non-empty
  456. *
  457. * @param string $path
  458. * @return bool
  459. */
  460. protected function _verifyPath($path)
  461. {
  462. $path = realpath($path);
  463. $base = realpath($this->_options['public_dir']);
  464. return strncmp($path, $base, strlen($base)) !== 0;
  465. }
  466. /**
  467. * Determine the page to save from the request
  468. *
  469. * @return string
  470. */
  471. protected function _detectId()
  472. {
  473. return $_SERVER['REQUEST_URI'];
  474. }
  475. /**
  476. * Validate a cache id or a tag (security, reliable filenames, reserved prefixes...)
  477. *
  478. * Throw an exception if a problem is found
  479. *
  480. * @param string $string Cache id or tag
  481. * @throws Zend_Cache_Exception
  482. * @return void
  483. * @deprecated Not usable until perhaps ZF 2.0
  484. */
  485. protected static function _validateIdOrTag($string)
  486. {
  487. if (!is_string($string)) {
  488. Zend_Cache::throwException('Invalid id or tag : must be a string');
  489. }
  490. // Internal only checked in Frontend - not here!
  491. if (substr($string, 0, 9) == 'internal-') {
  492. return;
  493. }
  494. // Validation assumes no query string, fragments or scheme included - only the path
  495. if (!preg_match(
  496. '/^(?:\/(?:(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*\'()\[\]:@&=+$,;])*)?)+$/',
  497. $string
  498. )
  499. ) {
  500. Zend_Cache::throwException("Invalid id or tag '$string' : must be a valid URL path");
  501. }
  502. }
  503. /**
  504. * Detect an octal string and return its octal value for file permission ops
  505. * otherwise return the non-string (assumed octal or decimal int already)
  506. *
  507. * @param $val The potential octal in need of conversion
  508. * @return int
  509. */
  510. protected function _octdec($val)
  511. {
  512. if (decoct(octdec($val)) == $val && is_string($val)) {
  513. return octdec($val);
  514. }
  515. return $val;
  516. }
  517. /**
  518. * Decode a request URI from the provided ID
  519. */
  520. protected function _decodeId($id)
  521. {
  522. return pack('H*', $id);;
  523. }
  524. }