MediaWiki master
MessageCache.php
Go to the documentation of this file.
1<?php
43use Psr\Log\LoggerAwareInterface;
44use Psr\Log\LoggerInterface;
50use Wikimedia\RequestTimeout\TimeoutException;
51use Wikimedia\ScopedCallback;
52
57define( 'MSG_CACHE_VERSION', 2 );
58
64class MessageCache implements LoggerAwareInterface {
68 public const CONSTRUCTOR_OPTIONS = [
69 MainConfigNames::UseDatabaseMessages,
70 MainConfigNames::MaxMsgCacheEntrySize,
71 MainConfigNames::AdaptiveMessageCache,
72 MainConfigNames::UseXssLanguage,
73 MainConfigNames::RawHtmlMessages,
74 ];
75
80 public const MAX_REQUEST_LANGUAGES = 10;
81
82 private const FOR_UPDATE = 1; // force message reload
83
85 private const WAIT_SEC = 15;
87 private const LOCK_TTL = 30;
88
93 private const WAN_TTL = ExpirationAwareness::TTL_DAY;
94
96 private $logger;
97
103 private $cache;
104
110 private $systemMessageNames;
111
115 private $cacheVolatile = [];
116
121 private $disable;
122
124 private $maxEntrySize;
125
127 private $adaptive;
128
130 private $useXssLanguage;
131
133 private $rawHtmlMessages;
134
139 private $parserOptions;
140
142 private $parser = null;
143
147 private $inParser = false;
148
150 private $wanCache;
152 private $clusterCache;
154 private $srvCache;
156 private $contLang;
158 private $contLangCode;
160 private $contLangConverter;
162 private $langFactory;
164 private $localisationCache;
166 private $languageNameUtils;
168 private $languageFallback;
170 private $hookRunner;
172 private $parserFactory;
173
175 private $messageKeyOverrides;
176
183 public static function normalizeKey( $key ) {
184 $lckey = strtr( $key, ' ', '_' );
185 if ( $lckey === '' ) {
186 // T300792
187 return $lckey;
188 }
189
190 if ( ord( $lckey ) < 128 ) {
191 $lckey[0] = strtolower( $lckey[0] );
192 } else {
193 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
194 }
195
196 return $lckey;
197 }
198
215 public function __construct(
216 WANObjectCache $wanCache,
217 BagOStuff $clusterCache,
218 BagOStuff $serverCache,
219 Language $contLang,
220 LanguageConverterFactory $langConverterFactory,
221 LoggerInterface $logger,
222 ServiceOptions $options,
223 LanguageFactory $langFactory,
224 LocalisationCache $localisationCache,
225 LanguageNameUtils $languageNameUtils,
226 LanguageFallback $languageFallback,
227 HookContainer $hookContainer,
228 ParserFactory $parserFactory
229 ) {
230 $this->wanCache = $wanCache;
231 $this->clusterCache = $clusterCache;
232 $this->srvCache = $serverCache;
233 $this->contLang = $contLang;
234 $this->contLangConverter = $langConverterFactory->getLanguageConverter( $contLang );
235 $this->contLangCode = $contLang->getCode();
236 $this->logger = $logger;
237 $this->langFactory = $langFactory;
238 $this->localisationCache = $localisationCache;
239 $this->languageNameUtils = $languageNameUtils;
240 $this->languageFallback = $languageFallback;
241 $this->hookRunner = new HookRunner( $hookContainer );
242 $this->parserFactory = $parserFactory;
243
244 // limit size
245 $this->cache = new MapCacheLRU( self::MAX_REQUEST_LANGUAGES );
246
247 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
248 $this->disable = !$options->get( MainConfigNames::UseDatabaseMessages );
249 $this->maxEntrySize = $options->get( MainConfigNames::MaxMsgCacheEntrySize );
250 $this->adaptive = $options->get( MainConfigNames::AdaptiveMessageCache );
251 $this->useXssLanguage = $options->get( MainConfigNames::UseXssLanguage );
252 $this->rawHtmlMessages = $options->get( MainConfigNames::RawHtmlMessages );
253 }
254
255 public function setLogger( LoggerInterface $logger ) {
256 $this->logger = $logger;
257 }
258
264 private function getParserOptions() {
265 if ( !$this->parserOptions ) {
266 $context = RequestContext::getMain();
267 $user = $context->getUser();
268 if ( !$user->isSafeToLoad() ) {
269 // It isn't safe to use the context user yet, so don't try to get a
270 // ParserOptions for it. And don't cache this ParserOptions
271 // either.
272 $po = ParserOptions::newFromAnon();
273 $po->setAllowUnsafeRawHtml( false );
274 return $po;
275 }
276
277 $this->parserOptions = ParserOptions::newFromContext( $context );
278 // Messages may take parameters that could come
279 // from malicious sources. As a precaution, disable
280 // the <html> parser tag when parsing messages.
281 $this->parserOptions->setAllowUnsafeRawHtml( false );
282 }
283
284 return $this->parserOptions;
285 }
286
293 private function getLocalCache( $code ) {
294 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
295
296 return $this->srvCache->get( $cacheKey );
297 }
298
305 private function saveToLocalCache( $code, $cache ) {
306 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
307 $this->srvCache->set( $cacheKey, $cache );
308 }
309
330 private function load( string $code, $mode = null ) {
331 // Don't do double loading...
332 if ( $this->isLanguageLoaded( $code ) && $mode !== self::FOR_UPDATE ) {
333 return true;
334 }
335
336 // Show a log message (once) if loading is disabled
337 if ( $this->disable ) {
338 static $shownDisabled = false;
339 if ( !$shownDisabled ) {
340 $this->logger->debug( __METHOD__ . ': disabled' );
341 $shownDisabled = true;
342 }
343
344 return true;
345 }
346
347 try {
348 return $this->loadUnguarded( $code, $mode );
349 } catch ( Throwable $e ) {
350 // Don't try to load again during the exception handler
351 $this->disable = true;
352 throw $e;
353 }
354 }
355
363 private function loadUnguarded( $code, $mode ) {
364 $success = false; // Keep track of success
365 $staleCache = false; // a cache array with expired data, or false if none has been loaded
366 $where = []; // Debug info, delayed to avoid spamming debug log too much
367
368 // A hash of the expected content is stored in a WAN cache key, providing a way
369 // to invalid the local cache on every server whenever a message page changes.
370 [ $hash, $hashVolatile ] = $this->getValidationHash( $code );
371 $this->cacheVolatile[$code] = $hashVolatile;
372 $volatilityOnlyStaleness = false;
373
374 // Try the local cache and check against the cluster hash key...
375 $cache = $this->getLocalCache( $code );
376 if ( !$cache ) {
377 $where[] = 'local cache is empty';
378 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
379 $where[] = 'local cache has the wrong hash';
380 $staleCache = $cache;
381 } elseif ( $this->isCacheExpired( $cache ) ) {
382 $where[] = 'local cache is expired';
383 $staleCache = $cache;
384 } elseif ( $hashVolatile ) {
385 // Some recent message page changes might not show due to DB lag
386 $where[] = 'local cache validation key is expired/volatile';
387 $staleCache = $cache;
388 $volatilityOnlyStaleness = true;
389 } else {
390 $where[] = 'got from local cache';
391 $this->cache->set( $code, $cache );
392 $success = true;
393 }
394
395 if ( !$success ) {
396 // Try the cluster cache, using a lock for regeneration...
397 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
398 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
399 if ( $volatilityOnlyStaleness && $staleCache ) {
400 // While the cluster cache *might* be more up-to-date, we do not want
401 // the I/O strain of every application server fetching the key here during
402 // the volatility period. Either this thread wins the lock and regenerates
403 // the cache or the stale local cache value gets reused.
404 $where[] = 'global cache is presumed expired';
405 } else {
406 $cache = $this->clusterCache->get( $cacheKey );
407 if ( !$cache ) {
408 $where[] = 'global cache is empty';
409 } elseif ( $this->isCacheExpired( $cache ) ) {
410 $where[] = 'global cache is expired';
411 $staleCache = $cache;
412 } elseif ( $hashVolatile ) {
413 // Some recent message page changes might not show due to DB lag
414 $where[] = 'global cache is expired/volatile';
415 $staleCache = $cache;
416 } else {
417 $where[] = 'got from global cache';
418 $this->cache->set( $code, $cache );
419 $this->saveToCaches( $cache, 'local-only', $code );
420 $success = true;
421 break;
422 }
423 }
424
425 // We need to call loadFromDB(). Limit the concurrency to one thread.
426 // This prevents the site from going down when the cache expires.
427 // Note that the DB slam protection lock here is non-blocking.
428 $loadStatus = $this->loadFromDBWithMainLock( $code, $where, $mode );
429 if ( $loadStatus === true ) {
430 $success = true;
431 break;
432 } elseif ( $staleCache ) {
433 // Use the stale cache while some other thread constructs the new one
434 $where[] = 'using stale cache';
435 $this->cache->set( $code, $staleCache );
436 $success = true;
437 break;
438 } elseif ( $failedAttempts > 0 ) {
439 $where[] = 'failed to find cache after waiting';
440 // Already blocked once, so avoid another lock/unlock cycle.
441 // This case will typically be hit if memcached is down, or if
442 // loadFromDB() takes longer than LOCK_WAIT.
443 break;
444 } elseif ( $loadStatus === 'cantacquire' ) {
445 // Wait for the other thread to finish, then retry. Normally,
446 // the memcached get() will then yield the other thread's result.
447 $where[] = 'waiting for other thread to complete';
448 [ , $ioError ] = $this->getReentrantScopedLock( $code );
449 if ( $ioError ) {
450 $where[] = 'failed waiting';
451 // Call loadFromDB() with concurrency limited to one thread per server.
452 // It should be rare for all servers to lack even a stale local cache.
453 $success = $this->loadFromDBWithLocalLock( $code, $where, $mode );
454 break;
455 }
456 } else {
457 // Disable cache; $loadStatus is 'disabled'
458 break;
459 }
460 }
461 }
462
463 if ( !$success ) {
464 $where[] = 'loading FAILED - cache is disabled';
465 $this->disable = true;
466 $this->cache->set( $code, [] );
467 $this->logger->error( __METHOD__ . ": Failed to load $code" );
468 // This used to throw an exception, but that led to nasty side effects like
469 // the whole wiki being instantly down if the memcached server died
470 }
471
472 if ( !$this->isLanguageLoaded( $code ) ) {
473 throw new LogicException( "Process cache for '$code' should be set by now." );
474 }
475
476 $info = implode( ', ', $where );
477 $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
478
479 return $success;
480 }
481
488 private function loadFromDBWithMainLock( $code, array &$where, $mode = null ) {
489 // If cache updates on all levels fail, give up on message overrides.
490 // This is to avoid easy site outages; see $saveSuccess comments below.
491 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
492 $status = $this->clusterCache->get( $statusKey );
493 if ( $status === 'error' ) {
494 $where[] = "could not load; method is still globally disabled";
495 return 'disabled';
496 }
497
498 // Now let's regenerate
499 $where[] = 'loading from DB';
500
501 // Lock the cache to prevent conflicting writes.
502 // This lock is non-blocking so stale cache can quickly be used.
503 // Note that load() will call a blocking getReentrantScopedLock()
504 // after this if it really needs to wait for any current thread.
505 [ $scopedLock ] = $this->getReentrantScopedLock( $code, 0 );
506 if ( !$scopedLock ) {
507 $where[] = 'could not acquire main lock';
508 return 'cantacquire';
509 }
510
511 $cache = $this->loadFromDB( $code, $mode );
512 $this->cache->set( $code, $cache );
513 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
514
515 if ( !$saveSuccess ) {
529 if ( $this->srvCache instanceof EmptyBagOStuff ) {
530 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
531 $where[] = 'could not save cache, disabled globally for 5 minutes';
532 } else {
533 $where[] = "could not save global cache";
534 }
535 }
536
537 return true;
538 }
539
546 private function loadFromDBWithLocalLock( $code, array &$where, $mode = null ) {
547 $success = false;
548 $where[] = 'loading from DB using local lock';
549
550 $scopedLock = $this->srvCache->getScopedLock(
551 $this->srvCache->makeKey( 'messages', $code ),
552 self::WAIT_SEC,
553 self::LOCK_TTL,
554 __METHOD__
555 );
556 if ( $scopedLock ) {
557 $cache = $this->loadFromDB( $code, $mode );
558 $this->cache->set( $code, $cache );
559 $this->saveToCaches( $cache, 'local-only', $code );
560 $success = true;
561 }
562
563 return $success;
564 }
565
575 private function loadFromDB( $code, $mode = null ) {
576 $icp = MediaWikiServices::getInstance()->getConnectionProvider();
577
578 $dbr = ( $mode === self::FOR_UPDATE ) ? $icp->getPrimaryDatabase() : $icp->getReplicaDatabase();
579
580 $cache = [];
581
582 $mostused = []; // list of "<cased message key>/<code>"
583 if ( $this->adaptive && $code !== $this->contLangCode ) {
584 if ( !$this->cache->has( $this->contLangCode ) ) {
585 $this->load( $this->contLangCode );
586 }
587 $mostused = array_keys( $this->cache->get( $this->contLangCode ) );
588 foreach ( $mostused as $key => $value ) {
589 $mostused[$key] = "$value/$code";
590 }
591 }
592
593 // Common conditions
594 $conds = [
595 'page_is_redirect' => 0,
596 'page_namespace' => NS_MEDIAWIKI,
597 ];
598 if ( count( $mostused ) ) {
599 $conds['page_title'] = $mostused;
600 } elseif ( $code !== $this->contLangCode ) {
601 $conds[] = $dbr->expr(
602 'page_title',
603 IExpression::LIKE,
604 new LikeValue( $dbr->anyString(), '/', $code )
605 );
606 } else {
607 // Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
608 // other than language code.
609 $conds[] = $dbr->expr(
610 'page_title',
611 IExpression::NOT_LIKE,
612 new LikeValue( $dbr->anyString(), '/', $dbr->anyString() )
613 );
614 }
615
616 // Set the stubs for oversized software-defined messages in the main cache map
617 $res = $dbr->newSelectQueryBuilder()
618 ->select( [ 'page_title', 'page_latest' ] )
619 ->from( 'page' )
620 ->where( $conds )
621 ->andWhere( [ 'page_len > ' . intval( $this->maxEntrySize ) ] )
622 ->caller( __METHOD__ . "($code)-big" )->fetchResultSet();
623 foreach ( $res as $row ) {
624 // Include entries/stubs for all keys in $mostused in adaptive mode
625 if ( $this->adaptive || $this->isMainCacheable( $row->page_title ) ) {
626 $cache[$row->page_title] = '!TOO BIG';
627 }
628 // At least include revision ID so page changes are reflected in the hash
629 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
630 }
631
632 // RevisionStore cannot be injected as it would break the installer since
633 // it instantiates MessageCache before the DB.
634 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
635 // Set the text for small software-defined messages in the main cache map
636 $revQuery = $revisionStore->getQueryInfo( [ 'page' ] );
637
638 // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
639 // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
640 // query (and also reorder it ourselves because as generated by RevisionStore it'll have
641 // `revision` first rather than `page`).
642 $revQuery['joins']['revision'] = $revQuery['joins']['page'];
643 unset( $revQuery['joins']['page'] );
644 // It isn't actually necessary to reorder $revQuery['tables'] as Database does the right thing
645 // when join conditions are given for all joins, but Gergő is wary of relying on that so pull
646 // `page` to the start.
647 $revQuery['tables'] = array_merge(
648 [ 'page' ],
649 array_diff( $revQuery['tables'], [ 'page' ] )
650 );
651
652 $res = $dbr->newSelectQueryBuilder()
653 ->queryInfo( $revQuery )
654 ->where( $conds )
655 ->andWhere( [
656 $dbr->expr( 'page_len', '<=', intval( $this->maxEntrySize ) ),
657 'page_latest = rev_id' // get the latest revision only
658 ] )
659 ->caller( __METHOD__ . "($code)-small" )
660 ->straightJoinOption()
661 ->fetchResultSet();
662
663 // Don't load content from uncacheable rows (T313004)
664 [ $cacheableRows, $uncacheableRows ] = $this->separateCacheableRows( $res );
665 $result = $revisionStore->newRevisionsFromBatch( $cacheableRows, [
666 'slots' => [ SlotRecord::MAIN ],
667 'content' => true
668 ] );
669 $revisions = $result->isOK() ? $result->getValue() : [];
670
671 foreach ( $cacheableRows as $row ) {
672 try {
673 $rev = $revisions[$row->rev_id] ?? null;
674 $content = $rev ? $rev->getContent( SlotRecord::MAIN ) : null;
675 $text = $this->getMessageTextFromContent( $content );
676 } catch ( TimeoutException $e ) {
677 throw $e;
678 } catch ( Exception $ex ) {
679 $text = false;
680 }
681
682 if ( !is_string( $text ) ) {
683 $entry = '!ERROR';
684 $this->logger->error(
685 __METHOD__
686 . ": failed to load message page text for {$row->page_title} ($code)"
687 );
688 } else {
689 $entry = ' ' . $text;
690 }
691 $cache[$row->page_title] = $entry;
692 }
693
694 foreach ( $uncacheableRows as $row ) {
695 // T193271: The cache object gets too big and slow to generate.
696 // At least include revision ID, so that page changes are reflected in the hash.
697 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
698 }
699
700 $cache['VERSION'] = MSG_CACHE_VERSION;
701 ksort( $cache );
702
703 // Hash for validating local cache (APC). No need to take into account
704 // messages larger than $wgMaxMsgCacheEntrySize, since those are only
705 // stored and fetched from memcache.
706 $cache['HASH'] = md5( serialize( $cache ) );
707 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
708 unset( $cache['EXCESSIVE'] ); // only needed for hash
709
710 return $cache;
711 }
712
719 private function isLanguageLoaded( $lang ) {
720 // It is important that this only returns true if the cache was fully
721 // populated by load(), so that callers can assume all cache keys exist.
722 // It is possible for $this->cache to be only partially populated through
723 // methods like MessageCache::replace(), which must not make this method
724 // return true (T208897). And this method must cease to return true
725 // if the language was evicted by MapCacheLRU (T230690).
726 return $this->cache->hasField( $lang, 'VERSION' );
727 }
728
740 private function isMainCacheable( $name, $code = null ) {
741 // Convert the first letter to lowercase, and strip /code suffix
742 $name = $this->contLang->lcfirst( $name );
743 // Include common conversion table pages. This also avoids problems with
744 // Installer::parse() bailing out due to disallowed DB queries (T207979).
745 if ( strpos( $name, 'conversiontable/' ) === 0 ) {
746 return true;
747 }
748 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
749
750 if ( $code === null ) {
751 // Bulk load
752 if ( $this->systemMessageNames === null ) {
753 $this->systemMessageNames = array_fill_keys(
754 $this->localisationCache->getSubitemList( $this->contLangCode, 'messages' ),
755 true );
756 }
757 return isset( $this->systemMessageNames[$msg] );
758 } else {
759 // Use individual subitem
760 return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
761 }
762 }
763
771 private function separateCacheableRows( $res ) {
772 if ( $this->adaptive ) {
773 // Include entries/stubs for all keys in $mostused in adaptive mode
774 return [ $res, [] ];
775 }
776 $cacheableRows = [];
777 $uncacheableRows = [];
778 foreach ( $res as $row ) {
779 if ( $this->isMainCacheable( $row->page_title ) ) {
780 $cacheableRows[] = $row;
781 } else {
782 $uncacheableRows[] = $row;
783 }
784 }
785 return [ $cacheableRows, $uncacheableRows ];
786 }
787
794 public function replace( $title, $text ) {
795 if ( $this->disable ) {
796 return;
797 }
798
799 [ $msg, $code ] = $this->figureMessage( $title );
800 if ( strpos( $title, '/' ) !== false && $code === $this->contLangCode ) {
801 // Content language overrides do not use the /<code> suffix
802 return;
803 }
804
805 // (a) Update the process cache with the new message text
806 if ( $text === false ) {
807 // Page deleted
808 $this->cache->setField( $code, $title, '!NONEXISTENT' );
809 } else {
810 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up-to-date
811 $this->cache->setField( $code, $title, ' ' . $text );
812 }
813
814 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
815 DeferredUpdates::addUpdate(
816 new MessageCacheUpdate( $code, $title, $msg ),
817 DeferredUpdates::PRESEND
818 );
819 }
820
825 public function refreshAndReplaceInternal( string $code, array $replacements ) {
826 // Allow one caller at a time to avoid race conditions
827 [ $scopedLock ] = $this->getReentrantScopedLock( $code );
828 if ( !$scopedLock ) {
829 foreach ( $replacements as [ $title ] ) {
830 $this->logger->error(
831 __METHOD__ . ': could not acquire lock to update {title} ({code})',
832 [ 'title' => $title, 'code' => $code ] );
833 }
834
835 return;
836 }
837
838 // Load the existing cache to update it in the local DC cache.
839 // The other DCs will see a hash mismatch.
840 if ( $this->load( $code, self::FOR_UPDATE ) ) {
841 $cache = $this->cache->get( $code );
842 } else {
843 // Err? Fall back to loading from the database.
844 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
845 }
846 // Check if individual cache keys should exist and update cache accordingly
847 $newTextByTitle = []; // map of (title => content)
848 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
849 // Can not inject the WikiPageFactory as it would break the installer since
850 // it instantiates MessageCache before the DB.
851 $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
852 foreach ( $replacements as [ $title ] ) {
853 $page = $wikiPageFactory->newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
854 $page->loadPageData( IDBAccessObject::READ_LATEST );
855 $text = $this->getMessageTextFromContent( $page->getContent() );
856 // Remember the text for the blob store update later on
857 $newTextByTitle[$title] = $text ?? '';
858 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
859 if ( !is_string( $text ) ) {
860 $cache[$title] = '!NONEXISTENT';
861 } elseif ( strlen( $text ) > $this->maxEntrySize ) {
862 $cache[$title] = '!TOO BIG';
863 $newBigTitles[$title] = $page->getLatest();
864 } else {
865 $cache[$title] = ' ' . $text;
866 }
867 }
868 // Update HASH for the new key. Incorporates various administrative keys,
869 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
870 // and previous replace() calls), but that doesn't really matter since we
871 // only ever compare it for equality with a copy saved by saveToCaches().
872 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
873 // Update the too-big WAN cache entries now that we have the new HASH
874 foreach ( $newBigTitles as $title => $id ) {
875 // Match logic of loadCachedMessagePageEntry()
876 $this->wanCache->set(
877 $this->bigMessageCacheKey( $cache['HASH'], $title ),
878 ' ' . $newTextByTitle[$title],
879 self::WAN_TTL
880 );
881 }
882 // Mark this cache as definitely being "latest" (non-volatile) so
883 // load() calls do not try to refresh the cache with replica DB data
884 $cache['LATEST'] = time();
885 // Update the process cache
886 $this->cache->set( $code, $cache );
887 // Pre-emptively update the local datacenter cache so things like edit filter and
888 // prevented changes are reflected immediately; these often use MediaWiki: pages.
889 // The datacenter handling replace() calls should be the same one handling edits
890 // as they require HTTP POST.
891 $this->saveToCaches( $cache, 'all', $code );
892 // Release the lock now that the cache is saved
893 ScopedCallback::consume( $scopedLock );
894
895 // Relay the purge. Touching this check key expires cache contents
896 // and local cache (APC) validation hash across all datacenters.
897 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
898
899 // Purge the messages in the message blob store and fire any hook handlers
900 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
901 foreach ( $replacements as [ $title, $msg ] ) {
902 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
903 $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
904 }
905 }
906
913 private function isCacheExpired( $cache ) {
914 return !isset( $cache['VERSION'] ) ||
915 !isset( $cache['EXPIRY'] ) ||
916 $cache['VERSION'] !== MSG_CACHE_VERSION ||
917 $cache['EXPIRY'] <= wfTimestampNow();
918 }
919
929 private function saveToCaches( array $cache, $dest, $code = false ) {
930 if ( $dest === 'all' ) {
931 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
932 $success = $this->clusterCache->set( $cacheKey, $cache );
933 $this->setValidationHash( $code, $cache );
934 } else {
935 $success = true;
936 }
937
938 $this->saveToLocalCache( $code, $cache );
939
940 return $success;
941 }
942
949 private function getValidationHash( $code ) {
950 $curTTL = null;
951 $value = $this->wanCache->get(
952 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
953 $curTTL,
954 [ $this->getCheckKey( $code ) ]
955 );
956
957 if ( $value ) {
958 $hash = $value['hash'];
959 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
960 // Cache was recently updated via replace() and should be up-to-date.
961 // That method is only called in the primary datacenter and uses FOR_UPDATE.
962 $expired = false;
963 } else {
964 // See if the "check" key was bumped after the hash was generated
965 $expired = ( $curTTL < 0 );
966 }
967 } else {
968 // No hash found at all; cache must regenerate to be safe
969 $hash = false;
970 $expired = true;
971 }
972
973 return [ $hash, $expired ];
974 }
975
986 private function setValidationHash( $code, array $cache ) {
987 $this->wanCache->set(
988 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
989 [
990 'hash' => $cache['HASH'],
991 'latest' => $cache['LATEST'] ?? 0
992 ],
993 WANObjectCache::TTL_INDEFINITE
994 );
995 }
996
1003 private function getReentrantScopedLock( $code, $timeout = self::WAIT_SEC ) {
1004 $key = $this->clusterCache->makeKey( 'messages', $code );
1005
1006 $watchPoint = $this->clusterCache->watchErrors();
1007 $scopedLock = $this->clusterCache->getScopedLock(
1008 $key,
1009 $timeout,
1010 self::LOCK_TTL,
1011 __METHOD__
1012 );
1013 $error = ( !$scopedLock && $this->clusterCache->getLastError( $watchPoint ) );
1014
1015 return [ $scopedLock, $error ];
1016 }
1017
1052 public function get( $key, $useDB = true, $langcode = true, &$usedKey = '' ) {
1053 if ( is_int( $key ) ) {
1054 // Fix numerical strings that somehow become ints on their way here
1055 $key = (string)$key;
1056 } elseif ( !is_string( $key ) ) {
1057 throw new TypeError( 'Message key must be a string' );
1058 } elseif ( $key === '' ) {
1059 // Shortcut: the empty key is always missing
1060 return false;
1061 }
1062
1063 $language = $this->getLanguageObject( $langcode );
1064
1065 // Normalise title-case input (with some inlining)
1066 $lckey = self::normalizeKey( $key );
1067
1068 // Initialize the overrides here to prevent calling the hook too early.
1069 if ( $this->messageKeyOverrides === null ) {
1070 $this->messageKeyOverrides = [];
1071 $this->hookRunner->onMessageCacheFetchOverrides( $this->messageKeyOverrides );
1072 }
1073
1074 if ( isset( $this->messageKeyOverrides[$lckey] ) ) {
1075 $override = $this->messageKeyOverrides[$lckey];
1076
1077 // Strings are deliberately interpreted as message keys,
1078 // to prevent ambiguity between message keys and functions.
1079 if ( is_string( $override ) ) {
1080 $lckey = $override;
1081 } else {
1082 $lckey = $override( $lckey, $this, $language, $useDB );
1083 }
1084 }
1085
1086 $this->hookRunner->onMessageCache__get( $lckey );
1087
1088 $usedKey = $lckey;
1089
1090 // Loop through each language in the fallback list until we find something useful
1091 $message = $this->getMessageFromFallbackChain(
1092 $language,
1093 $lckey,
1094 !$this->disable && $useDB
1095 );
1096
1097 // If we still have no message, maybe the key was in fact a full key so try that
1098 if ( $message === false ) {
1099 $parts = explode( '/', $lckey );
1100 // We may get calls for things that are http-urls from sidebar
1101 // Let's not load nonexistent languages for those
1102 // They usually have more than one slash.
1103 if ( count( $parts ) === 2 && $parts[1] !== '' ) {
1104 $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] ) ?? false;
1105 }
1106 }
1107
1108 // Post-processing if the message exists
1109 if ( $message !== false ) {
1110 // Fix whitespace
1111 $message = str_replace(
1112 [
1113 // Fix for trailing whitespace, removed by textarea
1114 '&#32;',
1115 // Fix for NBSP, converted to space by firefox
1116 '&nbsp;',
1117 '&#160;',
1118 '&shy;'
1119 ],
1120 [
1121 ' ',
1122 "\u{00A0}",
1123 "\u{00A0}",
1124 "\u{00AD}"
1125 ],
1126 $message
1127 );
1128 }
1129
1130 return $message;
1131 }
1132
1148 private function getLanguageObject( $langcode ) {
1149 # Identify which language to get or create a language object for.
1150 # Using is_object here due to Stub objects.
1151 if ( is_object( $langcode ) ) {
1152 # Great, we already have the object (hopefully)!
1153 return $langcode;
1154 }
1155
1156 if ( $langcode === true || $langcode === $this->contLangCode ) {
1157 # $langcode is the language code of the wikis content language object.
1158 # or it is a boolean and value is true
1159 return $this->contLang;
1160 }
1161
1162 global $wgLang;
1163 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1164 # $langcode is the language code of user language object.
1165 # or it was a boolean and value is false
1166 return $wgLang;
1167 }
1168
1169 $validCodes = array_keys( $this->languageNameUtils->getLanguageNames() );
1170 if ( in_array( $langcode, $validCodes ) ) {
1171 # $langcode corresponds to a valid language.
1172 return $this->langFactory->getLanguage( $langcode );
1173 }
1174
1175 # $langcode is a string, but not a valid language code; use content language.
1176 $this->logger->debug( 'Invalid language code passed to' . __METHOD__ . ', falling back to content language.' );
1177 return $this->contLang;
1178 }
1179
1192 private function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1193 $alreadyTried = [];
1194
1195 // First try the requested language.
1196 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1197 if ( $message !== false ) {
1198 return $message;
1199 }
1200
1201 // Now try checking the site language.
1202 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1203 return $message;
1204 }
1205
1216 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1217 $langcode = $lang->getCode();
1218
1219 // Try checking the database for the requested language
1220 if ( $useDB ) {
1221 $uckey = $this->contLang->ucfirst( $lckey );
1222
1223 if ( !isset( $alreadyTried[$langcode] ) ) {
1224 $message = $this->getMsgFromNamespace(
1225 $this->getMessagePageName( $langcode, $uckey ),
1226 $langcode
1227 );
1228 if ( $message !== false ) {
1229 return $message;
1230 }
1231 $alreadyTried[$langcode] = true;
1232 }
1233 } else {
1234 $uckey = null;
1235 }
1236
1237 // Return a special value handled in Message::format() to display the message key
1238 // (and fallback keys) and the parameters passed to the message.
1239 // TODO: Move to a better place.
1240 if ( $langcode === 'qqx' ) {
1241 return '($*)';
1242 } elseif (
1243 $langcode === 'x-xss' &&
1244 $this->useXssLanguage &&
1245 !in_array( $lckey, $this->rawHtmlMessages, true )
1246 ) {
1247 $xssViaInnerHtml = "<script>alert('$lckey')</script>";
1248 $xssViaAttribute = '">' . $xssViaInnerHtml . '<x y="';
1249 return $xssViaInnerHtml . $xssViaAttribute . '($*)';
1250 }
1251
1252 // Check the localisation cache
1253 [ $defaultMessage, $messageSource ] =
1254 $this->localisationCache->getSubitemWithSource( $langcode, 'messages', $lckey );
1255 if ( $messageSource === $langcode ) {
1256 return $defaultMessage;
1257 }
1258
1259 // Try checking the database for all of the fallback languages
1260 if ( $useDB ) {
1261 $fallbackChain = $this->languageFallback->getAll( $langcode );
1262
1263 foreach ( $fallbackChain as $code ) {
1264 if ( isset( $alreadyTried[$code] ) ) {
1265 continue;
1266 }
1267
1268 $message = $this->getMsgFromNamespace(
1269 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable uckey is set when used
1270 $this->getMessagePageName( $code, $uckey ), $code );
1271
1272 if ( $message !== false ) {
1273 return $message;
1274 }
1275 $alreadyTried[$code] = true;
1276
1277 // Reached the source language of the default message. Don't look for DB overrides
1278 // further back in the fallback chain. (T229992)
1279 if ( $code === $messageSource ) {
1280 return $defaultMessage;
1281 }
1282 }
1283 }
1284
1285 return $defaultMessage ?? false;
1286 }
1287
1295 private function getMessagePageName( $langcode, $uckey ) {
1296 if ( $langcode === $this->contLangCode ) {
1297 // Messages created in the content language will not have the /lang extension
1298 return $uckey;
1299 } else {
1300 return "$uckey/$langcode";
1301 }
1302 }
1303
1316 public function getMsgFromNamespace( $title, $code ) {
1317 // Load all MediaWiki page definitions into cache. Note that individual keys
1318 // already loaded into the cache during this request remain in the cache, which
1319 // includes the value of hook-defined messages.
1320 $this->load( $code );
1321
1322 $entry = $this->cache->getField( $code, $title );
1323
1324 if ( $entry !== null ) {
1325 // Message page exists as an override of a software messages
1326 if ( substr( $entry, 0, 1 ) === ' ' ) {
1327 // The message exists and is not '!TOO BIG' or '!ERROR'
1328 return (string)substr( $entry, 1 );
1329 } elseif ( $entry === '!NONEXISTENT' ) {
1330 // The text might be '-' or missing due to some data loss
1331 return false;
1332 }
1333 // Load the message page, utilizing the individual message cache.
1334 // If the page does not exist, there will be no hook handler fallbacks.
1335 $entry = $this->loadCachedMessagePageEntry(
1336 $title,
1337 $code,
1338 $this->cache->getField( $code, 'HASH' )
1339 );
1340 } else {
1341 // Message page either does not exist or does not override a software message
1342 if ( !$this->isMainCacheable( $title, $code ) ) {
1343 // Message page does not override any software-defined message. A custom
1344 // message might be defined to have content or settings specific to the wiki.
1345 // Load the message page, utilizing the individual message cache as needed.
1346 $entry = $this->loadCachedMessagePageEntry(
1347 $title,
1348 $code,
1349 $this->cache->getField( $code, 'HASH' )
1350 );
1351 }
1352 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1353 // Message does not have a MediaWiki page definition; try hook handlers
1354 $message = false;
1355 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
1356 $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1357 if ( $message !== false ) {
1358 $this->cache->setField( $code, $title, ' ' . $message );
1359 } else {
1360 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1361 }
1362
1363 return $message;
1364 }
1365 }
1366
1367 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1368 if ( $this->cacheVolatile[$code] ) {
1369 // Make sure that individual keys respect the WAN cache holdoff period too
1370 $this->logger->debug(
1371 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1372 [ 'titleKey' => $title, 'code' => $code ] );
1373 } else {
1374 $this->cache->setField( $code, $title, $entry );
1375 }
1376 // The message exists, so make sure a string is returned
1377 return (string)substr( $entry, 1 );
1378 }
1379
1380 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1381
1382 return false;
1383 }
1384
1391 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1392 $fname = __METHOD__;
1393 return $this->srvCache->getWithSetCallback(
1394 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1395 BagOStuff::TTL_HOUR,
1396 function () use ( $code, $dbKey, $hash, $fname ) {
1397 return $this->wanCache->getWithSetCallback(
1398 $this->bigMessageCacheKey( $hash, $dbKey ),
1399 self::WAN_TTL,
1400 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1401 // Try loading the message from the database
1402 $setOpts += Database::getCacheSetOptions(
1403 MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase()
1404 );
1405 // Use newKnownCurrent() to avoid querying revision/user tables
1406 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1407 // Injecting RevisionStore breaks installer since it
1408 // instantiates MessageCache before DB.
1409 $revision = MediaWikiServices::getInstance()
1410 ->getRevisionLookup()
1411 ->getKnownCurrentRevision( $title );
1412 if ( !$revision ) {
1413 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1414 // When overrides are created, self::replace() takes care of the cache.
1415 return '!NONEXISTENT';
1416 }
1417 $content = $revision->getContent( SlotRecord::MAIN );
1418 if ( $content ) {
1419 $message = $this->getMessageTextFromContent( $content );
1420 } else {
1421 $this->logger->warning(
1422 $fname . ': failed to load page text for \'{titleKey}\'',
1423 [ 'titleKey' => $dbKey, 'code' => $code ]
1424 );
1425 $message = null;
1426 }
1427
1428 if ( !is_string( $message ) ) {
1429 // Revision failed to load Content, or Content is incompatible with wikitext.
1430 // Possibly a temporary loading failure.
1431 $ttl = 5;
1432
1433 return '!NONEXISTENT';
1434 }
1435
1436 return ' ' . $message;
1437 }
1438 );
1439 }
1440 );
1441 }
1442
1450 public function transform( $message, $interface = false, $language = null, PageReference $page = null ) {
1451 // Avoid creating parser if nothing to transform
1452 if ( $this->inParser || !str_contains( $message, '{{' ) ) {
1453 return $message;
1454 }
1455
1456 $parser = $this->getParser();
1457 $popts = $this->getParserOptions();
1458 $popts->setInterfaceMessage( $interface );
1459 $popts->setTargetLanguage( $language );
1460
1461 $userlang = $popts->setUserLang( $language );
1462 $this->inParser = true;
1463 $message = $parser->transformMsg( $message, $popts, $page );
1464 $this->inParser = false;
1465 $popts->setUserLang( $userlang );
1466
1467 return $message;
1468 }
1469
1473 public function getParser() {
1474 if ( !$this->parser ) {
1475 $this->parser = $this->parserFactory->create();
1476 }
1477
1478 return $this->parser;
1479 }
1480
1489 public function parse( $text, PageReference $page = null, $linestart = true,
1490 $interface = false, $language = null
1491 ) {
1492 global $wgTitle;
1493
1494 if ( $this->inParser ) {
1495 return htmlspecialchars( $text );
1496 }
1497
1498 $parser = $this->getParser();
1499 $popts = $this->getParserOptions();
1500 $popts->setInterfaceMessage( $interface );
1501
1502 if ( is_string( $language ) ) {
1503 $language = $this->langFactory->getLanguage( $language );
1504 }
1505 $popts->setTargetLanguage( $language );
1506
1507 if ( !$page ) {
1508 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1509 $logger->info(
1510 __METHOD__ . ' called with no title set.',
1511 [ 'exception' => new RuntimeException ]
1512 );
1513 $page = $wgTitle;
1514 }
1515 // Sometimes $wgTitle isn't set either...
1516 if ( !$page ) {
1517 // It's not uncommon having a null $wgTitle in scripts. See r80898
1518 // Create a ghost title in such case
1519 $page = PageReferenceValue::localReference(
1520 NS_SPECIAL,
1521 'Badtitle/title not set in ' . __METHOD__
1522 );
1523 }
1524
1525 $this->inParser = true;
1526 $res = $parser->parse( $text, $page, $popts, $linestart );
1527 $this->inParser = false;
1528
1529 return $res;
1530 }
1531
1532 public function disable() {
1533 $this->disable = true;
1534 }
1535
1536 public function enable() {
1537 $this->disable = false;
1538 }
1539
1552 public function isDisabled() {
1553 return $this->disable;
1554 }
1555
1561 public function clear() {
1562 $langs = $this->languageNameUtils->getLanguageNames();
1563 foreach ( $langs as $code => $_ ) {
1564 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1565 }
1566 $this->cache->clear();
1567 }
1568
1573 public function figureMessage( $key ) {
1574 $pieces = explode( '/', $key );
1575 if ( count( $pieces ) < 2 ) {
1576 return [ $key, $this->contLangCode ];
1577 }
1578
1579 $lang = array_pop( $pieces );
1580 if ( !$this->languageNameUtils->getLanguageName(
1581 $lang,
1582 LanguageNameUtils::AUTONYMS,
1583 LanguageNameUtils::DEFINED
1584 ) ) {
1585 return [ $key, $this->contLangCode ];
1586 }
1587
1588 $message = implode( '/', $pieces );
1589
1590 return [ $message, $lang ];
1591 }
1592
1602 public function getAllMessageKeys( $code ) {
1603 $this->load( $code );
1604 if ( !$this->cache->has( $code ) ) {
1605 // Apparently load() failed
1606 return null;
1607 }
1608 // Remove administrative keys
1609 $cache = $this->cache->get( $code );
1610 unset( $cache['VERSION'] );
1611 unset( $cache['EXPIRY'] );
1612 unset( $cache['EXCESSIVE'] );
1613 // Remove any !NONEXISTENT keys
1614 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1615
1616 // Keys may appear with a capital first letter. lcfirst them.
1617 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1618 }
1619
1627 public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1628 // treat null as not existing
1629 $msgText = $this->getMessageTextFromContent( $content ) ?? false;
1630
1631 $this->replace( $linkTarget->getDBkey(), $msgText );
1632
1633 if ( $this->contLangConverter->hasVariants() ) {
1634 $this->contLangConverter->updateConversionTable( $linkTarget );
1635 }
1636 }
1637
1642 public function getCheckKey( $code ) {
1643 return $this->wanCache->makeKey( 'messages', $code );
1644 }
1645
1650 private function getMessageTextFromContent( Content $content = null ) {
1651 // @TODO: could skip pseudo-messages like js/css here, based on content model
1652 if ( $content ) {
1653 // Message page exists...
1654 // XXX: Is this the right way to turn a Content object into a message?
1655 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1656 // CssContent. MessageContent is *not* used for storing messages, it's
1657 // only used for wrapping them when needed.
1658 $msgText = $content->getWikitextForTransclusion();
1659 if ( $msgText === false || $msgText === null ) {
1660 // This might be due to some kind of misconfiguration...
1661 $msgText = null;
1662 $this->logger->warning(
1663 __METHOD__ . ": message content doesn't provide wikitext "
1664 . "(content model: " . $content->getModel() . ")" );
1665 }
1666 } else {
1667 // Message page does not exist...
1668 $msgText = false;
1669 }
1670
1671 return $msgText;
1672 }
1673
1679 private function bigMessageCacheKey( $hash, $title ) {
1680 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1681 }
1682}
const NS_MEDIAWIKI
Definition Defines.php:72
const NS_SPECIAL
Definition Defines.php:53
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgLang
Definition Setup.php:537
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgTitle
Definition Setup.php:537
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:85
A BagOStuff object with no objects in it.
Base class for language-specific code.
Definition Language.php:63
getCode()
Get the internal language code for this language object.
Caching for the contents of localisation files.
Store key-value entries in a size-limited in-memory LRU cache.
set( $key, $value, $rank=self::RANK_TOP)
Set a key/value pair.
get( $key, $maxAge=INF, $default=null)
Get the value for a key.
hasField( $key, $field, $maxAge=INF)
A class for passing options to services.
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
Group all the pieces relevant to the context of a request into one instance.
Defer callable updates to run later in the PHP process.
Message cache purging and in-place update handler for specific message page changes.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
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.
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Immutable value object representing a page reference.
ParserOutput is a rendering of a Content object or a message.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:156
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:693
transformMsg( $text, ParserOptions $options, ?PageReference $page=null)
Wrapper for preprocess()
Definition Parser.php:4940
Value object representing a content slot associated with a page revision.
Class to implement stub globals, which are globals that delay loading the their associated module cod...
Stub object for the user language.
Represents a title within MediaWiki.
Definition Title.php:78
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.
replace( $title, $text)
Updates cache as necessary when message page is changed.
Set options of the Parser.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Multi-datacenter aware caching interface.
Content of like value.
Definition LikeValue.php:14
Base interface for representing page content.
Definition Content.php:37
The shared interface for all language converters.
Represents the target of a wiki link.
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.