PageRenderTime 50ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Zend/Cache/Backend/Static.php

https://bitbucket.org/andrewjleavitt/magestudy
PHP | 559 lines | 445 code | 21 blank | 93 comment | 42 complexity | d02e3e3f87ecc4a475a7c188dffa0ce4 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.1, GPL-2.0, WTFPL
  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: Static.php 22950 2010-09-16 19:33:00Z mabe $
  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 ($this->_tagged === null && $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 ($id === null || 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 ($id === null || 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 ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
  223. $this->_tagged = $tagged;
  224. } elseif ($this->_tagged === null) {
  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. if (!is_dir($path)) {
  244. $oldUmask = umask(0);
  245. if ( !@mkdir($path, $this->_octdec($this->_options['cache_directory_umask']), true)) {
  246. $lastErr = error_get_last();
  247. umask($oldUmask);
  248. Zend_Cache::throwException("Can't create directory: {$lastErr['message']}");
  249. }
  250. umask($oldUmask);
  251. }
  252. }
  253. /**
  254. * Detect serialization of data (cannot predict since this is the only way
  255. * to obey the interface yet pass in another parameter).
  256. *
  257. * In future, ZF 2.0, check if we can just avoid the interface restraints.
  258. *
  259. * This format is the only valid one possible for the class, so it's simple
  260. * to just run a regular expression for the starting serialized format.
  261. */
  262. protected function _isSerialized($data)
  263. {
  264. return preg_match("/a:2:\{i:0;s:\d+:\"/", $data);
  265. }
  266. /**
  267. * Remove a cache record
  268. *
  269. * @param string $id Cache id
  270. * @return boolean True if no problem
  271. */
  272. public function remove($id)
  273. {
  274. if (!$this->_verifyPath($id)) {
  275. Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
  276. }
  277. $fileName = basename($id);
  278. if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
  279. $this->_tagged = $tagged;
  280. } elseif (!$this->_tagged) {
  281. return false;
  282. }
  283. if (isset($this->_tagged[$id])) {
  284. $extension = $this->_tagged[$id]['extension'];
  285. } else {
  286. $extension = $this->_options['file_extension'];
  287. }
  288. if (empty($fileName)) {
  289. $fileName = $this->_options['index_filename'];
  290. }
  291. $pathName = $this->_options['public_dir'] . dirname($id);
  292. $file = realpath($pathName) . '/' . $fileName . $extension;
  293. if (!file_exists($file)) {
  294. return false;
  295. }
  296. return unlink($file);
  297. }
  298. /**
  299. * Remove a cache record recursively for the given directory matching a
  300. * REQUEST_URI based relative path (deletes the actual file matching this
  301. * in addition to the matching directory)
  302. *
  303. * @param string $id Cache id
  304. * @return boolean True if no problem
  305. */
  306. public function removeRecursively($id)
  307. {
  308. if (!$this->_verifyPath($id)) {
  309. Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
  310. }
  311. $fileName = basename($id);
  312. if (empty($fileName)) {
  313. $fileName = $this->_options['index_filename'];
  314. }
  315. $pathName = $this->_options['public_dir'] . dirname($id);
  316. $file = $pathName . '/' . $fileName . $this->_options['file_extension'];
  317. $directory = $pathName . '/' . $fileName;
  318. if (file_exists($directory)) {
  319. if (!is_writable($directory)) {
  320. return false;
  321. }
  322. foreach (new DirectoryIterator($directory) as $file) {
  323. if (true === $file->isFile()) {
  324. if (false === unlink($file->getPathName())) {
  325. return false;
  326. }
  327. }
  328. }
  329. rmdir(dirname($path));
  330. }
  331. if (file_exists($file)) {
  332. if (!is_writable($file)) {
  333. return false;
  334. }
  335. return unlink($file);
  336. }
  337. return true;
  338. }
  339. /**
  340. * Clean some cache records
  341. *
  342. * Available modes are :
  343. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  344. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  345. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  346. * ($tags can be an array of strings or a single string)
  347. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  348. * ($tags can be an array of strings or a single string)
  349. * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
  350. * ($tags can be an array of strings or a single string)
  351. *
  352. * @param string $mode Clean mode
  353. * @param array $tags Array of tags
  354. * @return boolean true if no problem
  355. */
  356. public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  357. {
  358. $result = false;
  359. switch ($mode) {
  360. case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
  361. case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
  362. if (empty($tags)) {
  363. throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
  364. }
  365. if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
  366. $this->_tagged = $tagged;
  367. } elseif (!$this->_tagged) {
  368. return true;
  369. }
  370. foreach ($tags as $tag) {
  371. $urls = array_keys($this->_tagged);
  372. foreach ($urls as $url) {
  373. if (isset($this->_tagged[$url]['tags']) && in_array($tag, $this->_tagged[$url]['tags'])) {
  374. $this->remove($url);
  375. unset($this->_tagged[$url]);
  376. }
  377. }
  378. }
  379. $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
  380. $result = true;
  381. break;
  382. case Zend_Cache::CLEANING_MODE_ALL:
  383. if ($this->_tagged === null) {
  384. $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
  385. $this->_tagged = $tagged;
  386. }
  387. if ($this->_tagged === null || empty($this->_tagged)) {
  388. return true;
  389. }
  390. $urls = array_keys($this->_tagged);
  391. foreach ($urls as $url) {
  392. $this->remove($url);
  393. unset($this->_tagged[$url]);
  394. }
  395. $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
  396. $result = true;
  397. break;
  398. case Zend_Cache::CLEANING_MODE_OLD:
  399. $this->_log("Zend_Cache_Backend_Static : Selected Cleaning Mode Currently Unsupported By This Backend");
  400. break;
  401. case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
  402. if (empty($tags)) {
  403. throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
  404. }
  405. if ($this->_tagged === null) {
  406. $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
  407. $this->_tagged = $tagged;
  408. }
  409. if ($this->_tagged === null || empty($this->_tagged)) {
  410. return true;
  411. }
  412. $urls = array_keys($this->_tagged);
  413. foreach ($urls as $url) {
  414. $difference = array_diff($tags, $this->_tagged[$url]['tags']);
  415. if (count($tags) == count($difference)) {
  416. $this->remove($url);
  417. unset($this->_tagged[$url]);
  418. }
  419. }
  420. $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
  421. $result = true;
  422. break;
  423. default:
  424. Zend_Cache::throwException('Invalid mode for clean() method');
  425. break;
  426. }
  427. return $result;
  428. }
  429. /**
  430. * Set an Inner Cache, used here primarily to store Tags associated
  431. * with caches created by this backend. Note: If Tags are lost, the cache
  432. * should be completely cleaned as the mapping of tags to caches will
  433. * have been irrevocably lost.
  434. *
  435. * @param Zend_Cache_Core
  436. * @return void
  437. */
  438. public function setInnerCache(Zend_Cache_Core $cache)
  439. {
  440. $this->_tagCache = $cache;
  441. $this->_options['tag_cache'] = $cache;
  442. }
  443. /**
  444. * Get the Inner Cache if set
  445. *
  446. * @return Zend_Cache_Core
  447. */
  448. public function getInnerCache()
  449. {
  450. if ($this->_tagCache === null) {
  451. Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()');
  452. }
  453. return $this->_tagCache;
  454. }
  455. /**
  456. * Verify path exists and is non-empty
  457. *
  458. * @param string $path
  459. * @return bool
  460. */
  461. protected function _verifyPath($path)
  462. {
  463. $path = realpath($path);
  464. $base = realpath($this->_options['public_dir']);
  465. return strncmp($path, $base, strlen($base)) !== 0;
  466. }
  467. /**
  468. * Determine the page to save from the request
  469. *
  470. * @return string
  471. */
  472. protected function _detectId()
  473. {
  474. return $_SERVER['REQUEST_URI'];
  475. }
  476. /**
  477. * Validate a cache id or a tag (security, reliable filenames, reserved prefixes...)
  478. *
  479. * Throw an exception if a problem is found
  480. *
  481. * @param string $string Cache id or tag
  482. * @throws Zend_Cache_Exception
  483. * @return void
  484. * @deprecated Not usable until perhaps ZF 2.0
  485. */
  486. protected static function _validateIdOrTag($string)
  487. {
  488. if (!is_string($string)) {
  489. Zend_Cache::throwException('Invalid id or tag : must be a string');
  490. }
  491. // Internal only checked in Frontend - not here!
  492. if (substr($string, 0, 9) == 'internal-') {
  493. return;
  494. }
  495. // Validation assumes no query string, fragments or scheme included - only the path
  496. if (!preg_match(
  497. '/^(?:\/(?:(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*\'()\[\]:@&=+$,;])*)?)+$/',
  498. $string
  499. )
  500. ) {
  501. Zend_Cache::throwException("Invalid id or tag '$string' : must be a valid URL path");
  502. }
  503. }
  504. /**
  505. * Detect an octal string and return its octal value for file permission ops
  506. * otherwise return the non-string (assumed octal or decimal int already)
  507. *
  508. * @param $val The potential octal in need of conversion
  509. * @return int
  510. */
  511. protected function _octdec($val)
  512. {
  513. if (is_string($val) && decoct(octdec($val)) == $val) {
  514. return octdec($val);
  515. }
  516. return $val;
  517. }
  518. /**
  519. * Decode a request URI from the provided ID
  520. */
  521. protected function _decodeId($id)
  522. {
  523. return pack('H*', $id);;
  524. }
  525. }