Static.php 19 KB

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