PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/I18N/core/TCache_Lite.php

http://prado3.googlecode.com/
PHP | 628 lines | 287 code | 42 blank | 299 comment | 61 complexity | dc2c0b7d138cac74e9ab64e539630e6f MD5 | raw file
Possible License(s): Apache-2.0, IPL-1.0, LGPL-3.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /**
  3. * TCache_Lite class file.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the BSD License.
  7. *
  8. * Copyright(c) 2004 by Qiang Xue. All rights reserved.
  9. *
  10. * To contact the author write to {@link mailto:qiang.xue@gmail.com Qiang Xue}
  11. * The latest version of PRADO can be obtained from:
  12. * {@link http://prado.sourceforge.net/}
  13. *
  14. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  15. * @version $Revision: 1.3 $ $Date: 2005/10/09 10:24:12 $
  16. * @package System.I18N.core
  17. */
  18. /**
  19. * Fast, light and safe Cache Class
  20. *
  21. * TCache_Lite is a fast, light and safe cache system. It's optimized
  22. * for file containers. It is fast and safe (because it uses file
  23. * locking and/or anti-corruption tests).
  24. *
  25. * There are some examples in the 'docs/examples' file
  26. * Technical choices are described in the 'docs/technical' file
  27. *
  28. * A tutorial is available in english at this url :
  29. * http://www.pearfr.org/index.php/en/article/cache_lite
  30. * (big thanks to Pierre-Alain Joye for the translation)
  31. *
  32. * The same tutorial is also available in french at this url :
  33. * http://www.pearfr.org/index.php/fr/article/cache_lite
  34. *
  35. * Memory Caching is from an original idea of
  36. * Mike BENOIT <ipso@snappymail.ca>
  37. *
  38. * @package System.I18N.core
  39. * @version $Id: TCache_Lite.php 3188 2012-07-12 12:13:23Z ctrlaltca $
  40. * @author Fabien MARTY <fab@php.net>
  41. * @copyright 1997-2005 The PHP Group
  42. * @license http://www.gnu.org/copyleft/lesser.html GNU LGPL
  43. * @link http://pear.php.net/package/Cache_Lite
  44. */
  45. class TCache_Lite
  46. {
  47. // --- Private properties ---
  48. /**
  49. * Directory where to put the cache files
  50. * (make sure to add a trailing slash)
  51. *
  52. * @var string $_cacheDir
  53. */
  54. protected $_cacheDir = '/tmp/';
  55. /**
  56. * Enable / disable caching
  57. *
  58. * (can be very usefull for the debug of cached scripts)
  59. *
  60. * @var boolean $_caching
  61. */
  62. protected $_caching = true;
  63. /**
  64. * Cache lifetime (in seconds)
  65. *
  66. * @var int $_lifeTime
  67. */
  68. protected $_lifeTime = 3600;
  69. /**
  70. * Enable / disable fileLocking
  71. *
  72. * (can avoid cache corruption under bad circumstances)
  73. *
  74. * @var boolean $_fileLocking
  75. */
  76. protected $_fileLocking = true;
  77. /**
  78. * Timestamp of the last valid cache
  79. *
  80. * @var int $_refreshTime
  81. */
  82. protected $_refreshTime;
  83. /**
  84. * File name (with path)
  85. *
  86. * @var string $_file
  87. */
  88. protected $_file;
  89. /**
  90. * Enable / disable write control (the cache is read just after writing
  91. * to detect corrupt entries)
  92. *
  93. * Enable write control will lightly slow the cache writing but not the
  94. * cache reading. Write control can detect some corrupt cache files but
  95. * maybe it's not a perfect control
  96. *
  97. * @var boolean $_writeControl
  98. */
  99. protected $_writeControl = true;
  100. /**
  101. * Enable / disable read control
  102. *
  103. * If enabled, a control key is embeded in cache file and this key is
  104. * compared with the one calculated after the reading.
  105. *
  106. * @var boolean $_writeControl
  107. */
  108. protected $_readControl = true;
  109. /**
  110. * Type of read control (only if read control is enabled)
  111. *
  112. * Available values are :
  113. * 'md5' for a md5 hash control (best but slowest)
  114. * 'crc32' for a crc32 hash control (lightly less safe but faster,
  115. * better choice)
  116. * 'strlen' for a length only test (fastest)
  117. *
  118. * @var boolean $_readControlType
  119. */
  120. protected $_readControlType = 'crc32';
  121. /**
  122. * Current cache id
  123. *
  124. * @var string $_id
  125. */
  126. protected $_id;
  127. /**
  128. * Current cache group
  129. *
  130. * @var string $_group
  131. */
  132. protected $_group;
  133. /**
  134. * Enable / Disable "Memory Caching"
  135. *
  136. * NB : There is no lifetime for memory caching !
  137. *
  138. * @var boolean $_memoryCaching
  139. */
  140. protected $_memoryCaching = false;
  141. /**
  142. * Enable / Disable "Only Memory Caching"
  143. * (be carefull, memory caching is "beta quality")
  144. *
  145. * @var boolean $_onlyMemoryCaching
  146. */
  147. protected $_onlyMemoryCaching = false;
  148. /**
  149. * Memory caching array
  150. *
  151. * @var array $_memoryCachingArray
  152. */
  153. protected $_memoryCachingArray = array();
  154. /**
  155. * Memory caching counter
  156. *
  157. * @var int $memoryCachingCounter
  158. */
  159. protected $_memoryCachingCounter = 0;
  160. /**
  161. * Memory caching limit
  162. *
  163. * @var int $memoryCachingLimit
  164. */
  165. protected $_memoryCachingLimit = 1000;
  166. /**
  167. * File Name protection
  168. *
  169. * if set to true, you can use any cache id or group name
  170. * if set to false, it can be faster but cache ids and group names
  171. * will be used directly in cache file names so be carefull with
  172. * special characters...
  173. *
  174. * @var boolean $fileNameProtection
  175. */
  176. protected $_fileNameProtection = true;
  177. /**
  178. * Enable / disable automatic serialization
  179. *
  180. * it can be used to save directly datas which aren't strings
  181. * (but it's slower)
  182. *
  183. * @var boolean $_serialize
  184. */
  185. protected $_automaticSerialization = false;
  186. // --- Public methods ---
  187. /**
  188. * Constructor
  189. *
  190. * $options is an assoc. Available options are :
  191. * $options = array(
  192. * 'cacheDir' => directory where to put the cache files (string),
  193. * 'caching' => enable / disable caching (boolean),
  194. * 'lifeTime' => cache lifetime in seconds (int),
  195. * 'fileLocking' => enable / disable fileLocking (boolean),
  196. * 'writeControl' => enable / disable write control (boolean),
  197. * 'readControl' => enable / disable read control (boolean),
  198. * 'readControlType' => type of read control 'crc32', 'md5', 'strlen',
  199. * 'memoryCaching' => enable / disable memory caching (boolean),
  200. * 'onlyMemoryCaching' => enable / disable only memory caching (boolean),
  201. * 'memoryCachingLimit' => max nbr of records in memory caching (int),
  202. * 'fileNameProtection' => enable / disable file name protection (boolean),
  203. * 'automaticSerialization' => enable / disable serialization (boolean)
  204. * );
  205. *
  206. * @param array $options options
  207. * @access public
  208. */
  209. function TCache_Lite($options = array(null))
  210. {
  211. $availableOptions = array( 'automaticSerialization',
  212. 'fileNameProtection',
  213. 'memoryCaching',
  214. 'onlyMemoryCaching',
  215. 'memoryCachingLimit',
  216. 'cacheDir',
  217. 'caching',
  218. 'lifeTime',
  219. 'fileLocking',
  220. 'writeControl',
  221. 'readControl',
  222. 'readControlType');
  223. foreach($options as $key => $value) {
  224. if(in_array($key, $availableOptions)) {
  225. $property = '_'.$key;
  226. $this->$property = $value;
  227. }
  228. }
  229. $this->_refreshTime = time() - $this->_lifeTime;
  230. }
  231. /**
  232. * Test if a cache is available and (if yes) return it
  233. *
  234. * @param string $id cache id
  235. * @param string $group name of the cache group
  236. * @param boolean $doNotTestCacheValidity if set to true, the cache
  237. * validity won't be tested
  238. * @return string data of the cache (or false if no cache available)
  239. * @access public
  240. */
  241. function get($id, $group = 'default', $doNotTestCacheValidity = false)
  242. {
  243. $this->_id = $id;
  244. $this->_group = $group;
  245. $data = false;
  246. if ($this->_caching) {
  247. $this->_setFileName($id, $group);
  248. if ($this->_memoryCaching) {
  249. if (isset($this->_memoryCachingArray[$this->_file])) {
  250. if ($this->_automaticSerialization) {
  251. return unserialize(
  252. $this->_memoryCachingArray[$this->_file]);
  253. } else {
  254. return $this->_memoryCachingArray[$this->_file];
  255. }
  256. } else {
  257. if ($this->_onlyMemoryCaching) {
  258. return false;
  259. }
  260. }
  261. }
  262. if ($doNotTestCacheValidity) {
  263. if (file_exists($this->_file)) {
  264. $data = $this->_read();
  265. }
  266. } else {
  267. if (@filemtime($this->_file) > $this->_refreshTime) {
  268. $data = $this->_read();
  269. }
  270. }
  271. if (($data) and ($this->_memoryCaching)) {
  272. $this->_memoryCacheAdd($this->_file, $data);
  273. }
  274. if ($this->_automaticSerialization && is_string($data)) {
  275. $data = unserialize($data);
  276. }
  277. return $data;
  278. }
  279. return false;
  280. }
  281. /**
  282. * Save some data in a cache file
  283. *
  284. * @param string $data data to put in cache (can be another type than strings
  285. * if automaticSerialization is on)
  286. * @param string $id cache id
  287. * @param string $group name of the cache group
  288. * @return boolean true if no problem
  289. * @access public
  290. */
  291. function save($data, $id = null, $group = 'default')
  292. {
  293. if ($this->_caching) {
  294. if ($this->_automaticSerialization) {
  295. $data = serialize($data);
  296. }
  297. if (isset($id)) {
  298. $this->_setFileName($id, $group);
  299. }
  300. if ($this->_memoryCaching) {
  301. $this->_memoryCacheAdd($this->_file, $data);
  302. if ($this->_onlyMemoryCaching) {
  303. return true;
  304. }
  305. }
  306. if ($this->_writeControl) {
  307. if (!$this->_writeAndControl($data)) {
  308. @touch($this->_file, time() - 2*abs($this->_lifeTime));
  309. return false;
  310. } else {
  311. return true;
  312. }
  313. } else {
  314. return $this->_write($data);
  315. }
  316. }
  317. return false;
  318. }
  319. /**
  320. * Remove a cache file
  321. *
  322. * @param string $id cache id
  323. * @param string $group name of the cache group
  324. * @return boolean true if no problem
  325. * @access public
  326. */
  327. function remove($id, $group = 'default')
  328. {
  329. $this->_setFileName($id, $group);
  330. if (!@unlink($this->_file)) {
  331. $this->raiseError('TCache_Lite : Unable to remove cache !', -3);
  332. return false;
  333. }
  334. return true;
  335. }
  336. /**
  337. * Clean the cache
  338. *
  339. * if no group is specified all cache files will be destroyed
  340. * else only cache files of the specified group will be destroyed
  341. *
  342. * @param string $group name of the cache group
  343. * @return boolean true if no problem
  344. * @access public
  345. */
  346. function clean($group = false)
  347. {
  348. if ($this->_fileNameProtection) {
  349. $motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
  350. } else {
  351. $motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
  352. }
  353. if ($this->_memoryCaching) {
  354. while (list($key, $value) = each($this->_memoryCaching)) {
  355. if (strpos($key, $motif, 0)) {
  356. unset($this->_memoryCaching[$key]);
  357. $this->_memoryCachingCounter =
  358. $this->_memoryCachingCounter - 1;
  359. }
  360. }
  361. if ($this->_onlyMemoryCaching) {
  362. return true;
  363. }
  364. }
  365. if (!($dh = opendir($this->_cacheDir))) {
  366. $this->raiseError('TCache_Lite : Unable to open cache directory !');
  367. return false;
  368. }
  369. while ($file = readdir($dh)) {
  370. if (($file != '.') && ($file != '..')) {
  371. $file = $this->_cacheDir . $file;
  372. if (is_file($file)) {
  373. if (strpos($file, $motif, 0)) {
  374. if (!@unlink($file)) {
  375. $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
  376. return false;
  377. }
  378. }
  379. }
  380. }
  381. }
  382. return true;
  383. }
  384. /**
  385. * Set a new life time
  386. *
  387. * @param int $newLifeTime new life time (in seconds)
  388. * @access public
  389. */
  390. function setLifeTime($newLifeTime)
  391. {
  392. $this->_lifeTime = $newLifeTime;
  393. $this->_refreshTime = time() - $newLifeTime;
  394. }
  395. /**
  396. *
  397. * @access public
  398. */
  399. function saveMemoryCachingState($id, $group = 'default')
  400. {
  401. if ($this->_caching) {
  402. $array = array(
  403. 'counter' => $this->_memoryCachingCounter,
  404. 'array' => $this->_memoryCachingState
  405. );
  406. $data = serialize($array);
  407. $this->save($data, $id, $group);
  408. }
  409. }
  410. /**
  411. *
  412. * @access public
  413. */
  414. function getMemoryCachingState($id, $group = 'default',
  415. $doNotTestCacheValidity = false)
  416. {
  417. if ($this->_caching) {
  418. if ($data = $this->get($id, $group, $doNotTestCacheValidity))
  419. {
  420. $array = unserialize($data);
  421. $this->_memoryCachingCounter = $array['counter'];
  422. $this->_memoryCachingArray = $array['array'];
  423. }
  424. }
  425. }
  426. /**
  427. * Return the cache last modification time
  428. *
  429. * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
  430. *
  431. * @return int last modification time
  432. */
  433. function lastModified() {
  434. return filemtime($this->cache->_file);
  435. }
  436. /**
  437. * Trigger a PEAR error
  438. *
  439. * To improve performances, the PEAR.php file is included dynamically.
  440. * The file is so included only when an error is triggered. So, in most
  441. * cases, the file isn't included and perfs are much better.
  442. *
  443. * @param string $msg error message
  444. * @param int $code error code
  445. * @access public
  446. */
  447. function raiseError($msg, $code)
  448. {
  449. throw new Exception($msg);
  450. }
  451. // --- Private methods ---
  452. /**
  453. *
  454. * @access private
  455. */
  456. function _memoryCacheAdd($id, $data)
  457. {
  458. $this->_memoryCachingArray[$this->_file] = $data;
  459. if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
  460. list($key, $value) = each($this->_memoryCachingArray);
  461. unset($this->_memoryCachingArray[$key]);
  462. } else {
  463. $this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
  464. }
  465. }
  466. /**
  467. * Make a file name (with path)
  468. *
  469. * @param string $id cache id
  470. * @param string $group name of the group
  471. * @access private
  472. */
  473. function _setFileName($id, $group)
  474. {
  475. if ($this->_fileNameProtection) {
  476. $this->_file = ($this->_cacheDir.'cache_'.md5($group).'_'
  477. .md5($id));
  478. } else {
  479. $this->_file = $this->_cacheDir.'cache_'.$group.'_'.$id;
  480. }
  481. }
  482. function getCacheFile()
  483. {
  484. return $this->_file;
  485. }
  486. /**
  487. * Read the cache file and return the content
  488. *
  489. * @return string content of the cache file
  490. * @access private
  491. */
  492. function _read()
  493. {
  494. $fp = @fopen($this->_file, "rb");
  495. if ($this->_fileLocking) @flock($fp, LOCK_SH);
  496. if ($fp) {
  497. // because the filesize can be cached by PHP itself...
  498. clearstatcache();
  499. $length = @filesize($this->_file);
  500. if(version_compare(PHP_VERSION, '5.3.0', 'lt'))
  501. {
  502. $mqr = get_magic_quotes_runtime();
  503. set_magic_quotes_runtime(0);
  504. }
  505. if ($this->_readControl) {
  506. $hashControl = @fread($fp, 32);
  507. $length = $length - 32;
  508. }
  509. $data = @fread($fp, $length);
  510. if(isset($mqr))
  511. set_magic_quotes_runtime($mqr);
  512. if ($this->_fileLocking) @flock($fp, LOCK_UN);
  513. @fclose($fp);
  514. if ($this->_readControl) {
  515. $hashData = $this->_hash($data, $this->_readControlType);
  516. if ($hashData != $hashControl) {
  517. @touch($this->_file, time() - 2*abs($this->_lifeTime));
  518. return false;
  519. }
  520. }
  521. return $data;
  522. }
  523. $this->raiseError('Cache_Lite : Unable to read cache !', -2);
  524. return false;
  525. }
  526. /**
  527. * Write the given data in the cache file
  528. *
  529. * @param string $data data to put in cache
  530. * @return boolean true if ok
  531. * @access private
  532. */
  533. function _write($data)
  534. {
  535. $fp = @fopen($this->_file, "wb");
  536. if ($fp) {
  537. if ($this->_fileLocking) @flock($fp, LOCK_EX);
  538. if ($this->_readControl) {
  539. @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
  540. }
  541. $len = strlen($data);
  542. @fwrite($fp, $data, $len);
  543. if ($this->_fileLocking) @flock($fp, LOCK_UN);
  544. @fclose($fp);
  545. return true;
  546. }
  547. $this->raiseError('Cache_Lite : Unable to write cache !', -1);
  548. return false;
  549. }
  550. /**
  551. * Write the given data in the cache file and control it just after to avoid
  552. * corrupted cache entries
  553. *
  554. * @param string $data data to put in cache
  555. * @return boolean true if the test is ok
  556. * @access private
  557. */
  558. function _writeAndControl($data)
  559. {
  560. $this->_write($data);
  561. $dataRead = $this->_read($data);
  562. return ($dataRead==$data);
  563. }
  564. /**
  565. * Make a control key with the string containing datas
  566. *
  567. * @param string $data data
  568. * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
  569. * @return string control key
  570. * @access private
  571. */
  572. function _hash($data, $controlType)
  573. {
  574. switch ($controlType) {
  575. case 'md5':
  576. return md5($data);
  577. case 'crc32':
  578. return sprintf('% 32d', crc32($data));
  579. case 'strlen':
  580. return sprintf('% 32d', strlen($data));
  581. default:
  582. $this->raiseError('Unknown controlType ! '.
  583. '(available values are only \'md5\', \'crc32\', \'strlen\')', -5);
  584. }
  585. }
  586. }