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->select(
653 $revQuery['tables'],
654 $revQuery['fields'],
655 array_merge( $conds, [
656 'page_len <= ' . intval( $this->maxEntrySize ),
657 'page_latest = rev_id' // get the latest revision only
658 ] ),
659 __METHOD__ . "($code)-small",
660 [ 'STRAIGHT_JOIN' ],
661 $revQuery['joins']
662 );
663
664 // Don't load content from uncacheable rows (T313004)
665 [ $cacheableRows, $uncacheableRows ] = $this->separateCacheableRows( $res );
666 $result = $revisionStore->newRevisionsFromBatch( $cacheableRows, [
667 'slots' => [ SlotRecord::MAIN ],
668 'content' => true
669 ] );
670 $revisions = $result->isOK() ? $result->getValue() : [];
671
672 foreach ( $cacheableRows as $row ) {
673 try {
674 $rev = $revisions[$row->rev_id] ?? null;
675 $content = $rev ? $rev->getContent( SlotRecord::MAIN ) : null;
676 $text = $this->getMessageTextFromContent( $content );
677 } catch ( TimeoutException $e ) {
678 throw $e;
679 } catch ( Exception $ex ) {
680 $text = false;
681 }
682
683 if ( !is_string( $text ) ) {
684 $entry = '!ERROR';
685 $this->logger->error(
686 __METHOD__
687 . ": failed to load message page text for {$row->page_title} ($code)"
688 );
689 } else {
690 $entry = ' ' . $text;
691 }
692 $cache[$row->page_title] = $entry;
693 }
694
695 foreach ( $uncacheableRows as $row ) {
696 // T193271: The cache object gets too big and slow to generate.
697 // At least include revision ID, so that page changes are reflected in the hash.
698 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
699 }
700
701 $cache['VERSION'] = MSG_CACHE_VERSION;
702 ksort( $cache );
703
704 // Hash for validating local cache (APC). No need to take into account
705 // messages larger than $wgMaxMsgCacheEntrySize, since those are only
706 // stored and fetched from memcache.
707 $cache['HASH'] = md5( serialize( $cache ) );
708 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
709 unset( $cache['EXCESSIVE'] ); // only needed for hash
710
711 return $cache;
712 }
713
720 private function isLanguageLoaded( $lang ) {
721 // It is important that this only returns true if the cache was fully
722 // populated by load(), so that callers can assume all cache keys exist.
723 // It is possible for $this->cache to be only partially populated through
724 // methods like MessageCache::replace(), which must not make this method
725 // return true (T208897). And this method must cease to return true
726 // if the language was evicted by MapCacheLRU (T230690).
727 return $this->cache->hasField( $lang, 'VERSION' );
728 }
729
741 private function isMainCacheable( $name, $code = null ) {
742 // Convert the first letter to lowercase, and strip /code suffix
743 $name = $this->contLang->lcfirst( $name );
744 // Include common conversion table pages. This also avoids problems with
745 // Installer::parse() bailing out due to disallowed DB queries (T207979).
746 if ( strpos( $name, 'conversiontable/' ) === 0 ) {
747 return true;
748 }
749 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
750
751 if ( $code === null ) {
752 // Bulk load
753 if ( $this->systemMessageNames === null ) {
754 $this->systemMessageNames = array_fill_keys(
755 $this->localisationCache->getSubitemList( $this->contLangCode, 'messages' ),
756 true );
757 }
758 return isset( $this->systemMessageNames[$msg] );
759 } else {
760 // Use individual subitem
761 return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
762 }
763 }
764
772 private function separateCacheableRows( $res ) {
773 if ( $this->adaptive ) {
774 // Include entries/stubs for all keys in $mostused in adaptive mode
775 return [ $res, [] ];
776 }
777 $cacheableRows = [];
778 $uncacheableRows = [];
779 foreach ( $res as $row ) {
780 if ( $this->isMainCacheable( $row->page_title ) ) {
781 $cacheableRows[] = $row;
782 } else {
783 $uncacheableRows[] = $row;
784 }
785 }
786 return [ $cacheableRows, $uncacheableRows ];
787 }
788
795 public function replace( $title, $text ) {
796 if ( $this->disable ) {
797 return;
798 }
799
800 [ $msg, $code ] = $this->figureMessage( $title );
801 if ( strpos( $title, '/' ) !== false && $code === $this->contLangCode ) {
802 // Content language overrides do not use the /<code> suffix
803 return;
804 }
805
806 // (a) Update the process cache with the new message text
807 if ( $text === false ) {
808 // Page deleted
809 $this->cache->setField( $code, $title, '!NONEXISTENT' );
810 } else {
811 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up-to-date
812 $this->cache->setField( $code, $title, ' ' . $text );
813 }
814
815 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
816 DeferredUpdates::addUpdate(
817 new MessageCacheUpdate( $code, $title, $msg ),
818 DeferredUpdates::PRESEND
819 );
820 }
821
826 public function refreshAndReplaceInternal( string $code, array $replacements ) {
827 // Allow one caller at a time to avoid race conditions
828 [ $scopedLock ] = $this->getReentrantScopedLock( $code );
829 if ( !$scopedLock ) {
830 foreach ( $replacements as [ $title ] ) {
831 $this->logger->error(
832 __METHOD__ . ': could not acquire lock to update {title} ({code})',
833 [ 'title' => $title, 'code' => $code ] );
834 }
835
836 return;
837 }
838
839 // Load the existing cache to update it in the local DC cache.
840 // The other DCs will see a hash mismatch.
841 if ( $this->load( $code, self::FOR_UPDATE ) ) {
842 $cache = $this->cache->get( $code );
843 } else {
844 // Err? Fall back to loading from the database.
845 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
846 }
847 // Check if individual cache keys should exist and update cache accordingly
848 $newTextByTitle = []; // map of (title => content)
849 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
850 // Can not inject the WikiPageFactory as it would break the installer since
851 // it instantiates MessageCache before the DB.
852 $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
853 foreach ( $replacements as [ $title ] ) {
854 $page = $wikiPageFactory->newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
855 $page->loadPageData( IDBAccessObject::READ_LATEST );
856 $text = $this->getMessageTextFromContent( $page->getContent() );
857 // Remember the text for the blob store update later on
858 $newTextByTitle[$title] = $text ?? '';
859 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
860 if ( !is_string( $text ) ) {
861 $cache[$title] = '!NONEXISTENT';
862 } elseif ( strlen( $text ) > $this->maxEntrySize ) {
863 $cache[$title] = '!TOO BIG';
864 $newBigTitles[$title] = $page->getLatest();
865 } else {
866 $cache[$title] = ' ' . $text;
867 }
868 }
869 // Update HASH for the new key. Incorporates various administrative keys,
870 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
871 // and previous replace() calls), but that doesn't really matter since we
872 // only ever compare it for equality with a copy saved by saveToCaches().
873 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
874 // Update the too-big WAN cache entries now that we have the new HASH
875 foreach ( $newBigTitles as $title => $id ) {
876 // Match logic of loadCachedMessagePageEntry()
877 $this->wanCache->set(
878 $this->bigMessageCacheKey( $cache['HASH'], $title ),
879 ' ' . $newTextByTitle[$title],
880 self::WAN_TTL
881 );
882 }
883 // Mark this cache as definitely being "latest" (non-volatile) so
884 // load() calls do not try to refresh the cache with replica DB data
885 $cache['LATEST'] = time();
886 // Update the process cache
887 $this->cache->set( $code, $cache );
888 // Pre-emptively update the local datacenter cache so things like edit filter and
889 // prevented changes are reflected immediately; these often use MediaWiki: pages.
890 // The datacenter handling replace() calls should be the same one handling edits
891 // as they require HTTP POST.
892 $this->saveToCaches( $cache, 'all', $code );
893 // Release the lock now that the cache is saved
894 ScopedCallback::consume( $scopedLock );
895
896 // Relay the purge. Touching this check key expires cache contents
897 // and local cache (APC) validation hash across all datacenters.
898 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
899
900 // Purge the messages in the message blob store and fire any hook handlers
901 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
902 foreach ( $replacements as [ $title, $msg ] ) {
903 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
904 $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
905 }
906 }
907
914 private function isCacheExpired( $cache ) {
915 return !isset( $cache['VERSION'] ) ||
916 !isset( $cache['EXPIRY'] ) ||
917 $cache['VERSION'] !== MSG_CACHE_VERSION ||
918 $cache['EXPIRY'] <= wfTimestampNow();
919 }
920
930 private function saveToCaches( array $cache, $dest, $code = false ) {
931 if ( $dest === 'all' ) {
932 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
933 $success = $this->clusterCache->set( $cacheKey, $cache );
934 $this->setValidationHash( $code, $cache );
935 } else {
936 $success = true;
937 }
938
939 $this->saveToLocalCache( $code, $cache );
940
941 return $success;
942 }
943
950 private function getValidationHash( $code ) {
951 $curTTL = null;
952 $value = $this->wanCache->get(
953 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
954 $curTTL,
955 [ $this->getCheckKey( $code ) ]
956 );
957
958 if ( $value ) {
959 $hash = $value['hash'];
960 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
961 // Cache was recently updated via replace() and should be up-to-date.
962 // That method is only called in the primary datacenter and uses FOR_UPDATE.
963 $expired = false;
964 } else {
965 // See if the "check" key was bumped after the hash was generated
966 $expired = ( $curTTL < 0 );
967 }
968 } else {
969 // No hash found at all; cache must regenerate to be safe
970 $hash = false;
971 $expired = true;
972 }
973
974 return [ $hash, $expired ];
975 }
976
987 private function setValidationHash( $code, array $cache ) {
988 $this->wanCache->set(
989 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
990 [
991 'hash' => $cache['HASH'],
992 'latest' => $cache['LATEST'] ?? 0
993 ],
994 WANObjectCache::TTL_INDEFINITE
995 );
996 }
997
1004 private function getReentrantScopedLock( $code, $timeout = self::WAIT_SEC ) {
1005 $key = $this->clusterCache->makeKey( 'messages', $code );
1006
1007 $watchPoint = $this->clusterCache->watchErrors();
1008 $scopedLock = $this->clusterCache->getScopedLock(
1009 $key,
1010 $timeout,
1011 self::LOCK_TTL,
1012 __METHOD__
1013 );
1014 $error = ( !$scopedLock && $this->clusterCache->getLastError( $watchPoint ) );
1015
1016 return [ $scopedLock, $error ];
1017 }
1018
1051 public function get( $key, $useDB = true, $langcode = true ) {
1052 if ( is_int( $key ) ) {
1053 // Fix numerical strings that somehow become ints on their way here
1054 $key = (string)$key;
1055 } elseif ( !is_string( $key ) ) {
1056 throw new TypeError( 'Message key must be a string' );
1057 } elseif ( $key === '' ) {
1058 // Shortcut: the empty key is always missing
1059 return false;
1060 }
1061
1062 $language = $this->getLanguageObject( $langcode );
1063
1064 // Normalise title-case input (with some inlining)
1065 $lckey = self::normalizeKey( $key );
1066
1067 // Initialize the overrides here to prevent calling the hook too early.
1068 if ( $this->messageKeyOverrides === null ) {
1069 $this->messageKeyOverrides = [];
1070 $this->hookRunner->onMessageCacheFetchOverrides( $this->messageKeyOverrides );
1071 }
1072
1073 if ( isset( $this->messageKeyOverrides[$lckey] ) ) {
1074 $override = $this->messageKeyOverrides[$lckey];
1075
1076 // Strings are deliberately interpreted as message keys,
1077 // to prevent ambiguity between message keys and functions.
1078 if ( is_string( $override ) ) {
1079 $lckey = $override;
1080 } else {
1081 $lckey = $override( $lckey, $this, $language, $useDB );
1082 }
1083 }
1084
1085 $this->hookRunner->onMessageCache__get( $lckey );
1086
1087 // Loop through each language in the fallback list until we find something useful
1088 $message = $this->getMessageFromFallbackChain(
1089 $language,
1090 $lckey,
1091 !$this->disable && $useDB
1092 );
1093
1094 // If we still have no message, maybe the key was in fact a full key so try that
1095 if ( $message === false ) {
1096 $parts = explode( '/', $lckey );
1097 // We may get calls for things that are http-urls from sidebar
1098 // Let's not load nonexistent languages for those
1099 // They usually have more than one slash.
1100 if ( count( $parts ) === 2 && $parts[1] !== '' ) {
1101 $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] ) ?? false;
1102 }
1103 }
1104
1105 // Post-processing if the message exists
1106 if ( $message !== false ) {
1107 // Fix whitespace
1108 $message = str_replace(
1109 [
1110 // Fix for trailing whitespace, removed by textarea
1111 '&#32;',
1112 // Fix for NBSP, converted to space by firefox
1113 '&nbsp;',
1114 '&#160;',
1115 '&shy;'
1116 ],
1117 [
1118 ' ',
1119 "\u{00A0}",
1120 "\u{00A0}",
1121 "\u{00AD}"
1122 ],
1123 $message
1124 );
1125 }
1126
1127 return $message;
1128 }
1129
1145 private function getLanguageObject( $langcode ) {
1146 # Identify which language to get or create a language object for.
1147 # Using is_object here due to Stub objects.
1148 if ( is_object( $langcode ) ) {
1149 # Great, we already have the object (hopefully)!
1150 return $langcode;
1151 }
1152
1153 if ( $langcode === true || $langcode === $this->contLangCode ) {
1154 # $langcode is the language code of the wikis content language object.
1155 # or it is a boolean and value is true
1156 return $this->contLang;
1157 }
1158
1159 global $wgLang;
1160 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1161 # $langcode is the language code of user language object.
1162 # or it was a boolean and value is false
1163 return $wgLang;
1164 }
1165
1166 $validCodes = array_keys( $this->languageNameUtils->getLanguageNames() );
1167 if ( in_array( $langcode, $validCodes ) ) {
1168 # $langcode corresponds to a valid language.
1169 return $this->langFactory->getLanguage( $langcode );
1170 }
1171
1172 # $langcode is a string, but not a valid language code; use content language.
1173 $this->logger->debug( 'Invalid language code passed to' . __METHOD__ . ', falling back to content language.' );
1174 return $this->contLang;
1175 }
1176
1189 private function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1190 $alreadyTried = [];
1191
1192 // First try the requested language.
1193 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1194 if ( $message !== false ) {
1195 return $message;
1196 }
1197
1198 // Now try checking the site language.
1199 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1200 return $message;
1201 }
1202
1213 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1214 $langcode = $lang->getCode();
1215
1216 // Try checking the database for the requested language
1217 if ( $useDB ) {
1218 $uckey = $this->contLang->ucfirst( $lckey );
1219
1220 if ( !isset( $alreadyTried[$langcode] ) ) {
1221 $message = $this->getMsgFromNamespace(
1222 $this->getMessagePageName( $langcode, $uckey ),
1223 $langcode
1224 );
1225 if ( $message !== false ) {
1226 return $message;
1227 }
1228 $alreadyTried[$langcode] = true;
1229 }
1230 } else {
1231 $uckey = null;
1232 }
1233
1234 // Return a special value handled in Message::format() to display the message key
1235 // (and fallback keys) and the parameters passed to the message.
1236 // TODO: Move to a better place.
1237 if ( $langcode === 'qqx' ) {
1238 return '($*)';
1239 } elseif (
1240 $langcode === 'x-xss' &&
1241 $this->useXssLanguage &&
1242 !in_array( $lckey, $this->rawHtmlMessages, true )
1243 ) {
1244 $xssViaInnerHtml = "<script>alert('$lckey')</script>";
1245 $xssViaAttribute = '">' . $xssViaInnerHtml . '<x y="';
1246 return $xssViaInnerHtml . $xssViaAttribute . '($*)';
1247 }
1248
1249 // Check the localisation cache
1250 [ $defaultMessage, $messageSource ] =
1251 $this->localisationCache->getSubitemWithSource( $langcode, 'messages', $lckey );
1252 if ( $messageSource === $langcode ) {
1253 return $defaultMessage;
1254 }
1255
1256 // Try checking the database for all of the fallback languages
1257 if ( $useDB ) {
1258 $fallbackChain = $this->languageFallback->getAll( $langcode );
1259
1260 foreach ( $fallbackChain as $code ) {
1261 if ( isset( $alreadyTried[$code] ) ) {
1262 continue;
1263 }
1264
1265 $message = $this->getMsgFromNamespace(
1266 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable uckey is set when used
1267 $this->getMessagePageName( $code, $uckey ), $code );
1268
1269 if ( $message !== false ) {
1270 return $message;
1271 }
1272 $alreadyTried[$code] = true;
1273
1274 // Reached the source language of the default message. Don't look for DB overrides
1275 // further back in the fallback chain. (T229992)
1276 if ( $code === $messageSource ) {
1277 return $defaultMessage;
1278 }
1279 }
1280 }
1281
1282 return $defaultMessage ?? false;
1283 }
1284
1292 private function getMessagePageName( $langcode, $uckey ) {
1293 if ( $langcode === $this->contLangCode ) {
1294 // Messages created in the content language will not have the /lang extension
1295 return $uckey;
1296 } else {
1297 return "$uckey/$langcode";
1298 }
1299 }
1300
1313 public function getMsgFromNamespace( $title, $code ) {
1314 // Load all MediaWiki page definitions into cache. Note that individual keys
1315 // already loaded into the cache during this request remain in the cache, which
1316 // includes the value of hook-defined messages.
1317 $this->load( $code );
1318
1319 $entry = $this->cache->getField( $code, $title );
1320
1321 if ( $entry !== null ) {
1322 // Message page exists as an override of a software messages
1323 if ( substr( $entry, 0, 1 ) === ' ' ) {
1324 // The message exists and is not '!TOO BIG' or '!ERROR'
1325 return (string)substr( $entry, 1 );
1326 } elseif ( $entry === '!NONEXISTENT' ) {
1327 // The text might be '-' or missing due to some data loss
1328 return false;
1329 }
1330 // Load the message page, utilizing the individual message cache.
1331 // If the page does not exist, there will be no hook handler fallbacks.
1332 $entry = $this->loadCachedMessagePageEntry(
1333 $title,
1334 $code,
1335 $this->cache->getField( $code, 'HASH' )
1336 );
1337 } else {
1338 // Message page either does not exist or does not override a software message
1339 if ( !$this->isMainCacheable( $title, $code ) ) {
1340 // Message page does not override any software-defined message. A custom
1341 // message might be defined to have content or settings specific to the wiki.
1342 // Load the message page, utilizing the individual message cache as needed.
1343 $entry = $this->loadCachedMessagePageEntry(
1344 $title,
1345 $code,
1346 $this->cache->getField( $code, 'HASH' )
1347 );
1348 }
1349 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1350 // Message does not have a MediaWiki page definition; try hook handlers
1351 $message = false;
1352 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
1353 $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1354 if ( $message !== false ) {
1355 $this->cache->setField( $code, $title, ' ' . $message );
1356 } else {
1357 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1358 }
1359
1360 return $message;
1361 }
1362 }
1363
1364 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1365 if ( $this->cacheVolatile[$code] ) {
1366 // Make sure that individual keys respect the WAN cache holdoff period too
1367 $this->logger->debug(
1368 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1369 [ 'titleKey' => $title, 'code' => $code ] );
1370 } else {
1371 $this->cache->setField( $code, $title, $entry );
1372 }
1373 // The message exists, so make sure a string is returned
1374 return (string)substr( $entry, 1 );
1375 }
1376
1377 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1378
1379 return false;
1380 }
1381
1388 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1389 $fname = __METHOD__;
1390 return $this->srvCache->getWithSetCallback(
1391 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1392 BagOStuff::TTL_HOUR,
1393 function () use ( $code, $dbKey, $hash, $fname ) {
1394 return $this->wanCache->getWithSetCallback(
1395 $this->bigMessageCacheKey( $hash, $dbKey ),
1396 self::WAN_TTL,
1397 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1398 // Try loading the message from the database
1399 $setOpts += Database::getCacheSetOptions(
1400 MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase()
1401 );
1402 // Use newKnownCurrent() to avoid querying revision/user tables
1403 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1404 // Injecting RevisionStore breaks installer since it
1405 // instantiates MessageCache before DB.
1406 $revision = MediaWikiServices::getInstance()
1407 ->getRevisionLookup()
1408 ->getKnownCurrentRevision( $title );
1409 if ( !$revision ) {
1410 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1411 // When overrides are created, self::replace() takes care of the cache.
1412 return '!NONEXISTENT';
1413 }
1414 $content = $revision->getContent( SlotRecord::MAIN );
1415 if ( $content ) {
1416 $message = $this->getMessageTextFromContent( $content );
1417 } else {
1418 $this->logger->warning(
1419 $fname . ': failed to load page text for \'{titleKey}\'',
1420 [ 'titleKey' => $dbKey, 'code' => $code ]
1421 );
1422 $message = null;
1423 }
1424
1425 if ( !is_string( $message ) ) {
1426 // Revision failed to load Content, or Content is incompatible with wikitext.
1427 // Possibly a temporary loading failure.
1428 $ttl = 5;
1429
1430 return '!NONEXISTENT';
1431 }
1432
1433 return ' ' . $message;
1434 }
1435 );
1436 }
1437 );
1438 }
1439
1447 public function transform( $message, $interface = false, $language = null, PageReference $page = null ) {
1448 // Avoid creating parser if nothing to transform
1449 if ( $this->inParser || !str_contains( $message, '{{' ) ) {
1450 return $message;
1451 }
1452
1453 $parser = $this->getParser();
1454 $popts = $this->getParserOptions();
1455 $popts->setInterfaceMessage( $interface );
1456 $popts->setTargetLanguage( $language );
1457
1458 $userlang = $popts->setUserLang( $language );
1459 $this->inParser = true;
1460 $message = $parser->transformMsg( $message, $popts, $page );
1461 $this->inParser = false;
1462 $popts->setUserLang( $userlang );
1463
1464 return $message;
1465 }
1466
1470 public function getParser() {
1471 if ( !$this->parser ) {
1472 $this->parser = $this->parserFactory->create();
1473 }
1474
1475 return $this->parser;
1476 }
1477
1486 public function parse( $text, PageReference $page = null, $linestart = true,
1487 $interface = false, $language = null
1488 ) {
1489 global $wgTitle;
1490
1491 if ( $this->inParser ) {
1492 return htmlspecialchars( $text );
1493 }
1494
1495 $parser = $this->getParser();
1496 $popts = $this->getParserOptions();
1497 $popts->setInterfaceMessage( $interface );
1498
1499 if ( is_string( $language ) ) {
1500 $language = $this->langFactory->getLanguage( $language );
1501 }
1502 $popts->setTargetLanguage( $language );
1503
1504 if ( !$page ) {
1505 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1506 $logger->info(
1507 __METHOD__ . ' called with no title set.',
1508 [ 'exception' => new RuntimeException ]
1509 );
1510 $page = $wgTitle;
1511 }
1512 // Sometimes $wgTitle isn't set either...
1513 if ( !$page ) {
1514 // It's not uncommon having a null $wgTitle in scripts. See r80898
1515 // Create a ghost title in such case
1516 $page = PageReferenceValue::localReference(
1517 NS_SPECIAL,
1518 'Badtitle/title not set in ' . __METHOD__
1519 );
1520 }
1521
1522 $this->inParser = true;
1523 $res = $parser->parse( $text, $page, $popts, $linestart );
1524 $this->inParser = false;
1525
1526 return $res;
1527 }
1528
1529 public function disable() {
1530 $this->disable = true;
1531 }
1532
1533 public function enable() {
1534 $this->disable = false;
1535 }
1536
1549 public function isDisabled() {
1550 return $this->disable;
1551 }
1552
1558 public function clear() {
1559 $langs = $this->languageNameUtils->getLanguageNames();
1560 foreach ( $langs as $code => $_ ) {
1561 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1562 }
1563 $this->cache->clear();
1564 }
1565
1570 public function figureMessage( $key ) {
1571 $pieces = explode( '/', $key );
1572 if ( count( $pieces ) < 2 ) {
1573 return [ $key, $this->contLangCode ];
1574 }
1575
1576 $lang = array_pop( $pieces );
1577 if ( !$this->languageNameUtils->getLanguageName(
1578 $lang,
1579 LanguageNameUtils::AUTONYMS,
1580 LanguageNameUtils::DEFINED
1581 ) ) {
1582 return [ $key, $this->contLangCode ];
1583 }
1584
1585 $message = implode( '/', $pieces );
1586
1587 return [ $message, $lang ];
1588 }
1589
1599 public function getAllMessageKeys( $code ) {
1600 $this->load( $code );
1601 if ( !$this->cache->has( $code ) ) {
1602 // Apparently load() failed
1603 return null;
1604 }
1605 // Remove administrative keys
1606 $cache = $this->cache->get( $code );
1607 unset( $cache['VERSION'] );
1608 unset( $cache['EXPIRY'] );
1609 unset( $cache['EXCESSIVE'] );
1610 // Remove any !NONEXISTENT keys
1611 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1612
1613 // Keys may appear with a capital first letter. lcfirst them.
1614 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1615 }
1616
1624 public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1625 // treat null as not existing
1626 $msgText = $this->getMessageTextFromContent( $content ) ?? false;
1627
1628 $this->replace( $linkTarget->getDBkey(), $msgText );
1629
1630 if ( $this->contLangConverter->hasVariants() ) {
1631 $this->contLangConverter->updateConversionTable( $linkTarget );
1632 }
1633 }
1634
1639 public function getCheckKey( $code ) {
1640 return $this->wanCache->makeKey( 'messages', $code );
1641 }
1642
1647 private function getMessageTextFromContent( Content $content = null ) {
1648 // @TODO: could skip pseudo-messages like js/css here, based on content model
1649 if ( $content ) {
1650 // Message page exists...
1651 // XXX: Is this the right way to turn a Content object into a message?
1652 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1653 // CssContent. MessageContent is *not* used for storing messages, it's
1654 // only used for wrapping them when needed.
1655 $msgText = $content->getWikitextForTransclusion();
1656 if ( $msgText === false || $msgText === null ) {
1657 // This might be due to some kind of misconfiguration...
1658 $msgText = null;
1659 $this->logger->warning(
1660 __METHOD__ . ": message content doesn't provide wikitext "
1661 . "(content model: " . $content->getModel() . ")" );
1662 }
1663 } else {
1664 // Message page does not exist...
1665 $msgText = false;
1666 }
1667
1668 return $msgText;
1669 }
1670
1676 private function bigMessageCacheKey( $hash, $title ) {
1677 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1678 }
1679}
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:536
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli') $wgTitle
Definition Setup.php:536
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.
Rendered output of a wiki page, as parsed from wikitext.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:155
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:659
transformMsg( $text, ParserOptions $options, ?PageReference $page=null)
Wrapper for preprocess()
Definition Parser.php:4891
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.