1: <?php
2: /**
3: * CFileCache class file
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CFileCache provides a file-based caching mechanism.
13: *
14: * For each data value being cached, CFileCache will use store it in a separate file
15: * under {@link cachePath} which defaults to 'protected/runtime/cache'.
16: * CFileCache will perform garbage collection automatically to remove expired cache files.
17: *
18: * See {@link CCache} manual for common cache operations that are supported by CFileCache.
19: *
20: * @property integer $gCProbability The probability (parts per million) that garbage collection (GC) should be performed
21: * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
22: *
23: * @author Qiang Xue <qiang.xue@gmail.com>
24: * @package system.caching
25: */
26: class CFileCache extends CCache
27: {
28: /**
29: * @var string the directory to store cache files. Defaults to null, meaning
30: * using 'protected/runtime/cache' as the directory.
31: */
32: public $cachePath;
33: /**
34: * @var integer the permission to be set for directory to store cache files
35: * This value will be used by PHP chmod function.
36: * Defaults to 0777, meaning the directory can be read, written and executed by all users.
37: * @since 1.1.16
38: */
39: public $cachePathMode=0777;
40: /**
41: * @var string cache file suffix. Defaults to '.bin'.
42: */
43: public $cacheFileSuffix='.bin';
44: /**
45: * @var integer the permission to be set for new cache files.
46: * This value will be used by PHP chmod function.
47: * Defaults to 0666, meaning the file is read-writable by all users.
48: * @since 1.1.16
49: */
50: public $cacheFileMode=0666;
51: /**
52: * @var integer the level of sub-directories to store cache files. Defaults to 0,
53: * meaning no sub-directories. If the system has huge number of cache files (e.g. 10K+),
54: * you may want to set this value to be 1 or 2 so that the file system is not over burdened.
55: * The value of this property should not exceed 16 (less than 3 is recommended).
56: */
57: public $directoryLevel=0;
58: /**
59: * @var boolean whether cache entry expiration time should be embedded into a physical file.
60: * Defaults to false meaning that the file modification time will be used to store expire value.
61: * True value means that first ten bytes of the file would be reserved and used to store expiration time.
62: * On some systems PHP is not allowed to change file modification time to be in future even with 777
63: * permissions, so this property could be useful in this case.
64: * @since 1.1.14
65: */
66: public $embedExpiry=false;
67:
68: private $_gcProbability=100;
69: private $_gced=false;
70:
71: /**
72: * Initializes this application component.
73: * This method is required by the {@link IApplicationComponent} interface.
74: */
75: public function init()
76: {
77: parent::init();
78: if($this->cachePath===null)
79: $this->cachePath=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'cache';
80: if(!is_dir($this->cachePath))
81: {
82: mkdir($this->cachePath,$this->cachePathMode,true);
83: chmod($this->cachePath,$this->cachePathMode);
84: }
85: }
86:
87: /**
88: * @return integer the probability (parts per million) that garbage collection (GC) should be performed
89: * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
90: */
91: public function getGCProbability()
92: {
93: return $this->_gcProbability;
94: }
95:
96: /**
97: * @param integer $value the probability (parts per million) that garbage collection (GC) should be performed
98: * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
99: * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
100: */
101: public function setGCProbability($value)
102: {
103: $value=(int)$value;
104: if($value<0)
105: $value=0;
106: if($value>1000000)
107: $value=1000000;
108: $this->_gcProbability=$value;
109: }
110:
111: /**
112: * Deletes all values from cache.
113: * This is the implementation of the method declared in the parent class.
114: * @return boolean whether the flush operation was successful.
115: * @since 1.1.5
116: */
117: protected function flushValues()
118: {
119: $this->gc(false);
120: return true;
121: }
122:
123: /**
124: * Retrieves a value from cache with a specified key.
125: * This is the implementation of the method declared in the parent class.
126: * @param string $key a unique key identifying the cached value
127: * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
128: */
129: protected function getValue($key)
130: {
131: $cacheFile=$this->getCacheFile($key);
132: if(($time=$this->filemtime($cacheFile))>time())
133: return @file_get_contents($cacheFile,false,null,$this->embedExpiry ? 10 : -1);
134: elseif($time>0)
135: @unlink($cacheFile);
136: return false;
137: }
138:
139: /**
140: * Stores a value identified by a key in cache.
141: * This is the implementation of the method declared in the parent class.
142: *
143: * @param string $key the key identifying the value to be cached
144: * @param string $value the value to be cached
145: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
146: * @return boolean true if the value is successfully stored into cache, false otherwise
147: */
148: protected function setValue($key,$value,$expire)
149: {
150: if(!$this->_gced && mt_rand(0,1000000)<$this->_gcProbability)
151: {
152: $this->gc();
153: $this->_gced=true;
154: }
155:
156: if($expire<=0)
157: $expire=31536000; // 1 year
158: $expire+=time();
159:
160: $cacheFile=$this->getCacheFile($key);
161: if($this->directoryLevel>0)
162: {
163: $cacheDir=dirname($cacheFile);
164: @mkdir($cacheDir,$this->cachePathMode,true);
165: @chmod($cacheDir,$this->cachePathMode);
166: }
167: if(@file_put_contents($cacheFile,$this->embedExpiry ? $expire.$value : $value,LOCK_EX)!==false)
168: {
169: @chmod($cacheFile,$this->cacheFileMode);
170: return $this->embedExpiry ? true : @touch($cacheFile,$expire);
171: }
172: else
173: return false;
174: }
175:
176: /**
177: * Stores a value identified by a key into cache if the cache does not contain this key.
178: * This is the implementation of the method declared in the parent class.
179: *
180: * @param string $key the key identifying the value to be cached
181: * @param string $value the value to be cached
182: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
183: * @return boolean true if the value is successfully stored into cache, false otherwise
184: */
185: protected function addValue($key,$value,$expire)
186: {
187: $cacheFile=$this->getCacheFile($key);
188: if($this->filemtime($cacheFile)>time())
189: return false;
190: return $this->setValue($key,$value,$expire);
191: }
192:
193: /**
194: * Deletes a value with the specified key from cache
195: * This is the implementation of the method declared in the parent class.
196: * @param string $key the key of the value to be deleted
197: * @return boolean if no error happens during deletion
198: */
199: protected function deleteValue($key)
200: {
201: $cacheFile=$this->getCacheFile($key);
202: return @unlink($cacheFile);
203: }
204:
205: /**
206: * Returns the cache file path given the cache key.
207: * @param string $key cache key
208: * @return string the cache file path
209: */
210: protected function getCacheFile($key)
211: {
212: if($this->directoryLevel>0)
213: {
214: $base=$this->cachePath;
215: for($i=0;$i<$this->directoryLevel;++$i)
216: {
217: if(($prefix=substr($key,$i+$i,2))!==false)
218: $base.=DIRECTORY_SEPARATOR.$prefix;
219: }
220: return $base.DIRECTORY_SEPARATOR.$key.$this->cacheFileSuffix;
221: }
222: else
223: return $this->cachePath.DIRECTORY_SEPARATOR.$key.$this->cacheFileSuffix;
224: }
225:
226: /**
227: * Removes expired cache files.
228: * @param boolean $expiredOnly whether only expired cache files should be removed.
229: * If false, all cache files under {@link cachePath} will be removed.
230: * @param string $path the path to clean with. If null, it will be {@link cachePath}.
231: */
232: public function gc($expiredOnly=true,$path=null)
233: {
234: if($path===null)
235: $path=$this->cachePath;
236: if(($handle=opendir($path))===false)
237: return;
238: while(($file=readdir($handle))!==false)
239: {
240: if($file[0]==='.')
241: continue;
242: $fullPath=$path.DIRECTORY_SEPARATOR.$file;
243: if(is_dir($fullPath))
244: $this->gc($expiredOnly,$fullPath);
245: elseif($expiredOnly && $this->filemtime($fullPath)<time() || !$expiredOnly)
246: @unlink($fullPath);
247: }
248: closedir($handle);
249: }
250:
251: /**
252: * Returns cache file modification time. {@link $embedExpiry} aware.
253: * @param string $path to the file, modification time to be retrieved from.
254: * @return integer file modification time.
255: */
256: private function filemtime($path)
257: {
258: if($this->embedExpiry)
259: return (int)@file_get_contents($path,false,null,0,10);
260: else
261: return @filemtime($path);
262: }
263: }
264: