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