PageRenderTime 27ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/Cache/Lite.php

https://bitbucket.org/dgough/annamaria-daneswood-25102012
PHP | 609 lines | 273 code | 45 blank | 291 comment | 59 complexity | 65e8e90c1ae814595b80a6c5e6d22aa2 MD5 | raw file
Possible License(s): GPL-2.0, 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 3313 2006-04-26 19:43:05Z stingrey $
  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 (@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 (!@unlink($this->_file)) {
  308. $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
  309. return false;
  310. }
  311. return true;
  312. }
  313. /**
  314. * Clean the cache
  315. *
  316. * if no group is specified all cache files will be destroyed
  317. * else only cache files of the specified group will be destroyed
  318. *
  319. * @param string $group name of the cache group
  320. * @return boolean true if no problem
  321. * @access public
  322. */
  323. function clean($group = false)
  324. {
  325. if ($this->_fileNameProtection) {
  326. $motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
  327. } else {
  328. $motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
  329. }
  330. if ($this->_memoryCaching) {
  331. while (list($key, $value) = each($this->_memoryCaching)) {
  332. if (strpos($key, $motif, 0)) {
  333. unset($this->_memoryCaching[$key]);
  334. $this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
  335. }
  336. }
  337. if ($this->_onlyMemoryCaching) {
  338. return true;
  339. }
  340. }
  341. if (!($dh = opendir($this->_cacheDir))) {
  342. $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
  343. return false;
  344. }
  345. while ($file = readdir($dh)) {
  346. if (($file != '.') && ($file != '..')) {
  347. $file = $this->_cacheDir . $file;
  348. if (is_file($file)) {
  349. if (strpos($file, $motif, 0)) {
  350. if (!@unlink($file)) {
  351. $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
  352. return false;
  353. }
  354. }
  355. }
  356. }
  357. }
  358. return true;
  359. }
  360. /**
  361. * Set to debug mode
  362. *
  363. * When an error is found, the script will stop and the message will be displayed
  364. * (in debug mode only).
  365. *
  366. * @access public
  367. */
  368. function setToDebug()
  369. {
  370. $this->_pearErrorMode = CACHE_LITE_ERROR_DIE;
  371. }
  372. /**
  373. * Set a new life time
  374. *
  375. * @param int $newLifeTime new life time (in seconds)
  376. * @access public
  377. */
  378. function setLifeTime($newLifeTime)
  379. {
  380. $this->_lifeTime = $newLifeTime;
  381. $this->_refreshTime = time() - $newLifeTime;
  382. }
  383. /**
  384. *
  385. * @access public
  386. */
  387. function saveMemoryCachingState($id, $group = 'default')
  388. {
  389. if ($this->_caching) {
  390. $array = array(
  391. 'counter' => $this->_memoryCachingCounter,
  392. 'array' => $this->_memoryCachingState
  393. );
  394. $data = serialize($array);
  395. $this->save($data, $id, $group);
  396. }
  397. }
  398. /**
  399. *
  400. * @access public
  401. */
  402. function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
  403. {
  404. if ($this->_caching) {
  405. if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
  406. $array = unserialize($data);
  407. $this->_memoryCachingCounter = $array['counter'];
  408. $this->_memoryCachingArray = $array['array'];
  409. }
  410. }
  411. }
  412. /**
  413. * Return the cache last modification time
  414. *
  415. * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
  416. *
  417. * @return int last modification time
  418. */
  419. function lastModified() {
  420. return filemtime($this->_file);
  421. }
  422. /**
  423. * Trigger a PEAR error
  424. *
  425. * To improve performances, the PEAR.php file is included dynamically.
  426. * The file is so included only when an error is triggered. So, in most
  427. * cases, the file isn't included and perfs are much better.
  428. *
  429. * @param string $msg error message
  430. * @param int $code error code
  431. * @access public
  432. */
  433. function raiseError($msg, $code) {
  434. $path = dirname( __FILE__ ) . DIRECTORY_SEPARATOR .'includes'. DIRECTORY_SEPARATOR .'PEAR'. DIRECTORY_SEPARATOR .'PEAR.php';
  435. if ( file_exists( $path ) ) {
  436. include_once( $path );
  437. PEAR::raiseError($msg, $code, $this->_pearErrorMode);
  438. }
  439. }
  440. // --- Private methods ---
  441. /**
  442. *
  443. * @access private
  444. */
  445. function _memoryCacheAdd($id, $data)
  446. {
  447. $this->_memoryCachingArray[$this->_file] = $data;
  448. if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
  449. list($key, $value) = each($this->_memoryCachingArray);
  450. unset($this->_memoryCachingArray[$key]);
  451. } else {
  452. $this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
  453. }
  454. }
  455. /**
  456. * Make a file name (with path)
  457. *
  458. * @param string $id cache id
  459. * @param string $group name of the group
  460. * @access private
  461. */
  462. function _setFileName($id, $group)
  463. {
  464. if ($this->_fileNameProtection) {
  465. $this->_file = ($this->_cacheDir.'cache_'.md5($group).'_'.md5($id));
  466. } else {
  467. $this->_file = $this->_cacheDir.'cache_'.$group.'_'.$id;
  468. }
  469. }
  470. /**
  471. * Read the cache file and return the content
  472. *
  473. * @return string content of the cache file
  474. * @access private
  475. */
  476. function _read()
  477. {
  478. $fp = @fopen($this->_file, "rb");
  479. if ($this->_fileLocking) @flock($fp, LOCK_SH);
  480. if ($fp) {
  481. clearstatcache(); // because the filesize can be cached by PHP itself...
  482. $length = @filesize($this->_file);
  483. $mqr = get_magic_quotes_runtime();
  484. set_magic_quotes_runtime(0);
  485. if ($this->_readControl) {
  486. $hashControl = @fread($fp, 32);
  487. $length = $length - 32;
  488. }
  489. $data = @fread($fp, $length);
  490. set_magic_quotes_runtime($mqr);
  491. if ($this->_fileLocking) @flock($fp, LOCK_UN);
  492. @fclose($fp);
  493. if ($this->_readControl) {
  494. $hashData = $this->_hash($data, $this->_readControlType);
  495. if ($hashData != $hashControl) {
  496. @touch($this->_file, time() - 2*abs($this->_lifeTime));
  497. return false;
  498. }
  499. }
  500. return $data;
  501. }
  502. $this->raiseError('Cache_Lite : Unable to read cache !', -2);
  503. return false;
  504. }
  505. /**
  506. * Write the given data in the cache file
  507. *
  508. * @param string $data data to put in cache
  509. * @return boolean true if ok
  510. * @access private
  511. */
  512. function _write($data)
  513. {
  514. $fp = @fopen($this->_file, "wb");
  515. if ($fp) {
  516. if ($this->_fileLocking) @flock($fp, LOCK_EX);
  517. if ($this->_readControl) {
  518. @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
  519. }
  520. $len = strlen($data);
  521. @fwrite($fp, $data, $len);
  522. if ($this->_fileLocking) @flock($fp, LOCK_UN);
  523. @fclose($fp);
  524. return true;
  525. }
  526. $this->raiseError('Cache_Lite : Unable to write cache !', -1);
  527. return false;
  528. }
  529. /**
  530. * Write the given data in the cache file and control it just after to avoir corrupted cache entries
  531. *
  532. * @param string $data data to put in cache
  533. * @return boolean true if the test is ok
  534. * @access private
  535. */
  536. function _writeAndControl($data)
  537. {
  538. $this->_write($data);
  539. $dataRead = $this->_read($data);
  540. return ($dataRead==$data);
  541. }
  542. /**
  543. * Make a control key with the string containing datas
  544. *
  545. * @param string $data data
  546. * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
  547. * @return string control key
  548. * @access private
  549. */
  550. function _hash($data, $controlType)
  551. {
  552. switch ($controlType) {
  553. case 'md5':
  554. return md5($data);
  555. case 'crc32':
  556. return sprintf('% 32d', crc32($data));
  557. case 'strlen':
  558. return sprintf('% 32d', strlen($data));
  559. default:
  560. $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
  561. }
  562. }
  563. }
  564. ?>