PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/Lite.php

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