User::isSafeToLoad() should return false if MW_NO_SESSION
[mediawiki.git] / includes / cache / FileCacheBase.php
blob360420b615b7f1cdf1726b8f711eacd98a9a2fc0
1 <?php
2 /**
3 * Data storage in the file system.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Cache
24 /**
25 * Base class for data storage in the file system.
27 * @ingroup Cache
29 abstract class FileCacheBase {
30 protected $mKey;
31 protected $mType = 'object';
32 protected $mExt = 'cache';
33 protected $mFilePath;
34 protected $mUseGzip;
35 /* lazy loaded */
36 protected $mCached;
38 /* @todo configurable? */
39 const MISS_FACTOR = 15; // log 1 every MISS_FACTOR cache misses
40 const MISS_TTL_SEC = 3600; // how many seconds ago is "recent"
42 protected function __construct() {
43 global $wgUseGzip;
45 $this->mUseGzip = (bool)$wgUseGzip;
48 /**
49 * Get the base file cache directory
50 * @return string
52 final protected function baseCacheDirectory() {
53 global $wgFileCacheDirectory;
55 return $wgFileCacheDirectory;
58 /**
59 * Get the base cache directory (not specific to this file)
60 * @return string
62 abstract protected function cacheDirectory();
64 /**
65 * Get the path to the cache file
66 * @return string
68 protected function cachePath() {
69 if ( $this->mFilePath !== null ) {
70 return $this->mFilePath;
73 $dir = $this->cacheDirectory();
74 # Build directories (methods include the trailing "/")
75 $subDirs = $this->typeSubdirectory() . $this->hashSubdirectory();
76 # Avoid extension confusion
77 $key = str_replace( '.', '%2E', urlencode( $this->mKey ) );
78 # Build the full file path
79 $this->mFilePath = "{$dir}/{$subDirs}{$key}.{$this->mExt}";
80 if ( $this->useGzip() ) {
81 $this->mFilePath .= '.gz';
84 return $this->mFilePath;
87 /**
88 * Check if the cache file exists
89 * @return bool
91 public function isCached() {
92 if ( $this->mCached === null ) {
93 $this->mCached = file_exists( $this->cachePath() );
96 return $this->mCached;
99 /**
100 * Get the last-modified timestamp of the cache file
101 * @return string|bool TS_MW timestamp
103 public function cacheTimestamp() {
104 $timestamp = filemtime( $this->cachePath() );
106 return ( $timestamp !== false )
107 ? wfTimestamp( TS_MW, $timestamp )
108 : false;
112 * Check if up to date cache file exists
113 * @param string $timestamp MW_TS timestamp
115 * @return bool
117 public function isCacheGood( $timestamp = '' ) {
118 global $wgCacheEpoch;
120 if ( !$this->isCached() ) {
121 return false;
124 $cachetime = $this->cacheTimestamp();
125 $good = ( $timestamp <= $cachetime && $wgCacheEpoch <= $cachetime );
126 wfDebug( __METHOD__ .
127 ": cachetime $cachetime, touched '{$timestamp}' epoch {$wgCacheEpoch}, good $good\n" );
129 return $good;
133 * Check if the cache is gzipped
134 * @return bool
136 protected function useGzip() {
137 return $this->mUseGzip;
141 * Get the uncompressed text from the cache
142 * @return string
144 public function fetchText() {
145 if ( $this->useGzip() ) {
146 $fh = gzopen( $this->cachePath(), 'rb' );
148 return stream_get_contents( $fh );
149 } else {
150 return file_get_contents( $this->cachePath() );
155 * Save and compress text to the cache
156 * @param string $text
157 * @return string Compressed text
159 public function saveText( $text ) {
160 global $wgUseFileCache;
162 if ( !$wgUseFileCache ) {
163 return false;
166 if ( $this->useGzip() ) {
167 $text = gzencode( $text );
170 $this->checkCacheDirs(); // build parent dir
171 if ( !file_put_contents( $this->cachePath(), $text, LOCK_EX ) ) {
172 wfDebug( __METHOD__ . "() failed saving " . $this->cachePath() . "\n" );
173 $this->mCached = null;
175 return false;
178 $this->mCached = true;
180 return $text;
184 * Clear the cache for this page
185 * @return void
187 public function clearCache() {
188 MediaWiki\suppressWarnings();
189 unlink( $this->cachePath() );
190 MediaWiki\restoreWarnings();
191 $this->mCached = false;
195 * Create parent directors of $this->cachePath()
196 * @return void
198 protected function checkCacheDirs() {
199 wfMkdirParents( dirname( $this->cachePath() ), null, __METHOD__ );
203 * Get the cache type subdirectory (with trailing slash)
204 * An extending class could use that method to alter the type -> directory
205 * mapping. @see HTMLFileCache::typeSubdirectory() for an example.
207 * @return string
209 protected function typeSubdirectory() {
210 return $this->mType . '/';
214 * Return relative multi-level hash subdirectory (with trailing slash)
215 * or the empty string if not $wgFileCacheDepth
216 * @return string
218 protected function hashSubdirectory() {
219 global $wgFileCacheDepth;
221 $subdir = '';
222 if ( $wgFileCacheDepth > 0 ) {
223 $hash = md5( $this->mKey );
224 for ( $i = 1; $i <= $wgFileCacheDepth; $i++ ) {
225 $subdir .= substr( $hash, 0, $i ) . '/';
229 return $subdir;
233 * Roughly increments the cache misses in the last hour by unique visitors
234 * @param WebRequest $request
235 * @return void
237 public function incrMissesRecent( WebRequest $request ) {
238 if ( mt_rand( 0, self::MISS_FACTOR - 1 ) == 0 ) {
239 $cache = ObjectCache::getLocalClusterInstance();
240 # Get a large IP range that should include the user even if that
241 # person's IP address changes
242 $ip = $request->getIP();
243 if ( !IP::isValid( $ip ) ) {
244 return;
246 $ip = IP::isIPv6( $ip )
247 ? IP::sanitizeRange( "$ip/32" )
248 : IP::sanitizeRange( "$ip/16" );
250 # Bail out if a request already came from this range...
251 $key = wfMemcKey( get_class( $this ), 'attempt', $this->mType, $this->mKey, $ip );
252 if ( $cache->get( $key ) ) {
253 return; // possibly the same user
255 $cache->set( $key, 1, self::MISS_TTL_SEC );
257 # Increment the number of cache misses...
258 $key = $this->cacheMissKey();
259 if ( $cache->get( $key ) === false ) {
260 $cache->set( $key, 1, self::MISS_TTL_SEC );
261 } else {
262 $cache->incr( $key );
268 * Roughly gets the cache misses in the last hour by unique visitors
269 * @return int
271 public function getMissesRecent() {
272 $cache = ObjectCache::getLocalClusterInstance();
274 return self::MISS_FACTOR * $cache->get( $this->cacheMissKey() );
278 * @return string
280 protected function cacheMissKey() {
281 return wfMemcKey( get_class( $this ), 'misses', $this->mType, $this->mKey );