FileCache:
[lhc/web/wiklou.git] / includes / cache / FileCacheBase.php
1 <?php
2 /**
3 * Contain the FileCacheBase class
4 * @file
5 * @ingroup Cache
6 */
7 abstract class FileCacheBase {
8 protected $mKey;
9 protected $mType = 'object';
10 protected $mExt = 'cache';
11 protected $mFilePath;
12 protected $mUseGzip;
13
14 /* @TODO: configurable? */
15 const MISS_FACTOR = 10; // log 1 every MISS_FACTOR cache misses
16
17 protected function __construct() {
18 global $wgUseGzip;
19
20 $this->mUseGzip = (bool)$wgUseGzip;
21 }
22
23 /**
24 * Get the base file cache directory
25 * @return string
26 */
27 final protected function baseCacheDirectory() {
28 global $wgCacheDirectory, $wgFileCacheDirectory, $wgFileCacheDepth;
29 if ( $wgFileCacheDirectory ) {
30 $dir = $wgFileCacheDirectory;
31 } elseif ( $wgCacheDirectory ) {
32 $dir = $wgCacheDirectory;
33 } else {
34 throw new MWException( 'Please set $wgCacheDirectory in LocalSettings.php if you wish to use the HTML file cache' );
35 }
36 return $dir;
37 }
38
39 /**
40 * Get the base cache directory (not speficic to this file)
41 * @return string
42 */
43 abstract protected function cacheDirectory();
44
45 /**
46 * Get the path to the cache file
47 * @return string
48 */
49 protected function cachePath() {
50 if ( $this->mFilePath !== null ) {
51 return $this->mFilePath;
52 }
53
54 $dir = $this->cacheDirectory();
55 # Build directories (methods include the trailing "/")
56 $subDirs = $this->typeSubdirectory() . $this->hashSubdirectory();
57 # Avoid extension confusion
58 $key = str_replace( '.', '%2E', urlencode( $this->mKey ) );
59 # Build the full file path
60 $this->mFilePath = "{$dir}/{$subDirs}{$key}.{$this->mExt}";
61 if ( $this->useGzip() ) {
62 $this->mFilePath .= '.gz';
63 }
64
65 return $this->mFilePath;
66 }
67
68 /**
69 * Check if the cache file exists
70 * @return bool
71 */
72 public function isCached() {
73 return file_exists( $this->cachePath() );
74 }
75
76 /**
77 * Get the last-modified timestamp of the cache file
78 * @return string|false TS_MW timestamp
79 */
80 public function cacheTimestamp() {
81 $timestamp = filemtime( $this->cachePath() );
82 return ( $timestamp !== false )
83 ? wfTimestamp( TS_MW, $timestamp )
84 : false;
85 }
86
87 /**
88 * Check if up to date cache file exists
89 * @param $timestamp string MW_TS timestamp
90 *
91 * @return bool
92 */
93 public function isCacheGood( $timestamp = '' ) {
94 global $wgCacheEpoch;
95
96 if ( !$this->isCached() ) {
97 return false;
98 }
99
100 $cachetime = $this->cacheTimestamp();
101 $good = ( $timestamp <= $cachetime && $wgCacheEpoch <= $cachetime );
102 wfDebug( __METHOD__ . ": cachetime $cachetime, touched '{$timestamp}' epoch {$wgCacheEpoch}, good $good\n");
103
104 return $good;
105 }
106
107 /**
108 * Check if the cache is gzipped
109 * @return bool
110 */
111 protected function useGzip() {
112 return $this->mUseGzip;
113 }
114
115 /**
116 * Get the uncompressed text from the cache
117 * @return string
118 */
119 public function fetchText() {
120 if ( $this->useGzip() ) {
121 /* Why is there no gzfile_get_contents() or gzdecode()? */
122 return implode( '', gzfile( $this->cachePath() ) );
123 } else {
124 return file_get_contents( $this->cachePath() );
125 }
126 }
127
128 /**
129 * Save and compress text to the cache
130 * @return string compressed text
131 */
132 public function saveText( $text ) {
133 global $wgUseFileCache;
134
135 if ( !$wgUseFileCache ) {
136 return false;
137 }
138
139 if ( $this->useGzip() ) {
140 $text = gzencode( $text );
141 }
142
143 $this->checkCacheDirs(); // build parent dir
144 if ( !file_put_contents( $this->cachePath(), $text, LOCK_EX ) ) {
145 return false;
146 }
147
148 return $text;
149 }
150
151 /**
152 * Clear the cache for this page
153 * @return void
154 */
155 public function clearCache() {
156 wfSuppressWarnings();
157 unlink( $this->cachePath() );
158 wfRestoreWarnings();
159 }
160
161 /**
162 * Create parent directors of $this->cachePath()
163 * @return void
164 */
165 protected function checkCacheDirs() {
166 wfMkdirParents( dirname( $this->cachePath() ), null, __METHOD__ );
167 }
168
169 /**
170 * Get the cache type subdirectory (with trailing slash) or the empty string
171 * @return string
172 */
173 protected function typeSubdirectory() {
174 return $this->mType . '/';
175 }
176
177 /**
178 * Return relative multi-level hash subdirectory (with trailing slash)
179 * or the empty string if not $wgFileCacheDepth
180 * @return string
181 */
182 protected function hashSubdirectory() {
183 global $wgFileCacheDepth;
184
185 $subdir = '';
186 if ( $wgFileCacheDepth > 0 ) {
187 $hash = md5( $this->mKey );
188 for ( $i = 1; $i <= $wgFileCacheDepth; $i++ ) {
189 $subdir .= substr( $hash, 0, $i ) . '/';
190 }
191 }
192
193 return $subdir;
194 }
195
196 /**
197 * Roughly increments the cache misses in the last hour by unique visitors
198 * @param $request WebRequest
199 * @return void
200 */
201 public function incrMissesRecent( WebRequest $request ) {
202 global $wgMemc;
203 if ( mt_rand( 0, self::MISS_FACTOR - 1 ) == 0 ) {
204 # Get an large IP range that should include the user
205 # even if that person's IP address changes...
206 $ip = $request->getIP();
207 if ( !IP::isValid( $ip ) ) {
208 return;
209 }
210 $ip = IP::isIPv6( $ip )
211 ? IP::sanitizeRange( "$ip/64" )
212 : IP::sanitizeRange( "$ip/16" );
213
214 # Bail out if a request already came from this range...
215 $key = wfMemcKey( get_class( $this ), 'attempt', $this->mType, $this->mKey, $ip );
216 if ( $wgMemc->get( $key ) ) {
217 return; // possibly the same user
218 }
219 $wgMemc->set( $key, 1, 3600 );
220
221 # Increment the number of cache misses...
222 $key = $this->cacheMissKey();
223 if ( $wgMemc->get( $key ) === false ) {
224 $wgMemc->set( $key, 1, 3600 );
225 } else {
226 $wgMemc->incr( $key );
227 }
228 }
229 }
230
231 /**
232 * Roughly gets the cache misses in the last hour by unique visitors
233 * @return int
234 */
235 public function getMissesRecent() {
236 global $wgMemc;
237 return self::MISS_FACTOR * $wgMemc->get( $this->cacheMissKey() );
238 }
239
240 /**
241 * @return string
242 */
243 protected function cacheMissKey() {
244 return wfMemcKey( get_class( $this ), 'misses', $this->mType, $this->mKey );
245 }
246 }