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