PageRenderTime 60ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/vendors/phpgacl/Cache_Lite/Lite.php

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