4 * TCache_Lite class file.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the BSD License.
9 * Copyright(c) 2004 by Qiang Xue. All rights reserved.
11 * To contact the author write to {@link mailto:qiang.xue@gmail.com Qiang Xue}
12 * The latest version of PRADO can be obtained from:
13 * {@link http://prado.sourceforge.net/}
15 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
16 * @version $Revision: 1.3 $ $Date: 2005/10/09 10:24:12 $
17 * @package System.I18N.core
21 * Fast, light and safe Cache Class
23 * TCache_Lite is a fast, light and safe cache system. It's optimized
24 * for file containers. It is fast and safe (because it uses file
25 * locking and/or anti-corruption tests).
27 * There are some examples in the 'docs/examples' file
28 * Technical choices are described in the 'docs/technical' file
30 * A tutorial is available in english at this url :
31 * http://www.pearfr.org/index.php/en/article/cache_lite
32 * (big thanks to Pierre-Alain Joye for the translation)
34 * The same tutorial is also available in french at this url :
35 * http://www.pearfr.org/index.php/fr/article/cache_lite
37 * Memory Caching is from an original idea of
38 * Mike BENOIT <ipso@snappymail.ca>
40 * @package System.I18N.core
41 * @author Fabien MARTY <fab@php.net>
42 * @copyright 1997-2005 The PHP Group
43 * @license http://www.gnu.org/copyleft/lesser.html GNU LGPL
44 * @link http://pear.php.net/package/Cache_Lite
49 // --- Private properties ---
52 * Directory where to put the cache files
53 * (make sure to add a trailing slash)
55 * @var string $_cacheDir
57 protected $_cacheDir = '/tmp/';
60 * Enable / disable caching
62 * (can be very usefull for the debug of cached scripts)
64 * @var boolean $_caching
66 protected $_caching = true;
69 * Cache lifetime (in seconds)
73 protected $_lifeTime = 3600;
76 * Enable / disable fileLocking
78 * (can avoid cache corruption under bad circumstances)
80 * @var boolean $_fileLocking
82 protected $_fileLocking = true;
85 * Timestamp of the last valid cache
87 * @var int $_refreshTime
89 protected $_refreshTime;
92 * File name (with path)
99 * Enable / disable write control (the cache is read just after writing
100 * to detect corrupt entries)
102 * Enable write control will lightly slow the cache writing but not the
103 * cache reading. Write control can detect some corrupt cache files but
104 * maybe it's not a perfect control
106 * @var boolean $_writeControl
108 protected $_writeControl = true;
111 * Enable / disable read control
113 * If enabled, a control key is embeded in cache file and this key is
114 * compared with the one calculated after the reading.
116 * @var boolean $_writeControl
118 protected $_readControl = true;
121 * Type of read control (only if read control is enabled)
123 * Available values are :
124 * 'md5' for a md5 hash control (best but slowest)
125 * 'crc32' for a crc32 hash control (lightly less safe but faster,
127 * 'strlen' for a length only test (fastest)
129 * @var boolean $_readControlType
131 protected $_readControlType = 'crc32';
141 * Current cache group
143 * @var string $_group
148 * Enable / Disable "Memory Caching"
150 * NB : There is no lifetime for memory caching !
152 * @var boolean $_memoryCaching
154 protected $_memoryCaching = false;
157 * Enable / Disable "Only Memory Caching"
158 * (be carefull, memory caching is "beta quality")
160 * @var boolean $_onlyMemoryCaching
162 protected $_onlyMemoryCaching = false;
165 * Memory caching array
167 * @var array $_memoryCachingArray
169 protected $_memoryCachingArray = array();
172 * Memory caching counter
174 * @var int $memoryCachingCounter
176 protected $_memoryCachingCounter = 0;
179 * Memory caching limit
181 * @var int $memoryCachingLimit
183 protected $_memoryCachingLimit = 1000;
186 * File Name protection
188 * if set to true, you can use any cache id or group name
189 * if set to false, it can be faster but cache ids and group names
190 * will be used directly in cache file names so be carefull with
191 * special characters...
193 * @var boolean $fileNameProtection
195 protected $_fileNameProtection = true;
198 * Enable / disable automatic serialization
200 * it can be used to save directly datas which aren't strings
203 * @var boolean $_serialize
205 protected $_automaticSerialization = false;
207 // --- Public methods ---
212 * $options is an assoc. Available options are :
214 * 'cacheDir' => directory where to put the cache files (string),
215 * 'caching' => enable / disable caching (boolean),
216 * 'lifeTime' => cache lifetime in seconds (int),
217 * 'fileLocking' => enable / disable fileLocking (boolean),
218 * 'writeControl' => enable / disable write control (boolean),
219 * 'readControl' => enable / disable read control (boolean),
220 * 'readControlType' => type of read control 'crc32', 'md5', 'strlen',
221 * 'memoryCaching' => enable / disable memory caching (boolean),
222 * 'onlyMemoryCaching' => enable / disable only memory caching (boolean),
223 * 'memoryCachingLimit' => max nbr of records in memory caching (int),
224 * 'fileNameProtection' => enable / disable file name protection (boolean),
225 * 'automaticSerialization' => enable / disable serialization (boolean)
228 * @param array $options options
231 function __construct($options = array(null))
233 $availableOptions = array( 'automaticSerialization',
234 'fileNameProtection',
237 'memoryCachingLimit',
245 foreach($options as $key => $value) {
246 if(in_array($key, $availableOptions)) {
247 $property = '_'.$key;
248 $this->$property = $value;
251 $this->_refreshTime = time() - $this->_lifeTime;
255 * Test if a cache is available and (if yes) return it
257 * @param string $id cache id
258 * @param string $group name of the cache group
259 * @param boolean $doNotTestCacheValidity if set to true, the cache
260 * validity won't be tested
261 * @return string data of the cache (or false if no cache available)
264 function get($id, $group = 'default', $doNotTestCacheValidity = false)
267 $this->_group = $group;
269 if ($this->_caching) {
270 $this->_setFileName($id, $group);
271 if ($this->_memoryCaching) {
272 if (isset($this->_memoryCachingArray[$this->_file])) {
273 if ($this->_automaticSerialization) {
275 $this->_memoryCachingArray[$this->_file]);
277 return $this->_memoryCachingArray[$this->_file];
280 if ($this->_onlyMemoryCaching) {
285 if ($doNotTestCacheValidity) {
286 if (file_exists($this->_file)) {
287 $data = $this->_read();
290 if (@filemtime($this->_file) > $this->_refreshTime) {
291 $data = $this->_read();
294 if (($data) and ($this->_memoryCaching)) {
295 $this->_memoryCacheAdd($this->_file, $data);
297 if ($this->_automaticSerialization && is_string($data)) {
298 $data = unserialize($data);
306 * Save some data in a cache file
308 * @param string $data data to put in cache (can be another type than strings
309 * if automaticSerialization is on)
310 * @param string $id cache id
311 * @param string $group name of the cache group
312 * @return boolean true if no problem
315 function save($data, $id = null, $group = 'default')
317 if ($this->_caching) {
318 if ($this->_automaticSerialization) {
319 $data = serialize($data);
322 $this->_setFileName($id, $group);
324 if ($this->_memoryCaching) {
325 $this->_memoryCacheAdd($this->_file, $data);
326 if ($this->_onlyMemoryCaching) {
330 if ($this->_writeControl) {
331 if (!$this->_writeAndControl($data)) {
332 @touch($this->_file, time() - 2*abs($this->_lifeTime));
338 return $this->_write($data);
345 * Remove a cache file
347 * @param string $id cache id
348 * @param string $group name of the cache group
349 * @return boolean true if no problem
352 function remove($id, $group = 'default')
354 $this->_setFileName($id, $group);
355 if (!@unlink($this->_file)) {
356 $this->raiseError('TCache_Lite : Unable to remove cache !', -3);
365 * if no group is specified all cache files will be destroyed
366 * else only cache files of the specified group will be destroyed
368 * @param string $group name of the cache group
369 * @return boolean true if no problem
372 function clean($group = false)
374 if ($this->_fileNameProtection) {
375 $motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
377 $motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
379 if ($this->_memoryCaching) {
380 while (list($key, $value) = each($this->_memoryCaching)) {
381 if (strpos($key, $motif, 0)) {
382 unset($this->_memoryCaching[$key]);
383 $this->_memoryCachingCounter =
384 $this->_memoryCachingCounter - 1;
387 if ($this->_onlyMemoryCaching) {
391 if (!($dh = opendir($this->_cacheDir))) {
392 $this->raiseError('TCache_Lite : Unable to open cache directory !');
395 while ($file = readdir($dh)) {
396 if (($file != '.') && ($file != '..')) {
397 $file = $this->_cacheDir . $file;
398 if (is_file($file)) {
399 if (strpos($file, $motif, 0)) {
400 if (!@unlink($file)) {
401 $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
412 * Set a new life time
414 * @param int $newLifeTime new life time (in seconds)
417 function setLifeTime($newLifeTime)
419 $this->_lifeTime = $newLifeTime;
420 $this->_refreshTime = time() - $newLifeTime;
427 function saveMemoryCachingState($id, $group = 'default')
429 if ($this->_caching) {
431 'counter' => $this->_memoryCachingCounter,
432 'array' => $this->_memoryCachingState
434 $data = serialize($array);
435 $this->save($data, $id, $group);
443 function getMemoryCachingState($id, $group = 'default',
444 $doNotTestCacheValidity = false)
446 if ($this->_caching) {
447 if ($data = $this->get($id, $group, $doNotTestCacheValidity))
449 $array = unserialize($data);
450 $this->_memoryCachingCounter = $array['counter'];
451 $this->_memoryCachingArray = $array['array'];
457 * Return the cache last modification time
459 * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
461 * @return int last modification time
463 function lastModified() {
464 return filemtime($this->cache->_file);
468 * Trigger a PEAR error
470 * To improve performances, the PEAR.php file is included dynamically.
471 * The file is so included only when an error is triggered. So, in most
472 * cases, the file isn't included and perfs are much better.
474 * @param string $msg error message
475 * @param int $code error code
478 function raiseError($msg, $code)
480 throw new Exception($msg);
483 // --- Private methods ---
489 function _memoryCacheAdd($id, $data)
491 $this->_memoryCachingArray[$this->_file] = $data;
492 if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
493 list($key, $value) = each($this->_memoryCachingArray);
494 unset($this->_memoryCachingArray[$key]);
496 $this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
501 * Make a file name (with path)
503 * @param string $id cache id
504 * @param string $group name of the group
507 function _setFileName($id, $group)
509 if ($this->_fileNameProtection) {
510 $this->_file = ($this->_cacheDir.'cache_'.md5($group).'_'
513 $this->_file = $this->_cacheDir.'cache_'.$group.'_'.$id;
517 function getCacheFile()
523 * Read the cache file and return the content
525 * @return string content of the cache file
530 $fp = @fopen($this->_file, "rb");
531 if ($this->_fileLocking) @flock($fp, LOCK_SH);
533 // because the filesize can be cached by PHP itself...
535 $length = @filesize($this->_file);
536 if ($this->_readControl) {
537 $hashControl = @fread($fp, 32);
538 $length = $length - 32;
540 $data = @fread($fp, $length);
541 if ($this->_fileLocking) @flock($fp, LOCK_UN);
543 if ($this->_readControl) {
544 $hashData = $this->_hash($data, $this->_readControlType);
545 if ($hashData != $hashControl) {
546 @touch($this->_file, time() - 2*abs($this->_lifeTime));
552 $this->raiseError('Cache_Lite : Unable to read cache !', -2);
557 * Write the given data in the cache file
559 * @param string $data data to put in cache
560 * @return boolean true if ok
563 function _write($data)
565 $fp = @fopen($this->_file, "wb");
567 if ($this->_fileLocking) @flock($fp, LOCK_EX);
568 if ($this->_readControl) {
569 @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
571 $len = strlen($data);
572 @fwrite($fp, $data, $len);
573 if ($this->_fileLocking) @flock($fp, LOCK_UN);
577 $this->raiseError('Cache_Lite : Unable to write cache !', -1);
582 * Write the given data in the cache file and control it just after to avoid
583 * corrupted cache entries
585 * @param string $data data to put in cache
586 * @return boolean true if the test is ok
589 function _writeAndControl($data)
591 $this->_write($data);
592 $dataRead = $this->_read($data);
593 return ($dataRead==$data);
597 * Make a control key with the string containing datas
599 * @param string $data data
600 * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
601 * @return string control key
604 function _hash($data, $controlType)
606 switch ($controlType) {
610 return sprintf('% 32d', crc32($data));
612 return sprintf('% 32d', strlen($data));
614 $this->raiseError('Unknown controlType ! '.
615 '(available values are only \'md5\', \'crc32\', \'strlen\')', -5);