MediaWiki  1.27.3
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() {
44 
45  $this->mUseGzip = (bool)$wgUseGzip;
46  }
47 
52  final protected function baseCacheDirectory() {
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 = '' ) {
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 ) {
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() {
188  MediaWiki\suppressWarnings();
189  unlink( $this->cachePath() );
190  MediaWiki\restoreWarnings();
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() {
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  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 ( $cache->get( $key ) ) {
253  return; // possibly the same user
254  }
255  $cache->set( $key, 1, self::MISS_TTL_SEC );
256 
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 );
263  }
264  }
265  }
266 
271  public function getMissesRecent() {
273 
274  return self::MISS_FACTOR * $cache->get( $this->cacheMissKey() );
275  }
276 
280  protected function cacheMissKey() {
281  return wfMemcKey( get_class( $this ), 'misses', $this->mType, $this->mKey );
282  }
283 }
saveText($text)
Save and compress text to the cache.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2325
if(count($args)==0) $dir
getIP()
Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of...
static sanitizeRange($range)
Gets rid of unneeded numbers in quad-dotted/octet IP strings For example, 127.111.113.151/24 -> 127.111.113.0/24.
Definition: IP.php:713
wfMkdirParents($dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
incrMissesRecent(WebRequest $request)
Roughly increments the cache misses in the last hour by unique visitors.
baseCacheDirectory()
Get the base file cache directory.
static getLocalClusterInstance()
Get the main cluster-local cache object.
$wgFileCacheDepth
Depth of the subdirectory hierarchy to be created under $wgFileCacheDirectory.
static isIPv6($ip)
Given a string, determine if it as valid IP in IPv6 only.
Definition: IP.php:90
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
isCacheGood($timestamp= '')
Check if up to date cache file exists.
cacheTimestamp()
Get the last-modified timestamp of the cache file.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
isCached()
Check if the cache file exists.
typeSubdirectory()
Get the cache type subdirectory (with trailing slash) An extending class could use that method to alt...
$wgUseFileCache
This will cache static pages for non-logged-in users to reduce database traffic on public sites...
if($limit) $timestamp
static isValid($ip)
Validate an IP address.
Definition: IP.php:113
Base class for data storage in the file system.
$cache
Definition: mcc.php:33
$wgUseGzip
When using the file cache, we can store the cached HTML gzipped to save disk space.
cachePath()
Get the path to the cache file.
hashSubdirectory()
Return relative multi-level hash subdirectory (with trailing slash) or the empty string if not $wgFil...
cacheDirectory()
Get the base cache directory (not specific to this file)
fetchText()
Get the uncompressed text from the cache.
getMissesRecent()
Roughly gets the cache misses in the last hour by unique visitors.
clearCache()
Clear the cache for this page.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2422
useGzip()
Check if the cache is gzipped.
wfMemcKey()
Make a cache key for the local wiki.
checkCacheDirs()
Create parent directors of $this->cachePath()
$wgCacheEpoch
Set this to current time to invalidate all prior cached pages.
$wgFileCacheDirectory
Directory where the cached page will be saved.