MediaWiki  master
MessageCache.php
Go to the documentation of this file.
1 <?php
35 use Psr\Log\LoggerAwareInterface;
36 use Psr\Log\LoggerInterface;
38 use Wikimedia\ScopedCallback;
39 
44 define( 'MSG_CACHE_VERSION', 2 );
45 
52 class MessageCache implements LoggerAwareInterface {
53  private const FOR_UPDATE = 1; // force message reload
54 
56  private const WAIT_SEC = 15;
58  private const LOCK_TTL = 30;
59 
64  private const WAN_TTL = IExpiringStore::TTL_DAY;
65 
67  private $logger;
68 
74  protected $cache;
75 
82 
86  protected $cacheVolatile = [];
87 
92  protected $mDisable;
93 
98  protected $mParserOptions;
100  protected $mParser;
101 
105  protected $mInParser = false;
106 
108  protected $wanCache;
110  protected $clusterCache;
112  protected $srvCache;
114  protected $contLang;
116  protected $contLangCode;
120  protected $langFactory;
126  protected $languageFallback;
128  private $hookRunner;
129 
136  public static function normalizeKey( $key ) {
137  $lckey = strtr( $key, ' ', '_' );
138  if ( ord( $lckey ) < 128 ) {
139  $lckey[0] = strtolower( $lckey[0] );
140  } else {
141  $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
142  }
143 
144  return $lckey;
145  }
146 
164  public function __construct(
167  BagOStuff $serverCache,
170  LoggerInterface $logger,
171  array $options,
176  HookContainer $hookContainer
177  ) {
178  $this->wanCache = $wanCache;
179  $this->clusterCache = $clusterCache;
180  $this->srvCache = $serverCache;
181  $this->contLang = $contLang;
182  $this->contLangConverter = $contLangConverter;
183  $this->contLangCode = $contLang->getCode();
184  $this->logger = $logger;
185  $this->langFactory = $langFactory;
186  $this->localisationCache = $localisationCache;
187  $this->languageNameUtils = $languageNameUtils;
188  $this->languageFallback = $languageFallback;
189  $this->hookRunner = new HookRunner( $hookContainer );
190 
191  // limit size
192  $this->cache = new MapCacheLRU( 5 );
193 
194  $this->mDisable = !( $options['useDB'] ?? true );
195  }
196 
197  public function setLogger( LoggerInterface $logger ) {
198  $this->logger = $logger;
199  }
200 
206  private function getParserOptions() {
207  if ( !$this->mParserOptions ) {
208  $context = RequestContext::getMain();
209  $user = $context->getUser();
210  if ( !$user->isSafeToLoad() ) {
211  // It isn't safe to use the context user yet, so don't try to get a
212  // ParserOptions for it. And don't cache this ParserOptions
213  // either.
215  $po->setAllowUnsafeRawHtml( false );
216  return $po;
217  }
218 
219  $this->mParserOptions = ParserOptions::newFromContext( $context );
220  // Messages may take parameters that could come
221  // from malicious sources. As a precaution, disable
222  // the <html> parser tag when parsing messages.
223  $this->mParserOptions->setAllowUnsafeRawHtml( false );
224  }
225 
226  return $this->mParserOptions;
227  }
228 
235  protected function getLocalCache( $code ) {
236  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
237 
238  return $this->srvCache->get( $cacheKey );
239  }
240 
247  protected function saveToLocalCache( $code, $cache ) {
248  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
249  $this->srvCache->set( $cacheKey, $cache );
250  }
251 
273  protected function load( $code, $mode = null ) {
274  if ( !is_string( $code ) ) {
275  throw new InvalidArgumentException( "Missing language code" );
276  }
277 
278  # Don't do double loading...
279  if ( $this->isLanguageLoaded( $code ) && $mode != self::FOR_UPDATE ) {
280  return true;
281  }
282 
283  # 8 lines of code just to say (once) that message cache is disabled
284  if ( $this->mDisable ) {
285  static $shownDisabled = false;
286  if ( !$shownDisabled ) {
287  $this->logger->debug( __METHOD__ . ': disabled' );
288  $shownDisabled = true;
289  }
290 
291  return true;
292  }
293 
294  # Loading code starts
295  $success = false; # Keep track of success
296  $staleCache = false; # a cache array with expired data, or false if none has been loaded
297  $where = []; # Debug info, delayed to avoid spamming debug log too much
298 
299  # Hash of the contents is stored in memcache, to detect if data-center cache
300  # or local cache goes out of date (e.g. due to replace() on some other server)
301  list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
302  $this->cacheVolatile[$code] = $hashVolatile;
303 
304  # Try the local cache and check against the cluster hash key...
305  $cache = $this->getLocalCache( $code );
306  if ( !$cache ) {
307  $where[] = 'local cache is empty';
308  } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
309  $where[] = 'local cache has the wrong hash';
310  $staleCache = $cache;
311  } elseif ( $this->isCacheExpired( $cache ) ) {
312  $where[] = 'local cache is expired';
313  $staleCache = $cache;
314  } elseif ( $hashVolatile ) {
315  $where[] = 'local cache validation key is expired/volatile';
316  $staleCache = $cache;
317  } else {
318  $where[] = 'got from local cache';
319  $this->cache->set( $code, $cache );
320  $success = true;
321  }
322 
323  if ( !$success ) {
324  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
325  # Try the global cache. If it is empty, try to acquire a lock. If
326  # the lock can't be acquired, wait for the other thread to finish
327  # and then try the global cache a second time.
328  for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
329  if ( $hashVolatile && $staleCache ) {
330  # Do not bother fetching the whole cache blob to avoid I/O.
331  # Instead, just try to get the non-blocking $statusKey lock
332  # below, and use the local stale value if it was not acquired.
333  $where[] = 'global cache is presumed expired';
334  } else {
335  $cache = $this->clusterCache->get( $cacheKey );
336  if ( !$cache ) {
337  $where[] = 'global cache is empty';
338  } elseif ( $this->isCacheExpired( $cache ) ) {
339  $where[] = 'global cache is expired';
340  $staleCache = $cache;
341  } elseif ( $hashVolatile ) {
342  # DB results are replica DB lag prone until the holdoff TTL passes.
343  # By then, updates should be reflected in loadFromDBWithLock().
344  # One thread regenerates the cache while others use old values.
345  $where[] = 'global cache is expired/volatile';
346  $staleCache = $cache;
347  } else {
348  $where[] = 'got from global cache';
349  $this->cache->set( $code, $cache );
350  $this->saveToCaches( $cache, 'local-only', $code );
351  $success = true;
352  }
353  }
354 
355  if ( $success ) {
356  # Done, no need to retry
357  break;
358  }
359 
360  # We need to call loadFromDB. Limit the concurrency to one process.
361  # This prevents the site from going down when the cache expires.
362  # Note that the DB slam protection lock here is non-blocking.
363  $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
364  if ( $loadStatus === true ) {
365  $success = true;
366  break;
367  } elseif ( $staleCache ) {
368  # Use the stale cache while some other thread constructs the new one
369  $where[] = 'using stale cache';
370  $this->cache->set( $code, $staleCache );
371  $success = true;
372  break;
373  } elseif ( $failedAttempts > 0 ) {
374  # Already blocked once, so avoid another lock/unlock cycle.
375  # This case will typically be hit if memcached is down, or if
376  # loadFromDB() takes longer than LOCK_WAIT.
377  $where[] = "could not acquire status key.";
378  break;
379  } elseif ( $loadStatus === 'cantacquire' ) {
380  # Wait for the other thread to finish, then retry. Normally,
381  # the memcached get() will then yield the other thread's result.
382  $where[] = 'waited for other thread to complete';
383  $this->getReentrantScopedLock( $cacheKey );
384  } else {
385  # Disable cache; $loadStatus is 'disabled'
386  break;
387  }
388  }
389  }
390 
391  if ( !$success ) {
392  $where[] = 'loading FAILED - cache is disabled';
393  $this->mDisable = true;
394  $this->cache->set( $code, [] );
395  $this->logger->error( __METHOD__ . ": Failed to load $code" );
396  # This used to throw an exception, but that led to nasty side effects like
397  # the whole wiki being instantly down if the memcached server died
398  }
399 
400  if ( !$this->isLanguageLoaded( $code ) ) {
401  throw new LogicException( "Process cache for '$code' should be set by now." );
402  }
403 
404  $info = implode( ', ', $where );
405  $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
406 
407  return $success;
408  }
409 
416  protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
417  # If cache updates on all levels fail, give up on message overrides.
418  # This is to avoid easy site outages; see $saveSuccess comments below.
419  $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
420  $status = $this->clusterCache->get( $statusKey );
421  if ( $status === 'error' ) {
422  $where[] = "could not load; method is still globally disabled";
423  return 'disabled';
424  }
425 
426  # Now let's regenerate
427  $where[] = 'loading from database';
428 
429  # Lock the cache to prevent conflicting writes.
430  # This lock is non-blocking so stale cache can quickly be used.
431  # Note that load() will call a blocking getReentrantScopedLock()
432  # after this if it really need to wait for any current thread.
433  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
434  $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
435  if ( !$scopedLock ) {
436  $where[] = 'could not acquire main lock';
437  return 'cantacquire';
438  }
439 
440  $cache = $this->loadFromDB( $code, $mode );
441  $this->cache->set( $code, $cache );
442  $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
443 
444  if ( !$saveSuccess ) {
458  if ( $this->srvCache instanceof EmptyBagOStuff ) {
459  $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
460  $where[] = 'could not save cache, disabled globally for 5 minutes';
461  } else {
462  $where[] = "could not save global cache";
463  }
464  }
465 
466  return true;
467  }
468 
478  protected function loadFromDB( $code, $mode = null ) {
479  $maxMsgCacheEntrySize = MediaWikiServices::getInstance()->getMainConfig()->get( 'MaxMsgCacheEntrySize' );
480  $adaptiveMessageCache = MediaWikiServices::getInstance()->getMainConfig()->get( 'AdaptiveMessageCache' );
481  // (T164666) The query here performs really poorly on WMF's
482  // contributions replicas. We don't have a way to say "any group except
483  // contributions", so for the moment let's specify 'api'.
484  // @todo: Get rid of this hack.
485  $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_PRIMARY : DB_REPLICA, 'api' );
486 
487  $cache = [];
488 
489  $mostused = []; // list of "<cased message key>/<code>"
490  if ( $adaptiveMessageCache && $code !== $this->contLangCode ) {
491  if ( !$this->cache->has( $this->contLangCode ) ) {
492  $this->load( $this->contLangCode );
493  }
494  $mostused = array_keys( $this->cache->get( $this->contLangCode ) );
495  foreach ( $mostused as $key => $value ) {
496  $mostused[$key] = "$value/$code";
497  }
498  }
499 
500  // Common conditions
501  $conds = [
502  'page_is_redirect' => 0,
503  'page_namespace' => NS_MEDIAWIKI,
504  ];
505  if ( count( $mostused ) ) {
506  $conds['page_title'] = $mostused;
507  } elseif ( $code !== $this->contLangCode ) {
508  $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
509  } else {
510  # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
511  # other than language code.
512  $conds[] = 'page_title NOT' .
513  $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
514  }
515 
516  // Set the stubs for oversized software-defined messages in the main cache map
517  $res = $dbr->select(
518  'page',
519  [ 'page_title', 'page_latest' ],
520  array_merge( $conds, [ 'page_len > ' . intval( $maxMsgCacheEntrySize ) ] ),
521  __METHOD__ . "($code)-big"
522  );
523  foreach ( $res as $row ) {
524  // Include entries/stubs for all keys in $mostused in adaptive mode
525  if ( $adaptiveMessageCache || $this->isMainCacheable( $row->page_title )
526  ) {
527  $cache[$row->page_title] = '!TOO BIG';
528  }
529  // At least include revision ID so page changes are reflected in the hash
530  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
531  }
532 
533  // Can not inject the RevisionStore as it would break the installer since
534  // it instantiates MessageCache before the DB.
535  $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
536  // Set the text for small software-defined messages in the main cache map
537  $revQuery = $revisionStore->getQueryInfo( [ 'page' ] );
538 
539  // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
540  // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
541  // query (and also reorder it ourselves because as generated by RevisionStore it'll have
542  // `revision` first rather than `page`).
543  $revQuery['joins']['revision'] = $revQuery['joins']['page'];
544  unset( $revQuery['joins']['page'] );
545  // It isn't actually necessary to reorder $revQuery['tables'] as Database does the right thing
546  // when join conditions are given for all joins, but GergÅ‘ is wary of relying on that so pull
547  // `page` to the start.
548  $revQuery['tables'] = array_merge(
549  [ 'page' ],
550  array_diff( $revQuery['tables'], [ 'page' ] )
551  );
552 
553  $res = $dbr->select(
554  $revQuery['tables'],
555  $revQuery['fields'],
556  array_merge( $conds, [
557  'page_len <= ' . intval( $maxMsgCacheEntrySize ),
558  'page_latest = rev_id' // get the latest revision only
559  ] ),
560  __METHOD__ . "($code)-small",
561  [ 'STRAIGHT_JOIN' ],
562  $revQuery['joins']
563  );
564  $result = $revisionStore->newRevisionsFromBatch( $res, [
565  'slots' => [ SlotRecord::MAIN ],
566  'content' => true
567  ] );
568  $revisions = $result->isOK() ? $result->getValue() : [];
569  foreach ( $res as $row ) {
570  // Include entries/stubs for all keys in $mostused in adaptive mode
571  if ( $adaptiveMessageCache || $this->isMainCacheable( $row->page_title )
572  ) {
573  try {
574  $rev = $revisions[$row->rev_id] ?? null;
575  $content = $rev ? $rev->getContent( SlotRecord::MAIN ) : null;
576  $text = $this->getMessageTextFromContent( $content );
577  } catch ( Exception $ex ) {
578  $text = false;
579  }
580 
581  if ( !is_string( $text ) ) {
582  $entry = '!ERROR';
583  $this->logger->error(
584  __METHOD__
585  . ": failed to load message page text for {$row->page_title} ($code)"
586  );
587  } else {
588  $entry = ' ' . $text;
589  }
590  $cache[$row->page_title] = $entry;
591  } else {
592  // T193271: cache object gets too big and slow to generate.
593  // At least include revision ID so page changes are reflected in the hash.
594  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
595  }
596  }
597 
598  $cache['VERSION'] = MSG_CACHE_VERSION;
599  ksort( $cache );
600 
601  # Hash for validating local cache (APC). No need to take into account
602  # messages larger than $wgMaxMsgCacheEntrySize, since those are only
603  # stored and fetched from memcache.
604  $cache['HASH'] = md5( serialize( $cache ) );
605  $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
606  unset( $cache['EXCESSIVE'] ); // only needed for hash
607 
608  return $cache;
609  }
610 
617  private function isLanguageLoaded( $lang ) {
618  // It is important that this only returns true if the cache was fully
619  // populated by load(), so that callers can assume all cache keys exist.
620  // It is possible for $this->cache to be only partially populated through
621  // methods like MessageCache::replace(), which must not make this method
622  // return true (T208897). And this method must cease to return true
623  // if the language was evicted by MapCacheLRU (T230690).
624  return $this->cache->hasField( $lang, 'VERSION' );
625  }
626 
638  private function isMainCacheable( $name, $code = null ) {
639  // Convert first letter to lowercase, and strip /code suffix
640  $name = $this->contLang->lcfirst( $name );
641  // Include common conversion table pages. This also avoids problems with
642  // Installer::parse() bailing out due to disallowed DB queries (T207979).
643  if ( strpos( $name, 'conversiontable/' ) === 0 ) {
644  return true;
645  }
646  $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
647 
648  if ( $code === null ) {
649  // Bulk load
650  if ( $this->systemMessageNames === null ) {
651  $this->systemMessageNames = array_fill_keys(
652  $this->localisationCache->getSubitemList( $this->contLangCode, 'messages' ),
653  true );
654  }
655  return isset( $this->systemMessageNames[$msg] );
656  } else {
657  // Use individual subitem
658  return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
659  }
660  }
661 
668  public function replace( $title, $text ) {
669  if ( $this->mDisable ) {
670  return;
671  }
672 
673  list( $msg, $code ) = $this->figureMessage( $title );
674  if ( strpos( $title, '/' ) !== false && $code === $this->contLangCode ) {
675  // Content language overrides do not use the /<code> suffix
676  return;
677  }
678 
679  // (a) Update the process cache with the new message text
680  if ( $text === false ) {
681  // Page deleted
682  $this->cache->setField( $code, $title, '!NONEXISTENT' );
683  } else {
684  // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
685  $this->cache->setField( $code, $title, ' ' . $text );
686  }
687 
688  // (b) Update the shared caches in a deferred update with a fresh DB snapshot
690  new MessageCacheUpdate( $code, $title, $msg ),
691  DeferredUpdates::PRESEND
692  );
693  }
694 
700  public function refreshAndReplaceInternal( $code, array $replacements ) {
701  $maxMsgCacheEntrySize = MediaWikiServices::getInstance()->getMainConfig()->get( 'MaxMsgCacheEntrySize' );
702 
703  // Allow one caller at a time to avoid race conditions
704  $scopedLock = $this->getReentrantScopedLock(
705  $this->clusterCache->makeKey( 'messages', $code )
706  );
707  if ( !$scopedLock ) {
708  foreach ( $replacements as list( $title ) ) {
709  $this->logger->error(
710  __METHOD__ . ': could not acquire lock to update {title} ({code})',
711  [ 'title' => $title, 'code' => $code ] );
712  }
713 
714  return;
715  }
716 
717  // Load the existing cache to update it in the local DC cache.
718  // The other DCs will see a hash mismatch.
719  if ( $this->load( $code, self::FOR_UPDATE ) ) {
720  $cache = $this->cache->get( $code );
721  } else {
722  // Err? Fall back to loading from the database.
723  $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
724  }
725  // Check if individual cache keys should exist and update cache accordingly
726  $newTextByTitle = []; // map of (title => content)
727  $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
728  foreach ( $replacements as list( $title ) ) {
730  $page->loadPageData( $page::READ_LATEST );
731  $text = $this->getMessageTextFromContent( $page->getContent() );
732  // Remember the text for the blob store update later on
733  $newTextByTitle[$title] = $text;
734  // Note that if $text is false, then $cache should have a !NONEXISTANT entry
735  if ( !is_string( $text ) ) {
736  $cache[$title] = '!NONEXISTENT';
737  } elseif ( strlen( $text ) > $maxMsgCacheEntrySize ) {
738  $cache[$title] = '!TOO BIG';
739  $newBigTitles[$title] = $page->getLatest();
740  } else {
741  $cache[$title] = ' ' . $text;
742  }
743  }
744  // Update HASH for the new key. Incorporates various administrative keys,
745  // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
746  // and previous replace() calls), but that doesn't really matter since we
747  // only ever compare it for equality with a copy saved by saveToCaches().
748  $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
749  // Update the too-big WAN cache entries now that we have the new HASH
750  foreach ( $newBigTitles as $title => $id ) {
751  // Match logic of loadCachedMessagePageEntry()
752  $this->wanCache->set(
753  $this->bigMessageCacheKey( $cache['HASH'], $title ),
754  ' ' . $newTextByTitle[$title],
755  self::WAN_TTL
756  );
757  }
758  // Mark this cache as definitely being "latest" (non-volatile) so
759  // load() calls do not try to refresh the cache with replica DB data
760  $cache['LATEST'] = time();
761  // Update the process cache
762  $this->cache->set( $code, $cache );
763  // Pre-emptively update the local datacenter cache so things like edit filter and
764  // prevented changes are reflected immediately; these often use MediaWiki: pages.
765  // The datacenter handling replace() calls should be the same one handling edits
766  // as they require HTTP POST.
767  $this->saveToCaches( $cache, 'all', $code );
768  // Release the lock now that the cache is saved
769  ScopedCallback::consume( $scopedLock );
770 
771  // Relay the purge. Touching this check key expires cache contents
772  // and local cache (APC) validation hash across all datacenters.
773  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
774 
775  // Purge the messages in the message blob store and fire any hook handlers
776  $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
777  foreach ( $replacements as list( $title, $msg ) ) {
778  $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
779  $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
780  }
781  }
782 
789  protected function isCacheExpired( $cache ) {
790  if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
791  return true;
792  }
793  if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
794  return true;
795  }
796  if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
797  return true;
798  }
799 
800  return false;
801  }
802 
812  protected function saveToCaches( array $cache, $dest, $code = false ) {
813  if ( $dest === 'all' ) {
814  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
815  $success = $this->clusterCache->set( $cacheKey, $cache );
816  $this->setValidationHash( $code, $cache );
817  } else {
818  $success = true;
819  }
820 
821  $this->saveToLocalCache( $code, $cache );
822 
823  return $success;
824  }
825 
832  protected function getValidationHash( $code ) {
833  $curTTL = null;
834  $value = $this->wanCache->get(
835  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
836  $curTTL,
837  [ $this->getCheckKey( $code ) ]
838  );
839 
840  if ( $value ) {
841  $hash = $value['hash'];
842  if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
843  // Cache was recently updated via replace() and should be up-to-date.
844  // That method is only called in the primary datacenter and uses FOR_UPDATE.
845  // Also, it is unlikely that the current datacenter is *now* secondary one.
846  $expired = false;
847  } else {
848  // See if the "check" key was bumped after the hash was generated
849  $expired = ( $curTTL < 0 );
850  }
851  } else {
852  // No hash found at all; cache must regenerate to be safe
853  $hash = false;
854  $expired = true;
855  }
856 
857  return [ $hash, $expired ];
858  }
859 
870  protected function setValidationHash( $code, array $cache ) {
871  $this->wanCache->set(
872  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
873  [
874  'hash' => $cache['HASH'],
875  'latest' => $cache['LATEST'] ?? 0
876  ],
877  WANObjectCache::TTL_INDEFINITE
878  );
879  }
880 
886  protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
887  return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
888  }
889 
923  public function get( $key, $useDB = true, $langcode = true ) {
924  if ( is_int( $key ) ) {
925  // Fix numerical strings that somehow become ints
926  // on their way here
927  $key = (string)$key;
928  } elseif ( !is_string( $key ) ) {
929  throw new MWException( 'Non-string key given' );
930  } elseif ( $key === '' ) {
931  // Shortcut: the empty key is always missing
932  return false;
933  }
934 
935  // Normalise title-case input (with some inlining)
936  $lckey = self::normalizeKey( $key );
937 
938  $this->hookRunner->onMessageCache__get( $lckey );
939 
940  // Loop through each language in the fallback list until we find something useful
941  $message = $this->getMessageFromFallbackChain(
942  wfGetLangObj( $langcode ),
943  $lckey,
944  !$this->mDisable && $useDB
945  );
946 
947  // If we still have no message, maybe the key was in fact a full key so try that
948  if ( $message === false ) {
949  $parts = explode( '/', $lckey );
950  // We may get calls for things that are http-urls from sidebar
951  // Let's not load nonexistent languages for those
952  // They usually have more than one slash.
953  if ( count( $parts ) == 2 && $parts[1] !== '' ) {
954  $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] );
955  if ( $message === null ) {
956  $message = false;
957  }
958  }
959  }
960 
961  // Post-processing if the message exists
962  if ( $message !== false ) {
963  // Fix whitespace
964  $message = str_replace(
965  [
966  # Fix for trailing whitespace, removed by textarea
967  '&#32;',
968  # Fix for NBSP, converted to space by firefox
969  '&nbsp;',
970  '&#160;',
971  '&shy;'
972  ],
973  [
974  ' ',
975  "\u{00A0}",
976  "\u{00A0}",
977  "\u{00AD}"
978  ],
979  $message
980  );
981  }
982 
983  return $message;
984  }
985 
998  protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
999  $alreadyTried = [];
1000 
1001  // First try the requested language.
1002  $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1003  if ( $message !== false ) {
1004  return $message;
1005  }
1006 
1007  // Now try checking the site language.
1008  $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1009  return $message;
1010  }
1011 
1022  private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1023  $langcode = $lang->getCode();
1024 
1025  // Try checking the database for the requested language
1026  if ( $useDB ) {
1027  $uckey = $this->contLang->ucfirst( $lckey );
1028 
1029  if ( !isset( $alreadyTried[$langcode] ) ) {
1030  $message = $this->getMsgFromNamespace(
1031  $this->getMessagePageName( $langcode, $uckey ),
1032  $langcode
1033  );
1034  if ( $message !== false ) {
1035  return $message;
1036  }
1037  $alreadyTried[$langcode] = true;
1038  }
1039  } else {
1040  $uckey = null;
1041  }
1042 
1043  // Check the CDB cache
1044  $message = $lang->getMessage( $lckey );
1045  if ( $message !== null ) {
1046  return $message;
1047  }
1048 
1049  // Try checking the database for all of the fallback languages
1050  if ( $useDB ) {
1051  $fallbackChain = $this->languageFallback->getAll( $langcode );
1052 
1053  foreach ( $fallbackChain as $code ) {
1054  if ( isset( $alreadyTried[$code] ) ) {
1055  continue;
1056  }
1057 
1058  $message = $this->getMsgFromNamespace(
1059  $this->getMessagePageName( $code, $uckey ), $code );
1060 
1061  if ( $message !== false ) {
1062  return $message;
1063  }
1064  $alreadyTried[$code] = true;
1065  }
1066  }
1067 
1068  return false;
1069  }
1070 
1078  private function getMessagePageName( $langcode, $uckey ) {
1079  if ( $langcode === $this->contLangCode ) {
1080  // Messages created in the content language will not have the /lang extension
1081  return $uckey;
1082  } else {
1083  return "$uckey/$langcode";
1084  }
1085  }
1086 
1099  public function getMsgFromNamespace( $title, $code ) {
1100  // Load all MediaWiki page definitions into cache. Note that individual keys
1101  // already loaded into cache during this request remain in the cache, which
1102  // includes the value of hook-defined messages.
1103  $this->load( $code );
1104 
1105  $entry = $this->cache->getField( $code, $title );
1106 
1107  if ( $entry !== null ) {
1108  // Message page exists as an override of a software messages
1109  if ( substr( $entry, 0, 1 ) === ' ' ) {
1110  // The message exists and is not '!TOO BIG' or '!ERROR'
1111  return (string)substr( $entry, 1 );
1112  } elseif ( $entry === '!NONEXISTENT' ) {
1113  // The text might be '-' or missing due to some data loss
1114  return false;
1115  }
1116  // Load the message page, utilizing the individual message cache.
1117  // If the page does not exist, there will be no hook handler fallbacks.
1118  $entry = $this->loadCachedMessagePageEntry(
1119  $title,
1120  $code,
1121  $this->cache->getField( $code, 'HASH' )
1122  );
1123  } else {
1124  // Message page either does not exist or does not override a software message
1125  if ( !$this->isMainCacheable( $title, $code ) ) {
1126  // Message page does not override any software-defined message. A custom
1127  // message might be defined to have content or settings specific to the wiki.
1128  // Load the message page, utilizing the individual message cache as needed.
1129  $entry = $this->loadCachedMessagePageEntry(
1130  $title,
1131  $code,
1132  $this->cache->getField( $code, 'HASH' )
1133  );
1134  }
1135  if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1136  // Message does not have a MediaWiki page definition; try hook handlers
1137  $message = false;
1138  $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1139  if ( $message !== false ) {
1140  $this->cache->setField( $code, $title, ' ' . $message );
1141  } else {
1142  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1143  }
1144 
1145  return $message;
1146  }
1147  }
1148 
1149  if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1150  if ( $this->cacheVolatile[$code] ) {
1151  // Make sure that individual keys respect the WAN cache holdoff period too
1152  $this->logger->debug(
1153  __METHOD__ . ': loading volatile key \'{titleKey}\'',
1154  [ 'titleKey' => $title, 'code' => $code ] );
1155  } else {
1156  $this->cache->setField( $code, $title, $entry );
1157  }
1158  // The message exists, so make sure a string is returned
1159  return (string)substr( $entry, 1 );
1160  }
1161 
1162  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1163 
1164  return false;
1165  }
1166 
1173  private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1174  $fname = __METHOD__;
1175  return $this->srvCache->getWithSetCallback(
1176  $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1177  BagOStuff::TTL_HOUR,
1178  function () use ( $code, $dbKey, $hash, $fname ) {
1179  return $this->wanCache->getWithSetCallback(
1180  $this->bigMessageCacheKey( $hash, $dbKey ),
1181  self::WAN_TTL,
1182  function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1183  // Try loading the message from the database
1184  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1185  // Use newKnownCurrent() to avoid querying revision/user tables
1186  $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1187  // Injecting RevisionStore breaks installer since it
1188  // instantiates MessageCache before DB.
1189  $revision = MediaWikiServices::getInstance()
1190  ->getRevisionLookup()
1191  ->getKnownCurrentRevision( $title );
1192  if ( !$revision ) {
1193  // The wiki doesn't have a local override page. Cache absence with normal TTL.
1194  // When overrides are created, self::replace() takes care of the cache.
1195  return '!NONEXISTENT';
1196  }
1197  $content = $revision->getContent( SlotRecord::MAIN );
1198  if ( $content ) {
1199  $message = $this->getMessageTextFromContent( $content );
1200  } else {
1201  $this->logger->warning(
1202  $fname . ': failed to load page text for \'{titleKey}\'',
1203  [ 'titleKey' => $dbKey, 'code' => $code ]
1204  );
1205  $message = null;
1206  }
1207 
1208  if ( !is_string( $message ) ) {
1209  // Revision failed to load Content, or Content is incompatible with wikitext.
1210  // Possibly a temporary loading failure.
1211  $ttl = 5;
1212 
1213  return '!NONEXISTENT';
1214  }
1215 
1216  return ' ' . $message;
1217  }
1218  );
1219  }
1220  );
1221  }
1222 
1230  public function transform( $message, $interface = false, $language = null, PageReference $page = null ) {
1231  // Avoid creating parser if nothing to transform
1232  if ( strpos( $message, '{{' ) === false ) {
1233  return $message;
1234  }
1235 
1236  if ( $this->mInParser ) {
1237  return $message;
1238  }
1239 
1240  $parser = $this->getParser();
1241  if ( $parser ) {
1242  $popts = $this->getParserOptions();
1243  $popts->setInterfaceMessage( $interface );
1244  $popts->setTargetLanguage( $language );
1245 
1246  $userlang = $popts->setUserLang( $language );
1247  $this->mInParser = true;
1248  $message = $parser->transformMsg( $message, $popts, $page );
1249  $this->mInParser = false;
1250  $popts->setUserLang( $userlang );
1251  }
1252 
1253  return $message;
1254  }
1255 
1259  public function getParser() {
1260  if ( !$this->mParser ) {
1261  $parser = MediaWikiServices::getInstance()->getParser();
1262  # Clone it and store it
1263  $this->mParser = clone $parser;
1264  }
1265 
1266  return $this->mParser;
1267  }
1268 
1277  public function parse( $text, PageReference $page = null, $linestart = true,
1278  $interface = false, $language = null
1279  ) {
1280  global $wgTitle;
1281 
1282  if ( $this->mInParser ) {
1283  return htmlspecialchars( $text );
1284  }
1285 
1286  $parser = $this->getParser();
1287  $popts = $this->getParserOptions();
1288  $popts->setInterfaceMessage( $interface );
1289 
1290  if ( is_string( $language ) ) {
1291  $language = $this->langFactory->getLanguage( $language );
1292  }
1293  $popts->setTargetLanguage( $language );
1294 
1295  if ( !$page ) {
1296  $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1297  $logger->info(
1298  __METHOD__ . ' called with no title set.',
1299  [ 'exception' => new Exception ]
1300  );
1301  $page = $wgTitle;
1302  }
1303  // Sometimes $wgTitle isn't set either...
1304  if ( !$page ) {
1305  # It's not uncommon having a null $wgTitle in scripts. See r80898
1306  # Create a ghost title in such case
1307  $page = PageReferenceValue::localReference(
1308  NS_SPECIAL,
1309  'Badtitle/title not set in ' . __METHOD__
1310  );
1311  }
1312 
1313  $this->mInParser = true;
1314  $res = $parser->parse( $text, $page, $popts, $linestart );
1315  $this->mInParser = false;
1316 
1317  return $res;
1318  }
1319 
1320  public function disable() {
1321  $this->mDisable = true;
1322  }
1323 
1324  public function enable() {
1325  $this->mDisable = false;
1326  }
1327 
1340  public function isDisabled() {
1341  return $this->mDisable;
1342  }
1343 
1349  public function clear() {
1350  $langs = $this->languageNameUtils->getLanguageNames();
1351  foreach ( array_keys( $langs ) as $code ) {
1352  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1353  }
1354  $this->cache->clear();
1355  }
1356 
1361  public function figureMessage( $key ) {
1362  $pieces = explode( '/', $key );
1363  if ( count( $pieces ) < 2 ) {
1364  return [ $key, $this->contLangCode ];
1365  }
1366 
1367  $lang = array_pop( $pieces );
1368  if ( !$this->languageNameUtils->getLanguageName(
1369  $lang,
1370  LanguageNameUtils::AUTONYMS,
1371  LanguageNameUtils::DEFINED
1372  ) ) {
1373  return [ $key, $this->contLangCode ];
1374  }
1375 
1376  $message = implode( '/', $pieces );
1377 
1378  return [ $message, $lang ];
1379  }
1380 
1389  public function getAllMessageKeys( $code ) {
1390  $this->load( $code );
1391  if ( !$this->cache->has( $code ) ) {
1392  // Apparently load() failed
1393  return null;
1394  }
1395  // Remove administrative keys
1396  $cache = $this->cache->get( $code );
1397  unset( $cache['VERSION'] );
1398  unset( $cache['EXPIRY'] );
1399  unset( $cache['EXCESSIVE'] );
1400  // Remove any !NONEXISTENT keys
1401  $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1402 
1403  // Keys may appear with a capital first letter. lcfirst them.
1404  return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1405  }
1406 
1414  public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1415  $msgText = $this->getMessageTextFromContent( $content );
1416  if ( $msgText === null ) {
1417  $msgText = false; // treat as not existing
1418  }
1419 
1420  $this->replace( $linkTarget->getDBkey(), $msgText );
1421 
1422  if ( $this->contLangConverter->hasVariants() ) {
1423  $this->contLangConverter->updateConversionTable( $linkTarget );
1424  }
1425  }
1426 
1431  public function getCheckKey( $code ) {
1432  return $this->wanCache->makeKey( 'messages', $code );
1433  }
1434 
1439  private function getMessageTextFromContent( Content $content = null ) {
1440  // @TODO: could skip pseudo-messages like js/css here, based on content model
1441  if ( $content ) {
1442  // Message page exists...
1443  // XXX: Is this the right way to turn a Content object into a message?
1444  // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1445  // CssContent. MessageContent is *not* used for storing messages, it's
1446  // only used for wrapping them when needed.
1447  $msgText = $content->getWikitextForTransclusion();
1448  if ( $msgText === false || $msgText === null ) {
1449  // This might be due to some kind of misconfiguration...
1450  $msgText = null;
1451  $this->logger->warning(
1452  __METHOD__ . ": message content doesn't provide wikitext "
1453  . "(content model: " . $content->getModel() . ")" );
1454  }
1455  } else {
1456  // Message page does not exist...
1457  $msgText = false;
1458  }
1459 
1460  return $msgText;
1461  }
1462 
1468  private function bigMessageCacheKey( $hash, $title ) {
1469  return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1470  }
1471 }
MessageCache\$mParser
Parser $mParser
Definition: MessageCache.php:100
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:45
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:52
MessageCache\$contLangConverter
ILanguageConverter $contLangConverter
Definition: MessageCache.php:118
MessageCache\setValidationHash
setValidationHash( $code, array $cache)
Set the md5 used to validate the local disk cache.
Definition: MessageCache.php:870
MessageCache\updateMessageOverride
updateMessageOverride(LinkTarget $linkTarget, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
Definition: MessageCache.php:1414
MessageCache\isLanguageLoaded
isLanguageLoaded( $lang)
Whether the language was loaded and its data is still in the process cache.
Definition: MessageCache.php:617
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:72
MessageCache\$clusterCache
BagOStuff $clusterCache
Definition: MessageCache.php:110
MessageCache\normalizeKey
static normalizeKey( $key)
Normalize message key input.
Definition: MessageCache.php:136
EmptyBagOStuff
A BagOStuff object with no objects in it.
Definition: EmptyBagOStuff.php:29
MessageCache\saveToCaches
saveToCaches(array $cache, $dest, $code=false)
Shortcut to update caches.
Definition: MessageCache.php:812
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:203
MessageCache\enable
enable()
Definition: MessageCache.php:1324
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
MessageCache\$mParserOptions
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
Definition: MessageCache.php:98
true
return true
Definition: router.php:90
MediaWiki\Languages\LanguageFactory
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: LanguageFactory.php:42
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1649
MessageCache\$mInParser
bool $mInParser
Definition: MessageCache.php:105
MessageCache\loadCachedMessagePageEntry
loadCachedMessagePageEntry( $dbKey, $code, $hash)
Definition: MessageCache.php:1173
MessageCache\$logger
LoggerInterface $logger
Definition: MessageCache.php:60
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:125
ParserOptions\newFromAnon
static newFromAnon()
Get a ParserOptions object for an anonymous user.
Definition: ParserOptions.php:1032
MediaWiki\Languages\LanguageFallback
Definition: LanguageFallback.php:31
MessageCache\setLogger
setLogger(LoggerInterface $logger)
Definition: MessageCache.php:197
MessageCache\LOCK_TTL
const LOCK_TTL
How long memcached locks last.
Definition: MessageCache.php:58
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:86
MessageCache\saveToLocalCache
saveToLocalCache( $code, $cache)
Save the cache to APC.
Definition: MessageCache.php:247
$success
$success
Definition: NoLocalSettings.php:42
$res
$res
Definition: testCompression.php:57
serialize
serialize()
Definition: ApiMessageTrait.php:138
$revQuery
$revQuery
Definition: testCompression.php:56
Page\PageReference
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Definition: PageReference.php:49
MediaWiki\Languages\LanguageNameUtils
A service that provides utilities to do with language names and codes.
Definition: LanguageNameUtils.php:43
MessageCache\getValidationHash
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
Definition: MessageCache.php:832
$dbr
$dbr
Definition: testCompression.php:54
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:53
MessageCache\getMessageTextFromContent
getMessageTextFromContent(Content $content=null)
Definition: MessageCache.php:1439
MessageCache\$hookRunner
HookRunner $hookRunner
Definition: MessageCache.php:128
MessageCache\loadFromDB
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
Definition: MessageCache.php:478
MWException
MediaWiki exception.
Definition: MWException.php:29
MessageCache\getCheckKey
getCheckKey( $code)
Definition: MessageCache.php:1431
MessageCache\getMsgFromNamespace
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
Definition: MessageCache.php:1099
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
MessageCache\bigMessageCacheKey
bigMessageCacheKey( $hash, $title)
Definition: MessageCache.php:1468
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2186
MessageCache\isMainCacheable
isMainCacheable( $name, $code=null)
Can the given DB key be added to the main cache blob? To reduce the impact of abuse of the MediaWiki ...
Definition: MessageCache.php:638
MessageCache\$languageFallback
LanguageFallback $languageFallback
Definition: MessageCache.php:126
MessageCache\getMessagePageName
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
Definition: MessageCache.php:1078
MSG_CACHE_VERSION
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
Definition: MessageCache.php:44
MapCacheLRU
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:36
MessageCache\$cacheVolatile
bool[] $cacheVolatile
Map of (language code => boolean)
Definition: MessageCache.php:86
MessageCache\figureMessage
figureMessage( $key)
Definition: MessageCache.php:1361
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1117
MessageCache\$srvCache
BagOStuff $srvCache
Definition: MessageCache.php:112
$title
$title
Definition: testCompression.php:38
MessageCache\replace
replace( $title, $text)
Updates cache as necessary when message page is changed.
Definition: MessageCache.php:668
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:648
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1678
MessageCache\getMessageFromFallbackChain
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
Definition: MessageCache.php:998
MessageCacheUpdate
Message cache purging and in-place update handler for specific message page changes.
Definition: MessageCacheUpdate.php:32
MessageCache\FOR_UPDATE
const FOR_UPDATE
Definition: MessageCache.php:53
MessageCache\WAIT_SEC
const WAIT_SEC
How long to wait for memcached locks.
Definition: MessageCache.php:56
$wgTitle
$wgTitle
Definition: Setup.php:879
MessageCache\$cache
MapCacheLRU $cache
Process cache of loaded messages that are defined in MediaWiki namespace.
Definition: MessageCache.php:74
$content
$content
Definition: router.php:76
MessageCache\$languageNameUtils
LanguageNameUtils $languageNameUtils
Definition: MessageCache.php:124
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:29
Language\getCode
getCode()
Get the internal language code for this language object.
Definition: Language.php:4348
MessageCache\parse
parse( $text, PageReference $page=null, $linestart=true, $interface=false, $language=null)
Definition: MessageCache.php:1277
ParserOptions\newFromContext
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Definition: ParserOptions.php:1065
MessageCache\$contLangCode
string $contLangCode
Definition: MessageCache.php:116
MessageCache\clear
clear()
Clear all stored messages in global and local cache.
Definition: MessageCache.php:1349
DB_PRIMARY
const DB_PRIMARY
Definition: defines.php:27
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:131
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part of the link target, in canonical database form.
MessageCache\getReentrantScopedLock
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
Definition: MessageCache.php:886
MapCacheLRU\set
set( $key, $value, $rank=self::RANK_TOP)
Set a key/value pair.
Definition: MapCacheLRU.php:109
MessageCache\$localisationCache
LocalisationCache $localisationCache
Definition: MessageCache.php:122
LocalisationCache
Class for caching the contents of localisation files, Messages*.php and *.i18n.php.
Definition: LocalisationCache.php:43
Parser
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition: Parser.php:91
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:484
Content
Base interface for content objects.
Definition: Content.php:35
MessageCache\getParser
getParser()
Definition: MessageCache.php:1259
MessageCache\getLocalCache
getLocalCache( $code)
Try to load the cache from APC.
Definition: MessageCache.php:235
MessageCache\$langFactory
LanguageFactory $langFactory
Definition: MessageCache.php:120
MessageCache\refreshAndReplaceInternal
refreshAndReplaceInternal( $code, array $replacements)
Definition: MessageCache.php:700
MessageCache\$systemMessageNames
array $systemMessageNames
Map of (lowercase message key => unused) for all software defined messages.
Definition: MessageCache.php:81
MessageCache\loadFromDBWithLock
loadFromDBWithLock( $code, array &$where, $mode=null)
Definition: MessageCache.php:416
MessageCache\$mDisable
bool $mDisable
Should mean that database cannot be used, but check.
Definition: MessageCache.php:92
MessageCache\load
load( $code, $mode=null)
Loads messages from caches or from database in this order: (1) local message cache (if $wgUseLocalMes...
Definition: MessageCache.php:273
WikiPage\factory
static factory(PageIdentity $pageIdentity)
Create a WikiPage object of the appropriate class for the given PageIdentity.
Definition: WikiPage.php:203
MessageCache\__construct
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, Language $contLang, ILanguageConverter $contLangConverter, LoggerInterface $logger, array $options, LanguageFactory $langFactory, LocalisationCache $localisationCache, LanguageNameUtils $languageNameUtils, LanguageFallback $languageFallback, HookContainer $hookContainer)
Definition: MessageCache.php:164
MessageCache\$wanCache
WANObjectCache $wanCache
Definition: MessageCache.php:108
Page\PageReferenceValue
Immutable value object representing a page reference.
Definition: PageReferenceValue.php:42
MapCacheLRU\get
get( $key, $maxAge=INF, $default=null)
Get the value for a key.
Definition: MapCacheLRU.php:172
MessageCache\isDisabled
isDisabled()
Whether DB/cache usage is disabled for determining messages.
Definition: MessageCache.php:1340
MessageCache\getParserOptions
getParserOptions()
ParserOptions is lazy initialised.
Definition: MessageCache.php:206
MessageCache\isCacheExpired
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
Definition: MessageCache.php:789
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
MessageCache\transform
transform( $message, $interface=false, $language=null, PageReference $page=null)
Definition: MessageCache.php:1230
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:557
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
MessageCache\disable
disable()
Definition: MessageCache.php:1320
MessageCache
Cache of messages that are defined by MediaWiki namespace pages or by hooks.
Definition: MessageCache.php:52
MessageCache\getMessageForLang
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
Definition: MessageCache.php:1022
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:42
MediaWiki\Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:40
MessageCache\getAllMessageKeys
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
Definition: MessageCache.php:1389
MessageCache\$contLang
Language $contLang
Definition: MessageCache.php:114