1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
|
<?php
/**
* Data storage in the file system.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Cache
*/
namespace MediaWiki\Cache;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiServices;
use MediaWiki\Request\WebRequest;
use Wikimedia\AtEase\AtEase;
use Wikimedia\IPUtils;
use Wikimedia\ObjectCache\BagOStuff;
/**
* Base class for data storage in the file system.
*
* @ingroup Cache
*/
abstract class FileCacheBase {
private const CONSTRUCTOR_OPTIONS = [
MainConfigNames::CacheEpoch,
MainConfigNames::FileCacheDepth,
MainConfigNames::FileCacheDirectory,
MainConfigNames::MimeType,
MainConfigNames::UseGzip,
];
/** @var string */
protected $mKey;
/** @var string */
protected $mType = 'object';
/** @var string */
protected $mExt = 'cache';
/** @var string|null */
protected $mFilePath;
/** @var bool */
protected $mUseGzip;
/** @var bool|null lazy loaded */
protected $mCached;
/** @var ServiceOptions */
protected $options;
/* @todo configurable? */
private const MISS_FACTOR = 15; // log 1 every MISS_FACTOR cache misses
private const MISS_TTL_SEC = 3600; // how many seconds ago is "recent"
protected function __construct() {
$this->options = new ServiceOptions(
self::CONSTRUCTOR_OPTIONS,
MediaWikiServices::getInstance()->getMainConfig()
);
$this->mUseGzip = (bool)$this->options->get( MainConfigNames::UseGzip );
}
/**
* Get the base file cache directory
* @return string
*/
final protected function baseCacheDirectory() {
return $this->options->get( MainConfigNames::FileCacheDirectory );
}
/**
* Get the base cache directory (not specific to this file)
* @return string
*/
abstract protected function cacheDirectory();
/**
* Get the path to the cache file
* @return string
*/
protected function cachePath() {
if ( $this->mFilePath !== null ) {
return $this->mFilePath;
}
$dir = $this->cacheDirectory();
# Build directories (methods include the trailing "/")
$subDirs = $this->typeSubdirectory() . $this->hashSubdirectory();
# Avoid extension confusion
$key = str_replace( '.', '%2E', urlencode( $this->mKey ) );
# Build the full file path
$this->mFilePath = "{$dir}/{$subDirs}{$key}.{$this->mExt}";
if ( $this->useGzip() ) {
$this->mFilePath .= '.gz';
}
return $this->mFilePath;
}
/**
* Check if the cache file exists
* @return bool
*/
public function isCached() {
$this->mCached ??= is_file( $this->cachePath() );
return $this->mCached;
}
/**
* Get the last-modified timestamp of the cache file
* @return string|bool TS_MW timestamp
*/
public function cacheTimestamp() {
$timestamp = filemtime( $this->cachePath() );
return ( $timestamp !== false )
? wfTimestamp( TS_MW, $timestamp )
: false;
}
/**
* Check if up to date cache file exists
* @param string $timestamp MW_TS timestamp
*
* @return bool
*/
public function isCacheGood( $timestamp = '' ) {
$cacheEpoch = $this->options->get( MainConfigNames::CacheEpoch );
if ( !$this->isCached() ) {
return false;
}
$cachetime = $this->cacheTimestamp();
$good = ( $timestamp <= $cachetime && $cacheEpoch <= $cachetime );
wfDebug( __METHOD__ .
": cachetime $cachetime, touched '{$timestamp}' epoch {$cacheEpoch}, good " . wfBoolToStr( $good ) );
return $good;
}
/**
* Check if the cache is gzipped
* @return bool
*/
protected function useGzip() {
return $this->mUseGzip;
}
/**
* Get the uncompressed text from the cache
* @return string
*/
public function fetchText() {
if ( $this->useGzip() ) {
$fh = gzopen( $this->cachePath(), 'rb' );
return stream_get_contents( $fh );
} else {
return file_get_contents( $this->cachePath() );
}
}
/**
* Save and compress text to the cache
* @param string $text
* @return string|false Compressed text
*/
public function saveText( $text ) {
if ( $this->useGzip() ) {
$text = gzencode( $text );
}
$this->checkCacheDirs(); // build parent dir
if ( !file_put_contents( $this->cachePath(), $text, LOCK_EX ) ) {
wfDebug( __METHOD__ . "() failed saving " . $this->cachePath() );
$this->mCached = null;
return false;
}
$this->mCached = true;
return $text;
}
/**
* Clear the cache for this page
* @return void
*/
public function clearCache() {
AtEase::suppressWarnings();
unlink( $this->cachePath() );
AtEase::restoreWarnings();
$this->mCached = false;
}
/**
* Create parent directors of $this->cachePath()
* @return void
*/
protected function checkCacheDirs() {
wfMkdirParents( dirname( $this->cachePath() ), null, __METHOD__ );
}
/**
* Get the cache type subdirectory (with trailing slash)
* An extending class could use that method to alter the type -> directory
* mapping. @see HTMLFileCache::typeSubdirectory() for an example.
*
* @return string
*/
protected function typeSubdirectory() {
return $this->mType . '/';
}
/**
* Return relative multi-level hash subdirectory (with trailing slash)
* or the empty string if not $wgFileCacheDepth
* @return string
*/
protected function hashSubdirectory() {
$fileCacheDepth = $this->options->get( MainConfigNames::FileCacheDepth );
$subdir = '';
if ( $fileCacheDepth > 0 ) {
$hash = md5( $this->mKey );
for ( $i = 1; $i <= $fileCacheDepth; $i++ ) {
$subdir .= substr( $hash, 0, $i ) . '/';
}
}
return $subdir;
}
/**
* Roughly increments the cache misses in the last hour by unique visitors
* @param WebRequest $request
* @return void
*/
public function incrMissesRecent( WebRequest $request ) {
if ( mt_rand( 1, self::MISS_FACTOR ) == 1 ) {
# Get a large IP range that should include the user even if that
# person's IP address changes
$ip = $request->getIP();
if ( !IPUtils::isValid( $ip ) ) {
return;
}
$ip = IPUtils::isIPv6( $ip )
? IPUtils::sanitizeRange( "$ip/32" )
: IPUtils::sanitizeRange( "$ip/16" );
# Bail out if a request already came from this range...
$cache = MediaWikiServices::getInstance()->getObjectCacheFactory()
->getLocalClusterInstance();
$key = $cache->makeKey( static::class, 'attempt', $this->mType, $this->mKey, $ip );
if ( !$cache->add( $key, 1, self::MISS_TTL_SEC ) ) {
return; // possibly the same user
}
# Increment the number of cache misses...
$cache->incrWithInit( $this->cacheMissKey( $cache ), self::MISS_TTL_SEC );
}
}
/**
* Roughly gets the cache misses in the last hour by unique visitors
* @return int
*/
public function getMissesRecent() {
$cache = MediaWikiServices::getInstance()->getObjectCacheFactory()
->getLocalClusterInstance();
return self::MISS_FACTOR * $cache->get( $this->cacheMissKey( $cache ) );
}
/**
* @param BagOStuff $cache Instance that the key will be used with
* @return string
*/
protected function cacheMissKey( BagOStuff $cache ) {
return $cache->makeKey( static::class, 'misses', $this->mType, $this->mKey );
}
}
/** @deprecated class alias since 1.42 */
class_alias( FileCacheBase::class, 'FileCacheBase' );
|