Static.php 17 KB

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