MediaWiki REL1_39
MessageCache.php
Go to the documentation of this file.
1<?php
35use Psr\Log\LoggerAwareInterface;
36use Psr\Log\LoggerInterface;
39use Wikimedia\RequestTimeout\TimeoutException;
40use Wikimedia\ScopedCallback;
41
46define( 'MSG_CACHE_VERSION', 2 );
47
53class MessageCache implements LoggerAwareInterface {
57 public const CONSTRUCTOR_OPTIONS = [
58 MainConfigNames::UseDatabaseMessages,
59 MainConfigNames::MaxMsgCacheEntrySize,
60 MainConfigNames::AdaptiveMessageCache,
61 ];
62
67 public const MAX_REQUEST_LANGUAGES = 10;
68
69 private const FOR_UPDATE = 1; // force message reload
70
72 private const WAIT_SEC = 15;
74 private const LOCK_TTL = 30;
75
80 private const WAN_TTL = IExpiringStore::TTL_DAY;
81
83 private $logger;
84
90 private $cache;
91
97 private $systemMessageNames;
98
102 private $cacheVolatile = [];
103
108 private $disable;
109
111 private $maxEntrySize;
112
114 private $adaptive;
115
120 private $parserOptions;
122 private $parser;
123
127 private $inParser = false;
128
130 private $wanCache;
132 private $clusterCache;
134 private $srvCache;
136 private $contLang;
138 private $contLangCode;
140 private $contLangConverter;
142 private $langFactory;
144 private $localisationCache;
146 private $languageNameUtils;
148 private $languageFallback;
150 private $hookRunner;
151
158 public static function normalizeKey( $key ) {
159 $lckey = strtr( $key, ' ', '_' );
160 if ( $lckey === '' ) {
161 // T300792
162 return $lckey;
163 }
164
165 if ( ord( $lckey ) < 128 ) {
166 $lckey[0] = strtolower( $lckey[0] );
167 } else {
168 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
169 }
170
171 return $lckey;
172 }
173
189 public function __construct(
190 WANObjectCache $wanCache,
191 BagOStuff $clusterCache,
192 BagOStuff $serverCache,
193 Language $contLang,
194 LanguageConverterFactory $langConverterFactory,
195 LoggerInterface $logger,
196 ServiceOptions $options,
197 LanguageFactory $langFactory,
198 LocalisationCache $localisationCache,
199 LanguageNameUtils $languageNameUtils,
200 LanguageFallback $languageFallback,
201 HookContainer $hookContainer
202 ) {
203 $this->wanCache = $wanCache;
204 $this->clusterCache = $clusterCache;
205 $this->srvCache = $serverCache;
206 $this->contLang = $contLang;
207 $this->contLangConverter = $langConverterFactory->getLanguageConverter( $contLang );
208 $this->contLangCode = $contLang->getCode();
209 $this->logger = $logger;
210 $this->langFactory = $langFactory;
211 $this->localisationCache = $localisationCache;
212 $this->languageNameUtils = $languageNameUtils;
213 $this->languageFallback = $languageFallback;
214 $this->hookRunner = new HookRunner( $hookContainer );
215
216 // limit size
217 $this->cache = new MapCacheLRU( self::MAX_REQUEST_LANGUAGES );
218
219 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
220 $this->disable = !$options->get( MainConfigNames::UseDatabaseMessages );
221 $this->maxEntrySize = $options->get( MainConfigNames::MaxMsgCacheEntrySize );
222 $this->adaptive = $options->get( MainConfigNames::AdaptiveMessageCache );
223 }
224
225 public function setLogger( LoggerInterface $logger ) {
226 $this->logger = $logger;
227 }
228
234 private function getParserOptions() {
235 if ( !$this->parserOptions ) {
236 $context = RequestContext::getMain();
237 $user = $context->getUser();
238 if ( !$user->isSafeToLoad() ) {
239 // It isn't safe to use the context user yet, so don't try to get a
240 // ParserOptions for it. And don't cache this ParserOptions
241 // either.
242 $po = ParserOptions::newFromAnon();
243 $po->setAllowUnsafeRawHtml( false );
244 return $po;
245 }
246
247 $this->parserOptions = ParserOptions::newFromContext( $context );
248 // Messages may take parameters that could come
249 // from malicious sources. As a precaution, disable
250 // the <html> parser tag when parsing messages.
251 $this->parserOptions->setAllowUnsafeRawHtml( false );
252 }
253
254 return $this->parserOptions;
255 }
256
263 private function getLocalCache( $code ) {
264 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
265
266 return $this->srvCache->get( $cacheKey );
267 }
268
275 private function saveToLocalCache( $code, $cache ) {
276 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
277 $this->srvCache->set( $cacheKey, $cache );
278 }
279
300 private function load( string $code, $mode = null ) {
301 // Don't do double loading...
302 if ( $this->isLanguageLoaded( $code ) && $mode !== self::FOR_UPDATE ) {
303 return true;
304 }
305
306 // Show a log message (once) if loading is disabled
307 if ( $this->disable ) {
308 static $shownDisabled = false;
309 if ( !$shownDisabled ) {
310 $this->logger->debug( __METHOD__ . ': disabled' );
311 $shownDisabled = true;
312 }
313
314 return true;
315 }
316
317 try {
318 return $this->loadUnguarded( $code, $mode );
319 } catch ( Throwable $e ) {
320 // Don't try to load again during the exception handler
321 $this->disable = true;
322 throw $e;
323 }
324 }
325
333 private function loadUnguarded( $code, $mode ) {
334 $success = false; // Keep track of success
335 $staleCache = false; // a cache array with expired data, or false if none has been loaded
336 $where = []; // Debug info, delayed to avoid spamming debug log too much
337
338 // A hash of the expected content is stored in a WAN cache key, providing a way
339 // to invalid the local cache on every server whenever a message page changes.
340 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
341 $this->cacheVolatile[$code] = $hashVolatile;
342 $volatilityOnlyStaleness = false;
343
344 // Try the local cache and check against the cluster hash key...
345 $cache = $this->getLocalCache( $code );
346 if ( !$cache ) {
347 $where[] = 'local cache is empty';
348 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
349 $where[] = 'local cache has the wrong hash';
350 $staleCache = $cache;
351 } elseif ( $this->isCacheExpired( $cache ) ) {
352 $where[] = 'local cache is expired';
353 $staleCache = $cache;
354 } elseif ( $hashVolatile ) {
355 // Some recent message page changes might not show due to DB lag
356 $where[] = 'local cache validation key is expired/volatile';
357 $staleCache = $cache;
358 $volatilityOnlyStaleness = true;
359 } else {
360 $where[] = 'got from local cache';
361 $this->cache->set( $code, $cache );
362 $success = true;
363 }
364
365 if ( !$success ) {
366 // Try the cluster cache, using a lock for regeneration...
367 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
368 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
369 if ( $volatilityOnlyStaleness && $staleCache ) {
370 // While the cluster cache *might* be more up-to-date, we do not want
371 // the I/O strain of every application server fetching the key here during
372 // the volatility period. Either this thread wins the lock and regenerates
373 // the cache or the stale local cache value gets reused.
374 $where[] = 'global cache is presumed expired';
375 } else {
376 $cache = $this->clusterCache->get( $cacheKey );
377 if ( !$cache ) {
378 $where[] = 'global cache is empty';
379 } elseif ( $this->isCacheExpired( $cache ) ) {
380 $where[] = 'global cache is expired';
381 $staleCache = $cache;
382 } elseif ( $hashVolatile ) {
383 // Some recent message page changes might not show due to DB lag
384 $where[] = 'global cache is expired/volatile';
385 $staleCache = $cache;
386 } else {
387 $where[] = 'got from global cache';
388 $this->cache->set( $code, $cache );
389 $this->saveToCaches( $cache, 'local-only', $code );
390 $success = true;
391 break;
392 }
393 }
394
395 // We need to call loadFromDB(). Limit the concurrency to one thread.
396 // This prevents the site from going down when the cache expires.
397 // Note that the DB slam protection lock here is non-blocking.
398 $loadStatus = $this->loadFromDBWithMainLock( $code, $where, $mode );
399 if ( $loadStatus === true ) {
400 $success = true;
401 break;
402 } elseif ( $staleCache ) {
403 // Use the stale cache while some other thread constructs the new one
404 $where[] = 'using stale cache';
405 $this->cache->set( $code, $staleCache );
406 $success = true;
407 break;
408 } elseif ( $failedAttempts > 0 ) {
409 $where[] = 'failed to find cache after waiting';
410 // Already blocked once, so avoid another lock/unlock cycle.
411 // This case will typically be hit if memcached is down, or if
412 // loadFromDB() takes longer than LOCK_WAIT.
413 break;
414 } elseif ( $loadStatus === 'cantacquire' ) {
415 // Wait for the other thread to finish, then retry. Normally,
416 // the memcached get() will then yield the other thread's result.
417 $where[] = 'waiting for other thread to complete';
418 [ , $ioError ] = $this->getReentrantScopedLock( $code );
419 if ( $ioError ) {
420 $where[] = 'failed waiting';
421 // Call loadFromDB() with concurrency limited to one thread per server.
422 // It should be rare for all servers to lack even a stale local cache.
423 $success = $this->loadFromDBWithLocalLock( $code, $where, $mode );
424 break;
425 }
426 } else {
427 // Disable cache; $loadStatus is 'disabled'
428 break;
429 }
430 }
431 }
432
433 if ( !$success ) {
434 $where[] = 'loading FAILED - cache is disabled';
435 $this->disable = true;
436 $this->cache->set( $code, [] );
437 $this->logger->error( __METHOD__ . ": Failed to load $code" );
438 // This used to throw an exception, but that led to nasty side effects like
439 // the whole wiki being instantly down if the memcached server died
440 }
441
442 if ( !$this->isLanguageLoaded( $code ) ) {
443 throw new LogicException( "Process cache for '$code' should be set by now." );
444 }
445
446 $info = implode( ', ', $where );
447 $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
448
449 return $success;
450 }
451
458 private function loadFromDBWithMainLock( $code, array &$where, $mode = null ) {
459 // If cache updates on all levels fail, give up on message overrides.
460 // This is to avoid easy site outages; see $saveSuccess comments below.
461 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
462 $status = $this->clusterCache->get( $statusKey );
463 if ( $status === 'error' ) {
464 $where[] = "could not load; method is still globally disabled";
465 return 'disabled';
466 }
467
468 // Now let's regenerate
469 $where[] = 'loading from DB';
470
471 // Lock the cache to prevent conflicting writes.
472 // This lock is non-blocking so stale cache can quickly be used.
473 // Note that load() will call a blocking getReentrantScopedLock()
474 // after this if it really need to wait for any current thread.
475 [ $scopedLock ] = $this->getReentrantScopedLock( $code, 0 );
476 if ( !$scopedLock ) {
477 $where[] = 'could not acquire main lock';
478 return 'cantacquire';
479 }
480
481 $cache = $this->loadFromDB( $code, $mode );
482 $this->cache->set( $code, $cache );
483 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
484
485 if ( !$saveSuccess ) {
499 if ( $this->srvCache instanceof EmptyBagOStuff ) {
500 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
501 $where[] = 'could not save cache, disabled globally for 5 minutes';
502 } else {
503 $where[] = "could not save global cache";
504 }
505 }
506
507 return true;
508 }
509
516 private function loadFromDBWithLocalLock( $code, array &$where, $mode = null ) {
517 $success = false;
518 $where[] = 'loading from DB using local lock';
519
520 $scopedLock = $this->srvCache->getScopedLock(
521 $this->srvCache->makeKey( 'messages', $code ),
522 self::WAIT_SEC,
523 self::LOCK_TTL,
524 __METHOD__
525 );
526 if ( $scopedLock ) {
527 $cache = $this->loadFromDB( $code, $mode );
528 $this->cache->set( $code, $cache );
529 $this->saveToCaches( $cache, 'local-only', $code );
530 $success = true;
531 }
532
533 return $success;
534 }
535
545 private function loadFromDB( $code, $mode = null ) {
546 $dbr = wfGetDB( ( $mode === self::FOR_UPDATE ) ? DB_PRIMARY : DB_REPLICA );
547
548 $cache = [];
549
550 $mostused = []; // list of "<cased message key>/<code>"
551 if ( $this->adaptive && $code !== $this->contLangCode ) {
552 if ( !$this->cache->has( $this->contLangCode ) ) {
553 $this->load( $this->contLangCode );
554 }
555 $mostused = array_keys( $this->cache->get( $this->contLangCode ) );
556 foreach ( $mostused as $key => $value ) {
557 $mostused[$key] = "$value/$code";
558 }
559 }
560
561 // Common conditions
562 $conds = [
563 'page_is_redirect' => 0,
564 'page_namespace' => NS_MEDIAWIKI,
565 ];
566 if ( count( $mostused ) ) {
567 $conds['page_title'] = $mostused;
568 } elseif ( $code !== $this->contLangCode ) {
569 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
570 } else {
571 // Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
572 // other than language code.
573 $conds[] = 'page_title NOT' .
574 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
575 }
576
577 // Set the stubs for oversized software-defined messages in the main cache map
578 $res = $dbr->select(
579 'page',
580 [ 'page_title', 'page_latest' ],
581 array_merge( $conds, [ 'page_len > ' . intval( $this->maxEntrySize ) ] ),
582 __METHOD__ . "($code)-big"
583 );
584 foreach ( $res as $row ) {
585 // Include entries/stubs for all keys in $mostused in adaptive mode
586 if ( $this->adaptive || $this->isMainCacheable( $row->page_title ) ) {
587 $cache[$row->page_title] = '!TOO BIG';
588 }
589 // At least include revision ID so page changes are reflected in the hash
590 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
591 }
592
593 // Can not inject the RevisionStore as it would break the installer since
594 // it instantiates MessageCache before the DB.
595 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
596 // Set the text for small software-defined messages in the main cache map
597 $revQuery = $revisionStore->getQueryInfo( [ 'page' ] );
598
599 // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
600 // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
601 // query (and also reorder it ourselves because as generated by RevisionStore it'll have
602 // `revision` first rather than `page`).
603 $revQuery['joins']['revision'] = $revQuery['joins']['page'];
604 unset( $revQuery['joins']['page'] );
605 // It isn't actually necessary to reorder $revQuery['tables'] as Database does the right thing
606 // when join conditions are given for all joins, but Gergő is wary of relying on that so pull
607 // `page` to the start.
608 $revQuery['tables'] = array_merge(
609 [ 'page' ],
610 array_diff( $revQuery['tables'], [ 'page' ] )
611 );
612
613 $res = $dbr->select(
614 $revQuery['tables'],
615 $revQuery['fields'],
616 array_merge( $conds, [
617 'page_len <= ' . intval( $this->maxEntrySize ),
618 'page_latest = rev_id' // get the latest revision only
619 ] ),
620 __METHOD__ . "($code)-small",
621 [ 'STRAIGHT_JOIN' ],
622 $revQuery['joins']
623 );
624
625 // Don't load content from uncacheable rows (T313004)
626 [ $cacheableRows, $uncacheableRows ] = $this->separateCacheableRows( $res );
627 $result = $revisionStore->newRevisionsFromBatch( $cacheableRows, [
628 'slots' => [ SlotRecord::MAIN ],
629 'content' => true
630 ] );
631 $revisions = $result->isOK() ? $result->getValue() : [];
632
633 foreach ( $cacheableRows as $row ) {
634 try {
635 $rev = $revisions[$row->rev_id] ?? null;
636 $content = $rev ? $rev->getContent( SlotRecord::MAIN ) : null;
637 $text = $this->getMessageTextFromContent( $content );
638 } catch ( TimeoutException $e ) {
639 throw $e;
640 } catch ( Exception $ex ) {
641 $text = false;
642 }
643
644 if ( !is_string( $text ) ) {
645 $entry = '!ERROR';
646 $this->logger->error(
647 __METHOD__
648 . ": failed to load message page text for {$row->page_title} ($code)"
649 );
650 } else {
651 $entry = ' ' . $text;
652 }
653 $cache[$row->page_title] = $entry;
654 }
655
656 foreach ( $uncacheableRows as $row ) {
657 // T193271: cache object gets too big and slow to generate.
658 // At least include revision ID so page changes are reflected in the hash.
659 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
660 }
661
662 $cache['VERSION'] = MSG_CACHE_VERSION;
663 ksort( $cache );
664
665 // Hash for validating local cache (APC). No need to take into account
666 // messages larger than $wgMaxMsgCacheEntrySize, since those are only
667 // stored and fetched from memcache.
668 $cache['HASH'] = md5( serialize( $cache ) );
669 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
670 unset( $cache['EXCESSIVE'] ); // only needed for hash
671
672 return $cache;
673 }
674
681 private function isLanguageLoaded( $lang ) {
682 // It is important that this only returns true if the cache was fully
683 // populated by load(), so that callers can assume all cache keys exist.
684 // It is possible for $this->cache to be only partially populated through
685 // methods like MessageCache::replace(), which must not make this method
686 // return true (T208897). And this method must cease to return true
687 // if the language was evicted by MapCacheLRU (T230690).
688 return $this->cache->hasField( $lang, 'VERSION' );
689 }
690
702 private function isMainCacheable( $name, $code = null ) {
703 // Convert first letter to lowercase, and strip /code suffix
704 $name = $this->contLang->lcfirst( $name );
705 // Include common conversion table pages. This also avoids problems with
706 // Installer::parse() bailing out due to disallowed DB queries (T207979).
707 if ( strpos( $name, 'conversiontable/' ) === 0 ) {
708 return true;
709 }
710 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
711
712 if ( $code === null ) {
713 // Bulk load
714 if ( $this->systemMessageNames === null ) {
715 $this->systemMessageNames = array_fill_keys(
716 $this->localisationCache->getSubitemList( $this->contLangCode, 'messages' ),
717 true );
718 }
719 return isset( $this->systemMessageNames[$msg] );
720 } else {
721 // Use individual subitem
722 return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
723 }
724 }
725
733 private function separateCacheableRows( $res ) {
734 if ( $this->adaptive ) {
735 // Include entries/stubs for all keys in $mostused in adaptive mode
736 return [ $res, [] ];
737 }
738 $cacheableRows = [];
739 $uncacheableRows = [];
740 foreach ( $res as $row ) {
741 if ( $this->isMainCacheable( $row->page_title ) ) {
742 $cacheableRows[] = $row;
743 } else {
744 $uncacheableRows[] = $row;
745 }
746 }
747 return [ $cacheableRows, $uncacheableRows ];
748 }
749
756 public function replace( $title, $text ) {
757 if ( $this->disable ) {
758 return;
759 }
760
761 list( $msg, $code ) = $this->figureMessage( $title );
762 if ( strpos( $title, '/' ) !== false && $code === $this->contLangCode ) {
763 // Content language overrides do not use the /<code> suffix
764 return;
765 }
766
767 // (a) Update the process cache with the new message text
768 if ( $text === false ) {
769 // Page deleted
770 $this->cache->setField( $code, $title, '!NONEXISTENT' );
771 } else {
772 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
773 $this->cache->setField( $code, $title, ' ' . $text );
774 }
775
776 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
777 DeferredUpdates::addUpdate(
778 new MessageCacheUpdate( $code, $title, $msg ),
779 DeferredUpdates::PRESEND
780 );
781 }
782
787 public function refreshAndReplaceInternal( string $code, array $replacements ) {
788 // Allow one caller at a time to avoid race conditions
789 [ $scopedLock ] = $this->getReentrantScopedLock( $code );
790 if ( !$scopedLock ) {
791 foreach ( $replacements as list( $title ) ) {
792 $this->logger->error(
793 __METHOD__ . ': could not acquire lock to update {title} ({code})',
794 [ 'title' => $title, 'code' => $code ] );
795 }
796
797 return;
798 }
799
800 // Load the existing cache to update it in the local DC cache.
801 // The other DCs will see a hash mismatch.
802 if ( $this->load( $code, self::FOR_UPDATE ) ) {
803 $cache = $this->cache->get( $code );
804 } else {
805 // Err? Fall back to loading from the database.
806 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
807 }
808 // Check if individual cache keys should exist and update cache accordingly
809 $newTextByTitle = []; // map of (title => content)
810 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
811 // Can not inject the WikiPageFactory as it would break the installer since
812 // it instantiates MessageCache before the DB.
813 $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
814 foreach ( $replacements as list( $title ) ) {
815 $page = $wikiPageFactory->newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
816 $page->loadPageData( $page::READ_LATEST );
817 $text = $this->getMessageTextFromContent( $page->getContent() );
818 // Remember the text for the blob store update later on
819 $newTextByTitle[$title] = $text ?? '';
820 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
821 if ( !is_string( $text ) ) {
822 $cache[$title] = '!NONEXISTENT';
823 } elseif ( strlen( $text ) > $this->maxEntrySize ) {
824 $cache[$title] = '!TOO BIG';
825 $newBigTitles[$title] = $page->getLatest();
826 } else {
827 $cache[$title] = ' ' . $text;
828 }
829 }
830 // Update HASH for the new key. Incorporates various administrative keys,
831 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
832 // and previous replace() calls), but that doesn't really matter since we
833 // only ever compare it for equality with a copy saved by saveToCaches().
834 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
835 // Update the too-big WAN cache entries now that we have the new HASH
836 foreach ( $newBigTitles as $title => $id ) {
837 // Match logic of loadCachedMessagePageEntry()
838 $this->wanCache->set(
839 $this->bigMessageCacheKey( $cache['HASH'], $title ),
840 ' ' . $newTextByTitle[$title],
841 self::WAN_TTL
842 );
843 }
844 // Mark this cache as definitely being "latest" (non-volatile) so
845 // load() calls do not try to refresh the cache with replica DB data
846 $cache['LATEST'] = time();
847 // Update the process cache
848 $this->cache->set( $code, $cache );
849 // Pre-emptively update the local datacenter cache so things like edit filter and
850 // prevented changes are reflected immediately; these often use MediaWiki: pages.
851 // The datacenter handling replace() calls should be the same one handling edits
852 // as they require HTTP POST.
853 $this->saveToCaches( $cache, 'all', $code );
854 // Release the lock now that the cache is saved
855 ScopedCallback::consume( $scopedLock );
856
857 // Relay the purge. Touching this check key expires cache contents
858 // and local cache (APC) validation hash across all datacenters.
859 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
860
861 // Purge the messages in the message blob store and fire any hook handlers
862 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
863 foreach ( $replacements as list( $title, $msg ) ) {
864 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
865 $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
866 }
867 }
868
875 private function isCacheExpired( $cache ) {
876 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
877 return true;
878 }
879 if ( $cache['VERSION'] !== MSG_CACHE_VERSION ) {
880 return true;
881 }
882 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
883 return true;
884 }
885
886 return false;
887 }
888
898 private function saveToCaches( array $cache, $dest, $code = false ) {
899 if ( $dest === 'all' ) {
900 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
901 $success = $this->clusterCache->set( $cacheKey, $cache );
902 $this->setValidationHash( $code, $cache );
903 } else {
904 $success = true;
905 }
906
907 $this->saveToLocalCache( $code, $cache );
908
909 return $success;
910 }
911
918 private function getValidationHash( $code ) {
919 $curTTL = null;
920 $value = $this->wanCache->get(
921 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
922 $curTTL,
923 [ $this->getCheckKey( $code ) ]
924 );
925
926 if ( $value ) {
927 $hash = $value['hash'];
928 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
929 // Cache was recently updated via replace() and should be up-to-date.
930 // That method is only called in the primary datacenter and uses FOR_UPDATE.
931 $expired = false;
932 } else {
933 // See if the "check" key was bumped after the hash was generated
934 $expired = ( $curTTL < 0 );
935 }
936 } else {
937 // No hash found at all; cache must regenerate to be safe
938 $hash = false;
939 $expired = true;
940 }
941
942 return [ $hash, $expired ];
943 }
944
955 private function setValidationHash( $code, array $cache ) {
956 $this->wanCache->set(
957 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
958 [
959 'hash' => $cache['HASH'],
960 'latest' => $cache['LATEST'] ?? 0
961 ],
962 WANObjectCache::TTL_INDEFINITE
963 );
964 }
965
972 private function getReentrantScopedLock( $code, $timeout = self::WAIT_SEC ) {
973 $key = $this->clusterCache->makeKey( 'messages', $code );
974
975 $watchPoint = $this->clusterCache->watchErrors();
976 $scopedLock = $this->clusterCache->getScopedLock(
977 $key,
978 $timeout,
979 self::LOCK_TTL,
980 __METHOD__
981 );
982 $error = ( !$scopedLock && $this->clusterCache->getLastError( $watchPoint ) );
983
984 return [ $scopedLock, $error ];
985 }
986
1019 public function get( $key, $useDB = true, $langcode = true ) {
1020 if ( is_int( $key ) ) {
1021 // Fix numerical strings that somehow become ints on their way here
1022 $key = (string)$key;
1023 } elseif ( !is_string( $key ) ) {
1024 throw new TypeError( 'Message key must be a string' );
1025 } elseif ( $key === '' ) {
1026 // Shortcut: the empty key is always missing
1027 return false;
1028 }
1029
1030 // Normalise title-case input (with some inlining)
1031 $lckey = self::normalizeKey( $key );
1032
1033 $this->hookRunner->onMessageCache__get( $lckey );
1034
1035 // Loop through each language in the fallback list until we find something useful
1036 $message = $this->getMessageFromFallbackChain(
1037 wfGetLangObj( $langcode ),
1038 $lckey,
1039 !$this->disable && $useDB
1040 );
1041
1042 // If we still have no message, maybe the key was in fact a full key so try that
1043 if ( $message === false ) {
1044 $parts = explode( '/', $lckey );
1045 // We may get calls for things that are http-urls from sidebar
1046 // Let's not load nonexistent languages for those
1047 // They usually have more than one slash.
1048 if ( count( $parts ) === 2 && $parts[1] !== '' ) {
1049 $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] );
1050 if ( $message === null ) {
1051 $message = false;
1052 }
1053 }
1054 }
1055
1056 // Post-processing if the message exists
1057 if ( $message !== false ) {
1058 // Fix whitespace
1059 $message = str_replace(
1060 [
1061 // Fix for trailing whitespace, removed by textarea
1062 '&#32;',
1063 // Fix for NBSP, converted to space by firefox
1064 '&nbsp;',
1065 '&#160;',
1066 '&shy;'
1067 ],
1068 [
1069 ' ',
1070 "\u{00A0}",
1071 "\u{00A0}",
1072 "\u{00AD}"
1073 ],
1074 $message
1075 );
1076 }
1077
1078 return $message;
1079 }
1080
1093 private function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1094 $alreadyTried = [];
1095
1096 // First try the requested language.
1097 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1098 if ( $message !== false ) {
1099 return $message;
1100 }
1101
1102 // Now try checking the site language.
1103 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1104 return $message;
1105 }
1106
1117 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1118 $langcode = $lang->getCode();
1119
1120 // Try checking the database for the requested language
1121 if ( $useDB ) {
1122 $uckey = $this->contLang->ucfirst( $lckey );
1123
1124 if ( !isset( $alreadyTried[$langcode] ) ) {
1125 $message = $this->getMsgFromNamespace(
1126 $this->getMessagePageName( $langcode, $uckey ),
1127 $langcode
1128 );
1129 if ( $message !== false ) {
1130 return $message;
1131 }
1132 $alreadyTried[$langcode] = true;
1133 }
1134 } else {
1135 $uckey = null;
1136 }
1137
1138 // Return a special value handled in Message::format() to display the message key
1139 // (and fallback keys) and the parameters passed to the message.
1140 // TODO: Move to a better place.
1141 if ( $langcode === 'qqx' ) {
1142 return '($*)';
1143 }
1144
1145 // Check the localisation cache
1146 [ $defaultMessage, $messageSource ] =
1147 $this->localisationCache->getSubitemWithSource( $langcode, 'messages', $lckey );
1148 if ( $messageSource === $langcode ) {
1149 return $defaultMessage;
1150 }
1151
1152 // Try checking the database for all of the fallback languages
1153 if ( $useDB ) {
1154 $fallbackChain = $this->languageFallback->getAll( $langcode );
1155
1156 foreach ( $fallbackChain as $code ) {
1157 if ( isset( $alreadyTried[$code] ) ) {
1158 continue;
1159 }
1160
1161 $message = $this->getMsgFromNamespace(
1162 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable uckey is set when used
1163 $this->getMessagePageName( $code, $uckey ), $code );
1164
1165 if ( $message !== false ) {
1166 return $message;
1167 }
1168 $alreadyTried[$code] = true;
1169
1170 // Reached the source language of the default message. Don't look for DB overrides
1171 // further back in the fallback chain. (T229992)
1172 if ( $code === $messageSource ) {
1173 return $defaultMessage;
1174 }
1175 }
1176 }
1177
1178 return $defaultMessage ?? false;
1179 }
1180
1188 private function getMessagePageName( $langcode, $uckey ) {
1189 if ( $langcode === $this->contLangCode ) {
1190 // Messages created in the content language will not have the /lang extension
1191 return $uckey;
1192 } else {
1193 return "$uckey/$langcode";
1194 }
1195 }
1196
1209 public function getMsgFromNamespace( $title, $code ) {
1210 // Load all MediaWiki page definitions into cache. Note that individual keys
1211 // already loaded into cache during this request remain in the cache, which
1212 // includes the value of hook-defined messages.
1213 $this->load( $code );
1214
1215 $entry = $this->cache->getField( $code, $title );
1216
1217 if ( $entry !== null ) {
1218 // Message page exists as an override of a software messages
1219 if ( substr( $entry, 0, 1 ) === ' ' ) {
1220 // The message exists and is not '!TOO BIG' or '!ERROR'
1221 return (string)substr( $entry, 1 );
1222 } elseif ( $entry === '!NONEXISTENT' ) {
1223 // The text might be '-' or missing due to some data loss
1224 return false;
1225 }
1226 // Load the message page, utilizing the individual message cache.
1227 // If the page does not exist, there will be no hook handler fallbacks.
1228 $entry = $this->loadCachedMessagePageEntry(
1229 $title,
1230 $code,
1231 $this->cache->getField( $code, 'HASH' )
1232 );
1233 } else {
1234 // Message page either does not exist or does not override a software message
1235 if ( !$this->isMainCacheable( $title, $code ) ) {
1236 // Message page does not override any software-defined message. A custom
1237 // message might be defined to have content or settings specific to the wiki.
1238 // Load the message page, utilizing the individual message cache as needed.
1239 $entry = $this->loadCachedMessagePageEntry(
1240 $title,
1241 $code,
1242 $this->cache->getField( $code, 'HASH' )
1243 );
1244 }
1245 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1246 // Message does not have a MediaWiki page definition; try hook handlers
1247 $message = false;
1248 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
1249 $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1250 if ( $message !== false ) {
1251 $this->cache->setField( $code, $title, ' ' . $message );
1252 } else {
1253 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1254 }
1255
1256 return $message;
1257 }
1258 }
1259
1260 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1261 if ( $this->cacheVolatile[$code] ) {
1262 // Make sure that individual keys respect the WAN cache holdoff period too
1263 $this->logger->debug(
1264 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1265 [ 'titleKey' => $title, 'code' => $code ] );
1266 } else {
1267 $this->cache->setField( $code, $title, $entry );
1268 }
1269 // The message exists, so make sure a string is returned
1270 return (string)substr( $entry, 1 );
1271 }
1272
1273 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1274
1275 return false;
1276 }
1277
1284 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1285 $fname = __METHOD__;
1286 return $this->srvCache->getWithSetCallback(
1287 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1288 BagOStuff::TTL_HOUR,
1289 function () use ( $code, $dbKey, $hash, $fname ) {
1290 return $this->wanCache->getWithSetCallback(
1291 $this->bigMessageCacheKey( $hash, $dbKey ),
1292 self::WAN_TTL,
1293 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1294 // Try loading the message from the database
1295 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1296 // Use newKnownCurrent() to avoid querying revision/user tables
1297 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1298 // Injecting RevisionStore breaks installer since it
1299 // instantiates MessageCache before DB.
1300 $revision = MediaWikiServices::getInstance()
1301 ->getRevisionLookup()
1302 ->getKnownCurrentRevision( $title );
1303 if ( !$revision ) {
1304 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1305 // When overrides are created, self::replace() takes care of the cache.
1306 return '!NONEXISTENT';
1307 }
1308 $content = $revision->getContent( SlotRecord::MAIN );
1309 if ( $content ) {
1310 $message = $this->getMessageTextFromContent( $content );
1311 } else {
1312 $this->logger->warning(
1313 $fname . ': failed to load page text for \'{titleKey}\'',
1314 [ 'titleKey' => $dbKey, 'code' => $code ]
1315 );
1316 $message = null;
1317 }
1318
1319 if ( !is_string( $message ) ) {
1320 // Revision failed to load Content, or Content is incompatible with wikitext.
1321 // Possibly a temporary loading failure.
1322 $ttl = 5;
1323
1324 return '!NONEXISTENT';
1325 }
1326
1327 return ' ' . $message;
1328 }
1329 );
1330 }
1331 );
1332 }
1333
1341 public function transform( $message, $interface = false, $language = null, PageReference $page = null ) {
1342 // Avoid creating parser if nothing to transform
1343 if ( strpos( $message, '{{' ) === false ) {
1344 return $message;
1345 }
1346
1347 if ( $this->inParser ) {
1348 return $message;
1349 }
1350
1351 $parser = $this->getParser();
1352 if ( $parser ) {
1353 $popts = $this->getParserOptions();
1354 $popts->setInterfaceMessage( $interface );
1355 $popts->setTargetLanguage( $language );
1356
1357 $userlang = $popts->setUserLang( $language );
1358 $this->inParser = true;
1359 $message = $parser->transformMsg( $message, $popts, $page );
1360 $this->inParser = false;
1361 $popts->setUserLang( $userlang );
1362 }
1363
1364 return $message;
1365 }
1366
1370 public function getParser() {
1371 if ( !$this->parser ) {
1372 $parser = MediaWikiServices::getInstance()->getParser();
1373 // Clone it and store it
1374 $this->parser = clone $parser;
1375 }
1376
1377 return $this->parser;
1378 }
1379
1388 public function parse( $text, PageReference $page = null, $linestart = true,
1389 $interface = false, $language = null
1390 ) {
1391 global $wgTitle;
1392
1393 if ( $this->inParser ) {
1394 return htmlspecialchars( $text );
1395 }
1396
1397 $parser = $this->getParser();
1398 $popts = $this->getParserOptions();
1399 $popts->setInterfaceMessage( $interface );
1400
1401 if ( is_string( $language ) ) {
1402 $language = $this->langFactory->getLanguage( $language );
1403 }
1404 $popts->setTargetLanguage( $language );
1405
1406 if ( !$page ) {
1407 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1408 $logger->info(
1409 __METHOD__ . ' called with no title set.',
1410 [ 'exception' => new Exception ]
1411 );
1412 $page = $wgTitle;
1413 }
1414 // Sometimes $wgTitle isn't set either...
1415 if ( !$page ) {
1416 // It's not uncommon having a null $wgTitle in scripts. See r80898
1417 // Create a ghost title in such case
1418 $page = PageReferenceValue::localReference(
1419 NS_SPECIAL,
1420 'Badtitle/title not set in ' . __METHOD__
1421 );
1422 }
1423
1424 $this->inParser = true;
1425 $res = $parser->parse( $text, $page, $popts, $linestart );
1426 $this->inParser = false;
1427
1428 return $res;
1429 }
1430
1431 public function disable() {
1432 $this->disable = true;
1433 }
1434
1435 public function enable() {
1436 $this->disable = false;
1437 }
1438
1451 public function isDisabled() {
1452 return $this->disable;
1453 }
1454
1460 public function clear() {
1461 $langs = $this->languageNameUtils->getLanguageNames();
1462 foreach ( array_keys( $langs ) as $code ) {
1463 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1464 }
1465 $this->cache->clear();
1466 }
1467
1472 public function figureMessage( $key ) {
1473 $pieces = explode( '/', $key );
1474 if ( count( $pieces ) < 2 ) {
1475 return [ $key, $this->contLangCode ];
1476 }
1477
1478 $lang = array_pop( $pieces );
1479 if ( !$this->languageNameUtils->getLanguageName(
1480 $lang,
1481 LanguageNameUtils::AUTONYMS,
1482 LanguageNameUtils::DEFINED
1483 ) ) {
1484 return [ $key, $this->contLangCode ];
1485 }
1486
1487 $message = implode( '/', $pieces );
1488
1489 return [ $message, $lang ];
1490 }
1491
1500 public function getAllMessageKeys( $code ) {
1501 $this->load( $code );
1502 if ( !$this->cache->has( $code ) ) {
1503 // Apparently load() failed
1504 return null;
1505 }
1506 // Remove administrative keys
1507 $cache = $this->cache->get( $code );
1508 unset( $cache['VERSION'] );
1509 unset( $cache['EXPIRY'] );
1510 unset( $cache['EXCESSIVE'] );
1511 // Remove any !NONEXISTENT keys
1512 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1513
1514 // Keys may appear with a capital first letter. lcfirst them.
1515 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1516 }
1517
1525 public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1526 $msgText = $this->getMessageTextFromContent( $content );
1527 if ( $msgText === null ) {
1528 $msgText = false; // treat as not existing
1529 }
1530
1531 $this->replace( $linkTarget->getDBkey(), $msgText );
1532
1533 if ( $this->contLangConverter->hasVariants() ) {
1534 $this->contLangConverter->updateConversionTable( $linkTarget );
1535 }
1536 }
1537
1542 public function getCheckKey( $code ) {
1543 return $this->wanCache->makeKey( 'messages', $code );
1544 }
1545
1550 private function getMessageTextFromContent( Content $content = null ) {
1551 // @TODO: could skip pseudo-messages like js/css here, based on content model
1552 if ( $content ) {
1553 // Message page exists...
1554 // XXX: Is this the right way to turn a Content object into a message?
1555 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1556 // CssContent. MessageContent is *not* used for storing messages, it's
1557 // only used for wrapping them when needed.
1558 $msgText = $content->getWikitextForTransclusion();
1559 if ( $msgText === false || $msgText === null ) {
1560 // This might be due to some kind of misconfiguration...
1561 $msgText = null;
1562 $this->logger->warning(
1563 __METHOD__ . ": message content doesn't provide wikitext "
1564 . "(content model: " . $content->getModel() . ")" );
1565 }
1566 } else {
1567 // Message page does not exist...
1568 $msgText = false;
1569 }
1570
1571 return $msgText;
1572 }
1573
1579 private function bigMessageCacheKey( $hash, $title ) {
1580 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1581 }
1582}
serialize()
const NS_MEDIAWIKI
Definition Defines.php:72
const NS_SPECIAL
Definition Defines.php:53
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode $wgTitle
Definition Setup.php:497
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:53
getCode()
Get the internal language code for this language object.
Caching for the contents of localisation files.
Handles a simple LRU key/value map with a maximum number of entries.
A class for passing options to services.
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
An interface for creating language converters.
getLanguageConverter( $language=null)
Provide a LanguageConverter for given language.
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
A service that provides utilities to do with language names and codes.
PSR-3 logger instance factory.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Immutable value object representing a page reference.
Value object representing a content slot associated with a page revision.
Message cache purging and in-place update handler for specific message page changes.
Cache messages that are defined by MediaWiki-namespace pages or by hooks.
refreshAndReplaceInternal(string $code, array $replacements)
const MAX_REQUEST_LANGUAGES
The size of the MapCacheLRU which stores message data.
getCheckKey( $code)
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, Language $contLang, LanguageConverterFactory $langConverterFactory, LoggerInterface $logger, ServiceOptions $options, LanguageFactory $langFactory, LocalisationCache $localisationCache, LanguageNameUtils $languageNameUtils, LanguageFallback $languageFallback, HookContainer $hookContainer)
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.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:96
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:691
transformMsg( $text, ParserOptions $options, ?PageReference $page=null)
Wrapper for preprocess()
Definition Parser.php:4908
Multi-datacenter aware caching interface.
Base interface for content objects.
Definition Content.php:35
The shared interface for all language converters.
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.
Result wrapper for grabbing data queried from an IDatabase object.
$cache
Definition mcc.php:33
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28
$content
Definition router.php:76
return true
Definition router.php:92
if(!isset( $args[0])) $lang