MediaWiki master
MessageCache.php
Go to the documentation of this file.
1<?php
48use Psr\Log\LoggerAwareInterface;
49use Psr\Log\LoggerInterface;
59use Wikimedia\RequestTimeout\TimeoutException;
60use Wikimedia\ScopedCallback;
61
66define( 'MSG_CACHE_VERSION', 2 );
67
73class MessageCache implements LoggerAwareInterface {
77 public const CONSTRUCTOR_OPTIONS = [
78 MainConfigNames::UseDatabaseMessages,
79 MainConfigNames::MaxMsgCacheEntrySize,
80 MainConfigNames::AdaptiveMessageCache,
81 MainConfigNames::UseXssLanguage,
82 MainConfigNames::RawHtmlMessages,
83 ];
84
89 public const MAX_REQUEST_LANGUAGES = 10;
90
91 private const FOR_UPDATE = 1; // force message reload
92
94 private const WAIT_SEC = 15;
96 private const LOCK_TTL = 30;
97
101 private const WAN_TTL = ExpirationAwareness::TTL_DAY;
102
104 private $logger;
105
111 private $cache;
112
118 private $systemMessageNames;
119
123 private $cacheVolatile = [];
124
129 private $disable;
130
132 private $maxEntrySize;
133
135 private $adaptive;
136
138 private $useXssLanguage;
139
141 private $rawHtmlMessages;
142
147 private $parserOptions;
148
150 private $parser = null;
151
155 private $inParser = false;
156
158 private $wanCache;
160 private $clusterCache;
162 private $srvCache;
164 private $contLang;
166 private $contLangCode;
168 private $contLangConverter;
170 private $langFactory;
172 private $localisationCache;
174 private $languageNameUtils;
176 private $languageFallback;
178 private $hookRunner;
180 private $parserFactory;
181
183 private $messageKeyOverrides;
184
191 public static function normalizeKey( $key ) {
192 $lckey = strtr( $key, ' ', '_' );
193 if ( $lckey === '' ) {
194 // T300792
195 return $lckey;
196 }
197
198 if ( ord( $lckey ) < 128 ) {
199 $lckey[0] = strtolower( $lckey[0] );
200 } else {
201 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
202 }
203
204 return $lckey;
205 }
206
223 public function __construct(
224 WANObjectCache $wanCache,
225 BagOStuff $clusterCache,
226 BagOStuff $serverCache,
227 Language $contLang,
228 LanguageConverterFactory $langConverterFactory,
229 LoggerInterface $logger,
230 ServiceOptions $options,
231 LanguageFactory $langFactory,
232 LocalisationCache $localisationCache,
233 LanguageNameUtils $languageNameUtils,
234 LanguageFallback $languageFallback,
235 HookContainer $hookContainer,
236 ParserFactory $parserFactory
237 ) {
238 $this->wanCache = $wanCache;
239 $this->clusterCache = $clusterCache;
240 $this->srvCache = $serverCache;
241 $this->contLang = $contLang;
242 $this->contLangConverter = $langConverterFactory->getLanguageConverter( $contLang );
243 $this->contLangCode = $contLang->getCode();
244 $this->logger = $logger;
245 $this->langFactory = $langFactory;
246 $this->localisationCache = $localisationCache;
247 $this->languageNameUtils = $languageNameUtils;
248 $this->languageFallback = $languageFallback;
249 $this->hookRunner = new HookRunner( $hookContainer );
250 $this->parserFactory = $parserFactory;
251
252 // limit size
253 $this->cache = new MapCacheLRU( self::MAX_REQUEST_LANGUAGES );
254
255 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
256 $this->disable = !$options->get( MainConfigNames::UseDatabaseMessages );
257 $this->maxEntrySize = $options->get( MainConfigNames::MaxMsgCacheEntrySize );
258 $this->adaptive = $options->get( MainConfigNames::AdaptiveMessageCache );
259 $this->useXssLanguage = $options->get( MainConfigNames::UseXssLanguage );
260 $this->rawHtmlMessages = $options->get( MainConfigNames::RawHtmlMessages );
261 }
262
263 public function setLogger( LoggerInterface $logger ) {
264 $this->logger = $logger;
265 }
266
272 private function getParserOptions() {
273 if ( !$this->parserOptions ) {
274 $context = RequestContext::getMain();
275 $user = $context->getUser();
276 if ( !$user->isSafeToLoad() ) {
277 // It isn't safe to use the context user yet, so don't try to get a
278 // ParserOptions for it. And don't cache this ParserOptions
279 // either.
280 $po = ParserOptions::newFromAnon();
281 $po->setAllowUnsafeRawHtml( false );
282 return $po;
283 }
284
285 $this->parserOptions = ParserOptions::newFromContext( $context );
286 // Messages may take parameters that could come
287 // from malicious sources. As a precaution, disable
288 // the <html> parser tag when parsing messages.
289 $this->parserOptions->setAllowUnsafeRawHtml( false );
290 }
291
292 return $this->parserOptions;
293 }
294
301 private function getLocalCache( $code ) {
302 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
303
304 return $this->srvCache->get( $cacheKey );
305 }
306
313 private function saveToLocalCache( $code, $cache ) {
314 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
315 $this->srvCache->set( $cacheKey, $cache );
316 }
317
338 private function load( string $code, $mode = null ) {
339 // Don't do double loading...
340 if ( $this->isLanguageLoaded( $code ) && $mode !== self::FOR_UPDATE ) {
341 return true;
342 }
343
344 // Show a log message (once) if loading is disabled
345 if ( $this->disable ) {
346 static $shownDisabled = false;
347 if ( !$shownDisabled ) {
348 $this->logger->debug( __METHOD__ . ': disabled' );
349 $shownDisabled = true;
350 }
351
352 return true;
353 }
354
355 try {
356 return $this->loadUnguarded( $code, $mode );
357 } catch ( Throwable $e ) {
358 // Don't try to load again during the exception handler
359 $this->disable = true;
360 throw $e;
361 }
362 }
363
371 private function loadUnguarded( $code, $mode ) {
372 $success = false; // Keep track of success
373 $staleCache = false; // a cache array with expired data, or false if none has been loaded
374 $where = []; // Debug info, delayed to avoid spamming debug log too much
375
376 // A hash of the expected content is stored in a WAN cache key, providing a way
377 // to invalid the local cache on every server whenever a message page changes.
378 [ $hash, $hashVolatile ] = $this->getValidationHash( $code );
379 $this->cacheVolatile[$code] = $hashVolatile;
380 $volatilityOnlyStaleness = false;
381
382 // Try the local cache and check against the cluster hash key...
383 $cache = $this->getLocalCache( $code );
384 if ( !$cache ) {
385 $where[] = 'local cache is empty';
386 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
387 $where[] = 'local cache has the wrong hash';
388 $staleCache = $cache;
389 } elseif ( $this->isCacheExpired( $cache ) ) {
390 $where[] = 'local cache is expired';
391 $staleCache = $cache;
392 } elseif ( $hashVolatile ) {
393 // Some recent message page changes might not show due to DB lag
394 $where[] = 'local cache validation key is expired/volatile';
395 $staleCache = $cache;
396 $volatilityOnlyStaleness = true;
397 } else {
398 $where[] = 'got from local cache';
399 $this->cache->set( $code, $cache );
400 $success = true;
401 }
402
403 if ( !$success ) {
404 // Try the cluster cache, using a lock for regeneration...
405 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
406 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
407 if ( $volatilityOnlyStaleness && $staleCache ) {
408 // While the cluster cache *might* be more up-to-date, we do not want
409 // the I/O strain of every application server fetching the key here during
410 // the volatility period. Either this thread wins the lock and regenerates
411 // the cache or the stale local cache value gets reused.
412 $where[] = 'global cache is presumed expired';
413 } else {
414 $cache = $this->clusterCache->get( $cacheKey );
415 if ( !$cache ) {
416 $where[] = 'global cache is empty';
417 } elseif ( $this->isCacheExpired( $cache ) ) {
418 $where[] = 'global cache is expired';
419 $staleCache = $cache;
420 } elseif ( $hashVolatile ) {
421 // Some recent message page changes might not show due to DB lag
422 $where[] = 'global cache is expired/volatile';
423 $staleCache = $cache;
424 } else {
425 $where[] = 'got from global cache';
426 $this->cache->set( $code, $cache );
427 $this->saveToCaches( $cache, 'local-only', $code );
428 $success = true;
429 break;
430 }
431 }
432
433 // We need to call loadFromDB(). Limit the concurrency to one thread.
434 // This prevents the site from going down when the cache expires.
435 // Note that the DB slam protection lock here is non-blocking.
436 $loadStatus = $this->loadFromDBWithMainLock( $code, $where, $mode );
437 if ( $loadStatus === true ) {
438 $success = true;
439 break;
440 } elseif ( $staleCache ) {
441 // Use the stale cache while some other thread constructs the new one
442 $where[] = 'using stale cache';
443 $this->cache->set( $code, $staleCache );
444 $success = true;
445 break;
446 } elseif ( $failedAttempts > 0 ) {
447 $where[] = 'failed to find cache after waiting';
448 // Already blocked once, so avoid another lock/unlock cycle.
449 // This case will typically be hit if memcached is down, or if
450 // loadFromDB() takes longer than LOCK_WAIT.
451 break;
452 } elseif ( $loadStatus === 'cantacquire' ) {
453 // Wait for the other thread to finish, then retry. Normally,
454 // the memcached get() will then yield the other thread's result.
455 $where[] = 'waiting for other thread to complete';
456 [ , $ioError ] = $this->getReentrantScopedLock( $code );
457 if ( $ioError ) {
458 $where[] = 'failed waiting';
459 // Call loadFromDB() with concurrency limited to one thread per server.
460 // It should be rare for all servers to lack even a stale local cache.
461 $success = $this->loadFromDBWithLocalLock( $code, $where, $mode );
462 break;
463 }
464 } else {
465 // Disable cache; $loadStatus is 'disabled'
466 break;
467 }
468 }
469 }
470
471 if ( !$success ) {
472 $where[] = 'loading FAILED - cache is disabled';
473 $this->disable = true;
474 $this->cache->set( $code, [] );
475 $this->logger->error( __METHOD__ . ": Failed to load $code" );
476 // This used to throw an exception, but that led to nasty side effects like
477 // the whole wiki being instantly down if the memcached server died
478 }
479
480 if ( !$this->isLanguageLoaded( $code ) ) {
481 throw new LogicException( "Process cache for '$code' should be set by now." );
482 }
483
484 $info = implode( ', ', $where );
485 $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
486
487 return $success;
488 }
489
496 private function loadFromDBWithMainLock( $code, array &$where, $mode = null ) {
497 // If cache updates on all levels fail, give up on message overrides.
498 // This is to avoid easy site outages; see $saveSuccess comments below.
499 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
500 $status = $this->clusterCache->get( $statusKey );
501 if ( $status === 'error' ) {
502 $where[] = "could not load; method is still globally disabled";
503 return 'disabled';
504 }
505
506 // Now let's regenerate
507 $where[] = 'loading from DB';
508
509 // Lock the cache to prevent conflicting writes.
510 // This lock is non-blocking so stale cache can quickly be used.
511 // Note that load() will call a blocking getReentrantScopedLock()
512 // after this if it really needs to wait for any current thread.
513 [ $scopedLock ] = $this->getReentrantScopedLock( $code, 0 );
514 if ( !$scopedLock ) {
515 $where[] = 'could not acquire main lock';
516 return 'cantacquire';
517 }
518
519 $cache = $this->loadFromDB( $code, $mode );
520 $this->cache->set( $code, $cache );
521 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
522
523 if ( !$saveSuccess ) {
537 if ( $this->srvCache instanceof EmptyBagOStuff ) {
538 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
539 $where[] = 'could not save cache, disabled globally for 5 minutes';
540 } else {
541 $where[] = "could not save global cache";
542 }
543 }
544
545 return true;
546 }
547
554 private function loadFromDBWithLocalLock( $code, array &$where, $mode = null ) {
555 $success = false;
556 $where[] = 'loading from DB using local lock';
557
558 $scopedLock = $this->srvCache->getScopedLock(
559 $this->srvCache->makeKey( 'messages', $code ),
560 self::WAIT_SEC,
561 self::LOCK_TTL,
562 __METHOD__
563 );
564 if ( $scopedLock ) {
565 $cache = $this->loadFromDB( $code, $mode );
566 $this->cache->set( $code, $cache );
567 $this->saveToCaches( $cache, 'local-only', $code );
568 $success = true;
569 }
570
571 return $success;
572 }
573
583 private function loadFromDB( $code, $mode = null ) {
584 $icp = MediaWikiServices::getInstance()->getConnectionProvider();
585
586 $dbr = ( $mode === self::FOR_UPDATE ) ? $icp->getPrimaryDatabase() : $icp->getReplicaDatabase();
587
588 $cache = [];
589
590 $mostused = []; // list of "<cased message key>/<code>"
591 if ( $this->adaptive && $code !== $this->contLangCode ) {
592 if ( !$this->cache->has( $this->contLangCode ) ) {
593 $this->load( $this->contLangCode );
594 }
595 $mostused = array_keys( $this->cache->get( $this->contLangCode ) );
596 foreach ( $mostused as $key => $value ) {
597 $mostused[$key] = "$value/$code";
598 }
599 }
600
601 // Common conditions
602 $conds = [
603 // Treat redirects as not existing (T376398)
604 'page_is_redirect' => 0,
605 'page_namespace' => NS_MEDIAWIKI,
606 ];
607 if ( count( $mostused ) ) {
608 $conds['page_title'] = $mostused;
609 } elseif ( $code !== $this->contLangCode ) {
610 $conds[] = $dbr->expr(
611 'page_title',
612 IExpression::LIKE,
613 new LikeValue( $dbr->anyString(), '/', $code )
614 );
615 } else {
616 // Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
617 // other than language code.
618 $conds[] = $dbr->expr(
619 'page_title',
620 IExpression::NOT_LIKE,
621 new LikeValue( $dbr->anyString(), '/', $dbr->anyString() )
622 );
623 }
624
625 // Set the stubs for oversized software-defined messages in the main cache map
626 $res = $dbr->newSelectQueryBuilder()
627 ->select( [ 'page_title', 'page_latest' ] )
628 ->from( 'page' )
629 ->where( $conds )
630 ->andWhere( $dbr->expr( 'page_len', '>', intval( $this->maxEntrySize ) ) )
631 ->caller( __METHOD__ . "($code)-big" )->fetchResultSet();
632 foreach ( $res as $row ) {
633 // Include entries/stubs for all keys in $mostused in adaptive mode
634 if ( $this->adaptive || $this->isMainCacheable( $row->page_title ) ) {
635 $cache[$row->page_title] = '!TOO BIG';
636 }
637 // At least include revision ID so page changes are reflected in the hash
638 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
639 }
640
641 // RevisionStore cannot be injected as it would break the installer since
642 // it instantiates MessageCache before the DB.
643 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
644 // Set the text for small software-defined messages in the main cache map
645 $revQuery = $revisionStore->getQueryInfo( [ 'page' ] );
646
647 // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
648 // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
649 // query (and also reorder it ourselves because as generated by RevisionStore it'll have
650 // `revision` first rather than `page`).
651 $revQuery['joins']['revision'] = $revQuery['joins']['page'];
652 unset( $revQuery['joins']['page'] );
653 // It isn't actually necessary to reorder $revQuery['tables'] as Database does the right thing
654 // when join conditions are given for all joins, but Gergő is wary of relying on that so pull
655 // `page` to the start.
656 $revQuery['tables'] = array_merge(
657 [ 'page' ],
658 array_diff( $revQuery['tables'], [ 'page' ] )
659 );
660
661 $res = $dbr->newSelectQueryBuilder()
662 ->queryInfo( $revQuery )
663 ->where( $conds )
664 ->andWhere( [
665 $dbr->expr( 'page_len', '<=', intval( $this->maxEntrySize ) ),
666 'page_latest = rev_id' // get the latest revision only
667 ] )
668 ->caller( __METHOD__ . "($code)-small" )
669 ->straightJoinOption()
670 ->fetchResultSet();
671
672 // Don't load content from uncacheable rows (T313004)
673 [ $cacheableRows, $uncacheableRows ] = $this->separateCacheableRows( $res );
674 $result = $revisionStore->newRevisionsFromBatch( $cacheableRows, [
675 'slots' => [ SlotRecord::MAIN ],
676 'content' => true
677 ] );
678 $revisions = $result->isOK() ? $result->getValue() : [];
679
680 foreach ( $cacheableRows as $row ) {
681 try {
682 $rev = $revisions[$row->rev_id] ?? null;
683 $content = $rev ? $rev->getContent( SlotRecord::MAIN ) : null;
684 $text = $this->getMessageTextFromContent( $content );
685 } catch ( TimeoutException $e ) {
686 throw $e;
687 } catch ( Exception $ex ) {
688 $text = false;
689 }
690
691 if ( !is_string( $text ) ) {
692 $entry = '!ERROR';
693 $this->logger->error(
694 __METHOD__
695 . ": failed to load message page text for {$row->page_title} ($code)"
696 );
697 } else {
698 $entry = ' ' . $text;
699 }
700 $cache[$row->page_title] = $entry;
701 }
702
703 foreach ( $uncacheableRows as $row ) {
704 // T193271: The cache object gets too big and slow to generate.
705 // At least include revision ID, so that page changes are reflected in the hash.
706 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
707 }
708
709 $cache['VERSION'] = MSG_CACHE_VERSION;
710 ksort( $cache );
711
712 // Hash for validating local cache (APC). No need to take into account
713 // messages larger than $wgMaxMsgCacheEntrySize, since those are only
714 // stored and fetched from memcache.
715 $cache['HASH'] = md5( serialize( $cache ) );
716 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
717 unset( $cache['EXCESSIVE'] ); // only needed for hash
718
719 return $cache;
720 }
721
728 private function isLanguageLoaded( $lang ) {
729 // It is important that this only returns true if the cache was fully
730 // populated by load(), so that callers can assume all cache keys exist.
731 // It is possible for $this->cache to be only partially populated through
732 // methods like MessageCache::replace(), which must not make this method
733 // return true (T208897). And this method must cease to return true
734 // if the language was evicted by MapCacheLRU (T230690).
735 return $this->cache->hasField( $lang, 'VERSION' );
736 }
737
749 private function isMainCacheable( $name, $code = null ) {
750 // Convert the first letter to lowercase, and strip /code suffix
751 $name = $this->contLang->lcfirst( $name );
752 // Include common conversion table pages. This also avoids problems with
753 // Installer::parse() bailing out due to disallowed DB queries (T207979).
754 if ( strpos( $name, 'conversiontable/' ) === 0 ) {
755 return true;
756 }
757 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
758
759 if ( $code === null ) {
760 // Bulk load
761 if ( $this->systemMessageNames === null ) {
762 $this->systemMessageNames = array_fill_keys(
763 $this->localisationCache->getSubitemList( $this->contLangCode, 'messages' ),
764 true );
765 }
766 return isset( $this->systemMessageNames[$msg] );
767 } else {
768 // Use individual subitem
769 return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
770 }
771 }
772
780 private function separateCacheableRows( $res ) {
781 if ( $this->adaptive ) {
782 // Include entries/stubs for all keys in $mostused in adaptive mode
783 return [ $res, [] ];
784 }
785 $cacheableRows = [];
786 $uncacheableRows = [];
787 foreach ( $res as $row ) {
788 if ( $this->isMainCacheable( $row->page_title ) ) {
789 $cacheableRows[] = $row;
790 } else {
791 $uncacheableRows[] = $row;
792 }
793 }
794 return [ $cacheableRows, $uncacheableRows ];
795 }
796
803 public function replace( $title, $text ) {
804 if ( $this->disable ) {
805 return;
806 }
807
808 [ $msg, $code ] = $this->figureMessage( $title );
809 if ( strpos( $title, '/' ) !== false && $code === $this->contLangCode ) {
810 // Content language overrides do not use the /<code> suffix
811 return;
812 }
813
814 // (a) Update the process cache with the new message text
815 if ( $text === false ) {
816 // Page deleted
817 $this->cache->setField( $code, $title, '!NONEXISTENT' );
818 } else {
819 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up-to-date
820 $this->cache->setField( $code, $title, ' ' . $text );
821 }
822
823 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
824 DeferredUpdates::addUpdate(
825 new MessageCacheUpdate( $code, $title, $msg ),
826 DeferredUpdates::PRESEND
827 );
828 }
829
834 public function refreshAndReplaceInternal( string $code, array $replacements ) {
835 // Allow one caller at a time to avoid race conditions
836 [ $scopedLock ] = $this->getReentrantScopedLock( $code );
837 if ( !$scopedLock ) {
838 foreach ( $replacements as [ $title ] ) {
839 $this->logger->error(
840 __METHOD__ . ': could not acquire lock to update {title} ({code})',
841 [ 'title' => $title, 'code' => $code ] );
842 }
843
844 return;
845 }
846
847 // Load the existing cache to update it in the local DC cache.
848 // The other DCs will see a hash mismatch.
849 if ( $this->load( $code, self::FOR_UPDATE ) ) {
850 $cache = $this->cache->get( $code );
851 } else {
852 // Err? Fall back to loading from the database.
853 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
854 }
855 // Check if individual cache keys should exist and update cache accordingly
856 $newTextByTitle = []; // map of (title => content)
857 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
858 // Can not inject the WikiPageFactory as it would break the installer since
859 // it instantiates MessageCache before the DB.
860 $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
861 foreach ( $replacements as [ $title ] ) {
862 $page = $wikiPageFactory->newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
863 $page->loadPageData( IDBAccessObject::READ_LATEST );
864 $text = $this->getMessageTextFromContent( $page->getContent() );
865 // Remember the text for the blob store update later on
866 $newTextByTitle[$title] = $text ?? '';
867 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
868 if ( !is_string( $text ) ) {
869 $cache[$title] = '!NONEXISTENT';
870 } elseif ( strlen( $text ) > $this->maxEntrySize ) {
871 $cache[$title] = '!TOO BIG';
872 $newBigTitles[$title] = $page->getLatest();
873 } else {
874 $cache[$title] = ' ' . $text;
875 }
876 }
877 // Update HASH for the new key. Incorporates various administrative keys,
878 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
879 // and previous replace() calls), but that doesn't really matter since we
880 // only ever compare it for equality with a copy saved by saveToCaches().
881 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
882 // Update the too-big WAN cache entries now that we have the new HASH
883 foreach ( $newBigTitles as $title => $id ) {
884 // Match logic of loadCachedMessagePageEntry()
885 $this->wanCache->set(
886 $this->bigMessageCacheKey( $cache['HASH'], $title ),
887 ' ' . $newTextByTitle[$title],
888 self::WAN_TTL
889 );
890 }
891 // Mark this cache as definitely being "latest" (non-volatile) so
892 // load() calls do not try to refresh the cache with replica DB data
893 $cache['LATEST'] = time();
894 // Update the process cache
895 $this->cache->set( $code, $cache );
896 // Pre-emptively update the local datacenter cache so things like edit filter and
897 // prevented changes are reflected immediately; these often use MediaWiki: pages.
898 // The datacenter handling replace() calls should be the same one handling edits
899 // as they require HTTP POST.
900 $this->saveToCaches( $cache, 'all', $code );
901 // Release the lock now that the cache is saved
902 ScopedCallback::consume( $scopedLock );
903
904 // Relay the purge. Touching this check key expires cache contents
905 // and local cache (APC) validation hash across all datacenters.
906 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
907
908 // Purge the messages in the message blob store and fire any hook handlers
909 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
910 foreach ( $replacements as [ $title, $msg ] ) {
911 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
912 $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
913 }
914 }
915
922 private function isCacheExpired( $cache ) {
923 return !isset( $cache['VERSION'] ) ||
924 !isset( $cache['EXPIRY'] ) ||
925 $cache['VERSION'] !== MSG_CACHE_VERSION ||
926 $cache['EXPIRY'] <= wfTimestampNow();
927 }
928
938 private function saveToCaches( array $cache, $dest, $code = false ) {
939 if ( $dest === 'all' ) {
940 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
941 $success = $this->clusterCache->set( $cacheKey, $cache );
942 $this->setValidationHash( $code, $cache );
943 } else {
944 $success = true;
945 }
946
947 $this->saveToLocalCache( $code, $cache );
948
949 return $success;
950 }
951
958 private function getValidationHash( $code ) {
959 $curTTL = null;
960 $value = $this->wanCache->get(
961 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
962 $curTTL,
963 [ $this->getCheckKey( $code ) ]
964 );
965
966 if ( $value ) {
967 $hash = $value['hash'];
968 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
969 // Cache was recently updated via replace() and should be up-to-date.
970 // That method is only called in the primary datacenter and uses FOR_UPDATE.
971 $expired = false;
972 } else {
973 // See if the "check" key was bumped after the hash was generated
974 $expired = ( $curTTL < 0 );
975 }
976 } else {
977 // No hash found at all; cache must regenerate to be safe
978 $hash = false;
979 $expired = true;
980 }
981
982 return [ $hash, $expired ];
983 }
984
995 private function setValidationHash( $code, array $cache ) {
996 $this->wanCache->set(
997 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
998 [
999 'hash' => $cache['HASH'],
1000 'latest' => $cache['LATEST'] ?? 0
1001 ],
1002 WANObjectCache::TTL_INDEFINITE
1003 );
1004 }
1005
1012 private function getReentrantScopedLock( $code, $timeout = self::WAIT_SEC ) {
1013 $key = $this->clusterCache->makeKey( 'messages', $code );
1014
1015 $watchPoint = $this->clusterCache->watchErrors();
1016 $scopedLock = $this->clusterCache->getScopedLock(
1017 $key,
1018 $timeout,
1019 self::LOCK_TTL,
1020 __METHOD__
1021 );
1022 $error = ( !$scopedLock && $this->clusterCache->getLastError( $watchPoint ) );
1023
1024 return [ $scopedLock, $error ];
1025 }
1026
1063 public function get( $key, $useDB = true, $language = null, &$usedKey = '' ) {
1064 if ( is_int( $key ) ) {
1065 // Fix numerical strings that somehow become ints on their way here
1066 $key = (string)$key;
1067 } elseif ( !is_string( $key ) ) {
1068 throw new TypeError( 'Message key must be a string' );
1069 } elseif ( $key === '' ) {
1070 // Shortcut: the empty key is always missing
1071 return false;
1072 }
1073
1074 $language ??= $this->contLang;
1075 $language = $this->getLanguageObject( $language );
1076
1077 // Normalise title-case input (with some inlining)
1078 $lckey = self::normalizeKey( $key );
1079
1080 // Initialize the overrides here to prevent calling the hook too early.
1081 if ( $this->messageKeyOverrides === null ) {
1082 $this->messageKeyOverrides = [];
1083 $this->hookRunner->onMessageCacheFetchOverrides( $this->messageKeyOverrides );
1084 }
1085
1086 if ( isset( $this->messageKeyOverrides[$lckey] ) ) {
1087 $override = $this->messageKeyOverrides[$lckey];
1088
1089 // Strings are deliberately interpreted as message keys,
1090 // to prevent ambiguity between message keys and functions.
1091 if ( is_string( $override ) ) {
1092 $lckey = $override;
1093 } else {
1094 $lckey = $override( $lckey, $this, $language, $useDB );
1095 }
1096 }
1097
1098 $this->hookRunner->onMessageCache__get( $lckey );
1099
1100 $usedKey = $lckey;
1101
1102 // Loop through each language in the fallback list until we find something useful
1103 $message = $this->getMessageFromFallbackChain(
1104 $language,
1105 $lckey,
1106 !$this->disable && $useDB
1107 );
1108
1109 // If we still have no message, maybe the key was in fact a full key so try that
1110 if ( $message === false ) {
1111 $parts = explode( '/', $lckey );
1112 // We may get calls for things that are http-urls from sidebar
1113 // Let's not load nonexistent languages for those
1114 // They usually have more than one slash.
1115 if ( count( $parts ) === 2 && $parts[1] !== '' ) {
1116 $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] ) ?? false;
1117 }
1118 }
1119
1120 // Post-processing if the message exists
1121 if ( $message !== false ) {
1122 // Fix whitespace
1123 $message = str_replace(
1124 [
1125 // Fix for trailing whitespace, removed by textarea
1126 '&#32;',
1127 // Fix for NBSP, converted to space by firefox
1128 '&nbsp;',
1129 '&#160;',
1130 '&shy;'
1131 ],
1132 [
1133 ' ',
1134 "\u{00A0}",
1135 "\u{00A0}",
1136 "\u{00AD}"
1137 ],
1138 $message
1139 );
1140 }
1141
1142 return $message;
1143 }
1144
1160 private function getLanguageObject( $langcode ) {
1161 # Identify which language to get or create a language object for.
1162 # Using is_object here due to Stub objects.
1163 if ( is_object( $langcode ) ) {
1164 # Great, we already have the object (hopefully)!
1165 return $langcode;
1166 }
1167
1168 wfDeprecated( __METHOD__ . ' with not a Language object in $langcode', '1.43' );
1169 if ( $langcode === true || $langcode === $this->contLangCode ) {
1170 # $langcode is the language code of the wikis content language object.
1171 # or it is a boolean and value is true
1172 return $this->contLang;
1173 }
1174
1175 global $wgLang;
1176 if ( $langcode === false || $langcode === $wgLang->getCode() ) {
1177 # $langcode is the language code of user language object.
1178 # or it was a boolean and value is false
1179 return $wgLang;
1180 }
1181
1182 $validCodes = array_keys( $this->languageNameUtils->getLanguageNames() );
1183 if ( in_array( $langcode, $validCodes ) ) {
1184 # $langcode corresponds to a valid language.
1185 return $this->langFactory->getLanguage( $langcode );
1186 }
1187
1188 # $langcode is a string, but not a valid language code; use content language.
1189 $this->logger->debug( 'Invalid language code passed to' . __METHOD__ . ', falling back to content language.' );
1190 return $this->contLang;
1191 }
1192
1205 private function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1206 $alreadyTried = [];
1207
1208 // First try the requested language.
1209 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1210 if ( $message !== false ) {
1211 return $message;
1212 }
1213
1214 // Now try checking the site language.
1215 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1216 return $message;
1217 }
1218
1229 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1230 $langcode = $lang->getCode();
1231
1232 // Try checking the database for the requested language
1233 if ( $useDB ) {
1234 $uckey = $this->contLang->ucfirst( $lckey );
1235
1236 if ( !isset( $alreadyTried[$langcode] ) ) {
1237 $message = $this->getMsgFromNamespace(
1238 $this->getMessagePageName( $langcode, $uckey ),
1239 $langcode
1240 );
1241 if ( $message !== false ) {
1242 return $message;
1243 }
1244 $alreadyTried[$langcode] = true;
1245 }
1246 } else {
1247 $uckey = null;
1248 }
1249
1250 // Return a special value handled in Message::format() to display the message key
1251 // (and fallback keys) and the parameters passed to the message.
1252 // TODO: Move to a better place.
1253 if ( $langcode === 'qqx' ) {
1254 return '($*)';
1255 } elseif (
1256 $langcode === 'x-xss' &&
1257 $this->useXssLanguage &&
1258 !in_array( $lckey, $this->rawHtmlMessages, true )
1259 ) {
1260 $xssViaInnerHtml = "<script>alert('$lckey')</script>";
1261 $xssViaAttribute = '">' . $xssViaInnerHtml . '<x y="';
1262 return $xssViaInnerHtml . $xssViaAttribute . '($*)';
1263 }
1264
1265 // Check the localisation cache
1266 [ $defaultMessage, $messageSource ] =
1267 $this->localisationCache->getSubitemWithSource( $langcode, 'messages', $lckey );
1268 if ( $messageSource === $langcode ) {
1269 return $defaultMessage;
1270 }
1271
1272 // Try checking the database for all of the fallback languages
1273 if ( $useDB ) {
1274 $fallbackChain = $this->languageFallback->getAll( $langcode );
1275
1276 foreach ( $fallbackChain as $code ) {
1277 if ( isset( $alreadyTried[$code] ) ) {
1278 continue;
1279 }
1280
1281 $message = $this->getMsgFromNamespace(
1282 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable uckey is set when used
1283 $this->getMessagePageName( $code, $uckey ), $code );
1284
1285 if ( $message !== false ) {
1286 return $message;
1287 }
1288 $alreadyTried[$code] = true;
1289
1290 // Reached the source language of the default message. Don't look for DB overrides
1291 // further back in the fallback chain. (T229992)
1292 if ( $code === $messageSource ) {
1293 return $defaultMessage;
1294 }
1295 }
1296 }
1297
1298 return $defaultMessage ?? false;
1299 }
1300
1308 private function getMessagePageName( $langcode, $uckey ) {
1309 if ( $langcode === $this->contLangCode ) {
1310 // Messages created in the content language will not have the /lang extension
1311 return $uckey;
1312 } else {
1313 return "$uckey/$langcode";
1314 }
1315 }
1316
1329 public function getMsgFromNamespace( $title, $code ) {
1330 // Load all MediaWiki page definitions into cache. Note that individual keys
1331 // already loaded into the cache during this request remain in the cache, which
1332 // includes the value of hook-defined messages.
1333 $this->load( $code );
1334
1335 $entry = $this->cache->getField( $code, $title );
1336
1337 if ( $entry !== null ) {
1338 // Message page exists as an override of a software messages
1339 if ( substr( $entry, 0, 1 ) === ' ' ) {
1340 // The message exists and is not '!TOO BIG' or '!ERROR'
1341 return (string)substr( $entry, 1 );
1342 } elseif ( $entry === '!NONEXISTENT' ) {
1343 // The text might be '-' or missing due to some data loss
1344 return false;
1345 }
1346 // Load the message page, utilizing the individual message cache.
1347 // If the page does not exist, there will be no hook handler fallbacks.
1348 $entry = $this->loadCachedMessagePageEntry(
1349 $title,
1350 $code,
1351 $this->cache->getField( $code, 'HASH' )
1352 );
1353 } else {
1354 // Message page either does not exist or does not override a software message
1355 if ( !$this->isMainCacheable( $title, $code ) ) {
1356 // Message page does not override any software-defined message. A custom
1357 // message might be defined to have content or settings specific to the wiki.
1358 // Load the message page, utilizing the individual message cache as needed.
1359 $entry = $this->loadCachedMessagePageEntry(
1360 $title,
1361 $code,
1362 $this->cache->getField( $code, 'HASH' )
1363 );
1364 }
1365 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1366 // Message does not have a MediaWiki page definition; try hook handlers
1367 $message = false;
1368 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
1369 $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1370 if ( $message !== false ) {
1371 $this->cache->setField( $code, $title, ' ' . $message );
1372 } else {
1373 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1374 }
1375
1376 return $message;
1377 }
1378 }
1379
1380 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1381 if ( $this->cacheVolatile[$code] ) {
1382 // Make sure that individual keys respect the WAN cache holdoff period too
1383 $this->logger->debug(
1384 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1385 [ 'titleKey' => $title, 'code' => $code ] );
1386 } else {
1387 $this->cache->setField( $code, $title, $entry );
1388 }
1389 // The message exists, so make sure a string is returned
1390 return (string)substr( $entry, 1 );
1391 }
1392
1393 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1394
1395 return false;
1396 }
1397
1404 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1405 $fname = __METHOD__;
1406 return $this->srvCache->getWithSetCallback(
1407 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1408 BagOStuff::TTL_HOUR,
1409 function () use ( $code, $dbKey, $hash, $fname ) {
1410 return $this->wanCache->getWithSetCallback(
1411 $this->bigMessageCacheKey( $hash, $dbKey ),
1412 self::WAN_TTL,
1413 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1414 // Try loading the message from the database
1415 $setOpts += Database::getCacheSetOptions(
1416 MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase()
1417 );
1418 // Use newKnownCurrent() to avoid querying revision/user tables
1419 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1420 // Injecting RevisionStore breaks installer since it
1421 // instantiates MessageCache before DB.
1422 $revision = MediaWikiServices::getInstance()
1423 ->getRevisionLookup()
1424 ->getKnownCurrentRevision( $title );
1425 if ( !$revision ) {
1426 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1427 // When overrides are created, self::replace() takes care of the cache.
1428 return '!NONEXISTENT';
1429 }
1430 $content = $revision->getContent( SlotRecord::MAIN );
1431 if ( $content ) {
1432 $message = $this->getMessageTextFromContent( $content );
1433 } else {
1434 $this->logger->warning(
1435 $fname . ': failed to load page text for \'{titleKey}\'',
1436 [ 'titleKey' => $dbKey, 'code' => $code ]
1437 );
1438 $message = null;
1439 }
1440
1441 if ( !is_string( $message ) ) {
1442 // Revision failed to load Content, or Content is incompatible with wikitext.
1443 // Possibly a temporary loading failure.
1444 $ttl = 5;
1445
1446 return '!NONEXISTENT';
1447 }
1448
1449 return ' ' . $message;
1450 }
1451 );
1452 }
1453 );
1454 }
1455
1463 public function transform( $message, $interface = false, $language = null, ?PageReference $page = null ) {
1464 // Avoid creating parser if nothing to transform
1465 if ( $this->inParser || !str_contains( $message, '{{' ) ) {
1466 return $message;
1467 }
1468
1469 $parser = $this->getParser();
1470 $popts = $this->getParserOptions();
1471 $popts->setInterfaceMessage( $interface );
1472 $popts->setTargetLanguage( $language );
1473
1474 $userlang = $popts->setUserLang( $language );
1475 $this->inParser = true;
1476 $message = $parser->transformMsg( $message, $popts, $page );
1477 $this->inParser = false;
1478 $popts->setUserLang( $userlang );
1479
1480 return $message;
1481 }
1482
1486 public function getParser() {
1487 if ( !$this->parser ) {
1488 $this->parser = $this->parserFactory->create();
1489 }
1490
1491 return $this->parser;
1492 }
1493
1502 public function parse( $text, ?PageReference $page = null, $linestart = true,
1503 $interface = false, $language = null
1504 ) {
1505 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
1506 global $wgTitle;
1507
1508 if ( $this->inParser ) {
1509 return htmlspecialchars( $text );
1510 }
1511
1512 $parser = $this->getParser();
1513 $popts = $this->getParserOptions();
1514 $popts->setInterfaceMessage( $interface );
1515
1516 if ( is_string( $language ) ) {
1517 $language = $this->langFactory->getLanguage( $language );
1518 }
1519 $popts->setTargetLanguage( $language );
1520
1521 if ( !$page ) {
1522 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1523 $logger->info(
1524 __METHOD__ . ' called with no title set.',
1525 [ 'exception' => new RuntimeException ]
1526 );
1527 $page = $wgTitle;
1528 }
1529 // Sometimes $wgTitle isn't set either...
1530 if ( !$page ) {
1531 // It's not uncommon having a null $wgTitle in scripts. See r80898
1532 // Create a ghost title in such case
1533 $page = PageReferenceValue::localReference(
1534 NS_SPECIAL,
1535 'Badtitle/title not set in ' . __METHOD__
1536 );
1537 }
1538
1539 $this->inParser = true;
1540 $res = $parser->parse( $text, $page, $popts, $linestart );
1541 $this->inParser = false;
1542
1543 return $res;
1544 }
1545
1546 public function disable() {
1547 $this->disable = true;
1548 }
1549
1550 public function enable() {
1551 $this->disable = false;
1552 }
1553
1566 public function isDisabled() {
1567 return $this->disable;
1568 }
1569
1575 public function clear() {
1576 $langs = $this->languageNameUtils->getLanguageNames();
1577 foreach ( $langs as $code => $_ ) {
1578 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1579 }
1580 $this->cache->clear();
1581 }
1582
1587 public function figureMessage( $key ) {
1588 $pieces = explode( '/', $key );
1589 if ( count( $pieces ) < 2 ) {
1590 return [ $key, $this->contLangCode ];
1591 }
1592
1593 $lang = array_pop( $pieces );
1594 if ( !$this->languageNameUtils->getLanguageName(
1595 $lang,
1596 LanguageNameUtils::AUTONYMS,
1597 LanguageNameUtils::DEFINED
1598 ) ) {
1599 return [ $key, $this->contLangCode ];
1600 }
1601
1602 $message = implode( '/', $pieces );
1603
1604 return [ $message, $lang ];
1605 }
1606
1616 public function getAllMessageKeys( $code ) {
1617 $this->load( $code );
1618 if ( !$this->cache->has( $code ) ) {
1619 // Apparently load() failed
1620 return null;
1621 }
1622 // Remove administrative keys
1623 $cache = $this->cache->get( $code );
1624 unset( $cache['VERSION'] );
1625 unset( $cache['EXPIRY'] );
1626 unset( $cache['EXCESSIVE'] );
1627 // Remove any !NONEXISTENT keys
1628 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1629
1630 // Keys may appear with a capital first letter. lcfirst them.
1631 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1632 }
1633
1641 public function updateMessageOverride( LinkTarget $linkTarget, ?Content $content = null ) {
1642 // treat null as not existing
1643 $msgText = $this->getMessageTextFromContent( $content ) ?? false;
1644
1645 $this->replace( $linkTarget->getDBkey(), $msgText );
1646
1647 if ( $this->contLangConverter->hasVariants() ) {
1648 $this->contLangConverter->updateConversionTable( $linkTarget );
1649 }
1650 }
1651
1656 public function getCheckKey( $code ) {
1657 return $this->wanCache->makeKey( 'messages', $code );
1658 }
1659
1664 private function getMessageTextFromContent( ?Content $content = null ) {
1665 // @TODO: could skip pseudo-messages like js/css here, based on content model
1666 if ( $content && $content->isRedirect() ) {
1667 // Treat redirects as not existing (T376398)
1668 $msgText = false;
1669 } elseif ( $content ) {
1670 // Message page exists...
1671 // XXX: Is this the right way to turn a Content object into a message?
1672 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1673 // CssContent.
1674 $msgText = $content->getWikitextForTransclusion();
1675 if ( $msgText === false || $msgText === null ) {
1676 // This might be due to some kind of misconfiguration...
1677 $msgText = null;
1678 $this->logger->warning(
1679 __METHOD__ . ": message content doesn't provide wikitext "
1680 . "(content model: " . $content->getModel() . ")" );
1681 }
1682 } else {
1683 // Message page does not exist...
1684 $msgText = false;
1685 }
1686
1687 return $msgText;
1688 }
1689
1695 private function bigMessageCacheKey( $hash, $title ) {
1696 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1697 }
1698}
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:541
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgTitle
Definition Setup.php:541
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...
Base class for language-specific code.
Definition Language.php:78
getCode()
Get the internal language code for this language object.
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.
Set options of the Parser.
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:143
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:669
transformMsg( $text, ParserOptions $options, ?PageReference $page=null)
Wrapper for preprocess()
Definition Parser.php:4927
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)
const CONSTRUCTOR_OPTIONS
Options to be included in the ServiceOptions.
transform( $message, $interface=false, $language=null, ?PageReference $page=null)
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.
updateMessageOverride(LinkTarget $linkTarget, ?Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
replace( $title, $text)
Updates cache as necessary when message page is changed.
Abstract class for any ephemeral data store.
Definition BagOStuff.php:89
No-op implementation that stores nothing.
Multi-datacenter aware caching interface.
Content of like value.
Definition LikeValue.php:14
Base interface for representing page content.
Definition Content.php:39
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.
Interface for database access objects.
Result wrapper for grabbing data queried from an IDatabase object.