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