Static.php 19 KB

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