MediaWiki REL1_37
MessageCache.php
Go to the documentation of this file.
1<?php
35use Psr\Log\LoggerAwareInterface;
36use Psr\Log\LoggerInterface;
38use Wikimedia\ScopedCallback;
39
44define( 'MSG_CACHE_VERSION', 2 );
45
52class MessageCache implements LoggerAwareInterface {
53 private const FOR_UPDATE = 1; // force message reload
54
56 private const WAIT_SEC = 15;
58 private const LOCK_TTL = 30;
59
64 private const WAN_TTL = IExpiringStore::TTL_DAY;
65
67 private $logger;
68
74 protected $cache;
75
82
86 protected $cacheVolatile = [];
87
92 protected $mDisable;
93
98 protected $mParserOptions;
100 protected $mParser;
101
105 protected $mInParser = false;
106
108 protected $wanCache;
110 protected $clusterCache;
112 protected $srvCache;
114 protected $contLang;
116 protected $contLangCode;
120 protected $langFactory;
128 private $hookRunner;
129
139 public static function singleton() {
140 wfDeprecated( __METHOD__, '1.34' );
141 return MediaWikiServices::getInstance()->getMessageCache();
142 }
143
150 public static function normalizeKey( $key ) {
151 $lckey = strtr( $key, ' ', '_' );
152 if ( ord( $lckey ) < 128 ) {
153 $lckey[0] = strtolower( $lckey[0] );
154 } else {
155 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
156 }
157
158 return $lckey;
159 }
160
178 public function __construct(
179 WANObjectCache $wanCache,
180 BagOStuff $clusterCache,
181 BagOStuff $serverCache,
182 Language $contLang,
183 ILanguageConverter $contLangConverter,
184 LoggerInterface $logger,
185 array $options,
186 LanguageFactory $langFactory,
187 LocalisationCache $localisationCache,
188 LanguageNameUtils $languageNameUtils,
189 LanguageFallback $languageFallback,
190 HookContainer $hookContainer
191 ) {
192 $this->wanCache = $wanCache;
193 $this->clusterCache = $clusterCache;
194 $this->srvCache = $serverCache;
195 $this->contLang = $contLang;
196 $this->contLangConverter = $contLangConverter;
197 $this->contLangCode = $contLang->getCode();
198 $this->logger = $logger;
199 $this->langFactory = $langFactory;
200 $this->localisationCache = $localisationCache;
201 $this->languageNameUtils = $languageNameUtils;
202 $this->languageFallback = $languageFallback;
203 $this->hookRunner = new HookRunner( $hookContainer );
204
205 $this->cache = new MapCacheLRU( 5 ); // limit size for sanity
206
207 $this->mDisable = !( $options['useDB'] ?? true );
208 }
209
210 public function setLogger( LoggerInterface $logger ) {
211 $this->logger = $logger;
212 }
213
219 private function getParserOptions() {
220 if ( !$this->mParserOptions ) {
221 $user = RequestContext::getMain()->getUser();
222 if ( !$user->isSafeToLoad() ) {
223 // It isn't safe to use the context user yet, so don't try to get a
224 // ParserOptions for it. And don't cache this ParserOptions
225 // either.
226 $po = ParserOptions::newFromAnon();
227 $po->setAllowUnsafeRawHtml( false );
228 return $po;
229 }
230
231 $this->mParserOptions = new ParserOptions( $user );
232 // Messages may take parameters that could come
233 // from malicious sources. As a precaution, disable
234 // the <html> parser tag when parsing messages.
235 $this->mParserOptions->setAllowUnsafeRawHtml( false );
236 }
237
238 return $this->mParserOptions;
239 }
240
247 protected function getLocalCache( $code ) {
248 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
249
250 return $this->srvCache->get( $cacheKey );
251 }
252
259 protected function saveToLocalCache( $code, $cache ) {
260 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
261 $this->srvCache->set( $cacheKey, $cache );
262 }
263
285 protected function load( $code, $mode = null ) {
286 if ( !is_string( $code ) ) {
287 throw new InvalidArgumentException( "Missing language code" );
288 }
289
290 # Don't do double loading...
291 if ( $this->isLanguageLoaded( $code ) && $mode != self::FOR_UPDATE ) {
292 return true;
293 }
294
295 # 8 lines of code just to say (once) that message cache is disabled
296 if ( $this->mDisable ) {
297 static $shownDisabled = false;
298 if ( !$shownDisabled ) {
299 $this->logger->debug( __METHOD__ . ': disabled' );
300 $shownDisabled = true;
301 }
302
303 return true;
304 }
305
306 # Loading code starts
307 $success = false; # Keep track of success
308 $staleCache = false; # a cache array with expired data, or false if none has been loaded
309 $where = []; # Debug info, delayed to avoid spamming debug log too much
310
311 # Hash of the contents is stored in memcache, to detect if data-center cache
312 # or local cache goes out of date (e.g. due to replace() on some other server)
313 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
314 $this->cacheVolatile[$code] = $hashVolatile;
315
316 # Try the local cache and check against the cluster hash key...
317 $cache = $this->getLocalCache( $code );
318 if ( !$cache ) {
319 $where[] = 'local cache is empty';
320 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
321 $where[] = 'local cache has the wrong hash';
322 $staleCache = $cache;
323 } elseif ( $this->isCacheExpired( $cache ) ) {
324 $where[] = 'local cache is expired';
325 $staleCache = $cache;
326 } elseif ( $hashVolatile ) {
327 $where[] = 'local cache validation key is expired/volatile';
328 $staleCache = $cache;
329 } else {
330 $where[] = 'got from local cache';
331 $this->cache->set( $code, $cache );
332 $success = true;
333 }
334
335 if ( !$success ) {
336 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
337 # Try the global cache. If it is empty, try to acquire a lock. If
338 # the lock can't be acquired, wait for the other thread to finish
339 # and then try the global cache a second time.
340 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
341 if ( $hashVolatile && $staleCache ) {
342 # Do not bother fetching the whole cache blob to avoid I/O.
343 # Instead, just try to get the non-blocking $statusKey lock
344 # below, and use the local stale value if it was not acquired.
345 $where[] = 'global cache is presumed expired';
346 } else {
347 $cache = $this->clusterCache->get( $cacheKey );
348 if ( !$cache ) {
349 $where[] = 'global cache is empty';
350 } elseif ( $this->isCacheExpired( $cache ) ) {
351 $where[] = 'global cache is expired';
352 $staleCache = $cache;
353 } elseif ( $hashVolatile ) {
354 # DB results are replica DB lag prone until the holdoff TTL passes.
355 # By then, updates should be reflected in loadFromDBWithLock().
356 # One thread regenerates the cache while others use old values.
357 $where[] = 'global cache is expired/volatile';
358 $staleCache = $cache;
359 } else {
360 $where[] = 'got from global cache';
361 $this->cache->set( $code, $cache );
362 $this->saveToCaches( $cache, 'local-only', $code );
363 $success = true;
364 }
365 }
366
367 if ( $success ) {
368 # Done, no need to retry
369 break;
370 }
371
372 # We need to call loadFromDB. Limit the concurrency to one process.
373 # This prevents the site from going down when the cache expires.
374 # Note that the DB slam protection lock here is non-blocking.
375 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
376 if ( $loadStatus === true ) {
377 $success = true;
378 break;
379 } elseif ( $staleCache ) {
380 # Use the stale cache while some other thread constructs the new one
381 $where[] = 'using stale cache';
382 $this->cache->set( $code, $staleCache );
383 $success = true;
384 break;
385 } elseif ( $failedAttempts > 0 ) {
386 # Already blocked once, so avoid another lock/unlock cycle.
387 # This case will typically be hit if memcached is down, or if
388 # loadFromDB() takes longer than LOCK_WAIT.
389 $where[] = "could not acquire status key.";
390 break;
391 } elseif ( $loadStatus === 'cantacquire' ) {
392 # Wait for the other thread to finish, then retry. Normally,
393 # the memcached get() will then yield the other thread's result.
394 $where[] = 'waited for other thread to complete';
395 $this->getReentrantScopedLock( $cacheKey );
396 } else {
397 # Disable cache; $loadStatus is 'disabled'
398 break;
399 }
400 }
401 }
402
403 if ( !$success ) {
404 $where[] = 'loading FAILED - cache is disabled';
405 $this->mDisable = true;
406 $this->cache->set( $code, [] );
407 $this->logger->error( __METHOD__ . ": Failed to load $code" );
408 # This used to throw an exception, but that led to nasty side effects like
409 # the whole wiki being instantly down if the memcached server died
410 }
411
412 if ( !$this->isLanguageLoaded( $code ) ) { // sanity
413 throw new LogicException( "Process cache for '$code' should be set by now." );
414 }
415
416 $info = implode( ', ', $where );
417 $this->logger->debug( __METHOD__ . ": Loading $code... $info" );
418
419 return $success;
420 }
421
428 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
429 # If cache updates on all levels fail, give up on message overrides.
430 # This is to avoid easy site outages; see $saveSuccess comments below.
431 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
432 $status = $this->clusterCache->get( $statusKey );
433 if ( $status === 'error' ) {
434 $where[] = "could not load; method is still globally disabled";
435 return 'disabled';
436 }
437
438 # Now let's regenerate
439 $where[] = 'loading from database';
440
441 # Lock the cache to prevent conflicting writes.
442 # This lock is non-blocking so stale cache can quickly be used.
443 # Note that load() will call a blocking getReentrantScopedLock()
444 # after this if it really need to wait for any current thread.
445 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
446 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
447 if ( !$scopedLock ) {
448 $where[] = 'could not acquire main lock';
449 return 'cantacquire';
450 }
451
452 $cache = $this->loadFromDB( $code, $mode );
453 $this->cache->set( $code, $cache );
454 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
455
456 if ( !$saveSuccess ) {
470 if ( $this->srvCache instanceof EmptyBagOStuff ) {
471 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
472 $where[] = 'could not save cache, disabled globally for 5 minutes';
473 } else {
474 $where[] = "could not save global cache";
475 }
476 }
477
478 return true;
479 }
480
490 protected function loadFromDB( $code, $mode = null ) {
492
493 // (T164666) The query here performs really poorly on WMF's
494 // contributions replicas. We don't have a way to say "any group except
495 // contributions", so for the moment let's specify 'api'.
496 // @todo: Get rid of this hack.
497 $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_PRIMARY : DB_REPLICA, 'api' );
498
499 $cache = [];
500
501 $mostused = []; // list of "<cased message key>/<code>"
502 if ( $wgAdaptiveMessageCache && $code !== $this->contLangCode ) {
503 if ( !$this->cache->has( $this->contLangCode ) ) {
504 $this->load( $this->contLangCode );
505 }
506 $mostused = array_keys( $this->cache->get( $this->contLangCode ) );
507 foreach ( $mostused as $key => $value ) {
508 $mostused[$key] = "$value/$code";
509 }
510 }
511
512 // Common conditions
513 $conds = [
514 'page_is_redirect' => 0,
515 'page_namespace' => NS_MEDIAWIKI,
516 ];
517 if ( count( $mostused ) ) {
518 $conds['page_title'] = $mostused;
519 } elseif ( $code !== $this->contLangCode ) {
520 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
521 } else {
522 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
523 # other than language code.
524 $conds[] = 'page_title NOT' .
525 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
526 }
527
528 // Set the stubs for oversized software-defined messages in the main cache map
529 $res = $dbr->select(
530 'page',
531 [ 'page_title', 'page_latest' ],
532 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
533 __METHOD__ . "($code)-big"
534 );
535 foreach ( $res as $row ) {
536 // Include entries/stubs for all keys in $mostused in adaptive mode
537 if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $row->page_title )
538 ) {
539 $cache[$row->page_title] = '!TOO BIG';
540 }
541 // At least include revision ID so page changes are reflected in the hash
542 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
543 }
544
545 // Can not inject the RevisionStore as it would break the installer since
546 // it instantiates MessageCache before the DB.
547 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
548 // Set the text for small software-defined messages in the main cache map
549 $revQuery = $revisionStore->getQueryInfo( [ 'page' ] );
550
551 // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
552 // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
553 // query (and also reorder it ourselves because as generated by RevisionStore it'll have
554 // `revision` first rather than `page`).
555 $revQuery['joins']['revision'] = $revQuery['joins']['page'];
556 unset( $revQuery['joins']['page'] );
557 // It isn't actually necesssary to reorder $revQuery['tables'] as Database does the right thing
558 // when join conditions are given for all joins, but Gergő is wary of relying on that so pull
559 // `page` to the start.
560 $revQuery['tables'] = array_merge(
561 [ 'page' ],
562 array_diff( $revQuery['tables'], [ 'page' ] )
563 );
564
565 $res = $dbr->select(
566 $revQuery['tables'],
567 $revQuery['fields'],
568 array_merge( $conds, [
569 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ),
570 'page_latest = rev_id' // get the latest revision only
571 ] ),
572 __METHOD__ . "($code)-small",
573 [ 'STRAIGHT_JOIN' ],
574 $revQuery['joins']
575 );
576 $result = $revisionStore->newRevisionsFromBatch( $res, [
577 'slots' => [ SlotRecord::MAIN ],
578 'content' => true
579 ] );
580 $revisions = $result->isOK() ? $result->getValue() : [];
581 foreach ( $res as $row ) {
582 // Include entries/stubs for all keys in $mostused in adaptive mode
583 if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $row->page_title )
584 ) {
585 try {
586 $rev = $revisions[$row->rev_id] ?? null;
587 $content = $rev ? $rev->getContent( SlotRecord::MAIN ) : null;
588 $text = $this->getMessageTextFromContent( $content );
589 } catch ( Exception $ex ) {
590 $text = false;
591 }
592
593 if ( !is_string( $text ) ) {
594 $entry = '!ERROR';
595 $this->logger->error(
596 __METHOD__
597 . ": failed to load message page text for {$row->page_title} ($code)"
598 );
599 } else {
600 $entry = ' ' . $text;
601 }
602 $cache[$row->page_title] = $entry;
603 } else {
604 // T193271: cache object gets too big and slow to generate.
605 // At least include revision ID so page changes are reflected in the hash.
606 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
607 }
608 }
609
610 $cache['VERSION'] = MSG_CACHE_VERSION;
611 ksort( $cache );
612
613 # Hash for validating local cache (APC). No need to take into account
614 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
615 # stored and fetched from memcache.
616 $cache['HASH'] = md5( serialize( $cache ) );
617 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + self::WAN_TTL );
618 unset( $cache['EXCESSIVE'] ); // only needed for hash
619
620 return $cache;
621 }
622
629 private function isLanguageLoaded( $lang ) {
630 // It is important that this only returns true if the cache was fully
631 // populated by load(), so that callers can assume all cache keys exist.
632 // It is possible for $this->cache to be only patially populated through
633 // methods like MessageCache::replace(), which must not make this method
634 // return true (T208897). And this method must cease to return true
635 // if the language was evicted by MapCacheLRU (T230690).
636 return $this->cache->hasField( $lang, 'VERSION' );
637 }
638
650 private function isMainCacheable( $name, $code = null ) {
651 // Convert first letter to lowercase, and strip /code suffix
652 $name = $this->contLang->lcfirst( $name );
653 // Include common conversion table pages. This also avoids problems with
654 // Installer::parse() bailing out due to disallowed DB queries (T207979).
655 if ( strpos( $name, 'conversiontable/' ) === 0 ) {
656 return true;
657 }
658 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
659
660 if ( $code === null ) {
661 // Bulk load
662 if ( $this->systemMessageNames === null ) {
663 $this->systemMessageNames = array_fill_keys(
664 $this->localisationCache->getSubitemList( $this->contLangCode, 'messages' ),
665 true );
666 }
667 return isset( $this->systemMessageNames[$msg] );
668 } else {
669 // Use individual subitem
670 return $this->localisationCache->getSubitem( $code, 'messages', $msg ) !== null;
671 }
672 }
673
680 public function replace( $title, $text ) {
681 if ( $this->mDisable ) {
682 return;
683 }
684
685 list( $msg, $code ) = $this->figureMessage( $title );
686 if ( strpos( $title, '/' ) !== false && $code === $this->contLangCode ) {
687 // Content language overrides do not use the /<code> suffix
688 return;
689 }
690
691 // (a) Update the process cache with the new message text
692 if ( $text === false ) {
693 // Page deleted
694 $this->cache->setField( $code, $title, '!NONEXISTENT' );
695 } else {
696 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
697 $this->cache->setField( $code, $title, ' ' . $text );
698 }
699
700 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
701 DeferredUpdates::addUpdate(
702 new MessageCacheUpdate( $code, $title, $msg ),
703 DeferredUpdates::PRESEND
704 );
705 }
706
712 public function refreshAndReplaceInternal( $code, array $replacements ) {
714
715 // Allow one caller at a time to avoid race conditions
716 $scopedLock = $this->getReentrantScopedLock(
717 $this->clusterCache->makeKey( 'messages', $code )
718 );
719 if ( !$scopedLock ) {
720 foreach ( $replacements as list( $title ) ) {
721 $this->logger->error(
722 __METHOD__ . ': could not acquire lock to update {title} ({code})',
723 [ 'title' => $title, 'code' => $code ] );
724 }
725
726 return;
727 }
728
729 // Load the existing cache to update it in the local DC cache.
730 // The other DCs will see a hash mismatch.
731 if ( $this->load( $code, self::FOR_UPDATE ) ) {
732 $cache = $this->cache->get( $code );
733 } else {
734 // Err? Fall back to loading from the database.
735 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
736 }
737 // Check if individual cache keys should exist and update cache accordingly
738 $newTextByTitle = []; // map of (title => content)
739 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
740 foreach ( $replacements as list( $title ) ) {
741 $page = WikiPage::factory( Title::makeTitle( NS_MEDIAWIKI, $title ) );
742 $page->loadPageData( $page::READ_LATEST );
743 $text = $this->getMessageTextFromContent( $page->getContent() );
744 // Remember the text for the blob store update later on
745 $newTextByTitle[$title] = $text;
746 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
747 if ( !is_string( $text ) ) {
748 $cache[$title] = '!NONEXISTENT';
749 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
750 $cache[$title] = '!TOO BIG';
751 $newBigTitles[$title] = $page->getLatest();
752 } else {
753 $cache[$title] = ' ' . $text;
754 }
755 }
756 // Update HASH for the new key. Incorporates various administrative keys,
757 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
758 // and previous replace() calls), but that doesn't really matter since we
759 // only ever compare it for equality with a copy saved by saveToCaches().
760 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
761 // Update the too-big WAN cache entries now that we have the new HASH
762 foreach ( $newBigTitles as $title => $id ) {
763 // Match logic of loadCachedMessagePageEntry()
764 $this->wanCache->set(
765 $this->bigMessageCacheKey( $cache['HASH'], $title ),
766 ' ' . $newTextByTitle[$title],
767 self::WAN_TTL
768 );
769 }
770 // Mark this cache as definitely being "latest" (non-volatile) so
771 // load() calls do not try to refresh the cache with replica DB data
772 $cache['LATEST'] = time();
773 // Update the process cache
774 $this->cache->set( $code, $cache );
775 // Pre-emptively update the local datacenter cache so things like edit filter and
776 // prevented changes are reflected immediately; these often use MediaWiki: pages.
777 // The datacenter handling replace() calls should be the same one handling edits
778 // as they require HTTP POST.
779 $this->saveToCaches( $cache, 'all', $code );
780 // Release the lock now that the cache is saved
781 ScopedCallback::consume( $scopedLock );
782
783 // Relay the purge. Touching this check key expires cache contents
784 // and local cache (APC) validation hash across all datacenters.
785 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
786
787 // Purge the messages in the message blob store and fire any hook handlers
788 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
789 foreach ( $replacements as list( $title, $msg ) ) {
790 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
791 $this->hookRunner->onMessageCacheReplace( $title, $newTextByTitle[$title] );
792 }
793 }
794
801 protected function isCacheExpired( $cache ) {
802 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
803 return true;
804 }
805 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
806 return true;
807 }
808 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
809 return true;
810 }
811
812 return false;
813 }
814
824 protected function saveToCaches( array $cache, $dest, $code = false ) {
825 if ( $dest === 'all' ) {
826 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
827 $success = $this->clusterCache->set( $cacheKey, $cache );
828 $this->setValidationHash( $code, $cache );
829 } else {
830 $success = true;
831 }
832
833 $this->saveToLocalCache( $code, $cache );
834
835 return $success;
836 }
837
844 protected function getValidationHash( $code ) {
845 $curTTL = null;
846 $value = $this->wanCache->get(
847 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
848 $curTTL,
849 [ $this->getCheckKey( $code ) ]
850 );
851
852 if ( $value ) {
853 $hash = $value['hash'];
854 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
855 // Cache was recently updated via replace() and should be up-to-date.
856 // That method is only called in the primary datacenter and uses FOR_UPDATE.
857 // Also, it is unlikely that the current datacenter is *now* secondary one.
858 $expired = false;
859 } else {
860 // See if the "check" key was bumped after the hash was generated
861 $expired = ( $curTTL < 0 );
862 }
863 } else {
864 // No hash found at all; cache must regenerate to be safe
865 $hash = false;
866 $expired = true;
867 }
868
869 return [ $hash, $expired ];
870 }
871
882 protected function setValidationHash( $code, array $cache ) {
883 $this->wanCache->set(
884 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
885 [
886 'hash' => $cache['HASH'],
887 'latest' => $cache['LATEST'] ?? 0
888 ],
889 WANObjectCache::TTL_INDEFINITE
890 );
891 }
892
898 protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
899 return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
900 }
901
935 public function get( $key, $useDB = true, $langcode = true ) {
936 if ( is_int( $key ) ) {
937 // Fix numerical strings that somehow become ints
938 // on their way here
939 $key = (string)$key;
940 } elseif ( !is_string( $key ) ) {
941 throw new MWException( 'Non-string key given' );
942 } elseif ( $key === '' ) {
943 // Shortcut: the empty key is always missing
944 return false;
945 }
946
947 // Normalise title-case input (with some inlining)
948 $lckey = self::normalizeKey( $key );
949
950 $this->hookRunner->onMessageCache__get( $lckey );
951
952 // Loop through each language in the fallback list until we find something useful
953 $message = $this->getMessageFromFallbackChain(
954 wfGetLangObj( $langcode ),
955 $lckey,
956 !$this->mDisable && $useDB
957 );
958
959 // If we still have no message, maybe the key was in fact a full key so try that
960 if ( $message === false ) {
961 $parts = explode( '/', $lckey );
962 // We may get calls for things that are http-urls from sidebar
963 // Let's not load nonexistent languages for those
964 // They usually have more than one slash.
965 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
966 $message = $this->localisationCache->getSubitem( $parts[1], 'messages', $parts[0] );
967 if ( $message === null ) {
968 $message = false;
969 }
970 }
971 }
972
973 // Post-processing if the message exists
974 if ( $message !== false ) {
975 // Fix whitespace
976 $message = str_replace(
977 [
978 # Fix for trailing whitespace, removed by textarea
979 '&#32;',
980 # Fix for NBSP, converted to space by firefox
981 '&nbsp;',
982 '&#160;',
983 '&shy;'
984 ],
985 [
986 ' ',
987 "\u{00A0}",
988 "\u{00A0}",
989 "\u{00AD}"
990 ],
991 $message
992 );
993 }
994
995 return $message;
996 }
997
1010 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
1011 $alreadyTried = [];
1012
1013 // First try the requested language.
1014 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
1015 if ( $message !== false ) {
1016 return $message;
1017 }
1018
1019 // Now try checking the site language.
1020 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
1021 return $message;
1022 }
1023
1034 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
1035 $langcode = $lang->getCode();
1036
1037 // Try checking the database for the requested language
1038 if ( $useDB ) {
1039 $uckey = $this->contLang->ucfirst( $lckey );
1040
1041 if ( !isset( $alreadyTried[$langcode] ) ) {
1042 $message = $this->getMsgFromNamespace(
1043 $this->getMessagePageName( $langcode, $uckey ),
1044 $langcode
1045 );
1046 if ( $message !== false ) {
1047 return $message;
1048 }
1049 $alreadyTried[$langcode] = true;
1050 }
1051 } else {
1052 $uckey = null;
1053 }
1054
1055 // Check the CDB cache
1056 $message = $lang->getMessage( $lckey );
1057 if ( $message !== null ) {
1058 return $message;
1059 }
1060
1061 // Try checking the database for all of the fallback languages
1062 if ( $useDB ) {
1063 $fallbackChain = $this->languageFallback->getAll( $langcode );
1064
1065 foreach ( $fallbackChain as $code ) {
1066 if ( isset( $alreadyTried[$code] ) ) {
1067 continue;
1068 }
1069
1070 $message = $this->getMsgFromNamespace(
1071 $this->getMessagePageName( $code, $uckey ), $code );
1072
1073 if ( $message !== false ) {
1074 return $message;
1075 }
1076 $alreadyTried[$code] = true;
1077 }
1078 }
1079
1080 return false;
1081 }
1082
1090 private function getMessagePageName( $langcode, $uckey ) {
1091 if ( $langcode === $this->contLangCode ) {
1092 // Messages created in the content language will not have the /lang extension
1093 return $uckey;
1094 } else {
1095 return "$uckey/$langcode";
1096 }
1097 }
1098
1111 public function getMsgFromNamespace( $title, $code ) {
1112 // Load all MediaWiki page definitions into cache. Note that individual keys
1113 // already loaded into cache during this request remain in the cache, which
1114 // includes the value of hook-defined messages.
1115 $this->load( $code );
1116
1117 $entry = $this->cache->getField( $code, $title );
1118
1119 if ( $entry !== null ) {
1120 // Message page exists as an override of a software messages
1121 if ( substr( $entry, 0, 1 ) === ' ' ) {
1122 // The message exists and is not '!TOO BIG' or '!ERROR'
1123 return (string)substr( $entry, 1 );
1124 } elseif ( $entry === '!NONEXISTENT' ) {
1125 // The text might be '-' or missing due to some data loss
1126 return false;
1127 }
1128 // Load the message page, utilizing the individual message cache.
1129 // If the page does not exist, there will be no hook handler fallbacks.
1130 $entry = $this->loadCachedMessagePageEntry(
1131 $title,
1132 $code,
1133 $this->cache->getField( $code, 'HASH' )
1134 );
1135 } else {
1136 // Message page either does not exist or does not override a software message
1137 if ( !$this->isMainCacheable( $title, $code ) ) {
1138 // Message page does not override any software-defined message. A custom
1139 // message might be defined to have content or settings specific to the wiki.
1140 // Load the message page, utilizing the individual message cache as needed.
1141 $entry = $this->loadCachedMessagePageEntry(
1142 $title,
1143 $code,
1144 $this->cache->getField( $code, 'HASH' )
1145 );
1146 }
1147 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1148 // Message does not have a MediaWiki page definition; try hook handlers
1149 $message = false;
1150 $this->hookRunner->onMessagesPreLoad( $title, $message, $code );
1151 if ( $message !== false ) {
1152 $this->cache->setField( $code, $title, ' ' . $message );
1153 } else {
1154 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1155 }
1156
1157 return $message;
1158 }
1159 }
1160
1161 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1162 if ( $this->cacheVolatile[$code] ) {
1163 // Make sure that individual keys respect the WAN cache holdoff period too
1164 $this->logger->debug(
1165 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1166 [ 'titleKey' => $title, 'code' => $code ] );
1167 } else {
1168 $this->cache->setField( $code, $title, $entry );
1169 }
1170 // The message exists, so make sure a string is returned
1171 return (string)substr( $entry, 1 );
1172 }
1173
1174 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1175
1176 return false;
1177 }
1178
1185 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1186 $fname = __METHOD__;
1187 return $this->srvCache->getWithSetCallback(
1188 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1189 BagOStuff::TTL_HOUR,
1190 function () use ( $code, $dbKey, $hash, $fname ) {
1191 return $this->wanCache->getWithSetCallback(
1192 $this->bigMessageCacheKey( $hash, $dbKey ),
1193 self::WAN_TTL,
1194 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1195 // Try loading the message from the database
1196 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
1197 // Use newKnownCurrent() to avoid querying revision/user tables
1198 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1199 // Injecting RevisionStore breaks installer since it
1200 // instantiates MessageCache before DB.
1201 $revision = MediaWikiServices::getInstance()
1202 ->getRevisionLookup()
1203 ->getKnownCurrentRevision( $title );
1204 if ( !$revision ) {
1205 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1206 // When overrides are created, self::replace() takes care of the cache.
1207 return '!NONEXISTENT';
1208 }
1209 $content = $revision->getContent( SlotRecord::MAIN );
1210 if ( $content ) {
1211 $message = $this->getMessageTextFromContent( $content );
1212 } else {
1213 $this->logger->warning(
1214 $fname . ': failed to load page text for \'{titleKey}\'',
1215 [ 'titleKey' => $dbKey, 'code' => $code ]
1216 );
1217 $message = null;
1218 }
1219
1220 if ( !is_string( $message ) ) {
1221 // Revision failed to load Content, or Content is incompatible with wikitext.
1222 // Possibly a temporary loading failure.
1223 $ttl = 5;
1224
1225 return '!NONEXISTENT';
1226 }
1227
1228 return ' ' . $message;
1229 }
1230 );
1231 }
1232 );
1233 }
1234
1242 public function transform( $message, $interface = false, $language = null, PageReference $page = null ) {
1243 // Avoid creating parser if nothing to transform
1244 if ( strpos( $message, '{{' ) === false ) {
1245 return $message;
1246 }
1247
1248 if ( $this->mInParser ) {
1249 return $message;
1250 }
1251
1252 $parser = $this->getParser();
1253 if ( $parser ) {
1254 $popts = $this->getParserOptions();
1255 $popts->setInterfaceMessage( $interface );
1256 $popts->setTargetLanguage( $language );
1257
1258 $userlang = $popts->setUserLang( $language );
1259 $this->mInParser = true;
1260 $message = $parser->transformMsg( $message, $popts, $page );
1261 $this->mInParser = false;
1262 $popts->setUserLang( $userlang );
1263 }
1264
1265 return $message;
1266 }
1267
1271 public function getParser() {
1272 if ( !$this->mParser ) {
1273 $parser = MediaWikiServices::getInstance()->getParser();
1274 # Clone it and store it
1275 $this->mParser = clone $parser;
1276 }
1277
1278 return $this->mParser;
1279 }
1280
1289 public function parse( $text, PageReference $page = null, $linestart = true,
1290 $interface = false, $language = null
1291 ) {
1292 global $wgTitle;
1293
1294 if ( $this->mInParser ) {
1295 return htmlspecialchars( $text );
1296 }
1297
1298 $parser = $this->getParser();
1299 $popts = $this->getParserOptions();
1300 $popts->setInterfaceMessage( $interface );
1301
1302 if ( is_string( $language ) ) {
1303 $language = $this->langFactory->getLanguage( $language );
1304 }
1305 $popts->setTargetLanguage( $language );
1306
1307 if ( !$page ) {
1308 $logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
1309 $logger->info(
1310 __METHOD__ . ' called with no title set.',
1311 [ 'exception' => new Exception ]
1312 );
1313 $page = $wgTitle;
1314 }
1315 // Sometimes $wgTitle isn't set either...
1316 if ( !$page ) {
1317 # It's not uncommon having a null $wgTitle in scripts. See r80898
1318 # Create a ghost title in such case
1319 $page = PageReferenceValue::localReference(
1320 NS_SPECIAL,
1321 'Badtitle/title not set in ' . __METHOD__
1322 );
1323 }
1324
1325 $this->mInParser = true;
1326 $res = $parser->parse( $text, $page, $popts, $linestart );
1327 $this->mInParser = false;
1328
1329 return $res;
1330 }
1331
1332 public function disable() {
1333 $this->mDisable = true;
1334 }
1335
1336 public function enable() {
1337 $this->mDisable = false;
1338 }
1339
1352 public function isDisabled() {
1353 return $this->mDisable;
1354 }
1355
1361 public function clear() {
1362 $langs = $this->languageNameUtils->getLanguageNames( null, 'mw' );
1363 foreach ( array_keys( $langs ) as $code ) {
1364 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1365 }
1366 $this->cache->clear();
1367 }
1368
1373 public function figureMessage( $key ) {
1374 $pieces = explode( '/', $key );
1375 if ( count( $pieces ) < 2 ) {
1376 return [ $key, $this->contLangCode ];
1377 }
1378
1379 $lang = array_pop( $pieces );
1380 if ( !$this->languageNameUtils->getLanguageName( $lang, null, 'mw' ) ) {
1381 return [ $key, $this->contLangCode ];
1382 }
1383
1384 $message = implode( '/', $pieces );
1385
1386 return [ $message, $lang ];
1387 }
1388
1397 public function getAllMessageKeys( $code ) {
1398 $this->load( $code );
1399 if ( !$this->cache->has( $code ) ) {
1400 // Apparently load() failed
1401 return null;
1402 }
1403 // Remove administrative keys
1404 $cache = $this->cache->get( $code );
1405 unset( $cache['VERSION'] );
1406 unset( $cache['EXPIRY'] );
1407 unset( $cache['EXCESSIVE'] );
1408 // Remove any !NONEXISTENT keys
1409 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1410
1411 // Keys may appear with a capital first letter. lcfirst them.
1412 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1413 }
1414
1422 public function updateMessageOverride( LinkTarget $linkTarget, Content $content = null ) {
1423 $msgText = $this->getMessageTextFromContent( $content );
1424 if ( $msgText === null ) {
1425 $msgText = false; // treat as not existing
1426 }
1427
1428 $this->replace( $linkTarget->getDBkey(), $msgText );
1429
1430 if ( $this->contLangConverter->hasVariants() ) {
1431 $this->contLangConverter->updateConversionTable( $linkTarget );
1432 }
1433 }
1434
1439 public function getCheckKey( $code ) {
1440 return $this->wanCache->makeKey( 'messages', $code );
1441 }
1442
1447 private function getMessageTextFromContent( Content $content = null ) {
1448 // @TODO: could skip pseudo-messages like js/css here, based on content model
1449 if ( $content ) {
1450 // Message page exists...
1451 // XXX: Is this the right way to turn a Content object into a message?
1452 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1453 // CssContent. MessageContent is *not* used for storing messages, it's
1454 // only used for wrapping them when needed.
1455 $msgText = $content->getWikitextForTransclusion();
1456 if ( $msgText === false || $msgText === null ) {
1457 // This might be due to some kind of misconfiguration...
1458 $msgText = null;
1459 $this->logger->warning(
1460 __METHOD__ . ": message content doesn't provide wikitext "
1461 . "(content model: " . $content->getModel() . ")" );
1462 }
1463 } else {
1464 // Message page does not exist...
1465 $msgText = false;
1466 }
1467
1468 return $msgText;
1469 }
1470
1476 private function bigMessageCacheKey( $hash, $title ) {
1477 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1478 }
1479}
serialize()
$wgAdaptiveMessageCache
Instead of caching everything, only cache those messages which have been customised in the site conte...
$wgMaxMsgCacheEntrySize
Maximum entry size in the message cache, in bytes.
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.
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.
$wgTitle
Definition Setup.php:849
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:86
A BagOStuff object with no objects in it.
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition Language.php:42
getCode()
Get the internal language code for this language object.
Class for caching the contents of localisation files, Messages*.php and *.i18n.php.
MediaWiki exception.
Handles a simple LRU key/value map with a maximum number of entries.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
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.
MediaWikiServices is the service locator for the application scope of MediaWiki.
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 of messages that are defined by MediaWiki namespace pages or by hooks.
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
isLanguageLoaded( $lang)
Whether the language was loaded and its data is still in the process cache.
loadFromDBWithLock( $code, array &$where, $mode=null)
const LOCK_TTL
How long memcached locks last.
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
saveToLocalCache( $code, $cache)
Save the cache to APC.
LanguageFactory $langFactory
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
Language $contLang
getCheckKey( $code)
saveToCaches(array $cache, $dest, $code=false)
Shortcut to update caches.
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, Language $contLang, ILanguageConverter $contLangConverter, LoggerInterface $logger, array $options, LanguageFactory $langFactory, LocalisationCache $localisationCache, LanguageNameUtils $languageNameUtils, LanguageFallback $languageFallback, HookContainer $hookContainer)
refreshAndReplaceInternal( $code, array $replacements)
setValidationHash( $code, array $cache)
Set the md5 used to validate the local disk cache.
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
const WAIT_SEC
How long to wait for memcached locks.
bool $mDisable
Should mean that database cannot be used, but check.
getLocalCache( $code)
Try to load the cache from APC.
parse( $text, PageReference $page=null, $linestart=true, $interface=false, $language=null)
transform( $message, $interface=false, $language=null, PageReference $page=null)
LocalisationCache $localisationCache
LanguageNameUtils $languageNameUtils
isMainCacheable( $name, $code=null)
Can the given DB key be added to the main cache blob? To reduce the impact of abuse of the MediaWiki ...
string $contLangCode
LanguageFallback $languageFallback
load( $code, $mode=null)
Loads messages from caches or from database in this order: (1) local message cache (if $wgUseLocalMes...
updateMessageOverride(LinkTarget $linkTarget, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
BagOStuff $srvCache
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
isDisabled()
Whether DB/cache usage is disabled for determining messages.
setLogger(LoggerInterface $logger)
BagOStuff $clusterCache
loadCachedMessagePageEntry( $dbKey, $code, $hash)
getMessageTextFromContent(Content $content=null)
clear()
Clear all stored messages in global and local cache.
static singleton()
Get the singleton instance of this class.
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
MapCacheLRU $cache
Process cache of loaded messages that are defined in MediaWiki namespace.
LoggerInterface $logger
WANObjectCache $wanCache
static normalizeKey( $key)
Normalize message key input.
bool[] $cacheVolatile
Map of (language code => boolean)
array $systemMessageNames
Map of (lowercase message key => unused) for all software defined messages.
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
ILanguageConverter $contLangConverter
replace( $title, $text)
Updates cache as necessary when message page is changed.
getParserOptions()
ParserOptions is lazy initialised.
HookRunner $hookRunner
bigMessageCacheKey( $hash, $title)
Set options of the Parser.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:91
Multi-datacenter aware caching interface.
Relational database abstraction object.
Definition Database.php:52
Base interface for content objects.
Definition Content.php:35
The shared interface for all language converters.
getDBkey()
Get the main part with underscores.
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
$cache
Definition mcc.php:33
const DB_REPLICA
Definition defines.php:25
const DB_PRIMARY
Definition defines.php:27
$content
Definition router.php:76
return true
Definition router.php:92
if(!isset( $args[0])) $lang