PageRenderTime 47ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/concreteOLD/libraries/3rdparty/Zend/Cache/Backend/Static.php

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