PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/php/Cache/Lite.php

https://bitbucket.org/adarshj/convenient_website
PHP | 755 lines | 351 code | 51 blank | 353 comment | 79 complexity | 0598acf1e337c8581ad0184054f3a6be MD5 | raw file
Possible License(s): Apache-2.0, MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-2-Clause, GPL-2.0, LGPL-3.0
  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. * Memory Caching is from an original idea of
  13. * Mike BENOIT <ipso@snappymail.ca>
  14. *
  15. * Nota : A chinese documentation (thanks to RainX <china_1982@163.com>) is
  16. * available at :
  17. * http://rainx.phpmore.com/manual/cache_lite.html
  18. *
  19. * @package Cache_Lite
  20. * @category Caching
  21. * @version $Id: Lite.php,v 1.30 2005/06/13 20:50:48 fab Exp $
  22. * @author Fabien MARTY <fab@php.net>
  23. */
  24. define('CACHE_LITE_ERROR_RETURN', 1);
  25. define('CACHE_LITE_ERROR_DIE', 8);
  26. class Cache_Lite
  27. {
  28. // --- Private properties ---
  29. /**
  30. * Directory where to put the cache files
  31. * (make sure to add a trailing slash)
  32. *
  33. * @var string $_cacheDir
  34. */
  35. var $_cacheDir = '/tmp/';
  36. /**
  37. * Enable / disable caching
  38. *
  39. * (can be very usefull for the debug of cached scripts)
  40. *
  41. * @var boolean $_caching
  42. */
  43. var $_caching = true;
  44. /**
  45. * Cache lifetime (in seconds)
  46. *
  47. * @var int $_lifeTime
  48. */
  49. var $_lifeTime = 3600;
  50. /**
  51. * Enable / disable fileLocking
  52. *
  53. * (can avoid cache corruption under bad circumstances)
  54. *
  55. * @var boolean $_fileLocking
  56. */
  57. var $_fileLocking = true;
  58. /**
  59. * Timestamp of the last valid cache
  60. *
  61. * @var int $_refreshTime
  62. */
  63. var $_refreshTime;
  64. /**
  65. * File name (with path)
  66. *
  67. * @var string $_file
  68. */
  69. var $_file;
  70. /**
  71. * File name (without path)
  72. *
  73. * @var string $_fileName
  74. */
  75. var $_fileName;
  76. /**
  77. * Enable / disable write control (the cache is read just after writing to detect corrupt entries)
  78. *
  79. * Enable write control will lightly slow the cache writing but not the cache reading
  80. * Write control can detect some corrupt cache files but maybe it's not a perfect control
  81. *
  82. * @var boolean $_writeControl
  83. */
  84. var $_writeControl = true;
  85. /**
  86. * Enable / disable read control
  87. *
  88. * If enabled, a control key is embeded in cache file and this key is compared with the one
  89. * calculated after the reading.
  90. *
  91. * @var boolean $_writeControl
  92. */
  93. var $_readControl = true;
  94. /**
  95. * Type of read control (only if read control is enabled)
  96. *
  97. * Available values are :
  98. * 'md5' for a md5 hash control (best but slowest)
  99. * 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
  100. * 'strlen' for a length only test (fastest)
  101. *
  102. * @var boolean $_readControlType
  103. */
  104. var $_readControlType = 'crc32';
  105. /**
  106. * Pear error mode (when raiseError is called)
  107. *
  108. * (see PEAR doc)
  109. *
  110. * @see setToDebug()
  111. * @var int $_pearErrorMode
  112. */
  113. var $_pearErrorMode = CACHE_LITE_ERROR_RETURN;
  114. /**
  115. * Current cache id
  116. *
  117. * @var string $_id
  118. */
  119. var $_id;
  120. /**
  121. * Current cache group
  122. *
  123. * @var string $_group
  124. */
  125. var $_group;
  126. /**
  127. * Enable / Disable "Memory Caching"
  128. *
  129. * NB : There is no lifetime for memory caching !
  130. *
  131. * @var boolean $_memoryCaching
  132. */
  133. var $_memoryCaching = false;
  134. /**
  135. * Enable / Disable "Only Memory Caching"
  136. * (be carefull, memory caching is "beta quality")
  137. *
  138. * @var boolean $_onlyMemoryCaching
  139. */
  140. var $_onlyMemoryCaching = false;
  141. /**
  142. * Memory caching array
  143. *
  144. * @var array $_memoryCachingArray
  145. */
  146. var $_memoryCachingArray = array();
  147. /**
  148. * Memory caching counter
  149. *
  150. * @var int $memoryCachingCounter
  151. */
  152. var $_memoryCachingCounter = 0;
  153. /**
  154. * Memory caching limit
  155. *
  156. * @var int $memoryCachingLimit
  157. */
  158. var $_memoryCachingLimit = 1000;
  159. /**
  160. * File Name protection
  161. *
  162. * if set to true, you can use any cache id or group name
  163. * if set to false, it can be faster but cache ids and group names
  164. * will be used directly in cache file names so be carefull with
  165. * special characters...
  166. *
  167. * @var boolean $fileNameProtection
  168. */
  169. var $_fileNameProtection = true;
  170. /**
  171. * Enable / disable automatic serialization
  172. *
  173. * it can be used to save directly datas which aren't strings
  174. * (but it's slower)
  175. *
  176. * @var boolean $_serialize
  177. */
  178. var $_automaticSerialization = false;
  179. /**
  180. * Disable / Tune the automatic cleaning process
  181. *
  182. * The automatic cleaning process destroy too old (for the given life time)
  183. * cache files when a new cache file is written.
  184. * 0 => no automatic cache cleaning
  185. * 1 => systematic cache cleaning
  186. * x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
  187. *
  188. * @var int $_automaticCleaning
  189. */
  190. var $_automaticCleaningFactor = 0;
  191. /**
  192. * Nested directory level
  193. *
  194. * Set the hashed directory structure level. 0 means "no hashed directory
  195. * structure", 1 means "one level of directory", 2 means "two levels"...
  196. * This option can speed up Cache_Lite only when you have many thousands of
  197. * cache file. Only specific benchs can help you to choose the perfect value
  198. * for you. Maybe, 1 or 2 is a good start.
  199. *
  200. * @var int $_hashedDirectoryLevel
  201. */
  202. var $_hashedDirectoryLevel = 0;
  203. /**
  204. * Umask for hashed directory structure
  205. *
  206. * @var int $_hashedDirectoryUmask
  207. */
  208. var $_hashedDirectoryUmask = 0700;
  209. // --- Public methods ---
  210. /**
  211. * Constructor
  212. *
  213. * $options is an assoc. Available options are :
  214. * $options = array(
  215. * 'cacheDir' => directory where to put the cache files (string),
  216. * 'caching' => enable / disable caching (boolean),
  217. * 'lifeTime' => cache lifetime in seconds (int),
  218. * 'fileLocking' => enable / disable fileLocking (boolean),
  219. * 'writeControl' => enable / disable write control (boolean),
  220. * 'readControl' => enable / disable read control (boolean),
  221. * 'readControlType' => type of read control 'crc32', 'md5', 'strlen' (string),
  222. * 'pearErrorMode' => pear error mode (when raiseError is called) (cf PEAR doc) (int),
  223. * 'memoryCaching' => enable / disable memory caching (boolean),
  224. * 'onlyMemoryCaching' => enable / disable only memory caching (boolean),
  225. * 'memoryCachingLimit' => max nbr of records to store into memory caching (int),
  226. * 'fileNameProtection' => enable / disable automatic file name protection (boolean),
  227. * 'automaticSerialization' => enable / disable automatic serialization (boolean)
  228. * 'automaticCleaningFactor' => distable / tune automatic cleaning process (int)
  229. * 'hashedDirectoryLevel' => level of the hashed directory system (int)
  230. * 'hashedDirectoryUmask' => umask for hashed directory structure (int)
  231. * );
  232. *
  233. * @param array $options options
  234. * @access public
  235. */
  236. function Cache_Lite($options = array(NULL))
  237. {
  238. $availableOptions = array('hashedDirectoryUmask', 'hashedDirectoryLevel', 'automaticCleaningFactor', 'automaticSerialization', 'fileNameProtection', 'memoryCaching', 'onlyMemoryCaching', 'memoryCachingLimit', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode');
  239. foreach($options as $key => $value) {
  240. if(in_array($key, $availableOptions)) {
  241. $property = '_'.$key;
  242. $this->$property = $value;
  243. }
  244. }
  245. $this->_refreshTime = time() - $this->_lifeTime;
  246. }
  247. /**
  248. * Test if a cache is available and (if yes) return it
  249. *
  250. * @param string $id cache id
  251. * @param string $group name of the cache group
  252. * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
  253. * @return string data of the cache (or false if no cache available)
  254. * @access public
  255. */
  256. function get($id, $group = 'default', $doNotTestCacheValidity = false)
  257. {
  258. $this->_id = $id;
  259. $this->_group = $group;
  260. $data = false;
  261. if ($this->_caching) {
  262. $this->_setFileName($id, $group);
  263. if ($this->_memoryCaching) {
  264. if (isset($this->_memoryCachingArray[$this->_file])) {
  265. if ($this->_automaticSerialization) {
  266. return unserialize($this->_memoryCachingArray[$this->_file]);
  267. } else {
  268. return $this->_memoryCachingArray[$this->_file];
  269. }
  270. } else {
  271. if ($this->_onlyMemoryCaching) {
  272. return false;
  273. }
  274. }
  275. }
  276. if ($doNotTestCacheValidity) {
  277. if (file_exists($this->_file)) {
  278. $data = $this->_read();
  279. }
  280. } else {
  281. if ((file_exists($this->_file)) && (@filemtime($this->_file) > $this->_refreshTime)) {
  282. $data = $this->_read();
  283. }
  284. }
  285. if (($data) and ($this->_memoryCaching)) {
  286. $this->_memoryCacheAdd($this->_file, $data);
  287. }
  288. if (($this->_automaticSerialization) and (is_string($data))) {
  289. $data = unserialize($data);
  290. }
  291. return $data;
  292. }
  293. return false;
  294. }
  295. /**
  296. * Save some data in a cache file
  297. *
  298. * @param string $data data to put in cache (can be another type than strings if automaticSerialization is on)
  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 save($data, $id = NULL, $group = 'default')
  305. {
  306. if ($this->_caching) {
  307. if ($this->_automaticSerialization) {
  308. $data = serialize($data);
  309. }
  310. if (isset($id)) {
  311. $this->_setFileName($id, $group);
  312. }
  313. if ($this->_memoryCaching) {
  314. $this->_memoryCacheAdd($this->_file, $data);
  315. if ($this->_onlyMemoryCaching) {
  316. return true;
  317. }
  318. }
  319. if ($this->_automaticCleaningFactor>0) {
  320. $rand = rand(1, $this->_automaticCleaningFactor);
  321. if ($rand==1) {
  322. $this->clean(false, 'old');
  323. }
  324. }
  325. if ($this->_writeControl) {
  326. if (!$this->_writeAndControl($data)) {
  327. @touch($this->_file, time() - 2*abs($this->_lifeTime));
  328. return false;
  329. } else {
  330. return true;
  331. }
  332. } else {
  333. return $this->_write($data);
  334. }
  335. }
  336. return false;
  337. }
  338. /**
  339. * Remove a cache file
  340. *
  341. * @param string $id cache id
  342. * @param string $group name of the cache group
  343. * @return boolean true if no problem
  344. * @access public
  345. */
  346. function remove($id, $group = 'default')
  347. {
  348. $this->_setFileName($id, $group);
  349. if ($this->_memoryCaching) {
  350. if (isset($this->_memoryCachingArray[$this->_file])) {
  351. unset($this->_memoryCachingArray[$this->_file]);
  352. $this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
  353. }
  354. if ($this->_onlyMemoryCaching) {
  355. return true;
  356. }
  357. }
  358. return $this->_unlink($this->_file);
  359. }
  360. /**
  361. * Clean the cache
  362. *
  363. * if no group is specified all cache files will be destroyed
  364. * else only cache files of the specified group will be destroyed
  365. *
  366. * @param string $group name of the cache group
  367. * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
  368. * 'callback_myFunction'
  369. * @return boolean true if no problem
  370. * @access public
  371. */
  372. function clean($group = false, $mode = 'ingroup')
  373. {
  374. return $this->_cleanDir($this->_cacheDir, $group, $mode);
  375. }
  376. /**
  377. * Set to debug mode
  378. *
  379. * When an error is found, the script will stop and the message will be displayed
  380. * (in debug mode only).
  381. *
  382. * @access public
  383. */
  384. function setToDebug()
  385. {
  386. $this->_pearErrorMode = CACHE_LITE_ERROR_DIE;
  387. }
  388. /**
  389. * Set a new life time
  390. *
  391. * @param int $newLifeTime new life time (in seconds)
  392. * @access public
  393. */
  394. function setLifeTime($newLifeTime)
  395. {
  396. $this->_lifeTime = $newLifeTime;
  397. $this->_refreshTime = time() - $newLifeTime;
  398. }
  399. /**
  400. * Save the state of the caching memory array into a cache file cache
  401. *
  402. * @param string $id cache id
  403. * @param string $group name of the cache group
  404. * @access public
  405. */
  406. function saveMemoryCachingState($id, $group = 'default')
  407. {
  408. if ($this->_caching) {
  409. $array = array(
  410. 'counter' => $this->_memoryCachingCounter,
  411. 'array' => $this->_memoryCachingState
  412. );
  413. $data = serialize($array);
  414. $this->save($data, $id, $group);
  415. }
  416. }
  417. /**
  418. * Load the state of the caching memory array from a given cache file cache
  419. *
  420. * @param string $id cache id
  421. * @param string $group name of the cache group
  422. * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
  423. * @access public
  424. */
  425. function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
  426. {
  427. if ($this->_caching) {
  428. if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
  429. $array = unserialize($data);
  430. $this->_memoryCachingCounter = $array['counter'];
  431. $this->_memoryCachingArray = $array['array'];
  432. }
  433. }
  434. }
  435. /**
  436. * Return the cache last modification time
  437. *
  438. * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
  439. *
  440. * @return int last modification time
  441. */
  442. function lastModified() {
  443. return @filemtime($this->_file);
  444. }
  445. /**
  446. * Trigger a PEAR error
  447. *
  448. * To improve performances, the PEAR.php file is included dynamically.
  449. * The file is so included only when an error is triggered. So, in most
  450. * cases, the file isn't included and perfs are much better.
  451. *
  452. * @param string $msg error message
  453. * @param int $code error code
  454. * @access public
  455. */
  456. function raiseError($msg, $code)
  457. {
  458. include_once('PEAR.php');
  459. PEAR::raiseError($msg, $code, $this->_pearErrorMode);
  460. }
  461. // --- Private methods ---
  462. /**
  463. * Remove a file
  464. *
  465. * @param string $file complete file path and name
  466. * @return boolean true if no problem
  467. * @access private
  468. */
  469. function _unlink($file)
  470. {
  471. if (!@unlink($file)) {
  472. $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
  473. return false;
  474. } else {
  475. return true;
  476. }
  477. }
  478. /**
  479. * Recursive function for cleaning cache file in the given directory
  480. *
  481. * @param string $dir directory complete path (with a trailing slash)
  482. * @param string $group name of the cache group
  483. * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
  484. 'callback_myFunction'
  485. * @return boolean true if no problem
  486. * @access private
  487. */
  488. function _cleanDir($dir, $group = false, $mode = 'ingroup')
  489. {
  490. if ($this->_fileNameProtection) {
  491. $motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
  492. } else {
  493. $motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
  494. }
  495. if ($this->_memoryCaching) {
  496. while (list($key, $value) = each($this->_memoryCachingArray)) {
  497. if (strpos($key, $motif, 0)) {
  498. unset($this->_memoryCachingArray[$key]);
  499. $this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
  500. }
  501. }
  502. if ($this->_onlyMemoryCaching) {
  503. return true;
  504. }
  505. }
  506. if (!($dh = opendir($dir))) {
  507. $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
  508. return false;
  509. }
  510. $result = true;
  511. while ($file = readdir($dh)) {
  512. if (($file != '.') && ($file != '..')) {
  513. if (substr($file, 0, 6)=='cache_') {
  514. $file2 = $dir . $file;
  515. if (is_file($file2)) {
  516. switch (substr($mode, 0, 9)) {
  517. case 'old':
  518. // files older than lifeTime get deleted from cache
  519. if ((mktime() - filemtime($file2)) > $this->_lifeTime) {
  520. $result = ($result and ($this->_unlink($file2)));
  521. }
  522. break;
  523. case 'notingrou':
  524. if (!strpos($file2, $motif, 0)) {
  525. $result = ($result and ($this->_unlink($file2)));
  526. }
  527. break;
  528. case 'callback_':
  529. $func = substr($mode, 9, strlen($mode) - 9);
  530. if ($func($file2, $group)) {
  531. $result = ($result and ($this->_unlink($file2)));
  532. }
  533. break;
  534. case 'ingroup':
  535. default:
  536. if (strpos($file2, $motif, 0)) {
  537. $result = ($result and ($this->_unlink($file2)));
  538. }
  539. break;
  540. }
  541. }
  542. if ((is_dir($file2)) and ($this->_hashedDirectoryLevel>0)) {
  543. $result = ($result and ($this->_cleanDir($file2 . '/', $group, $mode)));
  544. }
  545. }
  546. }
  547. }
  548. return $result;
  549. }
  550. /**
  551. * Add some date in the memory caching array
  552. *
  553. * @param string $id cache id
  554. * @param string $data data to cache
  555. * @access private
  556. */
  557. function _memoryCacheAdd($id, $data)
  558. {
  559. $this->_memoryCachingArray[$this->_file] = $data;
  560. if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
  561. list($key, $value) = each($this->_memoryCachingArray);
  562. unset($this->_memoryCachingArray[$key]);
  563. } else {
  564. $this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
  565. }
  566. }
  567. /**
  568. * Make a file name (with path)
  569. *
  570. * @param string $id cache id
  571. * @param string $group name of the group
  572. * @access private
  573. */
  574. function _setFileName($id, $group)
  575. {
  576. if ($this->_fileNameProtection) {
  577. $suffix = 'cache_'.md5($group).'_'.md5($id);
  578. } else {
  579. $suffix = 'cache_'.$group.'_'.$id;
  580. }
  581. $root = $this->_cacheDir;
  582. if ($this->_hashedDirectoryLevel>0) {
  583. $hash = md5($suffix);
  584. for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
  585. $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
  586. }
  587. }
  588. $this->_fileName = $suffix;
  589. $this->_file = $root.$suffix;
  590. }
  591. /**
  592. * Read the cache file and return the content
  593. *
  594. * @return string content of the cache file
  595. * @access private
  596. */
  597. function _read()
  598. {
  599. $fp = @fopen($this->_file, "rb");
  600. if ($this->_fileLocking) @flock($fp, LOCK_SH);
  601. if ($fp) {
  602. clearstatcache(); // because the filesize can be cached by PHP itself...
  603. $length = @filesize($this->_file);
  604. $mqr = get_magic_quotes_runtime();
  605. set_magic_quotes_runtime(0);
  606. if ($this->_readControl) {
  607. $hashControl = @fread($fp, 32);
  608. $length = $length - 32;
  609. }
  610. if ($length) {
  611. $data = @fread($fp, $length);
  612. } else {
  613. $data = '';
  614. }
  615. set_magic_quotes_runtime($mqr);
  616. if ($this->_fileLocking) @flock($fp, LOCK_UN);
  617. @fclose($fp);
  618. if ($this->_readControl) {
  619. $hashData = $this->_hash($data, $this->_readControlType);
  620. if ($hashData != $hashControl) {
  621. @touch($this->_file, time() - 2*abs($this->_lifeTime));
  622. return false;
  623. }
  624. }
  625. return $data;
  626. }
  627. $this->raiseError('Cache_Lite : Unable to read cache !', -2);
  628. return false;
  629. }
  630. /**
  631. * Write the given data in the cache file
  632. *
  633. * @param string $data data to put in cache
  634. * @return boolean true if ok
  635. * @access private
  636. */
  637. function _write($data)
  638. {
  639. $try = 1;
  640. while ($try<=2) {
  641. $fp = @fopen($this->_file, "wb");
  642. if ($fp) {
  643. if ($this->_fileLocking) @flock($fp, LOCK_EX);
  644. if ($this->_readControl) {
  645. @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
  646. }
  647. $len = strlen($data);
  648. @fwrite($fp, $data, $len);
  649. if ($this->_fileLocking) @flock($fp, LOCK_UN);
  650. @fclose($fp);
  651. return true;
  652. } else {
  653. if (($try==1) and ($this->_hashedDirectoryLevel>0)) {
  654. $hash = md5($this->_fileName);
  655. $root = $this->_cacheDir;
  656. for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
  657. $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
  658. @mkdir($root, $this->_hashedDirectoryUmask);
  659. }
  660. $try = 2;
  661. } else {
  662. $try = 999;
  663. }
  664. }
  665. }
  666. $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1);
  667. return false;
  668. }
  669. /**
  670. * Write the given data in the cache file and control it just after to avoir corrupted cache entries
  671. *
  672. * @param string $data data to put in cache
  673. * @return boolean true if the test is ok
  674. * @access private
  675. */
  676. function _writeAndControl($data)
  677. {
  678. $this->_write($data);
  679. $dataRead = $this->_read($data);
  680. return ($dataRead==$data);
  681. }
  682. /**
  683. * Make a control key with the string containing datas
  684. *
  685. * @param string $data data
  686. * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
  687. * @return string control key
  688. * @access private
  689. */
  690. function _hash($data, $controlType)
  691. {
  692. switch ($controlType) {
  693. case 'md5':
  694. return md5($data);
  695. case 'crc32':
  696. return sprintf('% 32d', crc32($data));
  697. case 'strlen':
  698. return sprintf('% 32d', strlen($data));
  699. default:
  700. $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
  701. }
  702. }
  703. }
  704. ?>