PageRenderTime 60ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 0ms

/cache_lite/vendors/Cache_Lite/Cache/Lite.php

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