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
1054 public function get( $key, $useDB = true, $language = null, &$usedKey = '' ) {
1055 if ( is_int( $key ) ) {
1056 // Fix numerical strings that somehow become ints on their way here
1057 $key = (string)$key;
1058 } elseif ( !is_string( $key ) ) {
1059 throw new TypeError( 'Message key must be a string' );
1060 } elseif ( $key === '' ) {
1061 // Shortcut: the empty key is always missing
1062 return false;
1063 }
1064
1065 $language ??= $this->contLang;
1066 $language = $this->getLanguageObject( $language );
1067
1068 // Normalise title-case input (with some inlining)
1069 $lckey = self::normalizeKey( $key );
1070
1071 // Initialize the overrides here to prevent calling the hook too early.
1072 if ( $this->messageKeyOverrides === null ) {
1073 $this->messageKeyOverrides = [];
1074 $this->hookRunner->onMessageCacheFetchOverrides( $this->messageKeyOverrides );
1075 }
1076
1077 if ( isset( $this->messageKeyOverrides[$lckey] ) ) {
1078 $override = $this->messageKeyOverrides[$lckey];
1079
1080 // Strings are deliberately interpreted as message keys,
1081 // to prevent ambiguity between message keys and functions.
1082 if ( is_string( $override ) ) {
1083 $lckey = $override;
1084 } else {
1085 $lckey = $override( $lckey, $this, $language, $useDB );
1086 }
1087 }
1088
1089 $this->hookRunner->onMessageCache__get( $lckey );
1090
1091 $usedKey = $lckey;
1092
1093 // Loop through each language in the fallback list until we find something useful
1094 $message = $this->getMessageFromFallbackChain(
1095 $language,
1096 $lckey,
1097 !$this->disable && $useDB
1098 );
1099
1100 // If we still have no message, maybe the key was in fact a full key so try that
1101 if ( $message === false ) {
1102 $parts = explode( '/', $lckey );
1103 // We may get calls for things that are http-urls from sidebar
1104 // Let's not load nonexistent languages for those
1105 // They usually have more than one slash.
1106 if ( count( $parts ) === 2 && $parts[1] !== '' ) {
1107 $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] ) ?? false;
1108 }
1109 }
1110
1111 // Post-processing if the message exists
1112 if ( $message !== false ) {
1113 // Fix whitespace
1114 $message = str_replace(
1115 [
1116 // Fix for trailing whitespace, removed by textarea
1117 '&#32;',
1118 // Fix for NBSP, converted to space by firefox
1119 '&nbsp;',
1120 '&#160;',
1121 '&shy;'
1122 ],
1123 [
1124 ' ',
1125 "\u{00A0}",
1126 "\u{00A0}",
1127 "\u{00AD}"
1128 ],
1129 $message
1130 );
1131 }
1132
1133 return $message;
1134 }
1135
1151 private function getLanguageObject( $langcode ) {
1152 # Identify which language to get or create a language object for.
1153 # Using is_object here due to Stub objects.
1154 if ( is_object( $langcode ) ) {
1155 # Great, we already have the object (hopefully)!
1156 return $langcode;
1157 }
1158
1159 wfDeprecated( __METHOD__ . ' with not a Language object in $langcode', '1.43' );
1160 if ( $langcode === true || $langcode === $this->contLangCode ) {
1161 # $langcode is the language code of the wikis content language object.
1162 # or it is a boolean and value is true
1163 return $this->contLang;
1164 }
1165
1166 global $wgLang;
1167 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1168 # $langcode is the language code of user language object.
1169 # or it was a boolean and value is false
1170 return $wgLang;
1171 }
1172
1173 $validCodes = array_keys( $this->languageNameUtils->getLanguageNames() );
1174 if ( in_array( $langcode, $validCodes ) ) {
1175 # $langcode corresponds to a valid language.
1176 return $this->langFactory->getLanguage( $langcode );
1177 }
1178
1179 # $langcode is a string, but not a valid language code; use content language.
1180 $this->logger->debug( 'Invalid language code passed to' . __METHOD__ . ', falling back to content language.' );
1181 return $this->contLang;
1182 }
1183
1196 private function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1197 $alreadyTried = [];
1198
1199 // First try the requested language.
1200 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1201 if ( $message !== false ) {
1202 return $message;
1203 }
1204
1205 // Now try checking the site language.
1206 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1207 return $message;
1208 }
1209
1220 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1221 $langcode = $lang->getCode();
1222
1223 // Try checking the database for the requested language
1224 if ( $useDB ) {
1225 $uckey = $this->contLang->ucfirst( $lckey );
1226
1227 if ( !isset( $alreadyTried[$langcode] ) ) {
1228 $message = $this->getMsgFromNamespace(
1229 $this->getMessagePageName( $langcode, $uckey ),
1230 $langcode
1231 );
1232 if ( $message !== false ) {
1233 return $message;
1234 }
1235 $alreadyTried[$langcode] = true;
1236 }
1237 } else {
1238 $uckey = null;
1239 }
1240
1241 // Return a special value handled in Message::format() to display the message key
1242 // (and fallback keys) and the parameters passed to the message.
1243 // TODO: Move to a better place.
1244 if ( $langcode === 'qqx' ) {
1245 return '($*)';
1246 } elseif (
1247 $langcode === 'x-xss' &&
1248 $this->useXssLanguage &&
1249 !in_array( $lckey, $this->rawHtmlMessages, true )
1250 ) {
1251 $xssViaInnerHtml = "<script>alert('$lckey')</script>";
1252 $xssViaAttribute = '">' . $xssViaInnerHtml . '<x y="';
1253 return $xssViaInnerHtml . $xssViaAttribute . '($*)';
1254 }
1255
1256 // Check the localisation cache
1257 [ $defaultMessage, $messageSource ] =
1258 $this->localisationCache->getSubitemWithSource( $langcode, 'messages', $lckey );
1259 if ( $messageSource === $langcode ) {
1260 return $defaultMessage;
1261 }
1262
1263 // Try checking the database for all of the fallback languages
1264 if ( $useDB ) {
1265 $fallbackChain = $this->languageFallback->getAll( $langcode );
1266
1267 foreach ( $fallbackChain as $code ) {
1268 if ( isset( $alreadyTried[$code] ) ) {
1269 continue;
1270 }
1271
1272 $message = $this->getMsgFromNamespace(
1273 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable uckey is set when used
1274 $this->getMessagePageName( $code, $uckey ), $code );
1275
1276 if ( $message !== false ) {
1277 return $message;
1278 }
1279 $alreadyTried[$code] = true;
1280
1281 // Reached the source language of the default message. Don't look for DB overrides
1282 // further back in the fallback chain. (T229992)
1283 if ( $code === $messageSource ) {
1284 return $defaultMessage;
1285 }
1286 }
1287 }
1288
1289 return $defaultMessage ?? false;
1290 }
1291
1299 private function getMessagePageName( $langcode, $uckey ) {
1300 if ( $langcode === $this->contLangCode ) {
1301 // Messages created in the content language will not have the /lang extension
1302 return $uckey;
1303 } else {
1304 return "$uckey/$langcode";
1305 }
1306 }
1307
1320 public function getMsgFromNamespace( $title, $code ) {
1321 // Load all MediaWiki page definitions into cache. Note that individual keys
1322 // already loaded into the cache during this request remain in the cache, which
1323 // includes the value of hook-defined messages.
1324 $this->load( $code );
1325
1326 $entry = $this->cache->getField( $code, $title );
1327
1328 if ( $entry !== null ) {
1329 // Message page exists as an override of a software messages
1330 if ( substr( $entry, 0, 1 ) === ' ' ) {
1331 // The message exists and is not '!TOO BIG' or '!ERROR'
1332 return (string)substr( $entry, 1 );
1333 } elseif ( $entry === '!NONEXISTENT' ) {
1334 // The text might be '-' or missing due to some data loss
1335 return false;
1336 }
1337 // Load the message page, utilizing the individual message cache.
1338 // If the page does not exist, there will be no hook handler fallbacks.
1339 $entry = $this->loadCachedMessagePageEntry(
1340 $title,
1341 $code,
1342 $this->cache->getField( $code, 'HASH' )
1343 );
1344 } else {
1345 // Message page either does not exist or does not override a software message
1346 if ( !$this->isMainCacheable( $title, $code ) ) {
1347 // Message page does not override any software-defined message. A custom
1348 // message might be defined to have content or settings specific to the wiki.
1349 // Load the message page, utilizing the individual message cache as needed.
1350 $entry = $this->loadCachedMessagePageEntry(
1351 $title,
1352 $code,
1353 $this->cache->getField( $code, 'HASH' )
1354 );
1355 }
1356 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1357 // Message does not have a MediaWiki page definition; try hook handlers
1358 $message = false;
1359 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
1360 $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1361 if ( $message !== false ) {
1362 $this->cache->setField( $code, $title, ' ' . $message );
1363 } else {
1364 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1365 }
1366
1367 return $message;
1368 }
1369 }
1370
1371 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1372 if ( $this->cacheVolatile[$code] ) {
1373 // Make sure that individual keys respect the WAN cache holdoff period too
1374 $this->logger->debug(
1375 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1376 [ 'titleKey' => $title, 'code' => $code ] );
1377 } else {
1378 $this->cache->setField( $code, $title, $entry );
1379 }
1380 // The message exists, so make sure a string is returned
1381 return (string)substr( $entry, 1 );
1382 }
1383
1384 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1385
1386 return false;
1387 }
1388
1395 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1396 $fname = __METHOD__;
1397 return $this->srvCache->getWithSetCallback(
1398 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1399 BagOStuff::TTL_HOUR,
1400 function () use ( $code, $dbKey, $hash, $fname ) {
1401 return $this->wanCache->getWithSetCallback(
1402 $this->bigMessageCacheKey( $hash, $dbKey ),
1403 self::WAN_TTL,
1404 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1405 // Try loading the message from the database
1406 $setOpts += Database::getCacheSetOptions(
1407 MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase()
1408 );
1409 // Use newKnownCurrent() to avoid querying revision/user tables
1410 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1411 // Injecting RevisionStore breaks installer since it
1412 // instantiates MessageCache before DB.
1413 $revision = MediaWikiServices::getInstance()
1414 ->getRevisionLookup()
1415 ->getKnownCurrentRevision( $title );
1416 if ( !$revision ) {
1417 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1418 // When overrides are created, self::replace() takes care of the cache.
1419 return '!NONEXISTENT';
1420 }
1421 $content = $revision->getContent( SlotRecord::MAIN );
1422 if ( $content ) {
1423 $message = $this->getMessageTextFromContent( $content );
1424 } else {
1425 $this->logger->warning(
1426 $fname . ': failed to load page text for \'{titleKey}\'',
1427 [ 'titleKey' => $dbKey, 'code' => $code ]
1428 );
1429 $message = null;
1430 }
1431
1432 if ( !is_string( $message ) ) {
1433 // Revision failed to load Content, or Content is incompatible with wikitext.
1434 // Possibly a temporary loading failure.
1435 $ttl = 5;
1436
1437 return '!NONEXISTENT';
1438 }
1439
1440 return ' ' . $message;
1441 }
1442 );
1443 }
1444 );
1445 }
1446
1454 public function transform( $message, $interface = false, $language = null, PageReference $page = null ) {
1455 // Avoid creating parser if nothing to transform
1456 if ( $this->inParser || !str_contains( $message, '{{' ) ) {
1457 return $message;
1458 }
1459
1460 $parser = $this->getParser();
1461 $popts = $this->getParserOptions();
1462 $popts->setInterfaceMessage( $interface );
1463 $popts->setTargetLanguage( $language );
1464
1465 $userlang = $popts->setUserLang( $language );
1466 $this->inParser = true;
1467 $message = $parser->transformMsg( $message, $popts, $page );
1468 $this->inParser = false;
1469 $popts->setUserLang( $userlang );
1470
1471 return $message;
1472 }
1473
1477 public function getParser() {
1478 if ( !$this->parser ) {
1479 $this->parser = $this->parserFactory->create();
1480 }
1481
1482 return $this->parser;
1483 }
1484
1493 public function parse( $text, PageReference $page = null, $linestart = true,
1494 $interface = false, $language = null
1495 ) {
1496 global $wgTitle;
1497
1498 if ( $this->inParser ) {
1499 return htmlspecialchars( $text );
1500 }
1501
1502 $parser = $this->getParser();
1503 $popts = $this->getParserOptions();
1504 $popts->setInterfaceMessage( $interface );
1505
1506 if ( is_string( $language ) ) {
1507 $language = $this->langFactory->getLanguage( $language );
1508 }
1509 $popts->setTargetLanguage( $language );
1510
1511 if ( !$page ) {
1512 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1513 $logger->info(
1514 __METHOD__ . ' called with no title set.',
1515 [ 'exception' => new RuntimeException ]
1516 );
1517 $page = $wgTitle;
1518 }
1519 // Sometimes $wgTitle isn't set either...
1520 if ( !$page ) {
1521 // It's not uncommon having a null $wgTitle in scripts. See r80898
1522 // Create a ghost title in such case
1523 $page = PageReferenceValue::localReference(
1524 NS_SPECIAL,
1525 'Badtitle/title not set in ' . __METHOD__
1526 );
1527 }
1528
1529 $this->inParser = true;
1530 $res = $parser->parse( $text, $page, $popts, $linestart );
1531 $this->inParser = false;
1532
1533 return $res;
1534 }
1535
1536 public function disable() {
1537 $this->disable = true;
1538 }
1539
1540 public function enable() {
1541 $this->disable = false;
1542 }
1543
1556 public function isDisabled() {
1557 return $this->disable;
1558 }
1559
1565 public function clear() {
1566 $langs = $this->languageNameUtils->getLanguageNames();
1567 foreach ( $langs as $code => $_ ) {
1568 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1569 }
1570 $this->cache->clear();
1571 }
1572
1577 public function figureMessage( $key ) {
1578 $pieces = explode( '/', $key );
1579 if ( count( $pieces ) < 2 ) {
1580 return [ $key, $this->contLangCode ];
1581 }
1582
1583 $lang = array_pop( $pieces );
1584 if ( !$this->languageNameUtils->getLanguageName(
1585 $lang,
1586 LanguageNameUtils::AUTONYMS,
1587 LanguageNameUtils::DEFINED
1588 ) ) {
1589 return [ $key, $this->contLangCode ];
1590 }
1591
1592 $message = implode( '/', $pieces );
1593
1594 return [ $message, $lang ];
1595 }
1596
1606 public function getAllMessageKeys( $code ) {
1607 $this->load( $code );
1608 if ( !$this->cache->has( $code ) ) {
1609 // Apparently load() failed
1610 return null;
1611 }
1612 // Remove administrative keys
1613 $cache = $this->cache->get( $code );
1614 unset( $cache['VERSION'] );
1615 unset( $cache['EXPIRY'] );
1616 unset( $cache['EXCESSIVE'] );
1617 // Remove any !NONEXISTENT keys
1618 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1619
1620 // Keys may appear with a capital first letter. lcfirst them.
1621 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1622 }
1623
1631 public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1632 // treat null as not existing
1633 $msgText = $this->getMessageTextFromContent( $content ) ?? false;
1634
1635 $this->replace( $linkTarget->getDBkey(), $msgText );
1636
1637 if ( $this->contLangConverter->hasVariants() ) {
1638 $this->contLangConverter->updateConversionTable( $linkTarget );
1639 }
1640 }
1641
1646 public function getCheckKey( $code ) {
1647 return $this->wanCache->makeKey( 'messages', $code );
1648 }
1649
1654 private function getMessageTextFromContent( Content $content = null ) {
1655 // @TODO: could skip pseudo-messages like js/css here, based on content model
1656 if ( $content ) {
1657 // Message page exists...
1658 // XXX: Is this the right way to turn a Content object into a message?
1659 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1660 // CssContent. MessageContent is *not* used for storing messages, it's
1661 // only used for wrapping them when needed.
1662 $msgText = $content->getWikitextForTransclusion();
1663 if ( $msgText === false || $msgText === null ) {
1664 // This might be due to some kind of misconfiguration...
1665 $msgText = null;
1666 $this->logger->warning(
1667 __METHOD__ . ": message content doesn't provide wikitext "
1668 . "(content model: " . $content->getModel() . ")" );
1669 }
1670 } else {
1671 // Message page does not exist...
1672 $msgText = false;
1673 }
1674
1675 return $msgText;
1676 }
1677
1683 private function bigMessageCacheKey( $hash, $title ) {
1684 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1685 }
1686}
const NS_MEDIAWIKI
Definition Defines.php:73
const NS_SPECIAL
Definition Defines.php:54
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.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgLang
Definition Setup.php:538
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgTitle
Definition Setup.php:538
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:66
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: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:696
transformMsg( $text, ParserOptions $options, ?PageReference $page=null)
Wrapper for preprocess()
Definition Parser.php:4955
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:79
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.