MediaWiki  1.32.5
ParserCache.php
Go to the documentation of this file.
1 <?php
25 
30 class ParserCache {
37  const USE_CURRENT_ONLY = 0;
38 
40  const USE_EXPIRED = 1;
41 
43  const USE_OUTDATED = 2;
44 
49  const USE_ANYTHING = 3;
50 
52  private $mMemc;
53 
59  private $cacheEpoch;
66  public static function singleton() {
67  return MediaWikiServices::getInstance()->getParserCache();
68  }
69 
80  public function __construct( BagOStuff $cache, $cacheEpoch = '20030516000000' ) {
81  $this->mMemc = $cache;
82  $this->cacheEpoch = $cacheEpoch;
83  }
84 
90  protected function getParserOutputKey( $article, $hash ) {
91  global $wgRequest;
92 
93  // idhash seem to mean 'page id' + 'rendering hash' (r3710)
94  $pageid = $article->getId();
95  $renderkey = (int)( $wgRequest->getVal( 'action' ) == 'render' );
96 
97  $key = $this->mMemc->makeKey( 'pcache', 'idhash', "{$pageid}-{$renderkey}!{$hash}" );
98  return $key;
99  }
100 
105  protected function getOptionsKey( $page ) {
106  return $this->mMemc->makeKey( 'pcache', 'idoptions', $page->getId() );
107  }
108 
113  public function deleteOptionsKey( $page ) {
114  $this->mMemc->delete( $this->getOptionsKey( $page ) );
115  }
116 
131  public function getETag( $article, $popts ) {
132  return 'W/"' . $this->getParserOutputKey( $article,
133  $popts->optionsHash( ParserOptions::allCacheVaryingOptions(), $article->getTitle() ) ) .
134  "--" . $article->getTouched() . '"';
135  }
136 
143  public function getDirty( $article, $popts ) {
144  $value = $this->get( $article, $popts, true );
145  return is_object( $value ) ? $value : false;
146  }
147 
168  public function getKey( $article, $popts, $useOutdated = self::USE_ANYTHING ) {
169  if ( is_bool( $useOutdated ) ) {
170  $useOutdated = $useOutdated ? self::USE_ANYTHING : self::USE_CURRENT_ONLY;
171  }
172 
173  if ( $popts instanceof User ) {
174  wfWarn( "Use of outdated prototype ParserCache::getKey( &\$article, &\$user )\n" );
175  $popts = ParserOptions::newFromUser( $popts );
176  }
177 
178  // Determine the options which affect this article
179  $casToken = null;
180  $optionsKey = $this->mMemc->get(
181  $this->getOptionsKey( $article ), $casToken, BagOStuff::READ_VERIFIED );
182  if ( $optionsKey instanceof CacheTime ) {
183  if ( $useOutdated < self::USE_EXPIRED && $optionsKey->expired( $article->getTouched() ) ) {
184  wfIncrStats( "pcache.miss.expired" );
185  $cacheTime = $optionsKey->getCacheTime();
186  wfDebugLog( "ParserCache",
187  "Parser options key expired, touched " . $article->getTouched()
188  . ", epoch {$this->cacheEpoch}, cached $cacheTime\n" );
189  return false;
190  } elseif ( $useOutdated < self::USE_OUTDATED &&
191  $optionsKey->isDifferentRevision( $article->getLatest() )
192  ) {
193  wfIncrStats( "pcache.miss.revid" );
194  $revId = $article->getLatest();
195  $cachedRevId = $optionsKey->getCacheRevisionId();
196  wfDebugLog( "ParserCache",
197  "ParserOutput key is for an old revision, latest $revId, cached $cachedRevId\n"
198  );
199  return false;
200  }
201 
202  // $optionsKey->mUsedOptions is set by save() by calling ParserOutput::getUsedOptions()
203  $usedOptions = $optionsKey->mUsedOptions;
204  wfDebug( "Parser cache options found.\n" );
205  } else {
206  if ( $useOutdated < self::USE_ANYTHING ) {
207  return false;
208  }
209  $usedOptions = ParserOptions::allCacheVaryingOptions();
210  }
211 
212  return $this->getParserOutputKey(
213  $article,
214  $popts->optionsHash( $usedOptions, $article->getTitle() )
215  );
216  }
217 
228  public function get( $article, $popts, $useOutdated = false ) {
229  $canCache = $article->checkTouched();
230  if ( !$canCache ) {
231  // It's a redirect now
232  return false;
233  }
234 
235  $touched = $article->getTouched();
236 
237  $parserOutputKey = $this->getKey( $article, $popts,
238  $useOutdated ? self::USE_OUTDATED : self::USE_CURRENT_ONLY
239  );
240  if ( $parserOutputKey === false ) {
241  wfIncrStats( 'pcache.miss.absent' );
242  return false;
243  }
244 
245  $casToken = null;
247  $value = $this->mMemc->get( $parserOutputKey, $casToken, BagOStuff::READ_VERIFIED );
248  if ( !$value ) {
249  wfDebug( "ParserOutput cache miss.\n" );
250  wfIncrStats( "pcache.miss.absent" );
251  return false;
252  }
253 
254  wfDebug( "ParserOutput cache found.\n" );
255 
256  $wikiPage = method_exists( $article, 'getPage' )
257  ? $article->getPage()
258  : $article;
259 
260  if ( !$useOutdated && $value->expired( $touched ) ) {
261  wfIncrStats( "pcache.miss.expired" );
262  $cacheTime = $value->getCacheTime();
263  wfDebugLog( "ParserCache",
264  "ParserOutput key expired, touched $touched, "
265  . "epoch {$this->cacheEpoch}, cached $cacheTime\n" );
266  $value = false;
267  } elseif ( !$useOutdated && $value->isDifferentRevision( $article->getLatest() ) ) {
268  wfIncrStats( "pcache.miss.revid" );
269  $revId = $article->getLatest();
270  $cachedRevId = $value->getCacheRevisionId();
271  wfDebugLog( "ParserCache",
272  "ParserOutput key is for an old revision, latest $revId, cached $cachedRevId\n"
273  );
274  $value = false;
275  } elseif (
276  Hooks::run( 'RejectParserCacheValue', [ $value, $wikiPage, $popts ] ) === false
277  ) {
278  wfIncrStats( 'pcache.miss.rejected' );
279  wfDebugLog( "ParserCache",
280  "ParserOutput key valid, but rejected by RejectParserCacheValue hook handler.\n"
281  );
282  $value = false;
283  } else {
284  wfIncrStats( "pcache.hit" );
285  }
286 
287  return $value;
288  }
289 
297  public function save(
298  ParserOutput $parserOutput,
299  $page,
300  $popts,
301  $cacheTime = null,
302  $revId = null
303  ) {
304  if ( !$parserOutput->hasText() ) {
305  throw new InvalidArgumentException( 'Attempt to cache a ParserOutput with no text set!' );
306  }
307 
308  $expire = $parserOutput->getCacheExpiry();
309  if ( $expire > 0 && !$this->mMemc instanceof EmptyBagOStuff ) {
310  $cacheTime = $cacheTime ?: wfTimestampNow();
311  if ( !$revId ) {
312  $revision = $page->getRevision();
313  $revId = $revision ? $revision->getId() : null;
314  }
315 
316  $optionsKey = new CacheTime;
317  $optionsKey->mUsedOptions = $parserOutput->getUsedOptions();
318  $optionsKey->updateCacheExpiry( $expire );
319 
320  $optionsKey->setCacheTime( $cacheTime );
321  $parserOutput->setCacheTime( $cacheTime );
322  $optionsKey->setCacheRevisionId( $revId );
323  $parserOutput->setCacheRevisionId( $revId );
324 
325  $parserOutputKey = $this->getParserOutputKey( $page,
326  $popts->optionsHash( $optionsKey->mUsedOptions, $page->getTitle() ) );
327 
328  // Save the timestamp so that we don't have to load the revision row on view
329  $parserOutput->setTimestamp( $page->getTimestamp() );
330 
331  $msg = "Saved in parser cache with key $parserOutputKey" .
332  " and timestamp $cacheTime" .
333  " and revision id $revId" .
334  "\n";
335 
336  $parserOutput->mText .= "\n<!-- $msg -->\n";
337  wfDebug( $msg );
338 
339  // Save the parser output
340  $this->mMemc->set( $parserOutputKey, $parserOutput, $expire );
341 
342  // ...and its pointer
343  $this->mMemc->set( $this->getOptionsKey( $page ), $optionsKey, $expire );
344 
345  Hooks::run(
346  'ParserCacheSaveComplete',
347  [ $this, $parserOutput, $page->getTitle(), $popts, $revId ]
348  );
349  } elseif ( $expire <= 0 ) {
350  wfDebug( "Parser output was marked as uncacheable and has not been saved.\n" );
351  }
352  }
353 
361  public function getCacheStorage() {
362  return $this->mMemc;
363  }
364 }
ParserCache\USE_EXPIRED
const USE_EXPIRED
Use expired data if current data is unavailable.
Definition: ParserCache.php:40
CacheTime\getCacheExpiry
getCacheExpiry()
Returns the number of seconds after which this object should expire.
Definition: CacheTime.php:129
$article
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used the name of the old file & $article
Definition: hooks.txt:1515
ParserCache\getOptionsKey
getOptionsKey( $page)
Definition: ParserCache.php:105
ParserOutput
Definition: ParserOutput.php:25
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
CacheTime
Parser cache specific expiry check.
Definition: CacheTime.php:29
EmptyBagOStuff
A BagOStuff object with no objects in it.
Definition: EmptyBagOStuff.php:29
ParserOutput\setTimestamp
setTimestamp( $timestamp)
Definition: ParserOutput.php:621
ParserOutput\getUsedOptions
getUsedOptions()
Returns the options from its ParserOptions which have been taken into account to produce this output.
Definition: ParserOutput.php:1047
ParserCache\getETag
getETag( $article, $popts)
Provides an E-Tag suitable for the whole page.
Definition: ParserCache.php:131
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:58
ContextSource\getTitle
getTitle()
Definition: ContextSource.php:79
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1082
ParserCache\$mMemc
BagOStuff $mMemc
Definition: ParserCache.php:52
php
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
CacheTime\setCacheTime
setCacheTime( $t)
setCacheTime() sets the timestamp expressing when the page has been rendered.
Definition: CacheTime.php:74
ParserCache\USE_ANYTHING
const USE_ANYTHING
Use expired data and data from different revisions, and if all else fails vary on all variable option...
Definition: ParserCache.php:49
wfIncrStats
wfIncrStats( $key, $count=1)
Increment a statistics counter.
Definition: GlobalFunctions.php:1227
ParserCache\getDirty
getDirty( $article, $popts)
Retrieve the ParserOutput from ParserCache, even if it's outdated.
Definition: ParserCache.php:143
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1983
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:988
ParserCache\getKey
getKey( $article, $popts, $useOutdated=self::USE_ANYTHING)
Generates a key for caching the given article considering the given parser options.
Definition: ParserCache.php:168
ParserCache\getCacheStorage
getCacheStorage()
Get the backend BagOStuff instance that powers the parser cache.
Definition: ParserCache.php:361
ParserCache\deleteOptionsKey
deleteOptionsKey( $page)
Definition: ParserCache.php:113
ParserCache\singleton
static singleton()
Get an instance of this object.
Definition: ParserCache.php:66
$value
$value
Definition: styleTest.css.php:49
ParserCache\USE_CURRENT_ONLY
const USE_CURRENT_ONLY
Constants for self::getKey()
Definition: ParserCache.php:37
$cache
$cache
Definition: mcc.php:33
ParserCache\getParserOutputKey
getParserOutputKey( $article, $hash)
Definition: ParserCache.php:90
BagOStuff\READ_VERIFIED
const READ_VERIFIED
Definition: BagOStuff.php:98
ParserOptions\allCacheVaryingOptions
static allCacheVaryingOptions()
Return all option keys that vary the options hash.
Definition: ParserOptions.php:1286
ParserOutput\hasText
hasText()
Returns true if text was passed to the constructor, or set using setText().
Definition: ParserOutput.php:263
CacheTime\setCacheRevisionId
setCacheRevisionId( $id)
Definition: CacheTime.php:95
ParserCache\$cacheEpoch
string $cacheEpoch
Anything cached prior to this is invalidated.
Definition: ParserCache.php:59
ParserCache
Definition: ParserCache.php:30
true
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:2044
ParserCache\save
save(ParserOutput $parserOutput, $page, $popts, $cacheTime=null, $revId=null)
Definition: ParserCache.php:297
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1132
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:747
MediaWikiServices
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 MediaWikiServices
Definition: injection.txt:23
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:47
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
ParserCache\USE_OUTDATED
const USE_OUTDATED
Use expired data or data from different revisions if current data is unavailable.
Definition: ParserCache.php:43
ParserCache\__construct
__construct(BagOStuff $cache, $cacheEpoch='20030516000000')
Setup a cache pathway with a given back-end storage mechanism.
Definition: ParserCache.php:80
ParserOptions\newFromUser
static newFromUser( $user)
Get a ParserOptions object from a given user.
Definition: ParserOptions.php:1015