MediaWiki  1.23.2
FileCacheBase.php
Go to the documentation of this file.
1 <?php
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;
37 
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"
41 
42  protected function __construct() {
43  global $wgUseGzip;
44 
45  $this->mUseGzip = (bool)$wgUseGzip;
46  }
47 
52  final protected function baseCacheDirectory() {
53  global $wgFileCacheDirectory;
54 
55  return $wgFileCacheDirectory;
56  }
57 
62  abstract protected function cacheDirectory();
63 
68  protected function cachePath() {
69  if ( $this->mFilePath !== null ) {
70  return $this->mFilePath;
71  }
72 
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';
82  }
83 
84  return $this->mFilePath;
85  }
86 
91  public function isCached() {
92  if ( $this->mCached === null ) {
93  $this->mCached = file_exists( $this->cachePath() );
94  }
95 
96  return $this->mCached;
97  }
98 
103  public function cacheTimestamp() {
104  $timestamp = filemtime( $this->cachePath() );
105 
106  return ( $timestamp !== false )
108  : false;
109  }
110 
117  public function isCacheGood( $timestamp = '' ) {
118  global $wgCacheEpoch;
119 
120  if ( !$this->isCached() ) {
121  return false;
122  }
123 
124  $cachetime = $this->cacheTimestamp();
125  $good = ( $timestamp <= $cachetime && $wgCacheEpoch <= $cachetime );
126  wfDebug( __METHOD__ .
127  ": cachetime $cachetime, touched '{$timestamp}' epoch {$wgCacheEpoch}, good $good\n" );
128 
129  return $good;
130  }
131 
136  protected function useGzip() {
137  return $this->mUseGzip;
138  }
139 
144  public function fetchText() {
145  if ( $this->useGzip() ) {
146  $fh = gzopen( $this->cachePath(), 'rb' );
147 
148  return stream_get_contents( $fh );
149  } else {
150  return file_get_contents( $this->cachePath() );
151  }
152  }
153 
159  public function saveText( $text ) {
160  global $wgUseFileCache;
161 
162  if ( !$wgUseFileCache ) {
163  return false;
164  }
165 
166  if ( $this->useGzip() ) {
167  $text = gzencode( $text );
168  }
169 
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;
174 
175  return false;
176  }
177 
178  $this->mCached = true;
179 
180  return $text;
181  }
182 
187  public function clearCache() {
189  unlink( $this->cachePath() );
191  $this->mCached = false;
192  }
193 
198  protected function checkCacheDirs() {
199  wfMkdirParents( dirname( $this->cachePath() ), null, __METHOD__ );
200  }
201 
209  protected function typeSubdirectory() {
210  return $this->mType . '/';
211  }
212 
218  protected function hashSubdirectory() {
219  global $wgFileCacheDepth;
220 
221  $subdir = '';
222  if ( $wgFileCacheDepth > 0 ) {
223  $hash = md5( $this->mKey );
224  for ( $i = 1; $i <= $wgFileCacheDepth; $i++ ) {
225  $subdir .= substr( $hash, 0, $i ) . '/';
226  }
227  }
228 
229  return $subdir;
230  }
231 
237  public function incrMissesRecent( WebRequest $request ) {
238  global $wgMemc;
239  if ( mt_rand( 0, self::MISS_FACTOR - 1 ) == 0 ) {
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;
245  }
246  $ip = IP::isIPv6( $ip )
247  ? IP::sanitizeRange( "$ip/32" )
248  : IP::sanitizeRange( "$ip/16" );
249 
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 ( $wgMemc->get( $key ) ) {
253  return; // possibly the same user
254  }
255  $wgMemc->set( $key, 1, self::MISS_TTL_SEC );
256 
257  # Increment the number of cache misses...
258  $key = $this->cacheMissKey();
259  if ( $wgMemc->get( $key ) === false ) {
260  $wgMemc->set( $key, 1, self::MISS_TTL_SEC );
261  } else {
262  $wgMemc->incr( $key );
263  }
264  }
265  }
266 
271  public function getMissesRecent() {
272  global $wgMemc;
273 
274  return self::MISS_FACTOR * $wgMemc->get( $this->cacheMissKey() );
275  }
276 
280  protected function cacheMissKey() {
281  return wfMemcKey( get_class( $this ), 'misses', $this->mType, $this->mKey );
282  }
283 }
FileCacheBase\__construct
__construct()
Definition: FileCacheBase.php:42
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
FileCacheBase\MISS_FACTOR
const MISS_FACTOR
Definition: FileCacheBase.php:39
FileCacheBase\saveText
saveText( $text)
Save and compress text to the cache.
Definition: FileCacheBase.php:159
FileCacheBase\isCacheGood
isCacheGood( $timestamp='')
Check if up to date cache file exists.
Definition: FileCacheBase.php:117
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:2590
$wgMemc
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest to get request data $wgMemc
Definition: globals.txt:25
$timestamp
if( $limit) $timestamp
Definition: importImages.php:104
FileCacheBase\$mCached
$mCached
Definition: FileCacheBase.php:36
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2483
FileCacheBase\$mUseGzip
$mUseGzip
Definition: FileCacheBase.php:34
FileCacheBase\cacheMissKey
cacheMissKey()
Definition: FileCacheBase.php:280
wfSuppressWarnings
wfSuppressWarnings( $end=false)
Reference-counted warning suppression.
Definition: GlobalFunctions.php:2387
IP\isIPv6
static isIPv6( $ip)
Given a string, determine if it as valid IP in IPv6 only.
Definition: IP.php:85
FileCacheBase\hashSubdirectory
hashSubdirectory()
Return relative multi-level hash subdirectory (with trailing slash) or the empty string if not $wgFil...
Definition: FileCacheBase.php:218
FileCacheBase\$mKey
$mKey
Definition: FileCacheBase.php:30
wfMemcKey
wfMemcKey()
Get a cache key.
Definition: GlobalFunctions.php:3571
wfRestoreWarnings
wfRestoreWarnings()
Restore error level to previous value.
Definition: GlobalFunctions.php:2417
FileCacheBase\$mExt
$mExt
Definition: FileCacheBase.php:32
FileCacheBase\useGzip
useGzip()
Check if the cache is gzipped.
Definition: FileCacheBase.php:136
FileCacheBase\baseCacheDirectory
baseCacheDirectory()
Get the base file cache directory.
Definition: FileCacheBase.php:52
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
FileCacheBase\fetchText
fetchText()
Get the uncompressed text from the cache.
Definition: FileCacheBase.php:144
FileCacheBase\typeSubdirectory
typeSubdirectory()
Get the cache type subdirectory (with trailing slash) An extending class could use that method to alt...
Definition: FileCacheBase.php:209
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:188
TS_MW
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Definition: GlobalFunctions.php:2431
FileCacheBase\MISS_TTL_SEC
const MISS_TTL_SEC
Definition: FileCacheBase.php:40
wfDebug
wfDebug( $text, $dest='all')
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:933
FileCacheBase\isCached
isCached()
Check if the cache file exists.
Definition: FileCacheBase.php:91
FileCacheBase\cacheDirectory
cacheDirectory()
Get the base cache directory (not specific to this file)
FileCacheBase\clearCache
clearCache()
Clear the cache for this page.
Definition: FileCacheBase.php:187
IP\isValid
static isValid( $ip)
Validate an IP address.
Definition: IP.php:108
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Definition: WebRequest.php:38
$hash
return false to override stock group addition can be modified try getUserPermissionsErrors userCan checks are continued by internal code can override on output return false to not delete it return false to override the default password checks & $hash
Definition: hooks.txt:2697
WebRequest\getIP
getIP()
Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of...
Definition: WebRequest.php:1102
FileCacheBase\$mFilePath
$mFilePath
Definition: FileCacheBase.php:33
FileCacheBase\getMissesRecent
getMissesRecent()
Roughly gets the cache misses in the last hour by unique visitors.
Definition: FileCacheBase.php:271
FileCacheBase\$mType
$mType
Definition: FileCacheBase.php:31
$dir
if(count( $args)==0) $dir
Definition: importImages.php:49
FileCacheBase\cachePath
cachePath()
Get the path to the cache file.
Definition: FileCacheBase.php:68
FileCacheBase\incrMissesRecent
incrMissesRecent(WebRequest $request)
Roughly increments the cache misses in the last hour by unique visitors.
Definition: FileCacheBase.php:237
IP\sanitizeRange
static sanitizeRange( $range)
Gets rid of unneeded numbers in quad-dotted/octet IP strings For example, 127.111....
Definition: IP.php:763
FileCacheBase\cacheTimestamp
cacheTimestamp()
Get the last-modified timestamp of the cache file.
Definition: FileCacheBase.php:103
FileCacheBase\checkCacheDirs
checkCacheDirs()
Create parent directors of $this->cachePath()
Definition: FileCacheBase.php:198
FileCacheBase
Base class for data storage in the file system.
Definition: FileCacheBase.php:29