PageRenderTime 63ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/classes/net/php/pear/Cache/Lite.class.php

http://tubepress.googlecode.com/
PHP | 691 lines | 303 code | 48 blank | 340 comment | 68 complexity | aac8f300226e3c1987e3eee8c242eac6 MD5 | raw file
Possible License(s): GPL-3.0, CC-BY-SA-4.0, BSD-3-Clause
  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.50 2008/04/13 14:41:23 tacker 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_exists('net_php_pear_PEAR') || require dirname(__FILE__) . '/../PEAR.class.php';
  27. class net_php_pear_Cache_Lite
  28. {
  29. // --- Private properties ---
  30. /**
  31. * Directory where to put the cache files
  32. * (make sure to add a trailing slash)
  33. *
  34. * @var string $_cacheDir
  35. */
  36. var $_cacheDir = '.tubepress_cache/';
  37. /**
  38. * Enable / disable caching
  39. *
  40. * (can be very usefull for the debug of cached scripts)
  41. *
  42. * @var boolean $_caching
  43. */
  44. var $_caching = true;
  45. /**
  46. * Cache lifetime (in seconds)
  47. *
  48. * If null, the cache is valid forever.
  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. * File Name protection
  131. *
  132. * if set to true, you can use any cache id or group name
  133. * if set to false, it can be faster but cache ids and group names
  134. * will be used directly in cache file names so be carefull with
  135. * special characters...
  136. *
  137. * @var boolean $fileNameProtection
  138. */
  139. var $_fileNameProtection = true;
  140. /**
  141. * Enable / disable automatic serialization
  142. *
  143. * it can be used to save directly datas which aren't strings
  144. * (but it's slower)
  145. *
  146. * @var boolean $_serialize
  147. */
  148. var $_automaticSerialization = false;
  149. /**
  150. * Disable / Tune the automatic cleaning process
  151. *
  152. * The automatic cleaning process destroy too old (for the given life time)
  153. * cache files when a new cache file is written.
  154. * 0 => no automatic cache cleaning
  155. * 1 => systematic cache cleaning
  156. * x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
  157. *
  158. * @var int $_automaticCleaning
  159. */
  160. var $_automaticCleaningFactor = 0;
  161. /**
  162. * Nested directory level
  163. *
  164. * Set the hashed directory structure level. 0 means "no hashed directory
  165. * structure", 1 means "one level of directory", 2 means "two levels"...
  166. * This option can speed up Cache_Lite only when you have many thousands of
  167. * cache file. Only specific benchs can help you to choose the perfect value
  168. * for you. Maybe, 1 or 2 is a good start.
  169. *
  170. * @var int $_hashedDirectoryLevel
  171. */
  172. var $_hashedDirectoryLevel = 0;
  173. /**
  174. * Umask for hashed directory structure
  175. *
  176. * @var int $_hashedDirectoryUmask
  177. */
  178. var $_hashedDirectoryUmask = 0700;
  179. /**
  180. * API break for error handling in CACHE_LITE_ERROR_RETURN mode
  181. *
  182. * In CACHE_LITE_ERROR_RETURN mode, error handling was not good because
  183. * for example save() method always returned a boolean (a PEAR_Error object
  184. * would be better in CACHE_LITE_ERROR_RETURN mode). To correct this without
  185. * breaking the API, this option (false by default) can change this handling.
  186. *
  187. * @var boolean
  188. */
  189. var $_errorHandlingAPIBreak = false;
  190. // --- Public methods ---
  191. /**
  192. * Constructor
  193. *
  194. * $options is an assoc. Available options are :
  195. * $options = array(
  196. * 'cacheDir' => directory where to put the cache files (string),
  197. * 'caching' => enable / disable caching (boolean),
  198. * 'lifeTime' => cache lifetime in seconds (int),
  199. * 'fileLocking' => enable / disable fileLocking (boolean),
  200. * 'writeControl' => enable / disable write control (boolean),
  201. * 'readControl' => enable / disable read control (boolean),
  202. * 'readControlType' => type of read control 'crc32', 'md5', 'strlen' (string),
  203. * 'pearErrorMode' => pear error mode (when raiseError is called) (cf PEAR doc) (int),
  204. * 'fileNameProtection' => enable / disable automatic file name protection (boolean),
  205. * 'automaticSerialization' => enable / disable automatic serialization (boolean),
  206. * 'automaticCleaningFactor' => distable / tune automatic cleaning process (int),
  207. * 'hashedDirectoryLevel' => level of the hashed directory system (int),
  208. * 'hashedDirectoryUmask' => umask for hashed directory structure (int),
  209. * 'errorHandlingAPIBreak' => API break for better error handling ? (boolean)
  210. * );
  211. *
  212. * @param array $options options
  213. * @access public
  214. */
  215. function net_php_pear_Cache_Lite($options = array(NULL))
  216. {
  217. foreach($options as $key => $value) {
  218. $this->setOption($key, $value);
  219. }
  220. }
  221. /**
  222. * Generic way to set a Cache_Lite option
  223. *
  224. * see Cache_Lite constructor for available options
  225. *
  226. * @var string $name name of the option
  227. * @var mixed $value value of the option
  228. * @access public
  229. */
  230. function setOption($name, $value)
  231. {
  232. $availableOptions = array('errorHandlingAPIBreak', 'hashedDirectoryUmask', 'hashedDirectoryLevel', 'automaticCleaningFactor', 'automaticSerialization', 'fileNameProtection', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode');
  233. if (in_array($name, $availableOptions)) {
  234. $property = '_'.$name;
  235. $this->$property = $value;
  236. }
  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 (else : false)
  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->_setRefreshTime();
  254. $this->_setFileName($id, $group);
  255. clearstatcache();
  256. if (($doNotTestCacheValidity) || (is_null($this->_refreshTime))) {
  257. if (file_exists($this->_file)) {
  258. $data = $this->_read();
  259. }
  260. } else {
  261. if ((file_exists($this->_file)) && (@filemtime($this->_file) > $this->_refreshTime)) {
  262. $data = $this->_read();
  263. }
  264. }
  265. if (($this->_automaticSerialization) and (is_string($data))) {
  266. $data = unserialize($data);
  267. }
  268. return $data;
  269. }
  270. return false;
  271. }
  272. /**
  273. * Save some data in a cache file
  274. *
  275. * @param string $data data to put in cache (can be another type than strings if automaticSerialization is on)
  276. * @param string $id cache id
  277. * @param string $group name of the cache group
  278. * @return boolean true if no problem (else : false or a PEAR_Error object)
  279. * @access public
  280. */
  281. function save($data, $id = NULL, $group = 'default')
  282. {
  283. if ($this->_caching) {
  284. if ($this->_automaticSerialization) {
  285. $data = serialize($data);
  286. }
  287. if (isset($id)) {
  288. $this->_setFileName($id, $group);
  289. }
  290. if ($this->_automaticCleaningFactor>0) {
  291. $rand = rand(1, $this->_automaticCleaningFactor);
  292. if ($rand==1) {
  293. $this->clean(false, 'old');
  294. }
  295. }
  296. if ($this->_writeControl) {
  297. $res = $this->_writeAndControl($data);
  298. if (is_bool($res)) {
  299. if ($res) {
  300. return true;
  301. }
  302. // if $res if false, we need to invalidate the cache
  303. @touch($this->_file, time() - 2*abs($this->_lifeTime));
  304. return false;
  305. }
  306. } else {
  307. $res = $this->_write($data);
  308. }
  309. if (is_object($res)) {
  310. // $res is a PEAR_Error object
  311. if (!($this->_errorHandlingAPIBreak)) {
  312. return false; // we return false (old API)
  313. }
  314. }
  315. return $res;
  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. return $this->_unlink($this->_file);
  331. }
  332. /**
  333. * Clean the cache
  334. *
  335. * if no group is specified all cache files will be destroyed
  336. * else only cache files of the specified group will be destroyed
  337. *
  338. * @param string $group name of the cache group
  339. * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
  340. * 'callback_myFunction'
  341. * @return boolean true if no problem
  342. * @access public
  343. */
  344. function clean($group = false, $mode = 'ingroup')
  345. {
  346. return $this->_cleanDir($this->_cacheDir, $group, $mode);
  347. }
  348. /**
  349. * Set to debug mode
  350. *
  351. * When an error is found, the script will stop and the message will be displayed
  352. * (in debug mode only).
  353. *
  354. * @access public
  355. */
  356. function setToDebug()
  357. {
  358. $this->setOption('pearErrorMode', CACHE_LITE_ERROR_DIE);
  359. }
  360. /**
  361. * Set a new life time
  362. *
  363. * @param int $newLifeTime new life time (in seconds)
  364. * @access public
  365. */
  366. function setLifeTime($newLifeTime)
  367. {
  368. $this->_lifeTime = $newLifeTime;
  369. $this->_setRefreshTime();
  370. }
  371. /**
  372. * Return the cache last modification time
  373. *
  374. * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
  375. *
  376. * @return int last modification time
  377. */
  378. function lastModified()
  379. {
  380. return @filemtime($this->_file);
  381. }
  382. /**
  383. * Trigger a PEAR error
  384. *
  385. * To improve performances, the PEAR.php file is included dynamically.
  386. * The file is so included only when an error is triggered. So, in most
  387. * cases, the file isn't included and perfs are much better.
  388. *
  389. * @param string $msg error message
  390. * @param int $code error code
  391. * @access public
  392. */
  393. function raiseError($msg, $code)
  394. {
  395. return net_php_pear_PEAR::raiseError($msg, $code, $this->_pearErrorMode);
  396. }
  397. /**
  398. * Extend the life of a valid cache file
  399. *
  400. * see http://pear.php.net/bugs/bug.php?id=6681
  401. *
  402. * @access public
  403. */
  404. function extendLife()
  405. {
  406. @touch($this->_file);
  407. }
  408. // --- Private methods ---
  409. /**
  410. * Compute & set the refresh time
  411. *
  412. * @access private
  413. */
  414. function _setRefreshTime()
  415. {
  416. if (is_null($this->_lifeTime)) {
  417. $this->_refreshTime = null;
  418. } else {
  419. $this->_refreshTime = time() - $this->_lifeTime;
  420. }
  421. }
  422. /**
  423. * Remove a file
  424. *
  425. * @param string $file complete file path and name
  426. * @return boolean true if no problem
  427. * @access private
  428. */
  429. function _unlink($file)
  430. {
  431. if (!@unlink($file)) {
  432. return $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
  433. }
  434. return true;
  435. }
  436. /**
  437. * Recursive function for cleaning cache file in the given directory
  438. *
  439. * @param string $dir directory complete path (with a trailing slash)
  440. * @param string $group name of the cache group
  441. * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
  442. 'callback_myFunction'
  443. * @return boolean true if no problem
  444. * @access private
  445. */
  446. function _cleanDir($dir, $group = false, $mode = 'ingroup')
  447. {
  448. if ($this->_fileNameProtection) {
  449. $motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
  450. } else {
  451. $motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
  452. }
  453. if (!($dh = opendir($dir))) {
  454. return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
  455. }
  456. $result = true;
  457. while ($file = readdir($dh)) {
  458. if (($file != '.') && ($file != '..')) {
  459. if (substr($file, 0, 6)=='cache_') {
  460. $file2 = $dir . $file;
  461. if (is_file($file2)) {
  462. switch (substr($mode, 0, 9)) {
  463. case 'old':
  464. // files older than lifeTime get deleted from cache
  465. if (!is_null($this->_lifeTime)) {
  466. if ((mktime() - @filemtime($file2)) > $this->_lifeTime) {
  467. $result = ($result and ($this->_unlink($file2)));
  468. }
  469. }
  470. break;
  471. case 'notingrou':
  472. if (strpos($file2, $motif) === false) {
  473. $result = ($result and ($this->_unlink($file2)));
  474. }
  475. break;
  476. case 'callback_':
  477. $func = substr($mode, 9, strlen($mode) - 9);
  478. if ($func($file2, $group)) {
  479. $result = ($result and ($this->_unlink($file2)));
  480. }
  481. break;
  482. case 'ingroup':
  483. default:
  484. if (strpos($file2, $motif) !== false) {
  485. $result = ($result and ($this->_unlink($file2)));
  486. }
  487. break;
  488. }
  489. }
  490. if ((is_dir($file2)) and ($this->_hashedDirectoryLevel>0)) {
  491. $result = ($result and ($this->_cleanDir($file2 . '/', $group, $mode)));
  492. }
  493. }
  494. }
  495. }
  496. return $result;
  497. }
  498. /**
  499. * Make a file name (with path)
  500. *
  501. * @param string $id cache id
  502. * @param string $group name of the group
  503. * @access private
  504. */
  505. function _setFileName($id, $group)
  506. {
  507. if ($this->_fileNameProtection) {
  508. $suffix = 'cache_'.md5($group).'_'.md5($id);
  509. } else {
  510. $suffix = 'cache_'.$group.'_'.$id;
  511. }
  512. $root = $this->_cacheDir;
  513. if ($this->_hashedDirectoryLevel>0) {
  514. $hash = md5($suffix);
  515. for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
  516. $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
  517. }
  518. }
  519. $this->_fileName = $suffix;
  520. $this->_file = $root.$suffix;
  521. }
  522. /**
  523. * Read the cache file and return the content
  524. *
  525. * @return string content of the cache file (else : false or a PEAR_Error object)
  526. * @access private
  527. */
  528. function _read()
  529. {
  530. $fp = @fopen($this->_file, "rb");
  531. if ($this->_fileLocking) @flock($fp, LOCK_SH);
  532. if ($fp) {
  533. clearstatcache();
  534. $length = @filesize($this->_file);
  535. $mqr = get_magic_quotes_runtime();
  536. //set_magic_quotes_runtime(0);
  537. if ($this->_readControl) {
  538. $hashControl = @fread($fp, 32);
  539. $length = $length - 32;
  540. }
  541. if ($length) {
  542. $data = @fread($fp, $length);
  543. } else {
  544. $data = '';
  545. }
  546. //set_magic_quotes_runtime($mqr);
  547. if ($this->_fileLocking) @flock($fp, LOCK_UN);
  548. @fclose($fp);
  549. if ($this->_readControl) {
  550. $hashData = $this->_hash($data, $this->_readControlType);
  551. if ($hashData != $hashControl) {
  552. if (!(is_null($this->_lifeTime))) {
  553. @touch($this->_file, time() - 2*abs($this->_lifeTime));
  554. } else {
  555. @unlink($this->_file);
  556. }
  557. return false;
  558. }
  559. }
  560. return $data;
  561. }
  562. return $this->raiseError('Cache_Lite : Unable to read cache !', -2);
  563. }
  564. /**
  565. * Write the given data in the cache file
  566. *
  567. * @param string $data data to put in cache
  568. * @return boolean true if ok (a PEAR_Error object else)
  569. * @access private
  570. */
  571. function _write($data)
  572. {
  573. if ($this->_hashedDirectoryLevel > 0) {
  574. $hash = md5($this->_fileName);
  575. $root = $this->_cacheDir;
  576. for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
  577. $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
  578. if (!(@is_dir($root))) {
  579. @mkdir($root, $this->_hashedDirectoryUmask);
  580. }
  581. }
  582. }
  583. $fp = @fopen($this->_file, "wb");
  584. if ($fp) {
  585. if ($this->_fileLocking) @flock($fp, LOCK_EX);
  586. if ($this->_readControl) {
  587. @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
  588. }
  589. $mqr = get_magic_quotes_runtime();
  590. //set_magic_quotes_runtime(0);
  591. @fwrite($fp, $data);
  592. //set_magic_quotes_runtime($mqr);
  593. if ($this->_fileLocking) @flock($fp, LOCK_UN);
  594. @fclose($fp);
  595. return true;
  596. }
  597. return $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1);
  598. }
  599. /**
  600. * Write the given data in the cache file and control it just after to avoir corrupted cache entries
  601. *
  602. * @param string $data data to put in cache
  603. * @return boolean true if the test is ok (else : false or a PEAR_Error object)
  604. * @access private
  605. */
  606. function _writeAndControl($data)
  607. {
  608. $result = $this->_write($data);
  609. if (is_object($result)) {
  610. return $result; # We return the PEAR_Error object
  611. }
  612. $dataRead = $this->_read();
  613. if (is_object($dataRead)) {
  614. return $dataRead; # We return the PEAR_Error object
  615. }
  616. if ((is_bool($dataRead)) && (!$dataRead)) {
  617. return false;
  618. }
  619. return ($dataRead==$data);
  620. }
  621. /**
  622. * Make a control key with the string containing datas
  623. *
  624. * @param string $data data
  625. * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
  626. * @return string control key
  627. * @access private
  628. */
  629. function _hash($data, $controlType)
  630. {
  631. switch ($controlType) {
  632. case 'md5':
  633. return md5($data);
  634. case 'crc32':
  635. return sprintf('% 32d', crc32($data));
  636. case 'strlen':
  637. return sprintf('% 32d', strlen($data));
  638. default:
  639. return $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
  640. }
  641. }
  642. }
  643. ?>