MediaWiki  master
MessageCache.php
Go to the documentation of this file.
1 <?php
38 use Psr\Log\LoggerAwareInterface;
39 use Psr\Log\LoggerInterface;
43 use Wikimedia\RequestTimeout\TimeoutException;
44 use Wikimedia\ScopedCallback;
45 
50 define( 'MSG_CACHE_VERSION', 2 );
51 
57 class MessageCache implements LoggerAwareInterface {
61  public const CONSTRUCTOR_OPTIONS = [
62  MainConfigNames::UseDatabaseMessages,
63  MainConfigNames::MaxMsgCacheEntrySize,
64  MainConfigNames::AdaptiveMessageCache,
65  MainConfigNames::UseXssLanguage,
66  MainConfigNames::RawHtmlMessages,
67  ];
68 
73  public const MAX_REQUEST_LANGUAGES = 10;
74 
75  private const FOR_UPDATE = 1; // force message reload
76 
78  private const WAIT_SEC = 15;
80  private const LOCK_TTL = 30;
81 
86  private const WAN_TTL = ExpirationAwareness::TTL_DAY;
87 
89  private $logger;
90 
96  private $cache;
97 
103  private $systemMessageNames;
104 
108  private $cacheVolatile = [];
109 
114  private $disable;
115 
117  private $maxEntrySize;
118 
120  private $adaptive;
121 
123  private $useXssLanguage;
124 
126  private $rawHtmlMessages;
127 
132  private $parserOptions;
134  private $parser = null;
135 
139  private $inParser = false;
140 
142  private $wanCache;
144  private $clusterCache;
146  private $srvCache;
148  private $contLang;
150  private $contLangCode;
152  private $contLangConverter;
154  private $langFactory;
156  private $localisationCache;
158  private $languageNameUtils;
160  private $languageFallback;
162  private $hookRunner;
164  private $parserFactory;
165 
167  private $messageKeyOverrides;
168 
175  public static function normalizeKey( $key ) {
176  $lckey = strtr( $key, ' ', '_' );
177  if ( $lckey === '' ) {
178  // T300792
179  return $lckey;
180  }
181 
182  if ( ord( $lckey ) < 128 ) {
183  $lckey[0] = strtolower( $lckey[0] );
184  } else {
185  $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
186  }
187 
188  return $lckey;
189  }
190 
207  public function __construct(
208  WANObjectCache $wanCache,
209  BagOStuff $clusterCache,
210  BagOStuff $serverCache,
211  Language $contLang,
212  LanguageConverterFactory $langConverterFactory,
213  LoggerInterface $logger,
214  ServiceOptions $options,
215  LanguageFactory $langFactory,
216  LocalisationCache $localisationCache,
217  LanguageNameUtils $languageNameUtils,
218  LanguageFallback $languageFallback,
219  HookContainer $hookContainer,
220  ParserFactory $parserFactory
221  ) {
222  $this->wanCache = $wanCache;
223  $this->clusterCache = $clusterCache;
224  $this->srvCache = $serverCache;
225  $this->contLang = $contLang;
226  $this->contLangConverter = $langConverterFactory->getLanguageConverter( $contLang );
227  $this->contLangCode = $contLang->getCode();
228  $this->logger = $logger;
229  $this->langFactory = $langFactory;
230  $this->localisationCache = $localisationCache;
231  $this->languageNameUtils = $languageNameUtils;
232  $this->languageFallback = $languageFallback;
233  $this->hookRunner = new HookRunner( $hookContainer );
234  $this->parserFactory = $parserFactory;
235 
236  // limit size
237  $this->cache = new MapCacheLRU( self::MAX_REQUEST_LANGUAGES );
238 
239  $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
240  $this->disable = !$options->get( MainConfigNames::UseDatabaseMessages );
241  $this->maxEntrySize = $options->get( MainConfigNames::MaxMsgCacheEntrySize );
242  $this->adaptive = $options->get( MainConfigNames::AdaptiveMessageCache );
243  $this->useXssLanguage = $options->get( MainConfigNames::UseXssLanguage );
244  $this->rawHtmlMessages = $options->get( MainConfigNames::RawHtmlMessages );
245  }
246 
247  public function setLogger( LoggerInterface $logger ) {
248  $this->logger = $logger;
249  }
250 
256  private function getParserOptions() {
257  if ( !$this->parserOptions ) {
258  $context = RequestContext::getMain();
259  $user = $context->getUser();
260  if ( !$user->isSafeToLoad() ) {
261  // It isn't safe to use the context user yet, so don't try to get a
262  // ParserOptions for it. And don't cache this ParserOptions
263  // either.
265  $po->setAllowUnsafeRawHtml( false );
266  return $po;
267  }
268 
269  $this->parserOptions = ParserOptions::newFromContext( $context );
270  // Messages may take parameters that could come
271  // from malicious sources. As a precaution, disable
272  // the <html> parser tag when parsing messages.
273  $this->parserOptions->setAllowUnsafeRawHtml( false );
274  }
275 
276  return $this->parserOptions;
277  }
278 
285  private function getLocalCache( $code ) {
286  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
287 
288  return $this->srvCache->get( $cacheKey );
289  }
290 
297  private function saveToLocalCache( $code, $cache ) {
298  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
299  $this->srvCache->set( $cacheKey, $cache );
300  }
301 
322  private function load( string $code, $mode = null ) {
323  // Don't do double loading...
324  if ( $this->isLanguageLoaded( $code ) && $mode !== self::FOR_UPDATE ) {
325  return true;
326  }
327 
328  // Show a log message (once) if loading is disabled
329  if ( $this->disable ) {
330  static $shownDisabled = false;
331  if ( !$shownDisabled ) {
332  $this->logger->debug( __METHOD__ . ': disabled' );
333  $shownDisabled = true;
334  }
335 
336  return true;
337  }
338 
339  try {
340  return $this->loadUnguarded( $code, $mode );
341  } catch ( Throwable $e ) {
342  // Don't try to load again during the exception handler
343  $this->disable = true;
344  throw $e;
345  }
346  }
347 
355  private function loadUnguarded( $code, $mode ) {
356  $success = false; // Keep track of success
357  $staleCache = false; // a cache array with expired data, or false if none has been loaded
358  $where = []; // Debug info, delayed to avoid spamming debug log too much
359 
360  // A hash of the expected content is stored in a WAN cache key, providing a way
361  // to invalid the local cache on every server whenever a message page changes.
362  [ $hash, $hashVolatile ] = $this->getValidationHash( $code );
363  $this->cacheVolatile[$code] = $hashVolatile;
364  $volatilityOnlyStaleness = false;
365 
366  // Try the local cache and check against the cluster hash key...
367  $cache = $this->getLocalCache( $code );
368  if ( !$cache ) {
369  $where[] = 'local cache is empty';
370  } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
371  $where[] = 'local cache has the wrong hash';
372  $staleCache = $cache;
373  } elseif ( $this->isCacheExpired( $cache ) ) {
374  $where[] = 'local cache is expired';
375  $staleCache = $cache;
376  } elseif ( $hashVolatile ) {
377  // Some recent message page changes might not show due to DB lag
378  $where[] = 'local cache validation key is expired/volatile';
379  $staleCache = $cache;
380  $volatilityOnlyStaleness = true;
381  } else {
382  $where[] = 'got from local cache';
383  $this->cache->set( $code, $cache );
384  $success = true;
385  }
386 
387  if ( !$success ) {
388  // Try the cluster cache, using a lock for regeneration...
389  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
390  for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
391  if ( $volatilityOnlyStaleness && $staleCache ) {
392  // While the cluster cache *might* be more up-to-date, we do not want
393  // the I/O strain of every application server fetching the key here during
394  // the volatility period. Either this thread wins the lock and regenerates
395  // the cache or the stale local cache value gets reused.
396  $where[] = 'global cache is presumed expired';
397  } else {
398  $cache = $this->clusterCache->get( $cacheKey );
399  if ( !$cache ) {
400  $where[] = 'global cache is empty';
401  } elseif ( $this->isCacheExpired( $cache ) ) {
402  $where[] = 'global cache is expired';
403  $staleCache = $cache;
404  } elseif ( $hashVolatile ) {
405  // Some recent message page changes might not show due to DB lag
406  $where[] = 'global cache is expired/volatile';
407  $staleCache = $cache;
408  } else {
409  $where[] = 'got from global cache';
410  $this->cache->set( $code, $cache );
411  $this->saveToCaches( $cache, 'local-only', $code );
412  $success = true;
413  break;
414  }
415  }
416 
417  // We need to call loadFromDB(). Limit the concurrency to one thread.
418  // This prevents the site from going down when the cache expires.
419  // Note that the DB slam protection lock here is non-blocking.
420  $loadStatus = $this->loadFromDBWithMainLock( $code, $where, $mode );
421  if ( $loadStatus === true ) {
422  $success = true;
423  break;
424  } elseif ( $staleCache ) {
425  // Use the stale cache while some other thread constructs the new one
426  $where[] = 'using stale cache';
427  $this->cache->set( $code, $staleCache );
428  $success = true;
429  break;
430  } elseif ( $failedAttempts > 0 ) {
431  $where[] = 'failed to find cache after waiting';
432  // Already blocked once, so avoid another lock/unlock cycle.
433  // This case will typically be hit if memcached is down, or if
434  // loadFromDB() takes longer than LOCK_WAIT.
435  break;
436  } elseif ( $loadStatus === 'cantacquire' ) {
437  // Wait for the other thread to finish, then retry. Normally,
438  // the memcached get() will then yield the other thread's result.
439  $where[] = 'waiting for other thread to complete';
440  [ , $ioError ] = $this->getReentrantScopedLock( $code );
441  if ( $ioError ) {
442  $where[] = 'failed waiting';
443  // Call loadFromDB() with concurrency limited to one thread per server.
444  // It should be rare for all servers to lack even a stale local cache.
445  $success = $this->loadFromDBWithLocalLock( $code, $where, $mode );
446  break;
447  }
448  } else {
449  // Disable cache; $loadStatus is 'disabled'
450  break;
451  }
452  }
453  }
454 
455  if ( !$success ) {
456  $where[] = 'loading FAILED - cache is disabled';
457  $this->disable = true;
458  $this->cache->set( $code, [] );
459  $this->logger->error( __METHOD__ . ": Failed to load $code" );
460  // This used to throw an exception, but that led to nasty side effects like
461  // the whole wiki being instantly down if the memcached server died
462  }
463 
464  if ( !$this->isLanguageLoaded( $code ) ) {
465  throw new LogicException( "Process cache for '$code' should be set by now." );
466  }
467 
468  $info = implode( ', ', $where );
469  $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
470 
471  return $success;
472  }
473 
480  private function loadFromDBWithMainLock( $code, array &$where, $mode = null ) {
481  // If cache updates on all levels fail, give up on message overrides.
482  // This is to avoid easy site outages; see $saveSuccess comments below.
483  $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
484  $status = $this->clusterCache->get( $statusKey );
485  if ( $status === 'error' ) {
486  $where[] = "could not load; method is still globally disabled";
487  return 'disabled';
488  }
489 
490  // Now let's regenerate
491  $where[] = 'loading from DB';
492 
493  // Lock the cache to prevent conflicting writes.
494  // This lock is non-blocking so stale cache can quickly be used.
495  // Note that load() will call a blocking getReentrantScopedLock()
496  // after this if it really need to wait for any current thread.
497  [ $scopedLock ] = $this->getReentrantScopedLock( $code, 0 );
498  if ( !$scopedLock ) {
499  $where[] = 'could not acquire main lock';
500  return 'cantacquire';
501  }
502 
503  $cache = $this->loadFromDB( $code, $mode );
504  $this->cache->set( $code, $cache );
505  $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
506 
507  if ( !$saveSuccess ) {
521  if ( $this->srvCache instanceof EmptyBagOStuff ) {
522  $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
523  $where[] = 'could not save cache, disabled globally for 5 minutes';
524  } else {
525  $where[] = "could not save global cache";
526  }
527  }
528 
529  return true;
530  }
531 
538  private function loadFromDBWithLocalLock( $code, array &$where, $mode = null ) {
539  $success = false;
540  $where[] = 'loading from DB using local lock';
541 
542  $scopedLock = $this->srvCache->getScopedLock(
543  $this->srvCache->makeKey( 'messages', $code ),
544  self::WAIT_SEC,
545  self::LOCK_TTL,
546  __METHOD__
547  );
548  if ( $scopedLock ) {
549  $cache = $this->loadFromDB( $code, $mode );
550  $this->cache->set( $code, $cache );
551  $this->saveToCaches( $cache, 'local-only', $code );
552  $success = true;
553  }
554 
555  return $success;
556  }
557 
567  private function loadFromDB( $code, $mode = null ) {
568  $dbr = wfGetDB( ( $mode === self::FOR_UPDATE ) ? DB_PRIMARY : DB_REPLICA );
569 
570  $cache = [];
571 
572  $mostused = []; // list of "<cased message key>/<code>"
573  if ( $this->adaptive && $code !== $this->contLangCode ) {
574  if ( !$this->cache->has( $this->contLangCode ) ) {
575  $this->load( $this->contLangCode );
576  }
577  $mostused = array_keys( $this->cache->get( $this->contLangCode ) );
578  foreach ( $mostused as $key => $value ) {
579  $mostused[$key] = "$value/$code";
580  }
581  }
582 
583  // Common conditions
584  $conds = [
585  'page_is_redirect' => 0,
586  'page_namespace' => NS_MEDIAWIKI,
587  ];
588  if ( count( $mostused ) ) {
589  $conds['page_title'] = $mostused;
590  } elseif ( $code !== $this->contLangCode ) {
591  $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
592  } else {
593  // Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
594  // other than language code.
595  $conds[] = 'page_title NOT' .
596  $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
597  }
598 
599  // Set the stubs for oversized software-defined messages in the main cache map
600  $res = $dbr->newSelectQueryBuilder()
601  ->select( [ 'page_title', 'page_latest' ] )
602  ->from( 'page' )
603  ->where( $conds )
604  ->andWhere( [ 'page_len > ' . intval( $this->maxEntrySize ) ] )
605  ->caller( __METHOD__ . "($code)-big" )->fetchResultSet();
606  foreach ( $res as $row ) {
607  // Include entries/stubs for all keys in $mostused in adaptive mode
608  if ( $this->adaptive || $this->isMainCacheable( $row->page_title ) ) {
609  $cache[$row->page_title] = '!TOO BIG';
610  }
611  // At least include revision ID so page changes are reflected in the hash
612  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
613  }
614 
615  // Can not inject the RevisionStore as it would break the installer since
616  // it instantiates MessageCache before the DB.
617  $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
618  // Set the text for small software-defined messages in the main cache map
619  $revQuery = $revisionStore->getQueryInfo( [ 'page' ] );
620 
621  // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
622  // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
623  // query (and also reorder it ourselves because as generated by RevisionStore it'll have
624  // `revision` first rather than `page`).
625  $revQuery['joins']['revision'] = $revQuery['joins']['page'];
626  unset( $revQuery['joins']['page'] );
627  // It isn't actually necessary to reorder $revQuery['tables'] as Database does the right thing
628  // when join conditions are given for all joins, but GergÅ‘ is wary of relying on that so pull
629  // `page` to the start.
630  $revQuery['tables'] = array_merge(
631  [ 'page' ],
632  array_diff( $revQuery['tables'], [ 'page' ] )
633  );
634 
635  $res = $dbr->select(
636  $revQuery['tables'],
637  $revQuery['fields'],
638  array_merge( $conds, [
639  'page_len <= ' . intval( $this->maxEntrySize ),
640  'page_latest = rev_id' // get the latest revision only
641  ] ),
642  __METHOD__ . "($code)-small",
643  [ 'STRAIGHT_JOIN' ],
644  $revQuery['joins']
645  );
646 
647  // Don't load content from uncacheable rows (T313004)
648  [ $cacheableRows, $uncacheableRows ] = $this->separateCacheableRows( $res );
649  $result = $revisionStore->newRevisionsFromBatch( $cacheableRows, [
650  'slots' => [ SlotRecord::MAIN ],
651  'content' => true
652  ] );
653  $revisions = $result->isOK() ? $result->getValue() : [];
654 
655  foreach ( $cacheableRows as $row ) {
656  try {
657  $rev = $revisions[$row->rev_id] ?? null;
658  $content = $rev ? $rev->getContent( SlotRecord::MAIN ) : null;
659  $text = $this->getMessageTextFromContent( $content );
660  } catch ( TimeoutException $e ) {
661  throw $e;
662  } catch ( Exception $ex ) {
663  $text = false;
664  }
665 
666  if ( !is_string( $text ) ) {
667  $entry = '!ERROR';
668  $this->logger->error(
669  __METHOD__
670  . ": failed to load message page text for {$row->page_title} ($code)"
671  );
672  } else {
673  $entry = ' ' . $text;
674  }
675  $cache[$row->page_title] = $entry;
676  }
677 
678  foreach ( $uncacheableRows as $row ) {
679  // T193271: cache object gets too big and slow to generate.
680  // At least include revision ID so page changes are reflected in the hash.
681  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
682  }
683 
684  $cache['VERSION'] = MSG_CACHE_VERSION;
685  ksort( $cache );
686 
687  // Hash for validating local cache (APC). No need to take into account
688  // messages larger than $wgMaxMsgCacheEntrySize, since those are only
689  // stored and fetched from memcache.
690  $cache['HASH'] = md5( serialize( $cache ) );
691  $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
692  unset( $cache['EXCESSIVE'] ); // only needed for hash
693 
694  return $cache;
695  }
696 
703  private function isLanguageLoaded( $lang ) {
704  // It is important that this only returns true if the cache was fully
705  // populated by load(), so that callers can assume all cache keys exist.
706  // It is possible for $this->cache to be only partially populated through
707  // methods like MessageCache::replace(), which must not make this method
708  // return true (T208897). And this method must cease to return true
709  // if the language was evicted by MapCacheLRU (T230690).
710  return $this->cache->hasField( $lang, 'VERSION' );
711  }
712 
724  private function isMainCacheable( $name, $code = null ) {
725  // Convert first letter to lowercase, and strip /code suffix
726  $name = $this->contLang->lcfirst( $name );
727  // Include common conversion table pages. This also avoids problems with
728  // Installer::parse() bailing out due to disallowed DB queries (T207979).
729  if ( strpos( $name, 'conversiontable/' ) === 0 ) {
730  return true;
731  }
732  $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
733 
734  if ( $code === null ) {
735  // Bulk load
736  if ( $this->systemMessageNames === null ) {
737  $this->systemMessageNames = array_fill_keys(
738  $this->localisationCache->getSubitemList( $this->contLangCode, 'messages' ),
739  true );
740  }
741  return isset( $this->systemMessageNames[$msg] );
742  } else {
743  // Use individual subitem
744  return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
745  }
746  }
747 
755  private function separateCacheableRows( $res ) {
756  if ( $this->adaptive ) {
757  // Include entries/stubs for all keys in $mostused in adaptive mode
758  return [ $res, [] ];
759  }
760  $cacheableRows = [];
761  $uncacheableRows = [];
762  foreach ( $res as $row ) {
763  if ( $this->isMainCacheable( $row->page_title ) ) {
764  $cacheableRows[] = $row;
765  } else {
766  $uncacheableRows[] = $row;
767  }
768  }
769  return [ $cacheableRows, $uncacheableRows ];
770  }
771 
778  public function replace( $title, $text ) {
779  if ( $this->disable ) {
780  return;
781  }
782 
783  [ $msg, $code ] = $this->figureMessage( $title );
784  if ( strpos( $title, '/' ) !== false && $code === $this->contLangCode ) {
785  // Content language overrides do not use the /<code> suffix
786  return;
787  }
788 
789  // (a) Update the process cache with the new message text
790  if ( $text === false ) {
791  // Page deleted
792  $this->cache->setField( $code, $title, '!NONEXISTENT' );
793  } else {
794  // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
795  $this->cache->setField( $code, $title, ' ' . $text );
796  }
797 
798  // (b) Update the shared caches in a deferred update with a fresh DB snapshot
800  new MessageCacheUpdate( $code, $title, $msg ),
801  DeferredUpdates::PRESEND
802  );
803  }
804 
809  public function refreshAndReplaceInternal( string $code, array $replacements ) {
810  // Allow one caller at a time to avoid race conditions
811  [ $scopedLock ] = $this->getReentrantScopedLock( $code );
812  if ( !$scopedLock ) {
813  foreach ( $replacements as [ $title ] ) {
814  $this->logger->error(
815  __METHOD__ . ': could not acquire lock to update {title} ({code})',
816  [ 'title' => $title, 'code' => $code ] );
817  }
818 
819  return;
820  }
821 
822  // Load the existing cache to update it in the local DC cache.
823  // The other DCs will see a hash mismatch.
824  if ( $this->load( $code, self::FOR_UPDATE ) ) {
825  $cache = $this->cache->get( $code );
826  } else {
827  // Err? Fall back to loading from the database.
828  $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
829  }
830  // Check if individual cache keys should exist and update cache accordingly
831  $newTextByTitle = []; // map of (title => content)
832  $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
833  // Can not inject the WikiPageFactory as it would break the installer since
834  // it instantiates MessageCache before the DB.
835  $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
836  foreach ( $replacements as [ $title ] ) {
837  $page = $wikiPageFactory->newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
838  $page->loadPageData( $page::READ_LATEST );
839  $text = $this->getMessageTextFromContent( $page->getContent() );
840  // Remember the text for the blob store update later on
841  $newTextByTitle[$title] = $text ?? '';
842  // Note that if $text is false, then $cache should have a !NONEXISTANT entry
843  if ( !is_string( $text ) ) {
844  $cache[$title] = '!NONEXISTENT';
845  } elseif ( strlen( $text ) > $this->maxEntrySize ) {
846  $cache[$title] = '!TOO BIG';
847  $newBigTitles[$title] = $page->getLatest();
848  } else {
849  $cache[$title] = ' ' . $text;
850  }
851  }
852  // Update HASH for the new key. Incorporates various administrative keys,
853  // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
854  // and previous replace() calls), but that doesn't really matter since we
855  // only ever compare it for equality with a copy saved by saveToCaches().
856  $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
857  // Update the too-big WAN cache entries now that we have the new HASH
858  foreach ( $newBigTitles as $title => $id ) {
859  // Match logic of loadCachedMessagePageEntry()
860  $this->wanCache->set(
861  $this->bigMessageCacheKey( $cache['HASH'], $title ),
862  ' ' . $newTextByTitle[$title],
863  self::WAN_TTL
864  );
865  }
866  // Mark this cache as definitely being "latest" (non-volatile) so
867  // load() calls do not try to refresh the cache with replica DB data
868  $cache['LATEST'] = time();
869  // Update the process cache
870  $this->cache->set( $code, $cache );
871  // Pre-emptively update the local datacenter cache so things like edit filter and
872  // prevented changes are reflected immediately; these often use MediaWiki: pages.
873  // The datacenter handling replace() calls should be the same one handling edits
874  // as they require HTTP POST.
875  $this->saveToCaches( $cache, 'all', $code );
876  // Release the lock now that the cache is saved
877  ScopedCallback::consume( $scopedLock );
878 
879  // Relay the purge. Touching this check key expires cache contents
880  // and local cache (APC) validation hash across all datacenters.
881  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
882 
883  // Purge the messages in the message blob store and fire any hook handlers
884  $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
885  foreach ( $replacements as [ $title, $msg ] ) {
886  $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
887  $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
888  }
889  }
890 
897  private function isCacheExpired( $cache ) {
898  return !isset( $cache['VERSION'] ) ||
899  !isset( $cache['EXPIRY'] ) ||
900  $cache['VERSION'] !== MSG_CACHE_VERSION ||
901  $cache['EXPIRY'] <= wfTimestampNow();
902  }
903 
913  private function saveToCaches( array $cache, $dest, $code = false ) {
914  if ( $dest === 'all' ) {
915  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
916  $success = $this->clusterCache->set( $cacheKey, $cache );
917  $this->setValidationHash( $code, $cache );
918  } else {
919  $success = true;
920  }
921 
922  $this->saveToLocalCache( $code, $cache );
923 
924  return $success;
925  }
926 
933  private function getValidationHash( $code ) {
934  $curTTL = null;
935  $value = $this->wanCache->get(
936  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
937  $curTTL,
938  [ $this->getCheckKey( $code ) ]
939  );
940 
941  if ( $value ) {
942  $hash = $value['hash'];
943  if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
944  // Cache was recently updated via replace() and should be up-to-date.
945  // That method is only called in the primary datacenter and uses FOR_UPDATE.
946  $expired = false;
947  } else {
948  // See if the "check" key was bumped after the hash was generated
949  $expired = ( $curTTL < 0 );
950  }
951  } else {
952  // No hash found at all; cache must regenerate to be safe
953  $hash = false;
954  $expired = true;
955  }
956 
957  return [ $hash, $expired ];
958  }
959 
970  private function setValidationHash( $code, array $cache ) {
971  $this->wanCache->set(
972  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
973  [
974  'hash' => $cache['HASH'],
975  'latest' => $cache['LATEST'] ?? 0
976  ],
977  WANObjectCache::TTL_INDEFINITE
978  );
979  }
980 
987  private function getReentrantScopedLock( $code, $timeout = self::WAIT_SEC ) {
988  $key = $this->clusterCache->makeKey( 'messages', $code );
989 
990  $watchPoint = $this->clusterCache->watchErrors();
991  $scopedLock = $this->clusterCache->getScopedLock(
992  $key,
993  $timeout,
994  self::LOCK_TTL,
995  __METHOD__
996  );
997  $error = ( !$scopedLock && $this->clusterCache->getLastError( $watchPoint ) );
998 
999  return [ $scopedLock, $error ];
1000  }
1001 
1034  public function get( $key, $useDB = true, $langcode = true ) {
1035  if ( is_int( $key ) ) {
1036  // Fix numerical strings that somehow become ints on their way here
1037  $key = (string)$key;
1038  } elseif ( !is_string( $key ) ) {
1039  throw new TypeError( 'Message key must be a string' );
1040  } elseif ( $key === '' ) {
1041  // Shortcut: the empty key is always missing
1042  return false;
1043  }
1044 
1045  $language = $this->getLanguageObject( $langcode );
1046 
1047  // Normalise title-case input (with some inlining)
1048  $lckey = self::normalizeKey( $key );
1049 
1050  // Initialize the overrides here to prevent calling the hook too early.
1051  if ( $this->messageKeyOverrides === null ) {
1052  $this->messageKeyOverrides = [];
1053  $this->hookRunner->onMessageCacheFetchOverrides( $this->messageKeyOverrides );
1054  }
1055 
1056  if ( isset( $this->messageKeyOverrides[$lckey] ) ) {
1057  $override = $this->messageKeyOverrides[$lckey];
1058 
1059  // Strings are deliberately interpreted as message keys,
1060  // to prevent ambiguity between message keys and functions.
1061  if ( is_string( $override ) ) {
1062  $lckey = $override;
1063  } else {
1064  $lckey = $override( $lckey, $this, $language, $useDB );
1065  }
1066  }
1067 
1068  $this->hookRunner->onMessageCache__get( $lckey );
1069 
1070  // Loop through each language in the fallback list until we find something useful
1071  $message = $this->getMessageFromFallbackChain(
1072  $language,
1073  $lckey,
1074  !$this->disable && $useDB
1075  );
1076 
1077  // If we still have no message, maybe the key was in fact a full key so try that
1078  if ( $message === false ) {
1079  $parts = explode( '/', $lckey );
1080  // We may get calls for things that are http-urls from sidebar
1081  // Let's not load nonexistent languages for those
1082  // They usually have more than one slash.
1083  if ( count( $parts ) === 2 && $parts[1] !== '' ) {
1084  $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] ) ?? false;
1085  }
1086  }
1087 
1088  // Post-processing if the message exists
1089  if ( $message !== false ) {
1090  // Fix whitespace
1091  $message = str_replace(
1092  [
1093  // Fix for trailing whitespace, removed by textarea
1094  '&#32;',
1095  // Fix for NBSP, converted to space by firefox
1096  '&nbsp;',
1097  '&#160;',
1098  '&shy;'
1099  ],
1100  [
1101  ' ',
1102  "\u{00A0}",
1103  "\u{00A0}",
1104  "\u{00AD}"
1105  ],
1106  $message
1107  );
1108  }
1109 
1110  return $message;
1111  }
1112 
1128  private function getLanguageObject( $langcode ) {
1129  # Identify which language to get or create a language object for.
1130  # Using is_object here due to Stub objects.
1131  if ( is_object( $langcode ) ) {
1132  # Great, we already have the object (hopefully)!
1133  return $langcode;
1134  }
1135 
1136  if ( $langcode === true || $langcode === $this->contLangCode ) {
1137  # $langcode is the language code of the wikis content language object.
1138  # or it is a boolean and value is true
1139  return $this->contLang;
1140  }
1141 
1142  global $wgLang;
1143  if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1144  # $langcode is the language code of user language object.
1145  # or it was a boolean and value is false
1146  return $wgLang;
1147  }
1148 
1149  $validCodes = array_keys( $this->languageNameUtils->getLanguageNames() );
1150  if ( in_array( $langcode, $validCodes ) ) {
1151  # $langcode corresponds to a valid language.
1152  return $this->langFactory->getLanguage( $langcode );
1153  }
1154 
1155  # $langcode is a string, but not a valid language code; use content language.
1156  $this->logger->debug( 'Invalid language code passed to' . __METHOD__ . ', falling back to content language.' );
1157  return $this->contLang;
1158  }
1159 
1172  private function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1173  $alreadyTried = [];
1174 
1175  // First try the requested language.
1176  $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1177  if ( $message !== false ) {
1178  return $message;
1179  }
1180 
1181  // Now try checking the site language.
1182  $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1183  return $message;
1184  }
1185 
1196  private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1197  $langcode = $lang->getCode();
1198 
1199  // Try checking the database for the requested language
1200  if ( $useDB ) {
1201  $uckey = $this->contLang->ucfirst( $lckey );
1202 
1203  if ( !isset( $alreadyTried[$langcode] ) ) {
1204  $message = $this->getMsgFromNamespace(
1205  $this->getMessagePageName( $langcode, $uckey ),
1206  $langcode
1207  );
1208  if ( $message !== false ) {
1209  return $message;
1210  }
1211  $alreadyTried[$langcode] = true;
1212  }
1213  } else {
1214  $uckey = null;
1215  }
1216 
1217  // Return a special value handled in Message::format() to display the message key
1218  // (and fallback keys) and the parameters passed to the message.
1219  // TODO: Move to a better place.
1220  if ( $langcode === 'qqx' ) {
1221  return '($*)';
1222  } elseif (
1223  $langcode === 'x-xss' &&
1224  $this->useXssLanguage &&
1225  !in_array( $lckey, $this->rawHtmlMessages, true )
1226  ) {
1227  $xssViaInnerHtml = "<script>alert('$lckey')</script>";
1228  $xssViaAttribute = '">' . $xssViaInnerHtml . '<x y="';
1229  return $xssViaInnerHtml . $xssViaAttribute . '($*)';
1230  }
1231 
1232  // Check the localisation cache
1233  [ $defaultMessage, $messageSource ] =
1234  $this->localisationCache->getSubitemWithSource( $langcode, 'messages', $lckey );
1235  if ( $messageSource === $langcode ) {
1236  return $defaultMessage;
1237  }
1238 
1239  // Try checking the database for all of the fallback languages
1240  if ( $useDB ) {
1241  $fallbackChain = $this->languageFallback->getAll( $langcode );
1242 
1243  foreach ( $fallbackChain as $code ) {
1244  if ( isset( $alreadyTried[$code] ) ) {
1245  continue;
1246  }
1247 
1248  $message = $this->getMsgFromNamespace(
1249  // @phan-suppress-next-line PhanTypeMismatchArgumentNullable uckey is set when used
1250  $this->getMessagePageName( $code, $uckey ), $code );
1251 
1252  if ( $message !== false ) {
1253  return $message;
1254  }
1255  $alreadyTried[$code] = true;
1256 
1257  // Reached the source language of the default message. Don't look for DB overrides
1258  // further back in the fallback chain. (T229992)
1259  if ( $code === $messageSource ) {
1260  return $defaultMessage;
1261  }
1262  }
1263  }
1264 
1265  return $defaultMessage ?? false;
1266  }
1267 
1275  private function getMessagePageName( $langcode, $uckey ) {
1276  if ( $langcode === $this->contLangCode ) {
1277  // Messages created in the content language will not have the /lang extension
1278  return $uckey;
1279  } else {
1280  return "$uckey/$langcode";
1281  }
1282  }
1283 
1296  public function getMsgFromNamespace( $title, $code ) {
1297  // Load all MediaWiki page definitions into cache. Note that individual keys
1298  // already loaded into cache during this request remain in the cache, which
1299  // includes the value of hook-defined messages.
1300  $this->load( $code );
1301 
1302  $entry = $this->cache->getField( $code, $title );
1303 
1304  if ( $entry !== null ) {
1305  // Message page exists as an override of a software messages
1306  if ( substr( $entry, 0, 1 ) === ' ' ) {
1307  // The message exists and is not '!TOO BIG' or '!ERROR'
1308  return (string)substr( $entry, 1 );
1309  } elseif ( $entry === '!NONEXISTENT' ) {
1310  // The text might be '-' or missing due to some data loss
1311  return false;
1312  }
1313  // Load the message page, utilizing the individual message cache.
1314  // If the page does not exist, there will be no hook handler fallbacks.
1315  $entry = $this->loadCachedMessagePageEntry(
1316  $title,
1317  $code,
1318  $this->cache->getField( $code, 'HASH' )
1319  );
1320  } else {
1321  // Message page either does not exist or does not override a software message
1322  if ( !$this->isMainCacheable( $title, $code ) ) {
1323  // Message page does not override any software-defined message. A custom
1324  // message might be defined to have content or settings specific to the wiki.
1325  // Load the message page, utilizing the individual message cache as needed.
1326  $entry = $this->loadCachedMessagePageEntry(
1327  $title,
1328  $code,
1329  $this->cache->getField( $code, 'HASH' )
1330  );
1331  }
1332  if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1333  // Message does not have a MediaWiki page definition; try hook handlers
1334  $message = false;
1335  // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
1336  $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1337  if ( $message !== false ) {
1338  $this->cache->setField( $code, $title, ' ' . $message );
1339  } else {
1340  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1341  }
1342 
1343  return $message;
1344  }
1345  }
1346 
1347  if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1348  if ( $this->cacheVolatile[$code] ) {
1349  // Make sure that individual keys respect the WAN cache holdoff period too
1350  $this->logger->debug(
1351  __METHOD__ . ': loading volatile key \'{titleKey}\'',
1352  [ 'titleKey' => $title, 'code' => $code ] );
1353  } else {
1354  $this->cache->setField( $code, $title, $entry );
1355  }
1356  // The message exists, so make sure a string is returned
1357  return (string)substr( $entry, 1 );
1358  }
1359 
1360  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1361 
1362  return false;
1363  }
1364 
1371  private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1372  $fname = __METHOD__;
1373  return $this->srvCache->getWithSetCallback(
1374  $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1375  BagOStuff::TTL_HOUR,
1376  function () use ( $code, $dbKey, $hash, $fname ) {
1377  return $this->wanCache->getWithSetCallback(
1378  $this->bigMessageCacheKey( $hash, $dbKey ),
1379  self::WAN_TTL,
1380  function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1381  // Try loading the message from the database
1382  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1383  // Use newKnownCurrent() to avoid querying revision/user tables
1384  $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1385  // Injecting RevisionStore breaks installer since it
1386  // instantiates MessageCache before DB.
1387  $revision = MediaWikiServices::getInstance()
1388  ->getRevisionLookup()
1389  ->getKnownCurrentRevision( $title );
1390  if ( !$revision ) {
1391  // The wiki doesn't have a local override page. Cache absence with normal TTL.
1392  // When overrides are created, self::replace() takes care of the cache.
1393  return '!NONEXISTENT';
1394  }
1395  $content = $revision->getContent( SlotRecord::MAIN );
1396  if ( $content ) {
1397  $message = $this->getMessageTextFromContent( $content );
1398  } else {
1399  $this->logger->warning(
1400  $fname . ': failed to load page text for \'{titleKey}\'',
1401  [ 'titleKey' => $dbKey, 'code' => $code ]
1402  );
1403  $message = null;
1404  }
1405 
1406  if ( !is_string( $message ) ) {
1407  // Revision failed to load Content, or Content is incompatible with wikitext.
1408  // Possibly a temporary loading failure.
1409  $ttl = 5;
1410 
1411  return '!NONEXISTENT';
1412  }
1413 
1414  return ' ' . $message;
1415  }
1416  );
1417  }
1418  );
1419  }
1420 
1428  public function transform( $message, $interface = false, $language = null, PageReference $page = null ) {
1429  // Avoid creating parser if nothing to transform
1430  if ( $this->inParser || !str_contains( $message, '{{' ) ) {
1431  return $message;
1432  }
1433 
1434  $parser = $this->getParser();
1435  $popts = $this->getParserOptions();
1436  $popts->setInterfaceMessage( $interface );
1437  $popts->setTargetLanguage( $language );
1438 
1439  $userlang = $popts->setUserLang( $language );
1440  $this->inParser = true;
1441  $message = $parser->transformMsg( $message, $popts, $page );
1442  $this->inParser = false;
1443  $popts->setUserLang( $userlang );
1444 
1445  return $message;
1446  }
1447 
1451  public function getParser() {
1452  if ( !$this->parser ) {
1453  $this->parser = $this->parserFactory->create();
1454  }
1455 
1456  return $this->parser;
1457  }
1458 
1467  public function parse( $text, PageReference $page = null, $linestart = true,
1468  $interface = false, $language = null
1469  ) {
1470  global $wgTitle;
1471 
1472  if ( $this->inParser ) {
1473  return htmlspecialchars( $text );
1474  }
1475 
1476  $parser = $this->getParser();
1477  $popts = $this->getParserOptions();
1478  $popts->setInterfaceMessage( $interface );
1479 
1480  if ( is_string( $language ) ) {
1481  $language = $this->langFactory->getLanguage( $language );
1482  }
1483  $popts->setTargetLanguage( $language );
1484 
1485  if ( !$page ) {
1486  $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1487  $logger->info(
1488  __METHOD__ . ' called with no title set.',
1489  [ 'exception' => new Exception ]
1490  );
1491  $page = $wgTitle;
1492  }
1493  // Sometimes $wgTitle isn't set either...
1494  if ( !$page ) {
1495  // It's not uncommon having a null $wgTitle in scripts. See r80898
1496  // Create a ghost title in such case
1497  $page = PageReferenceValue::localReference(
1498  NS_SPECIAL,
1499  'Badtitle/title not set in ' . __METHOD__
1500  );
1501  }
1502 
1503  $this->inParser = true;
1504  $res = $parser->parse( $text, $page, $popts, $linestart );
1505  $this->inParser = false;
1506 
1507  return $res;
1508  }
1509 
1510  public function disable() {
1511  $this->disable = true;
1512  }
1513 
1514  public function enable() {
1515  $this->disable = false;
1516  }
1517 
1530  public function isDisabled() {
1531  return $this->disable;
1532  }
1533 
1539  public function clear() {
1540  $langs = $this->languageNameUtils->getLanguageNames();
1541  foreach ( $langs as $code => $_ ) {
1542  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1543  }
1544  $this->cache->clear();
1545  }
1546 
1551  public function figureMessage( $key ) {
1552  $pieces = explode( '/', $key );
1553  if ( count( $pieces ) < 2 ) {
1554  return [ $key, $this->contLangCode ];
1555  }
1556 
1557  $lang = array_pop( $pieces );
1558  if ( !$this->languageNameUtils->getLanguageName(
1559  $lang,
1560  LanguageNameUtils::AUTONYMS,
1561  LanguageNameUtils::DEFINED
1562  ) ) {
1563  return [ $key, $this->contLangCode ];
1564  }
1565 
1566  $message = implode( '/', $pieces );
1567 
1568  return [ $message, $lang ];
1569  }
1570 
1579  public function getAllMessageKeys( $code ) {
1580  $this->load( $code );
1581  if ( !$this->cache->has( $code ) ) {
1582  // Apparently load() failed
1583  return null;
1584  }
1585  // Remove administrative keys
1586  $cache = $this->cache->get( $code );
1587  unset( $cache['VERSION'] );
1588  unset( $cache['EXPIRY'] );
1589  unset( $cache['EXCESSIVE'] );
1590  // Remove any !NONEXISTENT keys
1591  $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1592 
1593  // Keys may appear with a capital first letter. lcfirst them.
1594  return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1595  }
1596 
1604  public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1605  // treat null as not existing
1606  $msgText = $this->getMessageTextFromContent( $content ) ?? false;
1607 
1608  $this->replace( $linkTarget->getDBkey(), $msgText );
1609 
1610  if ( $this->contLangConverter->hasVariants() ) {
1611  $this->contLangConverter->updateConversionTable( $linkTarget );
1612  }
1613  }
1614 
1619  public function getCheckKey( $code ) {
1620  return $this->wanCache->makeKey( 'messages', $code );
1621  }
1622 
1627  private function getMessageTextFromContent( Content $content = null ) {
1628  // @TODO: could skip pseudo-messages like js/css here, based on content model
1629  if ( $content ) {
1630  // Message page exists...
1631  // XXX: Is this the right way to turn a Content object into a message?
1632  // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1633  // CssContent. MessageContent is *not* used for storing messages, it's
1634  // only used for wrapping them when needed.
1635  $msgText = $content->getWikitextForTransclusion();
1636  if ( $msgText === false || $msgText === null ) {
1637  // This might be due to some kind of misconfiguration...
1638  $msgText = null;
1639  $this->logger->warning(
1640  __METHOD__ . ": message content doesn't provide wikitext "
1641  . "(content model: " . $content->getModel() . ")" );
1642  }
1643  } else {
1644  // Message page does not exist...
1645  $msgText = false;
1646  }
1647 
1648  return $msgText;
1649  }
1650 
1656  private function bigMessageCacheKey( $hash, $title ) {
1657  return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1658  }
1659 }
const NS_MEDIAWIKI
Definition: Defines.php:72
const NS_SPECIAL
Definition: Defines.php:53
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
$success
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition: Setup.php:535
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgTitle
Definition: Setup.php:535
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:85
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
A BagOStuff object with no objects in it.
Base class for language-specific code.
Definition: Language.php:61
getCode()
Get the internal language code for this language object.
Definition: Language.php:3960
Caching for the contents of localisation files.
Store key-value entries in a size-limited in-memory LRU cache.
Definition: MapCacheLRU.php:34
A class for passing options to services.
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:568
An interface for creating language converters.
getLanguageConverter( $language=null)
Provide a LanguageConverter for given language.
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
A service that provides utilities to do with language names and codes.
PSR-3 logger instance factory.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Immutable value object representing a page reference.
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:40
Class to implement stub globals, which are globals that delay loading the their associated module cod...
Definition: StubObject.php:55
Stub object for the user language.
Represents a title within MediaWiki.
Definition: Title.php:76
Message cache purging and in-place update handler for specific message page changes.
Cache messages that are defined by MediaWiki-namespace pages or by hooks.
refreshAndReplaceInternal(string $code, array $replacements)
const MAX_REQUEST_LANGUAGES
The size of the MapCacheLRU which stores message data.
getCheckKey( $code)
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, Language $contLang, LanguageConverterFactory $langConverterFactory, LoggerInterface $logger, ServiceOptions $options, LanguageFactory $langFactory, LocalisationCache $localisationCache, LanguageNameUtils $languageNameUtils, LanguageFallback $languageFallback, HookContainer $hookContainer, ParserFactory $parserFactory)
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
parse( $text, PageReference $page=null, $linestart=true, $interface=false, $language=null)
transform( $message, $interface=false, $language=null, PageReference $page=null)
updateMessageOverride(LinkTarget $linkTarget, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
const CONSTRUCTOR_OPTIONS
Options to be included in the ServiceOptions.
isDisabled()
Whether DB/cache usage is disabled for determining messages.
setLogger(LoggerInterface $logger)
clear()
Clear all stored messages in global and local cache.
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
static normalizeKey( $key)
Normalize message key input.
figureMessage( $key)
replace( $title, $text)
Updates cache as necessary when message page is changed.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
static newFromAnon()
Get a ParserOptions object for an anonymous user.
parse( $text, PageReference $page, ParserOptions $options, $linestart=true, $clearState=true, $revid=null)
Convert wikitext to HTML Do not call this function recursively.
Definition: Parser.php:622
transformMsg( $text, ParserOptions $options, ?PageReference $page=null)
Wrapper for preprocess()
Definition: Parser.php:4812
static getMain()
Get the RequestContext object associated with the main request.
Multi-datacenter aware caching interface.
Base interface for representing page content.
Definition: Content.php:39
Represents the target of a wiki link.
Definition: LinkTarget.php:30
getDBkey()
Get the main part of the link target, in canonical database form.
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Generic interface providing Time-To-Live constants for expirable object storage.
Result wrapper for grabbing data queried from an IDatabase object.
const DB_REPLICA
Definition: defines.php:26
const DB_PRIMARY
Definition: defines.php:28
$content
Definition: router.php:76
return true
Definition: router.php:90