Static.php 19 KB

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