4 * Fast, light and safe Cache Class
6 * Cache_Lite is a fast, light and safe cache system. It's optimized
7 * for file containers. It is fast and safe (because it uses file
8 * locking and/or anti-corruption tests).
10 * There are some examples in the 'docs/examples' file
11 * Technical choices are described in the 'docs/technical' file
13 * A tutorial is available in english at this url :
14 * http://www.pearfr.org/index.php/en/article/cache_lite
15 * (big thanks to Pierre-Alain Joye for the translation)
17 * The same tutorial is also available in french at this url :
18 * http://www.pearfr.org/index.php/fr/article/cache_lite
20 * Memory Caching is from an original idea of
21 * Mike BENOIT <ipso@snappymail.ca>
26 * @author Fabien MARTY <fab@php.net>
29 define('CACHE_LITE_ERROR_RETURN', 1);
30 define('CACHE_LITE_ERROR_DIE', 8);
35 // --- Private properties ---
38 * Directory where to put the cache files
39 * (make sure to add a trailing slash)
41 * @var string $_cacheDir
43 var $_cacheDir = '/tmp/';
46 * Enable / disable caching
48 * (can be very usefull for the debug of cached scripts)
50 * @var boolean $_caching
55 * Cache lifetime (in seconds)
59 var $_lifeTime = 3600;
62 * Enable / disable fileLocking
64 * (can avoid cache corruption under bad circumstances)
66 * @var boolean $_fileLocking
68 var $_fileLocking = true;
71 * Timestamp of the last valid cache
73 * @var int $_refreshTime
78 * File name (with path)
85 * Enable / disable write control (the cache is read just after writing to detect corrupt entries)
87 * Enable write control will lightly slow the cache writing but not the cache reading
88 * Write control can detect some corrupt cache files but maybe it's not a perfect control
90 * @var boolean $_writeControl
92 var $_writeControl = true;
95 * Enable / disable read control
97 * If enabled, a control key is embeded in cache file and this key is compared with the one
98 * calculated after the reading.
100 * @var boolean $_writeControl
102 var $_readControl = true;
105 * Type of read control (only if read control is enabled)
107 * Available values are :
108 * 'md5' for a md5 hash control (best but slowest)
109 * 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
110 * 'strlen' for a length only test (fastest)
112 * @var boolean $_readControlType
114 var $_readControlType = 'crc32';
117 * Pear error mode (when raiseError is called)
122 * @var int $_pearErrorMode
124 var $_pearErrorMode = CACHE_LITE_ERROR_RETURN
;
134 * Current cache group
136 * @var string $_group
141 * Enable / Disable "Memory Caching"
143 * NB : There is no lifetime for memory caching !
145 * @var boolean $_memoryCaching
147 var $_memoryCaching = false;
150 * Enable / Disable "Only Memory Caching"
151 * (be carefull, memory caching is "beta quality")
153 * @var boolean $_onlyMemoryCaching
155 var $_onlyMemoryCaching = false;
158 * Memory caching array
160 * @var array $_memoryCachingArray
162 var $_memoryCachingArray = array();
165 * Memory caching counter
167 * @var int $memoryCachingCounter
169 var $_memoryCachingCounter = 0;
172 * Memory caching limit
174 * @var int $memoryCachingLimit
176 var $_memoryCachingLimit = 1000;
179 * File Name protection
181 * if set to true, you can use any cache id or group name
182 * if set to false, it can be faster but cache ids and group names
183 * will be used directly in cache file names so be carefull with
184 * special characters...
186 * @var boolean $fileNameProtection
188 var $_fileNameProtection = true;
191 * Enable / disable automatic serialization
193 * it can be used to save directly datas which aren't strings
196 * @var boolean $_serialize
198 var $_automaticSerialization = false;
200 // --- Public methods ---
205 * $options is an assoc. Available options are :
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)
222 * @param array $options options
225 function Cache_Lite($options = array(NULL))
227 $availableOptions = array('automaticSerialization', 'fileNameProtection', 'memoryCaching', 'onlyMemoryCaching', 'memoryCachingLimit', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode');
228 foreach($options as $key => $value) {
229 if(in_array($key, $availableOptions)) {
230 $property = '_'.$key;
231 $this->$property = $value;
234 $this->_refreshTime
= time() - $this->_lifeTime
;
238 * Test if a cache is available and (if yes) return it
240 * @param string $id cache id
241 * @param string $group name of the cache group
242 * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
243 * @return string data of the cache (or false if no cache available)
246 function get($id, $group = 'default', $doNotTestCacheValidity = false)
249 $this->_group
= $group;
251 if ($this->_caching
) {
252 $this->_setFileName($id, $group);
253 if ($this->_memoryCaching
) {
254 if (isset($this->_memoryCachingArray
[$this->_file
])) {
255 if ($this->_automaticSerialization
) {
256 return unserialize($this->_memoryCachingArray
[$this->_file
]);
258 return $this->_memoryCachingArray
[$this->_file
];
261 if ($this->_onlyMemoryCaching
) {
266 if ($doNotTestCacheValidity) {
267 if (file_exists($this->_file
)) {
268 $data = $this->_read();
271 if ((file_exists($this->_file
)) && (@filemtime
($this->_file
) > $this->_refreshTime
)) {
272 $data = $this->_read();
275 if (($data) and ($this->_memoryCaching
)) {
276 $this->_memoryCacheAdd($this->_file
, $data);
278 if (($this->_automaticSerialization
) and (is_string($data))) {
279 $data = unserialize($data);
287 * Save some data in a cache file
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
295 function save($data, $id = NULL, $group = 'default')
297 if ($this->_caching
) {
298 if ($this->_automaticSerialization
) {
299 $data = serialize($data);
302 $this->_setFileName($id, $group);
304 if ($this->_memoryCaching
) {
305 $this->_memoryCacheAdd($this->_file
, $data);
306 if ($this->_onlyMemoryCaching
) {
310 if ($this->_writeControl
) {
311 if (!$this->_writeAndControl($data)) {
312 @touch
($this->_file
, time() - 2*abs($this->_lifeTime
));
318 return $this->_write($data);
325 * Remove a cache file
327 * @param string $id cache id
328 * @param string $group name of the cache group
329 * @return boolean true if no problem
332 function remove($id, $group = 'default')
334 $this->_setFileName($id, $group);
335 if ($this->_memoryCaching
) {
336 if (isset($this->_memoryCachingArray
[$this->_file
])) {
337 unset($this->_memoryCachingArray
[$this->_file
]);
338 $this->_memoryCachingCounter
= $this->_memoryCachingCounter
- 1;
340 if ($this->_onlyMemoryCaching
) {
344 if (!@unlink
($this->_file
)) {
345 $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
354 * if no group is specified all cache files will be destroyed
355 * else only cache files of the specified group will be destroyed
357 * @param string $group name of the cache group
358 * @return boolean true if no problem
361 function clean($group = false)
363 if ($this->_fileNameProtection
) {
364 $motif = ($group) ?
'cache_'.md5($group).'_' : 'cache_';
366 $motif = ($group) ?
'cache_'.$group.'_' : 'cache_';
368 if ($this->_memoryCaching
) {
369 while (list($key, $value) = each($this->_memoryCachingArray
)) {
370 if (strpos($key, $motif, 0)) {
371 unset($this->_memoryCachingArray
[$key]);
372 $this->_memoryCachingCounter
= $this->_memoryCachingCounter
- 1;
375 if ($this->_onlyMemoryCaching
) {
379 if (!($dh = opendir($this->_cacheDir
))) {
380 $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
383 while ($file = readdir($dh)) {
384 if (($file != '.') && ($file != '..')) {
385 $file = $this->_cacheDir
. $file;
386 if (is_file($file)) {
387 if (strpos($file, $motif, 0)) {
388 if (!@unlink
($file)) {
389 $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
402 * When an error is found, the script will stop and the message will be displayed
403 * (in debug mode only).
407 function setToDebug()
409 $this->_pearErrorMode
= CACHE_LITE_ERROR_DIE
;
413 * Set a new life time
415 * @param int $newLifeTime new life time (in seconds)
418 function setLifeTime($newLifeTime)
420 $this->_lifeTime
= $newLifeTime;
421 $this->_refreshTime
= time() - $newLifeTime;
428 function saveMemoryCachingState($id, $group = 'default')
430 if ($this->_caching
) {
432 'counter' => $this->_memoryCachingCounter
,
433 'array' => $this->_memoryCachingState
435 $data = serialize($array);
436 $this->save($data, $id, $group);
444 function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
446 if ($this->_caching
) {
447 if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
448 $array = unserialize($data);
449 $this->_memoryCachingCounter
= $array['counter'];
450 $this->_memoryCachingArray
= $array['array'];
456 * Return the cache last modification time
458 * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
460 * @return int last modification time
462 function lastModified() {
463 return filemtime($this->_file
);
467 * Trigger a PEAR error
469 * To improve performances, the PEAR.php file is included dynamically.
470 * The file is so included only when an error is triggered. So, in most
471 * cases, the file isn't included and perfs are much better.
473 * @param string $msg error message
474 * @param int $code error code
477 function raiseError($msg, $code)
479 include_once('PEAR.php');
480 PEAR
::raiseError($msg, $code, $this->_pearErrorMode
);
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).'_'.md5($id));
512 $this->_file
= $this->_cacheDir
.'cache_'.$group.'_'.$id;
517 * Read the cache file and return the content
519 * @return string content of the cache file
524 $fp = @fopen
($this->_file
, "rb");
525 if ($this->_fileLocking
) @flock
($fp, LOCK_SH
);
527 clearstatcache(); // because the filesize can be cached by PHP itself...
528 $length = @filesize
($this->_file
);
529 $mqr = get_magic_quotes_runtime();
530 set_magic_quotes_runtime(0);
531 if ($this->_readControl
) {
532 $hashControl = @fread
($fp, 32);
533 $length = $length - 32;
535 $data = @fread
($fp, $length);
536 set_magic_quotes_runtime($mqr);
537 if ($this->_fileLocking
) @flock
($fp, LOCK_UN
);
539 if ($this->_readControl
) {
540 $hashData = $this->_hash($data, $this->_readControlType
);
541 if ($hashData != $hashControl) {
542 @touch
($this->_file
, time() - 2*abs($this->_lifeTime
));
548 $this->raiseError('Cache_Lite : Unable to read cache !', -2);
553 * Write the given data in the cache file
555 * @param string $data data to put in cache
556 * @return boolean true if ok
559 function _write($data)
561 $fp = @fopen
($this->_file
, "wb");
563 if ($this->_fileLocking
) @flock
($fp, LOCK_EX
);
564 if ($this->_readControl
) {
565 @fwrite
($fp, $this->_hash($data, $this->_readControlType
), 32);
567 $len = strlen($data);
568 @fwrite
($fp, $data, $len);
569 if ($this->_fileLocking
) @flock
($fp, LOCK_UN
);
573 $this->raiseError('Cache_Lite : Unable to write cache !', -1);
578 * Write the given data in the cache file and control it just after to avoir corrupted cache entries
580 * @param string $data data to put in cache
581 * @return boolean true if the test is ok
584 function _writeAndControl($data)
586 $this->_write($data);
587 $dataRead = $this->_read($data);
588 return ($dataRead==$data);
592 * Make a control key with the string containing datas
594 * @param string $data data
595 * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
596 * @return string control key
599 function _hash($data, $controlType)
601 switch ($controlType) {
605 return sprintf('% 32d', crc32($data));
607 return sprintf('% 32d', strlen($data));
609 $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);