MediaWiki  master
MessageCache.php
Go to the documentation of this file.
1 <?php
30 use Psr\Log\LoggerAwareInterface;
31 use Psr\Log\LoggerInterface;
33 use Wikimedia\ScopedCallback;
34 
39 define( 'MSG_CACHE_VERSION', 2 );
40 
47 class MessageCache implements LoggerAwareInterface {
48  const FOR_UPDATE = 1; // force message reload
49 
51  const WAIT_SEC = 15;
53  const LOCK_TTL = 30;
54 
59  const WAN_TTL = IExpiringStore::TTL_DAY;
60 
62  private $logger;
63 
69  protected $cache;
70 
76  protected $overridable;
77 
81  protected $cacheVolatile = [];
82 
87  protected $mDisable;
88 
93  protected $mParserOptions;
95  protected $mParser;
96 
100  protected $mInParser = false;
101 
103  protected $wanCache;
105  protected $clusterCache;
107  protected $srvCache;
109  protected $contLang;
113  protected $langFactory;
119  protected $languageFallback;
120 
128  public static function singleton() {
129  return MediaWikiServices::getInstance()->getMessageCache();
130  }
131 
138  public static function normalizeKey( $key ) {
139  $lckey = strtr( $key, ' ', '_' );
140  if ( ord( $lckey ) < 128 ) {
141  $lckey[0] = strtolower( $lckey[0] );
142  } else {
143  $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
144  }
145 
146  return $lckey;
147  }
148 
165  public function __construct(
168  BagOStuff $serverCache,
171  LoggerInterface $logger,
172  array $options,
177  ) {
178  $this->wanCache = $wanCache;
179  $this->clusterCache = $clusterCache;
180  $this->srvCache = $serverCache;
181  $this->contLang = $contLang;
182  $this->contLangConverter = $contLangConverter;
183  $this->logger = $logger;
184  $this->langFactory = $langFactory;
185  $this->localisationCache = $localisationCache;
186  $this->languageNameUtils = $languageNameUtils;
187  $this->languageFallback = $languageFallback;
188 
189  $this->cache = new MapCacheLRU( 5 ); // limit size for sanity
190 
191  $this->mDisable = !( $options['useDB'] ?? true );
192  }
193 
194  public function setLogger( LoggerInterface $logger ) {
195  $this->logger = $logger;
196  }
197 
203  private function getParserOptions() {
204  global $wgUser;
205 
206  if ( !$this->mParserOptions ) {
207  if ( !$wgUser || !$wgUser->isSafeToLoad() ) {
208  // $wgUser isn't available yet, so don't try to get a
209  // ParserOptions for it. And don't cache this ParserOptions
210  // either.
212  $po->setAllowUnsafeRawHtml( false );
213  $po->setTidy( true );
214  return $po;
215  }
216 
217  $this->mParserOptions = new ParserOptions( $wgUser );
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  // For the same reason, tidy the output!
223  $this->mParserOptions->setTidy( true );
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  $this->overridable =
284  array_flip( $this->localisationCache->getSubitemList( $code, 'messages' ) );
285 
286  # 8 lines of code just to say (once) that message cache is disabled
287  if ( $this->mDisable ) {
288  static $shownDisabled = false;
289  if ( !$shownDisabled ) {
290  $this->logger->debug( __METHOD__ . ': disabled' );
291  $shownDisabled = true;
292  }
293 
294  return true;
295  }
296 
297  # Loading code starts
298  $success = false; # Keep track of success
299  $staleCache = false; # a cache array with expired data, or false if none has been loaded
300  $where = []; # Debug info, delayed to avoid spamming debug log too much
301 
302  # Hash of the contents is stored in memcache, to detect if data-center cache
303  # or local cache goes out of date (e.g. due to replace() on some other server)
304  list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
305  $this->cacheVolatile[$code] = $hashVolatile;
306 
307  # Try the local cache and check against the cluster hash key...
308  $cache = $this->getLocalCache( $code );
309  if ( !$cache ) {
310  $where[] = 'local cache is empty';
311  } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
312  $where[] = 'local cache has the wrong hash';
313  $staleCache = $cache;
314  } elseif ( $this->isCacheExpired( $cache ) ) {
315  $where[] = 'local cache is expired';
316  $staleCache = $cache;
317  } elseif ( $hashVolatile ) {
318  $where[] = 'local cache validation key is expired/volatile';
319  $staleCache = $cache;
320  } else {
321  $where[] = 'got from local cache';
322  $this->cache->set( $code, $cache );
323  $success = true;
324  }
325 
326  if ( !$success ) {
327  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
328  # Try the global cache. If it is empty, try to acquire a lock. If
329  # the lock can't be acquired, wait for the other thread to finish
330  # and then try the global cache a second time.
331  for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
332  if ( $hashVolatile && $staleCache ) {
333  # Do not bother fetching the whole cache blob to avoid I/O.
334  # Instead, just try to get the non-blocking $statusKey lock
335  # below, and use the local stale value if it was not acquired.
336  $where[] = 'global cache is presumed expired';
337  } else {
338  $cache = $this->clusterCache->get( $cacheKey );
339  if ( !$cache ) {
340  $where[] = 'global cache is empty';
341  } elseif ( $this->isCacheExpired( $cache ) ) {
342  $where[] = 'global cache is expired';
343  $staleCache = $cache;
344  } elseif ( $hashVolatile ) {
345  # DB results are replica DB lag prone until the holdoff TTL passes.
346  # By then, updates should be reflected in loadFromDBWithLock().
347  # One thread regenerates the cache while others use old values.
348  $where[] = 'global cache is expired/volatile';
349  $staleCache = $cache;
350  } else {
351  $where[] = 'got from global cache';
352  $this->cache->set( $code, $cache );
353  $this->saveToCaches( $cache, 'local-only', $code );
354  $success = true;
355  }
356  }
357 
358  if ( $success ) {
359  # Done, no need to retry
360  break;
361  }
362 
363  # We need to call loadFromDB. Limit the concurrency to one process.
364  # This prevents the site from going down when the cache expires.
365  # Note that the DB slam protection lock here is non-blocking.
366  $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
367  if ( $loadStatus === true ) {
368  $success = true;
369  break;
370  } elseif ( $staleCache ) {
371  # Use the stale cache while some other thread constructs the new one
372  $where[] = 'using stale cache';
373  $this->cache->set( $code, $staleCache );
374  $success = true;
375  break;
376  } elseif ( $failedAttempts > 0 ) {
377  # Already blocked once, so avoid another lock/unlock cycle.
378  # This case will typically be hit if memcached is down, or if
379  # loadFromDB() takes longer than LOCK_WAIT.
380  $where[] = "could not acquire status key.";
381  break;
382  } elseif ( $loadStatus === 'cantacquire' ) {
383  # Wait for the other thread to finish, then retry. Normally,
384  # the memcached get() will then yield the other thread's result.
385  $where[] = 'waited for other thread to complete';
386  $this->getReentrantScopedLock( $cacheKey );
387  } else {
388  # Disable cache; $loadStatus is 'disabled'
389  break;
390  }
391  }
392  }
393 
394  if ( !$success ) {
395  $where[] = 'loading FAILED - cache is disabled';
396  $this->mDisable = true;
397  $this->cache->set( $code, [] );
398  $this->logger->error( __METHOD__ . ": Failed to load $code" );
399  # This used to throw an exception, but that led to nasty side effects like
400  # the whole wiki being instantly down if the memcached server died
401  }
402 
403  if ( !$this->isLanguageLoaded( $code ) ) { // sanity
404  throw new LogicException( "Process cache for '$code' should be set by now." );
405  }
406 
407  $info = implode( ', ', $where );
408  $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
409 
410  return $success;
411  }
412 
419  protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
420  # If cache updates on all levels fail, give up on message overrides.
421  # This is to avoid easy site outages; see $saveSuccess comments below.
422  $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
423  $status = $this->clusterCache->get( $statusKey );
424  if ( $status === 'error' ) {
425  $where[] = "could not load; method is still globally disabled";
426  return 'disabled';
427  }
428 
429  # Now let's regenerate
430  $where[] = 'loading from database';
431 
432  # Lock the cache to prevent conflicting writes.
433  # This lock is non-blocking so stale cache can quickly be used.
434  # Note that load() will call a blocking getReentrantScopedLock()
435  # after this if it really need to wait for any current thread.
436  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
437  $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
438  if ( !$scopedLock ) {
439  $where[] = 'could not acquire main lock';
440  return 'cantacquire';
441  }
442 
443  $cache = $this->loadFromDB( $code, $mode );
444  $this->cache->set( $code, $cache );
445  $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
446 
447  if ( !$saveSuccess ) {
461  if ( $this->srvCache instanceof EmptyBagOStuff ) {
462  $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
463  $where[] = 'could not save cache, disabled globally for 5 minutes';
464  } else {
465  $where[] = "could not save global cache";
466  }
467  }
468 
469  return true;
470  }
471 
481  protected function loadFromDB( $code, $mode = null ) {
483 
484  // (T164666) The query here performs really poorly on WMF's
485  // contributions replicas. We don't have a way to say "any group except
486  // contributions", so for the moment let's specify 'api'.
487  // @todo: Get rid of this hack.
488  $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
489 
490  $cache = [];
491 
492  $mostused = []; // list of "<cased message key>/<code>"
493  if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
494  if ( !$this->cache->has( $wgLanguageCode ) ) {
495  $this->load( $wgLanguageCode );
496  }
497  $mostused = array_keys( $this->cache->get( $wgLanguageCode ) );
498  foreach ( $mostused as $key => $value ) {
499  $mostused[$key] = "$value/$code";
500  }
501  }
502 
503  // Get the list of software-defined messages in core/extensions
504  $overridable =
505  array_flip( $this->localisationCache->getSubitemList( $wgLanguageCode, 'messages' ) );
506 
507  // Common conditions
508  $conds = [
509  'page_is_redirect' => 0,
510  'page_namespace' => NS_MEDIAWIKI,
511  ];
512  if ( count( $mostused ) ) {
513  $conds['page_title'] = $mostused;
514  } elseif ( $code !== $wgLanguageCode ) {
515  $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
516  } else {
517  # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
518  # other than language code.
519  $conds[] = 'page_title NOT' .
520  $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
521  }
522 
523  // Set the stubs for oversized software-defined messages in the main cache map
524  $res = $dbr->select(
525  'page',
526  [ 'page_title', 'page_latest' ],
527  array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
528  __METHOD__ . "($code)-big"
529  );
530  foreach ( $res as $row ) {
531  // Include entries/stubs for all keys in $mostused in adaptive mode
532  if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $row->page_title, $overridable ) ) {
533  $cache[$row->page_title] = '!TOO BIG';
534  }
535  // At least include revision ID so page changes are reflected in the hash
536  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
537  }
538 
539  // Can not inject the RevisionStore as it would break the installer since
540  // it instantiates MessageCache before the DB.
541  $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
542  // Set the text for small software-defined messages in the main cache map
543  $revQuery = $revisionStore->getQueryInfo( [ 'page', 'user' ] );
544 
545  // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
546  // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
547  // query (and also reorder it ourselves because as generated by RevisionStore it'll have
548  // `revision` first rather than `page`).
549  $revQuery['joins']['revision'] = $revQuery['joins']['page'];
550  unset( $revQuery['joins']['page'] );
551  // It isn't actually necesssary to reorder $revQuery['tables'] as Database does the right thing
552  // when join conditions are given for all joins, but GergÅ‘ is wary of relying on that so pull
553  // `page` to the start.
554  $revQuery['tables'] = array_merge(
555  [ 'page' ],
556  array_diff( $revQuery['tables'], [ 'page' ] )
557  );
558 
559  $res = $dbr->select(
560  $revQuery['tables'],
561  $revQuery['fields'],
562  array_merge( $conds, [
563  'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ),
564  'page_latest = rev_id' // get the latest revision only
565  ] ),
566  __METHOD__ . "($code)-small",
567  [ 'STRAIGHT_JOIN' ],
568  $revQuery['joins']
569  );
570  foreach ( $res as $row ) {
571  // Include entries/stubs for all keys in $mostused in adaptive mode
572  if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $row->page_title, $overridable ) ) {
573  try {
574  $rev = $revisionStore->newRevisionFromRow( $row, 0, Title::newFromRow( $row ) );
575  $content = $rev->getContent( MediaWiki\Revision\SlotRecord::MAIN );
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 patially 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 
632  private function isMainCacheable( $name, array $overridable ) {
633  // Convert first letter to lowercase, and strip /code suffix
634  $name = $this->contLang->lcfirst( $name );
635  $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
636  // Include common conversion table pages. This also avoids problems with
637  // Installer::parse() bailing out due to disallowed DB queries (T207979).
638  return ( isset( $overridable[$msg] ) || strpos( $name, 'conversiontable/' ) === 0 );
639  }
640 
647  public function replace( $title, $text ) {
648  global $wgLanguageCode;
649 
650  if ( $this->mDisable ) {
651  return;
652  }
653 
654  list( $msg, $code ) = $this->figureMessage( $title );
655  if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
656  // Content language overrides do not use the /<code> suffix
657  return;
658  }
659 
660  // (a) Update the process cache with the new message text
661  if ( $text === false ) {
662  // Page deleted
663  $this->cache->setField( $code, $title, '!NONEXISTENT' );
664  } else {
665  // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
666  $this->cache->setField( $code, $title, ' ' . $text );
667  }
668 
669  // (b) Update the shared caches in a deferred update with a fresh DB snapshot
671  new MessageCacheUpdate( $code, $title, $msg ),
673  );
674  }
675 
681  public function refreshAndReplaceInternal( $code, array $replacements ) {
683 
684  // Allow one caller at a time to avoid race conditions
685  $scopedLock = $this->getReentrantScopedLock(
686  $this->clusterCache->makeKey( 'messages', $code )
687  );
688  if ( !$scopedLock ) {
689  foreach ( $replacements as list( $title ) ) {
690  $this->logger->error(
691  __METHOD__ . ': could not acquire lock to update {title} ({code})',
692  [ 'title' => $title, 'code' => $code ] );
693  }
694 
695  return;
696  }
697 
698  // Load the existing cache to update it in the local DC cache.
699  // The other DCs will see a hash mismatch.
700  if ( $this->load( $code, self::FOR_UPDATE ) ) {
701  $cache = $this->cache->get( $code );
702  } else {
703  // Err? Fall back to loading from the database.
704  $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
705  }
706  // Check if individual cache keys should exist and update cache accordingly
707  $newTextByTitle = []; // map of (title => content)
708  $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
709  foreach ( $replacements as list( $title ) ) {
711  $page->loadPageData( $page::READ_LATEST );
712  $text = $this->getMessageTextFromContent( $page->getContent() );
713  // Remember the text for the blob store update later on
714  $newTextByTitle[$title] = $text;
715  // Note that if $text is false, then $cache should have a !NONEXISTANT entry
716  if ( !is_string( $text ) ) {
717  $cache[$title] = '!NONEXISTENT';
718  } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
719  $cache[$title] = '!TOO BIG';
720  $newBigTitles[$title] = $page->getLatest();
721  } else {
722  $cache[$title] = ' ' . $text;
723  }
724  }
725  // Update HASH for the new key. Incorporates various administrative keys,
726  // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
727  // and previous replace() calls), but that doesn't really matter since we
728  // only ever compare it for equality with a copy saved by saveToCaches().
729  $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
730  // Update the too-big WAN cache entries now that we have the new HASH
731  foreach ( $newBigTitles as $title => $id ) {
732  // Match logic of loadCachedMessagePageEntry()
733  $this->wanCache->set(
734  $this->bigMessageCacheKey( $cache['HASH'], $title ),
735  ' ' . $newTextByTitle[$title],
736  self::WAN_TTL
737  );
738  }
739  // Mark this cache as definitely being "latest" (non-volatile) so
740  // load() calls do not try to refresh the cache with replica DB data
741  $cache['LATEST'] = time();
742  // Update the process cache
743  $this->cache->set( $code, $cache );
744  // Pre-emptively update the local datacenter cache so things like edit filter and
745  // blacklist changes are reflected immediately; these often use MediaWiki: pages.
746  // The datacenter handling replace() calls should be the same one handling edits
747  // as they require HTTP POST.
748  $this->saveToCaches( $cache, 'all', $code );
749  // Release the lock now that the cache is saved
750  ScopedCallback::consume( $scopedLock );
751 
752  // Relay the purge. Touching this check key expires cache contents
753  // and local cache (APC) validation hash across all datacenters.
754  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
755 
756  // Purge the messages in the message blob store and fire any hook handlers
757  $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
758  foreach ( $replacements as list( $title, $msg ) ) {
759  $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
760  Hooks::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
761  }
762  }
763 
770  protected function isCacheExpired( $cache ) {
771  if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
772  return true;
773  }
774  if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
775  return true;
776  }
777  if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
778  return true;
779  }
780 
781  return false;
782  }
783 
793  protected function saveToCaches( array $cache, $dest, $code = false ) {
794  if ( $dest === 'all' ) {
795  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
796  $success = $this->clusterCache->set( $cacheKey, $cache );
797  $this->setValidationHash( $code, $cache );
798  } else {
799  $success = true;
800  }
801 
802  $this->saveToLocalCache( $code, $cache );
803 
804  return $success;
805  }
806 
813  protected function getValidationHash( $code ) {
814  $curTTL = null;
815  $value = $this->wanCache->get(
816  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
817  $curTTL,
818  [ $this->getCheckKey( $code ) ]
819  );
820 
821  if ( $value ) {
822  $hash = $value['hash'];
823  if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
824  // Cache was recently updated via replace() and should be up-to-date.
825  // That method is only called in the primary datacenter and uses FOR_UPDATE.
826  // Also, it is unlikely that the current datacenter is *now* secondary one.
827  $expired = false;
828  } else {
829  // See if the "check" key was bumped after the hash was generated
830  $expired = ( $curTTL < 0 );
831  }
832  } else {
833  // No hash found at all; cache must regenerate to be safe
834  $hash = false;
835  $expired = true;
836  }
837 
838  return [ $hash, $expired ];
839  }
840 
851  protected function setValidationHash( $code, array $cache ) {
852  $this->wanCache->set(
853  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
854  [
855  'hash' => $cache['HASH'],
856  'latest' => $cache['LATEST'] ?? 0
857  ],
858  WANObjectCache::TTL_INDEFINITE
859  );
860  }
861 
867  protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
868  return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
869  }
870 
904  public function get( $key, $useDB = true, $langcode = true ) {
905  if ( is_int( $key ) ) {
906  // Fix numerical strings that somehow become ints
907  // on their way here
908  $key = (string)$key;
909  } elseif ( !is_string( $key ) ) {
910  throw new MWException( 'Non-string key given' );
911  } elseif ( $key === '' ) {
912  // Shortcut: the empty key is always missing
913  return false;
914  }
915 
916  // Normalise title-case input (with some inlining)
917  $lckey = self::normalizeKey( $key );
918 
919  Hooks::run( 'MessageCache::get', [ &$lckey ] );
920 
921  // Loop through each language in the fallback list until we find something useful
922  $message = $this->getMessageFromFallbackChain(
923  wfGetLangObj( $langcode ),
924  $lckey,
925  !$this->mDisable && $useDB
926  );
927 
928  // If we still have no message, maybe the key was in fact a full key so try that
929  if ( $message === false ) {
930  $parts = explode( '/', $lckey );
931  // We may get calls for things that are http-urls from sidebar
932  // Let's not load nonexistent languages for those
933  // They usually have more than one slash.
934  if ( count( $parts ) == 2 && $parts[1] !== '' ) {
935  $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] );
936  if ( $message === null ) {
937  $message = false;
938  }
939  }
940  }
941 
942  // Post-processing if the message exists
943  if ( $message !== false ) {
944  // Fix whitespace
945  $message = str_replace(
946  [
947  # Fix for trailing whitespace, removed by textarea
948  '&#32;',
949  # Fix for NBSP, converted to space by firefox
950  '&nbsp;',
951  '&#160;',
952  '&shy;'
953  ],
954  [
955  ' ',
956  "\u{00A0}",
957  "\u{00A0}",
958  "\u{00AD}"
959  ],
960  $message
961  );
962  }
963 
964  return $message;
965  }
966 
979  protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
980  $alreadyTried = [];
981 
982  // First try the requested language.
983  $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
984  if ( $message !== false ) {
985  return $message;
986  }
987 
988  // Now try checking the site language.
989  $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
990  return $message;
991  }
992 
1003  private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1004  $langcode = $lang->getCode();
1005 
1006  // Try checking the database for the requested language
1007  if ( $useDB ) {
1008  $uckey = $this->contLang->ucfirst( $lckey );
1009 
1010  if ( !isset( $alreadyTried[$langcode] ) ) {
1011  $message = $this->getMsgFromNamespace(
1012  $this->getMessagePageName( $langcode, $uckey ),
1013  $langcode
1014  );
1015  if ( $message !== false ) {
1016  return $message;
1017  }
1018  $alreadyTried[$langcode] = true;
1019  }
1020  } else {
1021  $uckey = null;
1022  }
1023 
1024  // Check the CDB cache
1025  $message = $lang->getMessage( $lckey );
1026  if ( $message !== null ) {
1027  return $message;
1028  }
1029 
1030  // Try checking the database for all of the fallback languages
1031  if ( $useDB ) {
1032  $fallbackChain = $this->languageFallback->getAll( $langcode );
1033 
1034  foreach ( $fallbackChain as $code ) {
1035  if ( isset( $alreadyTried[$code] ) ) {
1036  continue;
1037  }
1038 
1039  $message = $this->getMsgFromNamespace(
1040  $this->getMessagePageName( $code, $uckey ), $code );
1041 
1042  if ( $message !== false ) {
1043  return $message;
1044  }
1045  $alreadyTried[$code] = true;
1046  }
1047  }
1048 
1049  return false;
1050  }
1051 
1059  private function getMessagePageName( $langcode, $uckey ) {
1060  global $wgLanguageCode;
1061 
1062  if ( $langcode === $wgLanguageCode ) {
1063  // Messages created in the content language will not have the /lang extension
1064  return $uckey;
1065  } else {
1066  return "$uckey/$langcode";
1067  }
1068  }
1069 
1082  public function getMsgFromNamespace( $title, $code ) {
1083  // Load all MediaWiki page definitions into cache. Note that individual keys
1084  // already loaded into cache during this request remain in the cache, which
1085  // includes the value of hook-defined messages.
1086  $this->load( $code );
1087 
1088  $entry = $this->cache->getField( $code, $title );
1089 
1090  if ( $entry !== null ) {
1091  // Message page exists as an override of a software messages
1092  if ( substr( $entry, 0, 1 ) === ' ' ) {
1093  // The message exists and is not '!TOO BIG' or '!ERROR'
1094  return (string)substr( $entry, 1 );
1095  } elseif ( $entry === '!NONEXISTENT' ) {
1096  // The text might be '-' or missing due to some data loss
1097  return false;
1098  }
1099  // Load the message page, utilizing the individual message cache.
1100  // If the page does not exist, there will be no hook handler fallbacks.
1101  $entry = $this->loadCachedMessagePageEntry(
1102  $title,
1103  $code,
1104  $this->cache->getField( $code, 'HASH' )
1105  );
1106  } else {
1107  // Message page either does not exist or does not override a software message
1108  if ( !$this->isMainCacheable( $title, $this->overridable ) ) {
1109  // Message page does not override any software-defined message. A custom
1110  // message might be defined to have content or settings specific to the wiki.
1111  // Load the message page, utilizing the individual message cache as needed.
1112  $entry = $this->loadCachedMessagePageEntry(
1113  $title,
1114  $code,
1115  $this->cache->getField( $code, 'HASH' )
1116  );
1117  }
1118  if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1119  // Message does not have a MediaWiki page definition; try hook handlers
1120  $message = false;
1121  Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1122  if ( $message !== false ) {
1123  $this->cache->setField( $code, $title, ' ' . $message );
1124  } else {
1125  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1126  }
1127 
1128  return $message;
1129  }
1130  }
1131 
1132  if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1133  if ( $this->cacheVolatile[$code] ) {
1134  // Make sure that individual keys respect the WAN cache holdoff period too
1135  $this->logger->debug(
1136  __METHOD__ . ': loading volatile key \'{titleKey}\'',
1137  [ 'titleKey' => $title, 'code' => $code ] );
1138  } else {
1139  $this->cache->setField( $code, $title, $entry );
1140  }
1141  // The message exists, so make sure a string is returned
1142  return (string)substr( $entry, 1 );
1143  }
1144 
1145  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1146 
1147  return false;
1148  }
1149 
1156  private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1157  $fname = __METHOD__;
1158  return $this->srvCache->getWithSetCallback(
1159  $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1160  BagOStuff::TTL_HOUR,
1161  function () use ( $code, $dbKey, $hash, $fname ) {
1162  return $this->wanCache->getWithSetCallback(
1163  $this->bigMessageCacheKey( $hash, $dbKey ),
1164  self::WAN_TTL,
1165  function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1166  // Try loading the message from the database
1167  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1168  // Use newKnownCurrent() to avoid querying revision/user tables
1169  $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1170  // Injecting RevisionStore breaks installer since it
1171  // instantiates MessageCache before DB.
1172  $revision = MediaWikiServices::getInstance()
1173  ->getRevisionLookup()
1174  ->getKnownCurrentRevision( $title );
1175  if ( !$revision ) {
1176  // The wiki doesn't have a local override page. Cache absence with normal TTL.
1177  // When overrides are created, self::replace() takes care of the cache.
1178  return '!NONEXISTENT';
1179  }
1180  $content = $revision->getContent( SlotRecord::MAIN );
1181  if ( $content ) {
1182  $message = $this->getMessageTextFromContent( $content );
1183  } else {
1184  $this->logger->warning(
1185  $fname . ': failed to load page text for \'{titleKey}\'',
1186  [ 'titleKey' => $dbKey, 'code' => $code ]
1187  );
1188  $message = null;
1189  }
1190 
1191  if ( !is_string( $message ) ) {
1192  // Revision failed to load Content, or Content is incompatible with wikitext.
1193  // Possibly a temporary loading failure.
1194  $ttl = 5;
1195 
1196  return '!NONEXISTENT';
1197  }
1198 
1199  return ' ' . $message;
1200  }
1201  );
1202  }
1203  );
1204  }
1205 
1213  public function transform( $message, $interface = false, $language = null, $title = null ) {
1214  // Avoid creating parser if nothing to transform
1215  if ( strpos( $message, '{{' ) === false ) {
1216  return $message;
1217  }
1218 
1219  if ( $this->mInParser ) {
1220  return $message;
1221  }
1222 
1223  $parser = $this->getParser();
1224  if ( $parser ) {
1225  $popts = $this->getParserOptions();
1226  $popts->setInterfaceMessage( $interface );
1227  $popts->setTargetLanguage( $language );
1228 
1229  $userlang = $popts->setUserLang( $language );
1230  $this->mInParser = true;
1231  $message = $parser->transformMsg( $message, $popts, $title );
1232  $this->mInParser = false;
1233  $popts->setUserLang( $userlang );
1234  }
1235 
1236  return $message;
1237  }
1238 
1242  public function getParser() {
1243  global $wgParserConf;
1244  if ( !$this->mParser ) {
1245  $parser = MediaWikiServices::getInstance()->getParser();
1246  # Do some initialisation so that we don't have to do it twice
1247  $parser->firstCallInit();
1248  # Clone it and store it
1249  $class = $wgParserConf['class'];
1250  if ( $class == ParserDiffTest::class ) {
1251  # Uncloneable
1252  // @phan-suppress-next-line PhanTypeMismatchProperty
1253  $this->mParser = new $class( $wgParserConf );
1254  } else {
1255  $this->mParser = clone $parser;
1256  }
1257  }
1258 
1259  return $this->mParser;
1260  }
1261 
1270  public function parse( $text, $title = null, $linestart = true,
1271  $interface = false, $language = null
1272  ) {
1273  global $wgTitle;
1274 
1275  if ( $this->mInParser ) {
1276  return htmlspecialchars( $text );
1277  }
1278 
1279  $parser = $this->getParser();
1280  $popts = $this->getParserOptions();
1281  $popts->setInterfaceMessage( $interface );
1282 
1283  if ( is_string( $language ) ) {
1284  $language = $this->langFactory->getLanguage( $language );
1285  }
1286  $popts->setTargetLanguage( $language );
1287 
1288  if ( !$title || !$title instanceof Title ) {
1289  $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1290  $logger->info(
1291  __METHOD__ . ' called with no title set.',
1292  [ 'exception' => new Exception ]
1293  );
1294  $title = $wgTitle;
1295  }
1296  // Sometimes $wgTitle isn't set either...
1297  if ( !$title ) {
1298  # It's not uncommon having a null $wgTitle in scripts. See r80898
1299  # Create a ghost title in such case
1300  $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1301  }
1302 
1303  $this->mInParser = true;
1304  $res = $parser->parse( $text, $title, $popts, $linestart );
1305  $this->mInParser = false;
1306 
1307  return $res;
1308  }
1309 
1310  public function disable() {
1311  $this->mDisable = true;
1312  }
1313 
1314  public function enable() {
1315  $this->mDisable = false;
1316  }
1317 
1330  public function isDisabled() {
1331  return $this->mDisable;
1332  }
1333 
1339  public function clear() {
1340  $langs = $this->languageNameUtils->getLanguageNames( null, 'mw' );
1341  foreach ( array_keys( $langs ) as $code ) {
1342  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1343  }
1344  $this->cache->clear();
1345  }
1346 
1351  public function figureMessage( $key ) {
1352  global $wgLanguageCode;
1353 
1354  $pieces = explode( '/', $key );
1355  if ( count( $pieces ) < 2 ) {
1356  return [ $key, $wgLanguageCode ];
1357  }
1358 
1359  $lang = array_pop( $pieces );
1360  if ( !$this->languageNameUtils->getLanguageName( $lang, null, 'mw' ) ) {
1361  return [ $key, $wgLanguageCode ];
1362  }
1363 
1364  $message = implode( '/', $pieces );
1365 
1366  return [ $message, $lang ];
1367  }
1368 
1377  public function getAllMessageKeys( $code ) {
1378  $this->load( $code );
1379  if ( !$this->cache->has( $code ) ) {
1380  // Apparently load() failed
1381  return null;
1382  }
1383  // Remove administrative keys
1384  $cache = $this->cache->get( $code );
1385  unset( $cache['VERSION'] );
1386  unset( $cache['EXPIRY'] );
1387  unset( $cache['EXCESSIVE'] );
1388  // Remove any !NONEXISTENT keys
1389  $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1390 
1391  // Keys may appear with a capital first letter. lcfirst them.
1392  return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1393  }
1394 
1402  public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1403  $msgText = $this->getMessageTextFromContent( $content );
1404  if ( $msgText === null ) {
1405  $msgText = false; // treat as not existing
1406  }
1407 
1408  $this->replace( $linkTarget->getDBkey(), $msgText );
1409 
1410  if ( $this->contLangConverter->hasVariants() ) {
1411  $this->contLangConverter->updateConversionTable( $linkTarget );
1412  }
1413  }
1414 
1419  public function getCheckKey( $code ) {
1420  return $this->wanCache->makeKey( 'messages', $code );
1421  }
1422 
1427  private function getMessageTextFromContent( Content $content = null ) {
1428  // @TODO: could skip pseudo-messages like js/css here, based on content model
1429  if ( $content ) {
1430  // Message page exists...
1431  // XXX: Is this the right way to turn a Content object into a message?
1432  // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1433  // CssContent. MessageContent is *not* used for storing messages, it's
1434  // only used for wrapping them when needed.
1435  $msgText = $content->getWikitextForTransclusion();
1436  if ( $msgText === false || $msgText === null ) {
1437  // This might be due to some kind of misconfiguration...
1438  $msgText = null;
1439  $this->logger->warning(
1440  __METHOD__ . ": message content doesn't provide wikitext "
1441  . "(content model: " . $content->getModel() . ")" );
1442  }
1443  } else {
1444  // Message page does not exist...
1445  $msgText = false;
1446  }
1447 
1448  return $msgText;
1449  }
1450 
1456  private function bigMessageCacheKey( $hash, $title ) {
1457  return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1458  }
1459 }
MessageCache\transform
transform( $message, $interface=false, $language=null, $title=null)
Definition: MessageCache.php:1213
MessageCache\$mParser
Parser $mParser
Definition: MessageCache.php:95
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:42
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:49
MessageCache\$contLangConverter
ILanguageConverter $contLangConverter
Definition: MessageCache.php:111
MessageCache\setValidationHash
setValidationHash( $code, array $cache)
Set the md5 used to validate the local disk cache.
Definition: MessageCache.php:851
MessageCache\updateMessageOverride
updateMessageOverride(LinkTarget $linkTarget, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
Definition: MessageCache.php:1402
MessageCache\isLanguageLoaded
isLanguageLoaded( $lang)
Whether the language was loaded and its data is still in the process cache.
Definition: MessageCache.php:617
MessageCache\$clusterCache
BagOStuff $clusterCache
Definition: MessageCache.php:105
MessageCache\normalizeKey
static normalizeKey( $key)
Normalize message key input.
Definition: MessageCache.php:138
MessageCache\parse
parse( $text, $title=null, $linestart=true, $interface=false, $language=null)
Definition: MessageCache.php:1270
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:793
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:137
MessageCache\enable
enable()
Definition: MessageCache.php:1314
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
$wgParserConf
$wgParserConf
Parser configuration.
Definition: DefaultSettings.php:4435
MessageCache\$mParserOptions
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
Definition: MessageCache.php:93
true
return true
Definition: router.php:92
MediaWiki\Languages\LanguageFactory
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: LanguageFactory.php:41
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1809
MessageCache\$mInParser
bool $mInParser
Definition: MessageCache.php:100
MessageCache\loadCachedMessagePageEntry
loadCachedMessagePageEntry( $dbKey, $code, $hash)
Definition: MessageCache.php:1156
MessageCache\$logger
LoggerInterface $logger
Definition: MessageCache.php:55
$wgMaxMsgCacheEntrySize
$wgMaxMsgCacheEntrySize
Maximum entry size in the message cache, in bytes.
Definition: DefaultSettings.php:3142
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
Definition: DeferredUpdates.php:85
ParserOptions\newFromAnon
static newFromAnon()
Get a ParserOptions object for an anonymous user.
Definition: ParserOptions.php:996
MediaWiki\Languages\LanguageFallback
Definition: LanguageFallback.php:31
MessageCache\setLogger
setLogger(LoggerInterface $logger)
Definition: MessageCache.php:194
MessageCache\LOCK_TTL
const LOCK_TTL
How long memcached locks last.
Definition: MessageCache.php:53
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:65
MessageCache\saveToLocalCache
saveToLocalCache( $code, $cache)
Save the cache to APC.
Definition: MessageCache.php:247
$wgTitle
if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
Definition: api.php:59
$success
$success
Definition: NoLocalSettings.php:42
$res
$res
Definition: testCompression.php:57
serialize
serialize()
Definition: ApiMessageTrait.php:138
$revQuery
$revQuery
Definition: testCompression.php:56
MediaWiki\Languages\LanguageNameUtils
A service that provides utilities to do with language names and codes.
Definition: LanguageNameUtils.php:41
MessageCache\getValidationHash
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
Definition: MessageCache.php:813
$dbr
$dbr
Definition: testCompression.php:54
Revision
Definition: Revision.php:40
MessageCache\getMessageTextFromContent
getMessageTextFromContent(Content $content=null)
Definition: MessageCache.php:1427
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:58
$wgAdaptiveMessageCache
$wgAdaptiveMessageCache
Instead of caching everything, only cache those messages which have been customised in the site conte...
Definition: DefaultSettings.php:2625
MessageCache\loadFromDB
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
Definition: MessageCache.php:481
MWException
MediaWiki exception.
Definition: MWException.php:26
MessageCache\getCheckKey
getCheckKey( $code)
Definition: MessageCache.php:1419
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:143
MessageCache\getMsgFromNamespace
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
Definition: MessageCache.php:1082
MessageCache\isMainCacheable
isMainCacheable( $name, array $overridable)
Definition: MessageCache.php:632
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
MessageCache\bigMessageCacheKey
bigMessageCacheKey( $hash, $title)
Definition: MessageCache.php:1456
Title\newFromRow
static newFromRow( $row)
Make a Title object from a DB row.
Definition: Title.php:527
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)
Definition: MessageCache.php:165
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2500
MessageCache\$languageFallback
LanguageFallback $languageFallback
Definition: MessageCache.php:119
MediaWiki
A helper class for throttling authentication attempts.
MessageCache\getMessagePageName
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
Definition: MessageCache.php:1059
MSG_CACHE_VERSION
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
Definition: MessageCache.php:39
MapCacheLRU
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:38
MessageCache\$cacheVolatile
bool[] $cacheVolatile
Map of (language code => boolean)
Definition: MessageCache.php:81
MessageCache\figureMessage
figureMessage( $key)
Definition: MessageCache.php:1351
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1151
MessageCache\$srvCache
BagOStuff $srvCache
Definition: MessageCache.php:107
$title
$title
Definition: testCompression.php:38
MessageCache\replace
replace( $title, $text)
Updates cache as necessary when message page is changed.
Definition: MessageCache.php:647
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:595
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1838
DB_MASTER
const DB_MASTER
Definition: defines.php:26
MessageCache\getMessageFromFallbackChain
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
Definition: MessageCache.php:979
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:48
MessageCache\singleton
static singleton()
Get the singleton instance of this class.
Definition: MessageCache.php:128
MessageCache\WAIT_SEC
const WAIT_SEC
How long to wait for memcached locks.
Definition: MessageCache.php:51
MessageCache\$overridable
array $overridable
Map of (lowercase message key => index) for all software defined messages.
Definition: MessageCache.php:76
MessageCache\$cache
MapCacheLRU $cache
Process cache of loaded messages that are defined in MediaWiki namespace.
Definition: MessageCache.php:69
$content
$content
Definition: router.php:78
MessageCache\$languageNameUtils
LanguageNameUtils $languageNameUtils
Definition: MessageCache.php:117
ILanguageConverter
The shared interface for all language converters.
Definition: ILanguageConverter.php:28
MessageCache\clear
clear()
Clear all stored messages in global and local cache.
Definition: MessageCache.php:1339
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:118
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:2998
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part with underscores.
MessageCache\getReentrantScopedLock
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
Definition: MessageCache.php:867
MapCacheLRU\set
set( $key, $value, $rank=self::RANK_TOP)
Set a key/value pair.
Definition: MapCacheLRU.php:111
MessageCache\$localisationCache
LocalisationCache $localisationCache
Definition: MessageCache.php:115
LocalisationCache
Class for caching the contents of localisation files, Messages*.php and *.i18n.php.
Definition: LocalisationCache.php:41
Content
Base interface for content objects.
Definition: Content.php:34
MessageCache\getParser
getParser()
Definition: MessageCache.php:1242
MessageCache\getLocalCache
getLocalCache( $code)
Try to load the cache from APC.
Definition: MessageCache.php:235
MessageCache\$langFactory
LanguageFactory $langFactory
Definition: MessageCache.php:113
MessageCache\refreshAndReplaceInternal
refreshAndReplaceInternal( $code, array $replacements)
Definition: MessageCache.php:681
Title
Represents a title within MediaWiki.
Definition: Title.php:42
MessageCache\loadFromDBWithLock
loadFromDBWithLock( $code, array &$where, $mode=null)
Definition: MessageCache.php:419
MessageCache\$mDisable
bool $mDisable
Should mean that database cannot be used, but check.
Definition: MessageCache.php:87
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
MessageCache\$wanCache
WANObjectCache $wanCache
Definition: MessageCache.php:103
DeferredUpdates\PRESEND
const PRESEND
Definition: DeferredUpdates.php:69
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:1330
MessageCache\getParserOptions
getParserOptions()
ParserOptions is lazy initialised.
Definition: MessageCache.php:203
MessageCache\isCacheExpired
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
Definition: MessageCache.php:770
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:77
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
MessageCache\disable
disable()
Definition: MessageCache.php:1310
MessageCache
Cache of messages that are defined by MediaWiki namespace pages or by hooks.
Definition: MessageCache.php:47
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
MessageCache\getMessageForLang
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
Definition: MessageCache.php:1003
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:39
Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:39
MessageCache\getAllMessageKeys
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
Definition: MessageCache.php:1377
MessageCache\$contLang
Language $contLang
Definition: MessageCache.php:109