Static.php 19 KB

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